fix: read the Claude Code stream after every session setup, not at the first prompt (#1623)

On v1, `ensureConsumer` started only from `prompt()`, Remote Control and
the clear-context coordinator. `session/load`, `session/resume` and
`session/fork` did not start it. A resumed session can run cycles before
the first prompt: a cron prompt that came due while the bridge was down,
or the follow-up of a background task that finished. That output waited
in the stream. When the first prompt arrived, the consumer read the
backlog first, with the prompt's turn queued at the head and not yet
echoed. The first result in the backlog was a cron cycle's, which has no
`origin`, so it took the user lane and `ensureActiveTurn` gave it to the
queued head. The prompt resolved with another cycle's usage and stop
reason, and its own cycle then ran with no turn to claim it.

This change starts the consumer in `afterSetupResponse`, the existing
step that already runs after a setup response and sends the commands and
starts MCP authentication. It runs after a load's replay, so live output
cannot interleave with the replayed history. `ensureConsumer` is
idempotent, so a prompt that arrives later finds the consumer running,
and one that arrives first starts it as before.

## Design

- No new component: `ensureConsumer` already owns starting the reader,
and `afterSetupResponse` already owns "what follows a setup response".
The change is one call and the comments that said otherwise.
- Every setup starts the reader, new sessions included, not only resumed
ones. This is the rule v2 already has (`Session.start()` calls
`consume()` when the session opens), it needs no flag that tells a
resumed setup from a new one, and a new session has no history from
which Claude Code could start a cycle, so for it the early read only
means nothing waits unread.
- It does not start in `createSession`: a load replays history after
`createSession`, and live output from the reader would interleave with
it. `afterSetupResponse` runs after the replay.
- One behavior change: a stream that ends before the first prompt now
closes the session at that moment (the consumer's existing stream-end
handling and `queryClosed`) and not at the first prompt.
- The query mocks in `create-session-options.test.ts` returned an empty
stream, which Claude Code does not. With a reader running from setup,
the empty stream closed the session at once, so the mock now keeps the
stream open until `close()`, like Claude Code's.

## v2

Not affected. `Session.start()` calls `consume(query)` when the session
opens, for new, resumed and forked sessions alike, so output before the
first prompt is reported as it comes. A test in
`src/tests/v2/acp-v2.test.ts` resumes a session that runs a cron cycle
before the first prompt and checks that the cycle is reported apart from
the prompt's turn, with its own usage. It passes with and without this
change.

## Tests

`it.each(["resumeSession", "loadSession"])` in the `session/fork`
describe of `src/tests/v1/acp-agent.test.ts`: that describe holds
`forkingAgent`, the only helper that drives the real setup methods with
a scripted query. It gained a `backlog` parameter for what Claude Code
sends before the first prompt. The test sends a cron cycle (no origin)
and a task-notification cycle as the backlog, waits until the consumer
has read them, then prompts, and checks that the prompt's response
carries its own usage (7 input tokens, not the cron cycle's 111).
Without the fix the consumer never starts before the prompt, so the wait
times out, and with the wait replaced by a fixed delay the response
carries the cron cycle's usage.

This is independent of #1620: each fix passes its own tests alone. #1620
is the case where an unclaimed result leaves the turn task open; this
change removes the way a loaded session got there at its first prompt.

Fixes #1621.

## Validation

Rebased on `main` at 7e857d5.

- `npm run check` and `npm run build` pass.
- `npm run test:run`: 4,135 passed, 36 skipped, 1 failed. The failure is
`tools.test.ts` "picks up a rewrite that restored the modification time
of the file", which also fails on `main` at 7e857d5 without this change.
- The new v1 test fails on `main`, and passes with the fix.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jonathan Ellis
2026-11-16 05:16:46 -06:00
committed by GitHub
parent c203b919ec
commit 7d9e1f6135
4 changed files with 142 additions and 7 deletions

View File

@@ -15020,8 +15020,9 @@ describe("session/fork", () => {
const modes = { currentModeId: "plan", availableModes: [] };
/** An agent whose sessions start without Claude Code: each one gets a
* scripted query that runs `turn` for every prompt. */
function forkingAgent(turn: (prompt: any) => any[] = () => []) {
* scripted query that runs `turn` for every prompt, after it sent `backlog`
* with no prompt open. */
function forkingAgent(turn: (prompt: any) => any[] = () => [], backlog: any[] = []) {
const updates: SessionNotification[] = [];
const agent = new ClaudeAcpAgent(
{ sessionUpdate: async (n: SessionNotification) => updates.push(n) } as unknown as AcpClient,
@@ -15035,6 +15036,7 @@ describe("session/fork", () => {
const sessionId = options.resume as string;
const input = new Pushable<any>();
async function* answer() {
yield* backlog;
for await (const prompt of input) yield* turn(prompt);
}
agent.sessions[sessionId] = mockSessionState(
@@ -15115,6 +15117,57 @@ describe("session/fork", () => {
expect(agent.sessions["fork-id"]).toBe(forked);
});
// After a bridge restart, Claude Code runs a cron cycle and a background
// task's follow-up before the first prompt. Nothing read the stream until
// then, and the prompt took the cron cycle's result as its own.
it.each(["resumeSession", "loadSession"] as const)(
"reads what Claude Code sends before the first prompt after %s (#1621)",
async (method) => {
const state = (state: "running" | "idle") => ({
type: "system",
subtype: "session_state_changed",
state,
uuid: randomUUID(),
session_id: "resumed-id",
});
const usage = (input: number, output: number) => ({
input_tokens: input,
output_tokens: output,
cache_read_input_tokens: 0,
cache_creation_input_tokens: 0,
});
const { agent } = forkingAgent(
(prompt) => [
userEcho(prompt),
state("running"),
successfulResultMessage({ usage: usage(7, 3) }),
state("idle"),
],
[
// A cron prompt: its result has no origin.
state("running"),
successfulResultMessage({ usage: usage(111, 11) }),
state("idle"),
state("running"),
successfulResultMessage({ origin: { kind: "task-notification" }, usage: usage(222, 22) }),
state("idle"),
],
);
// Only a load replays the transcript.
if (method === "loadSession") vi.mocked(getSessionMessages).mockResolvedValueOnce([]);
await agent[method]({ sessionId: "resumed-id", cwd: "/workspace", mcpServers: [] });
// The reader starts after the response.
await vi.waitFor(() => expect(agent.sessions["resumed-id"].lastSessionState).toBe("idle"));
const response = await agent.prompt({
sessionId: "resumed-id",
prompt: [{ type: "text", text: "go on" }],
});
expect(response.usage).toMatchObject({ inputTokens: 7, outputTokens: 3 });
},
);
it("fails when the forked session cannot start", async () => {
const { agent, createSession } = forkingAgent();
createSession.mockRejectedValueOnce(new Error("Claude Code did not start"));

View File

@@ -46,9 +46,19 @@ vi.mock("@anthropic-ai/claude-agent-sdk", async () => {
...actual,
query: (args: { prompt: unknown; options: Options }) => {
capturedOptions = args.options;
// Like Claude Code's, the stream stays open until the query is closed.
let streamClosed = () => {};
const closed = new Promise<void>((resolve) => (streamClosed = resolve));
return makeMockQuery({
interrupt: () => (interruptImpl ? interruptImpl() : Promise.resolve(undefined)),
close: () => closeSpy(),
close: () => {
closeSpy();
streamClosed();
},
next: async () => {
await closed;
return { done: true as const, value: undefined };
},
initializationResult: async () => {
await initGate;
if (initError) throw initError;

View File

@@ -4573,6 +4573,69 @@ describe("ACP v2 model cycles that Claude Code starts on its own", () => {
expect(turnTrace(client.sessionUpdates).at(-1)).toBe("idle end_turn");
});
// A resumed session can run cycles before its first prompt, for example a
// cron prompt. v2 reads the query from the start of the session, so that
// output is reported as it comes and does not answer the prompt.
it("reports a cycle that a resumed session runs before the first prompt, apart from the prompt's turn", async () => {
sdk.run = async function* (prompts, options) {
const input = prompts[Symbol.asyncIterator]();
if (!options.resume) {
while (!(await input.next()).done);
return;
}
// A cron prompt: its result has no origin.
yield assistantText(options, "Checked the build.", "msg_cron");
yield result(options, { usage: { ...result(options).usage, input_tokens: 111 } });
yield idleState(options);
const { value } = await input.next();
yield {
type: "user",
message: value!.message,
parent_tool_use_id: null,
uuid: value!.uuid,
session_id: options.sessionId,
isReplay: true,
};
yield assistantText(options, "Here is the answer.");
yield result(options, { usage: { ...result(options).usage, input_tokens: 7 } });
yield idleState(options);
while (!(await input.next()).done);
};
const client = v2Client();
await client.app.connectWith(connectRouter(), async (agent) => {
await initializeV2(agent);
const { sessionId } = await agent.request(v2.methods.agent.session.new, { cwd });
await agent.request(v2.methods.agent.session.close, { sessionId });
await agent.request(v2.methods.agent.session.resume, { sessionId, cwd });
await vi.waitFor(() =>
expect(turnTrace(client.sessionUpdates)).toContain("agent_message_chunk"),
);
await agent.request(v2.methods.agent.session.prompt, { sessionId, prompt: text("hi") });
await vi.waitFor(() =>
expect(
turnTrace(client.sessionUpdates).filter((state) => state.startsWith("idle end")),
).toHaveLength(2),
);
await client.authUpdate(1);
});
// Without the `idle` that the resume reports.
expect(turnTrace(client.sessionUpdates).filter((state) => state !== "idle")).toEqual([
"running",
"agent_message_chunk",
"idle end_turn",
"user_message",
"running",
"agent_message_chunk",
"idle end_turn",
]);
expect(
client
.updates("state_update")
.filter((update: any) => update.stopReason)
.map((update: any) => update.usage.inputTokens),
).toEqual([111, 7]);
});
it("ends the tool call that a cancelled cycle runs with Claude Code's result, before idle cancelled", async () => {
const interrupted = Promise.withResolvers<void>();
sdk.interrupt = async () => interrupted.resolve();

View File

@@ -3071,7 +3071,8 @@ export class ClaudeAcpAgent {
}
/** Lazily start the per-session consumer that drains the SDK query stream for
* the session's whole life. Idempotent: only the first `prompt()` starts it. */
* the session's whole life. Idempotent: the first caller starts it, a
* session setup (see `afterSetupResponse`) or a `prompt()`. */
private ensureConsumer(session: Session, sessionId: string): void {
if (session.consumer) {
return;
@@ -9231,9 +9232,9 @@ export class ClaudeAcpAgent {
}
/**
* The work that follows a session setup response: the session's commands,
* the current states of the subagents a load replayed, and MCP server
* authentication.
* The work that follows a session setup response: reading the session's
* query, the session's commands, the current states of the subagents a load
* replayed, and MCP server authentication.
*
* Call it in the same synchronous step as the handler's `return`: an
* `await` between them would let the timer run before the response. The ACP
@@ -9248,6 +9249,14 @@ export class ClaudeAcpAgent {
*/
private afterSetupResponse(sessionId: string, mcpServers: McpServer[]): void {
setTimeout(() => {
// Claude Code can run cycles of its own before the first prompt, for
// example a cron prompt or a finished background task of a session that a
// bridge restart resumed. Output that nothing reads waits in the stream,
// and the first prompt would take the first result in it as its answer.
// After the load's replay, so live output does not interleave with the
// replayed history.
const session = this.sessions[sessionId];
if (session && !session.queryClosed) this.ensureConsumer(session, sessionId);
this.sendAvailableCommandsUpdate(sessionId);
void this.publishCurrentSubagentStates(sessionId);
startMcpAuthentication(this, sessionId, mcpServers);