diff --git a/src/tests/v1/acp-agent.test.ts b/src/tests/v1/acp-agent.test.ts index 724b871a..d0cb4856 100644 --- a/src/tests/v1/acp-agent.test.ts +++ b/src/tests/v1/acp-agent.test.ts @@ -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(); 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")); diff --git a/src/tests/v1/create-session-options.test.ts b/src/tests/v1/create-session-options.test.ts index 0b9a53f5..1e603a92 100644 --- a/src/tests/v1/create-session-options.test.ts +++ b/src/tests/v1/create-session-options.test.ts @@ -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((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; diff --git a/src/tests/v2/acp-v2.test.ts b/src/tests/v2/acp-v2.test.ts index fde900da..a61f3d74 100644 --- a/src/tests/v2/acp-v2.test.ts +++ b/src/tests/v2/acp-v2.test.ts @@ -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(); sdk.interrupt = async () => interrupted.resolve(); diff --git a/src/v1/acp-agent.ts b/src/v1/acp-agent.ts index 361e03b1..b6aaa28e 100644 --- a/src/v1/acp-agent.ts +++ b/src/v1/acp-agent.ts @@ -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);