Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
Merge pull request #2131 from MagicLizi/fix/abort-not-clearing-turn-in-flight
Lizie2f591c13c19
diff --cc packages/maker-core/src/agents/claude-code/__tests__/abort-stops-background-tasks.test.tsindex 21c814aa73,8facbe5733..a7709beb00--- 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@@@ -2662,4 -748,64 +2662,64 @@@ describe('ClaudeCodeAgent abort stops bstream.end();await handle.close().catch(() => undefined);});++ it('clears turnInFlight immediately, not after interrupt resolves', async () => {+ const { handle, stream, fakeQuery } = await startSessionWithStream();++ // 模拟 SDK 在 retry backoff 中不立即响应 interrupt(如全池冷却 503)。+ let interruptResolved = false;+ fakeQuery.interrupt.mockImplementation(async () => {+ await new Promise((r) => setTimeout(r, 200));+ interruptResolved = true;+ });++ await handle.send({ type: 'user', content: 'test' });+ stream.emit(assistantText('thinking...'));+ await waitFor(() => handle.isTurnRunning?.() === true, 'turn is running');++ const abortPromise = handle.abort();++ // turnInFlight 应在 interrupt 返回前就已清除。+ await new Promise((r) => setTimeout(r, 10));+ expect(handle.isTurnRunning?.()).toBe(false);+ expect(interruptResolved).toBe(false);++ await abortPromise;++ // interrupt 已 await(带 5s 超时),200ms 延迟应已过。+ expect(interruptResolved).toBe(true);+ expect(fakeQuery.interrupt).toHaveBeenCalled();++ stream.end();+ await handle.close().catch(() => undefined);+ });+- it('calls q.close when interrupt does not respond within timeout', async () => {++ it('clears turnInFlight immediately and closes query when interrupt times out', async () => {+ vi.useFakeTimers();+ try {+ const { handle, stream, fakeQuery } = await startSessionWithStream();++ // interrupt 永远不响应(simulate hung SDK in retry backoff)。+ fakeQuery.interrupt.mockImplementation(() => new Promise(() => {}));++ await handle.send({ type: 'user', content: 'test' });+ stream.emit(assistantText('thinking...'));+ await waitFor(() => handle.isTurnRunning?.() === true, 'turn is running');++ const abortPromise = handle.abort();++ // turnInFlight 应立刻清除。+ await vi.advanceTimersByTimeAsync(10);+ expect(handle.isTurnRunning?.()).toBe(false);+- // 快进到 10s 超时。- await vi.advanceTimersByTimeAsync(11_000);-- expect(fakeQuery.close).toHaveBeenCalled();++ // 快进到 5s 超时。超时后 query 被标记为 cancelled,forward loop 负责收口。++ await vi.advanceTimersByTimeAsync(6_000);++ expect(handle.isTurnRunning?.()).toBe(false);++ stream.end();+ await abortPromise;+ await handle.close().catch(() => undefined);+ } finally {+ vi.useRealTimers();+ }+ });});diff --cc packages/maker-core/src/agents/claude-code/index.tsindex 4983d8cde5,f37f09d1c4..86dc62e003--- a/packages/maker-core/src/agents/claude-code/index.ts+++ b/packages/maker-core/src/agents/claude-code/index.ts@@@ -4600,8 -4254,13 +4605,9 @@@ export class ClaudeCodeAgent extends Balog.warn('send failed after bridge /compact injection: inputQueue.end threw', { error: String(endError) });}canceledBridgeQueries.add(q);- try {- q.close();- } catch (closeError) {- log.warn('send failed after bridge /compact injection: q.close threw', { error: String(closeError) });- }+ recordCanceledQueryClose(q, 'bridge send abandoned');turnInFlight = false;+ sendInAcceptPhase = false;turnState.interruptRequested = false;pendingToolIds.clear();acceptingRebuiltSend = false;@@@ -4947,79 -4618,50 +4956,128 @@@turnState.interruptRequested = true;turnState.interruptGeneration = turnState.generation;}- // 先关 turn-in-flight 再 interrupt, 与 upstream-idle watchdog 同模式。- // SDK retry backoff 的 setTimeout 期间不响应 interrupt(2026-08 实踩,- // OAuth 全池冷却 503 持续重试), 等它返回会让后续 send 被 SESSION_RUNNING- // 永拒。generation 守卫(translator handleResult)保证旧 q 的迟到- // error_during_execution result 被丢弃、不污染新 turn。++ // 先关 turn-in-flight 再 interrupt:SDK retry backoff 期间不响应 interrupt++ // (2026-08 实踩 OAuth 全池冷却 503 持续重试),等它返回会让后续 send 被++ // SESSION_RUNNING 永拒。generation 守卫(translator handleResult)保证旧 q++ // 的迟到 error_during_execution result 被丢弃、不污染新 turn。+ // sendInAcceptPhase 守卫: 并发 send 处于 accept 阶段时, 由 send 自己的+ // finishSendBeforeUserInput 负责清 turnInFlight + emit boundary,+ // abort 不能抢清, 否则 boundary 丢失(review 3541310178)。++ // 快照 turnInFlight 用于后续 close-query 分支判定(下方 foregroundNeedsTerminal++ // 需要旧值)。++ const foregroundWasInFlight = turnInFlight;+ if (!sendInAcceptPhase) {+ turnInFlight = false;+ pendingToolIds.clear();+ }// 用户 Stop 的产品语义 = 本会话所有模型调用停止:先发 stopTask 再 interrupt-- // (同一控制通道按序处理),封掉「interrupt 后任务恰好完成 → task_notification-- // 自动续跑新 turn」的竞态窗口。fire-and-forget,不阻塞 interrupt。- stopRunningWakeBackgroundTasks('user_stop');- const ABORT_INTERRUPT_TIMEOUT_MS = 10_000;++ // (同一控制通道按序处理)。interrupt 用 5s 超时防止 SDK retry backoff 死等;++ // 超时或失败时关 query 让下次 send 走 lazy rebuild。+ const stopRequests = stopRunningWakeBackgroundTasks('user_stop');++ const ABORT_INTERRUPT_TIMEOUT_MS = 5_000;try {- await q.interrupt();+ await Promise.race([+ q.interrupt(),+ new Promise<void>((_, reject) =>+ setTimeout(() => reject(new Error('INTERRUPT_TIMEOUT')), ABORT_INTERRUPT_TIMEOUT_MS),+ ),+ ]);+ // stopTask and interrupt share an ordered control channel: an+ // interrupt ACK guarantees these earlier stop requests have settled,- // so allSettled intentionally has no timeout or extra watchdog.++ // so allSettled intentionally has no extra timeout here.+ const settledStops = await Promise.allSettled(stopRequests.map(({ promise }) => promise));+ const hasRejectedStops = settledStops.some((stop) => stop.status === 'rejected');+ const fulfilledWakeIds = stopRequests+ .filter((_, index) => settledStops[index]?.status === 'fulfilled')+ .map(({ taskId }) => taskId);+ // interrupt ACK authorizes retiring only wake tasks whose stop RPC+ // also succeeded. Rejected stops remain tracked for provider events,+ // preserving their continuation contract instead of creating an+ // unaccounted auto-continue.+ const stoppedClaim = markWakeTasksStopped(fulfilledWakeIds, 'user_stop');+ // 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. A rejected stop is likewise+ // unconfirmed even when a completed notification already removed+ // that task from the local table; the old Query must still be closed+ // to prevent a queued automatic continuation from escaping Stop.+ const cancelledContinuation = stoppedClaim ?? cancelActiveContinuation('user_stop');+ const hasUnconfirmedWakeTasks = [...runningBackgroundTasks.values()].some((info) => info.wake);+ if (cancelledContinuation || hasUnconfirmedWakeTasks || hasRejectedStops) {+ // All cancellation sources share one terminal state: a cancelled+ // continuation claim, an unconfirmed wake task, or a rejected stop+ // 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;++ // 用 Stop 之前的 turnInFlight 快照判定 foreground 是否需要终态。++ // turnInFlight 已被上方立即清除(防 SESSION_RUNNING 死锁),但++ // close-query 分支仍需要旧值决定是否补 boundary。+ canceledBridgeQueries.add(cancelledQuery);+ // 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');++ // foregroundWasInFlight=false and therefore does not get a duplicate.++ if (foregroundWasInFlight) emitTurnBoundary('user_stop_unconfirmed_wake_tasks');+ }+ inputQueue.clear();+ try {+ inputQueue.end();+ } catch (e) {+ log.warn('user_stop cancellation: inputQueue.end threw', { error: String(e) });+ }+ recordCanceledQueryClose(cancelledQuery, 'user_stop cancellation');+ runningBackgroundTasks.clear();+ terminalBackgroundTaskIds.clear();+ turnInFlight = false;+ }} catch (e) {- // interrupt 失败 → 无 result 消费标记, 回收防误抑制(同 watchdog)。- turnState.interruptRequested = false;- log.warn('abort threw', { error: String(e) });+ const errMsg = e instanceof Error ? e.message : String(e);+ if (errMsg === 'INTERRUPT_TIMEOUT') {- // SDK 长时间不响应 interrupt(在 retry backoff 中) → 关 query 防止- // 信号悬挂。旧 q forward loop 随后按 U2 兜底收口, 事件循环自然终止。++ // SDK 长时间不响应 interrupt(在 retry backoff 中) → 关 query 让++ // 下次 send 走 lazy rebuild。+ log.warn('interrupt timed out during user stop — closing query', {+ sdkSessionId,+ });++ const cancelledContinuation = cancelActiveContinuation('user_stop');++ if (cancelledContinuation) {++ retireContinuationTasks(cancelledContinuation);++ emitCancelledContinuationBoundary(cancelledContinuation, 'user_stop');++ }++ continuationCancellationGeneration = turnState.generation;++ continuationCancellationRequiresQueryRebuild = true;++ canceledBridgeQueries.add(q);++ inputQueue.clear();+ try {- q.close();- } catch (closeError) {- log.warn('q.close after interrupt timeout threw', {- error: String(closeError),- });++ inputQueue.end();++ } catch (ee) {++ log.warn('user_stop cancellation: inputQueue.end threw', { error: String(ee) });+ }++ recordCanceledQueryClose(q, 'user_stop interrupt timeout');++ runningBackgroundTasks.clear();++ terminalBackgroundTaskIds.clear();++ turnInFlight = false;+ } else {- // interrupt 真正抛错(非超时), 回收标记防误抑制(同 watchdog)。++ // interrupt 真正抛错(非超时),回收标记防误抑制(同 watchdog)。+ turnState.interruptRequested = false;+ log.warn('abort threw', { error: String(e) });+ }}},