Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix: 修复中断自动重连只执行一次并增加重试上限 (#1552)
Dash3dc1a1059b58
diff --git a/apps/desktop/src/main/__tests__/interruptedContinuationContract.test.ts b/apps/desktop/src/main/__tests__/interruptedContinuationContract.test.tsindex bf5d5aeded..971d7517c2 100644--- a/apps/desktop/src/main/__tests__/interruptedContinuationContract.test.ts+++ b/apps/desktop/src/main/__tests__/interruptedContinuationContract.test.ts@@ -81,6 +81,15 @@ describe('interrupted continuation enqueue contract', () => {expect(scheduleEnd).toBeGreaterThan(scheduleStart);const scheduleHook = registerSource.slice(scheduleStart, scheduleEnd);expect(scheduleHook).not.toMatch(/clearSchedulerAutoResumePending\s*\(/);+ expect(scheduleHook).toMatch(/\(attempt\)\s*=>\s*\{\s*return\s*\(async/);+ expect(scheduleHook).not.toMatch(/void\s*\(async\s*\(\)\s*=>/);++ expect(registerSource).toMatch(/getAutoResumeDeferredOwner\(session\.id\)/);+ const ownerDiscardedStart = registerSource.indexOf('onResumableTurnErrorDiscarded:');+ const ownerDiscardedEnd = registerSource.indexOf('onResumableTurnError:', ownerDiscardedStart);+ expect(registerSource.slice(ownerDiscardedStart, ownerDiscardedEnd)).toMatch(+ /deferredOwner:\s*options\.owner/,+ );const dispatchedStart = registerSource.indexOf('onDispatchedUserTurn:');const dispatchedEnd = registerSource.indexOf('noteSessionClearBoundary', dispatchedStart);@@ -88,10 +97,10 @@ describe('interrupted continuation enqueue contract', () => {expect(dispatchedEnd).toBeGreaterThan(dispatchedStart);const dispatchedHook = registerSource.slice(dispatchedStart, dispatchedEnd);expect(dispatchedHook).toMatch(- /!inputCoordinator\.isAutoResumePending\(sessionId\)/,+ /attemptToken !== null/,);expect(dispatchedHook).toMatch(- /clearSchedulerAutoResumePending\(sessionId, item\.origin\.runId\)/,+ /clearSchedulerAutoResumePending\(sessionId, item\.origin\.runId, attemptToken\)/,);const discardedStart = registerSource.indexOf('onDiscardedQueuedMessage:');@@ -100,17 +109,22 @@ describe('interrupted continuation enqueue contract', () => {expect(discardedEnd).toBeGreaterThan(discardedStart);const discardedHook = registerSource.slice(discardedStart, discardedEnd);expect(discardedHook).toMatch(- /settleUndispatchedAutoResumeOutcome\(sessionId, item\)/,+ /settleUndispatchedInterruptedAutoResume\(sessionId, item\)/,);expect(discardedHook).toMatch(/finalizeUndispatchedClaimedRetry\(sessionId, item, ['"]cancelled['"]\)/,);expect(discardedHook).toMatch(- /interruptedTurnAutoResumeGuard\.noteResumeSendFailed\(sessionId\)/,+ /schedulerQueuedPromptDiscardWatchers/,);- expect(discardedHook).toMatch(- /notifySchedulerAutoResumeFailed\(sessionId, item\.origin\.runId\)/,+ const discardedSettleIndex = discardedHook.indexOf(+ 'settleUndispatchedInterruptedAutoResume(sessionId, item)',);+ const discardedFinalizeIndex = discardedHook.indexOf(+ "finalizeUndispatchedClaimedRetry(sessionId, item, 'cancelled')",+ );+ expect(discardedSettleIndex).toBeGreaterThan(-1);+ expect(discardedFinalizeIndex).toBeGreaterThan(discardedSettleIndex);const settleStart = registerSource.indexOf('function settleUndispatchedAutoResumeOutcome(');const settleEnd = registerSource.indexOf('\n}\n', settleStart);@@ -118,22 +132,48 @@ describe('interrupted continuation enqueue contract', () => {expect(settleEnd).toBeGreaterThan(settleStart);const settleHelper = registerSource.slice(settleStart, settleEnd);expect(settleHelper).toMatch(- /autoResumeBookkeeping\.isPendingOutcomeClientId\(sessionId, item\.clientId\)/,+ /autoResumeBookkeeping\.settleOutcomeForClient\(/,);expect(settleHelper).toMatch(- /autoResumeBookkeeping\.settleOutcome\(sessionId, ['"]failed['"]\)/,+ /item\.clientId/,+ );++ const interruptedSettleStart = registerSource.indexOf(+ 'function settleUndispatchedInterruptedAutoResume(',+ );+ const interruptedSettleEnd = registerSource.indexOf('\n}\n', interruptedSettleStart);+ expect(interruptedSettleStart).toBeGreaterThan(-1);+ expect(interruptedSettleEnd).toBeGreaterThan(interruptedSettleStart);+ const interruptedSettleHelper = registerSource.slice(+ interruptedSettleStart,+ interruptedSettleEnd,+ );+ expect(interruptedSettleHelper).toMatch(+ /autoResumeBookkeeping\.hasPendingLifecycleForClient\(/,+ );+ expect(interruptedSettleHelper).toMatch(+ /interruptedTurnAutoResumeGuard\.noteResumeSendFailed\(sessionId, attemptToken\)/,);const undispatchedStart = registerSource.indexOf('onUndispatchedUserTurn:');const undispatchedEnd = registerSource.indexOf('onQueueEmptied:', undispatchedStart);expect(undispatchedStart).toBeGreaterThan(-1);expect(undispatchedEnd).toBeGreaterThan(undispatchedStart);- expect(registerSource.slice(undispatchedStart, undispatchedEnd)).toMatch(- /settleUndispatchedAutoResumeOutcome\(sessionId, item\)/,+ const undispatchedHook = registerSource.slice(undispatchedStart, undispatchedEnd);+ expect(undispatchedHook).toMatch(+ /settleUndispatchedInterruptedAutoResume\(sessionId, item\)/,);- expect(registerSource.slice(undispatchedStart, undispatchedEnd)).toMatch(+ expect(undispatchedHook).toMatch(/finalizeUndispatchedClaimedRetry\(sessionId, item, disposition\)/,);+ const undispatchedSettleIndex = undispatchedHook.indexOf(+ 'settleUndispatchedInterruptedAutoResume(sessionId, item)',+ );+ const undispatchedFinalizeIndex = undispatchedHook.indexOf(+ 'finalizeUndispatchedClaimedRetry(sessionId, item, disposition)',+ );+ expect(undispatchedSettleIndex).toBeGreaterThan(-1);+ expect(undispatchedFinalizeIndex).toBeGreaterThan(undispatchedSettleIndex);const finalizeStart = registerSource.indexOf('const finalizeUndispatchedClaimedRetry = (');const finalizeEnd = registerSource.indexOf('\n };', finalizeStart);@@ -151,6 +191,28 @@ describe('interrupted continuation enqueue contract', () => {);});+ it('retires an interrupted attempt owner after both done and terminal error settlement', () => {+ const doneStart = registerSource.indexOf('const doneAttemptToken = event.turnAttemptToken;');+ const doneEnd = registerSource.indexOf('const isSilentStopDone', doneStart);+ expect(doneStart).toBeGreaterThan(-1);+ expect(doneEnd).toBeGreaterThan(doneStart);+ expect(registerSource.slice(doneStart, doneEnd)).toMatch(+ /autoResumeBookkeeping\.settleOutcome\(session\.id, doneAttemptToken, 'failed'\);\s*interruptedTurnAutoResumeGuard\.noteAttemptSettled\(session\.id, doneAttemptToken\);/,+ );++ const errorStart = registerSource.indexOf('const failedAttemptToken = event.turnAttemptToken;');+ const errorEnd = registerSource.indexOf('// 终止型 error 可能没有后续 status/done', errorStart);+ expect(errorStart).toBeGreaterThan(-1);+ expect(errorEnd).toBeGreaterThan(errorStart);+ expect(registerSource.slice(errorStart, errorEnd)).toMatch(+ /autoResumeBookkeeping\.settleOutcome\(session\.id, failedAttemptToken, 'failed'\);\s*interruptedTurnAutoResumeGuard\.noteAttemptSettled\(session\.id, failedAttemptToken\);/,+ );+ });++ it('advertises interval null-clear support for mobile wire compatibility', () => {+ expect(registerSource).toMatch(/supportsScheduleIntervalNullClear:\s*true/);+ });+it('fails a pending scheduler auto-resume before dispatching unrelated user input', () => {const userEnqueueStart = registerSource.indexOf('onUserEnqueue:');const userEnqueueEnd = registerSource.indexOf('onDiscardedQueuedMessage:', userEnqueueStart);diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.tsindex 92e2e6a018..cc5c146a99 100644--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts@@ -154,7 +154,7 @@ describe('maker:event hot path ordering', () => {// 回看窗口要盖住赋值点与所属 if 条件之间的声明/注释(done 分支里 silent-stop// 的 isSilentStopDone 判定 + 设计注释就有 ~500 字符),太窄会把仍在正确分支内的// 赋值误判成"脱离 done 路径"。- const CONTEXT_LOOKBACK = 700;+ const CONTEXT_LOOKBACK = 1_400;const statusContexts = statusIdleAssignments.map((index) =>wireSessionSource.slice(Math.max(0, index - CONTEXT_LOOKBACK), index + 'shouldMarkTurnStatusIdleAfterBroadcast = true;'.length),);diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.tsindex 6db419a76c..dcacc291c4 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts@@ -221,6 +221,9 @@ function createHarness() {NonNullable<AgentInputCoordinatorDeps['persistQueueSnapshot']>>();const onUiRetry = vi.fn<NonNullable<AgentInputCoordinatorDeps['onUiRetry']>>(() => {});+ const onAutomaticEnqueue = vi.fn<+ NonNullable<AgentInputCoordinatorDeps['onAutomaticEnqueue']>+ >(() => {});const onUserEnqueue = vi.fn<NonNullable<AgentInputCoordinatorDeps['onUserEnqueue']>>(() => {});const onDiscardedQueuedMessage = vi.fn<NonNullable<AgentInputCoordinatorDeps['onDiscardedQueuedMessage']>@@ -236,6 +239,7 @@ function createHarness() {steerToAgent,abortSession,onUiRetry,+ onAutomaticEnqueue,onUserEnqueue,onDiscardedQueuedMessage,onRejectedUserTurn,@@ -291,6 +295,7 @@ function createHarness() {emitProjection,projections,onUiRetry,+ onAutomaticEnqueue,onUserEnqueue,onDiscardedQueuedMessage,onRejectedUserTurn,@@ -2111,7 +2116,7 @@ describe('AgentInputCoordinator send transaction', () => {// 重发的是原文, 文本上与普通用户消息无异 —— 所以「用户显式重试」只能靠这个// 回调传出去。hook 侧的渠道回流(turn.reopen)依赖它: 零产出失败恰是上游过载// 最典型的形态, 也最需要把结果接回渠道那条消息。- expect(h.onUiRetry).toHaveBeenCalledWith(sid, expect.any(String), 'manual');+ expect(h.onUiRetry).toHaveBeenCalledWith(sid, expect.any(String), 'manual', undefined);});it('removes unsupported image blocks but preserves GIF and PDF files on retry', async () => {@@ -2462,7 +2467,7 @@ describe('AgentInputCoordinator send transaction', () => {expect(h.onUiRetry).not.toHaveBeenCalled();await h.coordinator.retryLastError(sid);await flush();- expect(h.onUiRetry).toHaveBeenCalledWith(sid, expect.any(String), 'manual');+ expect(h.onUiRetry).toHaveBeenCalledWith(sid, expect.any(String), 'manual', undefined);expect(h.onUiRetry).toHaveBeenCalledTimes(1);}});@@ -2486,7 +2491,7 @@ describe('AgentInputCoordinator send transaction', () => {await h.coordinator.retryLastError(sid);await flush();- expect(h.onUiRetry).toHaveBeenCalledWith(sid, expect.any(String), 'manual');+ expect(h.onUiRetry).toHaveBeenCalledWith(sid, expect.any(String), 'manual', undefined);expect(h.onUserEnqueue).not.toHaveBeenCalled();});@@ -6245,13 +6250,25 @@ describe('AgentInputCoordinator scheduler 排队心跳(撞忙排队桥)', () =>expect(bySchedule('sch-C')).toBe(false);});- it('drain 派发把 scheduler origin 透传进 sendOpts(orca/无 origin 项不透传)', async () => {+ it('drain 派发把自动来源写入持久化 metadata,仅 scheduler 进入 turn origin', async () => {const h = createHarness();h.coordinator.enqueue('s-sched', makeItem('c1', 'hb', { origin: schedulerOrigin('sch-1') }));await flush();const schedSendOpts = h.sendToAgent.mock.calls.at(-1)?.[3] as { origin?: unknown };expect(schedSendOpts.origin).toEqual(schedulerOrigin('sch-1'));+ const orcaOrigin = { kind: 'orca', senderLabel: 'Lead', displayText: 'hello' } as const;+ const hOrca = createHarness();+ hOrca.coordinator.enqueue('s-orca', makeItem('c-orca', 'orca input', { origin: orcaOrigin }));+ await flush();+ const orcaSendOpts = hOrca.sendToAgent.mock.calls.at(-1)?.[3] as {+ origin?: unknown;+ persistUserMessage?: { origin?: unknown };+ };+ expect(orcaSendOpts.origin).toBeUndefined();+ expect(orcaSendOpts.persistUserMessage?.origin).toEqual(orcaOrigin);+ expect(hOrca.onUserEnqueue, 'Orca 自动输入不应被当成人工接管').not.toHaveBeenCalled();+// 无 origin 的普通输入不透传(独立 harness:上面的派发已把全局 running 翻 true)。const h2 = createHarness();h2.coordinator.enqueue('s-plain', makeItem('c2', 'plain user input'));@@ -6861,9 +6878,14 @@ describe('AgentInputCoordinator 中断自动续跑', () => {expect.objectContaining({ clientId: 'q-sched', origin: item.origin }),);- await expect(h.coordinator.autoRetryLastError(sid)).resolves.toBe('resumed');+ await expect(+ h.coordinator.autoRetryLastError(sid, TAKEOVER_INFO.sessionTotal),+ ).resolves.toBe('resumed');await flush();expect(h.sendToAgent.mock.calls[1]?.[3]?.origin).toEqual(item.origin);+ // Scheduler 的自动续跑已有专属 waiter;不能触发通用自动入队回调,否则+ // register.ts 会把当前 waiter 当成被新输入作废,导致 scheduler retry 只执行一次。+ expect(h.onAutomaticEnqueue).not.toHaveBeenCalled();});it('用户接管会撤销已经离队但尚未派发的 scheduler 自动续跑', async () => {@@ -6885,7 +6907,9 @@ describe('AgentInputCoordinator 中断自动续跑', () => {// maker-core 已建立 reservation,vendor dispatch 仍未发生。const persistGate = deferred<Record<string, never>>();mocks.createMessage.mockImplementationOnce(() => persistGate.promise);- await expect(h.coordinator.autoRetryLastError(sid)).resolves.toBe('resumed');+ await expect(+ h.coordinator.autoRetryLastError(sid, TAKEOVER_INFO.sessionTotal),+ ).resolves.toBe('resumed');await vi.waitFor(() => expect(mocks.createMessage).toHaveBeenCalledTimes(2));const userItem = makeItem('q-user', 'take over');@@ -6922,7 +6946,9 @@ describe('AgentInputCoordinator 中断自动续跑', () => {// 模拟另一个 turn 占用会话:自动 Continue 已入队,但尚未离队派发。h.setRunning(true);- await expect(h.coordinator.autoRetryLastError(sid)).resolves.toBe('resumed');+ await expect(+ h.coordinator.autoRetryLastError(sid, TAKEOVER_INFO.sessionTotal),+ ).resolves.toBe('resumed');await flush();expect(latestProjection(h.projections).pendingQueue).toEqual([expect.objectContaining({ autoResume: true, origin: schedulerItem.origin }),@@ -7014,7 +7040,9 @@ describe('AgentInputCoordinator 中断自动续跑', () => {h.setHasAssistantProgressAfter(async () => true);await failAfterDispatch(h, sid);- await expect(h.coordinator.autoRetryLastError(sid)).resolves.toBe('resumed');+ await expect(+ h.coordinator.autoRetryLastError(sid, TAKEOVER_INFO.sessionTotal),+ ).resolves.toBe('resumed');await flush();expect(h.sendToAgent).toHaveBeenCalledTimes(2);@@ -7024,11 +7052,231 @@ describe('AgentInputCoordinator 中断自动续跑', () => {});// autoResume 必须透到落库参数:renderer 靠它隐藏气泡,host 靠它跳过额度充值。expect(h.sendToAgent.mock.calls[1]?.[3]?.persistUserMessage?.autoResume).toBe(true);- expect(h.onUiRetry).toHaveBeenCalledWith(sid, expect.any(String), 'auto');+ expect(h.onUiRetry).toHaveBeenCalledWith(+ sid,+ expect.any(String),+ 'auto',+ TAKEOVER_INFO.sessionTotal,+ );// 自动补发不冒充人类动作(userSendAt 是「人最近发过消息」的语义)。expect(mocks.touchUserSendInDb).toHaveBeenCalledTimes(1);});+ it('自动续跑等待 Codex cleanup 窗口后仍在 3 次上限处停止重试', async () => {+ vi.useFakeTimers();+ const h = createHarness();+ const sid = 'auto-retry-session-running-budget';+ h.setResumableTurnErrorTakeover(TAKEOVER_INFO);+ h.setHasAssistantProgressAfter(async () => true);+ await failAfterDispatch(h, sid);+ h.sendToAgent.mockImplementation(async () =>+ hostSendFailure('SESSION_RUNNING', '[SESSION_RUNNING] Session is already running a turn'));++ await expect(+ h.coordinator.autoRetryLastError(sid, TAKEOVER_INFO.sessionTotal),+ ).resolves.toBe('resumed');+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);++ // Codex reconnect-stalled 的两次 interrupt ACK 各最多等待 10s;不能在+ // 500ms 内把这条仍可恢复的自动续跑判成失败。+ await vi.advanceTimersByTimeAsync(9_999);+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);++ await vi.advanceTimersByTimeAsync(1);+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(3);++ await vi.advanceTimersByTimeAsync(9_999);+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(3);++ await vi.advanceTimersByTimeAsync(1);+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(4);+ expect(h.onDiscardedQueuedMessage).toHaveBeenCalledWith(+ sid,+ expect.objectContaining({ autoResume: true }),+ );+ expect(latestProjection(h.projections).pendingQueue).toEqual([]);++ await vi.advanceTimersByTimeAsync(2_000);+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(4);+ });++ it('自动续跑耗尽后唤醒其后的 scheduler 队列尾部', async () => {+ vi.useFakeTimers();+ const h = createHarness();+ const sid = 'auto-retry-budget-drains-scheduler-tail';+ h.setResumableTurnErrorTakeover(TAKEOVER_INFO);+ h.setHasAssistantProgressAfter(async () => true);+ await failAfterDispatch(h, sid);++ let busyAttempts = 0;+ h.sendToAgent.mockImplementation(async (_sessionId, message) => {+ const isContinuePrompt =+ message === CONTINUE_AFTER_ERROR_PROMPT ||+ (typeof message !== 'string' && message.content === CONTINUE_AFTER_ERROR_PROMPT);+ if (isContinuePrompt) {+ busyAttempts += 1;+ return hostSendFailure('SESSION_RUNNING', '[SESSION_RUNNING] Session is already running a turn');+ }+ return sendSuccess('scheduler-tail');+ });++ // Keep the auto-resume at the head while the provider is busy, then queue+ // a scheduler message behind it. Once the provider reports idle, the host+ // still returns SESSION_RUNNING for three dispatch races; the third busy+ // result removes only the auto item, so the remaining scheduler item must+ // still be dispatched.+ h.setRunning(true);+ await expect(+ h.coordinator.autoRetryLastError(sid, TAKEOVER_INFO.sessionTotal),+ ).resolves.toBe('resumed');+ await flush();+ h.coordinator.enqueue(sid, makeItem('q-scheduler-tail', 'next heartbeat', {+ origin: {+ kind: 'scheduler',+ scheduleId: 'sch-tail',+ scheduleName: 'Tail',+ runId: 'run-tail',+ },+ }));+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);++ h.setRunning(false);+ await vi.advanceTimersByTimeAsync(10_000);+ await flush();+ expect(busyAttempts).toBe(1);+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);++ await vi.advanceTimersByTimeAsync(10_000);+ await flush();+ expect(busyAttempts).toBe(2);+ expect(h.sendToAgent).toHaveBeenCalledTimes(3);++ await vi.advanceTimersByTimeAsync(10_000);+ await flush();++ expect(busyAttempts).toBe(3);+ expect(h.sendToAgent).toHaveBeenCalledTimes(5);+ expect(h.sendToAgent.mock.calls[4]?.[1]).toEqual({+ type: 'user',+ content: 'next heartbeat',+ });+ expect(latestProjection(h.projections).pendingQueue).toEqual([]);+ });++ it('live busy 挡住自动续跑时使用 10s fallback,terminal 边界仍立即唤醒', async () => {+ vi.useFakeTimers();+ const h = createHarness();+ const sid = 'auto-retry-live-busy-policy';+ h.setResumableTurnErrorTakeover(TAKEOVER_INFO);+ h.setHasAssistantProgressAfter(async () => true);+ await failAfterDispatch(h, sid);++ h.setRunning(true);+ await expect(+ h.coordinator.autoRetryLastError(sid, TAKEOVER_INFO.sessionTotal),+ ).resolves.toBe('resumed');+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);++ await vi.advanceTimersByTimeAsync(9_999);+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);++ // provider cleanup 的终态先到时,事件路径立即 drain,不必等 10s fallback。+ h.setRunning(false);+ h.coordinator.onTurnEvent(sid, 'done');+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);++ await vi.advanceTimersByTimeAsync(10_000);+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);+ });++ it('用户消息接管 auto-resume 队首后把 10s timer 换回 250ms policy', async () => {+ vi.useFakeTimers();+ const h = createHarness();+ const sid = 'auto-retry-policy-replaced-by-user';+ h.setResumableTurnErrorTakeover(TAKEOVER_INFO);+ h.setHasAssistantProgressAfter(async () => true);+ await failAfterDispatch(h, sid);++ h.setRunning(true);+ await expect(+ h.coordinator.autoRetryLastError(sid, TAKEOVER_INFO.sessionTotal),+ ).resolves.toBe('resumed');+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);++ h.coordinator.enqueue(sid, makeItem('q-user-takeover', 'take over now'));+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);+ h.setRunning(false);+ await vi.advanceTimersByTimeAsync(249);+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);++ await vi.advanceTimersByTimeAsync(1);+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);+ expect(h.sendToAgent.mock.calls[1]?.[1]).toEqual({+ type: 'user',+ content: 'take over now',+ });++ await vi.advanceTimersByTimeAsync(10_000);+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);+ });++ it('队列 move 把普通项移到 auto-resume 前时也切换回 250ms policy', async () => {+ vi.useFakeTimers();+ const h = createHarness();+ const sid = 'auto-retry-policy-replaced-by-move';+ h.setResumableTurnErrorTakeover(TAKEOVER_INFO);+ h.setHasAssistantProgressAfter(async () => true);+ await failAfterDispatch(h, sid);++ h.setRunning(true);+ await expect(+ h.coordinator.autoRetryLastError(sid, TAKEOVER_INFO.sessionTotal),+ ).resolves.toBe('resumed');+ await flush();++ h.coordinator.enqueue(sid, makeItem('q-scheduler-next', 'next heartbeat', {+ origin: {+ kind: 'scheduler',+ scheduleId: 'sch-1',+ scheduleName: '任务 1',+ runId: 'run-1',+ },+ }));+ await flush();+ h.coordinator.move(sid, 'q-scheduler-next', 0);+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);++ h.setRunning(false);+ await vi.advanceTimersByTimeAsync(249);+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);++ await vi.advanceTimersByTimeAsync(1);+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);+ expect(h.sendToAgent.mock.calls[1]?.[1]).toEqual({+ type: 'user',+ content: 'next heartbeat',+ });+ });+it('人工 retryLastError 不打 autoResume(否则会误跳过额度充值)', async () => {const h = createHarness();const sid = 'manual-retry-no-auto-flag';@@ -7043,28 +7291,72 @@ describe('AgentInputCoordinator 中断自动续跑', () => {expect(mocks.touchUserSendInDb).toHaveBeenCalledTimes(2);});- it('零产出时不自动补发,错误横幅与「继续」按钮留给用户', async () => {+ it('自动续跑再次失败后,人工 Retry 会清掉上一轮隐藏标记并重置真人额度', async () => {+ const h = createHarness();+ const sid = 'manual-retry-after-auto-failure';+ h.setResumableTurnErrorTakeover(TAKEOVER_INFO);+ h.setHasAssistantProgressAfter(async () => true);+ await failAfterDispatch(h, sid);++ await expect(+ h.coordinator.autoRetryLastError(sid, TAKEOVER_INFO.sessionTotal),+ ).resolves.toBe('resumed');+ await flush();++ // 自动续跑已经成为当前 active turn,但随后再次在 vendor 侧失败。+ h.setRunning(false);+ h.coordinator.onTurnEvent(sid, 'error', truncationMessage, truncationSignals);+ await flush();+ expect(latestProjection(h.projections).recovery).toEqual(+ expect.objectContaining({+ kind: 'active-turn',+ item: expect.objectContaining({ autoResume: true }),+ }),+ );++ await h.coordinator.retryLastError(sid);+ await flush();++ const persist = h.sendToAgent.mock.calls[2]?.[3]?.persistUserMessage;+ expect(persist?.autoResume).toBeUndefined();+ expect(persist?.autoResumeInfo).toBeUndefined();+ expect(mocks.touchUserSendInDb).toHaveBeenCalledTimes(2);+ });++ it('零产出时自动克隆重发原文,并沿用 autoResume 计数守卫', async () => {const h = createHarness();const sid = 'auto-retry-without-progress';h.setResumableTurnErrorTakeover(TAKEOVER_INFO);h.setHasAssistantProgressAfter(async () => false);await failAfterDispatch(h, sid);- // no-progress 而不是 superseded:这是一次没人接手的真失败,host 据此把横幅还给用户。- await expect(h.coordinator.autoRetryLastError(sid)).resolves.toBe('no-progress');+ await expect(+ h.coordinator.autoRetryLastError(sid, TAKEOVER_INFO.sessionTotal),+ ).resolves.toBe('resumed');await flush();- expect(h.sendToAgent, '不得克隆重发用户原文').toHaveBeenCalledTimes(1);- // 接管成立时横幅是被压住的,所以这一刻 error 仍为 null:把它还给用户是 host 的动作- // (finalizeSuppressedAutoResumeError → abandonAutoResume),outcome='no-progress'- // 正是那个信号。这里连着验完整条链,免得只测一半。- expect(latestProjection(h.projections).error).toBeNull();- h.coordinator.abandonAutoResume(sid, truncationMessage);- await flush();- const projection = latestProjection(h.projections);- expect(projection.error).toBe(truncationMessage);- expect(projection.autoResumePending ?? null).toBeNull();- expect(projection.recovery?.kind).toBe('active-turn');+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);+ expect(h.sendToAgent.mock.calls[1]?.[1]).toEqual({+ type: 'user',+ content: 'original long task',+ });+ expect(h.sendToAgent.mock.calls[1]?.[3]?.persistUserMessage?.autoResume).toBe(true);+ expect(h.onDispatchedUserTurn.mock.calls[1]?.[1]).toEqual(+ expect.objectContaining({+ autoResume: true,+ autoResumeInfo: TAKEOVER_INFO,+ supersedesUserClientId: undefined,+ }),+ );+ expect(h.onUiRetry).toHaveBeenCalledWith(+ sid,+ expect.any(String),+ 'auto',+ TAKEOVER_INFO.sessionTotal,+ );+ expect(h.supersedeRetriedUserTurn).not.toHaveBeenCalled();+ // 自动补发不冒充真人输入,守卫不会被重新充值。+ expect(mocks.touchUserSendInDb).toHaveBeenCalledTimes(1);});it('host 接管时不设 error、只置 autoResumePending(红横幅留给最终失败)', async () => {@@ -7099,7 +7391,9 @@ describe('AgentInputCoordinator 中断自动续跑', () => {await failAfterDispatch(h, sid);expect(latestProjection(h.projections).autoResumePending).toEqual(TAKEOVER_INFO);- await expect(h.coordinator.autoRetryLastError(sid)).resolves.toBe('resumed');+ await expect(+ h.coordinator.autoRetryLastError(sid, TAKEOVER_INFO.sessionTotal),+ ).resolves.toBe('resumed');await flush();const projection = latestProjection(h.projections);@@ -7175,7 +7469,9 @@ describe('AgentInputCoordinator 中断自动续跑', () => {h.coordinator.clearError(sid);await flush();- await expect(h.coordinator.autoRetryLastError(sid)).resolves.toBe('superseded');+ await expect(+ h.coordinator.autoRetryLastError(sid, TAKEOVER_INFO.sessionTotal),+ ).resolves.toBe('superseded');await flush();expect(h.sendToAgent).toHaveBeenCalledTimes(1);});@@ -7211,7 +7507,10 @@ describe('AgentInputCoordinator 中断自动续跑', () => {releasePersist();await flush();- expect(h.onResumableTurnErrorDiscarded).toHaveBeenCalledWith(sid, { surfaceError: false });+ expect(h.onResumableTurnErrorDiscarded).toHaveBeenCalledWith(+ sid,+ expect.objectContaining({ surfaceError: false, owner: expect.any(Object) }),+ );});it('在途重试的刹车:await 读库期间接管态被清(会话关闭)→ 判 superseded,不补发', async () => {@@ -7233,7 +7532,7 @@ describe('AgentInputCoordinator 中断自动续跑', () => {expect(h.coordinator.isAutoResumePending(sid)).toBe(true);const sendCallsBefore = h.sendToAgent.mock.calls.length;- const retry = h.coordinator.autoRetryLastError(sid);+ const retry = h.coordinator.autoRetryLastError(sid, TAKEOVER_INFO.sessionTotal);await flush();// 读库还没回来时会话被关掉 → teardown 清接管态(abandonAutoResume 不带 message)。h.coordinator.abandonAutoResume(sid);@@ -7306,7 +7605,10 @@ describe('AgentInputCoordinator 中断自动续跑', () => {const projection = latestProjection(h.projections);expect(projection.autoResumePending ?? null).toBeNull();expect(projection.error, '不接管就得把横幅还给用户').toBe(truncationMessage);- expect(h.onResumableTurnErrorDiscarded).toHaveBeenCalledWith(sid, { surfaceError: true });+ expect(h.onResumableTurnErrorDiscarded).toHaveBeenCalledWith(+ sid,+ expect.objectContaining({ surfaceError: true, owner: expect.any(Object) }),+ );});it('延后结算:候选窗口里用户自己发了消息 → 不接管、不消耗额度,回落成常规错误', async () => {@@ -7338,7 +7640,10 @@ describe('AgentInputCoordinator 中断自动续跑', () => {expect(projection.autoResumePending ?? null, '用户已接手 → 不该再显示重连').toBeNull();expect(projection.error, '回落成常规错误呈现,让用户自己决定要不要续跑').toBe(truncationMessage);expect(h.onResumableTurnError, '连问都不该问(不消耗额度)').not.toHaveBeenCalled();- expect(h.onResumableTurnErrorDiscarded).toHaveBeenCalledWith(sid, { surfaceError: false });+ expect(h.onResumableTurnErrorDiscarded).toHaveBeenCalledWith(+ sid,+ expect.objectContaining({ surfaceError: false, owner: expect.any(Object) }),+ );});it('退避窗口里用户自己发了消息 → autoRetryLastError 判 superseded(不抢在他前面代发)', async () => {@@ -7356,7 +7661,9 @@ describe('AgentInputCoordinator 中断自动续跑', () => {expect(h.coordinator.isAutoResumePending(sid), 'enqueue 同步撤掉接管态').toBe(false);const sendCallsBefore = h.sendToAgent.mock.calls.length;- await expect(h.coordinator.autoRetryLastError(sid)).resolves.toBe('superseded');+ await expect(+ h.coordinator.autoRetryLastError(sid, TAKEOVER_INFO.sessionTotal),+ ).resolves.toBe('superseded');await flush();expect(h.sendToAgent.mock.calls.length,@@ -7412,7 +7719,10 @@ describe('AgentInputCoordinator 中断自动续跑', () => {rejectPersist(new Error('disk full'));await flush();- expect(h.onResumableTurnErrorDiscarded).toHaveBeenCalledWith(sid, { surfaceError: true });+ expect(h.onResumableTurnErrorDiscarded).toHaveBeenCalledWith(+ sid,+ expect.objectContaining({ surfaceError: true, owner: expect.any(Object) }),+ );expect(h.onResumableTurnError, '落库失败就没有可续跑的目标,不该消耗额度').not.toHaveBeenCalled();});});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/autoResumeBookkeeping.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/autoResumeBookkeeping.test.tsindex 3ff12d0879..4b83778cae 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/autoResumeBookkeeping.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/autoResumeBookkeeping.test.ts@@ -356,6 +356,71 @@ describe('退避排期:必可撤销、必只认自己那次', () => {expect(h.persisted, '旧 completion 不得补落或删除手动 replacement 的错误').toEqual([]);});+ it('tokenized async callback 保持 lease,且业务 finalize 先释放 attempt 也能清自己的 lease', async () => {+ const h = createHarness();+ h.book.beginAttempt('s1', 7);+ h.book.stashSuppressedError('s1', { message: 'old interruption' }, 7);+ let release!: () => void;+ const gate = new Promise<void>((resolve) => { release = resolve; });+ let callbackAttempt!: { isCurrent: () => boolean };++ h.book.schedule('s1', 7, 1_000, async (attempt) => {+ callbackAttempt = attempt;+ await gate;+ expect(attempt.isCurrent()).toBe(true);+ h.book.finalizeSuppressedError('s1', 7, { surfaceBanner: false });+ });++ vi.advanceTimersByTime(1_000);+ await Promise.resolve();+ expect(h.book.hasSchedule('s1')).toBe(true);+ expect(callbackAttempt.isCurrent()).toBe(true);++ release();+ await Promise.resolve();+ await Promise.resolve();+ expect(h.book.hasSchedule('s1')).toBe(false);+ expect(h.persisted).toEqual([{ sessionId: 's1', detail: { message: 'old interruption' } }]);+ });++ it('结算 undispatched outcome 时保留 suppressed-error attempt lease 直到 finalize', () => {+ const h = createHarness();+ h.book.beginAttempt('s1', 7);+ h.book.stashSuppressedError('s1', { message: 'boom' }, 7);+ h.book.registerPendingOutcome('s1', 7, 'retry-1');++ h.book.settleOutcomeForClient('s1', 7, 'retry-1', 'failed');+ expect(h.book.isCurrentAttempt('s1', 7), 'suppressed owner 仍在时不能提前删 attempt').toBe(true);++ h.book.finalizeSuppressedError('s1', 7, { surfaceBanner: true });+ expect(h.book.isCurrentAttempt('s1', 7)).toBe(false);+ expect(h.persisted).toEqual([{ sessionId: 's1', detail: { message: 'boom' } }]);+ expect(h.outcomes).toEqual([{ sessionId: 's1', clientId: 'retry-1', outcome: 'failed' }]);+ });++ it('deferred owner 精确 flush 不会被 newer attempt 拦截或误删', () => {+ const h = createHarness();+ const oldOwner = { generation: 3, clientId: 'old-turn' };+ const newOwner = { generation: 4, clientId: 'new-turn' };+ h.book.stashSuppressedError('s1', { message: 'deferred error' }, null, oldOwner);+ h.book.beginAttempt('s1', 9);++ expect(h.book.flushSuppressedError('s1', { deferredOwner: newOwner })).toBe(false);+ expect(h.book.hasSuppressedError('s1')).toBe(true);+ expect(h.book.flushSuppressedError('s1', { deferredOwner: oldOwner })).toBe(true);+ expect(h.persisted).toEqual([{ sessionId: 's1', detail: { message: 'deferred error' } }]);+ });++ it('释放 suppressed error 后回收无其它 owner 的 current attempt', () => {+ const h = createHarness();+ h.book.beginAttempt('s1', 11);+ h.book.stashSuppressedError('s1', { message: 'boom' }, 11);++ expect(h.book.flushSuppressedError('s1', { attemptToken: 11 })).toBe(true);+ h.book.stashSuppressedError('s1', { message: 'next' });+ expect(h.book.flushSuppressedError('s1')).toBe(true);+ });+it('clearError / 新输入接管 → 同步释放旧 Island filter,已 fire 回调随即失效', async () => {const h = createHarness();h.book.stashSuppressedError('s1', { message: 'old interruption' });diff --git a/apps/desktop/src/main/maker-ipc/__tests__/interruptedTurnAutoResume.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/interruptedTurnAutoResume.test.tsindex 687bf646dd..1d406c0205 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/interruptedTurnAutoResume.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/interruptedTurnAutoResume.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest';import {INTERRUPTED_TURN_MAX_CONSECUTIVE_ATTEMPTS,+ INTERRUPTED_TURN_MAX_EPISODE_ATTEMPTS,InterruptedTurnAutoResumeGuard,interruptedTurnResumeDelayMs,isAutoResumeUserMessage,@@ -281,8 +282,8 @@ function runInterruptedTurn(g: ReturnType<typeof createGuard>): number {return g.now();}-// 额度模型的核心不变量:连续 N 次重连都没让模型产出任何东西 → 停下等人;中间只要有-// 一次产出就归零重来;会话累计不设上限(只要任务还在推进就一直自愈)。+// 额度模型的核心不变量:连续 N 次零产出会停;即使每次都有一点产出,同一次真人介入+// 之后也受 episode 硬上限保护,绝不无限自动循环。describe('InterruptedTurnAutoResumeGuard', () => {it('grants up to MAX consecutive attempts, then stops and waits for the user', () => {const g = createGuard();@@ -297,20 +298,25 @@ describe('InterruptedTurnAutoResumeGuard', () => {}expect(g.guard.onInterruptedTurn(SID, runInterruptedTurn(g))).toEqual({action: 'exhausted',+ reason: 'consecutive',consecutiveAttempts: INTERRUPTED_TURN_MAX_CONSECUTIVE_ATTEMPTS,+ episodeAttempts: INTERRUPTED_TURN_MAX_CONSECUTIVE_ATTEMPTS,});});it('model output resets the consecutive counter (但会话累计只增)', () => {const g = createGuard();+ let lastAttemptToken = 0;// 先耗光连续额度。for (let i = 0; i < INTERRUPTED_TURN_MAX_CONSECUTIVE_ATTEMPTS; i++) {- expect(g.guard.onInterruptedTurn(SID, runInterruptedTurn(g)).action).toBe('resume');+ const granted = g.guard.onInterruptedTurn(SID, runInterruptedTurn(g));+ expect(granted.action).toBe('resume');+ if (granted.action === 'resume') lastAttemptToken = granted.attemptToken;}expect(g.guard.onInterruptedTurn(SID, runInterruptedTurn(g)).action).toBe('exhausted');// 连上了、模型有输出 → 归零,又能再来一整轮。- g.guard.noteProgress(SID);+ expect(g.guard.noteProgress(SID, lastAttemptToken)).toBe(true);const decision = g.guard.onInterruptedTurn(SID, runInterruptedTurn(g));expect(decision.action).toBe('resume');if (decision.action === 'resume') {@@ -320,17 +326,23 @@ describe('InterruptedTurnAutoResumeGuard', () => {}});- it('会话累计不设上限:只要有进展就能一直自愈', () => {+ it('即使每次都有进展,同一人工介入周期仍受硬总上限保护', () => {const g = createGuard();- let total = 0;- // 反复「重连一次 → 有产出」十轮,远超单轮上限,不该出现 exhausted。- for (let round = 0; round < 10; round++) {+ for (let round = 0; round < INTERRUPTED_TURN_MAX_EPISODE_ATTEMPTS; round++) {const decision = g.guard.onInterruptedTurn(SID, runInterruptedTurn(g));expect(decision.action).toBe('resume');- total += 1;- if (decision.action === 'resume') expect(decision.sessionTotal).toBe(total);- g.guard.noteProgress(SID);+ if (decision.action === 'resume') {+ expect(decision.episodeAttempt).toBe(round + 1);+ expect(decision.sessionTotal).toBe(round + 1);+ expect(g.guard.noteProgress(SID, decision.attemptToken)).toBe(true);+ }}+ expect(g.guard.onInterruptedTurn(SID, runInterruptedTurn(g))).toEqual({+ action: 'exhausted',+ reason: 'episode',+ consecutiveAttempts: 0,+ episodeAttempts: INTERRUPTED_TURN_MAX_EPISODE_ATTEMPTS,+ });});it('noteProgress 在没有失败计数时是 no-op(热路径每条消息都会调)', () => {@@ -344,12 +356,38 @@ describe('InterruptedTurnAutoResumeGuard', () => {it('真实用户消息也重置连续计数(人工介入是新起点)', () => {const g = createGuard();- for (let i = 0; i < INTERRUPTED_TURN_MAX_CONSECUTIVE_ATTEMPTS; i++) {- g.guard.onInterruptedTurn(SID, runInterruptedTurn(g));+ for (let i = 0; i < INTERRUPTED_TURN_MAX_EPISODE_ATTEMPTS; i++) {+ const decision = g.guard.onInterruptedTurn(SID, runInterruptedTurn(g));+ expect(decision.action).toBe('resume');+ if (decision.action === 'resume') {+ expect(g.guard.noteProgress(SID, decision.attemptToken)).toBe(true);+ }}expect(g.guard.onInterruptedTurn(SID, runInterruptedTurn(g)).action).toBe('exhausted');g.guard.noteUserSend(SID);- expect(g.guard.onInterruptedTurn(SID, runInterruptedTurn(g)).action).toBe('resume');+ const decision = g.guard.onInterruptedTurn(SID, runInterruptedTurn(g));+ expect(decision.action).toBe('resume');+ if (decision.action === 'resume') {+ expect(decision.episodeAttempt).toBe(1);+ expect(decision.attempt).toBe(1);+ }+ });++ it('真人接管后拒绝旧 attempt 的迟到进展', () => {+ const g = createGuard();+ const first = g.guard.onInterruptedTurn(SID, runInterruptedTurn(g));+ expect(first.action).toBe('resume');+ if (first.action !== 'resume') return;++ g.guard.noteUserSend(SID);++ expect(g.guard.noteProgress(SID, first.attemptToken)).toBe(false);+ const next = g.guard.onInterruptedTurn(SID, runInterruptedTurn(g));+ expect(next.action).toBe('resume');+ if (next.action === 'resume') {+ expect(next.attempt).toBe(1);+ expect(next.episodeAttempt).toBe(1);+ }});it('每次重连都带退避,连续重试不被最小间隔掐死', () => {@@ -370,16 +408,116 @@ describe('InterruptedTurnAutoResumeGuard', () => {expect(g.guard.onInterruptedTurn(SID, erroredAt)).toEqual({ action: 'skip', why: 'pending' });});+ it('迟到的旧 status 起始事件不会清掉已排期的自动续跑', () => {+ const g = createGuard();+ const first = g.guard.onInterruptedTurn(SID, runInterruptedTurn(g));+ expect(first.action).toBe('resume');+ if (first.action !== 'resume') throw new Error('expected first resume');++ // terminal error 后 provider 可能补发旧 status(isRunning=true)。它没有 host token,+ // 不能冒领下一次自动续跑的 pending;只有 tokened event / 显式失败路径才能清理。+ g.guard.noteTurnStarted(SID, { clearPending: false });+ expect(g.guard.onInterruptedTurn(SID, g.now())).toEqual({ action: 'skip', why: 'pending' });+ expect(g.guard.noteAttemptEvent(SID, first.attemptToken)).toBe(true);+ });+it('noteResumeSendFailed clears pending so the next error can be decided again', () => {const g = createGuard();- expect(g.guard.onInterruptedTurn(SID, runInterruptedTurn(g)).action).toBe('resume');- g.guard.noteResumeSendFailed(SID);+ const first = g.guard.onInterruptedTurn(SID, runInterruptedTurn(g));+ expect(first.action).toBe('resume');+ if (first.action !== 'resume') throw new Error('expected resume');+ expect(g.guard.noteResumeSendFailed(SID, first.attemptToken)).toBe(true);const again = g.guard.onInterruptedTurn(SID, runInterruptedTurn(g));expect(again.action, '不再卡在 pending').toBe('resume');// 计数不回退(安全方向):失败的那次仍然算一次。if (again.action === 'resume') expect(again.attempt).toBe(2);});+ it('派发失败后 token 失效,后续无 token 的自动 turn 产出仍能重置连续计数', () => {+ const g = createGuard();+ const first = g.guard.onInterruptedTurn(SID, runInterruptedTurn(g));+ expect(first.action).toBe('resume');+ if (first.action !== 'resume') throw new Error('expected first resume');++ expect(g.guard.noteResumeSendFailed(SID, first.attemptToken)).toBe(true);+ expect(g.guard.noteProgress(SID)).toBe(true);+ const next = g.guard.onInterruptedTurn(SID, runInterruptedTurn(g));+ expect(next.action).toBe('resume');+ if (next.action === 'resume') expect(next.attempt).toBe(1);+ });++ it('a tokened provider event clears pending even without status(isRunning=true)', () => {+ const g = createGuard();+ const first = g.guard.onInterruptedTurn(SID, runInterruptedTurn(g));+ expect(first.action).toBe('resume');+ if (first.action !== 'resume') throw new Error('expected first resume');++ expect(g.guard.noteAttemptEvent(SID, first.attemptToken)).toBe(true);+ const second = g.guard.onInterruptedTurn(SID, runInterruptedTurn(g));+ expect(second.action).toBe('resume');+ if (second.action === 'resume') expect(second.attempt).toBe(2);+ });++ it('retires a settled attempt owner before accepting untagged automatic progress', () => {+ const g = createGuard();+ const first = g.guard.onInterruptedTurn(SID, runInterruptedTurn(g));+ expect(first.action).toBe('resume');+ if (first.action !== 'resume') throw new Error('expected first resume');++ expect(g.guard.noteAttemptEvent(SID, first.attemptToken)).toBe(true);+ expect(g.guard.noteAttemptSettled(SID, first.attemptToken)).toBe(true);+ expect(g.guard.noteProgress(SID, first.attemptToken)).toBe(false);+ expect(g.guard.noteProgress(SID)).toBe(true);++ const next = g.guard.onInterruptedTurn(SID, runInterruptedTurn(g));+ expect(next.action).toBe('resume');+ if (next.action === 'resume') expect(next.attempt).toBe(1);+ });++ it('allows consecutive terminal-only failures to consume the budget', () => {+ const g = createGuard();+ const attempts: number[] = [];+ for (let i = 0; i < 3; i += 1) {+ const decision = g.guard.onInterruptedTurn(SID, g.now());+ expect(decision.action).toBe('resume');+ if (decision.action !== 'resume') return;+ attempts.push(decision.attempt);+ // Simulate a provider that reports terminal error directly and never emits status(true).+ g.guard.noteAttemptEvent(SID, decision.attemptToken);+ }+ expect(attempts).toEqual([1, 2, 3]);+ });++ it('ignores a stale tokened event after a newer attempt or user intervention', () => {+ const g = createGuard();+ const first = g.guard.onInterruptedTurn(SID, runInterruptedTurn(g));+ expect(first.action).toBe('resume');+ if (first.action !== 'resume') throw new Error('expected first resume');+ g.guard.noteAttemptEvent(SID, first.attemptToken);++ g.guard.noteUserSend(SID);+ expect(g.guard.noteAttemptEvent(SID, first.attemptToken)).toBe(false);+ const fresh = g.guard.onInterruptedTurn(SID, runInterruptedTurn(g));+ expect(fresh.action).toBe('resume');+ if (fresh.action === 'resume') expect(fresh.attempt).toBe(1);+ });++ it('迟到的旧 attempt 不能清掉当前新 attempt', () => {+ const g = createGuard();+ const first = g.guard.onInterruptedTurn(SID, runInterruptedTurn(g));+ expect(first.action).toBe('resume');+ if (first.action !== 'resume') throw new Error('expected first resume');++ g.guard.noteTurnStarted(SID);+ const second = g.guard.onInterruptedTurn(SID, g.now());+ expect(second.action).toBe('resume');+ if (second.action !== 'resume') throw new Error('expected second resume');++ expect(g.guard.noteResumeSendFailed(SID, first.attemptToken)).toBe(false);+ expect(g.guard.isCurrentAttempt(SID, second.attemptToken)).toBe(true);+ expect(g.guard.noteResumeSendFailed(SID, second.attemptToken)).toBe(true);+ });+it('skips when the user already sent something after the error (绝不插队)', () => {const g = createGuard();const erroredAt = runInterruptedTurn(g);diff --git a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.tsindex d0ba1d9f7f..68060e8d55 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts@@ -233,6 +233,39 @@ describe('maker SEND transaction', () => {);});+ it('persists Orca queue origin without sending the unsupported origin to maker-core', async () => {+ const { deps, session } = createDeps();+ const transaction = createMakerSendTransaction(deps);+ const origin = { kind: 'orca', senderLabel: 'Lead', displayText: 'hello' } as const;++ await transaction.sendToAgentAccepted(+ 'session-1',+ { type: 'user', content: 'orca prompt' },+ undefined,+ {+ messageUuid: 'message-uuid',+ persistUserMessage: {+ clientId: 'client-1',+ content: 'orca prompt',+ delivery: 'turn',+ origin,+ },+ },+ );++ expect(session.send).toHaveBeenCalledWith(+ { type: 'user', content: 'orca prompt' },+ expect.not.objectContaining({ origin }),+ );+ expect(deps.createDbMessage).toHaveBeenCalledWith(+ 'session-1',+ expect.objectContaining({+ agentMeta: expect.objectContaining({ origin }),+ }),+ undefined,+ );+ });+it('threads the autoResume flag into persisted agentMeta', async () => {// 中断自动续跑补发的「继续」经 coordinator drain 透传 autoResume(见// AgentInputQueuedMessage.autoResume)。它必须落进 agentMeta:renderer 靠它隐藏气泡,@@ -246,12 +279,14 @@ describe('maker SEND transaction', () => {undefined,{messageUuid: 'message-uuid',+ turnAttemptToken: 7,persistUserMessage: {clientId: 'client-1',content: 'continue',sdkSessionId: 'sdk-1',delivery: 'turn',autoResume: true,+ autoResumeInfo: { attempt: 1, maxAttempts: 5, sessionTotal: 7 },},},);@@ -263,6 +298,9 @@ describe('maker SEND transaction', () => {}),undefined,);+ expect(+ (deps.getSession('session-1')?.send as ReturnType<typeof vi.fn>).mock.calls[0]?.[1],+ ).toEqual(expect.objectContaining({ turnAttemptToken: 7 }));});it('omits autoResume for ordinary user sends', async () => {diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.tsindex 1e4bc069a9..9edaf80fbf 100644--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts@@ -30,6 +30,7 @@ import { createLogger } from '../logger.js';import { createMessage as createDbMessage } from '../localDb/ipc/messages.js';import { touchUserSendInDb } from '../localDb/ipc/sessions.js';import type { InterruptedTurnErrorSignals } from './interruptedTurnAutoResume.js';+import type { SuppressedTurnErrorOwner } from './autoResumeBookkeeping.js';import type { HostSendFailureCode, HostSendOutcome } from '../maker-host/send-outcome.js';import type {AgentInputCreateOpts,@@ -58,6 +59,14 @@ import { attachSessionReferenceMetadata } from '../../shared/sessionReferenceMetconst log = createLogger('maker-input-coordinator');const SESSION_RUNNING_RETRY_DELAY_MS = 250;+/**+ * Codex 的 reconnect-stalled 清理要等两次 turn/interrupt ACK,每次最多 10s。+ * 自动续跑仍只允许 3 次 SESSION_RUNNING 派发尝试,但退避必须覆盖这段有界+ * cleanup 窗口;终态事件先到时 scheduleDrain 仍会立即放行,不会强制等满该间隔。+ */+const AUTO_RESUME_SESSION_RUNNING_RETRY_DELAY_MS = 10_000;+/** 同一自动续跑项撞上 host busy 时的有界派发次数,防止定时器无穷重入。 */+const MAX_AUTO_RESUME_DISPATCH_ATTEMPTS = 3;/*** 凭证切换等待的兜底重试间隔。与 SESSION_RUNNING(本会话 µs 级竞态,250ms 静默重试)* 不同:挡路的是**其它会话**的长任务,主唤醒靠 onExternalTurnSettled(挡路会话 turn@@ -158,6 +167,8 @@ export interface AgentInputSendOpts {userName?: string;throwOnStartFailure?: boolean;signal?: AbortSignal;+ /** 自动续跑的 runtime turn 归属;只进入 AgentEvent,不写入用户可见文本。 */+ turnAttemptToken?: number;/*** scheduler 排队消息的来源标记(与 maker-core SendOrigin 的 scheduler 变体同构)。* drain 派发时从队列项透传:send 事务把它打到 session.send 的 origin(本轮@@ -182,6 +193,12 @@ export interface AgentInputSendOpts {* 落库 agentMeta.autoResume:renderer 据此隐藏气泡,充值判据据此排除自动消息。*/autoResume?: boolean;+ autoResumeInfo?: AutoResumeInfo;+ /**+ * 仅写入 user 行的 agentMeta,不传给 maker-core。Orca 等自动队列来源没有+ * 对应的 SendOrigin 变体,但仍不能被 host 当成真人输入来给 episode 充值。+ */+ origin?: AgentInputQueuedMessage['origin'];shouldBroadcast?: () => boolean;onPersisting?: () => void;onPersisted?: () => void | Promise<void>;@@ -289,12 +306,10 @@ export interface AgentInputCoordinatorDeps {/*** 一条被 `isAutoResumeDeferred` 按住的 error 最终**没能走到决策**(用户气泡持久化失败等),* host 必须把压住的 error 行补落,否则那次中断在历史里彻底消失(不变量 I2)。- * `surfaceError` 只在这条 error 本身成为最终用户可见失败时为 true;被新输入或另一条- * 技术错误顶替时只补历史,不能再拿旧错误打扰用户。*/onResumableTurnErrorDiscarded?: (sessionId: string,- options: { surfaceError: boolean },+ options: { surfaceError: boolean; owner: SuppressedTurnErrorOwner },) => void;/** 在 vendor dispatch 前读取用户选中的本地/在线会话引用。 */resolveSessionReferences?: (@@ -333,21 +348,15 @@ export interface AgentInputCoordinatorDeps {beforeDispatchUserTurn?: (sessionId: string, item: AgentInputQueuedMessage) => void | Promise<void>;/*** Called when a user row crossed the persistence boundary but never reached- * vendor dispatch. `cancelled` is an explicit user lifecycle boundary- * (Stop/remove/clear/new input); `failed` means the attempted delivery itself- * failed and remains user-visible. Hosts use this to finalize retry ownership- * and discard turn-start side effects that would otherwise leak into a later turn.+ * vendor dispatch. `cancelled` is an explicit user lifecycle boundary;+ * `failed` means the attempted delivery itself failed and remains visible.*/onUndispatchedUserTurn?: (sessionId: string,item: AgentInputQueuedMessage,disposition: 'cancelled' | 'failed',) => void;- /**- * The delivery pipeline rejected this item for a technical/policy reason- * before vendor dispatch. Unlike Stop/remove/clear, this is a real failed- * attempt rather than explicit user cancellation.- */+ /** Technical or policy rejection before vendor dispatch. */onRejectedUserTurn?: (sessionId: string, item: AgentInputQueuedMessage) => void;onAcceptedQueuedMessage?: (sessionId: string, item: AgentInputQueuedMessage) => void | Promise<void>;/**@@ -377,10 +386,14 @@ export interface AgentInputCoordinatorDeps {* 克隆重发原文 —— 那条消息文本上与普通用户消息毫无区别, 从文本无法认出重试意图。* 只靠文本嗅探会让最需要回流的那类失败恰好没有信号。*/- onUiRetry?: (sessionId: string, clientId: string, source: 'manual' | 'auto') => void;+ onUiRetry?: (+ sessionId: string,+ clientId: string,+ source: 'manual' | 'auto',+ attemptToken?: number,+ ) => void;/**- * 用户接管了这个会话(新消息 enqueue、steer 回落为普通 turn,或在自动退避中- * clearError 以继续既有队列)。+ * 用户/上游用一条**新**消息接管了这个会话(enqueue 或 steer 回落为普通 turn)。** hook-control 用它作废该会话的待续跑记账: 会话已经被别的内容推进, 再把结果接回* 渠道那条旧消息只会显示无关输出。判据刻意用**入口**而不是消息文本 ——@@ -388,6 +401,8 @@ export interface AgentInputCoordinatorDeps {* pendingQueue.unshift、不经这两个用户输入入口, 于是不会自我作废。*/onUserEnqueue?: (sessionId: string) => void;+ /** 自动输入推进了会话,但不构成真人介入,也不能重置自动恢复预算。 */+ onAutomaticEnqueue?: (sessionId: string) => void;/*** 派发失败后队列可能已空(项目已从队列移除但未被放回时)回调。* host 用它触发 notifyQueueEmptied, 让 AgentIsland 中因队列非空而延迟的完成事件得到补发。@@ -489,6 +504,8 @@ interface SessionInputState {* 是否仍然有效"的唯一判据(`performRetryLastError` 的 auto 路径据此收手)。*/autoResumePending: AutoResumeInfo | null;+ /** 最新自动接管 attempt;展示态落库后仍保留到 vendor accepted 或明确失败。 */+ autoResumeAttemptToken: number | null;recovery: AgentInputRecovery;drainScheduled: boolean;drainWakeupGeneration: number;@@ -509,6 +526,11 @@ interface SessionInputState {abortReconcileRetryTimer: ReturnType<typeof setTimeout> | null;sessionRunningRetryTimer: ReturnType<typeof setTimeout> | null;sessionRunningRetryGeneration: number | null;+ /** 当前 retry timer 绑定的队首/compact owner;队首变化时必须替换 timer policy。 */+ sessionRunningRetryOwnerKey: string | null;+ sessionRunningRetryDelayMs: number | null;+ /** 保护新 generation 的 timer 不被旧 generation 的迟到 callback 清掉。 */+ sessionRunningRetryToken: symbol | null;/*** 发送撞上 CREDENTIAL_SWITCH_BUSY 后的可见等待态:队首保留,挡路会话 turn 结束* (onExternalTurnSettled)或兜底定时器触发自动重发。clientId 绑定等待中的那条@@ -526,6 +548,16 @@ interface SessionInputState {generation: number;}+interface PendingAutoResumeRecovery {+ sessionId: string;+ stateRef: SessionInputState;+ recovery: Extract<AgentInputRecovery, { kind: 'active-turn' }>;+ error: string | null;+ stickyError: string | null;+ autoResumeInfo: AutoResumeInfo | null;+ attemptToken: number;+}+function createInitialInputState(generation = 0): SessionInputState {return {pendingQueue: [],@@ -542,6 +574,7 @@ function createInitialInputState(generation = 0): SessionInputState {error: null,stickyError: null,autoResumePending: null,+ autoResumeAttemptToken: null,recovery: null,drainScheduled: false,drainWakeupGeneration: 0,@@ -551,6 +584,9 @@ function createInitialInputState(generation = 0): SessionInputState {abortReconcileRetryTimer: null,sessionRunningRetryTimer: null,sessionRunningRetryGeneration: null,+ sessionRunningRetryOwnerKey: null,+ sessionRunningRetryDelayMs: null,+ sessionRunningRetryToken: null,credentialSwitchWait: null,credentialSwitchRetryTimer: null,credentialSwitchRetryGeneration: null,@@ -670,6 +706,12 @@ function isSchedulerOriginItem(item: AgentInputQueuedMessage | null | undefined)return item?.origin?.kind === 'scheduler';}+/** Orca and scheduler inputs are automation, not a fresh human intervention. */+function isAutomaticOriginItem(item: AgentInputQueuedMessage | null | undefined): boolean {+ const kind = item?.origin?.kind;+ return kind === 'scheduler' || kind === 'orca';+}+function isUiContinuationItem(item: AgentInputQueuedMessage): boolean {return !isSchedulerOriginItem(item) && item.originalSyntheticTrigger === 'continue';}@@ -725,6 +767,14 @@ export class AgentInputCoordinator {private readonly restoreAttempted = new Set<string>();private readonly queueRestorePromises = new Map<string, Promise<void>>();private readonly lastQueueSnapshotJson = new Map<string, string>();+ /**+ * 自动重试项在真正 vendor dispatch 前仍可被 Stop / 新消息 / ghost block 丢弃。+ * 这段窗口里 `performRetryLastError` 已清掉原 recovery,按 clone clientId 暂存回滚信息,+ * 并用 stateRef 防止 clearSession 后迟到的旧结果复活新上下文。+ */+ private readonly pendingAutoResumeRecoveries = new Map<string, PendingAutoResumeRecovery>();+ /** transient busy 期间同一 auto item 已尝试过的派发次数。 */+ private readonly autoResumeDispatchAttempts = new Map<string, number>();constructor(private readonly deps: AgentInputCoordinatorDeps) {}@@ -1041,16 +1091,19 @@ export class AgentInputCoordinator {// 让消费方按 clientId 做权威归属(见 deps.onUiRetry 的说明)。// (错误横幅那条走 retryLastError, 压根不经本入口。)const schedulerOrigin = isSchedulerOriginItem(item);+ const automaticOrigin = isAutomaticOriginItem(item);if (!schedulerOrigin) {// 自动续跑可能已经从 pendingQueue 进入 activeTurn、但仍卡在持久化或其它// pre-vendor await。用户此时接管不能只作废 host waiter:那会让隐藏 Continue// 继续派发、而新输入排在它后面。复用 Stop 的 generation 取消边界,先确认// 旧续跑已被 coordinator 丢弃,再发布用户接管信号。- this.cancelPreparedSchedulerAutoResume(sessionId, state);+ this.cancelPreparedAutoResume(sessionId, state);}if (isUiContinuationItem(item)) {this.deps.onUiRetry?.(sessionId, item.clientId, 'manual');- } else if (!schedulerOrigin) {+ } else if (automaticOrigin && !schedulerOrigin) {+ this.deps.onAutomaticEnqueue?.(sessionId);+ } else if (!automaticOrigin) {this.deps.onUserEnqueue?.(sessionId);}if (!schedulerOrigin) {@@ -1058,6 +1111,7 @@ export class AgentInputCoordinator {// Scheduler 只是同一串行队列里的自动输入,不代表用户接手,不能取消正在退避的// 自动续跑;它会保持 FIFO,等当前恢复生命周期收口后再派发。state.autoResumePending = null;+ state.autoResumeAttemptToken = null;markPendingTerminalSupersededByUser(state.activeTurn);}// 崩溃恢复暂停队列的死锁解除(2026-07-14):恢复暂停只防"重启后自动替用户@@ -1098,7 +1152,7 @@ export class AgentInputCoordinator {// 入队若 bump 它,接下来 10 分钟内同会话其它心跳会被误当"用户正在远程控制"// 而静默顺延(PR #972 review P2)。侧栏排序的 bump 语义保留在派发时刻 ——// runner 的 accepted 回调按直发路径同款调 touchUserSendInDb(ctx.firedAt)。- if (item.origin?.kind !== 'scheduler') {+ if (!automaticOrigin) {this.touchUserSend(sessionId, opts?.sendAtMs);}// 视觉连续性: 当这条入队后立即可派发(agent 空闲、队列此前为空、无暂停/锁/恢复@@ -1123,7 +1177,7 @@ export class AgentInputCoordinator {// 手动 /compact 是用户接管,与 composer 新消息同语义。先撤掉尚未跨过// vendor dispatch 的隐藏 scheduler 续跑,再让 host 终止对应 run waiter;// 否则 compact 自己的 text/done 可能被旧 schedule run 误收。- this.cancelPreparedSchedulerAutoResume(sessionId, state);+ this.cancelPreparedAutoResume(sessionId, state);this.deps.onUserEnqueue?.(sessionId);// 手动压缩与发送新消息一样,都是用户对失败 turn 的明确后续选择:// 放弃 active-turn retry,让 /compact 在真实 dispatch boundary 空闲时立即执行,@@ -1304,7 +1358,7 @@ export class AgentInputCoordinator {}if (!isSchedulerOriginItem(item)) {- this.cancelPreparedSchedulerAutoResume(sessionId, state);+ this.cancelPreparedAutoResume(sessionId, state);}if (!this.isTurnSteerable(sessionId, state)) {@@ -1573,6 +1627,14 @@ export class AgentInputCoordinator {}this.emit(sessionId);}+ // steer accepted/removed may change the queue head while an older+ // SESSION_RUNNING timer is still armed. Rebind its policy now even though+ // the accepted steer itself keeps the dispatch boundary busy.+ if (accepted.pendingQueue.length > 0 || accepted.pendingCompacts.length > 0) {+ this.scheduleSessionRunningRetry(sessionId, 'steer-accepted');+ } else {+ this.clearSessionRunningRetry(accepted);+ }this.scheduleDrain(sessionId, 'steer-accepted');return true;}@@ -1580,13 +1642,17 @@ export class AgentInputCoordinator {stop(sessionId: string, opts?: { keepQueue?: boolean; pauseQueue?: boolean }): AgentInputProjection {const state = this.getState(sessionId);const preserveQueue = opts?.keepQueue === true;+ this.supersedePendingAutoResumeRecoveries(sessionId);+ this.cancelPreparedAutoResume(sessionId, state);this.abortSteerTransactions(sessionId);this.clearAbortReconcileRetry(state);// Stop 是用户显式收手:凭证切换等待随之取消(保留队列时队首仍在,恢复后会重新进入等待)。this.clearCredentialSwitchWait(state);if (!preserveQueue) {this.clearSessionRunningRetry(state);- for (const item of state.pendingQueue) {+ const droppedQueue = state.pendingQueue;+ state.pendingQueue = [];+ for (const item of droppedQueue) {if (item.origin?.kind === 'orca') {log.warn('dropping queued Orca message on stop', {sessionId,@@ -1597,9 +1663,8 @@ export class AgentInputCoordinator {this.deps.onDiscardedQueuedMessage?.(sessionId, item);}// 整批丢弃的排队消息同样从未派发:从弱网重发幂等窗口遗忘,允许再次入队。- const droppedIds = new Set(state.pendingQueue.map((q) => q.clientId));+ const droppedIds = new Set(droppedQueue.map((q) => q.clientId));state.recentEnqueuedClientIds = state.recentEnqueuedClientIds.filter((id) => !droppedIds.has(id));- state.pendingQueue = [];state.pendingCompacts = [];state.queueInteractionLocks = state.queueInteractionLocks.filter((lockId) =>state.interactionLocksPreservedOnStop.includes(lockId),@@ -1693,12 +1758,16 @@ export class AgentInputCoordinator {* 路上」):* - `resumed`:已补发续跑指令。* - `superseded`:目标已消失(用户自己接手 / 清了会话)——他已经在处理,别再弹横幅。- * - `no-progress`:失败 turn 零产出,按设计不自动续跑 —— 这是一次**没被自愈接手的- * 真失败**,调用方必须把错误回落成常规呈现(横幅 + 「继续任务」),否则它被静默- * 吞掉、用户什么都看不到(copilot review)。+ * - `no-progress`:保留给无法构造安全重试项的异常路径(例如 image-only fallback)。*/- async autoRetryLastError(sessionId: string): Promise<AutoRetryOutcome> {- const { outcome } = await this.performRetryLastError(sessionId, { auto: true });+ async autoRetryLastError(+ sessionId: string,+ attemptToken: number,+ ): Promise<AutoRetryOutcome> {+ const { outcome } = await this.performRetryLastError(sessionId, {+ auto: true,+ attemptToken,+ });return outcome;}@@ -1707,15 +1776,15 @@ export class AgentInputCoordinator {* 三处差别,其余完全共用人工那条已验证过的路径:* - 补发的续跑指令带 `autoResume`(隐藏气泡 / 「已自动继续」分隔线 / 不充值额度,* 见 AgentInputQueuedMessage.autoResume)。- * - **零产出的失败不自动重试**:那条路径是「克隆重发用户原文」,自动做等于让用户- * 的消息被悄悄重发一遍,而 autoResume 又会把气泡隐藏起来——用户视角是自己的- * 消息凭空消失。零产出的 turn 本来什么都没干,手点重试代价很低,留给用户。+ * - 零产出时克隆重发用户原文,并带 `autoResume` 标记。它不会给额度守卫充值,+ * 连续失败次数仍由 host 的 `InterruptedTurnAutoResumeGuard` 负责上限;因此短暂的+ * 首次 admission / 网络失败可以自动穿过,而持续无产出时仍会在上限处停下。* - 不 `touchUserSend`:那个时间戳的语义是「人最近发过消息」(会话列表 / 陈旧判定* 在读它),自动补发不该冒充人类动作。*/private async performRetryLastError(sessionId: string,- opts?: { auto?: boolean },+ opts?: { auto?: boolean; attemptToken?: number },): Promise<{ projection: AgentInputProjection; outcome: AutoRetryOutcome }> {const state = this.getState(sessionId);const recovery = state.recovery;@@ -1727,7 +1796,10 @@ export class AgentInputCoordinator {// 于是定时器到点仍能拿到 recovery,把一条隐藏的续跑指令插到用户那条消息**前面**,// 而「重新连接中」提示早就撤了,用户完全看不到这次代发(greptile P1)。// 接管态是唯一与用户所见一致的判据:它在 enqueue / clearError 时同步清除。- if (opts?.auto && !state.autoResumePending) {+ if (+ opts?.auto &&+ (!state.autoResumePending || state.autoResumeAttemptToken !== opts.attemptToken)+ ) {return { projection: this.getProjection(sessionId), outcome: 'superseded' };}// active-turn recovery 的续跑判定:失败 turn 若已有 assistant 侧产出,重发@@ -1736,13 +1808,17 @@ export class AgentInputCoordinator {// 续跑指令是共享英文常量(带 [UI_ACTION_TRIGGER] 前缀,renderer 渲染时过滤,// 用户只看到任务继续跑,不看到这条合成消息;2026-07-05 产品决策)。let continueItem: AgentInputQueuedMessage | null = null;+ let progressKnown = false;+ const previousAutoResumeInfo = opts?.auto ? state.autoResumePending : null;+ const attemptToken = opts?.auto ? opts.attemptToken ?? null : null;const continueText = CONTINUE_AFTER_ERROR_PROMPT;if (recovery.kind === 'active-turn' && this.deps.hasAssistantProgressAfter) {let hasProgress = false;try {hasProgress = await this.deps.hasAssistantProgressAfter(sessionId, recovery.item.clientId);+ progressKnown = true;} catch {- // 判定失败按零产出处理 —— 回退重发原文,语义与未注入 dep 一致。+ // 自动路径无法确认进度时不重放原文;人工 Retry 保持既有兼容行为。}// await 期间 turn 事件可能已推进状态(clearError / 新 error / 并发 retry):// recovery 不再是同一对象时放弃本次意图,以当前 projection 为准。@@ -1753,7 +1829,12 @@ export class AgentInputCoordinator {// 长到用户在此期间关掉会话 / 自己发消息 —— 而 onSessionClosed 刻意保留 recovery// (它是手动重试入口),所以上面那道 recovery 检查放得过去,自动续跑会往一个已经// 关掉的会话补发消息、把它重新拉起来(codex P1)。teardown 会清接管态,这里据此收手。- if (opts?.auto && !this.getState(sessionId).autoResumePending) {+ const latestAfterProgress = this.getState(sessionId);+ if (+ opts?.auto &&+ (!latestAfterProgress.autoResumePending ||+ latestAfterProgress.autoResumeAttemptToken !== attemptToken)+ ) {return { projection: this.getProjection(sessionId), outcome: 'superseded' };}if (hasProgress) {@@ -1764,16 +1845,10 @@ export class AgentInputCoordinator {text: continueText,originalSyntheticTrigger: 'continue',persistedContent: continueText,- ...(opts?.auto- ? {- autoResume: true,- // 展示信息随消息一起落库,成为「已重新连接」活动行的 param 位与展开- // 详情 —— error 行被压住之后,这是中断原因唯一的用户可见出口。- ...(state.autoResumePending- ? { autoResumeInfo: state.autoResumePending }- : {}),- }- : {}),+ autoResume: opts?.auto ? true : undefined,+ // 人工 Retry 是新的真人介入周期,不能继承上一轮隐藏自动消息的标记;自动路径+ // 则把展示信息随消息落库,成为「已重新连接」活动行的 param 位与展开详情。+ autoResumeInfo: opts?.auto ? previousAutoResumeInfo ?? undefined : undefined,// 附件 / mention 属于原始消息,已在失败 turn 里送达过模型,续跑指令不重带。files: undefined,mentions: undefined,@@ -1794,12 +1869,22 @@ export class AgentInputCoordinator {};}}- // 自动触发只走「续跑」,不走克隆重发(理由见方法注释)。此处提前返回时刻意- // 不动 state.error / recovery:横幅与「继续」按钮原样留给用户。- if (opts?.auto && !continueItem) {- log.debug('auto retry skipped — no assistant progress to continue from', { sessionId });+ // queue-head recovery 表示消息从未跨过 accepted 边界,自动重发仍然可能重复一条+ // 尚未确认是否落库的输入;这条路径继续交给用户。active-turn recovery 则已经落库,+ // 零产出克隆重发是安全的,连续失败次数由 host 守卫负责止损。+ if (+ opts?.auto &&+ (recovery.kind !== 'active-turn' || (!continueItem && !progressKnown))+ ) {+ log.debug('auto retry skipped — progress state is not safe to resend', {+ sessionId,+ recoveryKind: recovery.kind,+ progressKnown,+ });return { projection: this.getProjection(sessionId), outcome: 'no-progress' };}+ const previousError = state.error;+ const previousStickyError = state.stickyError;let retryItem = recovery.kind === 'active-turn' ? recovery.item : null;if (!continueItem@@ -1819,6 +1904,7 @@ export class AgentInputCoordinator {// 接管态在补发这一刻结束:聊天流里的「重新连接中」活动行交棒给落库的// autoResume 行(渲染成「已重新连接」活动行,详情同样可展开)。state.autoResumePending = null;+ if (!opts?.auto) state.autoResumeAttemptToken = null;state.recovery = null;if (recovery.kind === 'active-turn') {let item = continueItem;@@ -1827,11 +1913,11 @@ export class AgentInputCoordinator {item = {...(retryItem ?? recovery.item),clientId,- // retry-supersede:零产出克隆重发 —— 旧 user 行已落库但模型从未收到,- // 本条落库成功后 host 把旧行(与其后的 error 行)软删,历史只留这一条。- // 显式覆盖而非依赖展开继承:recovery.item 可能带着上一轮已消费的旧值- // (连环失败时指向更早的行),窗口必须锚定在本轮被取代的那条上。- supersedesUserClientId: recovery.item.clientId,+ autoResume: opts?.auto ? true : undefined,+ autoResumeInfo: opts?.auto ? previousAutoResumeInfo ?? undefined : undefined,+ // 自动 clone 自身会被 renderer 隐藏,不能再软删原始可见 user 行;人工 Retry+ // 才用可见克隆取代旧行。显式覆盖也避免继承上一轮的隐藏标记。+ supersedesUserClientId: opts?.auto ? undefined : recovery.item.clientId,chatMessage: {...(retryItem ?? recovery.item).chatMessage,clientId,@@ -1839,6 +1925,17 @@ export class AgentInputCoordinator {},};}+ if (opts?.auto && attemptToken !== null) {+ this.pendingAutoResumeRecoveries.set(item.clientId, {+ sessionId,+ stateRef: state,+ recovery,+ error: previousError,+ stickyError: previousStickyError,+ autoResumeInfo: previousAutoResumeInfo,+ attemptToken,+ });+ }state.pendingQueue.unshift(item);this.prependPendingCompactWaitClientId(state, item.clientId);// 「用户显式重试」信号 —— **只在 active-turn recovery 上发**。这一支重试的是@@ -1850,7 +1947,12 @@ export class AgentInputCoordinator {//// 带上这条重试消息的 clientId: 消费方(hook-control)用它做**权威归属** ——// 只有 clientId 对得上的那次 dispatch 才是目标续跑轮, 不再靠"首个事件"猜。- this.deps.onUiRetry?.(sessionId, item.clientId, opts?.auto ? 'auto' : 'manual');+ this.deps.onUiRetry?.(+ sessionId,+ item.clientId,+ opts?.auto ? 'auto' : 'manual',+ attemptToken ?? undefined,+ );}if (!opts?.auto) this.touchUserSend(sessionId);this.emit(sessionId);@@ -1861,15 +1963,15 @@ export class AgentInputCoordinator {clearError(sessionId: string): AgentInputProjection {const state = this.getState(sessionId);- const shouldDrainTail = state.recovery?.kind === 'active-turn';- // clearError can immediately wake an already queued turn. Release the old- // backoff owner before that drain, or its Island filter can swallow the new tail.if (state.autoResumePending) this.deps.onUserEnqueue?.(sessionId);+ this.cancelPreparedAutoResume(sessionId, state);+ const shouldDrainTail = state.recovery?.kind === 'active-turn';state.error = null;state.stickyError = null;// 用户显式收下了这条错误 → 自愈提示也该撤掉(退避到点后的复核会发现 recovery// 已清并回滚额度)。state.autoResumePending = null;+ state.autoResumeAttemptToken = null;if (state.recovery?.kind !== 'queue-head') {state.recovery = null;}@@ -1883,8 +1985,8 @@ export class AgentInputCoordinator {if (state.steeringQueueClientIds.includes(clientId)) return this.getProjection(sessionId);const before = state.pendingQueue.length;const removed = state.pendingQueue.find((q) => q.clientId === clientId);- if (removed) this.deps.onDiscardedQueuedMessage?.(sessionId, removed);state.pendingQueue = state.pendingQueue.filter((q) => q.clientId !== clientId);+ if (removed) this.deps.onDiscardedQueuedMessage?.(sessionId, removed);// 显式移除的消息从未派发:该 clientId 允许被合法地重新入队(重排/再发都是// 既有产品流),必须从弱网重发幂等窗口里遗忘,否则再入队会被误吞。if (removed) {@@ -2017,6 +2119,9 @@ export class AgentInputCoordinator {this.scheduleDrain(sessionId, 'credential-switch-wait-displaced');}this.emit(sessionId);+ // 队首变化也可能切换 SESSION_RUNNING retry policy(auto 10s ↔ 普通 250ms)。+ // 重新评估当前 busy boundary,替换仍绑定旧队首的 timer。+ this.scheduleExternalTurnRetryIfNeeded(sessionId, state, 'queue-moved');return this.getProjection(sessionId);}@@ -2084,6 +2189,7 @@ export class AgentInputCoordinator {clearSession(sessionId: string, clearedAt: string | number = Date.now()): AgentInputProjection {this.deps.noteSessionClearBoundary?.(sessionId, clearedAt);const prev = this.getState(sessionId);+ this.supersedePendingAutoResumeRecoveries(sessionId);this.clearAbortReconcileRetry(prev);this.clearSessionRunningRetry(prev);this.clearCredentialSwitchWait(prev);@@ -2172,6 +2278,7 @@ export class AgentInputCoordinator {: null;if (takeover) {state.autoResumePending = takeover;+ state.autoResumeAttemptToken = takeover.sessionTotal;} else {state.error = message ?? state.error;// Schedule 的确定性错误或额度耗尽仍由 runner 收口,不留下脱离 run 记账的@@ -2306,6 +2413,7 @@ export class AgentInputCoordinator {onSessionClosed(sessionId: string): void {const state = this.getState(sessionId);+ this.supersedePendingAutoResumeRecoveries(sessionId);const releasedAbortLock = state.queueAbortPending;this.cancelScheduledDrain(state);this.clearAbortReconcileRetry(state);@@ -2622,6 +2730,9 @@ export class AgentInputCoordinator {messageUuid: active.messageUuid,userName: head.userName,throwOnStartFailure: true,+ ...(head.autoResume && typeof head.autoResumeInfo?.sessionTotal === 'number'+ ? { turnAttemptToken: head.autoResumeInfo.sessionTotal }+ : {}),...(head.origin?.kind === 'scheduler' ? { origin: head.origin } : {}),// 手机来源透传到 send 事务:drain 已脱离入队时的 async context。...(head.fromMobileClient ? { fromMobileClient: true } : {}),@@ -2634,6 +2745,7 @@ export class AgentInputCoordinator {// host 靠它跳过额度充值(见 AgentInputQueuedMessage.autoResume)。...(head.autoResume ? { autoResume: true } : {}),...(head.autoResumeInfo ? { autoResumeInfo: head.autoResumeInfo } : {}),+ ...(head.origin ? { origin: head.origin } : {}),shouldBroadcast: () => this.isTurnGenerationCurrent(sessionId, active),onPersisting: () => {if (this.isTurnGenerationCurrent(sessionId, active)) {@@ -2666,7 +2778,7 @@ export class AgentInputCoordinator {},},);- if (this.discardOnStaleActiveTurn(sessionId, active)) return;+ if (this.discardOnStaleActiveTurn(sessionId, active, isSendDispatched(result))) return;active.persisting = false;if (!isSendDispatched(result)) {this.handleSendNotDispatched(sessionId, active, head, result);@@ -2686,6 +2798,7 @@ export class AgentInputCoordinator {error: err instanceof Error ? err.message : String(err),});}+ this.commitAutoResumeDispatch(sessionId, head);// retry-supersede:克隆重发行既落库又真正派发出去了,被取代的旧 user 行从此// 冗余,软删它(连同其后的 error 行)。落在这里而不是 onPersisted 里:落库到// 派发之间还夹着 beforeDispatch / onAccepted 两个 hook,期间停止或关闭会话会走@@ -2728,6 +2841,13 @@ export class AgentInputCoordinator {this.deferQueueHeadAfterSessionRunning(sessionId, active, head, reason, errorMessage(err));return;}+ if (head.autoResume) {+ latest.activeTurn = null;+ this.discardAutoResumeBeforeDispatch(sessionId, head);+ this.emit(sessionId);+ this.deps.onQueueEmptied?.(sessionId);+ return;+ }latest.activeTurn = null;this.prependQueueHeadIfMissing(latest, head);this.clearCredentialSwitchWait(latest);@@ -2795,6 +2915,13 @@ export class AgentInputCoordinator {this.deferQueueHeadForCredentialSwitch(sessionId, active, item, result);return;}+ if (item.autoResume) {+ latest.activeTurn = null;+ this.discardAutoResumeBeforeDispatch(sessionId, item);+ this.emit(sessionId);+ this.deps.onQueueEmptied?.(sessionId);+ return;+ }latest.activeTurn = null;if (!latest.pendingQueue.some((q) => q.clientId === item.clientId)) {latest.pendingQueue = [item, ...latest.pendingQueue];@@ -2904,6 +3031,9 @@ export class AgentInputCoordinator {const latest = this.getState(sessionId);if (!this.isActiveTurnCurrent(sessionId, active)) return;latest.activeTurn = null;+ if (this.abandonAutoResumeAfterTransientFailure(sessionId, latest, item, 'credential-switch-busy')) {+ return;+ }this.prependQueueHeadIfMissing(latest, item);latest.error = null;latest.stickyError = null;@@ -2990,6 +3120,9 @@ export class AgentInputCoordinator {const latest = this.getState(sessionId);if (!this.isActiveTurnCurrent(sessionId, active)) return;latest.activeTurn = null;+ if (this.abandonAutoResumeAfterTransientFailure(sessionId, latest, item, 'session-running')) {+ return;+ }this.prependQueueHeadIfMissing(latest, item);latest.error = null;latest.stickyError = null;@@ -3010,18 +3143,55 @@ export class AgentInputCoordinator {this.prependPendingCompactWaitClientId(state, item.clientId);}+ private getSessionRunningRetryPolicy(state: SessionInputState): {+ ownerKey: string | null;+ delayMs: number;+ } {+ const compact = state.pendingCompacts[0];+ if (compact && compact.waitForClientIds.length === 0) {+ return { ownerKey: 'compact', delayMs: SESSION_RUNNING_RETRY_DELAY_MS };+ }+ const head = state.pendingQueue[0];+ return {+ ownerKey: head ? `queue:${head.clientId}` : null,+ delayMs: head?.autoResume+ ? AUTO_RESUME_SESSION_RUNNING_RETRY_DELAY_MS+ : SESSION_RUNNING_RETRY_DELAY_MS,+ };+ }+private scheduleSessionRunningRetry(sessionId: string, reason: string): void {const state = this.getState(sessionId);+ const policy = this.getSessionRunningRetryPolicy(state);if (state.sessionRunningRetryTimer) {- if (state.sessionRunningRetryGeneration === state.generation) return;+ if (+ state.sessionRunningRetryGeneration === state.generation &&+ state.sessionRunningRetryOwnerKey === policy.ownerKey &&+ state.sessionRunningRetryDelayMs === policy.delayMs+ ) {+ return;+ }this.clearSessionRunningRetry(state);}const generation = state.generation;+ const retryToken = Symbol('session-running-retry');state.sessionRunningRetryGeneration = generation;+ state.sessionRunningRetryOwnerKey = policy.ownerKey;+ state.sessionRunningRetryDelayMs = policy.delayMs;+ state.sessionRunningRetryToken = retryToken;state.sessionRunningRetryTimer = setTimeout(() => {const latest = this.getState(sessionId);+ if (+ latest.sessionRunningRetryToken !== retryToken ||+ latest.sessionRunningRetryGeneration !== generation+ ) {+ return;+ }latest.sessionRunningRetryTimer = null;latest.sessionRunningRetryGeneration = null;+ latest.sessionRunningRetryOwnerKey = null;+ latest.sessionRunningRetryDelayMs = null;+ latest.sessionRunningRetryToken = null;if (latest.generation !== generation) return;if (latest.pendingQueue.length === 0 && latest.pendingCompacts.length === 0) return;if (this.isDispatchBoundaryBusy(sessionId, latest)) {@@ -3029,7 +3199,7 @@ export class AgentInputCoordinator {return;}this.scheduleDrain(sessionId, `session-running-retry:${reason}`);- }, SESSION_RUNNING_RETRY_DELAY_MS);+ }, policy.delayMs);}private markPendingExternalTerminalDone(sessionId: string, state: SessionInputState): void {@@ -3068,7 +3238,15 @@ export class AgentInputCoordinator {const hasRunnableCompact = Boolean(compact && compact.waitForClientIds.length === 0);const hasRunnableQueueHead = Boolean(head && !state.queueEditLocks.includes(head.clientId));if (!hasRunnableCompact && !hasRunnableQueueHead) return;- if (state.activeTurn !== null) return;+ if (state.activeTurn !== null) {+ // A prior busy boundary may have left a fallback timer armed while the+ // current turn is still active. Rebind it to the newly changed queue+ // head so a later lost-done fallback does not inherit the old policy.+ if (state.sessionRunningRetryTimer) {+ this.scheduleSessionRunningRetry(sessionId, reason);+ }+ return;+ }if (state.recovery !== null) return;if (state.queuePaused || state.queueAbortPending) return;if (state.queueInteractionLocks.length > 0 || state.steeringQueueClientIds.length > 0) return;@@ -3082,6 +3260,9 @@ export class AgentInputCoordinator {}state.sessionRunningRetryTimer = null;state.sessionRunningRetryGeneration = null;+ state.sessionRunningRetryOwnerKey = null;+ state.sessionRunningRetryDelayMs = null;+ state.sessionRunningRetryToken = null;}/** closed 事件可能早于 sendToAgent 返回;这里先挂起 terminal event,等真实 send outcome 决定 drain 还是 recovery。 */@@ -3139,6 +3320,10 @@ export class AgentInputCoordinator {}state.activeTurn = null;+ if (item.autoResume) {+ this.discardAutoResumeBeforeDispatch(sessionId, item);+ return;+ }if (!state.pendingQueue.some((q) => q.clientId === item.clientId)) {state.pendingQueue = [item, ...state.pendingQueue];this.prependPendingCompactWaitClientId(state, item.clientId);@@ -3178,20 +3363,126 @@ export class AgentInputCoordinator {}}+ /** 用户动作发生时撤销尚未交给 vendor 的自动续跑项。 */+ private supersedePendingAutoResumeRecoveries(sessionId: string): void {+ for (const [clientId, pending] of this.pendingAutoResumeRecoveries) {+ if (pending.sessionId === sessionId) {+ this.pendingAutoResumeRecoveries.delete(clientId);+ this.autoResumeDispatchAttempts.delete(clientId);+ }+ }+ const state = this.states.get(sessionId);+ if (state) state.autoResumeAttemptToken = null;+ }+/**- * 用户接管时撤销已经离队、但尚未交给 vendor 的隐藏 scheduler 自动续跑。- *- * 不扩成通用并发机制:普通 scheduler turn 仍按既有串行队列执行;只有 autoResume- * 是已被用户后续选择取代的合成 Continue。持久化前走 discard 回调,持久化后走- * undispatched 回调,两条既有 host 边界都会同步结清对应 schedule waiter。+ * 自动续跑项在 pre-vendor 边界被丢弃时恢复原错误入口。+ * 返回 false 表示它已经被用户动作取代、会话已清空,或已跨过 dispatch 边界。+ */+ restoreAutoResumeRecovery(+ sessionId: string,+ clientId: string,+ attemptToken: number,+ ): boolean {+ const pending = this.pendingAutoResumeRecoveries.get(clientId);+ if (!pending) return false;+ const state = this.states.get(sessionId);+ if (+ pending.sessionId !== sessionId ||+ pending.attemptToken !== attemptToken ||+ state !== pending.stateRef ||+ state.autoResumeAttemptToken !== attemptToken+ ) {+ return false;+ }+ this.pendingAutoResumeRecoveries.delete(clientId);+ state.error = pending.error;+ state.stickyError = pending.stickyError;+ state.recovery = pending.recovery;+ state.autoResumePending = pending.autoResumeInfo;+ this.emit(sessionId);+ return true;+ }++ private discardAutoResumeBeforeDispatch(+ sessionId: string,+ item: AgentInputQueuedMessage,+ ): void {+ // This item has already left pendingQueue but never crossed vendor dispatch. Reuse the+ // existing host cleanup boundary; register owns the single recovery/finalize operation.+ this.autoResumeDispatchAttempts.delete(item.clientId);+ this.deps.onDiscardedQueuedMessage?.(sessionId, item);+ }++ /** 自动续跑项已真正进入 vendor,之后不再需要 pre-vendor 回滚信息。 */+ private commitAutoResumeDispatch(+ sessionId: string,+ item: AgentInputQueuedMessage,+ ): void {+ this.pendingAutoResumeRecoveries.delete(item.clientId);+ this.autoResumeDispatchAttempts.delete(item.clientId);+ const attemptToken = item.autoResumeInfo?.sessionTotal;+ const state = this.getState(sessionId);+ if (+ item.autoResume &&+ typeof attemptToken === 'number' &&+ state.autoResumeAttemptToken === attemptToken+ ) {+ state.autoResumeAttemptToken = null;+ }+ }++ /**+ * 记录同一自动续跑项的 transient busy 失败;达到上限时就地放弃并交回原错误。+ * 普通用户消息仍沿用原有无限等待语义,只有隐藏 auto item 需要硬边界。+ */+ private abandonAutoResumeAfterTransientFailure(+ sessionId: string,+ state: SessionInputState,+ item: AgentInputQueuedMessage,+ reason: string,+ ): boolean {+ if (!item.autoResume) return false;+ const attempts = (this.autoResumeDispatchAttempts.get(item.clientId) ?? 0) + 1;+ this.autoResumeDispatchAttempts.set(item.clientId, attempts);+ if (attempts < MAX_AUTO_RESUME_DISPATCH_ATTEMPTS) return false;++ this.autoResumeDispatchAttempts.delete(item.clientId);+ state.activeTurn = null;+ state.pendingQueue = state.pendingQueue.filter((queued) => queued.clientId !== item.clientId);+ this.removePendingCompactWaitClientId(state, item.clientId);+ this.clearCredentialSwitchWait(state);+ this.discardAutoResumeBeforeDispatch(sessionId, item);+ log.warn('auto-resume dispatch budget exhausted while provider stayed busy', {+ sessionId,+ clientId: item.clientId,+ attempts,+ reason,+ });+ this.emit(sessionId);+ this.deps.onQueueEmptied?.(sessionId);+ // Exhausting the hidden auto-resume must not strand work queued behind it.+ // The retry timer has been consumed at this boundary, so wake any FIFO+ // tail explicitly once the auto item is removed.+ if (state.pendingQueue.length > 0 || state.pendingCompacts.length > 0) {+ this.scheduleDrain(sessionId, 'auto-resume-budget-exhausted');+ }+ return true;+ }++ /**+ * 用户接管时撤销已经离队、但尚未交给 vendor 的隐藏自动续跑。+ * 持久化前走 discard 回调,持久化后走 undispatched 回调,两条既有 host 边界都会结算+ * suppressed error 与 guard pending 状态。*/- private cancelPreparedSchedulerAutoResume(+ private cancelPreparedAutoResume(sessionId: string,state: SessionInputState,): boolean {const queuedClientIds = state.pendingQueue- .filter((item) => item.autoResume && isSchedulerOriginItem(item))+ .filter((item) => item.autoResume).map((item) => item.clientId);+ this.supersedePendingAutoResumeRecoveries(sessionId);for (const clientId of queuedClientIds) this.remove(sessionId, clientId);const active = state.activeTurn;@@ -3199,7 +3490,6 @@ export class AgentInputCoordinator {if (!active ||!item?.autoResume ||- !isSchedulerOriginItem(item) ||!isActiveTurnBeforeVendorDispatch(active)) {return queuedClientIds.length > 0;@@ -3207,8 +3497,8 @@ export class AgentInputCoordinator {const persisted = active.persisted;this.cancelPreSendActiveTurn(sessionId, state, false);this.emit(sessionId);- this.scheduleDrain(sessionId, 'scheduler-auto-resume-cancelled');- log.info('cancelled prepared scheduler auto-resume', {+ this.scheduleDrain(sessionId, 'auto-resume-cancelled');+ log.info('cancelled prepared auto-resume', {sessionId,clientId: item.clientId,runId: item.origin?.kind === 'scheduler' ? item.origin.runId : undefined,@@ -3224,7 +3514,9 @@ export class AgentInputCoordinator {// scheduler 自动续跑退避期间走到这里,必须先同步作废那一轮的 waiter,避免// fallback turn 的 text/done 被旧 run 消费。scheduler 自己与 UI Continue 仍保留// 各自的续跑归属,不按无关用户输入处理。- if (!isSchedulerOriginItem(item) && !isUiContinuationItem(item)) {+ if (isAutomaticOriginItem(item)) {+ if (!isSchedulerOriginItem(item)) this.deps.onAutomaticEnqueue?.(sessionId);+ } else if (!isUiContinuationItem(item)) {this.deps.onUserEnqueue?.(sessionId);}this.abandonActiveTurnRecoveryForUserAction(state);@@ -3580,6 +3872,25 @@ export class AgentInputCoordinator {return this.getState(sessionId).autoResumePending !== null;}+ getAutoResumeAttemptToken(sessionId: string): number | null {+ return this.getState(sessionId).autoResumeAttemptToken;+ }++ /** Exact owner for a deferred resumable terminal error, before it is decided. */+ getAutoResumeDeferredOwner(sessionId: string): SuppressedTurnErrorOwner | null {+ const active = this.getState(sessionId).activeTurn;+ if (!active?.item) return null;+ const pending = active.pendingTerminalEvent;+ if (pending?.type !== 'error' || pending.resumableCandidate !== true) {+ return null;+ }+ return { generation: active.generation, clientId: active.item.clientId };+ }++ isAutoResumeAttemptCurrent(sessionId: string, attemptToken: number): boolean {+ return this.getState(sessionId).autoResumeAttemptToken === attemptToken;+ }+/*** 有一条 terminal error 正被「可能接管」按住、还没走到决策(见* `isResumableTurnErrorCandidate` 与 `ActiveTurnTerminalEvent.resumableCandidate`)。@@ -3622,8 +3933,19 @@ export class AgentInputCoordinator {** 返回 true 表示"已经不是当前 turn,调用方该早返了"。*/- private discardOnStaleActiveTurn(sessionId: string, active: ActiveTurn): boolean {+ private discardOnStaleActiveTurn(+ sessionId: string,+ active: ActiveTurn,+ dispatchAccepted = false,+ ): boolean {if (this.isActiveTurnCurrent(sessionId, active)) return false;+ if (active.item?.autoResume) {+ if (dispatchAccepted) {+ this.commitAutoResumeDispatch(sessionId, active.item);+ } else {+ this.discardAutoResumeBeforeDispatch(sessionId, active.item);+ }+ }this.discardDeferredResumableCandidate(sessionId, active, { surfaceError: false });return true;}@@ -3635,14 +3957,17 @@ export class AgentInputCoordinator {): void {const pending = active.pendingTerminalEvent;if (pending?.type !== 'error' || pending.resumableCandidate !== true) return;+ const owner = active.item+ ? { generation: active.generation, clientId: active.item.clientId }+ : null;active.pendingTerminalEvent = null;- this.notifyResumableTurnErrorDiscarded(sessionId, options);+ if (owner) this.notifyResumableTurnErrorDiscarded(sessionId, { ...options, owner });}- /** 被按住的 error 没能走到决策 → 通知 host 按最终 disposition 释放它(不变量 I2)。 */+ /** 被按住的 error 没能走到决策 → 通知 host 补落 error 行(不变量 I2)。 */private notifyResumableTurnErrorDiscarded(sessionId: string,- options: { surfaceError: boolean },+ options: { surfaceError: boolean; owner: SuppressedTurnErrorOwner },): void {try {this.deps.onResumableTurnErrorDiscarded?.(sessionId, options);@@ -3651,14 +3976,25 @@ export class AgentInputCoordinator {}}- abandonAutoResume(sessionId: string, message?: string): void {+ abandonAutoResume(+ sessionId: string,+ message?: string,+ attemptToken?: number,+ ): void {const state = this.getState(sessionId);+ if (+ attemptToken !== undefined &&+ state.autoResumeAttemptToken !== attemptToken+ ) {+ return;+ }const hadPendingTakeover = state.autoResumePending !== null;state.autoResumePending = null;- const cancelledPrepared = this.cancelPreparedSchedulerAutoResume(sessionId, state);+ state.autoResumeAttemptToken = null;+ const cancelledPrepared = this.cancelPreparedAutoResume(sessionId, state);const surfacedMessage = Boolean(message && state.recovery);if (surfacedMessage) state.error = message ?? null;- // cancelPreparedSchedulerAutoResume 已为队列 / active 变化 emit;纯退避态仍需+ // cancelPreparedAutoResume 已为队列 / active 变化 emit;纯退避态仍需// 单独投影接管结束。没有任何接管状态时保持既有 no-op 语义。if (!cancelledPrepared && (hadPendingTakeover || surfacedMessage)) this.emit(sessionId);}@@ -3779,7 +4115,10 @@ export class AgentInputCoordinator {if (outcome === 'dropped-scheduler') {state.error = terminalEvent.message ?? state.error;if (deferredPersistSuppressed) {- this.notifyResumableTurnErrorDiscarded(sessionId, { surfaceError: true });+ this.notifyResumableTurnErrorDiscarded(sessionId, {+ surfaceError: true,+ owner: { generation: active.generation, clientId: active.item!.clientId },+ });}// 与 onTurnEvent 的 persisted 分支同款处置:没有 recovery 挡住"紧随的 done",// 必须用配对标记吃掉它,否则失败呈现会被 done 擦成"已完成"(第二十一轮 P1)。@@ -3806,6 +4145,7 @@ export class AgentInputCoordinator {: null;if (deferredTakeover) {state.autoResumePending = deferredTakeover;+ state.autoResumeAttemptToken = deferredTakeover.sessionTotal;// **必须撤掉 error**:候选判定为假时前置分支(active.persisting)照旧设过 state.error,// 接管后若不清,renderer 会收到同时带 error 与 autoResumePending 的投影 —— 违反// 「接管态为真时 error 必为 null」这条不变量(greptile P1)。候选判定为真时那里本就@@ -3816,6 +4156,7 @@ export class AgentInputCoordinator {if (deferredPersistSuppressed) {this.notifyResumableTurnErrorDiscarded(sessionId, {surfaceError: terminalEvent.supersededByUser !== true,+ owner: { generation: active.generation, clientId: active.item!.clientId },});}if (schedulerItem) {diff --git a/apps/desktop/src/main/maker-ipc/autoResumeBookkeeping.ts b/apps/desktop/src/main/maker-ipc/autoResumeBookkeeping.tsindex 06d0a79fd3..36fc84f0ae 100644--- a/apps/desktop/src/main/maker-ipc/autoResumeBookkeeping.ts+++ b/apps/desktop/src/main/maker-ipc/autoResumeBookkeeping.ts@@ -29,8 +29,18 @@ export interface SuppressedTurnError {sdkError?: string;}+/** Exact coordinator owner for a deferred terminal error. */+export interface SuppressedTurnErrorOwner {+ generation: number;+ clientId: string;+}+interface SuppressedTurnErrorEntry {detail: SuppressedTurnError;+ /** Runtime owner of this suppressed error; null is bound by beginAttempt for deferred paths. */+ attemptToken: number | null;+ /** Deferred terminal-error owner; null for already-decided auto-resume paths. */+ deferredOwner: SuppressedTurnErrorOwner | null;/** The retry queue item that will replace the failed turn. */retryOwnerClientId: string | null;/**@@ -55,11 +65,11 @@ export interface AutoResumeBookkeepingDeps {/** 回填一条自动续跑记录的结果(`agentMeta.autoResumeOutcome`)。 */markOutcome: (sessionId: string, clientId: string, outcome: AutoResumeOutcome) => void;/** 回滚守卫的 pendingResume(不回滚会让该会话之后的中断永远被判成「上一次还在路上」)。 */- rollbackGuardPendingResume: (sessionId: string) => void;+ rollbackGuardPendingResume: (sessionId: string, attemptToken?: number) => void;/** 清 coordinator 的接管态;带 message 时把红横幅回落出来。 */- abandonTakeover: (sessionId: string, message?: string) => void;+ abandonTakeover: (sessionId: string, message?: string, attemptToken?: number) => void;/** 已接管的自动续跑最终没能继续;Schedule runner 用它结束同一个逻辑 run。 */- onAutoResumeFailed?: (sessionId: string) => void;+ onAutoResumeFailed?: (sessionId: string, attemptToken?: number) => void;log?: (message: string, fields?: Record<string, unknown>) => void;}@@ -78,12 +88,21 @@ export class AutoResumeBookkeeping {* 那条消息在「续跑指令发出去」的瞬间就落库,那时还不知道有没有真连上;结果由* `settleOutcome` 在后续事件里回填。*/- private readonly pendingOutcomes = new Map<string, string>();+ private readonly pendingOutcomes = new Map<+ string,+ { clientId: string; attemptToken: number | null }+ >();++ /** Current automatic recovery owner. Every async settlement must match it. */+ private readonly currentAttempts = new Map<string, number>();++ /** Exact retry queue item that owns the suppressed error during pre-dispatch. */+ private readonly suppressedErrorClients = new Map<string, string>();/** 待触发或正在异步判定的退避 attempt(sessionId → 句柄 + ownership 令牌)。 */private readonly schedules = new Map<string,- { timer: ReturnType<typeof setTimeout> | null; token: number }+ { timer: ReturnType<typeof setTimeout> | null; token: number; attemptToken: number | null }>();/** 排期令牌自增源(全局单调;只用来判「是不是我那次」,跨会话共享无妨)。 */@@ -91,6 +110,17 @@ export class AutoResumeBookkeeping {constructor(private readonly deps: AutoResumeBookkeepingDeps) {}+ /** Start an attempt; deferred errors stashed before the decision inherit this token. */+ beginAttempt(sessionId: string, attemptToken: number): void {+ this.currentAttempts.set(sessionId, attemptToken);+ const suppressed = this.suppressedErrors.get(sessionId);+ if (suppressed?.attemptToken === null) suppressed.attemptToken = attemptToken;+ }++ isCurrentAttempt(sessionId: string, attemptToken: number): boolean {+ return this.currentAttempts.get(sessionId) === attemptToken;+ }+// ── 被压住的错误详情 ───────────────────────────────────────────────────────/**@@ -103,18 +133,34 @@ export class AutoResumeBookkeeping {* 「每次中断只调一次」是这条 flush 成立的前提:同一次中断若前后 stash 两遍,第二遍会把* 正在压制中的自己补落出来,红色错误卡与活动行同时出现,本功能也就白做了。*/- stashSuppressedError(sessionId: string, data: unknown): void {+ stashSuppressedError(+ sessionId: string,+ data: unknown,+ attemptToken: number | null = null,+ deferredOwner: SuppressedTurnErrorOwner | null = null,+ ): void {const previous = this.suppressedErrors.get(sessionId);if (previous?.replacementDispatching) {// The replacement has crossed the vendor boundary. A terminal error that// arrives now belongs to that new attempt; the older transient error was// successfully replaced and must not be restored beside it.this.suppressedErrors.delete(sessionId);+ this.suppressedErrorClients.delete(sessionId);} else {- this.flushSuppressedError(sessionId);+ // A newer error owns the session now. Release the previous entry before+ // installing the replacement, but only release its exact attempt owner+ // after the new entry is present. This preserves ownership when both+ // entries happen to belong to the same attempt token.+ if (previous) {+ this.suppressedErrors.delete(sessionId);+ this.suppressedErrorClients.delete(sessionId);+ this.deps.persistSuppressedError(sessionId, previous.detail);+ }}const d = (data ?? {}) as { message?: unknown; reason?: unknown; sdkError?: unknown };this.suppressedErrors.set(sessionId, {+ attemptToken,+ deferredOwner,detail: {...(typeof d.message === 'string' ? { message: d.message } : {}),...(typeof d.reason === 'string' ? { reason: d.reason } : {}),@@ -124,6 +170,41 @@ export class AutoResumeBookkeeping {islandReplacementPreviewed: false,replacementDispatching: false,});+ if (previous?.attemptToken !== null && previous?.attemptToken !== undefined) {+ this.releaseAttemptIfUnowned(sessionId, previous.attemptToken);+ }+ }++ /** Bind a tokenized automatic queue item to the suppressed error it will replace. */+ bindSuppressedErrorToClient(+ sessionId: string,+ attemptToken: number,+ clientId: string,+ ): void {+ const entry = this.suppressedErrors.get(sessionId);+ if (+ this.isCurrentAttempt(sessionId, attemptToken) &&+ entry?.attemptToken === attemptToken+ ) {+ this.suppressedErrorClients.set(sessionId, clientId);+ entry.retryOwnerClientId = clientId;+ }+ }++ /** Whether the exact token/client still owns either side of the retry lifecycle. */+ hasPendingLifecycleForClient(+ sessionId: string,+ attemptToken: number,+ clientId: string,+ ): boolean {+ if (!this.isCurrentAttempt(sessionId, attemptToken)) return false;+ const entry = this.suppressedErrors.get(sessionId);+ const pending = this.pendingOutcomes.get(sessionId);+ return (+ this.suppressedErrorClients.get(sessionId) === clientId ||+ entry?.retryOwnerClientId === clientId ||+ (pending?.clientId === clientId && pending.attemptToken === attemptToken)+ );}/** Bind the suppressed failure to the exact retry queue item that will replace it. */@@ -179,21 +260,84 @@ export class AutoResumeBookkeeping {* 同一拍里自己设好,后者用户已经自己接手了,再弹横幅只是打扰 —— 但两种情况下那次* 中断都必须在历史里留下痕迹。*/- flushSuppressedError(sessionId: string): boolean {+ flushSuppressedError(+ sessionId: string,+ opts?: {+ attemptToken?: number;+ deferredOwner?: SuppressedTurnErrorOwner;+ force?: boolean;+ },+ ): boolean {+ const entry = this.suppressedErrors.get(sessionId);+ if (!entry) return false;+ if (!opts?.force) {+ const currentAttemptToken = this.currentAttempts.get(sessionId);+ if (opts?.attemptToken !== undefined) {+ if (entry.attemptToken !== opts.attemptToken) return false;+ } else if (opts?.deferredOwner === undefined && currentAttemptToken !== undefined) {+ // Session-only stale cleanup must never flush a newer attempt's error.+ return false;+ }+ if (+ opts?.deferredOwner !== undefined &&+ !sameSuppressedTurnErrorOwner(entry.deferredOwner, opts.deferredOwner)+ ) {+ return false;+ }+ }return this.releaseSuppressedError(sessionId, false);}/** 把压住的错误一次性补落,并通知 host 将它呈现到其它用户可见表面。 */- surfaceSuppressedError(sessionId: string): boolean {+ surfaceSuppressedError(+ sessionId: string,+ opts?: {+ attemptToken?: number;+ deferredOwner?: SuppressedTurnErrorOwner;+ force?: boolean;+ },+ ): boolean {+ if (opts && !this.canReleaseSuppressedError(sessionId, opts)) return false;return this.releaseSuppressedError(sessionId, true);}+ private canReleaseSuppressedError(+ sessionId: string,+ opts: {+ attemptToken?: number;+ deferredOwner?: SuppressedTurnErrorOwner;+ force?: boolean;+ },+ ): boolean {+ const entry = this.suppressedErrors.get(sessionId);+ if (!entry || opts.force) return Boolean(entry);+ const currentAttemptToken = this.currentAttempts.get(sessionId);+ if (opts.attemptToken !== undefined && entry.attemptToken !== opts.attemptToken) return false;+ if (+ opts.deferredOwner !== undefined &&+ !sameSuppressedTurnErrorOwner(entry.deferredOwner, opts.deferredOwner)+ ) {+ return false;+ }+ if (+ opts.attemptToken === undefined &&+ opts.deferredOwner === undefined &&+ currentAttemptToken !== undefined+ ) {+ return false;+ }+ return true;+ }+private releaseSuppressedError(sessionId: string, surfaceError: boolean): boolean {const entry = this.suppressedErrors.get(sessionId);if (!entry) return false;+ const attemptToken = entry.attemptToken;this.suppressedErrors.delete(sessionId);+ this.suppressedErrorClients.delete(sessionId);this.deps.persistSuppressedError(sessionId, entry.detail);if (surfaceError) this.deps.surfaceSuppressedError?.(sessionId, entry.detail);+ if (attemptToken !== null) this.releaseAttemptIfUnowned(sessionId, attemptToken);return true;}@@ -205,7 +349,10 @@ export class AutoResumeBookkeeping {const entry = this.suppressedErrors.get(sessionId);if (entry?.retryOwnerClientId !== clientId) return false;if (disposition === 'discard') {+ const attemptToken = entry.attemptToken;this.suppressedErrors.delete(sessionId);+ this.suppressedErrorClients.delete(sessionId);+ if (attemptToken !== null) this.releaseAttemptIfUnowned(sessionId, attemptToken);return true;}return this.releaseSuppressedError(sessionId, disposition === 'surface');@@ -235,13 +382,25 @@ export class AutoResumeBookkeeping {discardReplacementProvenByProviderEvent(sessionId: string): boolean {const entry = this.suppressedErrors.get(sessionId);if (entry?.replacementDispatching !== true) return false;+ const attemptToken = entry.attemptToken;this.suppressedErrors.delete(sessionId);+ this.suppressedErrorClients.delete(sessionId);+ if (attemptToken !== null) this.releaseAttemptIfUnowned(sessionId, attemptToken);return true;}/** 自愈成功 → 压住的错误就此丢弃(用户看到的是「已重新连接」活动行,不该再有错误卡)。 */- discardSuppressedError(sessionId: string): void {+ discardSuppressedError(sessionId: string, attemptToken?: number): boolean {+ const entry = this.suppressedErrors.get(sessionId);+ if (attemptToken !== undefined) {+ if (!this.isCurrentAttempt(sessionId, attemptToken)) return false;+ if (entry && entry.attemptToken !== attemptToken) return false;+ }this.suppressedErrors.delete(sessionId);+ this.suppressedErrorClients.delete(sessionId);+ const ownerToken = entry?.attemptToken ?? attemptToken;+ if (ownerToken !== undefined) this.releaseAttemptIfUnowned(sessionId, ownerToken);+ return true;}/** 是否仍有一条失败轮的终态等待 disposition;供同轮 completion tail 共用这一边界。 */@@ -267,10 +426,19 @@ export class AutoResumeBookkeeping {* Claimed entries remain owned by their exact queue-item disposition.*/supersedeUnclaimedErrorForUserIntervention(sessionId: string): boolean {- this.cancelSchedule(sessionId);+ const cancelled = this.cancelSchedule(sessionId);+ if (!cancelled) {+ // A tokenized timer removes itself before entering async coordinator/DB work.+ // The current attempt still owns the guard during that window, so release it+ // even though there is no schedule handle left to cancel.+ const attemptToken = this.currentAttempts.get(sessionId);+ if (attemptToken !== undefined) {+ this.deps.rollbackGuardPendingResume(sessionId, attemptToken);+ }+ }const entry = this.suppressedErrors.get(sessionId);if (!entry || entry.retryOwnerClientId !== null) return false;- return this.flushSuppressedError(sessionId);+ return this.flushSuppressedError(sessionId, { force: true });}/**@@ -279,21 +447,57 @@ export class AutoResumeBookkeeping {* `surfaceError=false` 用于「退避窗口内用户自己接手了」:那时再弹错误只是打扰,* 但错误行仍要补落。*/- finalizeSuppressedError(sessionId: string, opts: { surfaceError: boolean }): void {- // 自愈到此为止 → 上一条续跑记录的结果就是失败。- this.settleOutcome(sessionId, 'failed');- const suppressed = this.suppressedErrors.get(sessionId)?.detail;- if (opts.surfaceError) this.surfaceSuppressedError(sessionId);- else this.flushSuppressedError(sessionId);- this.deps.abandonTakeover(sessionId, opts.surfaceError ? suppressed?.message : undefined);- this.deps.onAutoResumeFailed?.(sessionId);+ finalizeSuppressedError(+ sessionId: string,+ attemptOrOptions: number | { surfaceError?: boolean; surfaceBanner?: boolean },+ maybeOptions?: { surfaceBanner: boolean },+ ): boolean {+ const token = typeof attemptOrOptions === 'number' ? attemptOrOptions : undefined;+ const surfaceError =+ typeof attemptOrOptions === 'number'+ ? maybeOptions?.surfaceBanner === true+ : attemptOrOptions.surfaceError === true || attemptOrOptions.surfaceBanner === true;+ if (token !== undefined && !this.isCurrentAttempt(sessionId, token)) return false;++ if (token !== undefined) this.settleOutcome(sessionId, token, 'failed');+ else this.settleOutcome(sessionId, 'failed');++ const entry = this.suppressedErrors.get(sessionId);+ const ownsEntry = token === undefined || entry?.attemptToken === token;+ const detail = ownsEntry ? entry?.detail : undefined;+ const entryAttemptToken = ownsEntry ? entry?.attemptToken ?? null : null;+ if (ownsEntry) {+ this.suppressedErrors.delete(sessionId);+ this.suppressedErrorClients.delete(sessionId);+ if (detail) {+ this.deps.persistSuppressedError(sessionId, detail);+ if (surfaceError) this.deps.surfaceSuppressedError?.(sessionId, detail);+ }+ }+ this.deps.abandonTakeover(+ sessionId,+ surfaceError ? detail?.message : undefined,+ token,+ );+ this.deps.onAutoResumeFailed?.(sessionId, token);+ if (entryAttemptToken !== null) this.releaseAttemptIfUnowned(sessionId, entryAttemptToken);+ if (token !== undefined) this.releaseAttemptIfUnowned(sessionId, token);+ return true;}// ── 待确认的重连记录 ───────────────────────────────────────────────────────/** 自动续跑消息即将落库 → 登记待确认(产出→succeeded / 再被打断→failed)。 */- registerPendingOutcome(sessionId: string, clientId: string): void {- this.pendingOutcomes.set(sessionId, clientId);+ registerPendingOutcome(+ sessionId: string,+ attemptOrClientId: number | string,+ maybeClientId?: string,+ ): void {+ const attemptToken = typeof attemptOrClientId === 'number' ? attemptOrClientId : null;+ const clientId = typeof attemptOrClientId === 'string' ? attemptOrClientId : maybeClientId;+ if (!clientId) return;+ if (attemptToken !== null && !this.isCurrentAttempt(sessionId, attemptToken)) return;+ this.pendingOutcomes.set(sessionId, { clientId, attemptToken });}/**@@ -303,22 +507,66 @@ export class AutoResumeBookkeeping {* 失败回滚:留着会让后续事件去 patch 一条压根不存在的消息。按 clientId 校验,避免撤掉* 别人的登记。*/- releasePendingOutcome(sessionId: string, clientId: string): void {- if (this.pendingOutcomes.get(sessionId) !== clientId) return;+ releasePendingOutcome(+ sessionId: string,+ attemptOrClientId: number | string,+ maybeClientId?: string,+ ): void {+ const attemptToken = typeof attemptOrClientId === 'number' ? attemptOrClientId : null;+ const clientId = typeof attemptOrClientId === 'string' ? attemptOrClientId : maybeClientId;+ const pending = this.pendingOutcomes.get(sessionId);+ if (!clientId || pending?.clientId !== clientId) return;+ if (attemptToken !== null && pending.attemptToken !== attemptToken) return;this.pendingOutcomes.delete(sessionId);+ if (attemptToken !== null) this.releaseAttemptIfUnowned(sessionId, attemptToken);}/** 这条 clientId 是不是该会话待确认的那条自动续跑消息。 */isPendingOutcomeClientId(sessionId: string, clientId: string): boolean {- return this.pendingOutcomes.get(sessionId) === clientId;+ return this.pendingOutcomes.get(sessionId)?.clientId === clientId;}/** 回填结果并清除待确认(重复调用安全:没有待确认就 no-op)。 */- settleOutcome(sessionId: string, outcome: AutoResumeOutcome): void {- const clientId = this.pendingOutcomes.get(sessionId);- if (!clientId) return;+ settleOutcome(+ sessionId: string,+ attemptOrOutcome: number | AutoResumeOutcome,+ maybeOutcome?: AutoResumeOutcome,+ ): boolean {+ const attemptToken = typeof attemptOrOutcome === 'number' ? attemptOrOutcome : null;+ const outcome = typeof attemptOrOutcome === 'number' ? maybeOutcome : attemptOrOutcome;+ if (!outcome) return false;+ const pending = this.pendingOutcomes.get(sessionId);+ if (!pending) return false;+ if (attemptToken !== null && pending.attemptToken !== attemptToken) return false;this.pendingOutcomes.delete(sessionId);- this.deps.markOutcome(sessionId, clientId, outcome);+ this.deps.markOutcome(sessionId, pending.clientId, outcome);+ if (attemptToken !== null) this.releaseAttemptIfUnowned(sessionId, attemptToken);+ return true;+ }++ settleOutcomeForClient(+ sessionId: string,+ attemptToken: number,+ clientId: string,+ outcome: AutoResumeOutcome,+ ): boolean {+ const pending = this.pendingOutcomes.get(sessionId);+ if (+ pending?.clientId !== clientId ||+ pending.attemptToken !== attemptToken+ ) {+ return false;+ }+ return this.settleOutcome(sessionId, attemptToken, outcome);+ }++ private releaseAttemptIfUnowned(sessionId: string, attemptToken: number): void {+ if (this.currentAttempts.get(sessionId) !== attemptToken) return;+ const pending = this.pendingOutcomes.get(sessionId);+ if (pending?.attemptToken === attemptToken) return;+ const entry = this.suppressedErrors.get(sessionId);+ if (entry?.attemptToken === attemptToken) return;+ this.currentAttempts.delete(sessionId);}// ── 退避排期 ───────────────────────────────────────────────────────────────@@ -335,24 +583,70 @@ export class AutoResumeBookkeeping {*/schedule(sessionId: string,- delayMs: number,- run: (attempt: AutoResumeScheduleAttempt) => void | Promise<void>,+ attemptOrDelayMs: number,+ delayOrRun: number | ((attempt: AutoResumeScheduleAttempt) => void | Promise<void>),+ maybeRun?: (attempt: AutoResumeScheduleAttempt) => void | Promise<void>,): void {+ const tokenized = typeof delayOrRun === 'number';+ const attemptToken = tokenized ? attemptOrDelayMs : this.currentAttempts.get(sessionId) ?? null;+ const delayMs = tokenized ? delayOrRun : attemptOrDelayMs;+ const run = tokenized ? maybeRun : delayOrRun;+ if (typeof run !== 'function') return;this.supersedeSchedule(sessionId);const token = ++this.scheduleSeq;const timer = setTimeout(() => {const scheduled = this.schedules.get(sessionId);- if (scheduled?.token !== token) {+ if (scheduled?.token !== token || scheduled.attemptToken !== attemptToken) {this.deps.log?.('interrupted-turn auto-resume callback superseded; ignoring', { sessionId });return;}+ if (tokenized) {+ // Tokenized callbacks also keep a cancellable lease while async retry+ // classification is in flight. `attemptToken` is the durable owner, while+ // this schedule token lets Manual Retry / clear / teardown invalidate a+ // callback that already fired but is still awaiting DB/coordinator work.+ scheduled.timer = null;+ const attempt: AutoResumeScheduleAttempt = {+ isCurrent: () =>+ this.schedules.get(sessionId)?.token === token &&+ this.currentAttempts.get(sessionId) === attemptToken,+ };+ const complete = () => {+ const stillOwnsSchedule = this.schedules.get(sessionId)?.token === token;+ if (!stillOwnsSchedule) return;+ this.schedules.delete(sessionId);+ if (attemptToken !== null) this.releaseAttemptIfUnowned(sessionId, attemptToken);+ };+ try {+ const result = (run as (attempt: AutoResumeScheduleAttempt) => void | Promise<void>)(+ attempt,+ );+ if (result && typeof (result as Promise<void>).then === 'function') {+ void Promise.resolve(result).then(complete, (error: unknown) => {+ complete();+ this.deps.log?.('interrupted-turn auto-resume callback rejected', {+ sessionId,+ error: error instanceof Error ? error.message : String(error),+ });+ });+ } else complete();+ } catch (error) {+ complete();+ this.deps.log?.('interrupted-turn auto-resume callback threw', {+ sessionId,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ return;+ }// Keep the lease cancellable while async retry classification is in flight.scheduled.timer = null;const attempt: AutoResumeScheduleAttempt = {isCurrent: () => this.schedules.get(sessionId)?.token === token,};const complete = () => {- if (attempt.isCurrent()) this.schedules.delete(sessionId);+ if (this.schedules.get(sessionId)?.token !== token) return;+ this.schedules.delete(sessionId);};try {const result = run(attempt);@@ -375,7 +669,7 @@ export class AutoResumeBookkeeping {});}}, delayMs);- this.schedules.set(sessionId, { timer, token });+ this.schedules.set(sessionId, { timer, token, attemptToken });}/** 新排期顶替旧排期:纯撤销,**不**回滚守卫额度(理由见 `schedule`)。 */@@ -388,13 +682,18 @@ export class AutoResumeBookkeeping {}/** 终止当前 attempt 并回滚守卫的 pendingResume;没有 attempt 时是 no-op。 */- cancelSchedule(sessionId: string): void {+ cancelSchedule(sessionId: string): boolean {const scheduled = this.schedules.get(sessionId);- if (!scheduled) return;+ if (!scheduled) return false;if (scheduled.timer !== null) clearTimeout(scheduled.timer);this.schedules.delete(sessionId);- this.deps.rollbackGuardPendingResume(sessionId);+ if (scheduled.attemptToken === null) this.deps.rollbackGuardPendingResume(sessionId);+ else this.deps.rollbackGuardPendingResume(sessionId, scheduled.attemptToken);+ if (scheduled.attemptToken !== null) {+ this.releaseAttemptIfUnowned(sessionId, scheduled.attemptToken);+ }this.deps.log?.('interrupted-turn auto-resume attempt cancelled', { sessionId });+ return true;}/** 仅测试与诊断用:该会话此刻有没有待触发或正在判定的 attempt。 */@@ -417,11 +716,26 @@ export class AutoResumeBookkeeping {* 4. 把悬空的待确认记录钉成 failed。*/teardown(sessionId: string): void {- this.flushSuppressedError(sessionId);- this.cancelSchedule(sessionId);+ const attemptToken =+ this.currentAttempts.get(sessionId) ?? this.pendingOutcomes.get(sessionId)?.attemptToken ?? null;+ this.flushSuppressedError(sessionId, { force: true });+ const hadSchedule = this.cancelSchedule(sessionId);+ if (!hadSchedule && attemptToken !== null) {+ this.deps.rollbackGuardPendingResume(sessionId, attemptToken);+ }// 不带 message:只清接管态,不弹横幅(会话已经被用户终止,再弹一条只是打扰)。this.deps.abandonTakeover(sessionId);- this.settleOutcome(sessionId, 'failed');- this.deps.onAutoResumeFailed?.(sessionId);+ if (attemptToken !== null) this.settleOutcome(sessionId, attemptToken, 'failed');+ else this.settleOutcome(sessionId, 'failed');+ this.currentAttempts.delete(sessionId);+ this.suppressedErrorClients.delete(sessionId);+ this.deps.onAutoResumeFailed?.(sessionId, attemptToken ?? undefined);}}++function sameSuppressedTurnErrorOwner(+ left: SuppressedTurnErrorOwner | null,+ right: SuppressedTurnErrorOwner,+): boolean {+ return left?.generation === right.generation && left.clientId === right.clientId;+}diff --git a/apps/desktop/src/main/maker-ipc/interruptedTurnAutoResume.ts b/apps/desktop/src/main/maker-ipc/interruptedTurnAutoResume.tsindex 426048b1c5..703ab7e43f 100644--- a/apps/desktop/src/main/maker-ipc/interruptedTurnAutoResume.ts+++ b/apps/desktop/src/main/maker-ipc/interruptedTurnAutoResume.ts@@ -164,12 +164,13 @@ export function isSubstantiveProgressEvent(event: {/*** 一次中断事件里最多连续自动重连几次。*- * 额度模型是**连续失败计数**,不是「每条人话买 N 次」:+ * 额度模型是「连续失败上限 + 人工介入周期硬上限」两层:* - 连续 5 次重连都没能让模型产出任何东西 → 判定真的连不上,停下等人。* - 中间只要有一次**模型有实质产出**(assistant 文本 / 工具调用),计数归零,* 后面又可以再来 5 次。- * - **会话累计不设上限**:只要任务还在推进,就可以一直自愈;累计次数只用于展示- * (让用户看出这个会话的网络有多糟),不做限制。+ * - 但同一次人工介入之后最多自动重连 10 次;只有真人再发消息、手动 Retry 或重置+ * 会话才重新充值。这样「每次只产出一点又断」也不可能无止境循环。+ * - 会话累计仍只用于展示,不直接做限制;真正的硬边界是本次人工介入周期。** 为什么这样比「按人话充值」对:判据落在「是否在推进」而不是「人说了几句话」。长* 任务跑一小时不说话时不该被扣光额度;而真正连不上时,5 次退避(约 3+6+12+20+20@@ -177,6 +178,9 @@ export function isSubstantiveProgressEvent(event: {*/export const INTERRUPTED_TURN_MAX_CONSECUTIVE_ATTEMPTS = 5;+/** 一次真人介入之后最多允许多少次自动重连;有模型产出也不会重置。 */+export const INTERRUPTED_TURN_MAX_EPISODE_ATTEMPTS = 10;+/** 首次续跑前的退避基数。 */const RESUME_BACKOFF_BASE_MS = 3_000;/** 单次退避上限。 */@@ -218,11 +222,22 @@ export interface InterruptedTurnResumeProgress {maxAttempts: number;/** 本会话累计自动重连次数(只增,不设上限,仅用于展示)。 */sessionTotal: number;+ /** 当前自动重连 attempt 的进程内单调 token;只用于异步生命周期归属,不展示。 */+ attemptToken: number;+ /** 本次人工介入周期内第几次自动重连。 */+ episodeAttempt: number;+ /** 本次人工介入周期的硬上限。 */+ maxEpisodeAttempts: number;}export type InterruptedTurnResumeDecision =| ({ action: 'resume'; delayMs: number } & InterruptedTurnResumeProgress)- | { action: 'exhausted'; consecutiveAttempts: number }+ | {+ action: 'exhausted';+ reason: 'consecutive' | 'episode';+ consecutiveAttempts: number;+ episodeAttempts: number;+ }| { action: 'skip'; why: 'disabled' | 'superseded' | 'pending' };interface GuardLogger {@@ -233,11 +248,16 @@ interface GuardLogger {interface SessionGuardState {/** 本轮连续重连次数(模型有产出 / 人工介入即归零)。 */consecutiveAttempts: number;+ /** 自上一次真人介入起的自动重连总数;模型有产出也不归零。 */+ episodeAttempts: number;/** 会话累计自动重连次数(只增,仅展示)。 */sessionTotalResumes: number;lastTurnStartAt: number;lastUserSendAt: number;- pendingResume: boolean;+ /** 最新获准 attempt;直到真人介入、会话重置或更新 attempt 才失效。 */+ currentAttemptToken: number | null;+ /** 尚未被新 turn 接走或明确失败的 attempt。 */+ pendingAttemptToken: number | null;exhaustedWarned: boolean;}@@ -254,9 +274,9 @@ export interface InterruptedTurnAutoResumeGuardDeps {/*** 中断自动续跑的决策器。*- * 与 `SilentStopAutoResumeGuard` 保持相似形状(pendingResume 去重、陈旧保护、- * 可注入依赖)好让两处一起读,但额度语义完全不同:这里是**连续失败计数 + 有进展- * 就重置**,会话累计不限(见 `INTERRUPTED_TURN_MAX_CONSECUTIVE_ATTEMPTS`)。+ * 与 `SilentStopAutoResumeGuard` 保持相似形状(pending attempt 去重、陈旧保护、+ * 可注入依赖)好让两处一起读,但额度语义完全不同:这里同时限制连续失败与一次+ * 人工介入周期的总次数,后者保证自动续跑绝对有限。** 纯内存状态(app 重启即复位),无 IO;全部依赖可注入,便于单测。*/@@ -274,10 +294,12 @@ export class InterruptedTurnAutoResumeGuard {if (!s) {s = {consecutiveAttempts: 0,+ episodeAttempts: 0,sessionTotalResumes: 0,lastTurnStartAt: 0,lastUserSendAt: 0,- pendingResume: false,+ currentAttemptToken: null,+ pendingAttemptToken: null,exhaustedWarned: false,};this.sessions.set(sessionId, s);@@ -294,11 +316,20 @@ export class InterruptedTurnAutoResumeGuard {** 热路径友好:O(1)、无 IO、无日志(每条 assistant 消息与每次工具调用都会调)。*/- noteProgress(sessionId: string): void {+ noteProgress(sessionId: string, attemptToken?: number): boolean {const s = this.sessions.get(sessionId);- if (!s || s.consecutiveAttempts === 0) return;+ if (!s) return false;+ // 显式 token 必须严格属于当前 attempt。真人发送 / clear 会把 current 清成 null;+ // 这之后旧 turn 的迟到 text/tool 仍带旧 token,不能因为“当前没有 owner”就被接纳。+ if (attemptToken !== undefined) {+ if (s.currentAttemptToken !== attemptToken) return false;+ } else if (s.currentAttemptToken !== null) {+ return false;+ }+ if (s.consecutiveAttempts === 0) return true;s.consecutiveAttempts = 0;s.exhaustedWarned = false;+ return true;}/**@@ -309,23 +340,79 @@ export class InterruptedTurnAutoResumeGuard {noteUserSend(sessionId: string): void {const s = this.state(sessionId);s.consecutiveAttempts = 0;+ s.episodeAttempts = 0;+ s.currentAttemptToken = null;+ s.pendingAttemptToken = null;s.exhaustedWarned = false;s.lastUserSendAt = this.now();}- /** 新 turn 开始。清 pendingResume,记录时间做陈旧判定。 */- noteTurnStarted(sessionId: string): void {+ /**+ * 新 turn 开始,记录时间做陈旧判定。+ *+ * 未携带 host token 的 status 可能只是 terminal error 之后补发的旧事件,不能清掉+ * 已排期的自动续跑;生产事件转发会据 token 选择性清理,旧测试/其它显式调用保持+ * 默认清 pending 的兼容语义。+ */+ noteTurnStarted(sessionId: string, opts?: { clearPending?: boolean }): void {const s = this.state(sessionId);s.lastTurnStartAt = this.now();- s.pendingResume = false;+ if (opts?.clearPending === false) return;+ s.pendingAttemptToken = null;+ }++ /**+ * 自动续跑真正产生了属于自己的首个事件。+ *+ * 不能只依赖 status(isRunning=true):Pi 进程退出、Claude 空响应等路径可能直接+ * 发 terminal error。首个带 token 的事件就是 provider 已接受该 attempt 的最早+ * 可靠边界;清 pending 后,下一次 terminal error 才能继续消耗预算,而旧 token+ * 或真人接管后的迟到事件不会碰当前 attempt。+ */+ noteAttemptEvent(sessionId: string, attemptToken: number): boolean {+ const s = this.sessions.get(sessionId);+ if (!s || s.currentAttemptToken !== attemptToken) return false;+ if (s.pendingAttemptToken !== attemptToken) return false;+ s.pendingAttemptToken = null;+ s.lastTurnStartAt = this.now();+ return true;+ }++ /**+ * 自动续跑 turn 到达终态后退休 token owner。+ *+ * 首个 token 事件只证明 provider 已接受 attempt,不能在那里清 owner:同一个+ * turn 后续的 text/tool_use 仍需用该 token 结算。终态之后再清 owner,既拒绝+ * 迟到的旧 token 事件,也允许后续 scheduler/goal/Orca 等无 token 自动 turn 的+ * 实质产出重置连续失败计数。+ */+ noteAttemptSettled(sessionId: string, attemptToken: number): boolean {+ const s = this.sessions.get(sessionId);+ if (!s || s.currentAttemptToken !== attemptToken) return false;+ s.currentAttemptToken = null;+ s.pendingAttemptToken = null;+ return true;}/*** 自动续跑投递失败时清 pending,避免卡死后续决策。* 计数不回退(安全方向:宁可少试一次,不可无限试)。*/- noteResumeSendFailed(sessionId: string): void {- this.state(sessionId).pendingResume = false;+ noteResumeSendFailed(sessionId: string, attemptToken: number): boolean {+ const s = this.state(sessionId);+ if (+ s.currentAttemptToken !== attemptToken ||+ s.pendingAttemptToken !== attemptToken+ ) {+ return false;+ }+ s.pendingAttemptToken = null;+ // No provider event was observed for this attempt, so its token must not+ // block substantive progress from a later untagged automatic turn+ // (scheduler/goal/Orca). A stale tokened event is still rejected because+ // currentAttemptToken is cleared here.+ s.currentAttemptToken = null;+ return true;}/**@@ -335,12 +422,19 @@ export class InterruptedTurnAutoResumeGuard {*/noteSessionReset(sessionId: string): void {const s = this.state(sessionId);- s.pendingResume = false;+ s.currentAttemptToken = null;+ s.pendingAttemptToken = null;s.consecutiveAttempts = 0;+ s.episodeAttempts = 0;s.exhaustedWarned = false;s.lastUserSendAt = this.now();}+ /** 迟到的异步结果只能结算自己那一轮。 */+ isCurrentAttempt(sessionId: string, attemptToken: number): boolean {+ return this.sessions.get(sessionId)?.currentAttemptToken === attemptToken;+ }+/*** 对一次「turn 被打断」做决策。`erroredAt` 是该 terminal error 的观察时刻,用于* 陈旧判定(其后用户已发消息 / 新 turn 已开始 → superseded)。@@ -354,7 +448,7 @@ export class InterruptedTurnAutoResumeGuard {this.deps.log.debug('interrupted-turn auto-resume disabled by kill switch', { sessionId });return { action: 'skip', why: 'disabled' };}- if (s.pendingResume) {+ if (s.pendingAttemptToken !== null) {this.deps.log.debug('interrupted-turn duplicate error while resume pending', { sessionId });return { action: 'skip', why: 'pending' };}@@ -367,33 +461,58 @@ export class InterruptedTurnAutoResumeGuard {});return { action: 'skip', why: 'superseded' };}- if (s.consecutiveAttempts >= INTERRUPTED_TURN_MAX_CONSECUTIVE_ATTEMPTS) {+ const exhaustedReason =+ s.episodeAttempts >= INTERRUPTED_TURN_MAX_EPISODE_ATTEMPTS+ ? 'episode'+ : s.consecutiveAttempts >= INTERRUPTED_TURN_MAX_CONSECUTIVE_ATTEMPTS+ ? 'consecutive'+ : null;+ if (exhaustedReason) {if (!s.exhaustedWarned) {s.exhaustedWarned = true;this.deps.log.warn(- 'interrupted-turn auto-resume exhausted — no model output across consecutive attempts',- { sessionId, consecutiveAttempts: s.consecutiveAttempts },+ 'interrupted-turn auto-resume exhausted',+ {+ sessionId,+ reason: exhaustedReason,+ consecutiveAttempts: s.consecutiveAttempts,+ episodeAttempts: s.episodeAttempts,+ },);}- return { action: 'exhausted', consecutiveAttempts: s.consecutiveAttempts };+ return {+ action: 'exhausted',+ reason: exhaustedReason,+ consecutiveAttempts: s.consecutiveAttempts,+ episodeAttempts: s.episodeAttempts,+ };}s.consecutiveAttempts += 1;+ s.episodeAttempts += 1;s.sessionTotalResumes += 1;- s.pendingResume = true;+ const attemptToken = s.sessionTotalResumes;+ s.currentAttemptToken = attemptToken;+ s.pendingAttemptToken = attemptToken;const attempt = s.consecutiveAttempts;const delayMs = interruptedTurnResumeDelayMs(attempt, this.deps.random);this.deps.log.debug('interrupted-turn auto-resume granted', {sessionId,attempt,maxAttempts: INTERRUPTED_TURN_MAX_CONSECUTIVE_ATTEMPTS,+ episodeAttempt: s.episodeAttempts,+ maxEpisodeAttempts: INTERRUPTED_TURN_MAX_EPISODE_ATTEMPTS,sessionTotal: s.sessionTotalResumes,+ attemptToken,delayMs,});return {action: 'resume',attempt,maxAttempts: INTERRUPTED_TURN_MAX_CONSECUTIVE_ATTEMPTS,+ episodeAttempt: s.episodeAttempts,+ maxEpisodeAttempts: INTERRUPTED_TURN_MAX_EPISODE_ATTEMPTS,sessionTotal: s.sessionTotalResumes,+ attemptToken,delayMs,};}diff --git a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.tsindex fac1bd0e1c..155958aae9 100644--- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts+++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts@@ -31,6 +31,8 @@ type MakerSendOptions = {messageUuid?: string;userName?: string;throwOnStartFailure?: boolean;+ /** Host-owned per-turn lifecycle correlation; maker-core stamps it on AgentEvent. */+ turnAttemptToken?: number;/*** Direct Continue fallback only: acknowledge the interrupted marker on the* executor after vendor dispatch is irreversible. The executor must own the@@ -68,6 +70,8 @@ type MakerSendOptions = {autoResume?: unknown;/** 本次自动续跑的展示信息(合进 agentMeta.autoResumeInfo,供活动行 param 位与展开详情)。 */autoResumeInfo?: unknown;+ /** 队列自动来源(只写入 agentMeta,不传给 maker-core 的 turn origin)。 */+ origin?: unknown;};};@@ -224,6 +228,7 @@ function readPersistUserMessageOption(sendOpts: MakerSendOptions): {delivery?: 'turn' | 'steer';autoResume?: boolean;autoResumeInfo?: Record<string, unknown>;+ origin?: Record<string, unknown>;shouldBroadcast?: () => boolean;onPersisting?: () => void;onPersisted?: () => void | Promise<void>;@@ -238,6 +243,9 @@ function readPersistUserMessageOption(sendOpts: MakerSendOptions): {...(persist.autoResumeInfo && typeof persist.autoResumeInfo === 'object'? { autoResumeInfo: persist.autoResumeInfo as Record<string, unknown> }: {}),+ ...(persist.origin && typeof persist.origin === 'object' && !Array.isArray(persist.origin)+ ? { origin: persist.origin as Record<string, unknown> }+ : {}),...(persist.delivery === 'turn' || persist.delivery === 'steer' ? { delivery: persist.delivery } : {}),...(typeof persist.shouldBroadcast === 'function'? { shouldBroadcast: persist.shouldBroadcast as () => boolean }@@ -591,6 +599,7 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): MakemessageUuid: so.messageUuid,userName: so.userName,throwOnStartFailure: so.throwOnStartFailure,+ turnAttemptToken: so.turnAttemptToken,signal: so.signal,// scheduler 排队消息:origin 打到本轮 turnOrigin(IM 转播识别自动 turn),// 与 runner 直发路径的 session.send({ origin }) 语义对齐。@@ -656,6 +665,9 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make...(persistUserMessage.autoResumeInfo? { autoResumeInfo: persistUserMessage.autoResumeInfo }: {}),+ ...(persistUserMessage.origin+ ? { origin: persistUserMessage.origin }+ : {}),// scheduler 排队消息:与 runner 直发路径落库的 agentMeta.origin// 对齐,renderer 据此渲染"由自动化任务发送"标签。...(so.origin ? { origin: so.origin } : {}),diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex a6c2dba66e..3d8a8fc4ae 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -607,6 +607,7 @@ import { readSilentStopAutoResumeSettings } from '../maker-host/silent-stop-autoimport {AutoResumeBookkeeping,type SuppressedTurnError,+ type SuppressedTurnErrorOwner,} from './autoResumeBookkeeping.js';import {InterruptedTurnAutoResumeGuard,@@ -689,25 +690,51 @@ const interruptedTurnAutoResumeGuard = new InterruptedTurnAutoResumeGuard({// Schedule 不另建重试状态机:真正的恢复仍由 AgentInputCoordinator +// AutoResumeBookkeeping 独占。这里仅把「这一轮 scheduler run 已被普通自动续跑接管」// 和「最终仍失败」桥给 runner,让同一个 run 继续等待或正确失败。-const pendingSchedulerAutoResumeRunBySession = new Map<string, string>();+const pendingSchedulerAutoResumeRunBySession = new Map<+ string,+ { runId: string; attemptToken: number }+>();const schedulerAutoResumeFailureListeners = new Map<string, Set<() => void>>();function schedulerAutoResumeRunKey(sessionId: string, runId: string): string {return JSON.stringify([sessionId, runId]);}-function beginSchedulerAutoResume(sessionId: string, runId: string): void {- pendingSchedulerAutoResumeRunBySession.set(sessionId, runId);+function beginSchedulerAutoResume(+ sessionId: string,+ runId: string,+ attemptToken: number,+): void {+ pendingSchedulerAutoResumeRunBySession.set(sessionId, { runId, attemptToken });}-function clearSchedulerAutoResumePending(sessionId: string, runId: string): void {- if (pendingSchedulerAutoResumeRunBySession.get(sessionId) === runId) {+function clearSchedulerAutoResumePending(+ sessionId: string,+ runId: string,+ attemptToken?: number,+): void {+ const current = pendingSchedulerAutoResumeRunBySession.get(sessionId);+ if (+ current?.runId === runId &&+ (attemptToken === undefined || current.attemptToken === attemptToken)+ ) {pendingSchedulerAutoResumeRunBySession.delete(sessionId);}}-function notifySchedulerAutoResumeFailed(sessionId: string, runId: string): void {- clearSchedulerAutoResumePending(sessionId, runId);+function notifySchedulerAutoResumeFailed(+ sessionId: string,+ runId: string,+ attemptToken?: number,+): void {+ const current = pendingSchedulerAutoResumeRunBySession.get(sessionId);+ if (+ current?.runId !== runId ||+ (attemptToken !== undefined && current.attemptToken !== attemptToken)+ ) {+ return;+ }+ clearSchedulerAutoResumePending(sessionId, runId, attemptToken);const listeners = schedulerAutoResumeFailureListeners.get(schedulerAutoResumeRunKey(sessionId, runId),);@@ -721,13 +748,14 @@ function notifySchedulerAutoResumeFailed(sessionId: string, runId: string): void}}-function failPendingSchedulerAutoResume(sessionId: string): void {- const runId = pendingSchedulerAutoResumeRunBySession.get(sessionId);- if (runId) notifySchedulerAutoResumeFailed(sessionId, runId);+function failPendingSchedulerAutoResume(sessionId: string, attemptToken?: number): void {+ const current = pendingSchedulerAutoResumeRunBySession.get(sessionId);+ if (!current || (attemptToken !== undefined && current.attemptToken !== attemptToken)) return;+ notifySchedulerAutoResumeFailed(sessionId, current.runId, attemptToken);}export function isSchedulerAutoResumePending(sessionId: string, runId: string): boolean {- return pendingSchedulerAutoResumeRunBySession.get(sessionId) === runId;+ return pendingSchedulerAutoResumeRunBySession.get(sessionId)?.runId === runId;}export function onSchedulerAutoResumeFailed(@@ -773,12 +801,16 @@ const autoResumeBookkeeping = new AutoResumeBookkeeping({markOutcome: (sessionId, clientId, outcome) => {void markAutoResumeOutcome(sessionId, clientId, outcome);},- rollbackGuardPendingResume: (sessionId) =>- interruptedTurnAutoResumeGuard.noteResumeSendFailed(sessionId),+ rollbackGuardPendingResume: (sessionId, attemptToken) => {+ if (typeof attemptToken === 'number') {+ interruptedTurnAutoResumeGuard.noteResumeSendFailed(sessionId, attemptToken);+ }+ },// holder 是可变绑定,必须懒读(模块初始化时 coordinator 还没建)。- abandonTakeover: (sessionId, message) =>- agentInputCoordinatorHolder?.abandonAutoResume(sessionId, message),- onAutoResumeFailed: failPendingSchedulerAutoResume,+ abandonTakeover: (sessionId, message, attemptToken) =>+ agentInputCoordinatorHolder?.abandonAutoResume(sessionId, message, attemptToken),+ onAutoResumeFailed: (sessionId, attemptToken) =>+ failPendingSchedulerAutoResume(sessionId, attemptToken),log: (message, fields) => log.debug(message, fields),});@@ -794,14 +826,63 @@ function resetAutomaticRecoveryForExplicitStop(sessionId: string): void {autoResumeBookkeeping.teardown(sessionId);}+function autoResumeAttemptToken(item: AgentInputQueuedMessage): number | null {+ const value = item.autoResumeInfo?.sessionTotal;+ return item.autoResume === true && typeof value === 'number' ? value : null;+}++/** 持久化 user row 的 agentMeta 归属;不要把它与 AgentEvent 的 runtime token 混用。 */+function autoResumeAttemptTokenFromAgentMeta(agentMeta: unknown): number | null {+ if (!agentMeta || typeof agentMeta !== 'object') return null;+ const info = (agentMeta as { autoResumeInfo?: unknown }).autoResumeInfo;+ if (!info || typeof info !== 'object') return null;+ const value = (info as { sessionTotal?: unknown }).sessionTotal;+ return typeof value === 'number' ? value : null;+}+function settleUndispatchedAutoResumeOutcome(sessionId: string,item: AgentInputQueuedMessage,+ attemptToken: number,): boolean {- if (!autoResumeBookkeeping.isPendingOutcomeClientId(sessionId, item.clientId)) return false;// markOutcome 复用 durable-write 队列;持久化中取消时,failed patch 会排在// 正在进行的 user row insert 后面,不会出现先 patch、后 insert 的窗口。- autoResumeBookkeeping.settleOutcome(sessionId, 'failed');+ return autoResumeBookkeeping.settleOutcomeForClient(+ sessionId,+ attemptToken,+ item.clientId,+ 'failed',+ );+}++/**+ * 自动续跑项在 vendor dispatch 前被丢弃:恢复 coordinator 的原 recovery,补落被压住的+ * error,并回滚 guard 的 pendingResume。用户已接手 / clearSession 时 coordinator 会返回+ * false,此时只补历史、不重新弹横幅。+ */+function settleUndispatchedInterruptedAutoResume(+ sessionId: string,+ item: AgentInputQueuedMessage,+): boolean {+ const attemptToken = autoResumeAttemptToken(item);+ if (attemptToken === null) return false;+ const ownsAttempt = autoResumeBookkeeping.hasPendingLifecycleForClient(+ sessionId,+ attemptToken,+ item.clientId,+ );+ const restored =+ agentInputCoordinatorHolder?.restoreAutoResumeRecovery(+ sessionId,+ item.clientId,+ attemptToken,+ ) === true;+ settleUndispatchedAutoResumeOutcome(sessionId, item, attemptToken);+ if (!ownsAttempt) return false;+ interruptedTurnAutoResumeGuard.noteResumeSendFailed(sessionId, attemptToken);+ autoResumeBookkeeping.finalizeSuppressedError(sessionId, attemptToken, {+ surfaceBanner: restored,+ });return true;}@@ -2388,8 +2469,7 @@ function handleAgentIslandEventAfterBroadcast(agentInputCoordinatorHolder?.isAutoResumePending(session.id) === true ||agentInputCoordinatorHolder?.isAutoResumeDeferred(session.id) === true;const autoResumeOwnsError =- autoResumePendingOrDeferred ||- autoResumeBookkeeping.shouldSuppressAgentIslandError(session.id);+ autoResumePendingOrDeferred || autoResumeBookkeeping.shouldSuppressAgentIslandError(session.id);const autoResumeOwnsCompletionTail =autoResumePendingOrDeferred ||autoResumeBookkeeping.shouldSuppressAgentIslandCompletionTail(session.id);@@ -2397,9 +2477,6 @@ function handleAgentIslandEventAfterBroadcast((terminalError && autoResumeOwnsError) ||(isAgentIslandCompletionTail(event) && autoResumeOwnsCompletionTail)) {- // Auto-resume owns both the error and its provider completion tail. Do not- // let either enter Agent Island; the existing suppressed-error lifecycle- // will surface the real error once if recovery is ultimately rejected.return;}service.handleAgentEvent(meta, event);@@ -2415,8 +2492,7 @@ function handleAgentIslandEventAfterBroadcast(function isAgentIslandCompletionTail(event: AgentEvent): boolean {if (event.type === 'done') return true;if (event.type !== 'status') return false;- const data = event.data as { isRunning?: unknown } | undefined;- return data?.isRunning === false;+ return (event.data as { isRunning?: unknown } | undefined)?.isRunning === false;}function surfaceSuppressedAutoResumeErrorInAgentIsland(@@ -2966,6 +3042,12 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void// 转发事件到所有 window。interaction_dismissed 单独走专用 channel,// 让 renderer chat store 不必扫所有 vendor-raw 找它。registration.disposers.push(session.onEvent((event: AgentEvent) => {+ // 自动续跑的 pending 不能只靠 status(isRunning=true) 清理:Pi/Claude 的+ // terminal-only 路径可能首个事件就是 error。Session 已把 host-owned token+ // 盖到事件上,首个匹配 token 的事件即视为 provider accepted。+ if (typeof event.turnAttemptToken === 'number') {+ interruptedTurnAutoResumeGuard.noteAttemptEvent(session.id, event.turnAttemptToken);+ }let attributedEvent = event;if (event.type === 'error' && isTerminalTurnErrorEvent(event)) {const reason = !session.remoteHostId && session.agentKind === 'claude-code'@@ -3051,7 +3133,11 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): voidnoteTurnStarted(session.id);// silent-stop 守卫:新 turn 开始 → 清 pendingResume + 记录时刻(陈旧判定)。silentStopAutoResumeGuard.noteTurnStarted(session.id);- interruptedTurnAutoResumeGuard.noteTurnStarted(session.id);+ interruptedTurnAutoResumeGuard.noteTurnStarted(session.id, {+ // A tokenless status(true) can be a delayed tail from the failed turn. It+ // must not consume the pending token of the next scheduled auto-resume.+ clearPending: typeof event.turnAttemptToken === 'number',+ });const wasInTurn = sessionTurnActivityTracker.isSessionInTurn(session.id);sessionTurnActivityTracker.setSessionInTurn(session.id, data.isRunning);if (!wasInTurn) advanceSessionTurnBoundaryGeneration(session.id);@@ -3089,7 +3175,11 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): voidif (event.type === 'done') {// turn 正常收尾但一路没有实质产出时,上一条重连记录同样不能停在"结果未回填":// 成功路径已在产出事件里 settle 成 succeeded(此处 no-op),走到这里就是没产出。- autoResumeBookkeeping.settleOutcome(session.id, 'failed');+ const doneAttemptToken = event.turnAttemptToken;+ if (typeof doneAttemptToken === 'number') {+ autoResumeBookkeeping.settleOutcome(session.id, doneAttemptToken, 'failed');+ interruptedTurnAutoResumeGuard.noteAttemptSettled(session.id, doneAttemptToken);+ }const isSilentStopDone = (event.data as { silentStop?: boolean } | null | undefined)?.silentStop === true;// silent-stop done:自动续跑会在 1.5s 后启动新 turn(或弹耗尽横幅),// 不标 idle/不触发 goal idle/不通知 coordinator done——避免 renderer@@ -3129,7 +3219,11 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void// 只在"命中白名单、准备再接管"时才 settle 的话,非白名单的终态(认证 / 计费 /// invalid-request)会让记录悬空,随后一个无关 turn 的首个产出事件就把它标成// 「已重新连接」(codex P1)。- autoResumeBookkeeping.settleOutcome(session.id, 'failed');+ const failedAttemptToken = event.turnAttemptToken;+ if (typeof failedAttemptToken === 'number') {+ autoResumeBookkeeping.settleOutcome(session.id, failedAttemptToken, 'failed');+ interruptedTurnAutoResumeGuard.noteAttemptSettled(session.id, failedAttemptToken);+ }// 终止型 error 可能没有后续 status/done(SDK/event loop crash 等),需要在// EVENT broadcast 后结束逻辑 turn,并保留 terminal grace 给 renderer 收尾;// 可重试 error 保持 running。@@ -3191,14 +3285,24 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void// (Option C:内容重排状态机只在 main 一份,与落库同源同值)。let resolvedContent: string | undefined;// 中断自愈的额度判据是「是否在推进」:模型产出了实质内容(文本 / 工具调用)就把- // 连续失败计数归零,于是只要任务还在往前走,自愈次数不设上限;连续 N 次重连都- // 产出不了任何东西才停下等人(见 interruptedTurnAutoResume.ts 的额度模型)。+ // 连续失败计数归零;人工介入周期的硬总上限不归零,保证始终有限。// 刻意只认这两类事件:thinking / status / 空消息都不算产出;guard 侧是 O(1)、// 无 IO、无日志,放在热路径安全。if (isSubstantiveProgressEvent(event)) {- interruptedTurnAutoResumeGuard.noteProgress(session.id);- // 同一个信号也是「上一次重连真的成功了」的唯一证据 → 回填结果。- autoResumeBookkeeping.settleOutcome(session.id, 'succeeded');+ const progressAttemptToken = event.turnAttemptToken;+ const accepted = interruptedTurnAutoResumeGuard.noteProgress(+ session.id,+ progressAttemptToken ?? undefined,+ );+ // 同一个信号也是「上一次重连真的成功了」的唯一证据;旧 attempt 的迟到事件+ // token 不匹配时不会结算当前新 attempt。+ if (accepted && typeof progressAttemptToken === 'number') {+ autoResumeBookkeeping.settleOutcome(+ session.id,+ progressAttemptToken,+ 'succeeded',+ );+ }}if (event.type === 'text') {const td = event.data as { text?: unknown; isFinal?: unknown } | null;@@ -3363,7 +3467,12 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void// 压住的错误详情必须在这里存一份:决策推迟场景下 onResumableTurnError 还没被调用过// (它自己那份 set 发生在接管成立时),不存就无从补落。同 clientId 内容,覆盖无害。if (autoResumeSuppressesPersist) {- autoResumeBookkeeping.stashSuppressedError(session.id, attributedEvent.data);+ autoResumeBookkeeping.stashSuppressedError(+ session.id,+ attributedEvent.data,+ agentInputCoordinatorHolder?.getAutoResumeAttemptToken(session.id) ?? null,+ agentInputCoordinatorHolder?.getAutoResumeDeferredOwner(session.id) ?? null,+ );} else if (event.type === 'error' && isTerminalTurnErrorEvent(event)) {// replacement 可在 sendToAgent 返回前同步失败并让 coordinator 的 activeTurn// 失效;这个新终态已经取代旧中断,按 dispatch phase 直接清旧 owner。@@ -4118,6 +4227,7 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void// 远端断开、宿主回收)。只清 coordinator 不够 —— 排期中的定时器与悬空的重连记录// 都还活着,前者会到点往已关闭的会话补发消息(coordinator 关闭路径保留 recovery,// 补发会把用户关掉的会话重新拉起来),后者会把结果错绑到下一个会话实例(codex P1)。+ interruptedTurnAutoResumeGuard.noteSessionReset(session.id);autoResumeBookkeeping.teardown(session.id);agentInputCoordinatorHolder?.onSessionClosed(session.id);// 会话关闭:兑现延迟凭证切换(直接写 route),并唤醒被它挡住的等待者。@@ -7754,17 +7864,44 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// 这条防死循环的硬保证就没了 —— 上游连环抽风时会无限自动续跑。if (isAutoResumeUserMessage(message.agentMeta)) {// 这条自动续跑消息的结果还不知道,登记待确认(产出→succeeded / 再被打断→failed)。- autoResumeBookkeeping.registerPendingOutcome(sessionId, message.clientId);+ const attemptToken = autoResumeAttemptTokenFromAgentMeta(message.agentMeta);+ if (attemptToken !== null) {+ autoResumeBookkeeping.registerPendingOutcome(+ sessionId,+ attemptToken,+ message.clientId,+ );+ }} else {+ const origin =+ message.agentMeta && typeof message.agentMeta === 'object'+ ? (message.agentMeta as { origin?: unknown }).origin+ : undefined;+ const originKind =+ origin && typeof origin === 'object'+ ? (origin as { kind?: unknown }).kind+ : undefined;+ // Scheduler prompts are automatic inputs, not fresh human intervention. They may+ // share the coordinator persistence path with composer messages, but must not recharge+ // the interrupted-turn episode budget and defeat its hard upper bound.+ const isAutomaticPrompt =+ originKind === 'scheduler' || originKind === 'goal' || originKind === 'orca';silentStopAutoResumeGuard.noteUserSend(sessionId);- interruptedTurnAutoResumeGuard.noteUserSend(sessionId);+ if (!isAutomaticPrompt) interruptedTurnAutoResumeGuard.noteUserSend(sessionId);}// 落库失败 → 撤掉刚才那条待确认登记:那条消息压根不存在,留着会让后续事件去 patch// 一个不存在的 clientId,map 也一直脏着(copilot review)。登记刻意放在写之前(不能// 让写完到登记之间的事件漏掉结算),所以这里补一条失败回滚。const releasePendingOutcomeOnFailure = () => {if (!isAutoResumeUserMessage(message.agentMeta)) return;- autoResumeBookkeeping.releasePendingOutcome(sessionId, message.clientId);+ const attemptToken = autoResumeAttemptTokenFromAgentMeta(message.agentMeta);+ if (attemptToken !== null) {+ autoResumeBookkeeping.releasePendingOutcome(+ sessionId,+ attemptToken,+ message.clientId,+ );+ }};const result = await enqueueDurableWrite(`user:${sessionId}:${message.clientId}`, () => {// Coordinator accepts can stamp transcriptParentUuid early; this late FIFO@@ -7824,9 +7961,6 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)commitUserPromptPreview: (sessionId, clientId) => {commitAgentIslandUserPrompt(sessionId, clientId);if (clientId) {- // Session.send has returned accepted=true. This is the exact authoritative- // success boundary even when synchronous provider events already made the- // coordinator active turn stale before onDispatchedUserTurn can run.autoResumeBookkeeping.discardSuppressedErrorForRetry(sessionId, clientId);}},@@ -8056,12 +8190,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)/*** Finalize an exact retry owner that never crossed vendor dispatch.- *- * Technical delivery failure surfaces the suppressed error once. Explicit user- * cancellation persists it without attention and closes the replacement Island- * lifecycle, so delayed provider tails cannot turn the cancelled retry into a- * false success. Both queued discard and persisted/pre-dispatch cancellation use- * this boundary; keeping the disposition here prevents those paths from drifting.+ * Technical failure surfaces the suppressed error; explicit cancellation+ * persists it quietly and closes the replacement Island lifecycle.*/const finalizeUndispatchedClaimedRetry = (sessionId: string,@@ -8275,14 +8405,20 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// 两处必须同判据 —— 否则会出现"按住了却永远不接管"或"没按住却接管"的错配。isResumableTurnErrorCandidate: (signals: InterruptedTurnErrorSignals) =>isInterruptedTurnError(signals),- // 被按住的 error 最终没接管:统一从 bookkeeping 释放。真正成为最终失败时同步到- // Agent Island;被用户接手或被另一条技术错误顶替时只补历史,不再打扰用户。+ // 被按住的 error 最终没接管 → 只补落 error 行(横幅 coordinator 自己设)。onResumableTurnErrorDiscarded: (sessionId: string,- options: { surfaceError: boolean },+ options: { surfaceError: boolean; owner: SuppressedTurnErrorOwner },) => {- if (options.surfaceError) autoResumeBookkeeping.surfaceSuppressedError(sessionId);- else autoResumeBookkeeping.flushSuppressedError(sessionId);+ if (options.surfaceError) {+ autoResumeBookkeeping.surfaceSuppressedError(sessionId, {+ deferredOwner: options.owner,+ });+ } else {+ autoResumeBookkeeping.flushSuppressedError(sessionId, {+ deferredOwner: options.owner,+ });+ }},onResumableTurnError: (sessionId: string,@@ -8316,64 +8452,89 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)sessionId,attempt: decision.attempt,maxAttempts: decision.maxAttempts,+ episodeAttempt: decision.episodeAttempt,+ maxEpisodeAttempts: decision.maxEpisodeAttempts,sessionTotal: decision.sessionTotal,+ attemptToken: decision.attemptToken,delayMs: decision.delayMs,});+ autoResumeBookkeeping.beginAttempt(sessionId, decision.attemptToken);const schedulerRunId =item.origin?.kind === 'scheduler' && typeof item.origin.runId === 'string'? item.origin.runId: null;- if (schedulerRunId) beginSchedulerAutoResume(sessionId, schedulerRunId);+ if (schedulerRunId) {+ beginSchedulerAutoResume(sessionId, schedulerRunId, decision.attemptToken);+ }// 排期的撤旧、补落与令牌都在 AutoResumeBookkeeping.schedule 里(带单测),这里只给// 退避时长和到点要干的事。- autoResumeBookkeeping.schedule(sessionId, decision.delayMs, async (attempt) => {- try {- // 退避窗口内用户可能已经自己发了消息 / 清了会话。判据是 coordinator 的 recovery- // 与**接管态**(enqueue / clearError / teardown 会清掉接管态,recovery 未必),- // autoRetryLastError 内部复核后会 no-op 并返回非 resumed —— 此时必须回滚- // pendingResume。- const outcome = await inputCoordinator.autoRetryLastError(sessionId);- // Timer fire 不是 ownership 终点。上面的 DB 判定 await 期间,用户可能已用- // Manual Retry / clearError / 新输入接管;旧回调不得再 disposition 新 owner。- if (!attempt.isCurrent()) {- log.debug('interrupted-turn auto-resume completion superseded', {- sessionId,- outcome,- });- return;- }- if (outcome !== 'resumed') {- interruptedTurnAutoResumeGuard.noteResumeSendFailed(sessionId);- // superseded = 用户自己接手了,别再弹横幅打扰(但中断要补进历史);- // no-progress = 零产出、按设计不自动续跑,这是一次没人接手的真失败,- // 必须把横幅还给用户,否则被静默吞掉(copilot review)。- autoResumeBookkeeping.finalizeSuppressedError(sessionId, {- surfaceError: outcome === 'no-progress',- });- log.debug('interrupted-turn auto-resume not dispatched', { sessionId, outcome });- return;- }- // resumed 只表示续跑项已经进队;被压住的错误继续由那条 item 的 clientId- // 持有,直到灵动岛建立 replacement-turn 边界并真正跨过 vendor dispatch。- // Schedule 的 run 接管标记也不能在这里清:它会在续跑项即将进入- // vendor 前清掉,让同步返回的新 terminal error 只能靠**本 attempt**重新接管;- // 派发前被 Stop / clear / ghost block 丢弃时仍由 discard/undispatched 回调- // 立即失败同一个 run。- log.info('interrupted-turn auto-resume dispatched', { sessionId });- } catch (err) {- if (!attempt.isCurrent()) {- log.debug('interrupted-turn auto-resume rejection superseded', { sessionId });- return;- }- interruptedTurnAutoResumeGuard.noteResumeSendFailed(sessionId);- // 补发本身失败 → 回落成常规错误呈现,让用户能手点重试。- autoResumeBookkeeping.finalizeSuppressedError(sessionId, { surfaceError: true });- log.warn('interrupted-turn auto-resume failed', {- sessionId,- error: err instanceof Error ? err.message : String(err),- });- }- });+ autoResumeBookkeeping.schedule(+ sessionId,+ decision.attemptToken,+ decision.delayMs,+ (attempt) => {+ return (async () => {+ try {+ // 退避窗口内用户可能已经自己发了消息 / 清了会话。判据是 coordinator 的 recovery+ // 与**接管态**(enqueue / clearError / teardown 会清掉接管态,recovery 未必),+ // autoRetryLastError 内部复核后会 no-op 并返回非 resumed —— 此时必须回滚+ // pendingResume。+ const outcome = await inputCoordinator.autoRetryLastError(+ sessionId,+ decision.attemptToken,+ );+ if (!attempt.isCurrent()) {+ log.debug('interrupted-turn auto-resume completion superseded', {+ sessionId,+ outcome,+ });+ return;+ }+ if (outcome !== 'resumed') {+ interruptedTurnAutoResumeGuard.noteResumeSendFailed(+ sessionId,+ decision.attemptToken,+ );+ // superseded = 用户自己接手了,别再弹横幅打扰(但中断要补进历史);+ // no-progress = 零产出、按设计不自动续跑,这是一次没人接手的真失败,+ // 必须把横幅还给用户,否则被静默吞掉(copilot review)。+ autoResumeBookkeeping.finalizeSuppressedError(+ sessionId,+ decision.attemptToken,+ {+ surfaceBanner: outcome === 'no-progress',+ },+ );+ log.debug('interrupted-turn auto-resume not dispatched', { sessionId, outcome });+ return;+ }+ // resumed 只表示续跑项已经进队。被压住的错误要等 vendor 真正接受后再丢弃;+ // 派发前被 Stop / clear / ghost block 丢弃时,discard/undispatched 回调会恢复+ // 原 recovery 并把错误回落给用户。+ log.info('interrupted-turn auto-resume queued', { sessionId });+ } catch (err) {+ if (!attempt.isCurrent()) {+ log.debug('interrupted-turn auto-resume rejection superseded', { sessionId });+ return;+ }+ interruptedTurnAutoResumeGuard.noteResumeSendFailed(+ sessionId,+ decision.attemptToken,+ );+ // 补发本身失败 → 回落成常规错误呈现,让用户能手点重试。+ autoResumeBookkeeping.finalizeSuppressedError(+ sessionId,+ decision.attemptToken,+ { surfaceBanner: true },+ );+ log.warn('interrupted-turn auto-resume failed', {+ sessionId,+ error: err instanceof Error ? err.message : String(err),+ });+ }+ })();+ },+ );// 回传展示信息:coordinator 存进 autoResumePending → projection → 活动行// (「重新连接中 attempt/maxAttempts」+ 展开详情里的原因与会话累计)。return {@@ -8441,16 +8602,28 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)return orcaInterAgentDispatcher.runQueuedOrcaInterAgentAcceptedCallback(sessionId, item);},onDispatchedUserTurn: async (sessionId, item, preVendorDispatchAt): Promise<void> => {+ const attemptToken = autoResumeAttemptToken(item);+ if (+ attemptToken !== null &&+ autoResumeBookkeeping.discardSuppressedError(sessionId, attemptToken)+ ) {+ // sendToAgent may synchronously emit the next terminal error. If a newer attempt already+ // owns the takeover, retain its suppressed error and let that attempt settle it.+ log.info('interrupted-turn auto-resume accepted by vendor', {+ sessionId,+ clientId: item.clientId,+ attemptToken,+ });+ }if (item.autoResume &&item.origin?.kind === 'scheduler' &&typeof item.origin.runId === 'string' &&- // sendToAgent may synchronously emit the next recoverable terminal error.- // In that case the coordinator already owns a renewed auto-resume attempt;- // this older dispatch must not clear the same scheduler run's new claim.- !inputCoordinator.isAutoResumePending(sessionId)+ attemptToken !== null) {- clearSchedulerAutoResumePending(sessionId, item.origin.runId);+ // 只有 vendor dispatch 已不可逆后才释放 scheduler claim。token 比对保证+ // sendToAgent 同步触发的新 attempt(即使 runId 相同)不会被旧派发清掉。+ clearSchedulerAutoResumePending(sessionId, item.origin.runId, attemptToken);}// 「继续任务」只能在 vendor dispatch 不可逆后 durable ack:// - enqueue 时 ack:排队可取消,旧中断横幅回不来;@@ -8471,12 +8644,23 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)noteSessionClearBoundary,// 失败 turn 重试 → hook 侧把这一轮接回渠道那条已收口的消息。source 区分// 人工与自动续跑:只有真人接手才作废 scheduler waiter,自动路径不能取消自己。- onUiRetry: (sessionId, clientId, source) => {+ onUiRetry: (sessionId, clientId, source, attemptToken) => {autoResumeBookkeeping.claimSuppressedErrorForRetry(sessionId, clientId, source);+ if (source === 'auto' && attemptToken !== undefined) {+ autoResumeBookkeeping.bindSuppressedErrorToClient(+ sessionId,+ attemptToken,+ clientId,+ );+ }if (source === 'manual') {// UI continuation can dispatch before the scheduler backoff callback.// Retire that pending waiter first so it cannot consume the manual retry.failPendingSchedulerAutoResume(sessionId);+ // The click itself is the human intervention boundary. Reset here, before any+ // persistence/vendor await, so a failed manual retry still starts a fresh episode.+ silentStopAutoResumeGuard.noteUserSend(sessionId);+ interruptedTurnAutoResumeGuard.noteUserSend(sessionId);}publishUiContinuation(sessionId, clientId);},@@ -8484,7 +8668,6 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// 用 enqueue 入口而不是消息文本: 零产出重试重发的是原文, 文本上无从区分,// 而它走 unshift 不经这里, 于是不会把自己的回流作废掉。onUserEnqueue: (sessionId) => {- // 同步撤掉 timer / in-flight lease 与未认领的 Island filter,新 turn 不继承旧失败。autoResumeBookkeeping.supersedeUnclaimedErrorForUserIntervention(sessionId);// The user turn can dispatch before the backoff callback observes that its// recovery was superseded. Fail the scheduler waiter synchronously so it@@ -8492,19 +8675,32 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)failPendingSchedulerAutoResume(sessionId);publishUiSessionIntervention(sessionId);},- // 技术硬失败 / policy block 与用户 Stop/clear 是两种 disposition:前者没有人接手,- // 被压住的中断就是最终错误,必须一次性恢复到历史与 Agent Island。+ onAutomaticEnqueue: (sessionId) => {+ // Orca 等自动输入会推进同一会话,必须撤销旧 retry owner,避免它消费这轮事件;+ // 但预算充值仍只发生在真人消息的持久化路径,自动输入不会重置 episode。+ autoResumeBookkeeping.supersedeUnclaimedErrorForUserIntervention(sessionId);+ failPendingSchedulerAutoResume(sessionId);+ publishUiSessionIntervention(sessionId);+ },onRejectedUserTurn: (sessionId, item) => {+ // Auto-resume items have an exact-token cleanup boundary below. Keep+ // their attempt lease until that boundary can restore recovery and+ // finalize the suppressed error; releasing it here would make a later+ // undispatched discard skip finalizeSuppressedError.+ if (item.autoResume) return;autoResumeBookkeeping.surfaceSuppressedErrorForRetry(sessionId, item.clientId);},// 队列项未派发即被丢弃(stop/remove/clearSession) → 释放暂存的 accepted 副作用, 防回调表泄漏。onDiscardedQueuedMessage: (sessionId, item) => {orcaInterAgentDispatcher.discardQueuedOrcaInterAgentAcceptedCallback(item.clientId);- // 通用 discard 只做非打扰补落:Stop / clear / remove 不应复活旧错误;policy block- // 已先经 onRejectedUserTurn surface,这里按 clientId 会安全 no-op。+ // Auto-resume cleanup must run before generic claimed-retry release:+ // settleOutcome may drop the attempt lease, while finalizeSuppressedError+ // still needs the suppressed entry/current token to complete takeover drain.+ const autoResume = item.autoResume === true;+ if (autoResume) settleUndispatchedInterruptedAutoResume(sessionId, item);finalizeUndispatchedClaimedRetry(sessionId, item, 'cancelled');// 持久化中的项在这里被取消后不会再走 onUndispatchedUserTurn,复用同一结算出口。- settleUndispatchedAutoResumeOutcome(sessionId, item);+ if (!autoResume) settleUndispatchedInterruptedAutoResume(sessionId, item);// 排队心跳被丢弃 → 通知 runner 按 aborted 收尾对应 run,不让 fire 永久挂起。const watcher = schedulerQueuedPromptDiscardWatchers.get(item.clientId);if (watcher) {@@ -8518,16 +8714,6 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)});}}- if (- item.autoResume &&- item.origin?.kind === 'scheduler' &&- typeof item.origin.runId === 'string'- ) {- // 续跑还没跨过持久化边界,不会进入 onUndispatchedUserTurn;把普通聊天守卫- // 的 pendingResume 一并回滚,避免本次 Stop / block 让后续中断永远失去自愈。- interruptedTurnAutoResumeGuard.noteResumeSendFailed(sessionId);- notifySchedulerAutoResumeFailed(sessionId, item.origin.runId);- }},hasPendingCredentialSwitch: (sessionId) => {if (pendingCredentialSwitchHolder?.has(sessionId) === true) return true;@@ -8560,18 +8746,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)onUserMessageRewritten: (sessionId, item, info) =>broadcastGhostMessageRewritten({ sessionId, clientId: item.clientId, ...info }),beforeDispatchUserTurn: (sessionId, item) => {- if (- item.autoResume &&- item.origin?.kind === 'scheduler' &&- typeof item.origin.runId === 'string'- ) {- // 旧 attempt 的接管标记不能跨进下一次 vendor dispatch:sendToAgent 可能在- // 返回前同步发出新的 terminal error。先清旧标记后,可恢复错误会由同一条- // onResumableTurnError 链重新 begin;认证/计费等确定性错误则保持未接管,- // runner 会立即失败。若在真正 dispatch 前取消,下面的 undispatched 回调- // 仍会按 item.origin 精确通知对应 run,不会静默丢失。- clearSchedulerAutoResumePending(sessionId, item.origin.runId);- }+ autoResumeBookkeeping.markReplacementDispatching(sessionId, item.clientId);// hook 续跑回流的**权威归属点**: 在 vendor dispatch 之前(本回调被 await), 所以// 观察器挂上就不丢正文开头, 而 live session 此刻必然已就绪。clientId 对得上的// 才是目标续跑轮 —— 绕过 coordinator 的 turn(silent-stop 自动续跑)不走这里,@@ -8583,25 +8758,15 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// 目标轮落库了却没能 dispatch(取消 / 失败): 记账该立刻还回去, 而不是等超时。publishUiTurnUndispatched(sessionId, item.clientId);gitSnapshotCoordinator?.onTurnAbort(sessionId);- // persisted/pre-dispatch 与仍在队列的取消共用同一个 exact-owner 终局;技术失败- // 必须 surface,用户接管则进入 stopped,二者不能再靠调用路径隐式推断。+ autoResumeBookkeeping.rollbackReplacementPreview(sessionId, item.clientId);+ const autoResume = item.autoResume === true;+ if (autoResume) settleUndispatchedInterruptedAutoResume(sessionId, item);finalizeUndispatchedClaimedRetry(sessionId, item, disposition);// 自动续跑那条消息已落库、却最终没派出去 → 这次重连就是失败。**必须在这里钉死**:// 它不会产生任何 turn 事件,新加的终态结算路径够不到它,待确认记录于是悬空,被之后// 任何一个无关的 text / tool 事件误标成「已重新连接」(codex P1)。// 按 clientId 匹配 —— 别的 turn 未派发不该动这条记录。- if (settleUndispatchedAutoResumeOutcome(sessionId, item)) {- // 同时把守卫的 pendingResume 回滚:不回滚会让该会话之后的中断永远被判成- // 「上一次还在路上」,再也不自愈(不变量 I5)。- interruptedTurnAutoResumeGuard.noteResumeSendFailed(sessionId);- }- if (- item.autoResume &&- item.origin?.kind === 'scheduler' &&- typeof item.origin.runId === 'string'- ) {- notifySchedulerAutoResumeFailed(sessionId, item.origin.runId);- }+ if (!autoResume) settleUndispatchedInterruptedAutoResume(sessionId, item);},// Thread 3 fix: called from drain/dispatchCompact failure paths where the item// was removed from the queue but not put back (persisted-failure case). If no@@ -10628,7 +10793,11 @@ function emitWorkDirMissingError(}function redactEventForRenderer(event: AgentEvent): AgentEvent {- if (!event.data || typeof event.data !== 'object') return event;+ // These are main/maker-core lifecycle fields, not renderer data. Keep them on the main-side+ // event used for bookkeeping but never expose them through the raw renderer channel.+ const rendererEvent = { ...event };+ delete rendererEvent.turnAttemptToken;+ if (!event.data || typeof event.data !== 'object') return rendererEvent;const data = event.data as Record<string, unknown>;const safeData = { ...data };@@ -10661,7 +10830,7 @@ function redactEventForRenderer(event: AgentEvent): AgentEvent {safeData.raw = raw;}- return changed ? ({ ...event, data: safeData } as AgentEvent) : event;+ return changed ? ({ ...rendererEvent, data: safeData } as AgentEvent) : rendererEvent;}function broadcastToAllWindows(channel: string, payload: unknown): void {diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.tsindex d9c47e103c..3e5bdb45f2 100644--- a/packages/maker-core/src/agents/base-agent.ts+++ b/packages/maker-core/src/agents/base-agent.ts@@ -983,6 +983,8 @@ export interface SendOptions {* 共享 session 下区分自动任务 turn 与用户 turn。agent 子类不消费,透传无害。*/origin?: SendOrigin;+ /** Host-owned per-turn correlation copied onto every AgentEvent for lifecycle settlement. */+ turnAttemptToken?: number;/*** Host-owned, per-turn permission policy. This is deliberately a callback* rather than prompt text: providers must enforce it at their pre-executiondiff --git a/packages/maker-core/src/maker.test.ts b/packages/maker-core/src/maker.test.tsindex 71e9ef9679..01413bc2f3 100644--- a/packages/maker-core/src/maker.test.ts+++ b/packages/maker-core/src/maker.test.ts@@ -2211,9 +2211,10 @@ describe('Session turn send guard', () => {await expect(close).resolves.toBe(true);});- it('releases the reservation when handle.send fails before a turn starts', async () => {+ it('releases the failed send reservation but fences reuse until terminal drain closes', async () => {const handle = createHandle({ id: 'thread-1' });const firstError = new Error('boom');+ handle.close = vi.fn(async () => undefined);handle.send = vi.fn().mockRejectedValueOnce(firstError).mockResolvedValueOnce(undefined);@@ -2225,10 +2226,20 @@ describe('Session turn send guard', () => {capabilities: createAgent(async () => handle).capabilities,logger: createLogger(),});+ const closed = new Promise<void>((resolve) => {+ session.onStatusChange((status) => {+ if (status === 'closed') resolve();+ });+ });await expect(session.send('first')).rejects.toBe(firstError);- await expect(session.send('second')).resolves.toEqual({ accepted: true });- expect(handle.send).toHaveBeenCalledTimes(2);+ expect(session.isTurnRunning()).toBe(false);+ await expect(session.send('second')).rejects.toMatchObject({ code: 'SESSION_RUNNING' });+ expect(handle.send).toHaveBeenCalledTimes(1);++ await closed;+ expect(session.getStatus()).toBe('closed');+ expect(handle.close).toHaveBeenCalledTimes(1);});});diff --git a/packages/maker-core/src/session.origin.test.ts b/packages/maker-core/src/session.origin.test.tsindex f73887e137..06fbf3ec63 100644--- a/packages/maker-core/src/session.origin.test.ts+++ b/packages/maker-core/src/session.origin.test.ts@@ -11,6 +11,7 @@ import path from 'node:path';import { Session } from './session.js';import type { AgentSessionHandle } from './agents/base-agent.js';import type { AgentEvent, InteractionDecision, InteractionRequest, SendOrigin } from './types/events.js';+import type { AgentKind } from './types/common.js';function createLogger() {const logger = {@@ -24,23 +25,49 @@ function createLogger() {* 可控事件流的 fake handle:send 后通过 emit() 往事件流逐条推 AgentEvent。* isTurnRunning 跟随 send/terminal 翻转,模拟真实 turn 边界。*/-function createControllableHandle(opts?: { sendError?: Error }) {+function createControllableHandle(opts?: {+ sendError?: Error;+ sendErrorOnSend?: number;+ agentKind?: AgentKind;+ dispatchEvent?: AgentEvent;+ dispatchOnSend?: number;+ holdDispatch?: boolean;+ holdOnSend?: number;+}) {let push: ((e: AgentEvent) => void) | null = null;let turnRunning = false;+ let closeCalls = 0;+ let releaseDispatch: (() => void) | null = null;+ let sendCount = 0;const buffered: AgentEvent[] = [];let interactionResolver: ((req: InteractionRequest) => Promise<InteractionDecision>) | null = null;const handle: AgentSessionHandle = {id: 'thread-1',- agentKind: 'codex',+ agentKind: opts?.agentKind ?? 'codex',model: 'gpt-5.4',async send() {- if (opts?.sendError) throw opts.sendError; // 模拟 dispatch 失败(SESSION_RUNNING race)+ sendCount += 1;+ if (opts?.sendError && (opts.sendErrorOnSend ?? 1) === sendCount) {+ throw opts.sendError; // 模拟 dispatch 失败(SESSION_RUNNING race)+ }+ if (opts?.dispatchEvent && (opts.dispatchOnSend ?? 1) === sendCount) {+ if (push) push(opts.dispatchEvent);+ else buffered.push(opts.dispatchEvent);+ }+ if (opts?.holdDispatch && (opts.holdOnSend ?? 1) === sendCount) {+ await new Promise<void>((resolve) => {+ releaseDispatch = resolve;+ });+ }turnRunning = true;},async steer() {},async abort() {},- async close() {},+ async close() {+ closeCalls += 1;+ turnRunning = false;+ },async *events() {for (const e of buffered) yield e;buffered.length = 0;@@ -72,18 +99,32 @@ function createControllableHandle(opts?: { sendError?: Error }) {* SDK 处理 /compact 后发 done 但 handle 端 turnInFlight 仍是 true)。*/async emit(e: AgentEvent, opts: { keepRunning?: boolean } = {}) {- if ((e.type === 'done' || e.type === 'error') && !opts.keepRunning) turnRunning = false;+ const terminalError =+ e.type === 'error' &&+ (e.data as { isTerminal?: unknown } | null | undefined)?.isTerminal === true;+ if ((e.type === 'done' || terminalError) && !opts.keepRunning) turnRunning = false;if (push) push(e);else buffered.push(e);await new Promise((r) => setTimeout(r, 0)); // 让事件循环把它 fan-out 出去},+ setTurnRunning(running: boolean) {+ turnRunning = running;+ },+ releaseDispatch() {+ releaseDispatch?.();+ },+ queue(event: AgentEvent) {+ if (push) push(event);+ else buffered.push(event);+ },+ closeCalls: () => closeCalls,};}-function makeSession(handle: AgentSessionHandle): Session {+function makeSession(handle: AgentSessionHandle, agentKind: AgentKind = 'codex'): Session {return new Session({id: 'session-1',- agentKind: 'codex',+ agentKind,workDir: path.join('workspace', 'repo'),handle,capabilities: {} as never,@@ -221,6 +262,235 @@ describe('Session per-turn origin 打标', () => {expect(seen.every((e) => e.turnOrigin === undefined)).toBe(true);});+ it('带 runtime turnAttemptToken 的 send → 每个事件带同一 token,终态后清空', async () => {+ const { handle, emit } = createControllableHandle();+ const session = makeSession(handle);+ const seen: AgentEvent[] = [];+ session.onEvent((e) => seen.push({ ...e }));++ await session.send('auto retry', { turnAttemptToken: 7 });+ await emit({ type: 'text', data: { text: 'progress', isFinal: false } });+ await emit({ type: 'done', data: {} });+ await emit({ type: 'status', data: { isRunning: false } });++ expect(seen.slice(0, 2).map((event) => event.turnAttemptToken)).toEqual([7, 7]);+ expect(seen[2]?.turnAttemptToken).toBeUndefined();+ });++ it('Codex 在 provider 启动前报终态 error → 通过 event-loop generation 归属当前 attempt', async () => {+ const { handle, releaseDispatch } = createControllableHandle({+ dispatchEvent: {+ type: 'error',+ data: { message: 'dispatch failed', isTerminal: true },+ source: 'codex',+ },+ holdDispatch: true,+ });+ const session = makeSession(handle);+ const seen: AgentEvent[] = [];+ session.onEvent((event) => seen.push({ ...event }));++ const send = session.send('go', {+ origin: SCHED_ORIGIN,+ turnAttemptToken: 9,+ });+ await new Promise((resolve) => setTimeout(resolve, 0));++ expect(seen[0]).toEqual(expect.objectContaining({+ type: 'error',+ turnOrigin: SCHED_ORIGIN,+ turnAttemptToken: 9,+ }));+ releaseDispatch();+ await send;+ await session.close();+ });++ it('排队中的旧 Codex terminal error 不能冒领随后 dispatch 的 attempt token', async () => {+ const { handle, emit, queue, setTurnRunning, releaseDispatch } = createControllableHandle({+ dispatchEvent: {+ type: 'error',+ data: { message: 'second failed', isTerminal: true },+ source: 'codex',+ },+ dispatchOnSend: 2,+ holdDispatch: true,+ holdOnSend: 2,+ });+ const session = makeSession(handle);+ const seen: AgentEvent[] = [];+ session.onEvent((event) => seen.push({ ...event }));++ await session.send('first');+ await emit({ type: 'text', data: { text: 'first progress', isFinal: false } });+ setTurnRunning(false);+ queue({+ type: 'error',+ data: { message: 'first late failure', isTerminal: true },+ source: 'codex',+ });+ const second = session.send('second', {+ origin: SCHED_ORIGIN,+ turnAttemptToken: 2,+ });+ await new Promise((resolve) => setTimeout(resolve, 0));++ const late = seen.find((event) =>+ event.type === 'error' && (event.data as { message?: string }).message === 'first late failure');+ expect(late?.turnAttemptToken).toBeUndefined();+ expect(late?.turnOrigin).toBeUndefined();+ releaseDispatch();+ await second;+ await session.close();+ });++ it('terminal error 后先排空尾部,再允许新 attempt', async () => {+ const { handle, emit } = createControllableHandle();+ const session = makeSession(handle);+ const seen: AgentEvent[] = [];+ session.onEvent((event) => seen.push({ ...event }));++ await session.send('first', { turnAttemptToken: 1 });+ await emit({ type: 'error', data: { message: 'first failed', isTerminal: true } });++ await expect(session.send('second', { turnAttemptToken: 2 })).rejects.toMatchObject({+ code: 'SESSION_RUNNING',+ });+ await emit({ type: 'done', data: { reason: 'first-tail' } });+ await session.send('second', { turnAttemptToken: 2 });+ await emit({ type: 'error', data: { message: 'second failed', isTerminal: true } });++ expect(seen.map((event) => event.type)).toEqual(['error', 'done', 'error']);+ expect(seen[0]?.turnAttemptToken).toBe(1);+ expect(seen[1]?.turnAttemptToken).toBeUndefined();+ expect(seen[2]?.turnAttemptToken).toBe(2);+ });++ it('terminal error 后的 Codex idle status 会清 drain,不会误关健康 session', async () => {+ const { handle, emit, closeCalls } = createControllableHandle();+ const session = makeSession(handle);++ await session.send('first');+ await emit({ type: 'error', data: { message: 'first failed', isTerminal: true } });+ await emit({ type: 'status', data: { isRunning: false } });++ await expect(session.send('second', { turnAttemptToken: 2 })).resolves.toEqual({ accepted: true });+ await new Promise((resolve) => setTimeout(resolve, 300));+ expect(closeCalls()).toBe(0);+ });++ it('Claude terminal error 后的 idle status 不能越过 queued done 提前解锁', async () => {+ const { handle, emit } = createControllableHandle({ agentKind: 'claude-code' });+ const session = makeSession(handle, 'claude-code');++ await session.send('first');+ await emit({+ type: 'error',+ data: { message: 'first failed', isTerminal: true },+ source: 'claude-code',+ });+ await emit({ type: 'status', data: { isRunning: false }, source: 'claude-code' });++ await expect(session.send('second')).rejects.toMatchObject({ code: 'SESSION_RUNNING' });+ await emit({ type: 'done', data: {}, source: 'claude-code' });+ await expect(session.send('second')).resolves.toEqual({ accepted: true });+ await session.close();+ });++ it('non-terminal error 不启动 terminal drain,也不打开 generation fence', async () => {+ const { handle, emit, setTurnRunning, closeCalls } = createControllableHandle();+ const session = makeSession(handle);+ const seen: AgentEvent[] = [];+ session.onEvent((event) => seen.push({ ...event }));++ await session.send('first');+ await emit({ type: 'error', data: { message: 'retryable', isTerminal: false } });+ await new Promise((resolve) => setTimeout(resolve, 300));+ expect(closeCalls()).toBe(0);++ await emit({ type: 'text', data: { text: 'still running', isFinal: false } });+ setTurnRunning(false);+ expect(session.isTurnRunning()).toBe(false);+ await session.send('second', { turnAttemptToken: 2 });+ await emit({ type: 'done', data: {} }, { keepRunning: true });+ await emit({ type: 'text', data: { text: 'second turn', isFinal: false } });++ expect(seen.find((event) => event.type === 'text' &&+ (event.data as { text?: string }).text === 'second turn')?.turnAttemptToken).toBe(2);+ });++ it('普通事件不能让旧 turn 的迟到 done 冒领下一代 token', async () => {+ const { handle, emit, setTurnRunning } = createControllableHandle();+ const session = makeSession(handle);+ const seen: AgentEvent[] = [];+ session.onEvent((event) => seen.push({ ...event }));++ await session.send('first');+ await emit({ type: 'text', data: { text: 'first progress', isFinal: false } });+ setTurnRunning(false);+ expect(session.isTurnRunning()).toBe(false);+ await session.send('second', { turnAttemptToken: 2 });+ await emit({ type: 'done', data: { reason: 'late first tail' } }, { keepRunning: true });+ await emit({ type: 'text', data: { text: 'second progress', isFinal: false } });++ const lateDone = seen.find((event) => event.type === 'done');+ const secondText = seen.find(+ (event) => event.type === 'text' &&+ (event.data as { text?: string }).text === 'second progress',+ );+ expect(lateDone?.turnAttemptToken).toBeUndefined();+ expect(secondText?.turnAttemptToken).toBe(2);+ });++ it('event loop crash emits a terminal error and closes the poisoned session', async () => {+ let releaseCrash!: () => void;+ const crashReady = new Promise<void>((resolve) => {+ releaseCrash = resolve;+ });+ let turnRunning = false;+ const handle = {+ id: 'crashing-handle',+ agentKind: 'codex',+ model: 'gpt-5.4',+ async send() {+ turnRunning = true;+ },+ async steer() {},+ async abort() {},+ async close() {+ turnRunning = false;+ },+ async *events() {+ await crashReady;+ throw new Error('event stream crashed');+ },+ getUsageSnapshot: () => ({ tokenUsage: 0, contextTokens: 0, contextWindow: 0, costUsd: 0 }),+ setInteractionResolver() {},+ isTurnRunning: () => turnRunning,+ } as unknown as AgentSessionHandle;+ const session = makeSession(handle);+ const seen: AgentEvent[] = [];+ session.onEvent((event) => seen.push({ ...event }));+ const closed = new Promise<void>((resolve) => {+ session.onStatusChange((status) => {+ if (status === 'closed') resolve();+ });+ });++ await session.send('go', { turnAttemptToken: 1 });+ releaseCrash();+ await closed;++ expect(seen.at(-1)).toEqual(expect.objectContaining({+ type: 'error',+ data: expect.objectContaining({+ reason: 'session_event_loop_crashed',+ isTerminal: true,+ }),+ }));+ expect(session.getStatus()).toBe('closed');+ });+it('多 listener 拿到同一份 origin', async () => {const { handle, emit } = createControllableHandle();const session = makeSession(handle);@@ -252,6 +522,44 @@ describe('Session per-turn origin 打标', () => {expect(seen.at(-1)?.turnOrigin).toBeUndefined(); // origin 已清,不误打});+ it('dispatch 失败且没有旧尾事件时,drain 超时关闭歧义 session', async () => {+ const { handle, closeCalls } = createControllableHandle({+ sendError: new Error('boom-dispatch'),+ sendErrorOnSend: 1,+ });+ const session = makeSession(handle);++ await expect(session.send('failed', { turnAttemptToken: 1 })).rejects.toThrow('boom-dispatch');+ await expect(session.send('next', { turnAttemptToken: 2 })).rejects.toMatchObject({+ code: 'SESSION_RUNNING',+ });+ await new Promise((resolve) => setTimeout(resolve, 300));++ expect(closeCalls()).toBe(1);+ expect(session.getStatus()).toBe('closed');+ });++ it('dispatch 失败后的迟到终态不能冒领下一次 turn 的 token', async () => {+ const { handle, emit } = createControllableHandle({+ sendError: new Error('boom-dispatch'),+ sendErrorOnSend: 1,+ });+ const session = makeSession(handle);+ const seen: AgentEvent[] = [];+ session.onEvent((event) => seen.push({ ...event }));++ await expect(session.send('failed', { turnAttemptToken: 1 })).rejects.toThrow('boom-dispatch');+ await expect(session.send('next', { turnAttemptToken: 2 })).rejects.toMatchObject({+ code: 'SESSION_RUNNING',+ });+ await emit({ type: 'done', data: { reason: 'late failed-dispatch tail' } });+ await session.send('next', { turnAttemptToken: 2 });+ await emit({ type: 'text', data: { text: 'next turn progress', isFinal: false } });++ expect(seen[0]?.turnAttemptToken).toBeUndefined();+ expect(seen[1]?.turnAttemptToken).toBe(2);+ });+it('失败 send 还原(而非清空)正在跑 turn 的 origin —— turn1 的 done 仍带 origin(回归 Greptile P1)', async () => {// 场景:turn1(scheduler)还在跑、currentTurnOrigin=ORIGIN_1。turn2 在 turn1 的// done 尚未 fan-out 的窗口里发起(isTurnRunning 已翻 false → 越过 137 守卫),装上diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.tsindex c1129befb8..0a72d6a49d 100644--- a/packages/maker-core/src/session.ts+++ b/packages/maker-core/src/session.ts@@ -112,6 +112,8 @@ const TURN_STALL_SLICE_MS = 60_000;* 与 maker-scheduler 的 SUSPEND_GAP_MS 同量级:远大于正常的事件循环抖动。*/const TURN_STALL_SUSPEND_GAP_MS = 30_000;+/** Terminal error 的尾部 drain 宽限;超时后关闭句柄,下一次 send 由 Maker 重建。 */+const TERMINAL_ERROR_DRAIN_GRACE_MS = 250;function parseTurnStallMs(raw: string | undefined): number {if (raw === undefined || raw === '') return DEFAULT_TURN_STALL_MS;@@ -302,11 +304,13 @@ export class Session {private terminationStarted = false;private eventLoopStarted = false;/**- * 最近一次已观察到的终态事件属于哪个 Session turn generation;用于 iterator- * 崩溃时避免重复收口。不能只存一个 bool:上一轮已排队的 done 可能在新 turn- * 开始后才从 iterator 返回,不能拿它覆盖新 turn 的终态判据。+ * 最近一次已观察到的终态事件属于哪个 turn generation;事件迭代器可能在上一轮+ * 开始等待、下一轮 dispatch 后才返回旧事件,不能用一个 bool 判断是否已收口。*/private terminalEventObservedGeneration: number | null = null;+ /** 终态 error 后等待 provider 尾部 done;避免旧尾事件冒领下一轮。 */+ private terminalErrorDrainGeneration: number | null = null;+ private terminalErrorDrainTimer: ReturnType<typeof setTimeout> | null = null;private sendReservation: SendReservation | null = null;/*** 当前进行中 turn 的发起来源(来自 send 的 opts.origin)。事件 fan-out 前打到@@ -314,6 +318,8 @@ export class Session {* session(心跳 + 远程控制)下区分 per-turn 归属。null = 未标记来源(默认)。*/private currentTurnOrigin: SendOrigin | null = null;+ /** Host-owned per-turn correlation, kept beside origin and cleared at the terminal boundary. */+ private currentTurnAttemptToken: number | null = null;// ── turn 零事件看门狗(见 DEFAULT_TURN_STALL_MS)────────────────────────private readonly turnStallMs: number;private turnStallTimer: ReturnType<typeof setTimeout> | null = null;@@ -425,6 +431,15 @@ export class Session {: message;this.logger.debug('send', summarizeUserMessage(msg));this.ensureActive();+ if (this.terminalErrorDrainGeneration !== null) {+ throw this.createSessionRunningError();+ }+ // An auto-resume token remains owned until its terminal event has been fanned out. A vendor+ // may report idle one tick before that event; do not admit a new turn into that gap, or a late+ // old event could be attributed to the new attempt.+ if (this.currentTurnAttemptToken !== null && !this.isTurnRunning()) {+ throw this.createSessionRunningError();+ }if (this.isTurnRunning()) {throw this.createSessionRunningError();}@@ -436,6 +451,7 @@ export class Session {this.sendReservation = reservation;// 新一轮 turn 的代号(见 turnGeneration):看门狗的善后动作据此判断"还是不是那个// 卡死的 turn",避免误杀宽限期内新起的健康 turn。+ const previousTurnGeneration = this.turnGeneration;this.turnGeneration += 1;const cleanupExternalAbort = this.attachExternalCancellation(reservation, handleOpts.signal);// originInstalled:已越过 dispatch 边界、把本次 origin 装进 currentTurnOrigin。@@ -443,6 +459,7 @@ export class Session {let originInstalled = false;let turnDispatched = false;let previousTurnOrigin: SendOrigin | null = null;+ let previousTurnAttemptToken: number | null = null;const finishCancelledBeforeDispatch = (): SessionSendResult | null => {if (!reservation.cancelled && this.sendReservation === reservation) return null;if (this.sendReservation === reservation) this.sendReservation = null;@@ -476,7 +493,12 @@ export class Session {// 关联到具体 turn 事件而非单槽位(maker-core 热路径重构,规则 10),留作独立后续。previousTurnOrigin = this.currentTurnOrigin;this.currentTurnOrigin = handleOpts.origin ?? null;- this.terminalEventObservedGeneration = null;+ if (this.terminalErrorDrainGeneration === null) {+ this.terminalEventObservedGeneration = null;+ }+ previousTurnAttemptToken = this.currentTurnAttemptToken;+ this.currentTurnAttemptToken =+ typeof handleOpts.turnAttemptToken === 'number' ? handleOpts.turnAttemptToken : null;originInstalled = true;this.startEventLoopIfNeeded();try {@@ -521,6 +543,15 @@ export class Session {// state 污染下一轮(见 PR #129 review)。if (originInstalled && !turnDispatched) {this.currentTurnOrigin = previousTurnOrigin;+ this.currentTurnAttemptToken = previousTurnAttemptToken;+ this.turnGeneration = previousTurnGeneration;+ // runEventLoop may already be awaiting the failed generation. Reusing+ // the rolled-back generation immediately creates an ABA window where+ // a delayed terminal event from this failed dispatch can claim the+ // next turn's origin/token. Reuse the existing bounded tail fence:+ // an old terminal event releases it; no tail closes the ambiguous+ // Session so Maker can rebuild before the next send.+ this.armTerminalErrorDrain(previousTurnGeneration);}}}@@ -617,23 +648,22 @@ export class Session {let closeSucceeded = false;try {this.clearTurnStallWatchdog();+ this.clearTerminalErrorDrain();this.cancelSendReservation(this.sendReservation);await this.handle.close();closeSucceeded = true;} finally {this.sendReservation = null;this.currentTurnOrigin = null;+ this.currentTurnAttemptToken = null;this.eventListeners.clear();this.interactionListener = null;if (closeSucceeded) {this.setStatus('closed');this.statusListeners.clear();} else {- // handle.close() rejected: keep the Session in error rather than- // claiming the underlying transport is gone. Clear the rejected- // close promise so Maker can retry the same close before rebuilding- // this id; retain status listeners so a later successful retry still- // removes the Session from Maker.activeSessions.+ // 底层仍可能存活时不能发布 closed;保留 status listener,让 Maker 后续重试+ // close 时仍能从 activeSessions 移除,避免错误句柄永久占槽。this.closePromise = null;this.setStatus('error');}@@ -652,6 +682,8 @@ export class Session {} finally {this.sendReservation = null;this.currentTurnOrigin = null;+ this.currentTurnAttemptToken = null;+ this.clearTerminalErrorDrain();this.setStatus('closed');this.eventListeners.clear();this.statusListeners.clear();@@ -1108,26 +1140,43 @@ export class Session {private fanOutEvent(event: AgentEvent, observedGeneration = this.turnGeneration): void {this.lastEventAt = Date.now();this.lastEventType = event.type;+ const isCurrentGeneration = observedGeneration === this.turnGeneration;// fan-out 前打 turn origin(所有 listener 拿到同一份);事件对象由 translator// 每次新建、看门狗每次合成,不会串台。=== undefined 守卫:不覆盖 agent 自带的。- if (this.currentTurnOrigin && event.turnOrigin === undefined) {+ if (isCurrentGeneration && this.currentTurnOrigin && event.turnOrigin === undefined) {event.turnOrigin = this.currentTurnOrigin;}+ if (+ isCurrentGeneration &&+ this.currentTurnAttemptToken !== null &&+ event.turnAttemptToken === undefined+ ) {+ event.turnAttemptToken = this.currentTurnAttemptToken;+ }const isTerminal = event.type === 'done' || isTerminalAgentErrorEvent(event);- if (isTerminal) {- // 事件迭代器可能早在上一轮就已开始等待,上一轮排队的 done/error 会在新- // turn dispatch 后才返回。默认按 next() 开始等待时的 generation 归属;唯一- // 例外是 Codex provider send 仍 pending、handle 尚未置 running 时先到的 terminal- // error。Codex adapter 已按 turnId 过滤迟到错误,只有它允许 error 早于 turn/start- // response;其它 provider 不能靠 Session 的 reservation 瞬时状态推断归属。- const terminalBeforeProviderStartSettled =- event.type === 'error' &&- event.source === 'codex' &&- this.sendReservation?.phase === 'dispatching' &&- !this.isHandleTurnRunning();- if (observedGeneration === this.turnGeneration || terminalBeforeProviderStartSettled) {- this.terminalEventObservedGeneration = this.turnGeneration;+ // A dispatching send is not enough evidence that a terminal event belongs+ // to it: Codex can enqueue the previous turn's terminal error after flipping+ // its handle idle. Only runEventLoop's generation adoption may transfer+ // ownership to the new attempt.+ const terminalBoundaryObserved = isCurrentGeneration && isTerminal;+ if (terminalBoundaryObserved) {+ this.terminalEventObservedGeneration = this.turnGeneration;+ if (event.type === 'done') {+ this.clearTerminalErrorDrain();+ } else if (event.type === 'error') {+ this.armTerminalErrorDrain(this.turnGeneration);}+ } else if (+ this.agentKind === 'codex' &&+ isCurrentGeneration &&+ event.type === 'status' &&+ (event.data as { isRunning?: unknown } | null | undefined)?.isRunning === false &&+ this.terminalErrorDrainGeneration === this.turnGeneration+ ) {+ // Codex closes a terminal error with an idle status rather than a done+ // event. That status drains the provider tail, but it is not itself a+ // generation boundary for ordinary status events.+ this.clearTerminalErrorDrain();}const listenerEvent = redactEventForListeners(event);for (const listener of this.eventListeners) {@@ -1145,11 +1194,12 @@ export class Session {// 不应透传到 Session。凡是到达 Session 的 done / 终止型 error 都代表产品层// turn 已结束,必须清 origin,避免后续 standalone auto-compact 等后台 turn 继承// goal/scheduler origin。- if (isTerminal) {+ if (isCurrentGeneration && isTerminal) {this.currentTurnOrigin = null;+ this.currentTurnAttemptToken = null;// 终态之后不再计 stall 额度。this.clearTurnStallWatchdog();- } else {+ } else if (isCurrentGeneration) {this.armTurnStallWatchdog();}}@@ -1163,6 +1213,32 @@ export class Session {this.turnStallSliceStartedAt = 0;}+ private clearTerminalErrorDrain(): void {+ if (this.terminalErrorDrainTimer) {+ clearTimeout(this.terminalErrorDrainTimer);+ this.terminalErrorDrainTimer = null;+ }+ this.terminalErrorDrainGeneration = null;+ }++ private armTerminalErrorDrain(generation: number): void {+ this.clearTerminalErrorDrain();+ this.terminalErrorDrainGeneration = generation;+ const timer = setTimeout(() => {+ this.terminalErrorDrainTimer = null;+ if (this.terminalErrorDrainGeneration !== generation) return;+ this.logger.warn('terminal error drain timed out; closing session for rebuild', {+ generation,+ graceMs: TERMINAL_ERROR_DRAIN_GRACE_MS,+ });+ void this.close().catch((error) => {+ this.logger.warn('terminal error drain close failed', { error: String(error) });+ });+ }, TERMINAL_ERROR_DRAIN_GRACE_MS);+ this.terminalErrorDrainTimer = timer;+ (timer as unknown as { unref?: () => void }).unref?.();+ }+/*** (重新)起 turn 零事件看门狗。以下情形不起表:* - 阈值被关掉(0)@@ -1378,24 +1454,34 @@ export class Session {const iterator = this.handle.events()[Symbol.asyncIterator]();while (true) {const awaitingGeneration = this.turnGeneration;+ const awaitingCanAdoptNextGeneration =+ awaitingGeneration === 0 ||+ this.terminalEventObservedGeneration === awaitingGeneration;const result = await iterator.next();if (result.done) break;const event = result.value;this.releaseSendReservationIfObserved();+ let observedGeneration = awaitingGeneration;+ if (+ awaitingCanAdoptNextGeneration &&+ this.turnGeneration === awaitingGeneration + 1+ ) {+ // Only a next() that started while logically idle may follow the next send.+ // Capturing that fact before awaiting is essential. The terminal drain may+ // already be armed when a watchdog-generated error precedes this pending+ // next(); adopting the exact next generation lets the provider's tail done+ // clear that fence. The fence itself prevents any later generation entering.+ observedGeneration = this.turnGeneration;+ }// origin 打标与终态清理都收在 fanOutEvent 里(看门狗合成的事件共用同一语义,// 见那里的注释)。- this.fanOutEvent(event, awaitingGeneration);+ this.fanOutEvent(event, observedGeneration);}} catch (e) {this.logger.error('event loop crashed', { error: String(e) });if (this.closePromise || this.status === 'closed') return;- // 先占住 closing gate:terminal error 的 listener 可能同步尝试 send,不能让它- // 在底层 iterator 已经崩掉的窗口里重新进入 provider。复用 performClose,让- // closePromise 代表真实的 handle.close(),并在底层资源释放后再发布 closed。+ // 先占住 closing gate,避免 terminal error listener 在死掉的 iterator 上重新 send。this.closePromise = this.performClose();- // 终态事件可能属于已结束的上一轮,但新 turn 已经在 event loop 崩溃前被- // Session 接受。此时不能因为上一轮的 done/error 已观察过就吞掉本轮的- // `session_event_loop_crashed`,否则新 turn 只有 closed 没有终态 error。if (this.terminalEventObservedGeneration !== this.turnGeneration) {this.fanOutEvent({type: 'error',@@ -1427,10 +1513,7 @@ export class Session {// activeSessions.delete + emit 'session:closed' + lifecycleHooks.onClose → 下次// send 自然走 IPC lazy create-session 路径, 重建 handle / transport / 远端连接。//- // iterator 自然结束同样表示底层 handle 已死。显式 close/detach 已经占有收口权时,- // 不能让这里提前发布 closed:performClose 必须等 transport 真正关闭后再发布,失败- // 则保持 error 以便调用方重试。若活跃 turn 还没有观察到终态,先补一条与 crash- // 分支一致的 terminal error,避免 Desktop 把这一轮静默丢掉。+ // 仅当当前 status 还是 'active' 时切 — 'closed' / 'error' 已经表达终态, 不覆盖。if (this.terminationStarted || this.status === 'closed' || this.status === 'error') return;const unfinishedTurn =this.status === 'active' &&@@ -1438,8 +1521,6 @@ export class Session {this.terminalEventObservedGeneration !== this.turnGeneration;this.logger.debug('event loop ended (handle dead), auto-closing session', { unfinishedTurn });this.terminationStarted = true;- // 先占住 closing gate:terminal error 的 listener 可能同步尝试 send,不能让它在- // 底层 iterator 已经结束的窗口里重新进入 provider。this.closePromise = Promise.resolve();if (unfinishedTurn) {this.fanOutEvent({@@ -1456,6 +1537,7 @@ export class Session {this.cancelSendReservation(this.sendReservation);this.sendReservation = null;this.currentTurnOrigin = null;+ this.currentTurnAttemptToken = null;this.setStatus('closed');this.eventListeners.clear();this.statusListeners.clear();diff --git a/packages/maker-core/src/session.turn-stall.test.ts b/packages/maker-core/src/session.turn-stall.test.tsindex 08afe85520..7410c16e1b 100644--- a/packages/maker-core/src/session.turn-stall.test.ts+++ b/packages/maker-core/src/session.turn-stall.test.ts@@ -304,6 +304,10 @@ describe('Session turn stall watchdog', () => {await session.send('go');await vi.advanceTimersByTimeAsync(STALL_MS + 1);expect(stub.abort).toHaveBeenCalledTimes(1);+ // 正常 provider 会在 interrupt 后补 terminal done;先排空它,才能单独验证+ // “abort 没真正让 handle idle”这条 10s recovery。+ stub.pushEvent({ type: 'done', data: {}, source: 'claude-code' });+ await vi.advanceTimersByTimeAsync(0);// 宽限期内不急着关:interrupt 成功后 turn 的终态事件要走一圈才让 isTurnRunning 翻假expect(session.getStatus()).not.toBe('closed');@@ -328,6 +332,8 @@ describe('Session turn stall watchdog', () => {await session.send('go');await vi.advanceTimersByTimeAsync(STALL_MS + 1);expect(stub.abort).toHaveBeenCalledTimes(1);+ stub.pushEvent({ type: 'done', data: {}, source: 'claude-code' });+ await vi.advanceTimersByTimeAsync(0);expect(session.getStatus()).not.toBe('closed');await vi.advanceTimersByTimeAsync(STALL_ABORT_RECOVERY_GRACE_MS + 1);@@ -351,7 +357,9 @@ describe('Session turn stall watchdog', () => {await vi.advanceTimersByTimeAsync(STALL_MS + 1);expect(stub.abort).toHaveBeenCalledTimes(1);- // 宽限没走完就起了新 turn(abort 已生效,isTurnRunning 已翻假,send 不会被拒)+ // 旧 turn 的 terminal tail 先排空;之后宽限没走完就起新 turn。+ stub.pushEvent({ type: 'done', data: {}, source: 'claude-code' });+ await vi.advanceTimersByTimeAsync(0);await session.send('next');await vi.advanceTimersByTimeAsync(STALL_ABORT_RECOVERY_GRACE_MS + 1);@@ -363,6 +371,61 @@ describe('Session turn stall watchdog', () => {}});+ it('超时 turn 的迟到 done 不冒领宽限期内新 turn 的 attempt token', async () => {+ vi.useFakeTimers();+ try {+ const stub = createStubHandle();+ const session = createSession(stub);+ const seen: AgentEvent[] = [];+ session.onEvent((event) => seen.push({ ...event }));++ await session.send('first', { turnAttemptToken: 1 });+ await vi.advanceTimersByTimeAsync(STALL_MS + 1);+ expect(stub.abort).toHaveBeenCalledTimes(1);++ await expect(session.send('second', { turnAttemptToken: 2 })).rejects.toMatchObject({+ code: 'SESSION_RUNNING',+ });+ stub.pushEvent({ type: 'done', data: { reason: 'first-tail' }, source: 'claude-code' });+ await vi.advanceTimersByTimeAsync(0);++ await session.send('second', { turnAttemptToken: 2 });++ stub.endTurn();+ stub.pushEvent({+ type: 'error',+ data: { message: 'second failed', isTerminal: true },+ source: 'claude-code',+ });+ await vi.advanceTimersByTimeAsync(0);++ const terminalEvents = seen.filter((event) => event.type === 'error' || event.type === 'done');+ expect(terminalEvents.map((event) => event.type)).toEqual(['error', 'done', 'error']);+ expect(terminalEvents.map((event) => event.turnAttemptToken)).toEqual([1, undefined, 2]);+ } finally {+ vi.useRealTimers();+ }+ });++ it('abort 已 idle 但没有 terminal tail 时关闭旧 Session 供 Maker 重建', async () => {+ vi.useFakeTimers();+ try {+ const stub = createStubHandle();+ const session = createSession(stub);+ session.onEvent(() => {});++ await session.send('go');+ await vi.advanceTimersByTimeAsync(STALL_MS + 1);+ expect(stub.abort).toHaveBeenCalledTimes(1);+ expect(session.getStatus()).not.toBe('closed');++ await vi.advanceTimersByTimeAsync(300);+ expect(session.getStatus()).toBe('closed');+ } finally {+ vi.useRealTimers();+ }+ });+it('abort 生效时不关闭会话(会话仍可用,不该被误关)', async () => {vi.useFakeTimers();try {@@ -372,6 +435,8 @@ describe('Session turn stall watchdog', () => {await session.send('go');await vi.advanceTimersByTimeAsync(STALL_MS + 1);+ stub.pushEvent({ type: 'done', data: {}, source: 'claude-code' });+ await vi.advanceTimersByTimeAsync(0);await vi.advanceTimersByTimeAsync(STALL_ABORT_RECOVERY_GRACE_MS + 1);expect(stub.abort).toHaveBeenCalledTimes(1);diff --git a/packages/maker-core/src/types/events.ts b/packages/maker-core/src/types/events.tsindex 1c9272a70b..02ec7dcc96 100644--- a/packages/maker-core/src/types/events.ts+++ b/packages/maker-core/src/types/events.ts@@ -121,6 +121,8 @@ export interface AgentEvent {* translator 不产生此字段;消费方(IM 转播等)按需读取,默认忽略。*/turnOrigin?: SendOrigin;+ /** Host-owned per-turn correlation for lifecycle bookkeeping; never comes from vendor metadata. */+ turnAttemptToken?: number;/*** Vendor-specific 元数据透传 (claude-code 的 SDK uuid / parentUuid / sdkSessionId /* model / stopReason / requestId / usage 等)。host 落库时塞进 messages.agent_meta 列,