Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(claude): close cancelled wake queries and guard rewind
fmfsaisaiaaebc5a99fdf
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 283d25d50b..7410a9a208 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@@ -1507,6 +1507,70 @@ describe('ClaudeCodeAgent abort stops background wake tasks', () => {await handle.close().catch(() => undefined);});+ it('Stop closes a foreground Query when a wake stop is unconfirmed', async () => {+ const { handle, stream, events, fakeQuery, fakeQueries } = await startSessionWithStream();++ await handle.send({ type: 'user', content: 'foreground turn with wake task' });+ stream.emit(taskStarted('task-unconfirmed', 'local_agent'));+ await waitFor(() => taskEvents(events).length >= 1, 'wake task observed');++ fakeQuery.stopTask!.mockRejectedValueOnce(new Error('remote stop rejected'));+ await handle.abort();++ // The ACK succeeds, so the old provider process is retired even though its+ // stopTask RPC was rejected. A synthetic foreground terminal replaces the+ // interrupted result that close() intentionally prevents from arriving.+ expect(fakeQuery.close).toHaveBeenCalledTimes(1);+ await waitFor(() => events.filter(isProductTerminal).length === 1, 'synthetic foreground terminal observed');+ expect(events.filter(isProductTerminal)).toHaveLength(1);+ expect(handle.isTurnRunning?.()).toBe(false);+ expect(handle.listBackgroundTasks?.()).toEqual([]);++ const eventCountAfterStop = events.length;+ stream.emit(assistantText('late old-query assistant'));+ stream.emit(turnResult('late old-query result'));+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(events).toHaveLength(eventCountAfterStop);+ expect(events.filter(isProductTerminal)).toHaveLength(1);++ await handle.send({ type: 'user', content: 'fresh turn after query close' });+ expect(fakeQueries).toHaveLength(2);+ stream.emit(turnResult('fresh turn complete'));+ await waitFor(() => events.filter(isProductTerminal).length === 2, 'fresh terminal observed');+ await waitFor(() => handle.isTurnRunning?.() === false, 'fresh turn settled');++ stream.end();+ await handle.close().catch(() => undefined);+ });++ it('natural foreground result before Stop ACK is not duplicated when the Query closes', async () => {+ const { handle, stream, events, fakeQuery } = await startSessionWithStream();++ await handle.send({ type: 'user', content: 'natural result races Stop' });+ stream.emit(taskStarted('task-unconfirmed', 'local_agent'));+ await waitFor(() => taskEvents(events).length >= 1, 'wake task observed');++ fakeQuery.stopTask!.mockRejectedValueOnce(new Error('remote stop rejected'));+ const interrupt = createDeferred<void>();+ fakeQuery.interrupt.mockImplementationOnce(() => interrupt.promise);+ const abortPromise = handle.abort();+ await waitFor(() => fakeQuery.interrupt.mock.calls.length === 1, 'interrupt dispatched');++ // The provider's natural success result wins before interrupt ACK. The+ // later close must not synthesize a second product terminal.+ stream.emit(turnResult('natural completion'));+ await waitFor(() => events.filter(isProductTerminal).length === 1, 'natural terminal observed');+ interrupt.resolve(undefined);+ await abortPromise;++ expect(fakeQuery.close).toHaveBeenCalledTimes(1);+ expect(events.filter(isProductTerminal)).toHaveLength(1);+ expect(handle.isTurnRunning?.()).toBe(false);++ stream.end();+ await handle.close().catch(() => undefined);+ });+it('stopTask rejection does not leak an awaiting claim after interrupt succeeds', async () => {const { handle, stream, events, fakeQuery } = await startSessionWithStream();@@ -1572,7 +1636,7 @@ describe('ClaudeCodeAgent abort stops background wake tasks', () => {await handle.close().catch(() => undefined);});- it('只退休 stopTask 成功的 wake 任务,失败任务保留并正常记账', async () => {+ it('Stop 成功后关闭 Query,stopTask 失败任务不再留在本地表', async () => {const { handle, stream, events, fakeQuery } = await startSessionWithStream();await handle.send({ type: 'user', content: 'spawn parallel background work' });@@ -1596,9 +1660,11 @@ describe('ClaudeCodeAgent abort stops background wake tasks', () => {failedStop.reject(new Error('task still running remotely'));await abortPromise;- // Only the fulfilled stopTask is retired. The rejected task remains visible- // until its provider completion arrives, so it cannot continue untracked.- expect(handle.listBackgroundTasks?.().map((task) => task.taskId)).toEqual(['task-failed']);+ // Stop now closes the Query as well as installing the cancellation fence.+ // A rejected stopTask cannot continue in a closed provider process, so its+ // local row is cleared instead of waiting for a notification that close()+ // guarantees will never arrive.+ expect(handle.listBackgroundTasks?.()).toEqual([]);stream.emit(interruptedTurnResult());await waitFor(() => events.filter(isProductTerminal).length === 1, 'stopped foreground terminal observed');@@ -1624,7 +1690,7 @@ describe('ClaudeCodeAgent abort stops background wake tasks', () => {await handle.close().catch(() => undefined);});- it('stopTask reject 后允许本代 success result 收口并封住迟到续跑', async () => {+ it('stopTask reject 后关闭 Query,合成终态并封住迟到续跑', async () => {const { handle, stream, events, fakeQuery, fakeQueries } = await startSessionWithStream();await handle.send({ type: 'user', content: 'spawn background work' });@@ -1633,14 +1699,15 @@ describe('ClaudeCodeAgent abort stops background wake tasks', () => {fakeQuery.stopTask!.mockRejectedValueOnce(new Error('remote stop rejected'));await handle.abort();- // The foreground turn can naturally finish before the interrupt takes- // effect; its success result must still settle this fenced generation.+ // Stop ACK retires this Query immediately; the synthetic terminal settles+ // the foreground turn while the old provider tail is discarded.stream.emit(turnResult('natural completion raced with stop'));await waitFor(() => events.filter(isProductTerminal).length === 1, 'foreground stop terminal observed');await waitFor(() => handle.isTurnRunning?.() === false, 'foreground stop settled');- // The terminal task notification remains visible and clears local task- // accounting; only the same-generation automatic continuation tail is fenced.+ // Terminal task notifications still pass through the retired-query path+ // and clear local task accounting; only the automatic continuation tail is+ // discarded.stream.emit(taskNotification('task-unconfirmed', 'completed'));await waitFor(() => taskEvents(events).some((event) =>@@ -1668,7 +1735,7 @@ describe('ClaudeCodeAgent abort stops background wake tasks', () => {await handle.close().catch(() => undefined);});- it('老 daemon 无 stopTask 时也为未确认 wake 安装栅栏并在下一 send 换代', async () => {+ it('老 daemon 无 stopTask 时关闭 Query 并在下一 send 换代', async () => {const { handle, stream, events, fakeQueries } = await startSessionWithStream({ omitStopTask: true });await handle.send({ type: 'user', content: 'spawn background work' });@@ -1676,6 +1743,7 @@ describe('ClaudeCodeAgent abort stops background wake tasks', () => {await waitFor(() => taskEvents(events).length >= 1, 'legacy wake task observed');await handle.abort();+ expect(fakeQueries[0]?.close).toHaveBeenCalledTimes(1);stream.emit(interruptedTurnResult());await waitFor(() => events.filter(isProductTerminal).length === 1, 'legacy stop terminal observed');await waitFor(() => handle.isTurnRunning?.() === false, 'legacy stop settled');@@ -1948,7 +2016,7 @@ describe('ClaudeCodeAgent abort stops background wake tasks', () => {},);- it('synthetic cancellation 后先 rewind 只重建一个 Query', async () => {+ it('synthetic cancellation 后先 rewind 保持 checkpoint 重建链路', async () => {const { handle, stream, events, fakeQueries } = await startSessionWithStream();await handle.send({ type: 'user', content: 'spawn background work' });@@ -1963,8 +2031,12 @@ describe('ClaudeCodeAgent abort stops background wake tasks', () => {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();+ // Cancellation Stop closed query 0. Direct commit first installs query 1+ // solely to access rewindFiles, then closes it and the normal rewind send+ // installs query 2 at the checkpoint; three Query objects are intentional.+ expect(fakeQueries).toHaveLength(3);+ expect(fakeQueries[1]?.close).toHaveBeenCalledTimes(1);+ expect(fakeQueries[2]?.close).not.toHaveBeenCalled();stream.emit(turnResult('rewound turn complete'));await waitFor(() => events.filter(isProductTerminal).length === 2, 'rewound turn terminal observed');@@ -1974,6 +2046,113 @@ describe('ClaudeCodeAgent abort stops background wake tasks', () => {await handle.close().catch(() => undefined);});+ it('Stop 后直接 previewRewindFiles 会先换 fresh Query 再访问 rewindFiles', 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 for task'));+ await waitFor(() => events.some((event) => event.type === 'done'), 'parent done observed');+ await handle.abort();+ await waitFor(() => events.filter(isProductTerminal).length === 1, 'synthetic terminal observed');++ const preview = await handle.previewRewindFiles?.('user-uuid-1');+ expect(preview?.canRewind).toBe(false);+ expect(fakeQueries).toHaveLength(2);+ expect(fakeQueries[0]?.rewindFiles).not.toHaveBeenCalled();+ expect(fakeQueries[1]?.rewindFiles).toHaveBeenCalledWith('user-uuid-1', { dryRun: true });+ expect(fakeQueries[0]?.close).toHaveBeenCalledTimes(1);+ expect(fakeQueries[1]?.close).not.toHaveBeenCalled();++ await handle.send({ type: 'user', content: 'send after rewind preview' });+ expect(fakeQueries).toHaveLength(2);+ stream.emit(turnResult('preview follow-up complete'));+ await waitFor(() => events.filter(isProductTerminal).length === 2, 'preview follow-up terminal observed');+ await waitFor(() => handle.isTurnRunning?.() === false, 'preview follow-up settled');++ stream.end();+ await handle.close().catch(() => undefined);+ });++ it('Stop 后直接 commitRewindFiles 会在可用 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 for task'));+ await waitFor(() => events.some((event) => event.type === 'done'), 'parent done observed');+ await handle.abort();+ await waitFor(() => events.filter(isProductTerminal).length === 1, 'synthetic terminal observed');++ await handle.commitRewindFiles?.('user-uuid-1', 'assistant-uuid-1');+ expect(fakeQueries).toHaveLength(2);+ expect(fakeQueries[0]?.rewindFiles).not.toHaveBeenCalled();+ expect(fakeQueries[1]?.rewindFiles).toHaveBeenCalledWith('user-uuid-1', { dryRun: false });+ expect(fakeQueries[0]?.close).toHaveBeenCalledTimes(1);+ expect(fakeQueries[1]?.close).toHaveBeenCalledTimes(1);++ await handle.send({ type: 'user', content: 'send after direct rewind commit' });+ expect(fakeQueries).toHaveLength(3);+ stream.emit(turnResult('rewind follow-up complete'));+ await waitFor(() => events.filter(isProductTerminal).length === 2, 'rewind follow-up terminal observed');+ await waitFor(() => handle.isTurnRunning?.() === false, 'rewind follow-up settled');++ stream.end();+ await handle.close().catch(() => undefined);+ });++ it('preview 重建跳过 compact 后,下一 send 仍先补 compact 再入队消息', async () => {+ const { handle, stream, streams, events, fakeQueries } = await startSessionWithStream(+ undefined,+ { autoCompactThresholdPct: 50, capturePrompts: true },+ );++ await handle.send({ type: 'user', content: 'spawn background work' });+ stream.emit({+ type: 'stream_event',+ event: { type: 'message_delta', usage: { input_tokens: 400_000, output_tokens: 0 } },+ });+ await vi.waitFor(() => {+ expect(handle.getUsageSnapshot().contextTokens).toBe(400_000);+ });+ stream.emit(taskStarted('task-agent', 'local_agent'));+ await waitFor(() => taskEvents(events).length >= 1, 'wake task observed');+ stream.emit({ ...turnResult('waiting'), usage: { input_tokens: 400_000, output_tokens: 1 } });+ await waitFor(() => events.some((event) => event.type === 'done'), 'parent done observed');++ await handle.abort();+ await waitFor(() => events.filter(isProductTerminal).length === 1, 'synthetic terminal observed');+ await handle.setModel?.('claude-sonnet-5');+ expect(handle.getUsageSnapshot().contextWindow).toBe(500_000);++ const preview = await handle.previewRewindFiles?.('user-uuid-1');+ expect(preview?.canRewind).toBe(false);+ expect(fakeQueries).toHaveLength(2);+ expect(fakeQueries[1]?.rewindFiles).toHaveBeenCalledWith('user-uuid-1', { dryRun: true });+ expect(handle.isTurnRunning?.()).toBe(false);++ await handle.send({ type: 'user', content: 'send after preview compact rearm' });+ expect(fakeQueries).toHaveLength(3);+ const sendPrompt = (sdkMock.query.mock.calls[2]?.[0] as { prompt?: AsyncIterable<unknown> } | undefined)?.prompt;+ expect(sendPrompt).toBeDefined();+ const sendPromptIter = sendPrompt![Symbol.asyncIterator]();+ expect((await sendPromptIter.next()).value?.message?.content).toBe('/compact');+ expect((await sendPromptIter.next()).value?.message?.content).toBe('send after preview compact rearm');++ streams[2]?.emit(turnResult('compact complete'));+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(events.filter(isProductTerminal)).toHaveLength(1);+ expect(handle.isTurnRunning?.()).toBe(true);+ streams[2]?.emit(turnResult('user complete'));+ await waitFor(() => events.filter(isProductTerminal).length === 2, 'user terminal observed');+ await waitFor(() => handle.isTurnRunning?.() === false, 'user turn settled');++ stream.end();+ await handle.close().catch(() => undefined);+ });+it('synthetic cancellation rebuilds with compact before the next user message after a small-window switch', async () => {const { handle, stream, streams, events, fakeQueries } = await startSessionWithStream(undefined,diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.tsindex ccacda22ec..afb6bf6fc6 100644--- a/packages/maker-core/src/agents/claude-code/index.ts+++ b/packages/maker-core/src/agents/claude-code/index.ts@@ -2208,6 +2208,18 @@ export class ClaudeCodeAgent extends BaseAgent {return true;}+ // Rewind preview/commit intentionally skip injecting /compact because they+ // are control operations, not product turns. If a blocked model/window+ // switch crossed the threshold while the old Query was retired, leave the+ // cancellation rebuild tombstone armed so the next send can inject the+ // compact bridge on a fresh Query before accepting user input.+ function shouldRearmAutoCompactAfterRewindControl(): boolean {+ const snapshot = autoCompactController?.getLatestSnapshot();+ const threshold = autoCompactController?.getCurrentThresholdPct();+ return snapshot !== null && snapshot !== undefined &&+ threshold !== undefined && snapshot.ratio >= threshold / 100;+ }+function queueAutoCompactBridge(kind: ActiveBridgeKind, resumeAt?: string): boolean {const queued = triggerAutoCompactIfNeeded();if (!queued) return false;@@ -3070,7 +3082,6 @@ export class ClaudeCodeAgent extends BaseAgent {// Query is replaced before the next explicit user turn.let continuationCancellationGeneration: number | null = null;let continuationCancellationRequiresQueryRebuild = false;- let cancelledTailInterruptResultPending = false;const continuationClaims = new Map<number, ContinuationClaim>();const continuationListeners = new Set<(continuationId: number,@@ -3647,7 +3658,6 @@ export class ClaudeCodeAgent extends BaseAgent {// 残留的 interruptRequested 会错误抑制新 q 首个真实 is_error 终态 —— 兜底清。turnState.interruptRequested = false;continuationCancellationGeneration = null;- cancelledTailInterruptResultPending = false;// 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.@@ -3661,7 +3671,17 @@ export class ClaudeCodeAgent extends BaseAgent {try {for await (const rawMsg of currentQ) {if (closed) break;- if (canceledBridgeQueries.has(currentQ) || rewindTransitionQueries.has(currentQ)) {+ const rawType = (rawMsg as { type?: string } | null)?.type;+ const rawSubtype = (rawMsg as { subtype?: string } | null)?.subtype;+ const rawStatus = (rawMsg as { status?: string } | null)?.status;+ const isTerminalTaskNotification =+ rawType === 'system' &&+ rawSubtype === 'task_notification' &&+ (rawStatus === 'completed' || rawStatus === 'failed' || rawStatus === 'stopped');+ if (+ (canceledBridgeQueries.has(currentQ) || rewindTransitionQueries.has(currentQ)) &&+ !(canceledBridgeQueries.has(currentQ) && isTerminalTaskNotification)+ ) {continue;}if (activeBridgeKind !== null && queuedBridgeTurns === 0) {@@ -3671,16 +3691,9 @@ export class ClaudeCodeAgent extends BaseAgent {});clearBridgeState();}- const rawType = (rawMsg as { type?: string } | null)?.type;- // Keep the foreground result that acknowledges user Stop; only- // subsequent result/activity messages belong to the fenced tail.- const isExpectedInterruptResult =- cancelledTailInterruptResultPending &&- rawType === 'result';if (continuationCancellationGeneration !== null &&- (rawType === 'assistant' || rawType === 'stream_event' || rawType === 'result') &&- !isExpectedInterruptResult+ (rawType === 'assistant' || rawType === 'stream_event' || rawType === 'result')) {log.debug('ignoring provider activity from cancelled continuation query', {rawType,@@ -3873,7 +3886,6 @@ export class ClaudeCodeAgent extends BaseAgent {}: {}),});- if (isExpectedInterruptResult) cancelledTailInterruptResultPending = false;if (shouldCorrelateResumeFailure) {deferResumeFailureBoundary = false;deferredResumeFailureTimer = setTimeout(@@ -4338,7 +4350,10 @@ 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<boolean> {+ async function rebuildCancelledContinuationQuery(+ signal?: AbortSignal,+ options?: { queueCompactBridge?: boolean },+ ): Promise<boolean> {if (!continuationCancellationRequiresQueryRebuild) return false;const staleQuery = q;const runtimeSnapshot: QueryRuntimeSnapshot = {@@ -4353,10 +4368,12 @@ export class ClaudeCodeAgent extends BaseAgent {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) });+ if (!canceledBridgeQueries.has(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({@@ -4378,12 +4395,20 @@ export class ClaudeCodeAgent extends BaseAgent {startForwardLoop(q);notifySupportedModels(q);await replayRuntimeDrift(runtimeSnapshot, 'cancelled continuation rebuild');- // Cancellation rebuilds are fresh queries without a rewind checkpoint, but the- // model/window drift that was deferred while the cancelled query was fenced still- // needs the same compact→user bridge as rewind. Register the bridge before the- // caller pushes the next user message; do not invent activeBridgeRewindResumeAt.- const bridgeCompactQueued = queueAutoCompactBridge('cancellation');- continuationCancellationRequiresQueryRebuild = false;+ // Cancellation rebuilds used by send need the compact→user bridge for deferred+ // model/window drift. Rewind preview/commit use the same fresh-query isolation but+ // must not start a product turn or inject /compact before rewindFiles runs.+ const skipCompactBridge = options?.queueCompactBridge === false;+ const bridgeCompactQueued = skipCompactBridge+ ? false+ : queueAutoCompactBridge('cancellation');+ // Preview/commit must not generate, but a deferred compact caused by a+ // blocked model/window switch must survive until the next send. Keep+ // the tombstone only for that case; otherwise the fresh Query is ready+ // and the cancellation rebuild state can be cleared normally.+ continuationCancellationRequiresQueryRebuild = skipCompactBridge+ ? shouldRearmAutoCompactAfterRewindControl()+ : false;return bridgeCompactQueued;} finally {acceptingRebuiltSend = false;@@ -4902,52 +4927,51 @@ 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 = stoppedClaim ?? cancelActiveContinuation('user_stop');- 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.- retireContinuationTasks(cancelledContinuation);- // The provider may already have queued the automatic continuation- // on this Query. Close it now so that cancellation fences process- // termination and canUseTool callbacks as well as event output;- // the next send will perform the existing fresh-query rebuild.+ const hasUnconfirmedWakeTasks = [...runningBackgroundTasks.values()].some((info) => info.wake);+ if (cancelledContinuation || hasUnconfirmedWakeTasks) {+ // Both cancellation sources share one terminal state: a cancelled+ // continuation claim or an unconfirmed wake task means this Query+ // must be retired. The provider tail is fenced by the per-query+ // marker, then the next send/rewind installs a fresh Query.const cancelledQuery = q;+ const foregroundNeedsTerminal = turnInFlight;canceledBridgeQueries.add(cancelledQuery);- emitCancelledContinuationBoundary(cancelledContinuation, 'user_stop');+ // Query retirement always leaves a rebuild tombstone, even if the+ // synthetic boundary is rejected because the event queue is+ // already closing. The next explicit send/rewind must never push+ // into this retired query.+ continuationCancellationGeneration = turnState.generation;+ continuationCancellationRequiresQueryRebuild = true;+ if (cancelledContinuation) {+ // The successful Stop revokes the continuation contract. Retire+ // its task ledger before closing the provider process.+ retireContinuationTasks(cancelledContinuation);+ emitCancelledContinuationBoundary(cancelledContinuation, 'user_stop');+ } else {+ log.info('closing Query after user Stop with unconfirmed wake tasks', {+ generation: turnState.generation,+ });+ // close() prevents the interrupted result from arriving. If the+ // foreground turn has not already produced a terminal, replace+ // it with one synthetic boundary; a raced natural result leaves+ // turnInFlight=false and therefore does not get a duplicate.+ if (foregroundNeedsTerminal) emitTurnBoundary('user_stop_unconfirmed_wake_tasks');+ }inputQueue.clear();try {inputQueue.end();} catch (e) {- log.warn('user_stop continuation cancellation: inputQueue.end threw', { error: String(e) });+ log.warn('user_stop cancellation: inputQueue.end threw', { error: String(e) });}try {cancelledQuery.close();} catch (e) {- log.warn('user_stop continuation cancellation: q.close threw', { error: String(e) });+ log.warn('user_stop cancellation: q.close threw', { error: String(e) });}runningBackgroundTasks.clear();terminalBackgroundTaskIds.clear();turnInFlight = false;}- const hasUnconfirmedWakeTasks = [...runningBackgroundTasks.values()].some((info) => info.wake);- if (- hasUnconfirmedWakeTasks &&- continuationCancellationGeneration !== turnState.generation- ) {- // A successful interrupt without a cancelled claim still leaves- // wake tasks whose stop was rejected or unsupported. Keep the- // product turn idle, but fence their queued auto-continuation- // until the next send installs a fresh Query.- continuationCancellationGeneration = turnState.generation;- continuationCancellationRequiresQueryRebuild = true;- cancelledTailInterruptResultPending = turnInFlight;- log.info('installed cancelled-tail fence for unconfirmed wake tasks after user stop', {- generation: turnState.generation,- });- }} catch (e) {// interrupt 失败 → 无 result 消费标记, 回收防误抑制(同 watchdog)。turnState.interruptRequested = false;@@ -5429,6 +5453,14 @@ export class ClaudeCodeAgent extends BaseAgent {while (idleResumeRebuildGate) {await idleResumeRebuildGate;}+ if (continuationCancellationRequiresQueryRebuild) {+ // Stop may have already closed the old Query while leaving the+ // cancellation rebuild tombstone for the next explicit turn. A+ // rewind preview is also a valid next control action: install an+ // isolated fresh Query first, but do not inject the send-only+ // /compact bridge or start a product turn.+ await rebuildCancelledContinuationQuery(undefined, { queueCompactBridge: false });+ }log.info('previewRewindFiles', { userUuid, sdkSessionId });try {const result = await q.rewindFiles(userUuid, { dryRun: true });@@ -5461,6 +5493,11 @@ export class ClaudeCodeAgent extends BaseAgent {while (idleResumeRebuildGate) {await idleResumeRebuildGate;}+ if (continuationCancellationRequiresQueryRebuild) {+ // See previewRewindFiles: rebuild the fenced Query without the+ // compact bridge so rewindFiles retains its checkpoint semantics.+ await rebuildCancelledContinuationQuery(undefined, { queueCompactBridge: false });+ }log.info('commitRewindFiles ▶', { userUuid, priorAssistantUuid, sdkSessionId });// ① 立即把文件回滚到 target 时点 (失败 warn + 继续, forkSession=true 兜底)try {