mirror of
https://github.com/agentclientprotocol/claude-agent-acp.git
synced 2026-12-01 21:52:06 +00:00
fix: stop an autonomous turn while a prompt waits (#1727)
## Problem
In ACP v1 sessions with the `asyncTasks` capability, the "Claude is
working" task of an autonomous turn (one that a background task's
notification or a scheduler fire started) could not be stopped while the
user's next prompt waited behind it: `_session/async_task/stop` returned
`{ "stopped": false }`. The refusal assumed that the interrupt would
drop the waiting prompt.
## What the CLI actually does
Pinned by `src/tests/interrupt-queued-prompt-integration.test.ts`
against the bundled CLI:
- `interrupt()` returns `{ still_queued: [<waiting prompt uuid>] }`;
- the interrupted turn ends with its own result
(`error_during_execution`, `terminal_reason: "aborted_streaming"`,
`origin.kind: "task-notification"`), which does not name the waiting
prompt;
- the CLI then runs the waiting prompt by itself and ends it with a
normal result.
## Change
- `stopAsyncTask` interrupts the autonomous turn unless a waiting prompt
was already dispatched into a turn (a `started` lifecycle frame) or the
CLI sends no message lifecycle frames; in those cases it still returns
`{ stopped: false }`.
- A stop owes the interrupted turn's aborted result. The result handler
routes that result to the autonomous turn even when it has no `origin`
(a scheduler fire), so it does not end the waiting prompt.
- If a waiting prompt is missing from the receipt's `still_queued`, it
is logged.
- The logic lives in `async-task-stop.ts` (`interruptAutonomousTurn`)
and `AsyncTaskRuntime.startedByClaudeCode`; `acp-agent.ts` calls them.
- `docs/air-extensions.md` describes when the stop is refused.
v2 is unchanged: it has no autonomous-turn tasks.
## Tests
- Unit tests for the refusal rule, the owed result, and
`interruptAutonomousTurn`.
- Two integration tests (`RUN_INTEGRATION_TESTS=1`) that run the bundled
CLI against a scripted model on 127.0.0.1 in a throwaway home, so no
account or API usage: one pins the CLI behaviour above, one runs the
stop end to end through `ClaudeAcpAgent`. The end-to-end test fails on
`main`.
This commit is contained in:
@@ -1116,7 +1116,8 @@ It ends `completed` at the result of the turn or at the SDK `idle` state, and `f
|
||||
A coalesced placeholder result (`num_turns: 0`) does not end it.
|
||||
A prompt that the turn takes in ends the task, because that prompt owns the turn now.
|
||||
A stop request interrupts the turn instead of stopping an SDK task.
|
||||
It returns `{ "stopped": false }` while a prompt waits for its turn, because the interrupt would drop that prompt.
|
||||
A prompt that waits for its turn survives the stop and runs next.
|
||||
It returns `{ "stopped": false }` only while a prompt waits and either Claude Code already took it into the turn or the CLI sends no message lifecycle frames.
|
||||
|
||||
### Stop request
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { SDKMessage } from "@anthropic-ai/claude-agent-sdk";
|
||||
import type { ClientCapabilities } from "@agentclientprotocol/sdk/unstable";
|
||||
import type { AcpSessionNotification, AsyncTaskState } from "./acp-subagents.js";
|
||||
import { AIR_ASYNC_TASKS_CAPABILITY, clientSupportsAirCapability } from "./air-extension.js";
|
||||
import { AUTONOMOUS_RESULT_ORIGINS, isAbortedResult } from "./result-end.js";
|
||||
import { noticeOrTranscriptUpdate } from "./session-notices.js";
|
||||
|
||||
type Publish = (notification: AcpSessionNotification) => Promise<void>;
|
||||
@@ -154,6 +156,12 @@ export class AsyncTaskRuntime {
|
||||
private readonly outputPathsByToolCall = new Map<string, string[]>();
|
||||
/** The task of the autonomous turn that runs now. */
|
||||
private autonomousTurn?: AsyncTask;
|
||||
/**
|
||||
* Whether a stop interrupted the autonomous turn and its aborted result has
|
||||
* not come yet. Stopping ends the task, so this is the only trace that the
|
||||
* result belongs to that turn, see {@link startedByClaudeCode}.
|
||||
*/
|
||||
private interruptedTurnResultOwed = false;
|
||||
/** The summary of the last task notification, which usually starts the next autonomous turn. */
|
||||
private lastNotificationSummary?: string;
|
||||
|
||||
@@ -410,6 +418,7 @@ export class AsyncTaskRuntime {
|
||||
|
||||
async finishAll(state: Extract<AsyncTaskState, "failed" | "stopped">): Promise<void> {
|
||||
this.autonomousTurn = undefined;
|
||||
this.interruptedTurnResultOwed = false;
|
||||
const errors: unknown[] = [];
|
||||
for (const task of this.tasks.values()) {
|
||||
if ((task.announced || task.held) && !task.ignored && !isTerminal(task.state)) {
|
||||
@@ -520,6 +529,41 @@ export class AsyncTaskRuntime {
|
||||
await this.finish(task, state, undefined, "event");
|
||||
}
|
||||
|
||||
/** A stop is about to interrupt the autonomous turn: its aborted result is owed. */
|
||||
autonomousTurnInterrupting(): void {
|
||||
this.interruptedTurnResultOwed = true;
|
||||
}
|
||||
|
||||
/** The interrupt failed, so the turn goes on and no aborted result is owed. */
|
||||
autonomousTurnInterruptFailed(): void {
|
||||
this.interruptedTurnResultOwed = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether Claude Code started the work that a result reports: the result has
|
||||
* an autonomous origin, or it is the aborted result that a stop owes. Call it
|
||||
* for every result: the first one after the stop ends the debt, even when
|
||||
* the result has an autonomous origin. A turn that a scheduler fire started
|
||||
* has results with no `origin`, so the origin cannot tell it from a waiting
|
||||
* prompt's result. The first result is the turn's when it is aborted and
|
||||
* names no waiting prompt (`answersPrompt`). A non-aborted result means the
|
||||
* interrupted turn finished without an aborted result, and one that names a
|
||||
* waiting prompt means the turn took the prompt in; neither is the turn's.
|
||||
* This relies on the CLI emitting the interrupted turn's result before the
|
||||
* next turn's, which nothing enforces here.
|
||||
*/
|
||||
startedByClaudeCode(
|
||||
result: Extract<SDKMessage, { type: "result" }>,
|
||||
answersPrompt: boolean,
|
||||
): boolean {
|
||||
const owed = this.interruptedTurnResultOwed;
|
||||
this.interruptedTurnResultOwed = false;
|
||||
return (
|
||||
(result.origin != null && AUTONOMOUS_RESULT_ORIGINS.has(result.origin.kind)) ||
|
||||
(owed && isAbortedResult(result) && !answersPrompt)
|
||||
);
|
||||
}
|
||||
|
||||
/** Whether the task stands for an autonomous turn, which a stop interrupts. */
|
||||
isAutonomousTurn(taskId: string): boolean {
|
||||
return this.tasks.get(taskId)?.autonomousTurn === true;
|
||||
@@ -576,6 +620,7 @@ export class AsyncTaskRuntime {
|
||||
this.tasks.clear();
|
||||
this.outputPathsByToolCall.clear();
|
||||
this.autonomousTurn = undefined;
|
||||
this.interruptedTurnResultOwed = false;
|
||||
this.lastNotificationSummary = undefined;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { SDKMessage } from "@anthropic-ai/claude-agent-sdk";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { AcpSessionNotification } from "../acp-subagents.js";
|
||||
import {
|
||||
@@ -6,6 +7,13 @@ import {
|
||||
clientSupportsAsyncTasks,
|
||||
} from "../async-tasks.js";
|
||||
|
||||
const result = (aborted: boolean, origin?: { kind: string }) =>
|
||||
({
|
||||
type: "result",
|
||||
terminal_reason: aborted ? "aborted_streaming" : "completed",
|
||||
origin,
|
||||
}) as unknown as Extract<SDKMessage, { type: "result" }>;
|
||||
|
||||
describe("AsyncTaskRuntime", () => {
|
||||
it("keeps an autonomous turn open across the SDK task list and fails it at shutdown", async () => {
|
||||
const updates: AcpSessionNotification[] = [];
|
||||
@@ -25,6 +33,41 @@ describe("AsyncTaskRuntime", () => {
|
||||
).toEqual(["async_task_spawned", "failed"]);
|
||||
});
|
||||
|
||||
// [aborted, answersPrompt] per result, in stream order.
|
||||
it.each([
|
||||
["an aborted result that names no waiting prompt", false, [[true, false]], [true]],
|
||||
["a non-aborted result", false, [[false, false]], [false]],
|
||||
["an aborted result that names a waiting prompt", false, [[true, true]], [false]],
|
||||
[
|
||||
"only the first result",
|
||||
false,
|
||||
[
|
||||
[false, false],
|
||||
[true, false],
|
||||
],
|
||||
[false, false],
|
||||
],
|
||||
["a failed interrupt", true, [[true, false]], [false]],
|
||||
] as const)("owes the stopped turn's result to %s", (_name, failed, results, expected) => {
|
||||
const runtime = new AsyncTaskRuntime(true, "root", async () => {});
|
||||
runtime.autonomousTurnInterrupting();
|
||||
if (failed) runtime.autonomousTurnInterruptFailed();
|
||||
|
||||
expect(
|
||||
results.map(([aborted, answers]) => runtime.startedByClaudeCode(result(aborted), answers)),
|
||||
).toEqual(expected);
|
||||
});
|
||||
|
||||
it("clears the debt on a result with an autonomous origin", () => {
|
||||
const runtime = new AsyncTaskRuntime(true, "root", async () => {});
|
||||
runtime.autonomousTurnInterrupting();
|
||||
|
||||
expect(runtime.startedByClaudeCode(result(false, { kind: "task-notification" }), false)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(runtime.startedByClaudeCode(result(true), false)).toBe(false);
|
||||
});
|
||||
|
||||
it("recovers a background Bash task from its structured tool result", async () => {
|
||||
const updates: AcpSessionNotification[] = [];
|
||||
const runtime = new AsyncTaskRuntime(true, "root", async (notification) => {
|
||||
|
||||
141
src/tests/interrupt-queued-prompt-integration.test.ts
Normal file
141
src/tests/interrupt-queued-prompt-integration.test.ts
Normal file
@@ -0,0 +1,141 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdir, mkdtemp } from "node:fs/promises";
|
||||
import type { Server } from "node:http";
|
||||
import { tmpdir } from "node:os";
|
||||
import * as path from "node:path";
|
||||
import {
|
||||
query,
|
||||
type Query,
|
||||
type SDKMessage,
|
||||
type SDKUserMessage,
|
||||
} from "@anthropic-ai/claude-agent-sdk";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { claudeCliPath } from "../claude-cli.js";
|
||||
import { Pushable } from "../utils.js";
|
||||
import { cleanUp, isolateFromMachine, scriptedModel } from "./scripted-model.js";
|
||||
|
||||
/**
|
||||
* What the bundled Claude Code CLI does when `interrupt()` lands during an
|
||||
* autonomous turn (one that a background task's notification started) while a
|
||||
* user message waits in its queue. The adapter's cancel relies on the receipt
|
||||
* listing that message in `still_queued`, on the interrupted turn ending with
|
||||
* its own result, and on the CLI then running the queued message by itself.
|
||||
*
|
||||
* Only the model is scripted: Claude Code talks to a server on 127.0.0.1, in an
|
||||
* empty home directory. The case needs no account and costs no API usage.
|
||||
*/
|
||||
describe.skipIf(!process.env.RUN_INTEGRATION_TESTS)(
|
||||
"interrupt during an autonomous turn with a queued prompt",
|
||||
() => {
|
||||
let home: string;
|
||||
let model: Server;
|
||||
let scripted: ReturnType<typeof scriptedModel>;
|
||||
const closing: Array<() => Promise<unknown> | void> = [];
|
||||
|
||||
beforeEach(async () => {
|
||||
home = await mkdtemp(path.join(tmpdir(), "acp-interrupt-integration-"));
|
||||
await mkdir(path.join(home, "workspace"));
|
||||
scripted = scriptedModel();
|
||||
model = scripted.server;
|
||||
await new Promise<void>((resolve) => model.listen(0, "127.0.0.1", resolve));
|
||||
isolateFromMachine(home, model);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
for (const close of closing.splice(0).reverse()) await close();
|
||||
await cleanUp(home, model);
|
||||
});
|
||||
|
||||
const userMessage = (text: string, uuid: string): SDKUserMessage => ({
|
||||
type: "user",
|
||||
uuid: uuid as SDKUserMessage["uuid"],
|
||||
session_id: "",
|
||||
parent_tool_use_id: null,
|
||||
message: { role: "user", content: [{ type: "text", text }] },
|
||||
});
|
||||
|
||||
it("runs the queued prompt next, after the interrupted turn's own result", async () => {
|
||||
const input = new Pushable<SDKUserMessage>();
|
||||
const q: Query = query({
|
||||
prompt: input,
|
||||
options: {
|
||||
cwd: path.join(home, "workspace"),
|
||||
// The bundled CLI that the adapter runs, not one on PATH.
|
||||
pathToClaudeCodeExecutable: await claudeCliPath(),
|
||||
// The background Bash runs without a permission prompt; the home is a throwaway.
|
||||
permissionMode: "bypassPermissions",
|
||||
allowDangerouslySkipPermissions: true,
|
||||
allowedTools: ["Bash"],
|
||||
settingSources: [],
|
||||
// The CLI echoes each user message with its uuid, as the adapter's sessions get it.
|
||||
extraArgs: { "replay-user-messages": "" },
|
||||
},
|
||||
});
|
||||
closing.push(() => {
|
||||
input.end();
|
||||
q.close();
|
||||
});
|
||||
const messages: SDKMessage[] = [];
|
||||
void (async () => {
|
||||
try {
|
||||
for await (const message of q) messages.push(message);
|
||||
} catch {
|
||||
// The query is closed at the end of the case.
|
||||
}
|
||||
})();
|
||||
const results = () => messages.filter((m) => m.type === "result");
|
||||
|
||||
const U1 = randomUUID();
|
||||
const U2 = randomUUID();
|
||||
input.push(userMessage("PROMPT_ONE", U1));
|
||||
await vi.waitFor(() => expect(results()).toHaveLength(1), { timeout: 60_000 });
|
||||
expect(results()[0]).toMatchObject({ subtype: "success", is_error: false });
|
||||
|
||||
// The background command ends and Claude Code starts an autonomous turn,
|
||||
// whose model response the server holds mid-stream.
|
||||
await scripted.autonomousHeld;
|
||||
// Send Now: the prompt waits in the CLI's queue, since the held turn has no tool round to fold it into.
|
||||
input.push(userMessage("QUEUED_PROMPT", U2));
|
||||
// Time for the CLI to read the message into its queue; nothing signals that it did.
|
||||
await new Promise((resolve) => setTimeout(resolve, 1_000));
|
||||
|
||||
// What a Stop on the "Claude is working" row would send.
|
||||
const receipt = await q.interrupt();
|
||||
|
||||
// Results: prompt 1, the interrupted autonomous turn, prompt 2.
|
||||
await vi.waitFor(() => expect(results().length).toBeGreaterThanOrEqual(3), {
|
||||
timeout: 60_000,
|
||||
});
|
||||
|
||||
expect(receipt).toBeDefined();
|
||||
expect(receipt?.still_queued).toContain(U2);
|
||||
|
||||
const [, interrupted, answered] = results() as Array<
|
||||
Extract<SDKMessage, { type: "result" }> & { origin?: { kind?: string } }
|
||||
>;
|
||||
// `origin` is what lets the adapter route this result to the autonomous turn, not to prompt 2.
|
||||
expect(interrupted.origin?.kind).toBe("task-notification");
|
||||
expect(interrupted).toMatchObject({
|
||||
subtype: "error_during_execution",
|
||||
is_error: true,
|
||||
terminal_reason: "aborted_streaming",
|
||||
});
|
||||
// A result names its prompts in `user_message_uuids`; this one must not claim prompt 2.
|
||||
expect(JSON.stringify(interrupted)).not.toContain(U2);
|
||||
|
||||
// The CLI asked the model about the queued prompt without another push.
|
||||
expect(scripted.requestTexts().some((text) => text.includes("QUEUED_PROMPT"))).toBe(true);
|
||||
expect(answered.subtype).toBe("success");
|
||||
expect(answered.is_error).toBe(false);
|
||||
expect((answered as { result?: string }).result).toBe("answer-2");
|
||||
|
||||
// Nothing enforces this order: the CLI replays the queued prompt after the
|
||||
// interrupted turn's result and before the result that answers it.
|
||||
const echo = messages.findIndex(
|
||||
(m) => m.type === "user" && (m as { uuid?: string }).uuid === U2,
|
||||
);
|
||||
expect(echo).toBeGreaterThan(messages.indexOf(interrupted));
|
||||
expect(echo).toBeLessThan(messages.indexOf(answered));
|
||||
}, 120_000);
|
||||
},
|
||||
);
|
||||
132
src/tests/scripted-model.ts
Normal file
132
src/tests/scripted-model.ts
Normal file
@@ -0,0 +1,132 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { rm } from "node:fs/promises";
|
||||
import { createServer, type Server, type ServerResponse } from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import * as path from "node:path";
|
||||
import { vi } from "vitest";
|
||||
|
||||
/** Points Claude Code at `model` (listening on 127.0.0.1) in the empty home `home`. */
|
||||
export function isolateFromMachine(home: string, model: Server): void {
|
||||
// No account, model endpoint, user settings or project config of the machine.
|
||||
// CLAUDE_CODE_DISABLE_BACKGROUND_TASKS stays unset: the case needs a background Bash.
|
||||
vi.stubEnv("HOME", home);
|
||||
vi.stubEnv("CLAUDE_CONFIG_DIR", path.join(home, ".claude"));
|
||||
vi.stubEnv("ANTHROPIC_BASE_URL", `http://127.0.0.1:${(model.address() as AddressInfo).port}`);
|
||||
vi.stubEnv("ANTHROPIC_API_KEY", randomUUID());
|
||||
vi.stubEnv("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", "1");
|
||||
for (const name of ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"]) {
|
||||
vi.stubEnv(name, "http://127.0.0.1:9");
|
||||
}
|
||||
vi.stubEnv("NO_PROXY", "127.0.0.1,localhost");
|
||||
}
|
||||
|
||||
/** Undoes `isolateFromMachine` and removes what the case created. */
|
||||
export async function cleanUp(home: string, model: Server): Promise<void> {
|
||||
model.closeAllConnections();
|
||||
model.close();
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllEnvs();
|
||||
await rm(home, { recursive: true, force: true, maxRetries: 10 });
|
||||
}
|
||||
|
||||
/**
|
||||
* A model that Claude Code talks to in place of the Anthropic API. `PROMPT_ONE`
|
||||
* gets a background `Bash` call, then "started". The request that carries the
|
||||
* task notification is held: the server sends `message_start` and a text delta
|
||||
* and keeps the stream open. A request whose last user message has
|
||||
* `QUEUED_PROMPT` gets "answer-2". Every other request gets "ok".
|
||||
*/
|
||||
export function scriptedModel() {
|
||||
const autonomousHeld = Promise.withResolvers<void>();
|
||||
const texts: string[] = [];
|
||||
const held: ServerResponse[] = [];
|
||||
let heldOnce = false;
|
||||
const server = createServer(async (request, response) => {
|
||||
let raw = "";
|
||||
for await (const chunk of request) raw += chunk;
|
||||
const body = raw ? JSON.parse(raw) : {};
|
||||
const json = (value: unknown) => {
|
||||
response.setHeader("content-type", "application/json");
|
||||
response.end(JSON.stringify(value));
|
||||
};
|
||||
if (request.url?.includes("count_tokens")) return json({ input_tokens: 100 });
|
||||
if (request.url?.split("?")[0] !== "/v1/messages") return json({});
|
||||
const users = (body.messages ?? []).filter((m: { role: string }) => m.role === "user");
|
||||
const last = JSON.stringify(users.at(-1)?.content ?? "");
|
||||
texts.push(last);
|
||||
const lastIsToolResult = last.includes('"tool_result"');
|
||||
|
||||
type Block =
|
||||
| { type: "text"; text: string }
|
||||
| { type: "tool_use"; id: string; name: string; input: Record<string, unknown> };
|
||||
let blocks: Block[] = [{ type: "text", text: "ok" }];
|
||||
let hold = false;
|
||||
if (last.includes("QUEUED_PROMPT")) {
|
||||
blocks = [{ type: "text", text: "answer-2" }];
|
||||
} else if (last.includes("PROMPT_ONE")) {
|
||||
blocks = [
|
||||
{
|
||||
type: "tool_use",
|
||||
id: "toolu_bg",
|
||||
name: "Bash",
|
||||
input: { command: "sleep 1; echo bg-done", run_in_background: true, description: "bg" },
|
||||
},
|
||||
];
|
||||
} else if (lastIsToolResult && last.includes("toolu_bg")) {
|
||||
blocks = [{ type: "text", text: "started" }];
|
||||
} else if (last.includes("<task-notification>") && !heldOnce) {
|
||||
// The autonomous turn's request; only the first one is held, any later one gets "ok".
|
||||
heldOnce = true;
|
||||
hold = true;
|
||||
}
|
||||
|
||||
const stopReason = blocks[0].type === "tool_use" ? "tool_use" : "end_turn";
|
||||
const message = {
|
||||
type: "message",
|
||||
id: `msg_${randomUUID()}`,
|
||||
model: body.model,
|
||||
role: "assistant",
|
||||
stop_sequence: null,
|
||||
usage: { input_tokens: 100, output_tokens: 20 },
|
||||
content: blocks,
|
||||
stop_reason: stopReason,
|
||||
};
|
||||
if (!body.stream) return json(message);
|
||||
response.writeHead(200, { "content-type": "text/event-stream" });
|
||||
const send = (type: string, fields: Record<string, unknown> = {}) =>
|
||||
response.write(`event: ${type}\ndata: ${JSON.stringify({ type, ...fields })}\n\n`);
|
||||
send("message_start", { message: { ...message, content: [], stop_reason: null } });
|
||||
if (hold) {
|
||||
send("content_block_start", { index: 0, content_block: { type: "text", text: "" } });
|
||||
send("content_block_delta", { index: 0, delta: { type: "text_delta", text: "working" } });
|
||||
held.push(response);
|
||||
autonomousHeld.resolve();
|
||||
return;
|
||||
}
|
||||
blocks.forEach((block, index) => {
|
||||
send("content_block_start", {
|
||||
index,
|
||||
content_block: block.type === "tool_use" ? { ...block, input: {} } : { ...block, text: "" },
|
||||
});
|
||||
send("content_block_delta", {
|
||||
index,
|
||||
delta:
|
||||
block.type === "tool_use"
|
||||
? { type: "input_json_delta", partial_json: JSON.stringify(block.input) }
|
||||
: { type: "text_delta", text: block.text },
|
||||
});
|
||||
send("content_block_stop", { index });
|
||||
});
|
||||
send("message_delta", {
|
||||
delta: { stop_reason: stopReason, stop_sequence: null },
|
||||
usage: { output_tokens: 20 },
|
||||
});
|
||||
send("message_stop");
|
||||
response.end();
|
||||
});
|
||||
return {
|
||||
server,
|
||||
autonomousHeld: autonomousHeld.promise,
|
||||
requestTexts: () => [...texts],
|
||||
};
|
||||
}
|
||||
@@ -26799,13 +26799,14 @@ describe("deferred settlement for live background subagents (issues #864/#866)",
|
||||
describe("autonomous turn as an async task", () => {
|
||||
const airAgent = async (capabilities: string[] = ["asyncTasks"]) => {
|
||||
const updates: AcpSessionNotification[] = [];
|
||||
const logger = { log: vi.fn(), error: vi.fn() };
|
||||
const agent = new ClaudeAcpAgent(
|
||||
{
|
||||
sessionUpdate: async (notification: AcpSessionNotification) => {
|
||||
updates.push(notification);
|
||||
},
|
||||
} as unknown as AcpClient,
|
||||
{ log: () => {}, error: () => {} },
|
||||
logger,
|
||||
);
|
||||
await agent.initialize({
|
||||
protocolVersion: 1,
|
||||
@@ -26817,7 +26818,7 @@ describe("deferred settlement for live background subagents (issues #864/#866)",
|
||||
updates.flatMap(({ update }) =>
|
||||
update.sessionUpdate.startsWith("async_task_") ? [update as any] : [],
|
||||
);
|
||||
return { agent, updates, asyncTaskUpdates };
|
||||
return { agent, updates, asyncTaskUpdates, logger };
|
||||
};
|
||||
|
||||
const shellNotification = () => ({
|
||||
@@ -27196,6 +27197,236 @@ describe("deferred settlement for live background subagents (issues #864/#866)",
|
||||
]);
|
||||
});
|
||||
|
||||
describe("stop while a prompt waits", () => {
|
||||
/** An autonomous turn is running and a prompt waits behind it. `finish`
|
||||
* lets the CLI emit the interrupted result, then the waiting prompt's
|
||||
* echo, answer and result, as the real CLI orders them. */
|
||||
const waitingPromptScenario = async (options: {
|
||||
lifecycle: boolean;
|
||||
interruptedOrigin?: Record<string, unknown>;
|
||||
}) => {
|
||||
const { agent, asyncTaskUpdates, logger } = await airAgent();
|
||||
let wake = () => {};
|
||||
const woken = new Promise<void>((resolve) => (wake = resolve));
|
||||
let finish = () => {};
|
||||
const finished = new Promise<void>((resolve) => (finish = resolve));
|
||||
injectGeneratorSession(agent, (input) => {
|
||||
async function* messageGenerator() {
|
||||
const iter = input[Symbol.asyncIterator]();
|
||||
const first = await iter.next();
|
||||
if (options.lifecycle) yield lifecycleInit;
|
||||
yield userEcho(first.value);
|
||||
yield running();
|
||||
yield resultMessage();
|
||||
yield idle();
|
||||
await woken;
|
||||
yield running();
|
||||
yield assistantText("on my own");
|
||||
const waiting = await iter.next();
|
||||
await finished;
|
||||
yield {
|
||||
...assistantText("partial"),
|
||||
aborted: true,
|
||||
};
|
||||
yield {
|
||||
type: "user",
|
||||
message: {
|
||||
role: "user",
|
||||
content: [{ type: "text", text: "[Request interrupted by user]" }],
|
||||
},
|
||||
parent_tool_use_id: null,
|
||||
uuid: randomUUID(),
|
||||
session_id: "test-session",
|
||||
};
|
||||
yield resultMessage({
|
||||
subtype: "error_during_execution",
|
||||
is_error: true,
|
||||
stop_reason: null,
|
||||
terminal_reason: "aborted_streaming",
|
||||
...(options.interruptedOrigin ? { origin: options.interruptedOrigin } : {}),
|
||||
});
|
||||
if (options.lifecycle) yield lifecycleFrame(waiting.value.uuid, "started");
|
||||
yield userEcho(waiting.value);
|
||||
yield assistantText("answer to the waiting prompt");
|
||||
yield resultMessage({ user_message_uuids: [waiting.value.uuid] });
|
||||
if (options.lifecycle) yield lifecycleFrame(waiting.value.uuid, "completed");
|
||||
yield idle();
|
||||
}
|
||||
return messageGenerator();
|
||||
});
|
||||
|
||||
await agent.prompt({ sessionId: "test-session", prompt: [{ type: "text", text: "go" }] });
|
||||
wake();
|
||||
await waitFor(() => asyncTaskUpdates().length === 1);
|
||||
const waitingPrompt = agent.prompt({
|
||||
sessionId: "test-session",
|
||||
prompt: [{ type: "text", text: "and this" }],
|
||||
});
|
||||
const session = agent.sessions["test-session"]!;
|
||||
await waitFor(() => (session.turnQueue ?? []).some((turn: any) => !turn.settled));
|
||||
const promptUuid = session.turnQueue!.find((turn: any) => !turn.settled)!.promptUuid;
|
||||
const stop = () =>
|
||||
agent.stopAsyncTask({
|
||||
sessionId: "test-session",
|
||||
asyncTaskId: asyncTaskUpdates()[0].asyncTaskId,
|
||||
});
|
||||
return {
|
||||
agent,
|
||||
session,
|
||||
asyncTaskUpdates,
|
||||
logger,
|
||||
waitingPrompt,
|
||||
promptUuid,
|
||||
stop,
|
||||
finish,
|
||||
};
|
||||
};
|
||||
|
||||
// The result carries the origin that the real CLI gives the interrupted turn.
|
||||
const taskNotificationOrigin = { kind: "task-notification", producer: "session-task" };
|
||||
|
||||
it.each([
|
||||
["with its task-notification origin", taskNotificationOrigin],
|
||||
// A scheduler fire starts the turn, and its results have no origin.
|
||||
["without an origin after a scheduler fire", undefined],
|
||||
])(
|
||||
"keeps the waiting prompt and runs it next, interrupted result %s",
|
||||
async (_name, origin) => {
|
||||
const { session, asyncTaskUpdates, waitingPrompt, promptUuid, stop, finish } =
|
||||
await waitingPromptScenario({ lifecycle: true, interruptedOrigin: origin });
|
||||
vi.mocked(session.query.interrupt).mockResolvedValue({
|
||||
still_queued: [promptUuid],
|
||||
} as any);
|
||||
|
||||
await expect(stop()).resolves.toEqual({ stopped: true });
|
||||
expect(session.query.interrupt).toHaveBeenCalledTimes(1);
|
||||
finish();
|
||||
|
||||
await expect(waitingPrompt).resolves.toMatchObject({ stopReason: "end_turn" });
|
||||
expect(asyncTaskUpdates().map((update) => update.state ?? update.sessionUpdate)).toEqual([
|
||||
"async_task_spawned",
|
||||
"stopped",
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
it("rejects the stop and releases the claim when the interrupt fails", async () => {
|
||||
const { session, waitingPrompt, promptUuid, stop, finish } = await waitingPromptScenario({
|
||||
lifecycle: true,
|
||||
interruptedOrigin: taskNotificationOrigin,
|
||||
});
|
||||
vi.mocked(session.query.interrupt).mockRejectedValueOnce(new Error("interrupt failed"));
|
||||
|
||||
await expect(stop()).rejects.toThrow("interrupt failed");
|
||||
|
||||
vi.mocked(session.query.interrupt).mockResolvedValue({ still_queued: [promptUuid] } as any);
|
||||
await expect(stop()).resolves.toEqual({ stopped: true });
|
||||
finish();
|
||||
await waitingPrompt;
|
||||
});
|
||||
|
||||
it("logs a waiting prompt that the interrupt receipt does not list as still queued", async () => {
|
||||
const { session, logger, waitingPrompt, promptUuid, stop, finish } =
|
||||
await waitingPromptScenario({
|
||||
lifecycle: true,
|
||||
interruptedOrigin: taskNotificationOrigin,
|
||||
});
|
||||
vi.mocked(session.query.interrupt).mockResolvedValue({ still_queued: [] } as any);
|
||||
|
||||
await stop();
|
||||
expect(logger.log).toHaveBeenCalledWith(expect.stringContaining(promptUuid));
|
||||
finish();
|
||||
await waitingPrompt;
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"Claude Code already dispatched the prompt into a turn",
|
||||
true,
|
||||
(session: any) => {
|
||||
session.turnQueue.find((turn: any) => !turn.settled).commandStarted = false;
|
||||
},
|
||||
(session: any) => {
|
||||
session.turnQueue.find((turn: any) => !turn.settled).commandStarted = true;
|
||||
},
|
||||
],
|
||||
[
|
||||
"the CLI sends no lifecycle frames",
|
||||
false,
|
||||
(session: any) => {
|
||||
session.msgLifecycleV1 = true;
|
||||
},
|
||||
() => {},
|
||||
],
|
||||
])("refuses the stop when %s", async (_name, lifecycle, allow, deny) => {
|
||||
const { session, waitingPrompt, stop, finish } = await waitingPromptScenario({
|
||||
lifecycle,
|
||||
interruptedOrigin: taskNotificationOrigin,
|
||||
});
|
||||
deny(session);
|
||||
|
||||
await expect(stop()).resolves.toEqual({ stopped: false });
|
||||
expect(session.query.interrupt).not.toHaveBeenCalled();
|
||||
|
||||
// The refusal released the claim: the same task can be stopped once the prompt qualifies.
|
||||
allow(session);
|
||||
vi.mocked(session.query.interrupt).mockResolvedValue({ still_queued: [] } as any);
|
||||
await expect(stop()).resolves.toEqual({ stopped: true });
|
||||
finish();
|
||||
await waitingPrompt;
|
||||
});
|
||||
});
|
||||
|
||||
// The interrupted result with the autonomous origin ends the debt that the
|
||||
// stop owes, so a later prompt's origin-less aborted result is that prompt's.
|
||||
it("ends a later prompt at its own aborted result after a stop", async () => {
|
||||
const { agent, asyncTaskUpdates } = await airAgent();
|
||||
let wake = () => {};
|
||||
const woken = new Promise<void>((resolve) => (wake = resolve));
|
||||
let finish = () => {};
|
||||
const finished = new Promise<void>((resolve) => (finish = resolve));
|
||||
injectGeneratorSession(agent, (input) => {
|
||||
async function* messageGenerator() {
|
||||
const iter = input[Symbol.asyncIterator]();
|
||||
yield userEcho((await iter.next()).value);
|
||||
yield running();
|
||||
yield resultMessage();
|
||||
yield idle();
|
||||
await woken;
|
||||
yield running();
|
||||
yield assistantText("on my own");
|
||||
await finished;
|
||||
const aborted = {
|
||||
subtype: "error_during_execution",
|
||||
is_error: true,
|
||||
stop_reason: null,
|
||||
terminal_reason: "aborted_streaming",
|
||||
};
|
||||
yield resultMessage({ ...aborted, origin: { kind: "task-notification" } });
|
||||
yield idle();
|
||||
yield userEcho((await iter.next()).value);
|
||||
yield running();
|
||||
// A CLI that does not stamp results: no origin and no user_message_uuid(s).
|
||||
yield resultMessage(aborted);
|
||||
yield idle();
|
||||
}
|
||||
return messageGenerator();
|
||||
});
|
||||
|
||||
await agent.prompt({ sessionId: "test-session", prompt: [{ type: "text", text: "go" }] });
|
||||
wake();
|
||||
await waitFor(() => asyncTaskUpdates().length === 1);
|
||||
await agent.stopAsyncTask({
|
||||
sessionId: "test-session",
|
||||
asyncTaskId: asyncTaskUpdates()[0].asyncTaskId,
|
||||
});
|
||||
finish();
|
||||
|
||||
await expect(
|
||||
agent.prompt({ sessionId: "test-session", prompt: [{ type: "text", text: "next" }] }),
|
||||
).rejects.toThrow("error_during_execution");
|
||||
});
|
||||
|
||||
it("publishes nothing to a client without async tasks", async () => {
|
||||
const { agent, asyncTaskUpdates } = await airAgent([]);
|
||||
injectGeneratorSession(agent, (input) => {
|
||||
|
||||
60
src/tests/v1/async-task-stop.test.ts
Normal file
60
src/tests/v1/async-task-stop.test.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { interruptAutonomousTurn } from "../../v1/async-task-stop.js";
|
||||
|
||||
function setup(interrupt: () => Promise<{ still_queued?: string[] } | undefined>) {
|
||||
const calls: string[] = [];
|
||||
const asyncTasks = {
|
||||
autonomousTurnInterrupting: () => calls.push("interrupting"),
|
||||
autonomousTurnInterruptFailed: () => calls.push("failed"),
|
||||
};
|
||||
const query = {
|
||||
interrupt: async () => {
|
||||
calls.push("interrupt");
|
||||
return interrupt();
|
||||
},
|
||||
};
|
||||
const logger = { log: vi.fn() };
|
||||
return { calls, asyncTasks, query, logger };
|
||||
}
|
||||
|
||||
describe("interruptAutonomousTurn", () => {
|
||||
it("owes the aborted result before it interrupts", async () => {
|
||||
const { calls, asyncTasks, query, logger } = setup(async () => undefined);
|
||||
|
||||
await interruptAutonomousTurn(query, asyncTasks, [], logger);
|
||||
|
||||
expect(calls).toEqual(["interrupting", "interrupt"]);
|
||||
});
|
||||
|
||||
it("rolls the debt back and rethrows when the interrupt fails", async () => {
|
||||
const error = new Error("boom");
|
||||
const { calls, asyncTasks, query, logger } = setup(async () => {
|
||||
throw error;
|
||||
});
|
||||
|
||||
await expect(interruptAutonomousTurn(query, asyncTasks, [], logger)).rejects.toBe(error);
|
||||
expect(calls).toEqual(["interrupting", "interrupt", "failed"]);
|
||||
});
|
||||
|
||||
it("logs the waiting prompts that the receipt does not list", async () => {
|
||||
const { asyncTasks, query, logger } = setup(async () => ({ still_queued: ["kept"] }));
|
||||
|
||||
await interruptAutonomousTurn(
|
||||
query,
|
||||
asyncTasks,
|
||||
[{ promptUuid: "kept" }, { promptUuid: "lost" }],
|
||||
logger,
|
||||
);
|
||||
|
||||
expect(logger.log).toHaveBeenCalledTimes(1);
|
||||
expect(logger.log.mock.calls[0][0]).toContain("Prompt lost is not in");
|
||||
});
|
||||
|
||||
it("logs nothing without still_queued", async () => {
|
||||
const { asyncTasks, query, logger } = setup(async () => ({}));
|
||||
|
||||
await interruptAutonomousTurn(query, asyncTasks, [{ promptUuid: "any" }], logger);
|
||||
|
||||
expect(logger.log).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
126
src/tests/v1/autonomous-turn-stop-integration.test.ts
Normal file
126
src/tests/v1/autonomous-turn-stop-integration.test.ts
Normal file
@@ -0,0 +1,126 @@
|
||||
import { mkdir, mkdtemp, realpath } from "node:fs/promises";
|
||||
import type { Server } from "node:http";
|
||||
import { tmpdir } from "node:os";
|
||||
import * as path from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { AcpClient } from "../../acp-client.js";
|
||||
import { ClaudeAcpAgent } from "../../v1/acp-agent.js";
|
||||
import { cleanUp, isolateFromMachine, scriptedModel } from "../scripted-model.js";
|
||||
|
||||
type Update = { sessionId: string; update: Record<string, any> };
|
||||
|
||||
/**
|
||||
* Stopping the "Claude is working" row of an autonomous turn (one that a
|
||||
* background task's notification started) while the user's next prompt waits
|
||||
* behind it. The adapter must interrupt the turn and Claude Code must then run
|
||||
* the waiting prompt.
|
||||
*
|
||||
* Only the model is scripted: the real adapter runs the bundled Claude Code CLI
|
||||
* against a server on 127.0.0.1, in an empty home directory.
|
||||
*/
|
||||
describe.skipIf(!process.env.RUN_INTEGRATION_TESTS)(
|
||||
"stopping an autonomous turn with a queued prompt",
|
||||
() => {
|
||||
let home: string;
|
||||
let model: Server;
|
||||
let scripted: ReturnType<typeof scriptedModel>;
|
||||
let agent: ClaudeAcpAgent | undefined;
|
||||
|
||||
beforeEach(async () => {
|
||||
home = await realpath(await mkdtemp(path.join(tmpdir(), "acp-autonomous-stop-")));
|
||||
await mkdir(path.join(home, "workspace"));
|
||||
scripted = scriptedModel();
|
||||
model = scripted.server;
|
||||
await new Promise<void>((resolve) => model.listen(0, "127.0.0.1", resolve));
|
||||
isolateFromMachine(home, model);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await agent?.dispose();
|
||||
agent = undefined;
|
||||
await cleanUp(home, model);
|
||||
});
|
||||
|
||||
it("interrupts the turn and answers the queued prompt", async () => {
|
||||
const updates: Update[] = [];
|
||||
const client = {
|
||||
sessionUpdate: async (notification: Update) => {
|
||||
updates.push(notification);
|
||||
},
|
||||
requestPermission: async () => ({ outcome: { outcome: "cancelled" } }),
|
||||
readTextFile: async () => ({ content: "" }),
|
||||
writeTextFile: async () => ({}),
|
||||
} as unknown as AcpClient;
|
||||
agent = new ClaudeAcpAgent(client, { log: () => {}, error: () => {} });
|
||||
await agent.initialize({
|
||||
protocolVersion: 1,
|
||||
clientCapabilities: {
|
||||
_meta: { jetbrains: { air: { version: 1, capabilities: ["asyncTasks"] } } },
|
||||
},
|
||||
} as any);
|
||||
const { sessionId } = await agent.newSession({
|
||||
cwd: path.join(home, "workspace"),
|
||||
mcpServers: [],
|
||||
});
|
||||
// The background Bash runs without a permission prompt; the home is a throwaway.
|
||||
await agent.setSessionMode({ sessionId, modeId: "bypassPermissions" });
|
||||
|
||||
const asyncTaskUpdates = () =>
|
||||
updates.map((n) => n.update).filter((u) => u.sessionUpdate.startsWith("async_task_"));
|
||||
const spawnedTurns = () =>
|
||||
asyncTaskUpdates().filter(
|
||||
(u) => u.sessionUpdate === "async_task_spawned" && u.taskType === "turn",
|
||||
);
|
||||
|
||||
const first = await agent.prompt({
|
||||
sessionId,
|
||||
prompt: [{ type: "text", text: "PROMPT_ONE" }],
|
||||
});
|
||||
expect(first.stopReason).toBe("end_turn");
|
||||
|
||||
// The background command ends and Claude Code starts an autonomous turn,
|
||||
// whose model response the server holds mid-stream.
|
||||
await scripted.autonomousHeld;
|
||||
await vi.waitFor(() => expect(spawnedTurns()).toHaveLength(1), { timeout: 30_000 });
|
||||
const asyncTaskId = spawnedTurns()[0].asyncTaskId as string;
|
||||
|
||||
const queued = agent.prompt({
|
||||
sessionId,
|
||||
prompt: [{ type: "text", text: "QUEUED_PROMPT" }],
|
||||
});
|
||||
// Settle the case on any outcome, so a failing assertion below leaves no unhandled rejection.
|
||||
const queuedOutcome = queued.then(
|
||||
(value) => ({ value }),
|
||||
(error) => ({ error }),
|
||||
);
|
||||
// Time for the prompt to reach the turn queue; nothing signals that it did.
|
||||
await new Promise((resolve) => setTimeout(resolve, 1_000));
|
||||
|
||||
await expect(agent.stopAsyncTask({ sessionId, asyncTaskId })).resolves.toEqual({
|
||||
stopped: true,
|
||||
});
|
||||
|
||||
const outcome = await Promise.race([
|
||||
queuedOutcome,
|
||||
new Promise<never>((_, reject) =>
|
||||
setTimeout(() => reject(new Error("queued prompt did not settle")), 60_000),
|
||||
),
|
||||
]);
|
||||
expect(outcome).toHaveProperty("value");
|
||||
expect((outcome as { value: { stopReason: string } }).value.stopReason).toBe("end_turn");
|
||||
const agentText = updates
|
||||
.map((n) => n.update)
|
||||
.filter((u) => u.sessionUpdate === "agent_message_chunk" && u.content?.type === "text")
|
||||
.map((u) => u.content.text as string)
|
||||
.join("");
|
||||
expect(agentText).toContain("answer-2");
|
||||
|
||||
expect(
|
||||
asyncTaskUpdates().filter(
|
||||
(u) => u.sessionUpdate === "async_task_state_update" && u.asyncTaskId === asyncTaskId,
|
||||
),
|
||||
).toMatchObject([{ state: "stopped" }]);
|
||||
expect(spawnedTurns()).toHaveLength(1);
|
||||
}, 120_000);
|
||||
},
|
||||
);
|
||||
@@ -173,6 +173,9 @@ import {
|
||||
parseAsyncTaskStopRequest,
|
||||
type AsyncTaskStopRequest,
|
||||
type AsyncTaskStopResponse,
|
||||
interruptAutonomousTurn,
|
||||
interruptKeepsWaitingPrompts,
|
||||
waitingPrompts,
|
||||
} from "./async-task-stop.js";
|
||||
import {
|
||||
STEER_METHOD,
|
||||
@@ -489,7 +492,7 @@ import {
|
||||
import type { NewSessionMeta, SDKMessageFilter } from "../new-session-meta.js";
|
||||
import { computeSessionFingerprint } from "./session-fingerprint.js";
|
||||
import { promptToClaude, SUPPORTED_PROMPT_CONTENT_TYPES } from "../prompt-to-claude.js";
|
||||
import { AUTONOMOUS_RESULT_ORIGINS, isAbortedResult } from "../result-end.js";
|
||||
import { isAbortedResult } from "../result-end.js";
|
||||
import {
|
||||
messageIdForGrouping,
|
||||
stampParentToolUseId,
|
||||
@@ -3470,13 +3473,16 @@ export class ClaudeAcpAgent {
|
||||
try {
|
||||
if (asyncTasks.isAutonomousTurn(params.asyncTaskId)) {
|
||||
// The task stands for a turn that Claude Code started on its own, so
|
||||
// stopping it interrupts that turn. A prompt that waits for its turn
|
||||
// would be folded into it, and the interrupt would drop that prompt.
|
||||
if ((session.turnQueue ?? []).some((turn) => !turn.settled)) {
|
||||
// stopping it interrupts that turn. A waiting prompt that is still in
|
||||
// Claude Code's queue survives the interrupt and runs next. One that
|
||||
// Claude Code already dispatched into a turn, or any prompt on a CLI
|
||||
// that sends no lifecycle frames, may be part of the interrupted turn.
|
||||
const waiting = waitingPrompts(session.turnQueue);
|
||||
if (!interruptKeepsWaitingPrompts(session, waiting)) {
|
||||
asyncTasks.releaseStop(params.asyncTaskId);
|
||||
return { stopped: false };
|
||||
}
|
||||
await session.query.interrupt();
|
||||
await interruptAutonomousTurn(session.query, asyncTasks, waiting, this.logger);
|
||||
} else {
|
||||
await session.query.stopTask(params.asyncTaskId);
|
||||
}
|
||||
@@ -6034,9 +6040,11 @@ export class ClaudeAcpAgent {
|
||||
// slash-command output forwarding), though their cost is real.
|
||||
// The exception: the user's prompt was added to that turn while it
|
||||
// ran, so its result answers the prompt (see answersPendingPrompt).
|
||||
const startedByClaudeCode =
|
||||
message.origin != null && AUTONOMOUS_RESULT_ORIGINS.has(message.origin.kind);
|
||||
const isAutonomousResult = startedByClaudeCode && !answersPendingPrompt(message);
|
||||
// A stop that interrupted an autonomous turn owes that turn's
|
||||
// aborted result, which has no origin after a scheduler fire.
|
||||
const answersPrompt = answersPendingPrompt(message);
|
||||
const startedByClaudeCode = asyncTasks.startedByClaudeCode(message, answersPrompt);
|
||||
const isAutonomousResult = startedByClaudeCode && !answersPrompt;
|
||||
// A result with no turn to claim it also ends the cycle that
|
||||
// Claude Code started on its own, whatever its origin says. A
|
||||
// scheduler fire (a ScheduleWakeup or cron prompt) is one: its
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { RequestError } from "@agentclientprotocol/sdk/unstable";
|
||||
import type { AsyncTaskRuntime } from "../async-tasks.js";
|
||||
|
||||
/** Stops one Claude background task without cancelling the parent prompt turn. */
|
||||
export const ASYNC_TASK_STOP_METHOD = "_session/async_task/stop";
|
||||
@@ -33,3 +34,63 @@ export function parseAsyncTaskStopRequest(value: unknown): AsyncTaskStopRequest
|
||||
}
|
||||
return { sessionId, asyncTaskId };
|
||||
}
|
||||
|
||||
/** The part of a queued prompt turn that the stop of an autonomous turn reads. */
|
||||
export type WaitingPrompt = { promptUuid: string; settled?: boolean; commandStarted?: boolean };
|
||||
|
||||
/** The prompts in `turnQueue` that still await their turn. */
|
||||
export function waitingPrompts<T extends WaitingPrompt>(turnQueue: readonly T[] | undefined): T[] {
|
||||
return (turnQueue ?? []).filter((turn) => !turn.settled);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an interrupt of the running autonomous turn leaves `waiting` to run
|
||||
* next. A prompt still in Claude Code's queue survives it and is listed in the
|
||||
* receipt's `still_queued`. A prompt that a `started` lifecycle frame says the
|
||||
* CLI already dispatched into a turn may be part of the interrupted turn, and
|
||||
* without lifecycle frames the adapter cannot tell which case a prompt is in.
|
||||
*/
|
||||
export function interruptKeepsWaitingPrompts(
|
||||
session: { msgLifecycleV1?: boolean },
|
||||
waiting: readonly WaitingPrompt[],
|
||||
): boolean {
|
||||
return (
|
||||
waiting.length === 0 ||
|
||||
(session.msgLifecycleV1 === true && waiting.every((turn) => !turn.commandStarted))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Interrupts the running autonomous turn for a stop. The turn's aborted result
|
||||
* is owed to the stop from before the interrupt, so a failed interrupt rolls
|
||||
* the debt back.
|
||||
*/
|
||||
export async function interruptAutonomousTurn(
|
||||
query: { interrupt(): Promise<{ still_queued?: readonly string[] } | undefined> },
|
||||
asyncTasks: Pick<
|
||||
AsyncTaskRuntime,
|
||||
"autonomousTurnInterrupting" | "autonomousTurnInterruptFailed"
|
||||
>,
|
||||
waiting: readonly WaitingPrompt[],
|
||||
logger: { log(message: string): void },
|
||||
): Promise<void> {
|
||||
asyncTasks.autonomousTurnInterrupting();
|
||||
let receipt;
|
||||
try {
|
||||
receipt = await query.interrupt();
|
||||
} catch (error) {
|
||||
asyncTasks.autonomousTurnInterruptFailed();
|
||||
throw error;
|
||||
}
|
||||
if (Array.isArray(receipt?.still_queued)) {
|
||||
const stillQueued = new Set(receipt.still_queued);
|
||||
for (const turn of waiting) {
|
||||
if (stillQueued.has(turn.promptUuid)) continue;
|
||||
// Not an error: the prompt may also be one the CLI has not read
|
||||
// into its queue yet, and it then runs next as usual.
|
||||
logger.log(
|
||||
`Prompt ${turn.promptUuid} is not in the interrupt receipt's still_queued: Claude Code may have taken it into the interrupted turn, which then ends with the interrupted result.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user