Files
Ignacy Łątka a92c859d07 feat(argent-lens): argent lens — bind a claude session to the preview window (#416)
## What

Adds `argent lens` — open Argent Lens bound to a fresh `claude` session.

## Why

The Lens preview window and the agent communicate through a shared,
process-wide tool-server that carries **no per-agent identity** (only a
coarse telemetry header). So when the user requests changes in the
window, there's no reliable way to route them to the *specific* agent
that opened it.

`argent lens` sidesteps the problem by inverting ownership: the human
launches Lens, and Lens spawns (and therefore owns) exactly one `claude`
terminal. The binding is 1:1 by construction — no identity plumbing
required.

## How it works

1. `argent lens` ensures a tool-server and **begins a CLI Lens
session**, which opens the preview window up front (no
`await_user_selection` needed) and keeps it open across rounds.
2. It spawns a tracked `claude` terminal in the current directory — a
TypeScript port of the macOS applet's `osascript` spawn/track mechanism
— seeded to propose variants without blocking.
3. A watcher polls `GET /preview/outcome`; on each submitted round it
types a one-line feedback summary into that terminal, queuing it to the
agent as its next prompt. Requesting changes therefore "talks back" to
the bound agent instead of closing the window.

macOS only (drives Terminal/iTerm via `osascript`); off-darwin it exits
with a clear message.

## Changes

- **CLI** `lens-terminal.ts` — `osascript` spawn/track + a new
write-into-running-session path (the "outputting" channel; injects input
into the running TUI, which a tty write cannot do).
- **CLI** `lens.ts` — the command + feedback formatter.
- **tool-server** — a `cliSession` flag in the variant store (opens the
window, suppresses auto-close on submit); `POST /preview/cli-session`
and `GET /preview/outcome` routes.
- **UI** — relabels the submit action to "Request changes" while a CLI
session is active.

Behind the existing `argent-lens` feature flag.

## Verification

- Build + typecheck across the workspace; ESLint (`--max-warnings 0`) +
Prettier clean.
- 34 new unit tests; full `@argent/cli` suite **118 passing**,
tool-server variant/preview suites **46 passing**.
- **E2E (observed on this machine):**
- **tool-server HTTP** — `cli-session` toggles `cliSession` true/false;
submitted feedback round-trips through `/preview/outcome`.
- **terminal injection** — spawned a window running `cat`, confirmed
`writeToSession` lands text in the running program's **stdin** (both
iTerm and Terminal), with embedded newlines flattened.
- **full relay** — the real `watchAndRelay` loop against a real
tool-server typed two distinct submission rounds' feedback into a
stand-in agent terminal (dedup on `completedAt` verified).
- `argent lens --help` and the feature-flag gate (exit 1 with guidance,
no spawn).

Note: a real end-to-end with a live `claude` agent was not run (it would
drive a paid interactive session); the agent-facing channel is proven by
injecting into a stand-in process's stdin via the exact same code path.

---------

Co-authored-by: Filip131311 <contact@filipkaminski.com>
2026-07-01 19:57:56 +02:00

108 lines
3.1 KiB
TypeScript

import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
// Drive runRelaySession by feeding a scripted SSE event list through a mocked
// lensEvents generator, and stub the one-shot /outcome baseline fetch. The
// inject/registerDeath seams are supplied by the caller, so we can assert
// exactly what gets relayed to the agent terminal.
const scripted: { events: Array<{ event: string; data: string }> } = { events: [] };
vi.mock("../src/lens-stream.js", () => ({
lensEvents: async function* () {
for (const ev of scripted.events) yield ev;
},
}));
import { runRelaySession } from "../src/lens.js";
function stubBaselineOutcome(outcome: unknown): void {
vi.stubGlobal(
"fetch",
vi.fn(async () => ({ ok: true, json: async () => ({ outcome }) }))
);
}
function outcomeEvent(completedAt: number): { event: string; data: string } {
return {
event: "outcome",
data: JSON.stringify({
status: "completed",
round: completedAt,
selections: [],
unselected: [],
annotations: [],
completedAt,
}),
};
}
const SESSION_END = { event: "session-end", data: "{}" };
beforeEach(() => {
scripted.events = [];
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe("runRelaySession", () => {
it("relays each new outcome once, dedups by completedAt, and stops on session-end", async () => {
stubBaselineOutcome(null); // no prior round at startup → baseline completedAt = 0
scripted.events = [
outcomeEvent(100),
outcomeEvent(100), // same completedAt → must NOT relay again
outcomeEvent(200), // newer → relays
SESSION_END,
];
const injected: string[] = [];
await runRelaySession(
"http://x",
(t) => (injected.push(t), true),
() => {},
true
);
expect(injected).toHaveLength(2);
expect(injected[0]).toContain("round 100");
expect(injected[1]).toContain("round 200");
});
it("never relays an outcome at or before the startup baseline (no stale replay on launch)", async () => {
stubBaselineOutcome({ status: "completed", completedAt: 500 }); // a round already submitted before we started
scripted.events = [
outcomeEvent(500), // equal to baseline → skip (this is the replay-on-connect frame)
outcomeEvent(400), // older → skip
SESSION_END,
];
const injected: string[] = [];
await runRelaySession(
"http://x",
(t) => (injected.push(t), true),
() => {},
true
);
expect(injected).toEqual([]);
});
it("stops relaying once the agent has exited (registerDeath)", async () => {
stubBaselineOutcome(null);
// Death fires during the startup baseline fetch (registerDeath is invoked
// synchronously before the first await), so the scripted outcome is never
// relayed and the loop exits without reconnecting.
scripted.events = [outcomeEvent(100), SESSION_END];
const injected: string[] = [];
let die = () => {};
const p = runRelaySession(
"http://x",
(t) => (injected.push(t), true),
(onDeath) => {
die = onDeath;
},
true
);
die();
await p;
expect(injected).toEqual([]);
});
});