Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(agents): 修复假心跳导致的任务卡住与自动续跑 (#4353)

Dashabb822d9e330
diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
index cb6d8fa898..92cf22be62 100644
--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
@@ -445,30 +445,37 @@ describe('maker:event hot path ordering', () => {
);
});
- it('preserves only a waiting Codex reconnect-stall retry across its exact provider rebuild', () => {
+ it('preserves continuation-only retry across its exact unexpected provider rebuild', () => {
const closedBlock = extractSessionCloseAdaptersSource();
expect(source).toContain(
- 'const pendingCodexReconnectStalledRebuilds = new WeakMap<Session, number>();',
+ 'const pendingContinuationOnlyAutoResumeRebuilds = new WeakMap<Session, number>();',
);
- expect(source).toContain("if (signals.reason === 'codex_reconnect_stalled') {");
+ expect(source).toContain('if (isAcceptedTurnContinuationOnlyReason(signals.reason)) {');
expect(source).toContain(
- 'pendingCodexReconnectStalledRebuilds.set(runtimeSession, decision.attemptToken);',
+ 'pendingContinuationOnlyAutoResumeRebuilds.set(runtimeSession, decision.attemptToken);',
);
- expect(source).toContain("if (closeReason !== 'unexpected') return false;");
+ expect(source).toContain('shouldPreserveWaitingContinuationOnlyAutoResume({');
+ expect(source).toContain('leasedAttemptToken,');
expect(source).toContain(
'interruptedTurnAutoResumeGuard.isCurrentAttempt(session.id, attemptToken)',
);
- expect(source).toContain('coordinator.getAutoResumeAttemptToken(session.id) !== attemptToken');
- expect(source).toContain('autoResumeBookkeeping.hasWaitingSchedule(session.id, attemptToken)');
+ expect(source).toContain('autoResumeBookkeeping.hasLiveSchedule(session.id, attemptToken)');
+ expect(source).toContain('coordinator?.hasQueuedAutoResume(session.id)');
+ expect(source).toContain('isContinuationOnly:');
+ expect(source).toContain('coordinator?.isContinuationOnlyAutoResume(session.id) === true');
+ expect(source).toContain('coordinator?.isContinuationOnlyAutoResume(session.id) !== true');
expect(closedBlock).toContain(
- 'shouldPreserveCodexReconnectStalledAutoResume(session, closeReason)',
+ 'shouldPreserveContinuationOnlyAutoResume(session, closeReason)',
);
expect(closedBlock).toContain(
'shouldPreserveSessionRuntimeFallbackAutoResume(session, closeReason)',
);
expect(closedBlock).toContain('runSessionCloseCleanup(context.preserveAutoResumeIntent, {');
expect(closedBlock).toContain('autoResumeBookkeeping.teardown(session.id);');
+ expect(source).toMatch(/onBind: \(session: WiredSession\) => \{\s*advanceSessionTurnBoundaryGeneration\(session.id\);\s*bindContinuationOnlyAutoResumeLease\(session\);/);
+ expect(source).toContain('onUnconfirmedAutoResumeTurn:');
+ expect(source).toContain('autoResumeBookkeeping.abandonUnconfirmedPersistedResume(');
});
it('clears Agent Island after mandatory closed-session cleanup', () => {
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.ts
index fcb3b699b7..1a8bd22287 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
@@ -640,6 +640,13 @@ function sessionRunningError(): Error & { code: string } {
});
}
+function turnDispatchUnconfirmedError(message: string): Error & { code: string } {
+ return Object.assign(new Error(message), {
+ name: 'TurnDispatchUnconfirmedError',
+ code: 'TURN_DISPATCH_UNCONFIRMED',
+ });
+}
+
function unsupportedChatBridgeImageError(feature = "input content part 'input_image'"): string {
return (
'unexpected status 400 Bad Request: Responses feature is not supported by the ' +
@@ -714,6 +721,7 @@ function createHarness(opts?: {
// 非 null 时返回的就是要透到 UI 的展示信息(原因 + 本轮次数 + 会话累计)。
let resumableTurnErrorTakeover: {
error?: string;
+ reason?: string;
attempt: number;
maxAttempts: number;
sessionTotal: number;
@@ -778,6 +786,9 @@ function createHarness(opts?: {
const persistTerminalSendError = vi.fn<
NonNullable<AgentInputCoordinatorDeps['persistTerminalSendError']>
>(() => {});
+ const onUnconfirmedAutoResumeTurn = vi.fn<
+ NonNullable<AgentInputCoordinatorDeps['onUnconfirmedAutoResumeTurn']>
+ >(() => {});
const supersedeRetriedUserTurn = vi.fn<
NonNullable<AgentInputCoordinatorDeps['supersedeRetriedUserTurn']>
>(async () => []);
@@ -792,6 +803,7 @@ function createHarness(opts?: {
onDiscardedQueuedMessage,
onRejectedUserTurn,
persistTerminalSendError,
+ onUnconfirmedAutoResumeTurn,
supersedeRetriedUserTurn,
isTurnRunning: () => running,
isLiveTurnRunning: () => {
@@ -884,6 +896,7 @@ function createHarness(opts?: {
onDiscardedQueuedMessage,
onRejectedUserTurn,
persistTerminalSendError,
+ onUnconfirmedAutoResumeTurn,
supersedeRetriedUserTurn,
setRunning(value: boolean) {
running = value;
@@ -942,7 +955,13 @@ function createHarness(opts?: {
},
/** 模拟 host 决定接管自愈(判定命中 + 额度允许);传 null = 不接管。 */
setResumableTurnErrorTakeover(
- value: { error?: string; attempt: number; maxAttempts: number; sessionTotal: number } | null,
+ value: {
+ error?: string;
+ reason?: string;
+ attempt: number;
+ maxAttempts: number;
+ sessionTotal: number;
+ } | null,
) {
resumableTurnErrorTakeover = value;
},
@@ -11401,6 +11420,45 @@ describe('AgentInputCoordinator 中断自动续跑', () => {
expect(mocks.touchUserSendInDb).toHaveBeenCalledTimes(1);
});
+ it.each([
+ ['turn_no_event_timeout', false, true],
+ ['upstream_response_idle_timeout', false, true],
+ ['codex_reconnect_stalled', true, true],
+ ['turn_no_event_timeout', true, false],
+ ['upstream_response_idle_timeout', true, undefined],
+ ['empty-response', true, true],
+ ] as const)('watchdog timeout 保留原计划模式:%s progress=%s plan=%s', async (reason, progress, planMode) => {
+ const h = createHarness();
+ const sid = 'auto-retry-timeout-continue-only';
+ const takeover = { ...TAKEOVER_INFO, reason };
+ h.setResumableTurnErrorTakeover(takeover);
+ h.setHasAssistantProgressAfter(async () => progress);
+ const original = makeItem('q-first', 'original long task');
+ original.createOpts = { ...original.createOpts, permissionMode: 'bypassPermissions', planMode };
+ await failAfterDispatch(h, sid, original);
+
+ await expect(
+ h.coordinator.autoRetryLastError(sid, takeover.sessionTotal),
+ ).resolves.toBe('resumed');
+ await flush();
+
+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);
+ expect(h.sendToAgent.mock.calls[1]?.[1]).toEqual({
+ type: 'user',
+ content: CONTINUE_AFTER_ERROR_PROMPT,
+ });
+ expect(h.sendToAgent.mock.calls[1]?.[3]?.persistUserMessage?.autoResume).toBe(true);
+ expect(h.sendToAgent.mock.calls[1]?.[2]).toMatchObject({ planMode, permissionMode: 'bypassPermissions' });
+ expect(h.onDispatchedUserTurn.mock.calls[1]?.[1]).toEqual(
+ expect.objectContaining({
+ autoResume: true,
+ autoResumeInfo: takeover,
+ supersedesUserClientId: undefined,
+ }),
+ );
+ expect(mocks.touchUserSendInDb).toHaveBeenCalledTimes(1);
+ });
+
it('host 接管时不设 error、只置 autoResumePending(红横幅留给最终失败)', async () => {
const h = createHarness();
const sid = 'takeover-suppresses-banner';
@@ -11415,6 +11473,445 @@ describe('AgentInputCoordinator 中断自动续跑', () => {
expect(projection.recovery?.kind).toBe('active-turn');
});
+ it('unexpected close 后 idle timeout 零产出仍只发 CONTINUE', async () => {
+ const h = createHarness();
+ const sid = 'idle-timeout-preserved-across-unexpected-close';
+ const takeover = { ...TAKEOVER_INFO, reason: 'upstream_response_idle_timeout' };
+ h.setResumableTurnErrorTakeover(takeover);
+ h.setHasAssistantProgressAfter(async () => false);
+ const original = makeItem('q-first', 'original long task');
+ original.createOpts = { ...original.createOpts, planMode: true };
+ await failAfterDispatch(h, sid, original);
+
+ h.coordinator.onSessionClosed(sid, { preserveAutoResumeIntent: true });
+ await flush();
+
+ expect(h.coordinator.isAutoResumePending(sid)).toBe(true);
+ await expect(
+ h.coordinator.autoRetryLastError(sid, takeover.sessionTotal),
+ ).resolves.toBe('resumed');
+ await flush();
+
+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);
+ expect(h.sendToAgent.mock.calls[1]?.[1]).toEqual({
+ type: 'user',
+ content: CONTINUE_AFTER_ERROR_PROMPT,
+ });
+ expect(h.sendToAgent.mock.calls[1]?.[2]?.planMode).toBe(true);
+ });
+
+ it('CONTINUE 撞 SESSION_RUNNING 后 unexpected close 仍唤醒隐藏续跑', async () => {
+ vi.useFakeTimers();
+ const h = createHarness();
+ const sid = 'idle-timeout-session-running-then-unexpected-close';
+ const takeover = { ...TAKEOVER_INFO, reason: 'upstream_response_idle_timeout' };
+ h.setResumableTurnErrorTakeover(takeover);
+ h.setHasAssistantProgressAfter(async () => false);
+ await failAfterDispatch(h, sid);
+
+ h.sendToAgent.mockImplementationOnce(async () =>
+ hostSendFailure('SESSION_RUNNING', '[SESSION_RUNNING] Session is already running a turn'),
+ );
+ await expect(
+ h.coordinator.autoRetryLastError(sid, takeover.sessionTotal),
+ ).resolves.toBe('resumed');
+ await flush();
+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);
+ expect(h.coordinator.hasQueuedAutoResume(sid)).toBe(true);
+ expect(latestProjection(h.projections).pendingQueue.some((item) => item.autoResume)).toBe(
+ true,
+ );
+
+ h.setRunning(false);
+ expect(h.coordinator.getAutoResumeAttemptToken(sid)).toBe(takeover.sessionTotal);
+ h.coordinator.onSessionClosed(sid, { preserveAutoResumeIntent: true });
+ await flush();
+
+ expect(h.sendToAgent).toHaveBeenCalledTimes(3);
+ expect(h.sendToAgent.mock.calls[2]?.[1]).toEqual({
+ type: 'user',
+ content: CONTINUE_AFTER_ERROR_PROMPT,
+ });
+ expect(h.sendToAgent.mock.calls[2]?.[3]?.persistUserMessage?.autoResume).toBe(true);
+ });
+
+ it('CONTINUE 停在 getSdkSessionId 窗口时 unexpected close 仍交回 replacement', async () => {
+ const h = createHarness();
+ const sid = 'idle-timeout-pre-dispatch-sdk-lookup-then-unexpected-close';
+ const takeover = { ...TAKEOVER_INFO, reason: 'upstream_response_idle_timeout' };
+ h.setResumableTurnErrorTakeover(takeover);
+ h.setHasAssistantProgressAfter(async () => false);
+ await failAfterDispatch(h, sid);
+
+ const lookupStarted = deferred<void>();
+ const lookup = deferred<string | undefined>();
+ h.getSdkSessionId.mockImplementation(async () => {
+ lookupStarted.resolve();
+ return lookup.promise;
+ });
+
+ const retry = h.coordinator.autoRetryLastError(sid, takeover.sessionTotal);
+ await lookupStarted.promise;
+ await expect(retry).resolves.toBe('resumed');
+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);
+ expect(h.coordinator.hasQueuedAutoResume(sid)).toBe(true);
+
+ h.coordinator.onSessionClosed(sid, { preserveAutoResumeIntent: true });
+ lookup.resolve('sdk-session');
+ await flush();
+
+ expect(h.onDiscardedQueuedMessage).not.toHaveBeenCalled();
+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);
+ expect(h.sendToAgent.mock.calls[1]?.[1]).toEqual({
+ type: 'user',
+ content: CONTINUE_AFTER_ERROR_PROMPT,
+ });
+ expect(h.sendToAgent.mock.calls[1]?.[3]?.persistUserMessage?.autoResume).toBe(true);
+ });
+
+ it('CONTINUE 停在 beforeDispatch 窗口时 unexpected close 且 send 失败仍交回 replacement', async () => {
+ const h = createHarness();
+ const sid = 'idle-timeout-pre-dispatch-hook-then-unexpected-close';
+ const takeover = { ...TAKEOVER_INFO, reason: 'upstream_response_idle_timeout' };
+ h.setResumableTurnErrorTakeover(takeover);
+ h.setHasAssistantProgressAfter(async () => false);
+ await failAfterDispatch(h, sid);
+
+ const hookStarted = deferred<void>();
+ const hookRelease = deferred<void>();
+ h.beforeDispatchUserTurn.mockImplementation(async () => {
+ hookStarted.resolve();
+ await hookRelease.promise;
+ });
+ h.sendToAgent.mockImplementationOnce(async (sessionId, _message, _createOpts, sendOpts) => {
+ await persistQueuedUserMessage(sessionId, sendOpts);
+ return sessionDispatchFailure('SEND/before-dispatch-unexpected-close/send');
+ });
+
+ await expect(
+ h.coordinator.autoRetryLastError(sid, takeover.sessionTotal),
+ ).resolves.toBe('resumed');
+ await hookStarted.promise;
+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);
+ expect(h.coordinator.hasQueuedAutoResume(sid)).toBe(true);
+
+ h.coordinator.onSessionClosed(sid, { preserveAutoResumeIntent: true });
+ hookRelease.resolve();
+ await flush();
+
+ expect(h.onDiscardedQueuedMessage).not.toHaveBeenCalled();
+ expect(h.sendToAgent).toHaveBeenCalledTimes(3);
+ expect(h.sendToAgent.mock.calls[2]?.[1]).toEqual({
+ type: 'user',
+ content: CONTINUE_AFTER_ERROR_PROMPT,
+ });
+ expect(h.sendToAgent.mock.calls[2]?.[3]?.persistUserMessage?.autoResume).toBe(true);
+ });
+
+ it('CONTINUE 已 vendor accept 但 send promise 未返回时 unexpected close 不得二次派发', async () => {
+ const h = createHarness();
+ const sid = 'idle-timeout-accept-before-close-must-not-replay';
+ const takeover = { ...TAKEOVER_INFO, reason: 'upstream_response_idle_timeout' };
+ h.setResumableTurnErrorTakeover(takeover);
+ h.setHasAssistantProgressAfter(async () => false);
+ await failAfterDispatch(h, sid);
+
+ const sendStarted = deferred<void>();
+ const sendSettled = deferred<void>();
+ h.sendToAgent.mockImplementationOnce(async (sessionId, _message, _createOpts, sendOpts) => {
+ await persistQueuedUserMessage(sessionId, sendOpts);
+ sendStarted.resolve();
+ await sendSettled.promise;
+ return sendSuccess('maker-ipc');
+ });
+
+ await expect(
+ h.coordinator.autoRetryLastError(sid, takeover.sessionTotal),
+ ).resolves.toBe('resumed');
+ await sendStarted.promise;
+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);
+ expect(h.coordinator.hasQueuedAutoResume(sid)).toBe(true);
+
+ h.coordinator.onSessionClosed(sid, { preserveAutoResumeIntent: true });
+ sendSettled.resolve();
+ await flush();
+
+ expect(h.onDiscardedQueuedMessage).not.toHaveBeenCalled();
+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);
+ expect(h.coordinator.hasQueuedAutoResume(sid)).toBe(false);
+ expect(h.coordinator.getAutoResumeAttemptToken(sid)).toBeNull();
+ });
+
+ it('CONTINUE sendStarted 后 unexpected close 且 send 失败则交回 replacement', async () => {
+ const h = createHarness();
+ const sid = 'idle-timeout-send-started-then-unexpected-close-failed';
+ const takeover = { ...TAKEOVER_INFO, reason: 'upstream_response_idle_timeout' };
+ h.setResumableTurnErrorTakeover(takeover);
+ h.setHasAssistantProgressAfter(async () => false);
+ await failAfterDispatch(h, sid);
+
+ const sendStarted = deferred<void>();
+ const sendSettled = deferred<void>();
+ h.sendToAgent.mockImplementationOnce(async (sessionId, _message, _createOpts, sendOpts) => {
+ await persistQueuedUserMessage(sessionId, sendOpts);
+ sendStarted.resolve();
+ await sendSettled.promise;
+ return sessionDispatchFailure('SEND/send-started-unexpected-close/send');
+ });
+
+ await expect(
+ h.coordinator.autoRetryLastError(sid, takeover.sessionTotal),
+ ).resolves.toBe('resumed');
+ await sendStarted.promise;
+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);
+
+ h.coordinator.onSessionClosed(sid, { preserveAutoResumeIntent: true });
+ sendSettled.resolve();
+ await flush();
+
+ expect(h.onDiscardedQueuedMessage).not.toHaveBeenCalled();
+ expect(h.sendToAgent).toHaveBeenCalledTimes(3);
+ expect(h.sendToAgent.mock.calls[2]?.[1]).toEqual({
+ type: 'user',
+ content: CONTINUE_AFTER_ERROR_PROMPT,
+ });
+ expect(h.sendToAgent.mock.calls[2]?.[3]?.persistUserMessage?.autoResume).toBe(true);
+ });
+
+ it.each(['before-send', 'references', 'send-failed'] as const)(
+ '连续 replacement 关闭共用三次派发预算:%s',
+ async (phase) => {
+ const h = createHarness();
+ const sid = `auto-resume-close-budget-${phase}`;
+ const takeover = { ...TAKEOVER_INFO, reason: 'upstream_response_idle_timeout' };
+ h.setResumableTurnErrorTakeover(takeover);
+ h.setHasAssistantProgressAfter(async () => false);
+ await failAfterDispatch(h, sid, makeItem('q-first', 'original long task', {
+ sessionRefs: [{ sessionId: 'referenced-session' }],
+ }));
+ const attempts = Array.from({ length: 3 }, () => ({
+ started: deferred<void>(),
+ release: deferred<void>(),
+ }));
+ for (const attempt of attempts) {
+ if (phase === 'before-send') {
+ h.getSdkSessionId.mockImplementationOnce(async () => {
+ attempt.started.resolve();
+ await attempt.release.promise;
+ return 'sdk-session';
+ });
+ } else if (phase === 'references') {
+ h.resolveSessionReferences.mockImplementationOnce(async () => {
+ attempt.started.resolve();
+ await attempt.release.promise;
+ return [];
+ });
+ } else {
+ h.sendToAgent.mockImplementationOnce(async (sessionId, _message, _opts, sendOpts) => {
+ await persistQueuedUserMessage(sessionId, sendOpts);
+ attempt.started.resolve();
+ await attempt.release.promise;
+ return sessionDispatchFailure('SEND/replacement-closed/send');
+ });
+ }
+ }
+ await expect(h.coordinator.autoRetryLastError(sid, takeover.sessionTotal)).resolves.toBe('resumed');
+ for (const attempt of attempts) {
+ await attempt.started.promise;
+ h.coordinator.onSessionClosed(sid, { preserveAutoResumeIntent: true });
+ attempt.release.resolve();
+ await flush();
+ }
+ expect(h.onDiscardedQueuedMessage).toHaveBeenCalledTimes(1);
+ expect(h.onDiscardedQueuedMessage).toHaveBeenCalledWith(
+ sid, expect.objectContaining({ autoResume: true }),
+ );
+ expect(h.coordinator.hasQueuedAutoResume(sid)).toBe(false);
+ expect(latestProjection(h.projections).pendingQueue).toEqual([]);
+ await flush();
+ expect(h.sendToAgent).toHaveBeenCalledTimes(phase === 'send-failed' ? 4 : 1);
+ },
+ );
+
+ it.each(['pre-send-close', 'session-running'] as const)(
+ '队列态 replacement 连续关闭沿用 %s 已消费的预算', async (entry) => {
+ vi.useFakeTimers();
+ const h = createHarness();
+ const sid = `queued-auto-close-${entry}`;
+ const takeover = { ...TAKEOVER_INFO, reason: 'upstream_response_idle_timeout' };
+ h.setResumableTurnErrorTakeover(takeover);
+ h.setHasAssistantProgressAfter(async () => false);
+ await failAfterDispatch(h, sid);
+ const started = deferred<void>();
+ const release = deferred<void>();
+ if (entry === 'pre-send-close') {
+ h.getSdkSessionId.mockImplementationOnce(async () => {
+ started.resolve();
+ await release.promise;
+ return 'sdk-session';
+ });
+ } else {
+ h.sendToAgent.mockImplementationOnce(async () =>
+ hostSendFailure('SESSION_RUNNING', '[SESSION_RUNNING] busy'),
+ );
+ }
+ await h.coordinator.autoRetryLastError(sid, takeover.sessionTotal);
+ if (entry === 'pre-send-close') {
+ await started.promise;
+ h.coordinator.onSessionClosed(sid, { preserveAutoResumeIntent: true });
+ } else {
+ await flush();
+ }
+ // Both entry paths have spent one attempt and returned CONTINUE to the
+ // queue. Close replacements synchronously before the scheduled drain.
+ expect(latestProjection(h.projections).pendingQueue.some((item) => item.autoResume)).toBe(true);
+ h.coordinator.onSessionClosed(sid, { preserveAutoResumeIntent: true });
+ expect(h.onDiscardedQueuedMessage).not.toHaveBeenCalled();
+ h.coordinator.onSessionClosed(sid, { preserveAutoResumeIntent: true });
+ expect(h.onDiscardedQueuedMessage).toHaveBeenCalledTimes(1);
+ expect(h.coordinator.hasQueuedAutoResume(sid)).toBe(false);
+ // The host owns final token settlement; this harness spies on that
+ // boundary rather than installing register.ts's bookkeeping callback.
+ expect(h.onDiscardedQueuedMessage).toHaveBeenCalledWith(sid, expect.objectContaining({
+ autoResume: true, autoResumeInfo: expect.objectContaining({ sessionTotal: takeover.sessionTotal }),
+ }));
+ release.resolve();
+ await flush();
+ expect(h.sendToAgent).toHaveBeenCalledTimes(entry === 'pre-send-close' ? 1 : 2);
+ },
+ );
+
+ it('CONTINUE sendStarted 后 unexpected close 且 TurnDispatchUnconfirmedError 不得二次派发', async () => {
+ const h = createHarness();
+ const sid = 'idle-timeout-send-started-then-unconfirmed-must-not-replay';
+ const takeover = { ...TAKEOVER_INFO, reason: 'upstream_response_idle_timeout' };
+ h.setResumableTurnErrorTakeover(takeover);
+ h.setHasAssistantProgressAfter(async () => false);
+ await failAfterDispatch(h, sid);
+
+ const sendStarted = deferred<void>();
+ const sendSettled = deferred<void>();
+ h.sendToAgent.mockImplementationOnce(async (sessionId, _message, _createOpts, sendOpts) => {
+ await persistQueuedUserMessage(sessionId, sendOpts);
+ sendStarted.resolve();
+ await sendSettled.promise;
+ throw turnDispatchUnconfirmedError(
+ `Session ${sessionId} terminated before provider acceptance could be reconciled`,
+ );
+ });
+
+ await expect(
+ h.coordinator.autoRetryLastError(sid, takeover.sessionTotal),
+ ).resolves.toBe('resumed');
+ await sendStarted.promise;
+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);
+
+ h.coordinator.onSessionClosed(sid, { preserveAutoResumeIntent: true });
+ sendSettled.resolve();
+ await flush();
+
+ expect(h.onDiscardedQueuedMessage).not.toHaveBeenCalled();
+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);
+ expect(h.coordinator.hasQueuedAutoResume(sid)).toBe(false);
+ expect(h.coordinator.getAutoResumeAttemptToken(sid)).toBeNull();
+ expect(h.persistTerminalSendError).toHaveBeenCalledWith(
+ sid,
+ expect.stringContaining('terminated before provider acceptance'),
+ );
+ expect(h.onUnconfirmedAutoResumeTurn).toHaveBeenCalledTimes(1);
+ expect(h.onUnconfirmedAutoResumeTurn).toHaveBeenCalledWith(
+ sid,
+ expect.objectContaining({ autoResume: true }),
+ );
+ });
+
+ it('idle timeout 接管是 continuation-only,empty-response 不是', async () => {
+ const idle = createHarness();
+ const idleSid = 'continuation-only-idle-timeout';
+ idle.setResumableTurnErrorTakeover({
+ ...TAKEOVER_INFO,
+ reason: 'upstream_response_idle_timeout',
+ });
+ await failAfterDispatch(idle, idleSid);
+ expect(idle.coordinator.isContinuationOnlyAutoResume(idleSid)).toBe(true);
+
+ const generic = createHarness();
+ const genericSid = 'generic-empty-response-not-continuation-only';
+ generic.setResumableTurnErrorTakeover({ ...TAKEOVER_INFO, reason: 'empty-response' });
+ await failAfterDispatch(generic, genericSid);
+ expect(generic.coordinator.isContinuationOnlyAutoResume(genericSid)).toBe(false);
+ });
+
+ it('显式 close 在 sendStarted 且已落库窗口丢弃隐藏 CONTINUE,不留 recovery', async () => {
+ const h = createHarness();
+ const sid = 'idle-timeout-send-started-persisted-plain-close-discards';
+ const takeover = { ...TAKEOVER_INFO, reason: 'upstream_response_idle_timeout' };
+ h.setResumableTurnErrorTakeover(takeover);
+ h.setHasAssistantProgressAfter(async () => false);
+ await failAfterDispatch(h, sid);
+
+ const sendStarted = deferred<void>();
+ const sendSettled = deferred<void>();
+ h.sendToAgent.mockImplementationOnce(async (sessionId, _message, _createOpts, sendOpts) => {
+ await persistQueuedUserMessage(sessionId, sendOpts);
+ sendStarted.resolve();
+ await sendSettled.promise;
+ return sessionDispatchFailure('SEND/send-started-explicit-close/send');
+ });
+
+ await expect(
+ h.coordinator.autoRetryLastError(sid, takeover.sessionTotal),
+ ).resolves.toBe('resumed');
+ await sendStarted.promise;
+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);
+ expect(h.coordinator.hasQueuedAutoResume(sid)).toBe(true);
+
+ h.coordinator.onSessionClosed(sid);
+ sendSettled.resolve();
+ await flush();
+
+ expect(h.onDiscardedQueuedMessage).toHaveBeenCalledWith(
+ sid,
+ expect.objectContaining({ autoResume: true }),
+ );
+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);
+ expect(h.coordinator.hasQueuedAutoResume(sid)).toBe(false);
+ expect(h.coordinator.getAutoResumeAttemptToken(sid)).toBeNull();
+ expect(latestProjection(h.projections).recovery?.kind).not.toBe('active-turn');
+ });
+
+ it('显式 close 仍丢弃尚未派发的隐藏 CONTINUE', async () => {
+ const h = createHarness();
+ const sid = 'idle-timeout-pre-dispatch-plain-close-discards';
+ const takeover = { ...TAKEOVER_INFO, reason: 'upstream_response_idle_timeout' };
+ h.setResumableTurnErrorTakeover(takeover);
+ h.setHasAssistantProgressAfter(async () => false);
+ await failAfterDispatch(h, sid);
+
+ const lookupStarted = deferred<void>();
+ const lookup = deferred<string | undefined>();
+ h.getSdkSessionId.mockImplementation(async () => {
+ lookupStarted.resolve();
+ return lookup.promise;
+ });
+
+ await expect(
+ h.coordinator.autoRetryLastError(sid, takeover.sessionTotal),
+ ).resolves.toBe('resumed');
+ await lookupStarted.promise;
+
+ h.coordinator.onSessionClosed(sid);
+ lookup.resolve('sdk-session');
+ await flush();
+
+ expect(h.onDiscardedQueuedMessage).toHaveBeenCalledWith(
+ sid,
+ expect.objectContaining({ autoResume: true }),
+ );
+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);
+ expect(h.coordinator.hasQueuedAutoResume(sid)).toBe(false);
+ });
+
it('provider rebuild close 保留自动续跑意图,并仍由现有 retry 路径补发', async () => {
const h = createHarness();
const sid = 'takeover-preserved-across-provider-rebuild';
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/autoResumeBookkeeping.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/autoResumeBookkeeping.test.ts
index a9a2b6cc0d..ce362b435c 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/autoResumeBookkeeping.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/autoResumeBookkeeping.test.ts
@@ -35,6 +35,7 @@ function createHarness() {
const abandons: Array<{ sessionId: string; message?: string }> = [];
const surfaced: Array<{ sessionId: string; detail: SuppressedTurnError }> = [];
const orcaFinalized: Array<{ sessionId: string; payload: OrcaSuppressedTerminal }> = [];
+ const autoResumeFailed: Array<{ sessionId: string; attemptToken?: number }> = [];
const deps: AutoResumeBookkeepingDeps = {
persistSuppressedError: (sessionId, detail) => persisted.push({ sessionId, detail }),
surfaceSuppressedError: (sessionId, detail) => surfaced.push({ sessionId, detail }),
@@ -44,6 +45,7 @@ function createHarness() {
rollbackGuardPendingResume: (sessionId) => guardRollbacks.push(sessionId),
abandonTakeover: (sessionId, message) =>
abandons.push({ sessionId, ...(message !== undefined ? { message } : {}) }),
+ onAutoResumeFailed: (sessionId, attemptToken) => autoResumeFailed.push({ sessionId, attemptToken }),
};
return {
book: new AutoResumeBookkeeping(deps),
@@ -53,6 +55,7 @@ function createHarness() {
outcomes,
guardRollbacks,
abandons,
+ autoResumeFailed,
};
}
@@ -245,6 +248,48 @@ describe('待确认的重连记录:必有一次结算', () => {
expect(h.outcomes).toEqual([{ sessionId: 's1', clientId: 'c-1', outcome: 'failed' }]);
expect(h.book.isPendingOutcomeClientId('s2', 'c-2')).toBe(true);
});
+
+ it('unconfirmed persisted resume 一次结清 failed,不补落旧错误', () => {
+ const h = createHarness();
+ h.book.beginAttempt('s1', 7);
+ h.book.stashSuppressedError('s1', { message: 'idle timeout' }, 7);
+ h.book.bindSuppressedErrorToClient('s1', 7, 'continue-1');
+ h.book.registerPendingOutcome('s1', 7, 'continue-1');
+
+ const payload = createOrcaTerminal();
+ expect(h.book.stashOrcaSuppressedTerminal('s1', payload)).toBe(true);
+
+ expect(h.book.abandonUnconfirmedPersistedResume('s1', 7, 'continue-1')).toBe(true);
+ expect(h.book.abandonUnconfirmedPersistedResume('s1', 7, 'continue-1')).toBe(false);
+ expect(h.orcaFinalized).toEqual([{ sessionId: 's1', payload }]);
+ expect(h.outcomes).toEqual([{ sessionId: 's1', clientId: 'continue-1', outcome: 'failed' }]);
+ expect(h.persisted).toEqual([]);
+ expect(h.surfaced).toEqual([]);
+ expect(h.abandons).toEqual([]);
+ expect(h.guardRollbacks).toEqual(['s1']);
+ expect(h.autoResumeFailed).toEqual([{ sessionId: 's1', attemptToken: 7 }]);
+ expect(h.book.hasSuppressedError('s1')).toBe(false);
+ expect(h.book.isPendingOutcomeClientId('s1', 'continue-1')).toBe(false);
+ expect(h.book.isCurrentAttempt('s1', 7)).toBe(false);
+ });
+
+ it('unconfirmed persisted resume 过期 token 或别人的 clientId 是 no-op', () => {
+ const h = createHarness();
+ h.book.beginAttempt('s1', 7);
+ h.book.stashSuppressedError('s1', { message: 'idle timeout' }, 7);
+ h.book.bindSuppressedErrorToClient('s1', 7, 'continue-1');
+ h.book.registerPendingOutcome('s1', 7, 'continue-1');
+
+ expect(h.book.abandonUnconfirmedPersistedResume('s1', 8, 'continue-1')).toBe(false);
+ expect(h.book.abandonUnconfirmedPersistedResume('s1', 7, 'continue-other')).toBe(false);
+ expect(h.outcomes).toEqual([]);
+ expect(h.persisted).toEqual([]);
+ expect(h.guardRollbacks).toEqual([]);
+ expect(h.autoResumeFailed).toEqual([]);
+ expect(h.book.hasSuppressedError('s1')).toBe(true);
+ expect(h.book.isPendingOutcomeClientId('s1', 'continue-1')).toBe(true);
+ expect(h.book.isCurrentAttempt('s1', 7)).toBe(true);
+ });
});
describe('退避排期:必可撤销、必只认自己那次', () => {
@@ -392,13 +437,15 @@ describe('退避排期:必可撤销、必只认自己那次', () => {
});
expect(h.book.hasWaitingSchedule('s1', 7)).toBe(true);
+ expect(h.book.hasLiveSchedule('s1', 7)).toBe(true);
expect(h.book.hasWaitingSchedule('s1', 8)).toBe(false);
vi.advanceTimersByTime(1_000);
await Promise.resolve();
expect(h.book.hasSchedule('s1')).toBe(true);
+ expect(h.book.hasLiveSchedule('s1', 7)).toBe(true);
expect(
h.book.hasWaitingSchedule('s1', 7),
- 'timer 已触发、async callback 在跑时不再属于 provider rebuild 交棒窗口',
+ 'timer 已触发、async callback 在跑时 waiting 为 false,但 live schedule 仍在',
).toBe(false);
expect(callbackAttempt.isCurrent()).toBe(true);
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/interruptedTurnAutoResume.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/interruptedTurnAutoResume.test.ts
index 625df73aad..3ef8ab5768 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/interruptedTurnAutoResume.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/interruptedTurnAutoResume.test.ts
@@ -5,14 +5,21 @@ import {
INTERRUPTED_TURN_MAX_EPISODE_ATTEMPTS,
InterruptedTurnAutoResumeGuard,
interruptedTurnResumeDelayMs,
+ isAcceptedTurnContinuationOnlyReason,
isAutoResumeUserMessage,
isInterruptedTurnError,
isSubstantiveProgressEvent,
+ shouldPreserveWaitingContinuationOnlyAutoResume,
} from '../interruptedTurnAutoResume.js';
// 判定单测的核心是**白名单收紧**:自动重试一个确定性失败(认证过期、协议错)会反复
// 烧额度并反复报错,所以只有识别得了的"上游把 turn 打断了"才允许自愈。
describe('isInterruptedTurnError', () => {
+ it.each(['bridge_upstream_response_idle_timeout', 'bridge_turn_no_event_timeout'])(
+ 'does not continue a bridge timeout before the user input has executed: %s', (reason) => {
+ expect(isInterruptedTurnError({ reason, message: 'request timed out' })).toBe(false);
+ expect(isAcceptedTurnContinuationOnlyReason(reason)).toBe(false);
+ });
// 2026-07-30 实测的真实形态(Claude Code SDK 2.1.219 + Bedrock):SSE 流被中途切断,
// terminal_reason='api_error'、sdkError='server_error'、无 HTTP 状态码。这条用例是
// 回归锚 —— 上游改文案时它会先红。
@@ -66,6 +73,108 @@ describe('isInterruptedTurnError', () => {
).toBe(true);
});
+ it('accepts stall / idle timeouts so heartbeat-only zombie running can auto-retry', () => {
+ // 用量心跳不再刷新看门狗之后,这两类 reason 就是「以为还在跑、其实没进展」。
+ // 必须走自动续跑,不能直接把 Continue 交还用户;额度耗尽才停。
+ expect(
+ isInterruptedTurnError({
+ reason: 'turn_no_event_timeout',
+ message: 'This turn produced no activity at all for 45 minutes.',
+ }),
+ ).toBe(true);
+ expect(
+ isInterruptedTurnError({
+ reason: 'upstream_response_idle_timeout',
+ message: 'The model stopped responding for a long time.',
+ }),
+ ).toBe(true);
+ expect(isInterruptedTurnError({ reason: 'turn_no_event_timeout' })).toBe(true);
+ expect(isInterruptedTurnError({ reason: 'upstream_response_idle_timeout' })).toBe(true);
+ });
+
+ it('marks accepted-turn timeouts as continuation-only', () => {
+ expect(isAcceptedTurnContinuationOnlyReason('turn_no_event_timeout')).toBe(true);
+ expect(isAcceptedTurnContinuationOnlyReason('upstream_response_idle_timeout')).toBe(true);
+ expect(isAcceptedTurnContinuationOnlyReason('codex_reconnect_stalled')).toBe(true);
+ expect(isAcceptedTurnContinuationOnlyReason('empty-response')).toBe(false);
+ expect(isAcceptedTurnContinuationOnlyReason('upstream-overload')).toBe(false);
+ expect(isAcceptedTurnContinuationOnlyReason('turn-failed')).toBe(false);
+ expect(isAcceptedTurnContinuationOnlyReason(undefined)).toBe(false);
+ });
+
+ it('preserves waiting continuation-only auto-resume only across unexpected close', () => {
+ const waiting = {
+ closeReason: 'unexpected' as const,
+ leasedAttemptToken: 7,
+ guardIsCurrentAttempt: true,
+ bookIsCurrentAttempt: true,
+ coordinatorAttemptToken: 7,
+ hasLiveSchedule: true,
+ hasQueuedAutoResume: false,
+ isContinuationOnly: true,
+ };
+ // Session stall drain / Codex idle ACK-fail close / Claude interrupt-reject drain
+ // 都是 vendor 自己 close,Maker 没有显式 reason → unexpected。
+ expect(shouldPreserveWaitingContinuationOnlyAutoResume(waiting)).toBe(true);
+ expect(
+ shouldPreserveWaitingContinuationOnlyAutoResume({ ...waiting, closeReason: 'requested' }),
+ ).toBe(false);
+ expect(
+ shouldPreserveWaitingContinuationOnlyAutoResume({ ...waiting, closeReason: 'agent-switch' }),
+ ).toBe(false);
+ expect(
+ shouldPreserveWaitingContinuationOnlyAutoResume({
+ ...waiting,
+ leasedAttemptToken: undefined,
+ }),
+ ).toBe(true);
+ expect(
+ shouldPreserveWaitingContinuationOnlyAutoResume({
+ ...waiting,
+ leasedAttemptToken: undefined,
+ coordinatorAttemptToken: null,
+ hasLiveSchedule: false,
+ hasQueuedAutoResume: true,
+ }),
+ ).toBe(false);
+ expect(
+ shouldPreserveWaitingContinuationOnlyAutoResume({ ...waiting, hasLiveSchedule: false }),
+ ).toBe(false);
+ expect(
+ shouldPreserveWaitingContinuationOnlyAutoResume({
+ ...waiting,
+ hasLiveSchedule: false,
+ hasQueuedAutoResume: true,
+ }),
+ ).toBe(true);
+ expect(
+ shouldPreserveWaitingContinuationOnlyAutoResume({
+ ...waiting,
+ hasLiveSchedule: false,
+ hasQueuedAutoResume: true,
+ closeReason: 'requested',
+ }),
+ ).toBe(false);
+ expect(
+ shouldPreserveWaitingContinuationOnlyAutoResume({
+ ...waiting,
+ coordinatorAttemptToken: 8,
+ }),
+ ).toBe(false);
+ expect(
+ shouldPreserveWaitingContinuationOnlyAutoResume({
+ ...waiting,
+ guardIsCurrentAttempt: false,
+ }),
+ ).toBe(false);
+ expect(
+ shouldPreserveWaitingContinuationOnlyAutoResume({
+ ...waiting,
+ isContinuationOnly: false,
+ }),
+ ).toBe(false);
+ });
+
it('rejects oversized-history classification so auto-resume cannot loop', () => {
expect(
isInterruptedTurnError({
diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
index 0b9fc92e44..1006e18bb6 100644
--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
@@ -32,7 +32,10 @@ import { createLogger } from '../logger.js';
import { readAutoReviewUserText } from './autoReviewUserIntent.js';
import { createMessage as createDbMessage } from '../localDb/ipc/messages.js';
import { touchUserSendInDb } from '../localDb/ipc/sessions.js';
-import type { InterruptedTurnErrorSignals } from './interruptedTurnAutoResume.js';
+import {
+ isAcceptedTurnContinuationOnlyReason,
+ type InterruptedTurnErrorSignals,
+} from './interruptedTurnAutoResume.js';
import type { SuppressedTurnErrorOwner } from './autoResumeBookkeeping.js';
import {
restoreTrustedDesktopQueuedOrigin,
@@ -83,7 +86,7 @@ import {
const log = createLogger('maker-input-coordinator');
const SESSION_RUNNING_RETRY_DELAY_MS = 250;
/**
- * Codex 的 reconnect-stalled 清理要等两次 turn/interrupt ACK,每次最多 10s。
+ * Codex 的 reconnect-stalled / ordinary idle 清理要等两次 turn/interrupt ACK,每次最多 10s。
* 自动续跑仍只允许 3 次 SESSION_RUNNING 派发尝试,但退避必须覆盖这段有界
* cleanup 窗口;终态事件先到时 scheduleDrain 仍会立即放行,不会强制等满该间隔。
*/
@@ -481,6 +484,12 @@ export interface AgentInputCoordinatorDeps {
persistTerminalSendError?: (sessionId: string, message: string) => void;
/** 已落库但 vendor reject:宿主可关掉卡住的原生会话,等用户重试再换窗。 */
onPersistedSendRejected?: (sessionId: string, message: string) => void;
+ /**
+ * 已落库的隐藏 CONTINUE 无法确认 vendor 是否 accept。host 必须结算
+ * AutoResumeBookkeeping(pending outcome + suppressed error + guard),
+ * 且不得恢复原 recovery、不得再入队。
+ */
+ onUnconfirmedAutoResumeTurn?: (sessionId: string, item: AgentInputQueuedMessage) => void;
onAcceptedQueuedMessage?: (
sessionId: string,
item: AgentInputQueuedMessage,
@@ -869,6 +878,12 @@ function errorMessage(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}
+function isTurnDispatchUnconfirmedError(err: unknown): boolean {
+ if (!err || typeof err !== 'object') return false;
+ const rec = err as { name?: unknown; code?: unknown };
+ return rec.code === 'TURN_DISPATCH_UNCONFIRMED' || rec.name === 'TurnDispatchUnconfirmedError';
+}
+
function isSessionRunningError(err: unknown): boolean {
if (!err || typeof err !== 'object') return false;
const code = (err as { code?: unknown }).code;
@@ -2654,12 +2669,14 @@ export class AgentInputCoordinator {
/**
* `opts.auto` = 由 main 守卫自动触发(turn 被上游打断),不是用户点的「继续」。
- * 三处差别,其余完全共用人工那条已验证过的路径:
+ * 四处差别,其余完全共用人工那条已验证过的路径:
* - 补发的续跑指令带 `autoResume`(隐藏气泡 / 「已自动继续」分隔线 / 不充值额度,
* 见 AgentInputQueuedMessage.autoResume)。
* - 零产出时克隆重发用户原文,并带 `autoResume` 标记。它不会给额度守卫充值,
* 连续失败次数仍由 host 的 `InterruptedTurnAutoResumeGuard` 负责上限;因此短暂的
* 首次 admission / 网络失败可以自动穿过,而持续无产出时仍会在上限处停下。
+ * - 已 accept 的 stall / idle / reconnect-stalled timeout:即使 DB 里没有
+ * assistant 行,也只发 CONTINUE,绝不克隆原文(本 turn 可能已经跑过工具)。
* - 不 `touchUserSend`:那个时间戳的语义是「人最近发过消息」(会话列表 / 陈旧判定
* 在读它),自动补发不该冒充人类动作。
*/
@@ -2686,41 +2703,50 @@ export class AgentInputCoordinator {
// active-turn recovery 的续跑判定:失败 turn 若已有 assistant 侧产出,重发
// 原文等于让模型"从头再来"(原文可能是很久之前的初始任务指令),改发规范化
// 续跑指令;零产出(派发即失败 / 首个 API 调用就挂)才维持克隆重发。
+ // 例外:已 accept 的 stall / idle / reconnect-stalled timeout 即使零产出也只发
+ // CONTINUE——那些超时发生在 vendor 已经接住本 turn 之后,克隆会重放工具副作用。
// 续跑指令是共享英文常量(带 [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 continuationOnly = Boolean(
+ opts?.auto && isAcceptedTurnContinuationOnlyReason(previousAutoResumeInfo?.reason),
+ );
let continueText = CONTINUE_AFTER_ERROR_PROMPT;
let recoveryCheckpoint: RecoveryCheckpoint | undefined;
- if (recovery.kind === 'active-turn' && this.deps.hasAssistantProgressAfter) {
+ if (recovery.kind === 'active-turn') {
let hasProgress = false;
- try {
- hasProgress = await this.deps.hasAssistantProgressAfter(sessionId, recovery.item.clientId);
+ if (this.deps.hasAssistantProgressAfter) {
+ try {
+ hasProgress = await this.deps.hasAssistantProgressAfter(sessionId, recovery.item.clientId);
+ progressKnown = true;
+ } catch {
+ // 自动路径无法确认进度时不重放原文;人工 Retry 保持既有兼容行为。
+ }
+ // await 期间 turn 事件可能已推进状态(clearError / 新 error / 并发 retry):
+ // recovery 不再是同一对象时放弃本次意图,以当前 projection 为准。
+ if (this.getState(sessionId).recovery !== recovery) {
+ return { projection: this.getProjection(sessionId), outcome: 'superseded' };
+ }
+ // 接管态也要在 await **之后**再核一次。这个 await 里会读库(见 dep 实现),窗口足够
+ // 长到用户在此期间关掉会话 / 自己发消息 —— 而 onSessionClosed 刻意保留 recovery
+ // (它是手动重试入口),所以上面那道 recovery 检查放得过去,自动续跑会往一个已经
+ // 关掉的会话补发消息、把它重新拉起来(codex P1)。teardown 会清接管态,这里据此收手。
+ const latestAfterProgress = this.getState(sessionId);
+ if (
+ opts?.auto &&
+ (!latestAfterProgress.autoResumePending ||
+ latestAfterProgress.autoResumeAttemptToken !== attemptToken)
+ ) {
+ return { projection: this.getProjection(sessionId), outcome: 'superseded' };
+ }
+ } else if (continuationOnly) {
progressKnown = true;
- } catch {
- // 自动路径无法确认进度时不重放原文;人工 Retry 保持既有兼容行为。
- }
- // await 期间 turn 事件可能已推进状态(clearError / 新 error / 并发 retry):
- // recovery 不再是同一对象时放弃本次意图,以当前 projection 为准。
- if (this.getState(sessionId).recovery !== recovery) {
- return { projection: this.getProjection(sessionId), outcome: 'superseded' };
- }
- // 接管态也要在 await **之后**再核一次。这个 await 里会读库(见 dep 实现),窗口足够
- // 长到用户在此期间关掉会话 / 自己发消息 —— 而 onSessionClosed 刻意保留 recovery
- // (它是手动重试入口),所以上面那道 recovery 检查放得过去,自动续跑会往一个已经
- // 关掉的会话补发消息、把它重新拉起来(codex P1)。teardown 会清接管态,这里据此收手。
- const latestAfterProgress = this.getState(sessionId);
- if (
- opts?.auto &&
- (!latestAfterProgress.autoResumePending ||
- latestAfterProgress.autoResumeAttemptToken !== attemptToken)
- ) {
- return { projection: this.getProjection(sessionId), outcome: 'superseded' };
}
- if (hasProgress) {
- if (this.deps.getRecoveryContextSnapshot) {
+ if (hasProgress || continuationOnly) {
+ if (hasProgress && this.deps.getRecoveryContextSnapshot) {
try {
const snapshot = await this.deps.getRecoveryContextSnapshot(
sessionId,
@@ -2789,10 +2815,11 @@ export class AgentInputCoordinator {
// 不取代;展开继承的旧值若留着,落库后会把本轮"有产出失败"的 error 行
// 一并误藏(窗口从更早的行一直铺到本条)。
supersedesUserClientId: undefined,
- // 合成续跑指令显式普通执行:原消息若带 planMode=true,原样克隆会把隐藏
- // 指令路由进计划模式而不是立刻续跑(review P2)。与 sendUiTrigger 的
- // 合成 UI 动作同语义 —— planMode 强制 false。
- createOpts: { ...recovery.item.createOpts, planMode: false },
+ // 自动恢复不是计划批准:保留原 Plan/权限选项,不能因隐藏 CONTINUE
+ // 降到 Full access。人工 Retry 仍沿用既有合成 UI 动作策略。
+ createOpts: opts?.auto
+ ? { ...recovery.item.createOpts }
+ : { ...recovery.item.createOpts, planMode: false },
chatMessage: {
clientId,
role: 'user',
@@ -3606,8 +3633,15 @@ export class AgentInputCoordinator {
/**
* @param opts.preserveInputBoundary 为 true 时跳过 abortInputBoundary。
* @param opts.preserveAutoResumeIntent 为 true 时保留当前自动续跑接管态。
- * 仅用于 provider rebuild 在退避 timer 触发前关闭旧 Session 的交棒窗口;
- * active turn / steer / drain 等旧实例运行态仍照常清理。
+ * 用于 provider rebuild / unexpected close 交棒:waiting timer、in-flight
+ * callback、已因 SESSION_RUNNING 回队、以及已进入 drain 但尚未 vendor
+ * dispatch 的隐藏 CONTINUE 都要保住。尚未 sendStarted 的 active 项必须
+ * 重新入队,不能 discard;send 已开始、outcome 未返回时先等真实结果——
+ * vendor 已 accept 就 commit,不得再发第二次 CONTINUE;TurnDispatchUnconfirmedError
+ * 视为可能已 accept,禁止自动再发;其余失败且 attempt 仍匹配才重新入队。
+ * 显式 close / Stop 清掉 token 后,sendStarted+persisted 的隐藏 CONTINUE 必须
+ * discard,不得落成 active-turn recovery。active turn / steer / drain 等旧实例运行态仍照常清理;
+ * 清掉 sessionRunningRetry 之后必须自己唤醒队里的隐藏续跑。
* 用于 rehydrate / 凭证切换 close-rebuild 窗口:abort 会取消驱动本次重建的
* input signal(#1930),但**其余清理必须照常**(activeTurn / steer / queue
* 状态不能残留,否则 rebuild 失败或 close 后不 rebuild 时 coordinator
@@ -3633,7 +3667,22 @@ export class AgentInputCoordinator {
if (!opts?.preserveInputBoundary) this.abortInputBoundary(sessionId);
this.abortSteerTransactions(sessionId);
const active = state.activeTurn;
- if (active && !isActiveTurnDispatched(active)) {
+ const preserveUndispatchedAutoResume =
+ opts?.preserveAutoResumeIntent === true &&
+ Boolean(active && !isActiveTurnDispatched(active) && active.item?.autoResume);
+ if (preserveUndispatchedAutoResume && active?.sendStarted) {
+ // sendToAgent 已在飞:status=closed 可能早于 send promise。vendor 已
+ // accept 时再入队会二次 CONTINUE;等 outcome 再决定 commit 还是交回。
+ this.recordActiveTurnClosedBeforeSendOutcome(state, active);
+ state.queueAbortPending = false;
+ state.abortBoundaryToken = null;
+ this.clearAllSteeringMarkers(state);
+ this.emit(sessionId);
+ return;
+ }
+ if (preserveUndispatchedAutoResume && active) {
+ this.requeuePreservedUndispatchedAutoResume(sessionId, state, active);
+ } else if (active && !isActiveTurnDispatched(active)) {
if (active.sendStarted) {
this.recordActiveTurnClosedBeforeSendOutcome(state, active);
} else {
@@ -3645,12 +3694,25 @@ export class AgentInputCoordinator {
this.emit(sessionId);
return;
}
+ // An active pre-send item was already charged by the requeue helper above.
+ // Only items that were still queued at close need charging here, including
+ // closes before the next drain and while an abort boundary is released.
+ if (opts?.preserveAutoResumeIntent && !preserveUndispatchedAutoResume) {
+ for (const item of state.pendingQueue.filter((queued) => queued.autoResume)) {
+ this.abandonAutoResumeAfterTransientFailure(sessionId, state, item, 'unexpected-close');
+ }
+ }
state.activeTurn = null;
state.queueAbortPending = false;
state.abortBoundaryToken = null;
this.clearAllSteeringMarkers(state);
this.emit(sessionId);
if (releasedAbortLock) this.scheduleDrain(sessionId, 'session-closed-abort-boundary');
+ else if (opts?.preserveAutoResumeIntent && this.hasQueuedAutoResume(sessionId)) {
+ // Old provider busy is gone with this Session. The 10s SESSION_RUNNING
+ // retry was cleared above; wake the hidden CONTINUE onto the replacement.
+ this.scheduleDrain(sessionId, 'session-closed-preserved-auto-resume');
+ }
}
private projectQueueInspection(state: SessionInputState): SessionQueueInspectionEntry[] {
@@ -4354,18 +4416,19 @@ export class AgentInputCoordinator {
}
const sdkSessionId = await this.deps.getSdkSessionId(sessionId).catch(() => undefined);
if (!this.isActiveTurnCurrent(sessionId, active)) return;
- active.sendStarted = true;
- active.dispatchLifecycle = 'sending';
- // Freeze side-effect timestamps before entering vendor code. A dispatch
- // may synchronously emit the new turn's started marker before it returns;
- // post-dispatch acknowledgements must remain older than that marker.
- const preVendorDispatchAt = Math.max(0, Date.now() - 1);
const referenceContexts = await this.resolveReferenceContexts(head);
+ if (!this.isActiveTurnCurrent(sessionId, active)) return;
head.persistedContent = attachSessionReferenceMetadata(
head.persistedContent,
referenceContexts,
);
const makerUserMessage = buildMakerUserMessage(head, referenceContexts);
+ active.sendStarted = true;
+ active.dispatchLifecycle = 'sending';
+ // Freeze side-effect timestamps before entering vendor code. A dispatch
+ // may synchronously emit the new turn's started marker before it returns;
+ // post-dispatch acknowledgements must remain older than that marker.
+ const preVendorDispatchAt = Math.max(0, Date.now() - 1);
const result = await this.deps.sendToAgent(sessionId, makerUserMessage, head.createOpts, {
[AUTO_REVIEW_SOURCE_CONTENT]: head.autoReviewUserText ?? '',
messageUuid: active.messageUuid,
@@ -4502,6 +4565,9 @@ export class AgentInputCoordinator {
// 放在分支之前 —— 三条出口都不会再走到接管决策。
this.discardDeferredResumableCandidate(sessionId, active);
const latest = this.getState(sessionId);
+ if (this.requeuePreservedAutoResumeIfAttemptCurrent(sessionId, latest, active, err)) {
+ return;
+ }
if (!active.persisted) {
if (isSessionRunningError(err)) {
this.deferQueueHeadAfterSessionRunning(
@@ -4514,6 +4580,9 @@ export class AgentInputCoordinator {
return;
}
if (head.autoResume) {
+ if (this.requeuePreservedAutoResumeIfAttemptCurrent(sessionId, latest, active, err)) {
+ return;
+ }
latest.activeTurn = null;
this.discardAutoResumeBeforeDispatch(sessionId, head);
this.emit(sessionId);
@@ -4537,6 +4606,10 @@ export class AgentInputCoordinator {
this.emit(sessionId);
return;
}
+ if (head.autoResume) {
+ this.settlePersistedAutoResumeSendFailure(sessionId, latest, head, err);
+ return;
+ }
latest.error = errorMessage(err);
clearErrorProjectionSignals(latest);
latest.stickyError = null;
@@ -4573,6 +4646,9 @@ export class AgentInputCoordinator {
// 会重试的分支同理:重试的是**新** turn,旧 error 不会再被接管。
this.discardDeferredResumableCandidate(sessionId, active);
const latest = this.getState(sessionId);
+ if (this.requeuePreservedAutoResumeIfAttemptCurrent(sessionId, latest, active, result)) {
+ return;
+ }
const message = sendFailureMessage(result);
const logFields = sendFailureLogFields(result);
@@ -4586,6 +4662,9 @@ export class AgentInputCoordinator {
return;
}
if (item.autoResume) {
+ if (this.requeuePreservedAutoResumeIfAttemptCurrent(sessionId, latest, active, result)) {
+ return;
+ }
latest.activeTurn = null;
this.discardAutoResumeBeforeDispatch(sessionId, item);
this.emit(sessionId);
@@ -4616,6 +4695,11 @@ export class AgentInputCoordinator {
return;
}
+ if (item.autoResume) {
+ this.settlePersistedAutoResumeSendFailure(sessionId, latest, item, result);
+ return;
+ }
+
latest.activeTurn = null;
latest.error = message;
clearErrorProjectionSignals(latest);
@@ -4831,6 +4915,16 @@ export class AgentInputCoordinator {
this.prependPendingCompactWaitClientId(state, item.clientId);
}
+ private removeQueuedAutoResumeDuplicate(
+ sessionId: string,
+ item: AgentInputQueuedMessage,
+ ): void {
+ const state = this.getState(sessionId);
+ if (!state.pendingQueue.some((queued) => queued.clientId === item.clientId)) return;
+ state.pendingQueue = state.pendingQueue.filter((queued) => queued.clientId !== item.clientId);
+ this.removePendingCompactWaitClientId(state, item.clientId);
+ }
+
private getSessionRunningRetryPolicy(state: SessionInputState): {
ownerKey: string | null;
delayMs: number;
@@ -4961,6 +5055,102 @@ export class AgentInputCoordinator {
state.sessionRunningRetryToken = null;
}
+ /**
+ * Unexpected close 交棒:隐藏 CONTINUE 已离队成为 activeTurn,但还没
+ * vendor dispatch。不能走 discard / 普通 recovery——timer 已 fire,没人再
+ * 调 autoRetryLastError。把同一项放回队首,并抬 generation 让旧 drain 的
+ * persist / send 回调全部变 stale。
+ */
+ private requeuePreservedUndispatchedAutoResume(
+ sessionId: string,
+ state: SessionInputState,
+ active: ActiveTurn,
+ ): boolean {
+ const item = active.item;
+ if (!item?.autoResume) return false;
+ state.generation += 1;
+ state.activeTurn = null;
+ // A replacement that keeps closing must consume the same bounded dispatch
+ // budget as SESSION_RUNNING; preserving the attempt is not a fresh allowance.
+ if (this.abandonAutoResumeAfterTransientFailure(sessionId, state, item, 'unexpected-close')) {
+ return false;
+ }
+ this.prependQueueHeadIfMissing(state, item);
+ state.error = null;
+ clearErrorProjectionSignals(state);
+ state.stickyError = null;
+ state.recovery = null;
+ return true;
+ }
+
+ /**
+ * send 已开始但尚未 vendor accept:unexpected close 先等 outcome。
+ * 确认失败且 attemptToken 仍匹配时,把隐藏 CONTINUE 交回 replacement。
+ * TurnDispatchUnconfirmedError 不得交回——adapter 可能已经 accept,盲目再发会二次副作用。
+ */
+ private requeuePreservedAutoResumeIfAttemptCurrent(
+ sessionId: string,
+ state: SessionInputState,
+ active: ActiveTurn,
+ outcome?: unknown,
+ ): boolean {
+ const item = active.item;
+ if (!item?.autoResume) return false;
+ if (isTurnDispatchUnconfirmedError(outcome)) return false;
+ // 只有 unexpected close 抢在 send outcome 前把 turn 挂起时才交回;
+ // 其它 pre-vendor 失败仍走 discard,避免 cancelled-before-dispatch 空转。
+ if (active.pendingTerminalEvent?.type !== 'done') return false;
+ if (!this.autoResumeAttemptIsCurrent(state, item)) return false;
+ if (!this.requeuePreservedUndispatchedAutoResume(sessionId, state, active)) return true;
+ this.emit(sessionId);
+ this.scheduleDrain(sessionId, 'session-closed-preserved-auto-resume');
+ return true;
+ }
+
+ private autoResumeAttemptIsCurrent(
+ state: SessionInputState,
+ item: AgentInputQueuedMessage,
+ ): boolean {
+ const attemptToken = item.autoResumeInfo?.sessionTotal;
+ return typeof attemptToken === 'number' && state.autoResumeAttemptToken === attemptToken;
+ }
+
+ /**
+ * 已落库的隐藏 CONTINUE 没能确认 vendor accept。token 仍匹配的 unconfirmed
+ * 按可能已 accept 提交本次 attempt,禁止自动再发;其余(含显式 close 已清 token)
+ * 丢弃并交回原错误,不得落成 active-turn recovery。
+ */
+ private settlePersistedAutoResumeSendFailure(
+ sessionId: string,
+ state: SessionInputState,
+ item: AgentInputQueuedMessage,
+ outcome: unknown,
+ ): void {
+ state.activeTurn = null;
+ if (isTurnDispatchUnconfirmedError(outcome) && this.autoResumeAttemptIsCurrent(state, item)) {
+ this.commitAutoResumeDispatch(sessionId, item);
+ this.notifyUnconfirmedAutoResumeTurn(sessionId, item);
+ const message = errorMessage(outcome);
+ state.error = message;
+ clearErrorProjectionSignals(state);
+ state.stickyError = null;
+ this.notifyRejectedUserTurn(sessionId, item);
+ this.persistTerminalSendError(sessionId, message);
+ this.notifyPersistedSendRejected(sessionId, message);
+ log.warn('auto-resume send unconfirmed after persist; committed without replay', {
+ sessionId,
+ clientId: item.clientId,
+ error: message,
+ });
+ this.emit(sessionId);
+ this.deps.onQueueEmptied?.(sessionId);
+ return;
+ }
+ this.discardAutoResumeBeforeDispatch(sessionId, item);
+ this.emit(sessionId);
+ this.deps.onQueueEmptied?.(sessionId);
+ }
+
/** closed 事件可能早于 sendToAgent 返回;这里先挂起 terminal event,等真实 send outcome 决定 drain 还是 recovery。 */
private recordActiveTurnClosedBeforeSendOutcome(
state: SessionInputState,
@@ -5620,6 +5810,37 @@ export class AgentInputCoordinator {
return this.getState(sessionId).autoResumeAttemptToken;
}
+ /**
+ * unexpected close 只交棒 stall/idle/reconnect 的 CONTINUE-only 续跑。
+ * generic auto-retry(empty-response / overload)会克隆原文,不能跟着 Session 重建走。
+ */
+ isContinuationOnlyAutoResume(sessionId: string): boolean {
+ const state = this.states.get(sessionId);
+ if (!state) return false;
+ if (isAcceptedTurnContinuationOnlyReason(state.autoResumePending?.reason)) return true;
+ const activeItem =
+ state.activeTurn?.item && !isActiveTurnDispatched(state.activeTurn)
+ ? state.activeTurn.item
+ : null;
+ const items = activeItem ? [activeItem, ...state.pendingQueue] : state.pendingQueue;
+ return items.some(
+ (item) =>
+ item.autoResume === true &&
+ isAcceptedTurnContinuationOnlyReason(item.autoResumeInfo?.reason),
+ );
+ }
+
+ /**
+ * Hidden auto-resume CONTINUE is already in pendingQueue, or is the
+ * not-yet-dispatched active turn. Unexpected close must preserve and wake it.
+ */
+ hasQueuedAutoResume(sessionId: string): boolean {
+ const state = this.getState(sessionId);
+ if (state.pendingQueue.some((item) => item.autoResume === true)) return true;
+ const active = state.activeTurn;
+ return Boolean(active?.item?.autoResume && !isActiveTurnDispatched(active));
+ }
+
/** Exact owner for a deferred resumable terminal error, before it is decided. */
getAutoResumeDeferredOwner(sessionId: string): SuppressedTurnErrorOwner | null {
const active = this.getState(sessionId).activeTurn;
@@ -5685,8 +5906,11 @@ export class AgentInputCoordinator {
if (this.isActiveTurnCurrent(sessionId, active)) return false;
if (active.item?.autoResume) {
if (dispatchAccepted) {
+ // Vendor 已 accept:即使 unexpected close 曾把同一项重新入队,也必须
+ // commit 并摘掉队里的重复项,否则 replacement 会二次 CONTINUE。
this.commitAutoResumeDispatch(sessionId, active.item);
- } else {
+ this.removeQueuedAutoResumeDuplicate(sessionId, active.item);
+ } else if (!this.hasQueuedAutoResume(sessionId)) {
this.discardAutoResumeBeforeDispatch(sessionId, active.item);
}
}
@@ -5819,6 +6043,21 @@ export class AgentInputCoordinator {
}
}
+ private notifyUnconfirmedAutoResumeTurn(
+ sessionId: string,
+ item: AgentInputQueuedMessage,
+ ): void {
+ try {
+ this.deps.onUnconfirmedAutoResumeTurn?.(sessionId, item);
+ } catch (err) {
+ log.warn('onUnconfirmedAutoResumeTurn failed', {
+ sessionId,
+ clientId: item.clientId,
+ error: errorMessage(err),
+ });
+ }
+ }
+
private persistTerminalSendError(sessionId: string, message: string): void {
if (!message.trim()) return;
try {
diff --git a/apps/desktop/src/main/maker-ipc/autoResumeBookkeeping.ts b/apps/desktop/src/main/maker-ipc/autoResumeBookkeeping.ts
index e4dbcce4ff..482d59a47d 100644
--- a/apps/desktop/src/main/maker-ipc/autoResumeBookkeeping.ts
+++ b/apps/desktop/src/main/maker-ipc/autoResumeBookkeeping.ts
@@ -633,6 +633,37 @@ export class AutoResumeBookkeeping {
return this.settleOutcome(sessionId, attemptToken, outcome);
}
+ /**
+ * 已落库的隐藏 CONTINUE 无法确认 vendor 是否 accept。把这条续跑记成 failed,
+ * 丢掉原 suppressed error(不再补落、不再恢复 recovery),并回滚守卫 pendingResume。
+ * 终态错误由调用方自己表面;这里不得 requeue、不得把旧中断再弹出来。
+ */
+ abandonUnconfirmedPersistedResume(
+ sessionId: string,
+ attemptToken: number,
+ clientId: string,
+ ): boolean {
+ if (!this.isCurrentAttempt(sessionId, attemptToken)) return false;
+ const pending = this.pendingOutcomes.get(sessionId);
+ const entry = this.suppressedErrors.get(sessionId);
+ if (pending && (pending.clientId !== clientId || pending.attemptToken !== attemptToken)) {
+ return false;
+ }
+ if (entry?.retryOwnerClientId && entry.retryOwnerClientId !== clientId) return false;
+ if (!pending && entry?.retryOwnerClientId !== clientId) return false;
+ const orcaTerminal = entry?.orcaTerminal ?? null;
+ this.settleOutcomeForClient(sessionId, attemptToken, clientId, 'failed');
+ this.discardSuppressedErrorForRetry(sessionId, clientId);
+ this.discardSuppressedError(sessionId, attemptToken);
+ // The unconfirmed send is a product failure. Settle its captured Worker once
+ // without restoring the old error card or replaying the continuation.
+ this.releaseOrcaSuppressedTerminal(sessionId, orcaTerminal, true);
+ this.deps.rollbackGuardPendingResume(sessionId, attemptToken);
+ this.deps.onAutoResumeFailed?.(sessionId, attemptToken);
+ this.releaseAttemptIfUnowned(sessionId, attemptToken);
+ return true;
+ }
+
private releaseAttemptIfUnowned(sessionId: string, attemptToken: number): void {
if (this.currentAttempts.get(sessionId) !== attemptToken) return;
const pending = this.pendingOutcomes.get(sessionId);
@@ -780,13 +811,25 @@ export class AutoResumeBookkeeping {
return this.schedules.has(sessionId);
}
+ /**
+ * Whether the exact attempt still owns a schedule: waiting timer **or**
+ * in-flight callback. Unexpected close during either phase must preserve the
+ * approved continuation-only retry.
+ */
+ hasLiveSchedule(sessionId: string, attemptToken: number): boolean {
+ const scheduled = this.schedules.get(sessionId);
+ return (
+ scheduled?.attemptToken === attemptToken &&
+ this.currentAttempts.get(sessionId) === attemptToken
+ );
+ }
+
/**
* Whether the exact attempt is still waiting for its timer to fire.
*
- * `hasSchedule()` intentionally also returns true while the callback is
- * awaiting DB/coordinator work. Session-close handoff must distinguish that
- * execution phase from the pre-fire rebuild window; once the timer has fired,
- * the old Session is no longer safe to preserve.
+ * `hasLiveSchedule()` / `hasSchedule()` also return true while the callback is
+ * awaiting DB/coordinator work. Tests use this narrower check to distinguish
+ * those phases; session-close handoff must not treat timer-fired as cancelled.
*/
hasWaitingSchedule(sessionId: string, attemptToken: number): boolean {
const scheduled = this.schedules.get(sessionId);
diff --git a/apps/desktop/src/main/maker-ipc/interruptedTurnAutoResume.ts b/apps/desktop/src/main/maker-ipc/interruptedTurnAutoResume.ts
index ff7c452351..335b28b107 100644
--- a/apps/desktop/src/main/maker-ipc/interruptedTurnAutoResume.ts
+++ b/apps/desktop/src/main/maker-ipc/interruptedTurnAutoResume.ts
@@ -83,7 +83,7 @@ function isStreamTruncationError(signals: InterruptedTurnErrorSignals): boolean
*
* 先过 reason 门(带稳定 reason 的都是 translator 已归类的错误:`turn-failed`
* 连错误详情都没有、`silent-stop-exhausted` 是另一套自愈的耗尽信号),然后认
- * 三类:
+ * 四类:
*
* 1. **SSE 流被切断**(`isStreamTruncationError`)——最初的实测形态。
* 2. **网络到不了上游**(`isNetworkishErrorMessage`:502/503/504、errno、
@@ -94,6 +94,9 @@ function isStreamTruncationError(signals: InterruptedTurnErrorSignals): boolean
* `reason: 'upstream-overload'`**(translator 对每条容量错误都盖这个 key,renderer
* 隔着 IPC 只能靠它本地化文案),所以 reason 门必须给它开例外 —— 否则第 3 类对 Codex
* 恒为死代码,本份声称要接的「容量 + 已有产出」那一格永远走不到(codex review P1)。
+ * 4. **没有产品进展的假运行**(`turn_no_event_timeout` /
+ * `upstream_response_idle_timeout`,以及已有的 `codex_reconnect_stalled`)。
+ * 用量心跳不能冒充进展;看门狗打断之后必须走自动续跑,不能当成「还在跑」。
*
* **第 3 类与 #844 的分工靠「本 turn 有没有产出」自动划清,两者互斥、不会叠加重试**:
* 容量拒绝发生在 admission 阶段(模型一个字都没写)时,Codex 侧会重投同一份
@@ -104,6 +107,57 @@ function isStreamTruncationError(signals: InterruptedTurnErrorSignals): boolean
* 认这三类刻意**不**要求 `server_error` tag、也**允许**带状态码——502 / 529 本身就带
* 状态码,网络 errno 也没有 SDK tag。收紧只对第 1 类成立。
*/
+/**
+ * 这类 reason 表示 turn **已经被上游 / daemon accept** 之后卡死,不是 admission 失败。
+ *
+ * 自动续跑只能发 CONTINUE,不能克隆原始用户 prompt:本 turn 可能已经跑过工具、写过
+ * 文件,即使 DB 里还没有 assistant 行(心跳 zombie 就是这种形态)。
+ * `empty-response` / 流截断可以发生在零副作用的 admission 阶段,克隆原文仍然安全。
+ */
+export function isAcceptedTurnContinuationOnlyReason(reason: unknown): boolean {
+ return (
+ reason === 'turn_no_event_timeout' ||
+ reason === 'upstream_response_idle_timeout' ||
+ reason === 'codex_reconnect_stalled'
+ );
+}
+
+/**
+ * continuation-only 自动续跑已批准后,provider/Session 可能因为 stall abort 复核、
+ * terminal-error drain、或 Codex interrupt ACK 失败而 unexpected close。这时必须保住
+ * 已批准的自动续跑,不论退避 timer 是否已经开火。
+ *
+ * 只认 `unexpected`:用户 Stop / 关会话 / 切 agent 仍取消。lease 优先绑在**当时那个**
+ * Session 实例的 attemptToken 上,避免替身会话继承迟到的 close 回调。
+ *
+ * 交棒窗口包括:timer 还在等、callback 正在跑、CONTINUE 已因 SESSION_RUNNING
+ * 回到 pendingQueue,以及 CONTINUE 已进入 drain 但尚未 vendor dispatch。
+ * 连续 replacement close 时 WeakMap 可能已经跟着旧实例走了;此时只要
+ * coordinator / guard / book 仍指向同一 attemptToken,且队里或 live schedule
+ * 还活着,就用 coordinator token 交棒,不能把已批准的续跑拆掉。
+ */
+export function shouldPreserveWaitingContinuationOnlyAutoResume(input: {
+ closeReason: unknown;
+ leasedAttemptToken: number | undefined;
+ guardIsCurrentAttempt: boolean;
+ bookIsCurrentAttempt: boolean;
+ coordinatorAttemptToken: number | null | undefined;
+ hasLiveSchedule: boolean;
+ hasQueuedAutoResume: boolean;
+ isContinuationOnly: boolean;
+}): boolean {
+ if (input.closeReason !== 'unexpected') return false;
+ if (input.isContinuationOnly !== true) return false;
+ const token =
+ input.leasedAttemptToken ??
+ (typeof input.coordinatorAttemptToken === 'number' ? input.coordinatorAttemptToken : undefined);
+ if (token === undefined) return false;
+ if (!input.guardIsCurrentAttempt || !input.bookIsCurrentAttempt) return false;
+ if (input.coordinatorAttemptToken !== token) return false;
+ // autoRetryLastError 在入队前就清掉 autoResumePending;不能靠它判断交棒窗口。
+ return input.hasLiveSchedule || input.hasQueuedAutoResume;
+}
+
export function isInterruptedTurnError(signals: InterruptedTurnErrorSignals): boolean {
const reason = typeof signals.reason === 'string' ? signals.reason : '';
// 例外先行:`upstream-overload` 是**已归类为可重试**的 reason,它本身就是比文案更可靠的
@@ -117,10 +171,13 @@ export function isInterruptedTurnError(signals: InterruptedTurnErrorSignals): bo
// 见 performRetryLastError),对已有 durable progress 的长任务则带 RecoveryCheckpoint
// 续跑——两种形态都有安全动作可执行。连续空响应仍由同一份连续失败上限 / 人工介入周期
// 硬上限 / 退避止损,预算耗尽后横幅交还用户,不会无界重试。
+ //
+ // stall / idle / reconnect-stalled 也放行,但 coordinator 对它们是 **CONTINUE-only**:
+ // 见 `isAcceptedTurnContinuationOnlyReason`。
if (
reason === UPSTREAM_OVERLOAD_REASON ||
- reason === 'codex_reconnect_stalled' ||
- reason === 'empty-response'
+ reason === 'empty-response' ||
+ isAcceptedTurnContinuationOnlyReason(reason)
) {
return true;
}
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index bd0cfe034a..5de2513ede 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -1048,8 +1048,10 @@ import {
} from './autoResumeBookkeeping.js';
import {
InterruptedTurnAutoResumeGuard,
+ isAcceptedTurnContinuationOnlyReason,
isAutoResumeUserMessage,
isInterruptedTurnError,
+ shouldPreserveWaitingContinuationOnlyAutoResume,
type InterruptedTurnErrorSignals,
} from './interruptedTurnAutoResume.js';
import { readInterruptedTurnAutoResumeSettings } from '../maker-host/interrupted-turn-auto-resume-store.js';
@@ -1304,12 +1306,16 @@ const autoResumeBookkeeping = new AutoResumeBookkeeping({
});
/**
- * A Codex reconnect-stall retry is scheduled against the current runtime
- * Session, but that provider may close/rebuild the exact instance before the
+ * Continuation-only auto-retry is scheduled against the current runtime
+ * Session, but stall abort recovery, terminal-error drain, or a Codex
+ * interrupt ACK failure may close/rebuild that exact instance before the
* backoff timer fires. Bind the lease to the instance, not only sessionId:
* a replacement Session can otherwise inherit a late close callback.
+ *
+ * Only `unexpected` closes preserve the lease. User-requested close/stop
+ * still cancel via teardown.
*/
-const pendingCodexReconnectStalledRebuilds = new WeakMap<Session, number>();
+const pendingContinuationOnlyAutoResumeRebuilds = new WeakMap<Session, number>();
const pendingSessionRuntimeFallbackRebuilds = new WeakMap<Session, number>();
/**
@@ -3177,24 +3183,50 @@ function getWiredSessionCloseReason(session: WiredSession) {
}
/**
- * Preserve only the narrow provider-rebuild handoff window for an interrupted
- * Codex reconnect stall. Every check is deliberately instance- and token-
- * scoped so a user close, a later retry, or an already-running callback cannot
- * resurrect the old business session.
+ * Preserve the provider-rebuild handoff window for continuation-only
+ * auto-retry (stall / idle / reconnect-stall). Every check is instance- and
+ * token-scoped so a user close or a later retry cannot resurrect the old
+ * business session. An in-flight callback / queued CONTINUE still belongs to
+ * this attempt and must survive unexpected close.
*/
-function shouldPreserveCodexReconnectStalledAutoResume(
+function bindContinuationOnlyAutoResumeLease(session: Session): void {
+ const coordinator = agentInputCoordinatorHolder;
+ const token = coordinator?.getAutoResumeAttemptToken(session.id);
+ if (
+ typeof token !== 'number' ||
+ coordinator?.isContinuationOnlyAutoResume(session.id) !== true ||
+ !interruptedTurnAutoResumeGuard.isCurrentAttempt(session.id, token) ||
+ !autoResumeBookkeeping.isCurrentAttempt(session.id, token)
+ ) {
+ return;
+ }
+ pendingContinuationOnlyAutoResumeRebuilds.set(session, token);
+}
+
+function shouldPreserveContinuationOnlyAutoResume(
session: WiredSession,
closeReason: ReturnType<typeof getWiredSessionCloseReason>,
): boolean {
- const attemptToken = pendingCodexReconnectStalledRebuilds.get(session);
- if (attemptToken === undefined) return false;
- if (closeReason !== 'unexpected') return false;
- if (!interruptedTurnAutoResumeGuard.isCurrentAttempt(session.id, attemptToken)) return false;
- if (!autoResumeBookkeeping.isCurrentAttempt(session.id, attemptToken)) return false;
const coordinator = agentInputCoordinatorHolder;
- if (!coordinator || !coordinator.isAutoResumePending(session.id)) return false;
- if (coordinator.getAutoResumeAttemptToken(session.id) !== attemptToken) return false;
- return autoResumeBookkeeping.hasWaitingSchedule(session.id, attemptToken);
+ const coordinatorAttemptToken = coordinator?.getAutoResumeAttemptToken(session.id);
+ const leasedAttemptToken = pendingContinuationOnlyAutoResumeRebuilds.get(session);
+ const attemptToken =
+ leasedAttemptToken ??
+ (typeof coordinatorAttemptToken === 'number' ? coordinatorAttemptToken : undefined);
+ return shouldPreserveWaitingContinuationOnlyAutoResume({
+ closeReason,
+ leasedAttemptToken,
+ guardIsCurrentAttempt:
+ attemptToken !== undefined &&
+ interruptedTurnAutoResumeGuard.isCurrentAttempt(session.id, attemptToken),
+ bookIsCurrentAttempt:
+ attemptToken !== undefined && autoResumeBookkeeping.isCurrentAttempt(session.id, attemptToken),
+ coordinatorAttemptToken,
+ hasLiveSchedule:
+ attemptToken !== undefined && autoResumeBookkeeping.hasLiveSchedule(session.id, attemptToken),
+ hasQueuedAutoResume: Boolean(coordinator?.hasQueuedAutoResume(session.id)),
+ isContinuationOnly: coordinator?.isContinuationOnlyAutoResume(session.id) === true,
+ });
}
/**
@@ -4310,6 +4342,7 @@ const sessionBindings = createSessionBindingLifecycle<WiredSession, WiredSession
},
onBind: (session: WiredSession) => {
advanceSessionTurnBoundaryGeneration(session.id);
+ bindContinuationOnlyAutoResumeLease(session);
},
broadcastStatus: (session: WiredSession, status) => {
broadcastToAllWindows(MAKER_PUSH.STATUS_CHANGED, { sessionId: session.id, status });
@@ -4318,16 +4351,16 @@ const sessionBindings = createSessionBindingLifecycle<WiredSession, WiredSession
const closeReason = getWiredSessionCloseReason(session);
const closedDirectAbortBoundary = getDirectAbortBoundaryForClosingSession(session.id, session);
const preserveAutoResumeIntent =
- shouldPreserveCodexReconnectStalledAutoResume(session, closeReason) ||
+ shouldPreserveContinuationOnlyAutoResume(session, closeReason) ||
shouldPreserveSessionRuntimeFallbackAutoResume(session, closeReason);
- pendingCodexReconnectStalledRebuilds.delete(session);
+ pendingContinuationOnlyAutoResumeRebuilds.delete(session);
return { closeReason, closedDirectAbortBoundary, preserveAutoResumeIntent };
},
cleanupClosedSession: (session: WiredSession, context) => {
runSessionCloseCleanup(context.preserveAutoResumeIntent, {
cleanupInteractions: () => cleanupPendingInteractionsForSession(session.id, 'session_closed'),
preserveAutoResume: () => {
- log.info('preserving scheduled Codex reconnect-stall auto-resume across provider rebuild', {
+ log.info('preserving scheduled continuation-only auto-resume across provider rebuild', {
sessionId: session.id,
attemptToken: agentInputCoordinatorHolder?.getAutoResumeAttemptToken(session.id),
closeReason: context.closeReason,
@@ -13358,10 +13391,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (schedulerRunId) {
beginSchedulerAutoResume(sessionId, schedulerRunId, decision.attemptToken);
}
- if (signals.reason === 'codex_reconnect_stalled') {
+ if (isAcceptedTurnContinuationOnlyReason(signals.reason)) {
const runtimeSession = getStableSessionForTurnBoundary(sessionId);
if (runtimeSession) {
- pendingCodexReconnectStalledRebuilds.set(runtimeSession, decision.attemptToken);
+ pendingContinuationOnlyAutoResumeRebuilds.set(runtimeSession, decision.attemptToken);
}
}
// 排期的撤旧、补落与令牌都在 AutoResumeBookkeeping.schedule 里(带单测),这里只给
@@ -13438,6 +13471,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// (「重新连接中 attempt/maxAttempts」+ 展开详情里的原因与会话累计)。
return {
...(signals.message !== undefined ? { error: signals.message } : {}),
+ ...(typeof signals.reason === 'string' && signals.reason.length > 0
+ ? { reason: signals.reason }
+ : {}),
attempt: decision.attempt,
maxAttempts: decision.maxAttempts,
sessionTotal: decision.sessionTotal,
@@ -13675,6 +13711,15 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
null,
);
},
+ onUnconfirmedAutoResumeTurn: (sessionId, item) => {
+ const attemptToken = autoResumeAttemptToken(item);
+ if (attemptToken === null) return;
+ autoResumeBookkeeping.abandonUnconfirmedPersistedResume(
+ sessionId,
+ attemptToken,
+ item.clientId,
+ );
+ },
onPersistedSendRejected: (sessionId, message) => {
if (!isPiPromptRpcTimeoutError({ message })) return;
// 第一次 timeout:只关掉卡住的原生进程,不自动 replay。用户重试时再 hidden rebuild。
diff --git a/apps/desktop/src/renderer/components/chat/errorReasonI18n.ts b/apps/desktop/src/renderer/components/chat/errorReasonI18n.ts
index b90be3d3ce..5007c08136 100644
--- a/apps/desktop/src/renderer/components/chat/errorReasonI18n.ts
+++ b/apps/desktop/src/renderer/components/chat/errorReasonI18n.ts
@@ -26,6 +26,7 @@ export const ERROR_REASON_I18N_KEYS: Record<string, string> = {
'codex-auto-review-unavailable': 'logic.errors.codexAutoReviewUnavailable',
'host-shell-command-blocked': 'logic.errors.hostShellCommandBlocked',
upstream_response_idle_timeout: 'logic.errors.upstreamResponseIdleTimeout',
+ bridge_upstream_response_idle_timeout: 'logic.errors.upstreamResponseIdleTimeout',
codex_reconnect_stalled: 'logic.errors.upstreamResponseIdleTimeout',
codex_history_oversized: 'logic.errors.codexHistoryOversized',
// Persisted error rows and the live reason both lack a reliable retirement
@@ -39,6 +40,7 @@ export const ERROR_REASON_I18N_KEYS: Record<string, string> = {
'logic.errors.codexCompactionNotConvergingModelSwitch',
session_event_loop_crashed: 'logic.errors.turnFailed',
turn_no_event_timeout: 'logic.errors.turnNoEventTimeout',
+ bridge_turn_no_event_timeout: 'logic.errors.turnNoEventTimeout',
'context-overflow': 'chat.errorBanner.contextOverflow',
[UPSTREAM_OVERLOAD_REASON]: 'chat.errorBanner.overloadBusyNoRetry',
[UPSTREAM_STREAM_INTERRUPTED_REASON]: 'chat.errorBanner.streamInterruptedNoRetry',
diff --git a/apps/desktop/src/shared/agentInputQueue.ts b/apps/desktop/src/shared/agentInputQueue.ts
index 11831b4856..dd1108baf5 100644
--- a/apps/desktop/src/shared/agentInputQueue.ts
+++ b/apps/desktop/src/shared/agentInputQueue.ts
@@ -177,6 +177,11 @@ export interface AgentInputClearBoundaryOpts {
export interface AutoResumeInfo {
/** 中断原文(terminal error 的 message,通常是 SDK 的英文文案)。 */
error?: string;
+ /**
+ * translator / watchdog 给出的稳定 reason。展示用,自动续跑也靠它决定
+ * CONTINUE-only(已 accept 的 stall/idle/reconnect-stalled)还是可以克隆原文。
+ */
+ reason?: string;
/** 本轮连续第几次重连(从 1 起)。 */
attempt: number;
/** 本轮上限。 */
diff --git a/docs/dev-rules/maker-core-and-agent-behavior.md b/docs/dev-rules/maker-core-and-agent-behavior.md
index d7a90cd70f..0bda60d83b 100644
--- a/docs/dev-rules/maker-core-and-agent-behavior.md
+++ b/docs/dev-rules/maker-core-and-agent-behavior.md
@@ -120,7 +120,44 @@ Codex 0.153 的 unsubscribe 会延迟卸载 30 分钟,不能靠立即 resume
Codex 的 120 秒 reconnect watchdog 只是 fallback 收口,不是根因诊断。stderr 仍只作诊断日志,
不得用 `remote compaction v2` 文案驱动恢复动作。普通 timeout、纯文本大历史和网络失败
-不得进入这套压缩,也不得进入自动续跑死循环。
+不得进入这套压缩,也不得进入自动续跑死循环。`status` / `account_usage` 是传输层或用量
+心跳,不得刷新 Session 零事件看门狗或 Codex upstream-idle 计时。`text` / `thinking`
+只有包含实质文字才刷新;仅空白、Unicode 格式字符或控制字符不算进展,原事件仍无损传递。
+这两类超时与
+`codex_reconnect_stalled` 同类,进入 interrupted-turn 自动续跑;自动续跑对这三类
+**只发 CONTINUE 指令,绝不克隆原始用户 prompt**(turn 已被 accept,克隆会重放已执行的
+工具副作用)。Claude rewind / cancellation bridge 的 `/compact` 位于真实用户输入之前,
+Claude idle 超时使用 `bridge_upstream_response_idle_timeout`;共享 Session stall 同步查询
+handle 的只读 `isPreparingUserTurn()`,使用 `bridge_turn_no_event_timeout`。两者不进入
+该自动续跑白名单;查询复用 Claude 唯一的 `bridgeStateActive()`,包含 compact result 后
+到下一 SDK 消息前的间隙,不新增桥接状态。保持既有
+清队列、保留重建目标与人工重试行为,不能对尚未执行的用户输入发送 CONTINUE。
+引用内容解析等异步准备仍属于未派发态;完成后复核 active 身份,再在真正调用 send 前
+标记 sendStarted,迟到的准备结果不得发送或修改已经交给 replacement 的项。
+自动 CONTINUE 保留原请求的 Plan 与权限选项;超时恢复不等于 ExitPlanMode 批准,
+不得强制 planMode=false。若原计划已批准后执行失败,缺少可靠的审批周期记录时仍保守
+保留原 Plan 选项,可能重新进入计划模式;不为避免重入新增审批状态。人工 Retry 沿用
+既有合成 UI 动作策略,本自动恢复修复不调整该策略。
+退避窗口内 provider / Session 因 stall abort 复核、terminal-error drain
+或 interrupt ACK 失败而 `unexpected` close 时,必须用实例 + attemptToken 精确保留交棒,
+不得 teardown 已批准的自动续跑——包括 timer 已 fire、CONTINUE 已因 SESSION_RUNNING
+回队、CONTINUE 已进入 drain 但尚未 vendor dispatch、以及 CONTINUE 已 sendStarted 但
+send outcome 尚未返回的窗口。尚未 sendStarted 的未派发项必须重新入队再唤醒 replacement;
+send 已开始则等真实 outcome——vendor 已 accept 必须 commit、禁止二次 CONTINUE;
+`TurnDispatchUnconfirmedError`(adapter 已发出请求但无法确定 provider 是否 accept)
+不得自动再发 CONTINUE,按可能已 accept 提交本次 attempt,并结算 AutoResumeBookkeeping
+(pendingOutcome=failed、丢弃 suppressed、rollback guard);不得走会补落旧错误、恢复
+recovery 或再入队的 undispatched finalize。确认失败且 attemptToken 仍匹配才重新入队。
+显式关闭 / 停止已清 token 后,sendStarted 且已落库的隐藏 CONTINUE 必须丢弃,不得落成
+可重试 recovery。unexpected close 的 preserve 只认三类 CONTINUE-only reason
+(stall / idle / reconnect-stall);generic clone-原文 retry fail-closed 不交棒。
+连续 replacement `unexpected` close 时 WeakMap lease 可能已随旧实例消失,必须按同一
+attemptToken 把 lease 绑到新 Session,或在 coordinator / guard / book 仍一致且队里 /
+live schedule 仍活着时继续 preserve。预算内不能 discard 或只留人工 recovery,也不能清掉
+sessionRunningRetry 就停。每次因 replacement 关闭而重新入队都计入同一份三次派发预算,
+包括尚在 pendingQueue、已取出但尚未发送、以及发送确认失败的窗口;一次 close 不能对
+刚放回队列的 active 项重复计数。等待发送结果本身不重复计数,耗尽后恢复原错误并停止交棒。
+用户显式关闭 / 停止仍取消。连续失败上限与人工介入周期硬上限止损,额度耗尽才把 Continue 交还用户。
> **适用范围与增量原则**:Agent 能力归属(下节 1)与代码优先确定性(下节 2)按增量
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index 8ead3c1115..3d782554aa 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -2361,6 +2361,11 @@ export interface AgentSessionHandle {
* 默认实现为 false (capability 缺失时 host 不该问)。
*/
isTurnRunning?(): boolean;
+ /** A provider-owned preparatory turn still precedes the accepted user input.
+ * Host timeouts must not resume it with a generic CONTINUE. Read synchronously
+ * before abort clears the provider's existing preparation state.
+ */
+ isPreparingUserTurn?(): boolean;
}
export abstract class BaseAgent {
diff --git a/packages/maker-core/src/agents/claude-code/__tests__/abort-stops-background-tasks.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/abort-stops-background-tasks.test.ts
index 315b96c607..b1d86eb4d0 100644
--- a/packages/maker-core/src/agents/claude-code/__tests__/abort-stops-background-tasks.test.ts
+++ b/packages/maker-core/src/agents/claude-code/__tests__/abort-stops-background-tasks.test.ts
@@ -2974,7 +2974,7 @@ describe('ClaudeCodeAgent abort stops background wake tasks', () => {
() => events.some(
(event) => event.type === 'error' &&
(event.data as { reason?: unknown } | null | undefined)?.reason ===
- 'upstream_response_idle_timeout',
+ 'bridge_upstream_response_idle_timeout',
),
'watchdog timeout observed',
);
diff --git a/packages/maker-core/src/agents/claude-code/__tests__/rewind-runtime-settings.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/rewind-runtime-settings.test.ts
index 37835511b4..1a988619c6 100644
--- a/packages/maker-core/src/agents/claude-code/__tests__/rewind-runtime-settings.test.ts
+++ b/packages/maker-core/src/agents/claude-code/__tests__/rewind-runtime-settings.test.ts
@@ -20,6 +20,7 @@ import path from 'node:path';
import { afterEach, describe, expect, it, vi } from 'vitest';
import type { AgentDeps } from '../../base-agent.js';
+import { Session } from '../../../session.js';
import type { AuthAdapter } from '../../../interfaces/auth-adapter.js';
import type { AgentEvent } from '../../../types/events.js';
import type { Logger } from '../../../interfaces/logger.js';
@@ -1830,6 +1831,44 @@ describe('ClaudeCodeAgent runtime settings during rewind window', () => {
await handle.close();
});
+ it.each(['compact-running', 'between-turns', 'user-running'] as const)(
+ 'shared stall distinguishes the bridge from user execution: %s', async (phase) => {
+ const { agent, handle, firstQuery } = await startRewindableSession({ autoCompactThresholdPct: 50 });
+ firstQuery.stream.emit({ type: 'stream_event', event: {
+ type: 'message_delta', usage: { input_tokens: 400_000, output_tokens: 0 },
+ } });
+ await handle.commitRewindFiles?.('user-uuid-1', 'assistant-uuid-1');
+ await handle.setModel?.('claude-sonnet-5');
+ const query = createFakeQuery();
+ sdkMock.query.mockReturnValue(query);
+ const session = new Session({ id: 'bridge-stall', agentKind: 'claude-code',
+ workDir: '/repo', handle, capabilities: agent.capabilities,
+ logger: createNoopLogger(), turnStallMs: 200 });
+ const events: AgentEvent[] = [];
+ session.onEvent((event) => events.push(event));
+ try {
+ await session.send('execute the original instruction');
+ if (phase !== 'compact-running') {
+ query.stream.emit({ type: 'result', stop_reason: 'end_turn',
+ total_cost_usd: 0, usage: { input_tokens: 0, output_tokens: 0 } });
+ }
+ if (phase === 'user-running') {
+ query.stream.emit({ type: 'stream_event', event: { type: 'message_start',
+ message: { id: 'real-user-turn', role: 'assistant', content: [],
+ usage: { input_tokens: 0, output_tokens: 0 } } } });
+ }
+ await vi.waitFor(() => expect(events).toContainEqual(expect.objectContaining({
+ type: 'error', data: expect.objectContaining({ reason: phase === 'user-running'
+ ? 'turn_no_event_timeout' : 'bridge_turn_no_event_timeout' }),
+ })), { timeout: 2000 });
+ if (phase !== 'user-running') {
+ expect(query.close).toHaveBeenCalled();
+ expect(query.interrupt).not.toHaveBeenCalled();
+ }
+ } finally { await session.close(); }
+ },
+ );
+
it('upstream-idle watchdog during bridge closes query and rebuilds from rewind point', async () => {
// 反馈原型 (Codex review 3535664420 / 3536509277): watchdog 是**直接 push eventQueue**
// 绕过 filter;若打在 bridge /compact 上,只清 counter + interrupt 仍无法追回 SDK 已
@@ -1863,7 +1902,7 @@ describe('ClaudeCodeAgent runtime settings during rewind window', () => {
events.some(
(e) =>
e.type === 'error' &&
- (e.data as { reason?: string }).reason === 'upstream_response_idle_timeout',
+ (e.data as { reason?: string }).reason === 'bridge_upstream_response_idle_timeout',
),
'watchdog terminal error must reach eventQueue (not swallowed by bridge filter)',
).toBe(true);
@@ -1872,7 +1911,7 @@ describe('ClaudeCodeAgent runtime settings during rewind window', () => {
);
await vi.waitFor(() => {
expect(
- events.some((e) => e.type === 'done' && (e.data as { reason?: string }).reason === 'upstream_response_idle_timeout'),
+ events.some((e) => e.type === 'done' && (e.data as { reason?: string }).reason === 'bridge_upstream_response_idle_timeout'),
).toBe(true);
});
@@ -1947,7 +1986,7 @@ describe('ClaudeCodeAgent runtime settings during rewind window', () => {
events.some(
(e) =>
e.type === 'error' &&
- (e.data as { reason?: string }).reason === 'upstream_response_idle_timeout',
+ (e.data as { reason?: string }).reason === 'bridge_upstream_response_idle_timeout',
),
).toBe(true);
},
diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.ts
index f326e7d1a9..fc6e7e7724 100644
--- a/packages/maker-core/src/agents/claude-code/index.ts
+++ b/packages/maker-core/src/agents/claude-code/index.ts
@@ -2892,7 +2892,9 @@ export class ClaudeCodeAgent extends BaseAgent {
`已自动中断当前 turn 防止卡死。可以直接发下一条消息继续 ` +
`(已完成的 tool result 都保留)。`,
isTerminal: true,
- reason: 'upstream_response_idle_timeout',
+ // The bridge precedes the user's input, which is cleared below.
+ // It is not an accepted user turn that can receive CONTINUE.
+ reason: 'bridge_upstream_response_idle_timeout',
idleMs,
sdkSessionId,
lastEventType: upstreamResponseLastEventType,
@@ -2916,7 +2918,7 @@ export class ClaudeCodeAgent extends BaseAgent {
turnState.interruptRequested = false;
pendingToolIds.clear();
preserveBridgeRetryTarget(timedOutBridgeKind, timedOutRewindResumeAt);
- emitTurnBoundary('upstream_response_idle_timeout', suppressedDoneData);
+ emitTurnBoundary('bridge_upstream_response_idle_timeout', suppressedDoneData);
return;
}
eventQueue.push({
@@ -6960,6 +6962,8 @@ export class ClaudeCodeAgent extends BaseAgent {
// ── Rewind (Stage 2 C2) ────────────────────────────────────────────────
+ isPreparingUserTurn: bridgeStateActive,
+
isTurnRunning(): boolean {
// 前台 result/done 到后台 wake 任务自动续 turn 之间,SDK 会短暂把
// turnInFlight 清成 false,但从产品/Session 视角 Agent 仍未执行结束。
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index dfda9ea5ee..747ab0bb5b 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -28917,6 +28917,95 @@ describe('CodexAgent upstream-response-idle watchdog', () => {
}
});
+ it('status 用量心跳不重置 idle:自动续跑后的 zombie running 能被收口', async () => {
+ vi.useFakeTimers();
+ try {
+ const agent = new CodexAgent(createDeps());
+ const host = installIdleHost(agent);
+ const handle = await startIdleSession(agent, 'session-idle-usage-heartbeat');
+ const seen = collectEvents(handle);
+ await handle.send({ type: 'user', content: 'go' });
+ const handlers = host.getThreadHandlers();
+ if (!handlers) throw new Error('expected thread handlers');
+ handlers.turnStarted?.({ threadId: 'start-thread-id', turn: { id: 'turn-1' } } as never);
+
+ for (let i = 1; i <= 5; i++) {
+ await vi.advanceTimersByTimeAsync(500);
+ handlers.tokenUsageUpdated?.({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ tokenUsage: {
+ total: {
+ totalTokens: 100 * i,
+ inputTokens: 80 * i,
+ outputTokens: 20 * i,
+ cachedInputTokens: 0,
+ },
+ last: {
+ totalTokens: 100 * i,
+ inputTokens: 80 * i,
+ outputTokens: 20 * i,
+ cachedInputTokens: 0,
+ },
+ },
+ } as never);
+ await vi.advanceTimersByTimeAsync(0);
+ }
+
+ expect(seen.filter((ev) => ev.type === 'status').length).toBeGreaterThan(1);
+
+ await vi.advanceTimersByTimeAsync(IDLE_MS + 1 - 5 * 500);
+
+ const terminal = seen.find(
+ (ev) =>
+ ev.type === 'error' &&
+ (ev.data as { reason?: string } | null)?.reason === 'upstream_response_idle_timeout',
+ );
+ expect(terminal).toBeDefined();
+ expect((terminal!.data as { isTerminal?: boolean }).isTerminal).toBe(true);
+ await handle.close();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it.each(['agentMessageDelta', 'reasoningTextDelta'] as const)(
+ '%s 的不可见内容不刷新 idle,真实内容仍刷新',
+ async (handlerName) => {
+ vi.useFakeTimers();
+ try {
+ const agent = new CodexAgent(createDeps());
+ const host = installIdleHost(agent);
+ const handle = await startIdleSession(agent, `session-idle-${handlerName}`);
+ const seen = collectEvents(handle);
+ await handle.send({ type: 'user', content: 'go' });
+ const handlers = host.getThreadHandlers();
+ if (!handlers) throw new Error('expected thread handlers');
+ handlers.turnStarted?.({ threadId: 'start-thread-id', turn: { id: 'turn-1' } } as never);
+ const emitDelta = (delta: string) => handlers[handlerName]?.({
+ threadId: 'start-thread-id', turnId: 'turn-1', itemId: 'output-1', delta,
+ } as never);
+
+ await vi.advanceTimersByTimeAsync(IDLE_MS - 1_000);
+ emitDelta('real progress');
+ await vi.advanceTimersByTimeAsync(1_001);
+ expect(seen.some((event) => event.type === 'error')).toBe(false);
+
+ for (const delta of [' \t\n', '\u200B\u2060', '\x00\x1b']) {
+ await vi.advanceTimersByTimeAsync(10_000);
+ emitDelta(delta);
+ }
+ await vi.advanceTimersByTimeAsync(IDLE_MS - 31_000);
+ expect(seen).toContainEqual(expect.objectContaining({
+ type: 'error', data: expect.objectContaining({ reason: 'upstream_response_idle_timeout' }),
+ }));
+ await handle.close();
+ } finally {
+ vi.useRealTimers();
+ }
+ },
+ );
+
it('graceful stop interrupt 被拒绝后重新武装同一 turn 的 idle watchdog', async () => {
vi.useFakeTimers();
try {
@@ -29246,7 +29335,49 @@ describe('CodexAgent upstream-response-idle watchdog', () => {
(ev.data as { reason?: string } | null)?.reason === 'upstream_response_idle_timeout',
),
).toBe(true);
- // 关键:本地 turn 状态必须已收干净,不等 interrupt 的结果
+ // 自动续跑可能已经排期:ACK 前必须保持 busy,避免新 turn 撞上旧 transport。
+ expect(handle.isTurnRunning?.()).toBe(true);
+ await vi.advanceTimersByTimeAsync(10_000 * 2 + 10);
+ expect(handle.isTurnRunning?.()).toBe(false);
+ await handle.close();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('普通 idle timeout 在 interrupt ACK 前保持 busy', async () => {
+ vi.useFakeTimers();
+ try {
+ const agent = new CodexAgent(createDeps());
+ let turnSeq = 0;
+ let resolveInterrupt: ((value: unknown) => void) | undefined;
+ const interruptPromise = new Promise((resolve) => {
+ resolveInterrupt = resolve;
+ });
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.TurnStart) return { turn: { id: `turn-${++turnSeq}` } };
+ if (method === Method.TurnInterrupt) return interruptPromise as never;
+ return undefined;
+ });
+ const handle = await startIdleSession(agent, 'session-idle-defer-busy');
+ const seen = collectEvents(handle);
+ await handle.send({ type: 'user', content: 'go' });
+ const handlers = host.getThreadHandlers();
+ if (!handlers) throw new Error('expected thread handlers');
+ handlers.turnStarted?.({ threadId: 'start-thread-id', turn: { id: 'turn-1' } } as never);
+
+ await vi.advanceTimersByTimeAsync(IDLE_MS + 1);
+ expect(
+ seen.some(
+ (ev) =>
+ ev.type === 'error' &&
+ (ev.data as { reason?: string } | null)?.reason === 'upstream_response_idle_timeout',
+ ),
+ ).toBe(true);
+ expect(handle.isTurnRunning?.()).toBe(true);
+
+ resolveInterrupt?.({});
+ await vi.advanceTimersByTimeAsync(0);
expect(handle.isTurnRunning?.()).toBe(false);
await handle.close();
} finally {
@@ -29255,11 +29386,10 @@ describe('CodexAgent upstream-response-idle watchdog', () => {
});
it('interrupt 始终不 ack → 作废 host(否则坏 daemon 会被下一条 send 复用)', async () => {
- // watchdog 会先合成一次本地 turn 收口好让会话立刻可发,代价是 isTurnRunning() 变
- // false —— Session 层的 recoverIfTurnStillRunning 正以它为判据,于是会认为"中断
- // 生效了、会话仍可用"而放过这个 host。若中断其实从未被确认,这个已经哑火整个阈值
- // 周期的 app-server 就留给下一条 send 复用:要么再超时,要么撞上服务端那个还在跑
- // 的 turn(review #944 第五轮 P1)。确诊不可用就自己 close,让上层重建。
+ // watchdog 先推终态 error 但延后本地收口,直到两次 interrupt ACK 都超时才 close /
+ // 退役 host。ACK 前保持 isTurnRunning()=true,自动续跑不会撞上还在 interrupt 的
+ // 旧 transport;ACK 失败后 close 让上层重建,避免把已经哑火整个阈值周期的
+ // app-server 留给下一条 send(review #944 第五轮 P1)。
vi.useFakeTimers();
try {
const agent = new CodexAgent(createDeps());
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index e6eabbda0b..29cbe71faa 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -59,6 +59,7 @@ import type {
InteractionResolver,
UsageSnapshot,
} from '../../types/events.js';
+import { isTurnWatchdogLivenessEvent } from '../../types/events.js';
import type { AuthState, Effort, PermissionMode, UserMessage } from '../../types/common.js';
import type {
AgentBuiltinCommand,
@@ -1138,7 +1139,8 @@ const CRITICAL_THREAD_RPC_TIMEOUT_MS = 60_000;
* 计时语义与 claude 侧一致: 只在"客户端把 ball 交给上游、等上游回话"期间计时。
* - 有未完成的工具类 item (命令执行 / MCP / 动态工具 / web 搜索 / 图像生成) →
* 停表: 工具执行由 daemon 侧承担, 长 build / 拉大表 / 等审批不该被误杀。
- * - 任何投递给上层的事件 (reasoning / text delta / status / item 更新) → 重置。
+ * - 投递给上层的**产品进展**事件 (reasoning / text delta / tool item) → 重置。
+ * status / account_usage / 非终态 error / turn_diff 不算(见 isTurnWatchdogLivenessEvent)。
* 触发后走 turn/interrupt (与用户手动 Stop 同路径, 不销毁 thread), 并推一条终态
* error, reason 与 claude 侧共用 'upstream_response_idle_timeout'。
*/
@@ -5371,7 +5373,7 @@ export class CodexAgent extends BaseAgent {
update: SubagentLiveCardUpdate,
lifecycle: Pick<AgentEvent, 'turnScope' | 'backgroundTurnStartedAt'> = {},
): void => {
- // 子代理帧**不得**参与主 turn 的存活判定。eventQueue.push 上装了探针:每条事件都会刷新
+ // 子代理帧**不得**参与主 turn 的存活判定。eventQueue.push 上装了探针:产品进展事件会刷新
// upstreamIdleLastEventAt + armUpstreamIdle(),并喂给 observeReconnectStallEvent ——
// 而 `agent_task_update` 正在 isReconnectRecoveryEvent 的白名单里(那对 Claude 的主线程
// Task 更新是对的,不能从白名单里删)。于是子线程一有进展就会重置主线程的静默计时、
@@ -7969,9 +7971,11 @@ export class CodexAgent extends BaseAgent {
const msSinceLast =
upstreamIdleLastEventAt > 0 ? Date.now() - upstreamIdleLastEventAt : null;
const turnId = currentTurnId ?? pendingTurnId;
+ const timeoutReason = opts?.reason ?? 'upstream_response_idle_timeout';
const deferTurnCleanupUntilInterrupt =
- opts?.reason === 'codex_reconnect_stalled' ||
- opts?.reason === CODEX_HISTORY_OVERSIZED_REASON;
+ timeoutReason === 'codex_reconnect_stalled' ||
+ timeoutReason === CODEX_HISTORY_OVERSIZED_REASON ||
+ timeoutReason === 'upstream_response_idle_timeout';
if (deferTurnCleanupUntilInterrupt && !pendingTurnId && turnId) {
// Keep Session.isTurnRunning() true until the interrupt ACK (or the
// close/retire fallback) settles. Desktop may already have received
@@ -7994,7 +7998,7 @@ export class CodexAgent extends BaseAgent {
data: {
// reason 与 claude-code 侧共用同一稳定 key(renderer i18n 映射,规则 18);
// message 仅作非 renderer 消费方(IM / orca / 日志)的英文兜底。
- reason: opts?.reason ?? 'upstream_response_idle_timeout',
+ reason: timeoutReason,
message: opts?.message ??
(`The upstream response has been silent for ${Math.round(idleMs / 1000)}s; ` +
'the turn was interrupted automatically to avoid hanging forever. ' +
@@ -8087,8 +8091,9 @@ export class CodexAgent extends BaseAgent {
}
resetUpstreamIdleForTurnEnd();
if (!turnId) return;
- // 普通 upstream-idle watchdog 仍立即收本地 turn;只有明确的重连停滞
- // 路径延后这一步,直到 interrupt ACK 成功。
+ // 普通 upstream-idle 与 reconnect-stall 一样延后本地收口:自动续跑可能已经
+ // 排期,ACK 前发新 turn 会撞上还在 interrupt 的旧 transport。compaction-storm
+ // 等其它 reason 仍立即收口。
if (!deferTurnCleanupUntilInterrupt) {
handleTurnCompleted({
threadId,
@@ -8175,7 +8180,15 @@ export class CodexAgent extends BaseAgent {
} catch (e) {
log.warn('upstream-idle watchdog close threw', { error: String(e) });
}
- if (completedDuringRelease || settleInterruptedTurn()) {
+ const completedDuringClose = completedDuringRelease || settleInterruptedTurn();
+ // closeSessionHandle 不碰 isTurnInFlight。延后收口的 idle / reconnect-stall
+ // 在 ACK 失败后必须把本地 busy 放下,否则 isTurnRunning() 恒 true,自动续跑
+ // 会被 SESSION_RUNNING 挡住,只能干等到 Session 观察到 eventQueue.end()。
+ if (currentTurnId === turnId || currentTurnId === null) {
+ isTurnInFlight = false;
+ currentTurnId = null;
+ }
+ if (completedDuringClose) {
log.info('reconnect-stall turn completed during handle close; keeping shared host', {
threadId,
turnId,
@@ -8212,11 +8225,15 @@ export class CodexAgent extends BaseAgent {
// 子代理卡帧只是"子线程有进展",不代表主 turn 还活着 —— 不参与静默计时与
// reconnect 恢复判定,否则主 turn 哑火时会被子代理的心跳一直掩盖(review)。
if (!emittingDescendantUpdate && ev.turnScope !== 'background') {
- watchdogActivityVersion += 1;
- upstreamIdleLastEventType = ev.type;
- upstreamIdleLastEventAt = Date.now();
- armUpstreamIdle();
observeReconnectStallEvent(ev);
+ // 只有产品进展刷新 idle(白名单见 isTurnWatchdogLivenessEvent);reconnect
+ // 仍要看到 status(isRunning=false 算恢复)。
+ if (isTurnWatchdogLivenessEvent(ev)) {
+ watchdogActivityVersion += 1;
+ upstreamIdleLastEventType = ev.type;
+ upstreamIdleLastEventAt = Date.now();
+ armUpstreamIdle();
+ }
}
const accepted = rawEventQueuePush(ev);
if (!accepted) releaseYieldContinuationEvent(ev);
@@ -11459,7 +11476,7 @@ export class CodexAgent extends BaseAgent {
);
}
activateRootTurn(params.turn.id);
- // turn 开始 → 球在上游,起 idle 表(后续任何事件都会重置它)。
+ // turn 开始 → 球在上游,起 idle 表。后续产品进展会重置;status / account_usage 心跳不算。
armUpstreamIdle();
// turn/start 在飞期间权限档或可写根被收紧 (turnStarted 通知可能先于 turn/start resp
// 到达) → 拿到 id 立即补中断, 与 handleTurnStartResp 互斥消费同一标记。
diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.ts
index d32ebb7b96..c5e946e326 100644
--- a/packages/maker-core/src/session.ts
+++ b/packages/maker-core/src/session.ts
@@ -45,7 +45,7 @@ import type {
RewindFilesResult,
SendOrigin,
} from './types/events.js';
-import { isTerminalAgentErrorEvent, parseToolLoopErrorDetails } from './types/events.js';
+import { isTerminalAgentErrorEvent, parseToolLoopErrorDetails, isTurnWatchdogLivenessEvent } from './types/events.js';
import type { ContextUsageData } from './types/context-usage.js';
import type { PiRuntimeCapabilityManifest } from './types/pi-runtime-capabilities.js';
import type {
@@ -76,13 +76,14 @@ export type SessionStatusListener = (status: SessionStatus) => void;
export type InteractionRequestListener = (req: InteractionRequest) => Promise<InteractionDecision>;
/**
- * turn 零事件看门狗阈值(ms)。turn 在跑、却连续这么久**一个事件都没有**,视为整条
+ * turn 零事件看门狗阈值(ms)。turn 在跑、却连续这么久**没有产品进展**,视为整条
* 链路已死,中断本轮而不是永远转圈。env `XDT_SESSION_TURN_STALL_MS` 覆盖,0 关闭。
*
* 与 agent 层 watchdog 的分工:各 agent 内部的 upstream-idle watchdog 只盯"球在上游
* 却不回话"(claude-code 30min / codex 30min),它们在**工具执行期间刻意不计时** ——
* 因此工具自己 hang(MCP 卡住、SDK↔子进程 stdio 通道 wedge)时没有任何机制兜底,
- * turn 可以永久挂着。这一层就是兜那个洞:不区分球在谁手里,只看"还有没有动静"。
+ * turn 可以永久挂着。这一层就是兜那个洞:不区分球在谁手里,只看有没有产品进展。
+ * `status` / `account_usage` 是传输层或用量心跳,不算进展(见 isTurnWatchdogLivenessEvent)。
*
* 45min 刻意大于 agent 层的 30min,保证正常情况下 agent 自己先自愈、不被抢跑;
* 只有 agent 层也失灵才轮到这里。
@@ -938,8 +939,8 @@ export class Session {
turnDispatched = true;
reservation.accepted = true;
this.unacceptedSendGeneration = null;
- // turn 真正开始跑 → 起 stall 看门狗。后续每个事件都会重置它,done / 终态
- // error 会清掉它(见 armTurnStallWatchdog)。
+ // turn 真正开始跑 → 起 stall 看门狗。后续产品进展事件会重置它;status /
+ // account_usage 心跳不算。done / 终态 error 会清掉它(见 armTurnStallWatchdog)。
this.armTurnStallWatchdog();
return { accepted: true };
} catch (e) {
@@ -2495,7 +2496,6 @@ export class Session {
return;
}
const isBackgroundEvent = event.turnScope === 'background';
- if (!isBackgroundEvent) this.lastEventAt = Date.now();
this.lastEventType = event.type;
if (event.sessionInstanceId === undefined) {
event.sessionInstanceId = this.instanceId;
@@ -2516,6 +2516,11 @@ export class Session {
const isCurrentGeneration =
resolvedGeneration === this.turnGeneration &&
observedGeneration === this.turnGeneration;
+ // leftover / 旧 generation 的产品事件不能把当前 turn 的 stall 日志时钟往前拨。
+ // 心跳与非产品事件同样不算(见 isTurnWatchdogLivenessEvent)。
+ if (!isBackgroundEvent && isCurrentGeneration && isTurnWatchdogLivenessEvent(event)) {
+ this.lastEventAt = Date.now();
+ }
// In-flight start-failure is stamped N+1 from an older wait. Snapshot and
// probe must still settle the current send even when observed stays on N.
const settleAsCurrentGeneration =
@@ -2711,7 +2716,7 @@ export class Session {
// Only an actual Host claim keeps the executor available for bounded
// silent-stop continuation; an unowned terminal can retire normally.
this.finishRetirementIfSettled();
- } else if (isCurrentGeneration) {
+ } else if (isCurrentGeneration && isTurnWatchdogLivenessEvent(event)) {
this.armTurnStallWatchdog();
}
}
@@ -2841,7 +2846,7 @@ export class Session {
if (this.hasRunningBackgroundTasks()) return;
const now = Date.now();
const msSinceLastEvent = this.lastEventAt > 0 ? now - this.lastEventAt : null;
- this.logger.warn('turn stall watchdog tripped — no events at all, interrupting turn', {
+ this.logger.warn('turn stall watchdog tripped — no product activity, interrupting turn', {
turnStallMs: this.turnStallMs,
lastEventType: this.lastEventType,
msSinceLastEvent,
@@ -2857,7 +2862,9 @@ export class Session {
'(upstream, tools and the agent subprocess were all silent); ' +
'it was interrupted automatically. You can send the next message to continue.',
isTerminal: true,
- reason: 'turn_no_event_timeout',
+ reason: this.handle.isPreparingUserTurn?.()
+ ? 'bridge_turn_no_event_timeout'
+ : 'turn_no_event_timeout',
turnStallMs: this.turnStallMs,
lastEventType: this.lastEventType,
msSinceLastEvent,
diff --git a/packages/maker-core/src/session.turn-stall.test.ts b/packages/maker-core/src/session.turn-stall.test.ts
index 038b48fe7c..7afd853884 100644
--- a/packages/maker-core/src/session.turn-stall.test.ts
+++ b/packages/maker-core/src/session.turn-stall.test.ts
@@ -3,7 +3,8 @@
*
* 兜的是各 agent 内部 upstream-idle watchdog 结构上抓不到的洞:那些 watchdog 在
* **工具执行期间刻意不计时**,所以工具自己 hang(MCP 卡住 / stdio 通道 wedge)时
- * turn 可以永久挂着。这一层不区分球在谁手里,只看"还有没有动静"。
+ * turn 可以永久挂着。这一层不区分球在谁手里,只看有没有产品进展;
+ * status / account_usage 心跳不算。
*/
import { describe, expect, it, vi } from 'vitest';
@@ -204,7 +205,7 @@ describe('Session turn stall watchdog', () => {
}
});
- it('每个事件都重置计时:持续有动静的长 turn 不被中断', async () => {
+ it('text 事件重置计时:持续有产品进展的长 turn 不被中断', async () => {
vi.useFakeTimers();
try {
const stub = createStubHandle();
@@ -227,6 +228,153 @@ describe('Session turn stall watchdog', () => {
}
});
+ it.each([
+ { type: 'status', data: { status: 'Working…', isRunning: true, inputTokens: 1 } },
+ { type: 'text', data: { text: ' \t\n' } },
+ { type: 'text', data: { text: '\u200B\u2060' } },
+ { type: 'thinking', data: { text: ' \t\n' } },
+ { type: 'thinking', data: { text: '\u200B\u2060' } },
+ ] as AgentEvent[])('无进展帧不重置计时: $type $data', async (event) => {
+ vi.useFakeTimers();
+ try {
+ const stub = createStubHandle();
+ const session = createSession(stub);
+ const seen: AgentEvent[] = [];
+ session.onEvent((ev) => seen.push(ev));
+
+ await session.send('go');
+ for (let i = 0; i < 5; i++) {
+ await vi.advanceTimersByTimeAsync(STALL_MS - 1_000);
+ stub.pushEvent({ ...event, source: 'codex' });
+ await vi.advanceTimersByTimeAsync(0);
+ }
+
+ const terminal = seen.find((ev) => ev.type === 'error');
+ expect(terminal).toBeDefined();
+ expect((terminal!.data as { reason?: string }).reason).toBe('turn_no_event_timeout');
+ expect(stub.abort).toHaveBeenCalledTimes(1);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('非终态 error 不重置计时', async () => {
+ vi.useFakeTimers();
+ try {
+ const stub = createStubHandle();
+ const session = createSession(stub);
+ const seen: AgentEvent[] = [];
+ session.onEvent((ev) => seen.push(ev));
+
+ await session.send('go');
+ await vi.advanceTimersByTimeAsync(STALL_MS - 1_000);
+ stub.pushEvent({
+ type: 'error',
+ data: { message: 'retrying', willRetry: true, isTerminal: false },
+ source: 'codex',
+ } as AgentEvent);
+ await vi.advanceTimersByTimeAsync(0);
+ await vi.advanceTimersByTimeAsync(1_001);
+
+ const stall = seen.find(
+ (ev) => ev.type === 'error' && (ev.data as { reason?: string }).reason === 'turn_no_event_timeout',
+ );
+ expect(stall).toBeDefined();
+ expect(stub.abort).toHaveBeenCalledTimes(1);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('turn_diff 不重置计时', async () => {
+ vi.useFakeTimers();
+ try {
+ const stub = createStubHandle();
+ const session = createSession(stub);
+ const seen: AgentEvent[] = [];
+ session.onEvent((ev) => seen.push(ev));
+
+ await session.send('go');
+ await vi.advanceTimersByTimeAsync(STALL_MS - 1_000);
+ stub.pushEvent({
+ type: 'turn_diff',
+ data: { turnId: 't1', diff: '', cwd: '/repo' },
+ source: 'codex',
+ } as AgentEvent);
+ await vi.advanceTimersByTimeAsync(0);
+ await vi.advanceTimersByTimeAsync(1_001);
+
+ const stall = seen.find(
+ (ev) => ev.type === 'error' && (ev.data as { reason?: string }).reason === 'turn_no_event_timeout',
+ );
+ expect(stall).toBeDefined();
+ expect(stub.abort).toHaveBeenCalledTimes(1);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('旧 generation 的迟到 text 不重置当前 turn 的计时', async () => {
+ vi.useFakeTimers();
+ try {
+ const stub = createStubHandle();
+ const session = createSession(stub);
+ const seen: AgentEvent[] = [];
+ session.onEvent((ev) => seen.push(ev));
+
+ await session.send('first');
+ stub.endTurn();
+ stub.pushEvent({ type: 'done', data: {}, source: 'claude-code' } as AgentEvent);
+ await vi.advanceTimersByTimeAsync(0);
+ await session.send('second');
+ await vi.advanceTimersByTimeAsync(STALL_MS - 1_000);
+ stub.pushEvent({
+ type: 'text',
+ data: { text: 'leftover from gen 1' },
+ sessionTurnGeneration: 1,
+ source: 'claude-code',
+ } as AgentEvent);
+ await vi.advanceTimersByTimeAsync(0);
+ await vi.advanceTimersByTimeAsync(1_001);
+
+ const stall = seen.find(
+ (ev) => ev.type === 'error' && (ev.data as { reason?: string }).reason === 'turn_no_event_timeout',
+ );
+ expect(stall).toBeDefined();
+ expect(stub.abort).toHaveBeenCalledTimes(1);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('thinking / tool_use 仍重置计时', async () => {
+ vi.useFakeTimers();
+ try {
+ const stub = createStubHandle();
+ const session = createSession(stub);
+ const seen: AgentEvent[] = [];
+ session.onEvent((ev) => seen.push(ev));
+
+ await session.send('go');
+ await vi.advanceTimersByTimeAsync(STALL_MS - 1_000);
+ stub.pushEvent({ type: 'thinking', data: { text: 'hmm' }, source: 'codex' } as AgentEvent);
+ await vi.advanceTimersByTimeAsync(0);
+ await vi.advanceTimersByTimeAsync(STALL_MS - 1_000);
+ stub.pushEvent({
+ type: 'tool_use',
+ data: { name: 'Bash', id: 'tool-1' },
+ source: 'codex',
+ } as AgentEvent);
+ await vi.advanceTimersByTimeAsync(0);
+ await vi.advanceTimersByTimeAsync(STALL_MS - 1_000);
+
+ expect(seen.some((ev) => ev.type === 'error')).toBe(false);
+ expect(stub.abort).not.toHaveBeenCalled();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('等用户回应交互期间不计时(离开电脑不该被判卡死)', async () => {
vi.useFakeTimers();
try {
diff --git a/packages/maker-core/src/types/events.test.ts b/packages/maker-core/src/types/events.test.ts
index b1f7c400ec..ed5a10913a 100644
--- a/packages/maker-core/src/types/events.test.ts
+++ b/packages/maker-core/src/types/events.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest';
import {
isTerminalAgentErrorEvent,
isTerminalTurnEvent,
+ isTurnWatchdogLivenessEvent,
type AgentEvent,
} from './events.js';
@@ -25,3 +26,51 @@ describe('AgentEvent terminal predicates', () => {
expect(isTerminalTurnEvent({ type: 'text', data: { text: 'still running' } })).toBe(false);
});
});
+
+describe('isTurnWatchdogLivenessEvent', () => {
+ it('excludes transport heartbeats and background work', () => {
+ expect(isTurnWatchdogLivenessEvent({ type: 'status', data: { isRunning: true } })).toBe(false);
+ expect(isTurnWatchdogLivenessEvent({ type: 'status', data: { isRunning: false } })).toBe(false);
+ expect(isTurnWatchdogLivenessEvent({ type: 'account_usage', data: {} })).toBe(false);
+ expect(isTurnWatchdogLivenessEvent({
+ type: 'text',
+ data: { text: 'hi' },
+ turnScope: 'background',
+ })).toBe(false);
+ });
+
+ it('counts product activity as liveness', () => {
+ expect(isTurnWatchdogLivenessEvent({ type: 'text', data: { text: 'hi' } })).toBe(true);
+ expect(isTurnWatchdogLivenessEvent({ type: 'thinking', data: { text: 'reasoning' } })).toBe(true);
+ expect(isTurnWatchdogLivenessEvent({ type: 'tool_use', data: {} })).toBe(true);
+ expect(isTurnWatchdogLivenessEvent({ type: 'tool_result', data: {} })).toBe(true);
+ expect(isTurnWatchdogLivenessEvent({ type: 'tool_result_full', data: {} })).toBe(true);
+ expect(isTurnWatchdogLivenessEvent({ type: 'agent_task_update', data: {} })).toBe(true);
+ expect(isTurnWatchdogLivenessEvent({ type: 'image', data: {} })).toBe(true);
+ expect(isTurnWatchdogLivenessEvent({ type: 'interaction_request', data: {} })).toBe(true);
+ });
+
+ it.each(['text', 'thinking'] as const)('requires substantive %s payloads', (type) => {
+ for (const text of [undefined, null, 42, '', ' \t\n', '\u200B\u200C\u200D\u2060\u00AD', '\x00\x1b', '\uFEFF']) {
+ expect(isTurnWatchdogLivenessEvent({ type, data: { text } })).toBe(false);
+ }
+ expect(isTurnWatchdogLivenessEvent({ type, data: null })).toBe(false);
+ for (const text of ['答案', ' . ', '\u200Bthinking\u200D', '👩‍💻']) {
+ expect(isTurnWatchdogLivenessEvent({ type, data: { text } })).toBe(true);
+ }
+ });
+
+ it('excludes terminals, diagnostics, and retryable errors', () => {
+ expect(isTurnWatchdogLivenessEvent({ type: 'done', data: {} })).toBe(false);
+ expect(isTurnWatchdogLivenessEvent({ type: 'error', data: { isTerminal: true } })).toBe(false);
+ expect(isTurnWatchdogLivenessEvent({
+ type: 'error',
+ data: { message: 'retry', willRetry: true, isTerminal: false },
+ })).toBe(false);
+ expect(isTurnWatchdogLivenessEvent({ type: 'turn_diff', data: {} })).toBe(false);
+ expect(isTurnWatchdogLivenessEvent({ type: 'interaction_dismissed', data: {} })).toBe(false);
+ expect(isTurnWatchdogLivenessEvent({ type: 'plan_mode_changed', data: {} })).toBe(false);
+ expect(isTurnWatchdogLivenessEvent({ type: 'compact_boundary', data: {} })).toBe(false);
+ expect(isTurnWatchdogLivenessEvent({ type: 'session_id', data: {} })).toBe(false);
+ });
+});
diff --git a/packages/maker-core/src/types/events.ts b/packages/maker-core/src/types/events.ts
index f210bdbae3..a3ef096aa2 100644
--- a/packages/maker-core/src/types/events.ts
+++ b/packages/maker-core/src/types/events.ts
@@ -229,6 +229,41 @@ export function isTerminalTurnEvent(event: AgentEvent): boolean {
return isTerminalAgentErrorEvent(event);
}
+/**
+ * 会刷新 Session 零事件看门狗 / Codex upstream-idle 计时的事件。
+ *
+ * **白名单**,不是「排除心跳」的黑名单。`status` / `account_usage` 是传输层或用量
+ * 心跳;`turn_diff` / `compact_boundary` / `session_id` / `plan_mode_changed` /
+ * `interaction_dismissed` 是系统或诊断帧;`done` / `error`(含 `willRetry: true`
+ * 的非终态 error)由终态路径自己清 watchdog,不能再当存活证据。把这些算进存活,
+ * 会让卡死的 turn 永远像在跑(典型:自动续跑被 vendor accept 之后只剩 usage-refresh
+ * status,banner 被吞、Continue 进不去)。后台事件同样不是当前 turn 的存活证据。
+ *
+ * 超时后的终态 error 交给 interrupted-turn 自动续跑(与 reconnect-stalled
+ * 同类);额度耗尽才把 Continue 交还用户。
+ */
+const TURN_WATCHDOG_LIVENESS_TYPES = new Set<AgentEventType>([
+ 'text',
+ 'thinking',
+ 'tool_use',
+ 'tool_result',
+ 'tool_result_full',
+ 'agent_task_update',
+ 'image',
+ 'interaction_request',
+]);
+
+export function isTurnWatchdogLivenessEvent(event: AgentEvent): boolean {
+ if (event.turnScope === 'background') return false;
+ if (event.type === 'text' || event.type === 'thinking') {
+ const text = isRecord(event.data) ? event.data.text : undefined;
+ // Match Desktop's visible-text semantics: whitespace, format and control
+ // characters alone are not progress. Keep the original event untouched.
+ return typeof text === 'string' && /[^\s\p{Cf}\p{Cc}]/u.test(text);
+ }
+ return TURN_WATCHDOG_LIVENESS_TYPES.has(event.type);
+}
+
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}