Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(claude): settle stopped continuation claims (#1941)
fmfsaisaifd09d4b4bb4f
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.tsindex 8b169a8f84..eccb129f8e 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@@ -30,12 +30,45 @@ const sdkMock = vi.hoisted(() => ({forkSession: vi.fn(),query: vi.fn(),}));+const asyncQueueMock = vi.hoisted(() => ({+ rejectNextDone: false,+}));vi.mock('@anthropic-ai/claude-agent-sdk', () => ({forkSession: sdkMock.forkSession,query: sdkMock.query,}));+vi.mock('../../shared/async-queue.js', async (importOriginal) => {+ const actual = await importOriginal<typeof import('../../shared/async-queue.js')>();+ return {+ ...actual,+ createAsyncQueue<T>() {+ const queue = actual.createAsyncQueue<T>();+ return {+ push(item: T) {+ if (+ asyncQueueMock.rejectNextDone &&+ typeof item === 'object' &&+ item !== null &&+ (item as { type?: unknown }).type === 'done'+ ) {+ asyncQueueMock.rejectNextDone = false;+ return false;+ }+ return queue.push(item);+ },+ end: () => queue.end(),+ clear: () => queue.clear(),+ get pending() {+ return queue.pending;+ },+ [Symbol.asyncIterator]: () => queue[Symbol.asyncIterator](),+ };+ },+ };+});+import { ClaudeCodeAgent } from '../index.js';const tempDirs: string[] = [];@@ -56,7 +89,7 @@ function createNoopLogger(): Logger {return logger;}-function createDeps(): AgentDeps {+function createDeps(overrides: Partial<AgentDeps> = {}): AgentDeps {const auth: AuthAdapter = {async getState() {return { authenticated: true };@@ -74,6 +107,7 @@ function createDeps(): AgentDeps {runtimeConfig: {},binaryPath: process.execPath,logger: createNoopLogger(),+ ...overrides,};}@@ -82,7 +116,7 @@ function createControlledStream() {const items: unknown[] = [];let waiter: { resolve: (r: IteratorResult<unknown>) => void; reject: (e: unknown) => void } | null = null;let ended = false;- let failure: unknown = null;+ const failure: unknown = null;function pump(): void {if (!waiter) return;@@ -134,7 +168,13 @@ function createFakeQuery(interrupt: vi.fn(async () => {}),close: vi.fn(async () => {}),rewindFiles: vi.fn(async () => ({ canRewind: false })),- ...(opts?.omitStopTask ? {} : { stopTask: vi.fn(async (_taskId: string) => {}) }),+ ...(opts?.omitStopTask+ ? {}+ : {+ stopTask: vi.fn(async (taskId: string) => {+ void taskId;+ }),+ }),};}@@ -159,7 +199,9 @@ async function startSessionWithStream(if (prompt) {void (async () => {try {- for await (const _ of prompt) { /* discard — 只对齐 pending 语义 */ }+ for await (const ignored of prompt) {+ void ignored; // discard — 只对齐 pending 语义+ }} catch { /* end / abort 都算正常收尾 */ }})();}@@ -186,6 +228,33 @@ async function startSessionWithStream(return { agent, handle, stream, fakeQuery, events, collected };}+async function startRemoteSessionWithStream() {+ const configDir = await makeTempDir();+ process.env.CLAUDE_CONFIG_DIR = configDir;+ const workingDir = await makeTempDir();+ const stream = createControlledStream();+ const fakeQuery = {+ ...createFakeQuery(stream),+ send: vi.fn(async () => {}),+ detach: vi.fn(async () => {}),+ };+ const remoteCcQueryFactory: NonNullable<AgentDeps['remoteCcQueryFactory']> = async () =>+ fakeQuery as never;+ const agent = new ClaudeCodeAgent(createDeps({ remoteCcQueryFactory }));+ const handle = await agent.startSession({+ sessionId: 'session-stop-task-remote',+ remoteHostId: 'remote-host',+ model: 'claude-opus-4-6',+ workingDir,+ permissionMode: 'acceptEdits',+ });+ const events: AgentEvent[] = [];+ const collected = (async () => {+ for await (const event of handle.events()) events.push(event);+ })();+ return { handle, stream, fakeQuery, events, collected };+}+function taskStarted(taskId: string, taskType: string): Record<string, unknown> {return {type: 'system',@@ -206,6 +275,25 @@ function taskNotification(taskId: string, status: 'completed' | 'failed' | 'stop};}+function taskProgress(taskId: string, taskType = 'local_agent'): Record<string, unknown> {+ return {+ type: 'system',+ subtype: 'task_progress',+ task_id: taskId,+ task_type: taskType,+ description: `late progress ${taskId}`,+ };+}++function taskUpdatedRunning(taskId: string): Record<string, unknown> {+ return {+ type: 'system',+ subtype: 'task_updated',+ task_id: taskId,+ patch: { status: 'pending' },+ };+}+function turnResult(result = 'ok'): Record<string, unknown> {return {type: 'result',@@ -235,11 +323,26 @@ async function waitFor(cond: () => boolean, label: string): Promise<void> {}}+function createDeferred<T = void>(): {+ promise: Promise<T>;+ resolve: (value: T | PromiseLike<T>) => void;+ reject: (reason?: unknown) => void;+} {+ let resolve!: (value: T | PromiseLike<T>) => void;+ let reject!: (reason?: unknown) => void;+ const promise = new Promise<T>((res, rej) => {+ resolve = res;+ reject = rej;+ });+ return { promise, resolve, reject };+}+function taskEvents(events: AgentEvent[]): AgentEvent[] {return events.filter((e) => e.type === 'agent_task_update');}afterEach(async () => {+ asyncQueueMock.rejectNextDone = false;sdkMock.forkSession.mockReset();sdkMock.query.mockReset();if (originalClaudeConfigDir === undefined) {@@ -393,6 +496,296 @@ describe('ClaudeCodeAgent abort stops background wake tasks', () => {await handle.close().catch(() => undefined);});+ it('completed wake task 在用户 Stop 成功后显式取消 awaiting claim', 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');+ const continuationId = events.find((event) => event.type === 'done')?.turnContinuationId;+ expect(continuationId).toBeTypeOf('number');++ stream.emit(taskNotification('task-agent', 'completed'));+ await waitFor(() => taskEvents(events).length >= 2, 'task completion observed');+ expect(handle.beginTurnContinuationWait?.(continuationId)).toBe('awaiting');++ await handle.abort();+ expect(fakeQuery.stopTask).not.toHaveBeenCalled();+ expect(fakeQuery.interrupt).toHaveBeenCalledTimes(1);+ await waitFor(+ () =>+ events.some(+ (event) =>+ event.type === 'done' &&+ (event.data as { reason?: unknown } | null | undefined)?.reason ===+ 'turn_continuation_cancelled',+ ),+ 'user Stop cancellation boundary observed',+ );+ const completionIndex = events.findIndex(+ (event) =>+ event.type === 'agent_task_update' &&+ (event.data as { status?: unknown } | null | undefined)?.status === 'completed',+ );+ const cancellationDoneIndex = events.findIndex(+ (event) =>+ event.type === 'done' &&+ (event.data as { reason?: unknown } | null | undefined)?.reason ===+ 'turn_continuation_cancelled',+ );+ expect(cancellationDoneIndex).toBeGreaterThan(completionIndex);+ expect(handle.beginTurnContinuationWait?.(continuationId)).toBeNull();+ expect(handle.isTurnRunning?.()).toBe(false);++ stream.end();+ await handle.close().catch(() => undefined);+ });++ it('stopTask 先取消 claim 后 interrupt 成功仍屏蔽迟到 continuation 尾巴', 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');+ const continuationId = events.find((event) => event.type === 'done')?.turnContinuationId;+ expect(continuationId).toBeTypeOf('number');++ const interrupt = createDeferred<void>();+ 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();++ 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));++ expect(events).toHaveLength(eventCountAfterCancellation);+ expect(handle.listBackgroundTasks?.()).toEqual([]);+ expect(handle.isTurnRunning?.()).toBe(false);++ stream.end();+ await handle.close().catch(() => undefined);+ });++ it('interrupt 在途时 awaiting claim 先变 active,result 正常收尾且不再建 claim', 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');+ 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');++ stream.emit({+ type: 'assistant',+ message: { content: [{ type: 'text', text: 'continuation started before interrupt' }] },+ });+ await waitFor(+ () => handle.beginTurnContinuationWait?.(continuationId) === 'active',+ 'awaiting claim activated while interrupt was pending',+ );++ interrupt.resolve(undefined);+ await abortPromise;+ stream.emit(turnResult('interrupted continuation'));+ await waitFor(+ () => events.filter((event) => event.type === 'done').length >= 2,+ 'active continuation result 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);++ stream.end();+ await handle.close().catch(() => undefined);+ });++ it('stopBackgroundTask RPC 在途时先收到 completion,成功回包仍能取消 claim', 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');+ const continuationId = events.find((event) => event.type === 'done')?.turnContinuationId;+ expect(continuationId).toBeTypeOf('number');++ const stopTask = createDeferred<void>();+ fakeQuery.stopTask!.mockImplementationOnce(() => stopTask.promise);+ const stopPromise = handle.stopBackgroundTask!('task-agent');+ await waitFor(() => fakeQuery.stopTask!.mock.calls.length === 1, 'stopTask dispatched');++ stream.emit(taskNotification('task-agent', 'completed'));+ await waitFor(() => taskEvents(events).length >= 2, 'completion raced ahead of RPC response');+ expect(handle.beginTurnContinuationWait?.(continuationId)).toBe('awaiting');++ stopTask.resolve(undefined);+ await stopPromise;+ await waitFor(+ () =>+ events.some(+ (event) =>+ event.type === 'done' &&+ (event.data as { reason?: unknown } | null | undefined)?.reason ===+ 'turn_continuation_cancelled',+ ),+ 'stopTask cancellation boundary observed',+ );+ expect(handle.beginTurnContinuationWait?.(continuationId)).toBeNull();+ expect(handle.isTurnRunning?.()).toBe(false);++ stream.end();+ await handle.close().catch(() => undefined);+ });++ it('本代 Stop 后到达的 interrupted done 不会从残留 wake task 新建 claim', 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');++ 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.interrupt.mock.calls.length === 1, 'interrupt dispatched');++ stream.emit(turnResult('interrupted turn'));+ await waitFor(() => events.some((event) => event.type === 'done'), 'interrupted done observed');+ expect(events.find((event) => event.type === 'done')?.turnContinuationId).toBeUndefined();++ interrupt.resolve(undefined);+ stopTask.resolve(undefined);+ await abortPromise;+ await waitFor(() => handle.isTurnRunning?.() === false, 'interrupted turn settled');++ stream.end();+ await handle.close().catch(() => undefined);+ });++ it.each(+ (['completed', 'failed', 'stopped'] as const).flatMap((status) => [+ [status, 'task_started', (taskId: string) => taskStarted(taskId, 'local_agent')] as const,+ [status, 'task_progress', taskProgress] as const,+ [status, 'task_updated(pending)', taskUpdatedRunning] as const,+ ]),+ )('终态 %s 后迟到 %s 不会复活 wake task 或制造 claim', async (status, _lateType, lateEvent) => {+ const { handle, stream, events } = await startSessionWithStream();++ await handle.send({ type: 'user', content: 'spawn background work' });+ stream.emit(taskStarted('task-agent', 'local_agent'));+ stream.emit(taskNotification('task-agent', status));+ await waitFor(() => taskEvents(events).length >= 2, 'task terminal observed');++ stream.emit(lateEvent('task-agent'));+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(taskEvents(events)).toHaveLength(2);+ expect(handle.listBackgroundTasks?.()).toEqual([]);++ stream.emit(turnResult('foreground finished'));+ await waitFor(() => events.some((event) => event.type === 'done'), 'foreground done observed');+ expect(events.find((event) => event.type === 'done')?.turnContinuationId).toBeUndefined();+ expect(handle.isTurnRunning?.()).toBe(false);++ stream.end();+ await handle.close().catch(() => undefined);+ });++ it('四个并行 Agent 相邻 completed 后逐段自动续跑,最后一个 done 归零 busy', async () => {+ const { handle, stream, events } = await startSessionWithStream();+ const taskIds = ['task-1', 'task-2', 'task-3', 'task-4'];++ await handle.send({ type: 'user', content: 'spawn four background agents' });+ for (const taskId of taskIds) stream.emit(taskStarted(taskId, 'local_agent'));+ await waitFor(() => taskEvents(events).length >= taskIds.length, 'parallel tasks observed');+ 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'));+ 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);+ }++ const doneEvents = events.filter((event) => event.type === 'done');+ expect(doneEvents.at(-1)?.turnContinuationId).toBeUndefined();+ 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();++ await handle.send({ type: 'user', content: 'spawn remote background work' });+ stream.emit(taskStarted('task-agent', 'local_agent'));+ await waitFor(() => taskEvents(events).length >= 1, 'remote wake task observed');+ stream.emit(turnResult('waiting'));+ await waitFor(() => events.some((event) => event.type === 'done'), 'remote foreground done observed');+ const continuationId = events.find((event) => event.type === 'done')?.turnContinuationId;+ expect(continuationId).toBeTypeOf('number');+ expect(handle.beginTurnContinuationWait?.(continuationId)).toBe('awaiting');++ await handle.detach?.();+ expect(fakeQuery.detach).toHaveBeenCalledTimes(1);+ expect(handle.beginTurnContinuationWait?.(continuationId)).toBeNull();+ expect(handle.isTurnRunning?.()).toBe(false);++ stream.end();+ await collected;+ });+it('result-only 自动续 turn 会把旧 claim 标成 active,并由第二个 done 正常收口', async () => {const { handle, stream, events } = await startSessionWithStream();@@ -430,6 +823,27 @@ describe('ClaudeCodeAgent abort stops background wake tasks', () => {await handle.close().catch(() => undefined);});+ it('active continuation 的最终 done 入队失败时回滚 terminal busy 计数', async () => {+ const { handle, stream, 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.filter((event) => event.type === 'done').length >= 1, 'foreground done observed');++ stream.emit(taskNotification('task-agent', 'completed'));+ await waitFor(() => taskEvents(events).length >= 2, 'task completion observed');+ asyncQueueMock.rejectNextDone = true;+ stream.emit(turnResult(''));++ await waitFor(() => handle.isTurnRunning?.() === false, 'rejected final done counter rolled back');+ expect(events.filter((event) => event.type === 'done')).toHaveLength(1);++ stream.end();+ await handle.close().catch(() => undefined);+ });+it.each(['completed', 'failed'] as const)('active continuation 期间另一 wake task %s 会让当前 done 继续携带新 claim',async (status) => {@@ -572,7 +986,7 @@ describe('ClaudeCodeAgent abort stops background wake tasks', () => {await handle.close().catch(() => undefined);});- it('a rejecting stopTask does not block interrupt and abort still resolves', async () => {+ it('stopTask rejection does not leak an awaiting claim after interrupt succeeds', async () => {const { handle, stream, events, fakeQuery } = await startSessionWithStream();await handle.send({ type: 'user', content: 'spawn background work' });@@ -588,10 +1002,81 @@ describe('ClaudeCodeAgent abort stops background wake tasks', () => {expect(fakeQuery.interrupt).toHaveBeenCalledTimes(1);// fire-and-forget 的 rejection 被 catch 消化 —— 给微任务一拍确认无 unhandled。await new Promise((r) => setTimeout(r, 20));- // RPC 失败时不能先猜任务已经停下;claim 继续保持 busy,等待真实的- // task_notification / 自动续 turn 终态。+ await waitFor(+ () =>+ events.some(+ (event) =>+ event.type === 'done' &&+ (event.data as { reason?: unknown } | null | undefined)?.reason ===+ 'turn_continuation_cancelled',+ ),+ 'interrupt-authoritative cancellation observed',+ );+ expect(handle.beginTurnContinuationWait?.(continuationId)).toBeNull();+ expect(handle.isTurnRunning?.()).toBe(false);++ // q.interrupt can resolve before the provider's cancelled tail drains.+ // Neither an unknown late task nor model output may restart the turn.+ 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({+ type: 'stream_event',+ event: {+ type: 'message_start',+ message: { model: 'claude-opus-4-6', usage: { input_tokens: 0 } },+ },+ });+ stream.emit(turnResult('late interrupted result'));+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(events).toHaveLength(eventCountAfterCancellation);+ expect(handle.listBackgroundTasks?.()).toEqual([]);+ expect(handle.isTurnRunning?.()).toBe(false);++ // The tombstone is scoped to the cancelled provider tail. A newly+ // accepted user input clears it and runs normally.+ await handle.send({ type: 'user', content: 'start a new turn' });+ expect(handle.isTurnRunning?.()).toBe(true);+ stream.emit(turnResult('new turn finished'));+ await waitFor(+ () => events.filter((event) => event.type === 'done').length >= 3,+ 'new explicit turn completed',+ );+ expect(handle.isTurnRunning?.()).toBe(false);++ stream.end();+ await handle.close().catch(() => undefined);+ });++ it('stopTask 与 interrupt 都失败时不伪造 continuation 收口', async () => {+ const { handle, stream, events, fakeQuery } = await startSessionWithStream();++ await handle.send({ type: 'user', content: 'spawn background work' });+ stream.emit(taskStarted('task-1', 'local_agent'));+ await waitFor(() => taskEvents(events).length >= 1, 'task_started observed');+ stream.emit(turnResult('waiting for task'));+ await waitFor(() => events.some((event) => event.type === 'done'), 'foreground done observed');+ const continuationId = events.find((event) => event.type === 'done')?.turnContinuationId;+ expect(continuationId).toBeTypeOf('number');++ 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(handle.beginTurnContinuationWait?.(continuationId)).toBe('awaiting');expect(handle.isTurnRunning?.()).toBe(true);+ expect(+ events.some(+ (event) =>+ event.type === 'done' &&+ (event.data as { reason?: unknown } | null | undefined)?.reason ===+ 'turn_continuation_cancelled',+ ),+ ).toBe(false);stream.end();await handle.close().catch(() => undefined);diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.tsindex 62e3a2278c..840ad9b3ed 100644--- a/packages/maker-core/src/agents/claude-code/index.ts+++ b/packages/maker-core/src/agents/claude-code/index.ts@@ -2908,6 +2908,7 @@ export class ClaudeCodeAgent extends BaseAgent {activeBridgeRewindResumeAt = undefined;pendingToolIds.clear();runningBackgroundTasks.clear();+ terminalBackgroundTaskIds.clear();closed = true;try { dismissAllPending('session_closed', 'deny'); } catch (e) {log.warn(`${logLabel}: dismissAllPending threw`, { error: String(e) });@@ -2960,12 +2961,15 @@ export class ClaudeCodeAgent extends BaseAgent {continuationTerminalBoundaryEvents.add(doneEvent);pendingContinuationTerminalBoundaries += 1;}- if (!eventQueue.push(doneEvent) && trackContinuationTerminal) {- continuationTerminalBoundaryEvents.delete(doneEvent);- pendingContinuationTerminalBoundaries = Math.max(- 0,- pendingContinuationTerminalBoundaries - 1,- );+ const accepted = eventQueue.push(doneEvent);+ if (trackContinuationTerminal) {+ if (!accepted) {+ continuationTerminalBoundaryEvents.delete(doneEvent);+ pendingContinuationTerminalBoundaries = Math.max(+ 0,+ pendingContinuationTerminalBoundaries - 1,+ );+ }}}@@ -2993,6 +2997,12 @@ export class ClaudeCodeAgent extends BaseAgent {string,{ wake: boolean; taskType?: string; toolUseId?: string; title?: string }>();+ // SDK task progress can race behind its terminal notification. Once a task+ // is terminal within the current Query generation, a late running/progress+ // patch must not resurrect it into runningBackgroundTasks and manufacture+ // a fresh continuation claim at the next done.+ const terminalBackgroundTaskIds = new Set<string>();+ const ignoredLateTerminalTaskEvents = new WeakSet<AgentEvent>();type ContinuationTaskState = 'running' | 'completed' | 'failed' | 'stopped';type ContinuationClaim = {@@ -3009,6 +3019,10 @@ export class ClaudeCodeAgent extends BaseAgent {// result-only continuation cannot change what the host later observes.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).+ let continuationCancellationGeneration: number | null = null;const continuationClaims = new Map<number, ContinuationClaim>();const continuationListeners = new Set<(continuationId: number,@@ -3103,6 +3117,16 @@ export class ClaudeCodeAgent extends BaseAgent {// attaching a fresh claim to this done when another automatic turn is// now expected.}+ // A result produced by the generation being interrupted is already a+ // 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) ||+ continuationCancellationGeneration === turnState.generation+ ) {+ return wasActiveContinuation;+ }const wakeTasks = [...runningBackgroundTasks.entries()].filter(([, info]) => info.wake);for (const [taskId] of wakeTasks) {if (!carriedTasks.has(taskId)) carriedTasks.set(taskId, 'running');@@ -3141,8 +3165,12 @@ export class ClaudeCodeAgent extends BaseAgent {const claim = activeContinuationClaim();for (const taskId of taskIds) {const info = runningBackgroundTasks.get(taskId);- if (!info?.wake) continue;+ const claimTracksWakeTask =+ (claim?.state === 'awaiting' || claim?.state === 'active') &&+ claim.tasks.has(taskId);+ if (!info?.wake && !claimTracksWakeTask) continue;runningBackgroundTasks.delete(taskId);+ terminalBackgroundTaskIds.add(taskId);if (claim?.state === 'awaiting' || claim?.state === 'active') {claim.tasks.set(taskId, 'stopped');}@@ -3169,6 +3197,19 @@ export class ClaudeCodeAgent extends BaseAgent {if (!taskId) return null;const status = data?.status;if (status === 'running') {+ if (continuationCancellationGeneration !== null) {+ log.debug('ignoring task activity after user-cancelled continuation', {+ taskId,+ cancellationGeneration: continuationCancellationGeneration,+ });+ ignoredLateTerminalTaskEvents.add(e);+ return null;+ }+ if (terminalBackgroundTaskIds.has(taskId)) {+ log.debug('ignoring late running update for terminal background task', { taskId });+ ignoredLateTerminalTaskEvents.add(e);+ return null;+ }const prev = runningBackgroundTasks.get(taskId);const wake =prev?.wake === true ||@@ -3190,6 +3231,7 @@ export class ClaudeCodeAgent extends BaseAgent {} else if (status === 'completed' || status === 'failed' || status === 'stopped') {const prev = runningBackgroundTasks.get(taskId);runningBackgroundTasks.delete(taskId);+ terminalBackgroundTaskIds.add(taskId);const claim = activeContinuationClaim();if ((claim?.state === 'awaiting' || claim?.state === 'active') &&@@ -3343,7 +3385,7 @@ export class ClaudeCodeAgent extends BaseAgent {deferResumeFailureBoundary = false;}let pendingTerminalStatusEvent: AgentEvent | undefined;- const forwardEventSink: AsyncQueue<AgentEvent> = {+ const forwardEventSink: Pick<AsyncQueue<AgentEvent>, 'push'> = {// 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@@ -3356,6 +3398,7 @@ export class ClaudeCodeAgent extends BaseAgent {}// 后台任务表旁路观察(O(1) type check,task 事件低频,不碰热路径逻辑)。const cancelledContinuation = noteBackgroundTaskEvent(e);+ if (ignoredLateTerminalTaskEvents.delete(e)) return true;if (queuedBridgeTurns > 0) {if (e.type === 'done') {rememberBridgeSuppressedDoneData(e.data);@@ -3415,6 +3458,15 @@ export class ClaudeCodeAgent extends BaseAgent {pendingContinuationTerminalBoundaries += 1;}const accepted = eventQueue.push(e);+ if (isContinuationTerminalDone) {+ if (!accepted) {+ continuationTerminalBoundaryEvents.delete(e);+ pendingContinuationTerminalBoundaries = Math.max(+ 0,+ pendingContinuationTerminalBoundaries - 1,+ );+ }+ }// A stopped notification is part of the visible turn history. Preserve// its order, then append a real product-turn boundary so Session can// close the current generation even though the SDK will not emit a@@ -3424,19 +3476,6 @@ 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) ─────────────@@ -3479,10 +3518,12 @@ export class ClaudeCodeAgent extends BaseAgent {// q 换代: 上一代 q 的 pending interrupted result 不可能从新 q drain 出来,// 残留的 interruptRequested 会错误抑制新 q 首个真实 is_error 终态 —— 兜底清。turnState.interruptRequested = false;+ continuationCancellationGeneration = null;discardActiveContinuation('query_replaced');// q 换代 = 旧 CLI 子进程已死,其后台任务全部随之终止 —— 清表防 stale 条目// 让下次 abort 对不存在的任务空发 stopTask。runningBackgroundTasks.clear();+ terminalBackgroundTaskIds.clear();void (async () => {try {for await (const rawMsg of currentQ) {@@ -3499,6 +3540,16 @@ export class ClaudeCodeAgent extends BaseAgent {bridgeSuppressedDoneData = undefined;}const rawType = (rawMsg as { type?: string } | null)?.type;+ if (+ continuationCancellationGeneration !== null &&+ (rawType === 'assistant' || rawType === 'stream_event' || rawType === 'result')+ ) {+ log.debug('ignoring provider activity after user-cancelled continuation', {+ rawType,+ cancellationGeneration: continuationCancellationGeneration,+ });+ continue;+ }if (noteSdkInitMcpServerNames(rawMsg)) {await refreshSdkMcpProvenance(currentQ);}@@ -4459,6 +4510,7 @@ 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;@@ -4580,6 +4632,7 @@ export class ClaudeCodeAgent extends BaseAgent {const cancelledContinuation = cancelActiveContinuation('bridge_aborted');if (!cancelledContinuation) settleActiveContinuation('bridge_aborted');runningBackgroundTasks.clear();+ terminalBackgroundTaskIds.clear();turnInFlight = false;turnState.interruptRequested = false;emitTurnBoundary(@@ -4599,12 +4652,56 @@ export class ClaudeCodeAgent extends BaseAgent {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。stopRunningWakeBackgroundTasks('user_stop');try {await q.interrupt();+ // Stop is the authoritative cancellation boundary. An awaiting+ // continuation may already have lost every task from the running+ // table, so neither stopTask nor an idle interrupt is guaranteed to+ // 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+ // result or running patch cannot rebuild the claim we just+ // 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);+ }+ emitCancelledContinuationBoundary(cancelledContinuation, 'user_stop');+ }} catch (e) {// interrupt 失败 → 无 result 消费标记, 回收防误抑制(同 watchdog)。turnState.interruptRequested = false;@@ -4677,6 +4774,7 @@ export class ClaudeCodeAgent extends BaseAgent {abortController.abort();// close 会终结 CLI 子进程(本地)/ 远端 session,后台任务随之死亡。runningBackgroundTasks.clear();+ terminalBackgroundTaskIds.clear();} catch (e) {log.warn('close threw', { error: String(e) });}@@ -4698,11 +4796,14 @@ export class ClaudeCodeAgent extends BaseAgent {? {async detach() {if (closed) return;+ discardActiveContinuation('session_detached');closed = true;try {dismissAllPending('session_closed', 'deny');inputQueue.end();abortController.abort();+ runningBackgroundTasks.clear();+ terminalBackgroundTaskIds.clear();} catch (e) {log.warn('detach threw', { error: String(e) });}diff --git a/packages/maker-core/src/agents/claude-code/translator.ts b/packages/maker-core/src/agents/claude-code/translator.tsindex 23c5a54c2f..d77f46e9ab 100644--- a/packages/maker-core/src/agents/claude-code/translator.ts+++ b/packages/maker-core/src/agents/claude-code/translator.ts@@ -21,7 +21,6 @@ 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 {@@ -407,7 +406,7 @@ function formatCacheBucket(b: {const TURN_END_LOGGER_KEY = 'SDK ◀ turn end (result)';void TURN_END_LOGGER_KEY; // 只是给调用方对照参考-type EventQueue = ReturnType<typeof createAsyncQueue<AgentEvent>>;+type EventQueue = { push(event: AgentEvent): boolean };interface TranslatorLog {debug(msg: string, ctx?: Record<string, unknown>): void;info(msg: string, ctx?: Record<string, unknown>): void;