Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(claude): isolate cancelled continuation generations (#1941)

fmfsaisai995707d35d6d
diff --git a/packages/maker-core/src/agents/claude-code/__tests__/abort-stops-background-tasks.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/abort-stops-background-tasks.test.ts
index eccb129f8e..281bdbcc20 100644
--- a/packages/maker-core/src/agents/claude-code/__tests__/abort-stops-background-tasks.test.ts
+++ b/packages/maker-core/src/agents/claude-code/__tests__/abort-stops-background-tasks.test.ts
@@ -21,7 +21,7 @@ import path from 'node:path';
import { afterEach, describe, expect, it, vi } from 'vitest';
-import type { AgentDeps } from '../../base-agent.js';
+import type { AgentDeps, AgentSessionHandle } from '../../base-agent.js';
import type { AuthAdapter } from '../../../interfaces/auth-adapter.js';
import type { AgentEvent } from '../../../types/events.js';
import type { Logger } from '../../../interfaces/logger.js';
@@ -70,6 +70,7 @@ vi.mock('../../shared/async-queue.js', async (importOriginal) => {
});
import { ClaudeCodeAgent } from '../index.js';
+import { Session } from '../../../session.js';
const tempDirs: string[] = [];
const originalClaudeConfigDir = process.env.CLAUDE_CONFIG_DIR;
@@ -186,15 +187,29 @@ async function makeTempDir(): Promise<string> {
async function startSessionWithStream(
queryOpts?: { omitStopTask?: boolean },
- opts?: { autoCollect?: boolean },
+ opts?: { autoCollect?: boolean; vendorOptions?: Record<string, unknown> },
) {
const configDir = await makeTempDir();
process.env.CLAUDE_CONFIG_DIR = configDir;
const workingDir = await makeTempDir();
- const stream = createControlledStream();
- const fakeQuery = createFakeQuery(stream, queryOpts);
+ const streams: Array<ReturnType<typeof createControlledStream>> = [];
+ const fakeQueries: Array<ReturnType<typeof createFakeQuery>> = [];
+ const stream = {
+ emit(message: unknown): void {
+ const current = streams.at(-1);
+ if (!current) throw new Error('query stream is not ready');
+ current.emit(message);
+ },
+ end(): void {
+ for (const queryStream of streams) queryStream.end();
+ },
+ };
sdkMock.query.mockImplementation((options: unknown) => {
+ const queryStream = createControlledStream();
+ const fakeQuery = createFakeQuery(queryStream, queryOpts);
+ streams.push(queryStream);
+ fakeQueries.push(fakeQuery);
const prompt = (options as { prompt?: AsyncIterable<unknown> } | undefined)?.prompt;
if (prompt) {
void (async () => {
@@ -214,6 +229,7 @@ async function startSessionWithStream(
model: 'claude-opus-4-6',
workingDir,
permissionMode: 'acceptEdits',
+ vendorOptions: opts?.vendorOptions,
});
const events: AgentEvent[] = [];
@@ -225,10 +241,12 @@ async function startSessionWithStream(
}
})();
- return { agent, handle, stream, fakeQuery, events, collected };
+ const fakeQuery = fakeQueries[0];
+ if (!fakeQuery) throw new Error('initial fake query was not created');
+ return { agent, handle, stream, streams, fakeQuery, fakeQueries, events, collected };
}
-async function startRemoteSessionWithStream() {
+async function startRemoteSessionWithStream(opts?: { autoCollect?: boolean }) {
const configDir = await makeTempDir();
process.env.CLAUDE_CONFIG_DIR = configDir;
const workingDir = await makeTempDir();
@@ -249,9 +267,11 @@ async function startRemoteSessionWithStream() {
permissionMode: 'acceptEdits',
});
const events: AgentEvent[] = [];
- const collected = (async () => {
- for await (const event of handle.events()) events.push(event);
- })();
+ const collected = opts?.autoCollect === false
+ ? Promise.resolve()
+ : (async () => {
+ for await (const event of handle.events()) events.push(event);
+ })();
return { handle, stream, fakeQuery, events, collected };
}
@@ -304,6 +324,17 @@ function turnResult(result = 'ok'): Record<string, unknown> {
};
}
+function interruptedTurnResult(): Record<string, unknown> {
+ return {
+ type: 'result',
+ subtype: 'error_during_execution',
+ is_error: true,
+ stop_reason: null,
+ total_cost_usd: 0,
+ usage: { input_tokens: 1, output_tokens: 1 },
+ };
+}
+
function assistantText(text: string): Record<string, unknown> {
return {
type: 'assistant',
@@ -341,6 +372,40 @@ function taskEvents(events: AgentEvent[]): AgentEvent[] {
return events.filter((e) => e.type === 'agent_task_update');
}
+function isProductTerminal(event: AgentEvent): boolean {
+ return (
+ (event.type === 'done' && event.turnContinuationId === undefined) ||
+ (event.type === 'error' &&
+ (event.data as { isTerminal?: unknown } | null | undefined)?.isTerminal === true)
+ );
+}
+
+function createEventReader(handle: AgentSessionHandle) {
+ const iterator = handle.events()[Symbol.asyncIterator]();
+ const seen: AgentEvent[] = [];
+ const nextMatching = async (predicate: (event: AgentEvent) => boolean): Promise<AgentEvent> => {
+ for (;;) {
+ const result = await iterator.next();
+ if (result.done) throw new Error('event stream ended before the expected event');
+ seen.push(result.value);
+ if (predicate(result.value)) return result.value;
+ }
+ };
+ return { iterator, nextMatching, seen };
+}
+
+function wrapInSession(handle: AgentSessionHandle): Session {
+ return new Session({
+ id: 'session-continuation-cross-layer',
+ agentKind: 'claude-code',
+ workDir: path.join('workspace', 'repo'),
+ handle,
+ capabilities: {} as never,
+ logger: createNoopLogger(),
+ turnStallMs: 0,
+ });
+}
+
afterEach(async () => {
asyncQueueMock.rejectNextDone = false;
sdkMock.forkSession.mockReset();
@@ -543,90 +608,162 @@ describe('ClaudeCodeAgent abort stops background wake tasks', () => {
await handle.close().catch(() => undefined);
});
- it('stopTask 先取消 claim 后 interrupt 成功仍屏蔽迟到 continuation 尾巴', async () => {
+ it('interrupt ACK 前真实 continuation done 先到时不再追加 synthetic 终态', async () => {
const { handle, stream, events, fakeQuery } = await startSessionWithStream();
await handle.send({ type: 'user', content: 'spawn background work' });
stream.emit(taskStarted('task-agent', 'local_agent'));
await waitFor(() => taskEvents(events).length >= 1, 'wake task observed');
stream.emit(turnResult('waiting'));
- await waitFor(() => events.some((event) => event.type === 'done'), 'foreground done observed');
+ await waitFor(() => events.some((event) => event.type === 'done'), 'parent done observed');
const continuationId = events.find((event) => event.type === 'done')?.turnContinuationId;
expect(continuationId).toBeTypeOf('number');
+ const stopTask = createDeferred<void>();
const interrupt = createDeferred<void>();
+ fakeQuery.stopTask!.mockImplementationOnce(() => stopTask.promise);
fakeQuery.interrupt.mockImplementationOnce(() => interrupt.promise);
const abortPromise = handle.abort();
- await waitFor(() => fakeQuery.stopTask!.mock.calls.length === 1, 'stopTask dispatched');
- await waitFor(
- () =>
- events.some(
- (event) =>
- event.type === 'done' &&
- (event.data as { reason?: unknown } | null | undefined)?.reason ===
- 'turn_continuation_cancelled',
- ),
- 'stopTask cancelled claim before interrupt resolved',
- );
- expect(handle.beginTurnContinuationWait?.(continuationId)).toBeNull();
+ await waitFor(() => fakeQuery.interrupt.mock.calls.length === 1, 'interrupt dispatched');
+
+ stream.emit(assistantText('real continuation wins'));
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(handle.beginTurnContinuationWait?.(continuationId)).toBe('awaiting');
+ stream.emit(turnResult('real interrupted result'));
+ await waitFor(() => events.filter(isProductTerminal).length === 1, 'real product terminal observed');
+ stopTask.resolve(undefined);
interrupt.resolve(undefined);
await abortPromise;
- const eventCountAfterCancellation = events.length;
- stream.emit(taskStarted('task-late', 'local_agent'));
- stream.emit({
- type: 'assistant',
- message: { content: [{ type: 'text', text: 'late assistant output' }] },
- });
- stream.emit(turnResult('late interrupted result'));
- await new Promise((resolve) => setTimeout(resolve, 20));
+ await waitFor(() => handle.isTurnRunning?.() === false, 'real terminal acknowledged');
- expect(events).toHaveLength(eventCountAfterCancellation);
+ expect(events.filter(isProductTerminal)).toHaveLength(1);
+ expect(
+ events.filter(
+ (event) =>
+ event.type === 'done' &&
+ (event.data as { reason?: unknown } | null | undefined)?.reason ===
+ 'turn_continuation_cancelled',
+ ),
+ ).toHaveLength(0);
expect(handle.listBackgroundTasks?.()).toEqual([]);
- expect(handle.isTurnRunning?.()).toBe(false);
+
+ await handle.send({ type: 'user', content: 'next turn after real terminal' });
+ stream.emit(turnResult('next turn complete'));
+ await waitFor(() => events.filter(isProductTerminal).length === 2, 'next product terminal observed');
+ await waitFor(() => handle.isTurnRunning?.() === false, 'next turn settled');
+ expect(handle.beginTurnContinuationWait?.(continuationId)).toBeNull();
stream.end();
await handle.close().catch(() => undefined);
});
- it('interrupt 在途时 awaiting claim 先变 active,result 正常收尾且不再建 claim', async () => {
- const { handle, stream, events, fakeQuery } = await startSessionWithStream();
+ it.each([
+ ['success', () => turnResult('late old-generation success')],
+ ['is_error', interruptedTurnResult],
+ ] as const)(
+ '跨层 Session 丢弃 gen N 迟到的 %s result,不终结 gen N+1',
+ async (_lateKind, lateResult) => {
+ const { handle, stream, streams } = await startSessionWithStream(
+ undefined,
+ { autoCollect: false },
+ );
+ const session = wrapInSession(handle);
+ const seen: AgentEvent[] = [];
+ session.onEvent((event) => seen.push(event));
+
+ const firstSend = await session.send('spawn background work', { turnAttemptToken: 101 });
+ expect(firstSend).toEqual({ accepted: true });
+ stream.emit(taskStarted('task-agent', 'local_agent'));
+ await waitFor(() => taskEvents(seen).length >= 1, 'Session observed wake task');
+ stream.emit(turnResult('waiting'));
+ await waitFor(
+ () => seen.some((event) => event.type === 'done' && event.turnContinuationId !== undefined),
+ 'Session observed claimed parent done',
+ );
+ expect(seen.filter(isProductTerminal)).toHaveLength(0);
+ await expect(session.send('must remain blocked')).rejects.toThrow(/SESSION_RUNNING/);
+
+ stream.emit(taskNotification('task-agent', 'completed'));
+ await waitFor(() => taskEvents(seen).length >= 2, 'Session observed task completion');
+ await session.abort();
+ await waitFor(() => seen.filter(isProductTerminal).length === 1, 'Stop terminal observed');
+ await waitFor(() => session.isTurnRunning() === false, 'generation N settled');
+ expect(seen.filter(isProductTerminal)[0]?.turnAttemptToken).toBe(101);
+
+ const secondSend = await session.send('start generation N+1', { turnAttemptToken: 202 });
+ expect(secondSend).toEqual({ accepted: true });
+ await waitFor(
+ () =>
+ seen.some(
+ (event) =>
+ event.type === 'status' &&
+ event.turnAttemptToken === 202 &&
+ (event.data as { isRunning?: unknown } | null | undefined)?.isRunning === true,
+ ),
+ 'generation N+1 start status observed',
+ );
+ const eventCountBeforeLateResult = seen.length;
+ streams[0]?.emit(lateResult());
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(seen).toHaveLength(eventCountBeforeLateResult);
+ expect(session.isTurnRunning()).toBe(true);
+
+ stream.emit(assistantText('generation N+1 output'));
+ await waitFor(
+ () => seen.some((event) => event.type === 'text' && event.turnAttemptToken === 202),
+ 'generation N+1 assistant observed',
+ );
+ stream.emit(turnResult('generation N+1 complete'));
+ await waitFor(() => seen.filter(isProductTerminal).length === 2, 'generation N+1 terminal observed');
+ await waitFor(() => session.isTurnRunning() === false, 'generation N+1 settled');
+ expect(seen.filter(isProductTerminal).map((event) => event.turnAttemptToken)).toEqual([
+ 101,
+ 202,
+ ]);
+
+ stream.end();
+ await session.close().catch(() => undefined);
+ },
+ );
+
+ it('旧 query 迟到 result 被隔离后,新 query 的 is_error result 仍正常收口', async () => {
+ const { handle, stream, streams, events } = await startSessionWithStream();
await handle.send({ type: 'user', content: 'spawn background work' });
stream.emit(taskStarted('task-agent', 'local_agent'));
await waitFor(() => taskEvents(events).length >= 1, 'wake task observed');
stream.emit(turnResult('waiting'));
- await waitFor(() => events.some((event) => event.type === 'done'), 'foreground done observed');
- const continuationId = events.find((event) => event.type === 'done')?.turnContinuationId;
- expect(continuationId).toBeTypeOf('number');
-
- const interrupt = createDeferred<void>();
- fakeQuery.stopTask!.mockRejectedValueOnce(new Error('stop raced with continuation'));
- fakeQuery.interrupt.mockImplementationOnce(() => interrupt.promise);
- const abortPromise = handle.abort();
- await waitFor(() => fakeQuery.interrupt.mock.calls.length === 1, 'interrupt dispatched');
+ await waitFor(() => events.some((event) => event.type === 'done'), 'parent done observed');
+ stream.emit(taskNotification('task-agent', 'completed'));
+ await waitFor(() => taskEvents(events).length >= 2, 'task completion observed');
+ await handle.abort();
+ await waitFor(() => events.filter(isProductTerminal).length === 1, 'Stop terminal observed');
+ await waitFor(() => handle.isTurnRunning?.() === false, 'cancelled generation settled');
- stream.emit({
- type: 'assistant',
- message: { content: [{ type: 'text', text: 'continuation started before interrupt' }] },
- });
+ const eventCountBeforeNewSend = events.length;
+ await handle.send({ type: 'user', content: 'new failing turn' });
await waitFor(
- () => handle.beginTurnContinuationWait?.(continuationId) === 'active',
- 'awaiting claim activated while interrupt was pending',
+ () => events.length > eventCountBeforeNewSend,
+ 'new generation start status observed',
);
+ const eventCountBeforeOldTail = events.length;
+ streams[0]?.emit(turnResult('late old result'));
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(events).toHaveLength(eventCountBeforeOldTail);
- interrupt.resolve(undefined);
- await abortPromise;
- stream.emit(turnResult('interrupted continuation'));
+ stream.emit(interruptedTurnResult());
await waitFor(
- () => events.filter((event) => event.type === 'done').length >= 2,
- 'active continuation result observed',
+ () =>
+ events.some(
+ (event) =>
+ event.type === 'error' &&
+ (event.data as { isTerminal?: unknown } | null | undefined)?.isTerminal === true,
+ ),
+ 'new generation terminal error observed',
);
-
- const finalDone = events.filter((event) => event.type === 'done').at(-1);
- expect(finalDone?.turnContinuationId).toBeUndefined();
- expect(handle.beginTurnContinuationWait?.(continuationId)).toBeNull();
- expect(handle.isTurnRunning?.()).toBe(false);
+ await waitFor(() => handle.isTurnRunning?.() === false, 'new failing generation settled');
+ expect(events.filter((event) => event.type === 'done').at(-1)?.turnContinuationId).toBeUndefined();
stream.end();
await handle.close().catch(() => undefined);
@@ -726,7 +863,36 @@ describe('ClaudeCodeAgent abort stops background wake tasks', () => {
await handle.close().catch(() => undefined);
});
- it('四个并行 Agent 相邻 completed 后逐段自动续跑,最后一个 done 归零 busy', async () => {
+ it('terminal latch 只压同 task,其他 running wake task 仍正常进入 claim', async () => {
+ const { handle, stream, events } = await startSessionWithStream();
+
+ await handle.send({ type: 'user', content: 'spawn two background tasks' });
+ stream.emit(taskStarted('task-a', 'local_agent'));
+ stream.emit(taskStarted('task-b', 'local_agent'));
+ await waitFor(() => taskEvents(events).length >= 2, 'parallel tasks observed');
+
+ stream.emit(taskNotification('task-a', 'completed'));
+ await waitFor(() => taskEvents(events).length >= 3, 'task a completed');
+ stream.emit(taskProgress('task-a'));
+ stream.emit(taskUpdatedRunning('task-a'));
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(taskEvents(events)).toHaveLength(3);
+ expect(handle.listBackgroundTasks?.().map((task) => task.taskId)).toEqual(['task-b']);
+
+ stream.emit(turnResult('task b is still running'));
+ await waitFor(() => events.some((event) => event.type === 'done'), 'foreground done observed');
+ const continuationId = events.find((event) => event.type === 'done')?.turnContinuationId;
+ expect(continuationId).toBeTypeOf('number');
+ expect(handle.beginTurnContinuationWait?.(continuationId)).toBe('awaiting');
+
+ stream.emit(taskNotification('task-b', 'stopped'));
+ await waitFor(() => handle.isTurnRunning?.() === false, 'task b cancellation settled');
+
+ stream.end();
+ await handle.close().catch(() => undefined);
+ });
+
+ it('四个并行 Agent 的相邻终态通知合并为一段 continuation', async () => {
const { handle, stream, events } = await startSessionWithStream();
const taskIds = ['task-1', 'task-2', 'task-3', 'task-4'];
@@ -736,28 +902,24 @@ describe('ClaudeCodeAgent abort stops background wake tasks', () => {
stream.emit(turnResult('waiting for parallel tasks'));
await waitFor(() => events.filter((event) => event.type === 'done').length >= 1, 'foreground done observed');
- for (const taskId of taskIds) stream.emit(taskNotification(taskId, 'completed'));
+ stream.emit(taskNotification('task-1', 'completed'));
+ stream.emit(taskNotification('task-2', 'failed'));
+ stream.emit(taskNotification('task-3', 'completed'));
+ stream.emit(taskNotification('task-4', 'failed'));
await waitFor(
() => taskEvents(events).length >= taskIds.length * 2,
'adjacent task completions observed',
);
- for (let index = 0; index < taskIds.length; index += 1) {
- stream.emit(turnResult(''));
- await waitFor(
- () => events.filter((event) => event.type === 'done').length >= index + 2,
- `continuation ${index + 1} done observed`,
- );
- const continuationDone = events.filter((event) => event.type === 'done')[index + 1];
- if (index < taskIds.length - 1) {
- expect(continuationDone?.turnContinuationId).toBeTypeOf('number');
- } else {
- expect(continuationDone?.turnContinuationId).toBeUndefined();
- }
- expect(handle.isTurnRunning?.()).toBe(index < taskIds.length - 1);
- }
+ stream.emit(assistantText('all merged results'));
+ stream.emit(turnResult(''));
+ await waitFor(
+ () => events.filter((event) => event.type === 'done').length >= 2,
+ 'single merged continuation done observed',
+ );
const doneEvents = events.filter((event) => event.type === 'done');
+ expect(doneEvents).toHaveLength(2);
expect(doneEvents.at(-1)?.turnContinuationId).toBeUndefined();
expect(handle.isTurnRunning?.()).toBe(false);
@@ -765,6 +927,49 @@ describe('ClaudeCodeAgent abort stops background wake tasks', () => {
await handle.close().catch(() => undefined);
});
+ it('合并 continuation 只把仍 running 的任务带入下一 claim', async () => {
+ const { handle, stream, events } = await startSessionWithStream();
+
+ await handle.send({ type: 'user', content: 'spawn three background agents' });
+ for (const taskId of ['task-a', 'task-b', 'task-c']) {
+ stream.emit(taskStarted(taskId, 'local_agent'));
+ }
+ await waitFor(() => taskEvents(events).length >= 3, 'parallel tasks observed');
+ stream.emit(turnResult('waiting'));
+ await waitFor(() => events.filter((event) => event.type === 'done').length >= 1, 'parent done observed');
+
+ stream.emit(taskNotification('task-a', 'completed'));
+ stream.emit(taskNotification('task-b', 'failed'));
+ await waitFor(() => taskEvents(events).length >= 5, 'merged terminal notifications observed');
+ stream.emit(assistantText('merged a and b'));
+ stream.emit(turnResult(''));
+ await waitFor(
+ () => events.filter((event) => event.type === 'done').length >= 2,
+ 'merged continuation done observed',
+ );
+
+ const nextClaimId = events.filter((event) => event.type === 'done').at(-1)?.turnContinuationId;
+ expect(nextClaimId).toBeTypeOf('number');
+ expect(handle.beginTurnContinuationWait?.(nextClaimId)).toBe('awaiting');
+
+ stream.emit(taskNotification('task-c', 'stopped'));
+ await waitFor(
+ () =>
+ events.some(
+ (event) =>
+ event.type === 'done' &&
+ (event.data as { reason?: unknown } | null | undefined)?.reason ===
+ 'turn_continuation_cancelled',
+ ),
+ 'remaining running task cancellation observed',
+ );
+ expect(handle.beginTurnContinuationWait?.(nextClaimId)).toBeNull();
+ expect(handle.isTurnRunning?.()).toBe(false);
+
+ stream.end();
+ await handle.close().catch(() => undefined);
+ });
+
it('remote detach 显式丢弃 awaiting claim', async () => {
const { handle, stream, fakeQuery, events, collected } = await startRemoteSessionWithStream();
@@ -786,6 +991,30 @@ describe('ClaudeCodeAgent abort stops background wake tasks', () => {
await collected;
});
+ it('remote detach 在 claim boundary 未 ACK 时也立即释放旧 continuation id', async () => {
+ const { handle, stream, fakeQuery } = await startRemoteSessionWithStream({
+ autoCollect: false,
+ });
+ const { iterator, nextMatching, seen } = createEventReader(handle);
+
+ await handle.send({ type: 'user', content: 'spawn remote background work' });
+ stream.emit(taskStarted('task-agent', 'local_agent'));
+ await nextMatching((event) => event.type === 'agent_task_update');
+ stream.emit(turnResult('waiting'));
+ const parentDone = await nextMatching((event) => event.type === 'done');
+ expect(parentDone.turnContinuationId).toBeTypeOf('number');
+ expect(handle.beginTurnContinuationWait?.(parentDone.turnContinuationId)).toBe('awaiting');
+
+ await handle.detach?.();
+ expect(fakeQuery.detach).toHaveBeenCalledTimes(1);
+ expect(handle.beginTurnContinuationWait?.(parentDone.turnContinuationId)).toBeNull();
+ expect(handle.isTurnRunning?.()).toBe(false);
+ expect(seen.filter(isProductTerminal)).toHaveLength(0);
+
+ stream.end();
+ await iterator.return?.();
+ });
+
it('result-only 自动续 turn 会把旧 claim 标成 active,并由第二个 done 正常收口', async () => {
const { handle, stream, events } = await startSessionWithStream();
@@ -844,6 +1073,41 @@ describe('ClaudeCodeAgent abort stops background wake tasks', () => {
await handle.close().catch(() => undefined);
});
+ it('claim-bearing parent done 入队失败时回滚 claim 的两条 boundary 账', async () => {
+ const { handle, stream } = await startSessionWithStream(undefined, { autoCollect: false });
+ const { iterator, nextMatching } = createEventReader(handle);
+
+ await handle.send({ type: 'user', content: 'spawn background work' });
+ stream.emit(taskStarted('task-agent', 'local_agent'));
+ await nextMatching((event) => event.type === 'agent_task_update');
+
+ asyncQueueMock.rejectNextDone = true;
+ stream.emit(turnResult('waiting'));
+ const pairedStatus = await nextMatching(
+ (event) =>
+ event.type === 'status' &&
+ event.turnContinuationId !== undefined &&
+ (event.data as { isRunning?: unknown } | null | undefined)?.isRunning === false,
+ );
+ const continuationId = pairedStatus.turnContinuationId;
+ expect(continuationId).toBeTypeOf('number');
+ // The rejected done ledger was rolled back, while the yielded paired
+ // status still owns exactly one claim boundary until the next iterator ACK.
+ expect(handle.beginTurnContinuationWait?.(continuationId)).toBe('awaiting');
+ expect(handle.isTurnRunning?.()).toBe(false);
+
+ const drain = iterator.next();
+ await waitFor(
+ () => handle.beginTurnContinuationWait?.(continuationId) === null,
+ 'accepted paired status claim ledger acknowledged',
+ );
+ expect(handle.isTurnRunning?.()).toBe(false);
+
+ stream.end();
+ await drain;
+ await handle.close().catch(() => undefined);
+ });
+
it.each(['completed', 'failed'] as const)(
'active continuation 期间另一 wake task %s 会让当前 done 继续携带新 claim',
async (status) => {
@@ -1051,7 +1315,7 @@ describe('ClaudeCodeAgent abort stops background wake tasks', () => {
await handle.close().catch(() => undefined);
});
- it('stopTask 与 interrupt 都失败时不伪造 continuation 收口', async () => {
+ it('stopTask 成功但 interrupt 失败时不伪造 continuation 收口', async () => {
const { handle, stream, events, fakeQuery } = await startSessionWithStream();
await handle.send({ type: 'user', content: 'spawn background work' });
@@ -1061,22 +1325,30 @@ describe('ClaudeCodeAgent abort stops background wake tasks', () => {
await waitFor(() => events.some((event) => event.type === 'done'), 'foreground done observed');
const continuationId = events.find((event) => event.type === 'done')?.turnContinuationId;
expect(continuationId).toBeTypeOf('number');
+ const productTerminalCountBeforeAbort = events.filter(isProductTerminal).length;
+ const unclaimedIdleStatusCountBeforeAbort = events.filter(
+ (event) =>
+ event.type === 'status' &&
+ event.turnContinuationId === undefined &&
+ (event.data as { isRunning?: unknown } | null | undefined)?.isRunning === false,
+ ).length;
- fakeQuery.stopTask!.mockRejectedValueOnce(new Error('stop failed'));
fakeQuery.interrupt.mockRejectedValueOnce(new Error('interrupt failed'));
await expect(handle.abort()).resolves.toBeUndefined();
await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(fakeQuery.stopTask).toHaveBeenCalledTimes(1);
expect(handle.beginTurnContinuationWait?.(continuationId)).toBe('awaiting');
expect(handle.isTurnRunning?.()).toBe(true);
+ expect(events.filter(isProductTerminal)).toHaveLength(productTerminalCountBeforeAbort);
expect(
- events.some(
+ events.filter(
(event) =>
- event.type === 'done' &&
- (event.data as { reason?: unknown } | null | undefined)?.reason ===
- 'turn_continuation_cancelled',
+ event.type === 'status' &&
+ event.turnContinuationId === undefined &&
+ (event.data as { isRunning?: unknown } | null | undefined)?.isRunning === false,
),
- ).toBe(false);
+ ).toHaveLength(unclaimedIdleStatusCountBeforeAbort);
stream.end();
await handle.close().catch(() => undefined);
@@ -1189,6 +1461,161 @@ describe('ClaudeCodeAgent abort stops background wake tasks', () => {
await handle.close().catch(() => undefined);
});
+ it('completed claim stays busy until Stop synthetic terminal is acknowledged', async () => {
+ const { handle, stream, fakeQuery } = await startSessionWithStream(
+ undefined,
+ { autoCollect: false },
+ );
+ const { iterator, nextMatching, seen } = createEventReader(handle);
+
+ await handle.send({ type: 'user', content: 'spawn background work' });
+ stream.emit(taskStarted('task-agent', 'local_agent'));
+ await nextMatching(
+ (event) =>
+ event.type === 'agent_task_update' &&
+ (event.data as { status?: unknown } | null | undefined)?.status === 'running',
+ );
+ stream.emit(turnResult('waiting for task'));
+ const foregroundDone = await nextMatching((event) => event.type === 'done');
+ expect(foregroundDone.turnContinuationId).toBeTypeOf('number');
+
+ const completedEvent = nextMatching(
+ (event) =>
+ event.type === 'agent_task_update' &&
+ (event.data as { status?: unknown } | null | undefined)?.status === 'completed',
+ );
+ stream.emit(taskNotification('task-agent', 'completed'));
+ await completedEvent;
+ expect(handle.beginTurnContinuationWait?.(foregroundDone.turnContinuationId)).toBe('awaiting');
+
+ await handle.abort();
+ expect(fakeQuery.stopTask).not.toHaveBeenCalled();
+ expect(fakeQuery.interrupt).toHaveBeenCalledTimes(1);
+ expect(handle.isTurnRunning?.()).toBe(true);
+
+ // interrupt ACK 已返回、synthetic terminal 已排队但尚未被消费;provider
+ // 的迟到尾巴不能越过 tombstone 再追加一个真实终态。
+ stream.emit(assistantText('late provider assistant after interrupt ACK'));
+ stream.emit(turnResult('late provider result after interrupt ACK'));
+ await new Promise((resolve) => setTimeout(resolve, 20));
+
+ const cancellationDone = await nextMatching(
+ (event) =>
+ event.type === 'done' &&
+ (event.data as { reason?: unknown } | null | undefined)?.reason ===
+ 'turn_continuation_cancelled',
+ );
+ expect(cancellationDone.turnContinuationId).toBeUndefined();
+ expect(handle.isTurnRunning?.()).toBe(true);
+ expect(seen.filter(isProductTerminal)).toHaveLength(1);
+
+ // Asking for the next item acknowledges the yielded terminal boundary.
+ const drain = iterator.next();
+ await waitFor(() => handle.isTurnRunning?.() === false, 'cancellation done consumed');
+ expect(handle.beginTurnContinuationWait?.(foregroundDone.turnContinuationId)).toBeNull();
+ const nextState = await Promise.race([
+ drain.then(() => 'event' as const),
+ new Promise<'pending'>((resolve) => setTimeout(() => resolve('pending'), 30)),
+ ]);
+ expect(nextState).toBe('pending');
+ stream.end();
+ await handle.close().catch(() => undefined);
+ await drain;
+ });
+
+ it.each(['user Stop', 'stopped notification', 'single-task Stop'] as const)(
+ '%s synthetic 收口后无旧 result,新一代 result-only 仍正常结束',
+ async (source) => {
+ const { handle, stream, events, fakeQueries } = await startSessionWithStream();
+
+ await handle.send({ type: 'user', content: 'spawn background work' });
+ stream.emit(taskStarted('task-agent', 'local_agent'));
+ await waitFor(() => taskEvents(events).length >= 1, 'wake task observed');
+ stream.emit(turnResult('waiting'));
+ await waitFor(() => events.some((event) => event.type === 'done'), 'parent done observed');
+ expect(events.find((event) => event.type === 'done')?.turnContinuationId).toBeTypeOf('number');
+
+ if (source === 'user Stop') {
+ await handle.abort();
+ } else if (source === 'stopped notification') {
+ stream.emit(taskNotification('task-agent', 'stopped'));
+ } else {
+ await handle.stopBackgroundTask?.('task-agent');
+ }
+ await waitFor(() => events.filter(isProductTerminal).length === 1, 'synthetic terminal observed');
+ await waitFor(() => handle.isTurnRunning?.() === false, 'synthetic terminal acknowledged');
+
+ await handle.send({ type: 'user', content: 'result-only next turn' });
+ expect(fakeQueries).toHaveLength(2);
+ stream.emit(turnResult('next turn complete'));
+ await waitFor(() => events.filter(isProductTerminal).length === 2, 'new result-only terminal observed');
+ await waitFor(() => handle.isTurnRunning?.() === false, 'new result-only turn settled');
+
+ stream.end();
+ await handle.close().catch(() => undefined);
+ },
+ );
+
+ it('synthetic cancellation 后先 rewind 只重建一个 Query', async () => {
+ const { handle, stream, events, fakeQueries } = await startSessionWithStream();
+
+ await handle.send({ type: 'user', content: 'spawn background work' });
+ stream.emit(taskStarted('task-agent', 'local_agent'));
+ await waitFor(() => taskEvents(events).length >= 1, 'wake task observed');
+ stream.emit(turnResult('waiting'));
+ await waitFor(() => events.some((event) => event.type === 'done'), 'parent done observed');
+ stream.emit(taskNotification('task-agent', 'completed'));
+ await waitFor(() => taskEvents(events).length >= 2, 'completion observed');
+ await handle.abort();
+ await waitFor(() => events.filter(isProductTerminal).length === 1, 'synthetic terminal observed');
+
+ await handle.commitRewindFiles?.('user-uuid-1', 'assistant-uuid-1');
+ await handle.send({ type: 'user', content: 'send after rewind' });
+ expect(fakeQueries).toHaveLength(2);
+ expect(fakeQueries[1]?.close).not.toHaveBeenCalled();
+
+ stream.emit(turnResult('rewound turn complete'));
+ await waitFor(() => events.filter(isProductTerminal).length === 2, 'rewound turn terminal observed');
+ await waitFor(() => handle.isTurnRunning?.() === false, 'rewound turn settled');
+
+ stream.end();
+ await handle.close().catch(() => undefined);
+ });
+
+ it('cancellation rebuild 不重复初始 resumeSessionAt / forkSession', async () => {
+ const { handle, stream, events, fakeQueries } = await startSessionWithStream(undefined, {
+ vendorOptions: {
+ resumeSessionAt: 'initial-assistant-uuid',
+ forkSession: true,
+ },
+ });
+
+ await handle.send({ type: 'user', content: 'spawn background work' });
+ stream.emit(taskStarted('task-agent', 'local_agent'));
+ await waitFor(() => taskEvents(events).length >= 1, 'wake task observed');
+ stream.emit(turnResult('waiting'));
+ await waitFor(() => events.some((event) => event.type === 'done'), 'parent done observed');
+ stream.emit(taskNotification('task-agent', 'completed'));
+ await waitFor(() => taskEvents(events).length >= 2, 'completion observed');
+ await handle.abort();
+ await waitFor(() => events.filter(isProductTerminal).length === 1, 'synthetic terminal observed');
+
+ await handle.send({ type: 'user', content: 'send after cancellation' });
+ expect(fakeQueries).toHaveLength(2);
+ const rebuiltOptions = (sdkMock.query.mock.calls[1]?.[0] as {
+ options?: Record<string, unknown>;
+ } | undefined)?.options;
+ expect(rebuiltOptions).not.toHaveProperty('resumeSessionAt');
+ expect(rebuiltOptions).not.toHaveProperty('forkSession');
+
+ stream.emit(turnResult('replacement query complete'));
+ await waitFor(() => events.filter(isProductTerminal).length === 2, 'replacement terminal observed');
+ await waitFor(() => handle.isTurnRunning?.() === false, 'replacement turn settled');
+
+ stream.end();
+ await handle.close().catch(() => undefined);
+ });
+
it('stopBackgroundTask is idempotent for terminal / unknown tasks', async () => {
const { handle, stream, events, fakeQuery } = await startSessionWithStream();
diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.ts
index 840ad9b3ed..2422b2940c 100644
--- a/packages/maker-core/src/agents/claude-code/index.ts
+++ b/packages/maker-core/src/agents/claude-code/index.ts
@@ -2946,7 +2946,7 @@ export class ClaudeCodeAgent extends BaseAgent {
reason: string,
doneData?: Record<string, unknown>,
trackContinuationTerminal = false,
- ): void {
+ ): boolean {
eventQueue.push({
type: 'status',
data: { status: 'Done', ...usageTracker.snapshot(), isRunning: false },
@@ -2971,6 +2971,7 @@ export class ClaudeCodeAgent extends BaseAgent {
);
}
}
+ return accepted;
}
const canceledBridgeQueries = new WeakSet<Query>();
@@ -3020,9 +3021,10 @@ export class ClaudeCodeAgent extends BaseAgent {
let nextContinuationId = 1;
let activeContinuationId: number | null = null;
// User Stop can close an awaiting product continuation while the provider
- // still has buffered activity. Suppress that cancelled tail until the next
- // explicit user input is accepted (or the Query is replaced).
+ // still has buffered activity. Suppress that cancelled tail until its
+ // Query is replaced before the next explicit user turn.
let continuationCancellationGeneration: number | null = null;
+ let continuationCancellationRequiresQueryRebuild = false;
const continuationClaims = new Map<number, ContinuationClaim>();
const continuationListeners = new Set<(
continuationId: number,
@@ -3048,6 +3050,12 @@ export class ClaudeCodeAgent extends BaseAgent {
if (!claim.settled || claim.pendingBoundaryEvents > 0) return;
continuationClaims.delete(claim.id);
};
+ const retireContinuationTasks = (claim: ContinuationClaim): void => {
+ for (const taskId of claim.tasks.keys()) {
+ runningBackgroundTasks.delete(taskId);
+ terminalBackgroundTaskIds.add(taskId);
+ }
+ };
const cancelActiveContinuation = (reason: string): ContinuationClaim | null => {
const claim = activeContinuationClaim();
if (!claim || claim.state !== 'awaiting') return null;
@@ -3070,7 +3078,7 @@ export class ClaudeCodeAgent extends BaseAgent {
});
releaseSettledContinuationClaim(claim);
};
- const discardActiveContinuation = (reason: string): void => {
+ const discardActiveContinuation = (reason: string, forceRelease = false): void => {
if (continuationClaims.size > 0) {
log.debug('discarding turn continuation claims', {
reason,
@@ -3082,16 +3090,33 @@ export class ClaudeCodeAgent extends BaseAgent {
claim.settled = true;
releaseSettledContinuationClaim(claim);
}
+ if (forceRelease) continuationClaims.clear();
};
- const consumeTaskNotificationForActiveSegment = (claim: ContinuationClaim): void => {
- const consumed = [...claim.tasks].find(
- ([, state]) => state === 'completed' || state === 'failed',
- );
- if (consumed) claim.tasks.delete(consumed[0]);
+ const consumeTaskNotificationsForActiveSegment = (claim: ContinuationClaim): void => {
+ // The SDK may merge several task notifications that arrived before the
+ // first continuation activity into one automatic segment. Consume that
+ // whole terminal snapshot at activation; notifications arriving after
+ // the claim becomes active remain for the following segment.
+ for (const [taskId, state] of claim.tasks) {
+ if (state === 'completed' || state === 'failed') claim.tasks.delete(taskId);
+ }
};
const captureContinuationBoundary = (event: AgentEvent): boolean => {
if (event.type !== 'done') return false;
const existing = activeContinuationClaim();
+ const interruptedGeneration =
+ turnState.interruptRequested &&
+ turnState.interruptGeneration === turnState.generation;
+ if (interruptedGeneration && existing?.state === 'awaiting') {
+ // A real provider terminal can beat the interrupt ACK. It is the
+ // product terminal for this Stop, so retire the snapshotted awaiting
+ // claim instead of attaching it (or minting a successor) to this done.
+ retireContinuationTasks(existing);
+ existing.settled = true;
+ activeContinuationId = null;
+ releaseSettledContinuationClaim(existing);
+ return true;
+ }
if (existing?.state === 'awaiting') {
// Defensive duplicate done for the same boundary: preserve the same
// claim instead of letting the duplicate terminate host observers.
@@ -3121,10 +3146,10 @@ export class ClaudeCodeAgent extends BaseAgent {
// terminal boundary. Even if a wake task remains in the provider table,
// user Stop has revoked the right to create another automatic segment.
if (
- (turnState.interruptRequested &&
- turnState.interruptGeneration === turnState.generation) ||
+ interruptedGeneration ||
continuationCancellationGeneration === turnState.generation
) {
+ if (interruptedGeneration && existing) retireContinuationTasks(existing);
return wasActiveContinuation;
}
const wakeTasks = [...runningBackgroundTasks.entries()].filter(([, info]) => info.wake);
@@ -3251,10 +3276,17 @@ export class ClaudeCodeAgent extends BaseAgent {
reason,
continuationId: claim.id,
});
- emitTurnBoundary('turn_continuation_cancelled', undefined, true);
+ if (emitTurnBoundary('turn_continuation_cancelled', undefined, true)) {
+ // Install the cancelled-tail fence at the same enqueue boundary as
+ // the synthetic product terminal. stopTask can win before interrupt
+ // resolves, so waiting for the interrupt ACK leaves a double-terminal
+ // window for a late provider result.
+ continuationCancellationGeneration = turnState.generation;
+ continuationCancellationRequiresQueryRebuild = true;
+ }
};
- const acknowledgeConsumedEvent = (event: AgentEvent): void => {
+ const releaseEventAccounting = (event: AgentEvent): void => {
if (event.turnContinuationId !== undefined) {
const claim = continuationClaims.get(event.turnContinuationId);
if (claim) {
@@ -3269,6 +3301,11 @@ export class ClaudeCodeAgent extends BaseAgent {
);
}
};
+ const pushForwardedEvent = (event: AgentEvent): boolean => {
+ const accepted = eventQueue.push(event);
+ if (!accepted) releaseEventAccounting(event);
+ return accepted;
+ };
const consumedEventStream = async function* (): AsyncGenerator<AgentEvent> {
try {
@@ -3278,7 +3315,7 @@ export class ClaudeCodeAgent extends BaseAgent {
} finally {
// Code after yield runs when Session asks for the next event, i.e.
// after its synchronous fan-out (including Hook/Scheduler queries).
- acknowledgeConsumedEvent(event);
+ releaseEventAccounting(event);
}
}
} finally {
@@ -3311,11 +3348,13 @@ export class ClaudeCodeAgent extends BaseAgent {
for (const taskId of wakeIds) {
void q.stopTask(taskId).then(
() => {
- // RPC 成功才有资格把 provider claim 判成 stopped。若 foreground
- // `done` 已先入队,host 会暂时等在该 claim 上,并在这里收到确定的
- // cancellation;不能在 RPC 尚可能失败时先猜任务已经停下。
- const cancelledClaim = markWakeTasksStopped([taskId], reason);
- if (cancelledClaim) emitCancelledContinuationBoundary(cancelledClaim, reason);
+ // abort 的产品收口权威来自 q.interrupt ACK。stopTask 先成功不能提前
+ // cancel claim:若随后 interrupt reject,必须保持 awaiting/busy,等待
+ // provider 的真实 stopped/result;否则会伪造一次用户 Stop 成功。
+ log.debug('background wake task stop acknowledged; awaiting interrupt authority', {
+ reason,
+ taskId,
+ });
},
(e: unknown) => {
// 两类预期失败:任务恰好已自然结束;远端老 daemon 不认识 query/stopTask
@@ -3385,7 +3424,7 @@ export class ClaudeCodeAgent extends BaseAgent {
deferResumeFailureBoundary = false;
}
let pendingTerminalStatusEvent: AgentEvent | undefined;
- const forwardEventSink: Pick<AsyncQueue<AgentEvent>, 'push'> = {
+ const forwardEventSink: AsyncQueue<AgentEvent> = {
// Claude's translator emits `status(isRunning=false)` immediately before
// the matching `done`. Hold that status long enough to copy the
// provider continuation claim from `done`; otherwise every generic
@@ -3432,17 +3471,26 @@ export class ClaudeCodeAgent extends BaseAgent {
const data = e.data as { isRunning?: unknown } | null | undefined;
if (data?.isRunning === false) {
if (pendingTerminalStatusEvent) {
- eventQueue.push(pendingTerminalStatusEvent);
+ pushForwardedEvent(pendingTerminalStatusEvent);
}
pendingTerminalStatusEvent = e;
return true;
}
}
if (e.type !== 'done' && pendingTerminalStatusEvent) {
- eventQueue.push(pendingTerminalStatusEvent);
+ pushForwardedEvent(pendingTerminalStatusEvent);
pendingTerminalStatusEvent = undefined;
}
+ const continuationBeforeCapture = activeContinuationClaim();
const isContinuationTerminalDone = captureContinuationBoundary(e);
+ const continuationAfterCapture = activeContinuationClaim();
+ const createdContinuationClaim =
+ e.type === 'done' &&
+ e.turnContinuationId !== undefined &&
+ continuationAfterCapture?.id === e.turnContinuationId &&
+ continuationBeforeCapture?.id !== continuationAfterCapture.id
+ ? continuationAfterCapture
+ : null;
if (e.type === 'done' && pendingTerminalStatusEvent) {
const statusEvent = pendingTerminalStatusEvent;
pendingTerminalStatusEvent = undefined;
@@ -3451,21 +3499,23 @@ export class ClaudeCodeAgent extends BaseAgent {
const claim = continuationClaims.get(e.turnContinuationId);
if (claim) claim.pendingBoundaryEvents += 1;
}
- eventQueue.push(statusEvent);
+ pushForwardedEvent(statusEvent);
}
if (isContinuationTerminalDone) {
continuationTerminalBoundaryEvents.add(e);
pendingContinuationTerminalBoundaries += 1;
}
- const accepted = eventQueue.push(e);
- if (isContinuationTerminalDone) {
- if (!accepted) {
- continuationTerminalBoundaryEvents.delete(e);
- pendingContinuationTerminalBoundaries = Math.max(
- 0,
- pendingContinuationTerminalBoundaries - 1,
- );
+ const accepted = pushForwardedEvent(e);
+ if (!accepted && createdContinuationClaim) {
+ // A claim minted for a boundary that the host can never observe has
+ // no continuation contract. Retire it after rolling back the done's
+ // own ledger entry; an accepted paired status keeps the claim object
+ // alive only until that status is acknowledged.
+ createdContinuationClaim.settled = true;
+ if (activeContinuationId === createdContinuationClaim.id) {
+ activeContinuationId = null;
}
+ releaseSettledContinuationClaim(createdContinuationClaim);
}
// A stopped notification is part of the visible turn history. Preserve
// its order, then append a real product-turn boundary so Session can
@@ -3476,6 +3526,19 @@ export class ClaudeCodeAgent extends BaseAgent {
}
return accepted;
},
+ end: () => {
+ if (pendingTerminalStatusEvent) {
+ eventQueue.push(pendingTerminalStatusEvent);
+ pendingTerminalStatusEvent = undefined;
+ }
+ eventQueue.end();
+ },
+ clear: () => {
+ pendingTerminalStatusEvent = undefined;
+ eventQueue.clear();
+ },
+ get pending() { return eventQueue.pending; },
+ [Symbol.asyncIterator]: () => eventQueue[Symbol.asyncIterator](),
};
// ── 事件 forward loop(SDK 原始事件 → maker-core AgentEvent) ─────────────
@@ -3519,6 +3582,10 @@ export class ClaudeCodeAgent extends BaseAgent {
// 残留的 interruptRequested 会错误抑制新 q 首个真实 is_error 终态 —— 兜底清。
turnState.interruptRequested = false;
continuationCancellationGeneration = null;
+ // Any successfully installed replacement Query isolates the cancelled
+ // provider tail. This also covers rewind / invalid-resume rebuilds, so a
+ // later send must not create a redundant intermediate Query.
+ continuationCancellationRequiresQueryRebuild = false;
discardActiveContinuation('query_replaced');
// q 换代 = 旧 CLI 子进程已死,其后台任务全部随之终止 —— 清表防 stale 条目
// 让下次 abort 对不存在的任务空发 stopTask。
@@ -3544,7 +3611,7 @@ export class ClaudeCodeAgent extends BaseAgent {
continuationCancellationGeneration !== null &&
(rawType === 'assistant' || rawType === 'stream_event' || rawType === 'result')
) {
- log.debug('ignoring provider activity after user-cancelled continuation', {
+ log.debug('ignoring provider activity from cancelled continuation query', {
rawType,
cancellationGeneration: continuationCancellationGeneration,
});
@@ -3601,7 +3668,7 @@ export class ClaudeCodeAgent extends BaseAgent {
// Each task notification queues one SDK continuation segment.
// Consume only the notification that activated this segment;
// other terminal tasks must keep the next boundary claimed.
- consumeTaskNotificationForActiveSegment(claim);
+ consumeTaskNotificationsForActiveSegment(claim);
claim.state = 'active';
emitContinuationState(claim.id, 'active');
}
@@ -4099,7 +4166,11 @@ export class ClaudeCodeAgent extends BaseAgent {
// 窗口里用户切模型/权限档只会改闭包,不会影响当前和后续 turn。只有当前 q 已被
// 主动 close 并登记到 canceledBridgeQueries 时才阻塞 control request。
const controlRequestsBlocked = (): boolean =>
- pendingRewindTo !== undefined || acceptingRebuiltSend || idleResumeRebuildGate !== null || canceledBridgeQueries.has(q);
+ pendingRewindTo !== undefined ||
+ acceptingRebuiltSend ||
+ idleResumeRebuildGate !== null ||
+ continuationCancellationRequiresQueryRebuild ||
+ canceledBridgeQueries.has(q);
type QueryRuntimeSnapshot = {
model: string;
effort: Effort;
@@ -4170,6 +4241,51 @@ export class ClaudeCodeAgent extends BaseAgent {
}
log.warn(`${label}: runtime drift kept changing while replaying; leaving remaining drift to the next setter/rebuild`);
}
+ async function rebuildCancelledContinuationQuery(signal?: AbortSignal): Promise<void> {
+ if (!continuationCancellationRequiresQueryRebuild) return;
+ const staleQuery = q;
+ const runtimeSnapshot: QueryRuntimeSnapshot = {
+ model: mutableModel,
+ effort: mutableEffort,
+ fastMode: mutableFastMode,
+ sdkPermissionMode: currentTurnSdkPermissionMode(),
+ };
+ acceptingRebuiltSend = true;
+ inputQueue.end();
+ inputQueue = createAsyncQueue<SdkUserInput>();
+ abortController = new AbortController();
+ runtimeState.lastResultUsageAggregate = null;
+ rewindTransitionQueries.add(staleQuery);
+ try {
+ await Promise.resolve(staleQuery.close());
+ } catch (e) {
+ log.warn('cancelled continuation query close threw before rebuild', { error: String(e) });
+ }
+ try {
+ q = await buildQuery({
+ permissionMode: runtimeSnapshot.sdkPermissionMode,
+ fresh: true,
+ });
+ if (signal?.aborted) {
+ inputQueue.end();
+ rewindTransitionQueries.add(q);
+ try {
+ await Promise.resolve(q.close());
+ } catch (e) {
+ log.warn('cancelled continuation rebuild close threw after send cancellation', {
+ error: String(e),
+ });
+ }
+ throw new Error('Claude send cancelled before acceptance');
+ }
+ startForwardLoop(q);
+ notifySupportedModels(q);
+ await replayRuntimeDrift(runtimeSnapshot, 'cancelled continuation rebuild');
+ continuationCancellationRequiresQueryRebuild = false;
+ } finally {
+ acceptingRebuiltSend = false;
+ }
+ }
const handle: AgentSessionHandle = {
get id() { return sdkSessionId ?? '<pending>'; },
agentKind: 'claude-code',
@@ -4199,6 +4315,17 @@ export class ClaudeCodeAgent extends BaseAgent {
throw new Error('Claude send cancelled before acceptance');
}
if (sendOpts) handle.validateSendOptions?.(sendOpts);
+ // 保持普通 send / rewind send 原有的同步前置语义:即使 async helper 立即
+ // return,裸 await 也会让出一个 microtask,导致调用方在 Query rebuild 真正
+ // 开始前观察到半初始化窗口。只有确实存在 cancellation tombstone 时才进入
+ // 异步重建。
+ if (
+ continuationCancellationRequiresQueryRebuild &&
+ pendingRewindTo === undefined &&
+ activeBridgeRewindResumeAt === undefined
+ ) {
+ await rebuildCancelledContinuationQuery(sendOpts?.signal);
+ }
activeTurnPermissionPolicy = sendOpts?.turnPermissionPolicy ?? null;
// 仅用于诊断日志: 调用方每次 send 都可以带 logTitle (取自 storage 的最新值);
// 缺省时保留上一次的值 (没传不等于"清空")。
@@ -4510,7 +4637,6 @@ export class ClaudeCodeAgent extends BaseAgent {
throw new Error('Claude input queue is closed');
}
userInputAccepted = true;
- continuationCancellationGeneration = null;
activeCapabilitySelectionText = userMessageTextForCapabilityRouting(message.content);
setAutoReviewIntent(message.content);
replayableUserInput = sdkInput;
@@ -4645,19 +4771,14 @@ export class ClaudeCodeAgent extends BaseAgent {
// 用户主动停止: SDK 被 interrupt 后会 drain 出 error_during_execution 的
// is_error result, 打标记让 translator turn-end 跳过"失败兜底 error",
// 否则用户点停止会被误报成"执行失败"通知。
- // turnInFlight 守卫(与 watchdog / tool-loop 对齐): turn 已自然结束时的
- // 迟到 Stop 不置位 —— idle query 上的 interrupt 不保证产出 result 来消费
- // 标记, 残留会泄漏到下一真实 turn 吞掉其失败兜底(review P2)。
- if (turnInFlight) {
+ // 前台仍在跑或 provider continuation 正在 awaiting 时都要锁定本代 Stop。
+ // 后者的 turnInFlight 已经是 false,但 interrupt ACK 前的迟到 result 同样
+ // 不得重新铸造 continuation claim。
+ const awaitingContinuationAtUserStop = activeContinuationClaim();
+ if (turnInFlight || awaitingContinuationAtUserStop?.state === 'awaiting') {
turnState.interruptRequested = true;
turnState.interruptGeneration = turnState.generation;
}
- const awaitingContinuationAtUserStop = activeContinuationClaim();
- const awaitingContinuationIdAtUserStop =
- awaitingContinuationAtUserStop?.state === 'awaiting'
- ? awaitingContinuationAtUserStop.id
- : null;
- const continuationGenerationAtUserStop = turnState.generation;
// 用户 Stop 的产品语义 = 本会话所有模型调用停止:先发 stopTask 再 interrupt
// (同一控制通道按序处理),封掉「interrupt 后任务恰好完成 → task_notification
// 自动续跑新 turn」的竞态窗口。fire-and-forget,不阻塞 interrupt。
@@ -4670,25 +4791,6 @@ export class ClaudeCodeAgent extends BaseAgent {
// produce another provider result. Close it explicitly after the
// control action succeeds and append the ordered product terminal.
const cancelledContinuation = cancelActiveContinuation('user_stop');
- if (awaitingContinuationIdAtUserStop !== null) {
- const continuationAfterInterrupt = activeContinuationClaim();
- if (
- continuationAfterInterrupt?.id === awaitingContinuationIdAtUserStop &&
- continuationAfterInterrupt.state === 'active'
- ) {
- // Provider activity may have activated the snapshotted claim
- // while interrupt was in flight. Let its interrupted result run
- // the normal turn teardown, but forbid that result from minting
- // another continuation claim.
- turnState.interruptRequested = true;
- turnState.interruptGeneration = turnState.generation;
- } else if (continuationAfterInterrupt?.id !== awaitingContinuationIdAtUserStop) {
- // stopTask may have won the race and cancelled the same claim
- // before interrupt resolved. The successful interrupt still
- // authorizes the same cancelled-tail tombstone.
- continuationCancellationGeneration = continuationGenerationAtUserStop;
- }
- }
if (cancelledContinuation) {
// The successful Stop revokes these tasks' continuation contract.
// Retire their tracking entries as well, so a late provider
@@ -4696,10 +4798,7 @@ export class ClaudeCodeAgent extends BaseAgent {
// cancelled. This is product-side cancellation bookkeeping; the
// best-effort stopTask RPCs above remain responsible for stopping
// the provider tasks themselves.
- for (const taskId of cancelledContinuation.tasks.keys()) {
- runningBackgroundTasks.delete(taskId);
- terminalBackgroundTaskIds.add(taskId);
- }
+ retireContinuationTasks(cancelledContinuation);
emitCancelledContinuationBoundary(cancelledContinuation, 'user_stop');
}
} catch (e) {
@@ -4796,7 +4895,7 @@ export class ClaudeCodeAgent extends BaseAgent {
? {
async detach() {
if (closed) return;
- discardActiveContinuation('session_detached');
+ discardActiveContinuation('session_detached', true);
closed = true;
try {
dismissAllPending('session_closed', 'deny');
diff --git a/packages/maker-core/src/agents/claude-code/translator.ts b/packages/maker-core/src/agents/claude-code/translator.ts
index d77f46e9ab..23c5a54c2f 100644
--- a/packages/maker-core/src/agents/claude-code/translator.ts
+++ b/packages/maker-core/src/agents/claude-code/translator.ts
@@ -21,6 +21,7 @@ import {
extractNonSecretErrorSignals,
redactSensitiveText,
} from '@cindy/maker-shared/error-redaction';
+import type { createAsyncQueue } from '../shared/async-queue.js';
import { stripTerminalControlSequences } from '../shared/terminal-output.js';
import { formatOverloadRetryMessage, parseOverloadError } from '../shared/overload-error.js';
import {
@@ -406,7 +407,7 @@ function formatCacheBucket(b: {
const TURN_END_LOGGER_KEY = 'SDK ◀ turn end (result)';
void TURN_END_LOGGER_KEY; // 只是给调用方对照参考
-type EventQueue = { push(event: AgentEvent): boolean };
+type EventQueue = ReturnType<typeof createAsyncQueue<AgentEvent>>;
interface TranslatorLog {
debug(msg: string, ctx?: Record<string, unknown>): void;
info(msg: string, ctx?: Record<string, unknown>): void;