mirror of
https://github.com/agentclientprotocol/claude-agent-acp.git
synced 2026-11-17 14:51:13 +00:00
fix: read the Claude Code stream after a query restart, not at the next prompt (#1636)
## Summary Follow-up to #1623, which left this case open. On v1, `replaceSessionQuery` resumes a session on a new query in two cases: a provider change (`providers/set`, `providers/disable`) and a sign-out respawn under `--hide-claude-auth`. The reader of the old query ends with that query, and nothing started one for the new query until the next prompt. Claude Code can run a cycle of its own on the new query before that prompt, for example a cron prompt or the follow-up to a finished background task. Its output waited in the stream. At the next prompt the consumer read the backlog with the prompt's turn queued, and the first result in it, which has no `origin`, went to that turn. The prompt resolved with another cycle's usage and stop reason. #1623 fixed the same for `session/load`, `session/resume` and `session/fork`. `replaceSessionQuery` now starts the reader once the session's choices are restored and published. ## Design - No new mechanism. `ensureConsumer` already owns starting the reader, and `replaceSessionQuery` is the one function both restarts go through, so one call covers the provider restart and the sign-out respawn. - The reader starts after `restoreSessionChoices` and the `config_option_update`, so what it reports is read against the restored state. A setup has the same order: choices first, then the reader. - The `queryClosed` check is at the call site, as in `afterSetupResponse`, and not inside `ensureConsumer`. `prompt()` relies on a consumer that starts on a closed stream to reject its queued turn. - v2 needs no change: it reads every query from `Session.start()`, a restart's included. A test now pins that. Not addressed, as in #1623: a prompt sent while such a cycle is still running can claim that cycle's result. ## Tests - v1 (`provider-session-configuration.test.ts`): the new query of a provider restart sends a cron cycle before the next prompt. The cycle is read without a prompt, and the prompt gets its own usage. Fails without the fix. - v2 (`acp-v2.test.ts`): the same cycle after `providers/set` is reported as it comes. v2 passed this before the change. - `providers.test.ts`: the query mock's stream now stays open until `close()`, like Claude Code's. It ended at once, so the reader that now starts at a restart closed the query, and "switches every loaded session through proxy replacements and back to native routing" saw a `close()` it did not expect. - Two comments said the reader starts only at a prompt (`ensureConsumer`, and the Remote Control command). Both now name the setup and the restart. ## Testing - `npm run build`, `npm run check`, `npm run test:run` (4,183 tests pass) - Not run against the real CLI: no provider restart or sign-out respawn was driven live.
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
@@ -64,6 +65,8 @@ describe("provider updates preserve session configuration", { timeout: 10_000 },
|
||||
let rejectConfigUpdate: boolean;
|
||||
let models: typeof MODELS;
|
||||
let mcpServers: Array<{ name: string; status: string }>;
|
||||
/** What a query that resumes a session sends before it reads a prompt. */
|
||||
let backlog: any[];
|
||||
|
||||
function createQuery(request: { options: Options; prompt: AsyncIterable<any> }) {
|
||||
const state = {
|
||||
@@ -108,6 +111,7 @@ describe("provider updates preserve session configuration", { timeout: 10_000 },
|
||||
}),
|
||||
close: vi.fn(),
|
||||
[Symbol.asyncIterator]: async function* () {
|
||||
if (request.options.resume) yield* backlog;
|
||||
for await (const message of request.prompt) {
|
||||
calls.push({ prompt: message.message.content, state: { ...state } });
|
||||
yield userEcho(message);
|
||||
@@ -137,6 +141,7 @@ describe("provider updates preserve session configuration", { timeout: 10_000 },
|
||||
rejectConfigUpdate = false;
|
||||
models = MODELS;
|
||||
mcpServers = [];
|
||||
backlog = [];
|
||||
sdk.query.mockImplementation((request) => {
|
||||
const query = createQuery(request);
|
||||
queries.push(query);
|
||||
@@ -639,6 +644,33 @@ describe("provider updates preserve session configuration", { timeout: 10_000 },
|
||||
]);
|
||||
});
|
||||
|
||||
// Claude Code can run a cycle of its own on the new query before the next
|
||||
// prompt, for example a cron prompt. The reader of the old query ended with
|
||||
// that query.
|
||||
it("reads what the new query sends before the next prompt", async () => {
|
||||
const { sessionId } = await newSession();
|
||||
// The reader of the first query starts in a timer after the setup response.
|
||||
// Without this wait the timer would run after the restart and start the
|
||||
// reader of the new query.
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
const state = (state: "running" | "idle") => ({
|
||||
type: "system",
|
||||
subtype: "session_state_changed",
|
||||
state,
|
||||
uuid: randomUUID(),
|
||||
session_id: sessionId,
|
||||
});
|
||||
const usage = { ...successfulResultMessage().usage, input_tokens: 111 };
|
||||
// A cron prompt: its result has no origin.
|
||||
backlog = [state("running"), successfulResultMessage({ usage }), state("idle")];
|
||||
await refresh();
|
||||
await vi.waitFor(() => expect(agent.sessions[sessionId].lastSessionState).toBe("idle"));
|
||||
|
||||
const response = await prompt(sessionId);
|
||||
|
||||
expect(response.usage).toMatchObject({ inputTokens: 0 });
|
||||
});
|
||||
|
||||
it("reports a failed client MCP server once across a provider refresh", async () => {
|
||||
mcpServers = [{ name: "client-fs", status: "failed" }];
|
||||
const { sessionId } = await agent.newSession({
|
||||
|
||||
@@ -4,20 +4,28 @@ import { AcpClient } from "../../acp-client.js";
|
||||
import { loggableBaseUrl } from "../../providers.js";
|
||||
|
||||
const mockQuery = vi.hoisted(() =>
|
||||
vi.fn(() => ({
|
||||
initializationResult: vi.fn().mockResolvedValue({
|
||||
models: [
|
||||
{ value: "id", displayName: "name", description: "description", supportsAutoMode: true },
|
||||
],
|
||||
}),
|
||||
setModel: vi.fn(),
|
||||
setPermissionMode: vi.fn(),
|
||||
supportedCommands: vi.fn().mockResolvedValue([]),
|
||||
close: vi.fn(),
|
||||
interrupt: vi.fn().mockResolvedValue(undefined),
|
||||
getContextUsage: vi.fn().mockResolvedValue({ totalTokens: 0, rawMaxTokens: 200000 }),
|
||||
[Symbol.asyncIterator]: async function* () {},
|
||||
})),
|
||||
vi.fn(() => {
|
||||
// Like Claude Code's, the stream stays open until the query is closed.
|
||||
const closed = Promise.withResolvers<void>();
|
||||
return {
|
||||
initializationResult: vi.fn().mockResolvedValue({
|
||||
models: [
|
||||
{ value: "id", displayName: "name", description: "description", supportsAutoMode: true },
|
||||
],
|
||||
}),
|
||||
setModel: vi.fn(),
|
||||
setPermissionMode: vi.fn(),
|
||||
supportedCommands: vi.fn().mockResolvedValue([]),
|
||||
close: vi.fn(() => closed.resolve()),
|
||||
interrupt: vi.fn().mockResolvedValue(undefined),
|
||||
getContextUsage: vi.fn().mockResolvedValue({ totalTokens: 0, rawMaxTokens: 200000 }),
|
||||
next: async () => {
|
||||
await closed.promise;
|
||||
return { done: true as const, value: undefined };
|
||||
},
|
||||
[Symbol.asyncIterator]: async function* () {},
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
vi.mock("@anthropic-ai/claude-agent-sdk", async () => ({
|
||||
|
||||
@@ -10054,6 +10054,36 @@ describe("ACP v2 providers", () => {
|
||||
});
|
||||
});
|
||||
|
||||
// The new query of a restart can run a cycle before the next prompt, for
|
||||
// example a cron prompt. v2 reads every query from its start, so the cycle
|
||||
// is reported as it comes.
|
||||
it("reports a cycle that the new query of a restart runs before the next prompt", async () => {
|
||||
sdk.run = async function* (prompts, options) {
|
||||
if (options.resume) {
|
||||
// A cron prompt: its result has no origin.
|
||||
yield assistantText(options, "Checked the build.", "msg_cron");
|
||||
yield result(options);
|
||||
yield idleState(options);
|
||||
}
|
||||
const input = prompts[Symbol.asyncIterator]();
|
||||
while (!(await input.next()).done);
|
||||
};
|
||||
const client = v2Client();
|
||||
await client.app.connectWith(connectRouter(), async (agent) => {
|
||||
await initializeV2(agent);
|
||||
await agent.request(v2.methods.agent.session.new, { cwd });
|
||||
await setGateway(agent);
|
||||
await vi.waitFor(() =>
|
||||
expect(turnTrace(client.sessionUpdates)).toEqual([
|
||||
"running",
|
||||
"agent_message_chunk",
|
||||
"idle end_turn",
|
||||
]),
|
||||
);
|
||||
await client.authUpdate(1);
|
||||
});
|
||||
});
|
||||
|
||||
it("routes only the sessions started after a gateway login", async () => {
|
||||
const client = v2Client();
|
||||
await client.app.connectWith(connectRouter(), async (agent) => {
|
||||
|
||||
@@ -2475,8 +2475,10 @@ export class ClaudeAcpAgent {
|
||||
}
|
||||
// Once Remote Control is on, other clients can start turns or send
|
||||
// messages on their own. Something has to read the query stream for
|
||||
// those to reach this client, and a command that answers without a turn
|
||||
// would otherwise leave the stream unread until the next prompt.
|
||||
// those to reach this client. The reader starts after the session's
|
||||
// setup response and after a query restart; a command that comes before
|
||||
// the setup's timer ran (see `afterSetupResponse`) answers without a
|
||||
// turn and would leave the stream unread until that timer.
|
||||
this.ensureConsumer(session, params.sessionId);
|
||||
// Answered by the adapter without a model turn.
|
||||
events.inserted(randomUUID());
|
||||
@@ -3072,7 +3074,8 @@ export class ClaudeAcpAgent {
|
||||
|
||||
/** Lazily start the per-session consumer that drains the SDK query stream for
|
||||
* the session's whole life. Idempotent: the first caller starts it, a
|
||||
* session setup (see `afterSetupResponse`) or a `prompt()`. */
|
||||
* session setup (see `afterSetupResponse`), a query restart (see
|
||||
* `replaceSessionQuery`) or a `prompt()`. */
|
||||
private ensureConsumer(session: Session, sessionId: string): void {
|
||||
if (session.consumer) {
|
||||
return;
|
||||
@@ -10614,7 +10617,7 @@ export class ClaudeAcpAgent {
|
||||
}
|
||||
}
|
||||
|
||||
/** Recreates the session's query and restores its choices and reported MCP servers, unless it was closed meanwhile. */
|
||||
/** Recreates the session's query, restores its choices and reported MCP servers, and starts reading it, unless it was closed meanwhile. */
|
||||
private async replaceSessionQuery(
|
||||
sessionId: string,
|
||||
session: Session,
|
||||
@@ -10647,6 +10650,12 @@ export class ClaudeAcpAgent {
|
||||
error,
|
||||
);
|
||||
});
|
||||
// The reader of the old query ended with that query. Claude Code can run
|
||||
// cycles of its own on the new one before the next prompt, for example a
|
||||
// cron prompt or the follow-up to a finished background task, and that
|
||||
// prompt would take the first unread result as its answer. After the
|
||||
// choices are restored, so the reader reports against the restored state.
|
||||
if (!recreated.queryClosed) this.ensureConsumer(recreated, sessionId);
|
||||
}
|
||||
|
||||
/** Re-applies the choices of `previous` to the session that replaced it; a choice the new query rejects is logged. */
|
||||
|
||||
Reference in New Issue
Block a user