Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

fix: preserve ACP quiescence and Chat reasoning lineage (#1612)

Konstantin Dunasa9b5d88b50db
diff --git a/packages/ai/.changes/codex-chat-reasoning-details-replay.md b/packages/ai/.changes/codex-chat-reasoning-details-replay.md
new file mode 100644
index 0000000000..cdbd3e1239
--- /dev/null
+++ b/packages/ai/.changes/codex-chat-reasoning-details-replay.md
@@ -0,0 +1 @@
+- Fixed OpenAI-compatible Chat Completions replay dropping opaque `reasoning_details` between turns.
diff --git a/packages/ai/src/providers/openai-completions.ts b/packages/ai/src/providers/openai-completions.ts
index 647009d59e..00f945f17b 100644
--- a/packages/ai/src/providers/openai-completions.ts
+++ b/packages/ai/src/providers/openai-completions.ts
@@ -75,6 +75,31 @@ function isImageContentBlock(block: { type: string }): block is ImageContent {
return block.type === "image";
}
+const REASONING_DETAILS_SIGNATURE_TYPE = "openai-completions.reasoning_details.v1";
+
+interface ReasoningDetailsSignature {
+ type: typeof REASONING_DETAILS_SIGNATURE_TYPE;
+ details: Record<string, unknown>[];
+}
+
+function encodeReasoningDetails(details: Record<string, unknown>[]): string {
+ return JSON.stringify({ type: REASONING_DETAILS_SIGNATURE_TYPE, details } satisfies ReasoningDetailsSignature);
+}
+
+function decodeReasoningDetails(signature?: string): Record<string, unknown>[] | undefined {
+ if (!signature?.startsWith("{")) return undefined;
+ try {
+ const parsed = JSON.parse(signature) as Partial<ReasoningDetailsSignature>;
+ if (parsed.type !== REASONING_DETAILS_SIGNATURE_TYPE || !Array.isArray(parsed.details)) return undefined;
+ if (parsed.details.some((detail) => !detail || typeof detail !== "object" || Array.isArray(detail))) {
+ return undefined;
+ }
+ return parsed.details as Record<string, unknown>[];
+ } catch {
+ return undefined;
+ }
+}
+
export interface OpenAICompletionsOptions extends StreamOptions {
toolChoice?: "auto" | "none" | "required" | { type: "function"; function: { name: string } };
reasoningEffort?: "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
@@ -175,6 +200,9 @@ export const streamOpenAICompletions: StreamFunction<"openai-completions", OpenA
let thinkingBlock: ThinkingContent | null = null;
const toolCallBlocksByIndex = new Map<number, StreamingToolCallBlock>();
const toolCallBlocksById = new Map<string, StreamingToolCallBlock>();
+ const reasoningDetailsByIndex = new Map<number, Record<string, unknown>>();
+ let nextReasoningDetailsIndex = 0;
+ let reasoningDetailsBlock: ThinkingContent | null = null;
const blocks = output.content as StreamingBlock[];
const getContentIndex = (block: StreamingBlock) => blocks.indexOf(block);
const finishBlock = (block: StreamingBlock) => {
@@ -372,15 +400,50 @@ export const streamOpenAICompletions: StreamFunction<"openai-completions", OpenA
const reasoningDetails = (choice.delta as any).reasoning_details;
if (reasoningDetails && Array.isArray(reasoningDetails)) {
for (const detail of reasoningDetails) {
- if (detail.type === "reasoning.encrypted" && detail.id && detail.data) {
+ if (!detail || typeof detail !== "object" || Array.isArray(detail)) continue;
+ const detailRecord = detail as Record<string, unknown>;
+ const explicitIndex = typeof detailRecord.index === "number" ? detailRecord.index : undefined;
+ const index = explicitIndex ?? nextReasoningDetailsIndex;
+ nextReasoningDetailsIndex = Math.max(nextReasoningDetailsIndex, index + 1);
+ const previousDetail = reasoningDetailsByIndex.get(index);
+ const mergedDetail = { ...previousDetail, ...detailRecord };
+ for (const field of ["text", "summary"] as const) {
+ const previousFragment = previousDetail?.[field];
+ const fragment = detailRecord[field];
+ if (typeof previousFragment === "string" && typeof fragment === "string") {
+ mergedDetail[field] = previousFragment + fragment;
+ }
+ }
+ reasoningDetailsByIndex.set(index, mergedDetail);
+ if (
+ detailRecord.type === "reasoning.encrypted" &&
+ typeof detailRecord.id === "string" &&
+ detailRecord.data
+ ) {
const matchingToolCall = output.content.find(
- (b) => b.type === "toolCall" && b.id === detail.id,
+ (b) => b.type === "toolCall" && b.id === detailRecord.id,
) as ToolCall | undefined;
if (matchingToolCall) {
- matchingToolCall.thoughtSignature = JSON.stringify(detail);
+ matchingToolCall.thoughtSignature = JSON.stringify(detailRecord);
}
}
}
+ if (reasoningDetailsByIndex.size > 0) {
+ if (!reasoningDetailsBlock) {
+ reasoningDetailsBlock = { type: "thinking", thinking: "", redacted: true };
+ blocks.push(reasoningDetailsBlock);
+ stream.push({
+ type: "thinking_start",
+ contentIndex: getContentIndex(reasoningDetailsBlock),
+ partial: output,
+ });
+ }
+ reasoningDetailsBlock.thinkingSignature = encodeReasoningDetails(
+ [...reasoningDetailsByIndex.entries()]
+ .sort(([left], [right]) => left - right)
+ .map(([, detail]) => detail),
+ );
+ }
}
}
}
@@ -826,8 +889,16 @@ export function convertMessages(
);
const assistantText = assistantTextParts.map((part) => part.text).join("");
+ const replayReasoningDetails = msg.content
+ .filter(isThinkingContentBlock)
+ .flatMap((block) => decodeReasoningDetails(block.thinkingSignature) ?? []);
+ if (replayReasoningDetails.length > 0) {
+ (assistantMsg as any).reasoning_details = replayReasoningDetails;
+ }
+
const nonEmptyThinkingBlocks = msg.content
.filter(isThinkingContentBlock)
+ .filter((block) => decodeReasoningDetails(block.thinkingSignature) === undefined)
.filter((block) => block.thinking.trim().length > 0);
if (nonEmptyThinkingBlocks.length > 0) {
if (compat.requiresThinkingAsText) {
@@ -894,7 +965,7 @@ export function convertMessages(
}
})
.filter(Boolean);
- if (reasoningDetails.length > 0) {
+ if (reasoningDetails.length > 0 && replayReasoningDetails.length === 0) {
(assistantMsg as any).reasoning_details = reasoningDetails;
}
}
@@ -905,6 +976,9 @@ export function convertMessages(
) {
(assistantMsg as { reasoning_content?: string }).reasoning_content = "";
}
+ if (replayReasoningDetails.length > 0 && assistantMsg.content === null && !assistantMsg.tool_calls) {
+ assistantMsg.content = "";
+ }
// Skip assistant messages that have no content and no tool calls.
// Some providers require "either content or tool_calls, but not none".
// Other providers also don't accept empty assistant messages.
@@ -914,7 +988,7 @@ export function convertMessages(
content !== null &&
content !== undefined &&
(typeof content === "string" ? content.length > 0 : content.length > 0);
- if (!hasContent && !assistantMsg.tool_calls) {
+ if (!hasContent && !assistantMsg.tool_calls && replayReasoningDetails.length === 0) {
continue;
}
params.push(assistantMsg);
diff --git a/packages/ai/test/openai-completions-tool-choice.test.ts b/packages/ai/test/openai-completions-tool-choice.test.ts
index bc6befd35e..64dd360b75 100644
--- a/packages/ai/test/openai-completions-tool-choice.test.ts
+++ b/packages/ai/test/openai-completions-tool-choice.test.ts
@@ -760,6 +760,179 @@ describe("openai-completions tool_choice", () => {
expect(writeCall).not.toHaveProperty("partialArgs");
});
+ it("round-trips opaque reasoning_details without a matching tool call id", async () => {
+ const details = [
+ {
+ type: "reasoning.summary",
+ index: 0,
+ format: "unknown",
+ summary: "brief plan",
+ },
+ {
+ type: "reasoning.encrypted",
+ index: 1,
+ format: "unknown",
+ id: "rs_not_a_tool_call",
+ data: "opaque-continuation",
+ },
+ ];
+ mockState.chunks = [
+ {
+ id: "chatcmpl-reasoning-details",
+ choices: [{ delta: { reasoning_details: details }, finish_reason: "stop" }],
+ },
+ ];
+
+ const { compat: _compat, ...baseModel } = getModel("openai", "gpt-4o-mini")!;
+ const model = { ...baseModel, api: "openai-completions" } as const;
+ const first = await streamSimple(
+ model,
+ {
+ messages: [{ role: "user", content: "Think privately.", timestamp: 1 }],
+ },
+ { apiKey: "test" },
+ ).result();
+ const opaque = first.content.find((block) => block.type === "thinking" && block.redacted);
+ expect(opaque).toBeDefined();
+
+ mockState.chunks = [
+ {
+ id: "chatcmpl-after-replay",
+ choices: [{ delta: { content: "done" }, finish_reason: "stop" }],
+ },
+ ];
+ await streamSimple(
+ model,
+ {
+ messages: [
+ { role: "user", content: "Think privately.", timestamp: 1 },
+ first,
+ { role: "user", content: "Continue.", timestamp: 2 },
+ ],
+ },
+ { apiKey: "test" },
+ ).result();
+
+ const params = mockState.lastParams as { messages: Array<Record<string, unknown>> };
+ expect(params.messages[1]?.reasoning_details).toEqual(details);
+ expect(params.messages[1]?.content).toBe("");
+ });
+
+ it("keeps index-less reasoning details after explicitly indexed details", async () => {
+ const explicitDetail = {
+ type: "reasoning.summary",
+ index: 0,
+ format: "unknown",
+ summary: "brief plan",
+ };
+ const indexlessDetail = {
+ type: "reasoning.encrypted",
+ format: "unknown",
+ id: "rs_indexless",
+ data: "opaque-continuation",
+ };
+ mockState.chunks = [
+ {
+ id: "chatcmpl-reasoning-index-order",
+ choices: [{ delta: { reasoning_details: [explicitDetail, indexlessDetail] }, finish_reason: "stop" }],
+ },
+ ];
+
+ const { compat: _compat, ...baseModel } = getModel("openai", "gpt-4o-mini")!;
+ const model = { ...baseModel, api: "openai-completions" } as const;
+ const first = await streamSimple(
+ model,
+ { messages: [{ role: "user", content: "Think privately.", timestamp: 1 }] },
+ { apiKey: "test" },
+ ).result();
+
+ mockState.chunks = [
+ {
+ id: "chatcmpl-after-index-replay",
+ choices: [{ delta: { content: "done" }, finish_reason: "stop" }],
+ },
+ ];
+ await streamSimple(
+ model,
+ {
+ messages: [
+ { role: "user", content: "Think privately.", timestamp: 1 },
+ first,
+ { role: "user", content: "Continue.", timestamp: 2 },
+ ],
+ },
+ { apiKey: "test" },
+ ).result();
+
+ const params = mockState.lastParams as { messages: Array<Record<string, unknown>> };
+ expect(params.messages[1]?.reasoning_details).toEqual([explicitDetail, indexlessDetail]);
+ });
+
+ it("concatenates same-index reasoning detail fragments", async () => {
+ mockState.chunks = [
+ {
+ id: "chatcmpl-reasoning-fragments",
+ choices: [
+ {
+ delta: {
+ reasoning_details: [
+ { type: "reasoning.text", index: 0, format: "unknown", text: "first " },
+ { type: "reasoning.summary", index: 1, format: "unknown", summary: "brief " },
+ ],
+ },
+ finish_reason: null,
+ },
+ ],
+ },
+ {
+ id: "chatcmpl-reasoning-fragments",
+ choices: [
+ {
+ delta: {
+ reasoning_details: [
+ { type: "reasoning.text", index: 0, text: "second" },
+ { type: "reasoning.summary", index: 1, summary: "plan" },
+ ],
+ },
+ finish_reason: "stop",
+ },
+ ],
+ },
+ ];
+
+ const { compat: _compat, ...baseModel } = getModel("openai", "gpt-4o-mini")!;
+ const model = { ...baseModel, api: "openai-completions" } as const;
+ const first = await streamSimple(
+ model,
+ { messages: [{ role: "user", content: "Think privately.", timestamp: 1 }] },
+ { apiKey: "test" },
+ ).result();
+
+ mockState.chunks = [
+ {
+ id: "chatcmpl-after-fragment-replay",
+ choices: [{ delta: { content: "done" }, finish_reason: "stop" }],
+ },
+ ];
+ await streamSimple(
+ model,
+ {
+ messages: [
+ { role: "user", content: "Think privately.", timestamp: 1 },
+ first,
+ { role: "user", content: "Continue.", timestamp: 2 },
+ ],
+ },
+ { apiKey: "test" },
+ ).result();
+
+ const params = mockState.lastParams as { messages: Array<Record<string, unknown>> };
+ expect(params.messages[1]?.reasoning_details).toEqual([
+ { type: "reasoning.text", index: 0, format: "unknown", text: "first second" },
+ { type: "reasoning.summary", index: 1, format: "unknown", summary: "brief plan" },
+ ]);
+ });
+
it("does not double-count reasoning tokens in completion usage", async () => {
mockState.chunks = [
{
diff --git a/packages/coding-agent/.changes/codex-acp-await-terminal-quiescence.md b/packages/coding-agent/.changes/codex-acp-await-terminal-quiescence.md
new file mode 100644
index 0000000000..9b8201f540
--- /dev/null
+++ b/packages/coding-agent/.changes/codex-acp-await-terminal-quiescence.md
@@ -0,0 +1 @@
+- Changed ACP prompt requests to resolve only after all causally admitted subagent and parent work has settled.
diff --git a/packages/coding-agent/src/modes/acp/acp-mode.ts b/packages/coding-agent/src/modes/acp/acp-mode.ts
index 59ae63abeb..db1087f76c 100644
--- a/packages/coding-agent/src/modes/acp/acp-mode.ts
+++ b/packages/coding-agent/src/modes/acp/acp-mode.ts
@@ -105,6 +105,8 @@ interface AcpPendingTerminal {
boundary: TurnBoundary;
outcome: "result" | "error";
abort: AbortController;
+ status?: AgentAutonomousStatus;
+ turnFailure?: string;
failure?: string;
task?: Promise<void>;
}
@@ -641,6 +643,8 @@ export async function runAcpModeWithConnection(
if (pending.abort.signal.aborted || session !== entry || entry.pendingTerminal !== pending) return;
const terminalQuiescence = quiescenceMeta(status, liveChildren);
if (terminalQuiescence.outstandingSubagents !== 0) continue;
+ pending.status = status;
+ pending.turnFailure = finalFailure;
entry.producer.sealTerminal(pending.promptTurnId);
const autonomous = autonomousMeta(status);
@@ -653,11 +657,9 @@ export async function runAcpModeWithConnection(
"terminalQuiescence",
finalFailure ? "error" : pending.outcome,
);
- // publish() admits the terminal update synchronously before its first await.
- // Release the next prompt only after that ordering cut, not after the client
- // has already observed the notification.
- if (entry.pendingTerminal === pending) entry.pendingTerminal = undefined;
- if (entry.abort === pending.abort) entry.abort = undefined;
+ // Keep terminal ownership until this settlement task has fully drained.
+ // A follow-up prompt awaits that task; clearing ownership at publication
+ // admission would let it overlap the first prompt handler.
if (!(await publication)) return;
await entry.producer.drain();
return;
@@ -669,7 +671,6 @@ export async function runAcpModeWithConnection(
})
.finally(() => {
entry.producer.finishTerminalLifecycle(pending.promptTurnId);
- if (!pending.abort.signal.aborted) return;
if (entry.pendingTerminal === pending) entry.pendingTerminal = undefined;
if (entry.abort === pending.abort) entry.abort = undefined;
});
@@ -869,6 +870,7 @@ export async function runAcpModeWithConnection(
// delivered. This prevents late producer events becoming the next turn.
const promptTurnId = entry.producer.beginPrompt();
let responseBoundaryEmitted = false;
+ let terminalSettlementCancelled = false;
try {
const { text, images } = promptContent(params.prompt);
const priorMessages = turnBoundary(await connection.getMessages());
@@ -907,6 +909,7 @@ export async function runAcpModeWithConnection(
return { stopReason: "cancelled" satisfies AcpStopReason };
}
const outcome = failure ? "error" : "result";
+ let terminalStatus = status;
const observedQuiescence = quiescenceMeta(status, liveChildren);
// The roster is telemetry at the response cut, not proof of terminality:
// a child can publish a terminal status before its result reaches the parent.
@@ -937,12 +940,21 @@ export async function runAcpModeWithConnection(
const pending: AcpPendingTerminal = { promptTurnId, boundary: priorMessages, outcome, abort };
entry.pendingTerminal = pending;
finalizePendingTerminal(entry, pending);
+ await pending.task;
+ terminalSettlementCancelled = abort.signal.aborted;
+ if (pending.failure) {
+ throw new Error(`ACP lifecycle reconciliation failed: ${pending.failure}`);
+ }
+ if (pending.turnFailure) {
+ throw new Error(`prime-agent turn failed: ${pending.turnFailure}`);
+ }
+ terminalStatus = pending.status ?? status;
}
if (failure) throw new Error(`prime-agent turn failed: ${failure}`);
return {
stopReason: acpStopReason({
- cancelled: abort.signal.aborted && !entry.producer.isResponseCommitted(promptTurnId),
- autonomous: status,
+ cancelled: terminalSettlementCancelled,
+ autonomous: terminalStatus,
}),
};
} catch (error) {
diff --git a/packages/coding-agent/test/suite/acp-mode.test.ts b/packages/coding-agent/test/suite/acp-mode.test.ts
index aa43cfda19..7f386305b7 100644
--- a/packages/coding-agent/test/suite/acp-mode.test.ts
+++ b/packages/coding-agent/test/suite/acp-mode.test.ts
@@ -37,9 +37,9 @@ function injectWorkAfterHeadlessCompletion(
): () => boolean {
const waitForHeadlessCompletion = connection.waitForHeadlessCompletion.bind(connection);
let injected = false;
- connection.waitForHeadlessCompletion = async () => {
- const status = await waitForHeadlessCompletion();
- if (!injected) {
+ connection.waitForHeadlessCompletion = async (options) => {
+ const status = await waitForHeadlessCompletion(options);
+ if (!options?.waitForRlmQuiescence && !injected) {
injected = true;
void session.prompt(text);
const deadline = Date.now() + 5_000;
@@ -249,12 +249,17 @@ describe("ACP mode end to end", () => {
await client.request("initialize", { protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });
const session = await client.request("session/new", { cwd: harness.tempDir, mcpServers: [] });
- const first = await client.request("session/prompt", {
- sessionId: session.sessionId,
- prompt: [{ type: "text", text: "First turn" }],
- });
- expect(first.stopReason).toBe("end_turn");
- expect(injected()).toBe(true);
+ let firstSettled = false;
+ const first = client
+ .request("session/prompt", {
+ sessionId: session.sessionId,
+ prompt: [{ type: "text", text: "First turn" }],
+ })
+ .finally(() => {
+ firstSettled = true;
+ });
+ await vi.waitFor(() => expect(injected()).toBe(true));
+ expect(firstSettled).toBe(false);
expect(harness.session.isStreaming).toBe(true);
let secondSettled = false;
@@ -269,6 +274,7 @@ describe("ACP mode end to end", () => {
await new Promise((resolve) => setTimeout(resolve, 50));
expect(secondSettled).toBe(false);
releaseInjected();
+ await expect(first).resolves.toMatchObject({ stopReason: "end_turn" });
await expect(second).resolves.toMatchObject({ stopReason: "end_turn" });
const text = updates
@@ -279,7 +285,7 @@ describe("ACP mode end to end", () => {
harness.cleanup();
}, 5_000);
- it("reports the queued turn's stop reason from a fresh autonomous status", async () => {
+ it("reports the prompt stop reason from its terminal autonomous status", async () => {
const harness = await createHarness({
autonomous: {
enabled: true,
@@ -293,38 +299,27 @@ describe("ACP mode end to end", () => {
const injectedHeld = new Promise<AssistantMessage>((resolve) => {
releaseInjected = () => resolve(fauxAssistantMessage("injected work done"));
});
- harness.setResponses([
- fauxAssistantMessage("turn one done"),
- () => injectedHeld,
- fauxAssistantMessage("turn two done"),
- ]);
+ harness.setResponses([fauxAssistantMessage("turn one done"), () => injectedHeld]);
const connection = new InProcessAgentConnection(runtimeHostFor(harness.session));
- injectWorkAfterHeadlessCompletion(connection, harness.session, "injected work");
+ const injected = injectWorkAfterHeadlessCompletion(connection, harness.session, "injected work");
const { client } = connectAcpClient(connection);
await client.request("initialize", { protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });
const session = await client.request("session/new", { cwd: harness.tempDir, mcpServers: [] });
- const first = await client.request("session/prompt", {
+ const prompt = client.request("session/prompt", {
sessionId: session.sessionId,
prompt: [{ type: "text", text: "First turn" }],
});
- expect(first.stopReason).toBe("end_turn");
- expect(harness.session.getAutonomousStatus().turnsUsed).toBe(1);
-
- const second = client.request("session/prompt", {
- sessionId: session.sessionId,
- prompt: [{ type: "text", text: "Second turn" }],
- });
- await new Promise((resolve) => setTimeout(resolve, 50));
+ await vi.waitFor(() => expect(injected()).toBe(true));
releaseInjected();
- await expect(second).resolves.toMatchObject({ stopReason: "max_turn_requests" });
+ await expect(prompt).resolves.toMatchObject({ stopReason: "max_turn_requests" });
expect(harness.session.getAutonomousStatus().turnsUsed).toBeGreaterThanOrEqual(
harness.session.getAutonomousStatus().limits.maxTurns,
);
harness.cleanup();
}, 5_000);
- it("does not hold the prompt response open for detached work", async () => {
+ it("holds the prompt response open for causally admitted work", async () => {
const harness = await createHarness();
let releaseInjected!: () => void;
const injectedHeld = new Promise<AssistantMessage>((resolve) => {
@@ -352,7 +347,7 @@ describe("ACP mode end to end", () => {
}
expect(injected()).toBe(true);
await new Promise((resolve) => setTimeout(resolve, 100));
- expect(settled).toBe(true);
+ expect(settled).toBe(false);
expect(harness.session.isStreaming).toBe(true);
releaseInjected();
await expect(prompt).resolves.toMatchObject({ stopReason: "end_turn" });
@@ -375,10 +370,11 @@ describe("ACP mode end to end", () => {
const { client } = connectAcpClient(connection);
await client.request("initialize", { protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });
const session = await client.request("session/new", { cwd: harness.tempDir, mcpServers: [] });
- await client.request("session/prompt", {
+ const first = client.request("session/prompt", {
sessionId: session.sessionId,
prompt: [{ type: "text", text: "First turn" }],
});
+ await vi.waitFor(() => expect(harness.session.isStreaming).toBe(true));
const queued = client.request("session/prompt", {
sessionId: session.sessionId,
@@ -386,8 +382,9 @@ describe("ACP mode end to end", () => {
});
await new Promise((resolve) => setTimeout(resolve, 50));
void client.notify("session/cancel", { sessionId: session.sessionId });
- await expect(queued).resolves.toMatchObject({ stopReason: "cancelled" });
releaseInjected();
+ await expect(first).resolves.toBeDefined();
+ await expect(queued).resolves.toMatchObject({ stopReason: "cancelled" });
await new Promise((resolve) => setTimeout(resolve, 300));
const assistantText = harness.session.messages
.filter((message) => message.role === "assistant")
@@ -481,10 +478,12 @@ describe("ACP mode end to end", () => {
const { client, updates, close } = connectAcpClient(connection);
await client.request("initialize", { protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });
const session = await client.request("session/new", { cwd: process.cwd(), mcpServers: [] });
- await client.request("session/prompt", {
- sessionId: session.sessionId,
- prompt: [{ type: "text", text: "delegate" }],
- });
+ await expect(
+ client.request("session/prompt", {
+ sessionId: session.sessionId,
+ prompt: [{ type: "text", text: "delegate" }],
+ }),
+ ).rejects.toThrow();
await vi.waitFor(() =>
expect(
updates
@@ -518,10 +517,18 @@ describe("ACP mode end to end", () => {
const { client, updates, close } = connectAcpClient(connection);
await client.request("initialize", { protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });
const session = await client.request("session/new", { cwd: process.cwd(), mcpServers: [] });
- await client.request("session/prompt", {
- sessionId: session.sessionId,
- prompt: [{ type: "text", text: "delegate" }],
- });
+ let firstSettled = false;
+ const firstPrompt = client
+ .request("session/prompt", {
+ sessionId: session.sessionId,
+ prompt: [{ type: "text", text: "delegate" }],
+ })
+ .finally(() => {
+ firstSettled = true;
+ });
+ await vi.waitFor(() => expect(promptCalls).toBe(1));
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(firstSettled).toBe(false);
let metadata = updates.map((item) => item.update?._meta?.[PRIME_AGENT_META_NAMESPACE]).filter(Boolean);
expect(metadata.filter((item) => item.phase === "terminalQuiescence")).toHaveLength(0);
@@ -547,11 +554,58 @@ describe("ACP mode end to end", () => {
});
const sequences = metadata.map((item) => item.eventSequence);
expect(sequences).toEqual([...sequences].sort((left, right) => left - right));
+ await expect(firstPrompt).resolves.toBeDefined();
await nextPrompt;
expect(promptCalls).toBe(2);
close();
});
+ it("does not admit the next prompt while terminal settlement is still publishing", async () => {
+ let terminalPublicationStarted!: () => void;
+ let releaseTerminalPublication!: () => void;
+ const terminalPublicationStart = new Promise<void>((resolve) => {
+ terminalPublicationStarted = resolve;
+ });
+ const terminalPublicationRelease = new Promise<void>((resolve) => {
+ releaseTerminalPublication = resolve;
+ });
+ let promptCalls = 0;
+ let blockTerminalPublication = true;
+ const connection = fakeAcpConnection({
+ onPromptAndWait: () => {
+ promptCalls++;
+ },
+ });
+ const { client, close } = connectAcpClient(connection, {
+ beforeAcpUpdatePublish: async (update) => {
+ if (acpUpdatePhase(update) !== "terminalQuiescence" || !blockTerminalPublication) return;
+ blockTerminalPublication = false;
+ terminalPublicationStarted();
+ await terminalPublicationRelease;
+ },
+ });
+ await client.request("initialize", { protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });
+ const session = await client.request("session/new", { cwd: process.cwd(), mcpServers: [] });
+ const first = client.request("session/prompt", {
+ sessionId: session.sessionId,
+ prompt: [{ type: "text", text: "first" }],
+ });
+ await terminalPublicationStart;
+ const second = client.request("session/prompt", {
+ sessionId: session.sessionId,
+ prompt: [{ type: "text", text: "second" }],
+ });
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ const promptCallsBeforeSettlement = promptCalls;
+
+ releaseTerminalPublication();
+ await expect(first).resolves.toBeDefined();
+ await expect(second).resolves.toBeDefined();
+ expect(promptCallsBeforeSettlement).toBe(1);
+ expect(promptCalls).toBe(2);
+ close();
+ });
+
it("coalesces duplicate cancellation notifications under one stop owner", async () => {
let releaseAbort!: () => void;
const abortGate = new Promise<void>((resolve) => {
@@ -577,19 +631,25 @@ describe("ACP mode end to end", () => {
releaseBarrier();
},
});
- const { client, close } = connectAcpClient(connection);
+ const { client, updates, close } = connectAcpClient(connection);
await client.request("initialize", { protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });
const session = await client.request("session/new", { cwd: process.cwd(), mcpServers: [] });
- await client.request("session/prompt", {
+ const prompt = client.request("session/prompt", {
sessionId: session.sessionId,
prompt: [{ type: "text", text: "cancel twice" }],
});
+ await vi.waitFor(() =>
+ expect(
+ updates.some((item) => item.update?._meta?.[PRIME_AGENT_META_NAMESPACE]?.phase === "responseBoundary"),
+ ).toBe(true),
+ );
await client.notify("session/cancel", { sessionId: session.sessionId });
await abortStarted;
await client.notify("session/cancel", { sessionId: session.sessionId });
await Promise.resolve();
expect(abortCalls).toBe(1);
releaseAbort();
+ await expect(prompt).resolves.toBeDefined();
await vi.waitFor(async () => {
await expect(
client.request("session/prompt", {
@@ -630,12 +690,18 @@ describe("ACP mode end to end", () => {
const { client, updates, close } = connectAcpClient(connection);
await client.request("initialize", { protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });
const session = await client.request("session/new", { cwd: process.cwd(), mcpServers: [] });
- await client.request("session/prompt", {
+ const prompt = client.request("session/prompt", {
sessionId: session.sessionId,
prompt: [{ type: "text", text: "delegate" }],
});
+ await vi.waitFor(() =>
+ expect(
+ updates.some((item) => item.update?._meta?.[PRIME_AGENT_META_NAMESPACE]?.phase === "responseBoundary"),
+ ).toBe(true),
+ );
await client.notify("session/cancel", { sessionId: session.sessionId });
await aborted;
+ await expect(prompt).resolves.toBeDefined();
const firstTurnTerminal = updates
.map((item) => item.update?._meta?.[PRIME_AGENT_META_NAMESPACE])
@@ -652,6 +718,37 @@ describe("ACP mode end to end", () => {
close();
});
+ it("reports cancellation while terminal settlement is still pending", async () => {
+ let terminalSettlementStarted!: () => void;
+ let releaseTerminalSettlement!: () => void;
+ const terminalSettlementStart = new Promise<void>((resolve) => {
+ terminalSettlementStarted = resolve;
+ });
+ const terminalSettlementRelease = new Promise<void>((resolve) => {
+ releaseTerminalSettlement = resolve;
+ });
+ const connection = fakeAcpConnection({
+ onWaitForHeadlessCompletion: async (options) => {
+ if (!options?.waitForRlmQuiescence) return;
+ terminalSettlementStarted();
+ await terminalSettlementRelease;
+ },
+ onAbort: () => releaseTerminalSettlement(),
+ });
+ const { client, close } = connectAcpClient(connection);
+ await client.request("initialize", { protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });
+ const session = await client.request("session/new", { cwd: process.cwd(), mcpServers: [] });
+ const prompt = client.request("session/prompt", {
+ sessionId: session.sessionId,
+ prompt: [{ type: "text", text: "cancel during terminal settlement" }],
+ });
+
+ await terminalSettlementStart;
+ await client.notify("session/cancel", { sessionId: session.sessionId });
+ await expect(prompt).resolves.toMatchObject({ stopReason: "cancelled" });
+ close();
+ });
+
it("closes a pending child lifecycle without publishing a false terminal", async () => {
const child = { id: "child-close", label: "child", status: "running", sessionDir: "/tmp/child" };
let releaseBarrier!: () => void;
@@ -671,11 +768,18 @@ describe("ACP mode end to end", () => {
const { client, updates, close } = connectAcpClient(connection);
await client.request("initialize", { protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });
const session = await client.request("session/new", { cwd: process.cwd(), mcpServers: [] });
- await client.request("session/prompt", {
+ const prompt = client.request("session/prompt", {
sessionId: session.sessionId,
prompt: [{ type: "text", text: "delegate" }],
});
- await client.request("session/close", { sessionId: session.sessionId });
+ await vi.waitFor(() =>
+ expect(
+ updates.some((item) => item.update?._meta?.[PRIME_AGENT_META_NAMESPACE]?.phase === "responseBoundary"),
+ ).toBe(true),
+ );
+ const closing = client.request("session/close", { sessionId: session.sessionId });
+ await expect(prompt).resolves.toBeDefined();
+ await closing;
await Promise.resolve();
const terminal = updates