Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 修复重连时自动续跑被取消 (#2395)
Dash06e619716499
diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.tsindex 2d641e05f9..3fb466e78d 100644--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts@@ -453,6 +453,29 @@ describe('maker:event hot path ordering', () => {);});+ it('preserves only a waiting Codex reconnect-stall retry across its exact provider rebuild', () => {+ const wireSessionSource = extractWireSessionSource();+ const closedBlock = wireSessionSource.slice(wireSessionSource.indexOf("if (status === 'closed') {"));++ expect(source).toContain('const pendingCodexReconnectStalledRebuilds = new WeakMap<Session, number>();');+ expect(source).toContain("if (signals.reason === 'codex_reconnect_stalled') {");+ expect(source).toContain(+ 'pendingCodexReconnectStalledRebuilds.set(runtimeSession, decision.attemptToken);',+ );+ expect(source).toContain("if (closeReason !== 'unexpected') return false;");+ 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(closedBlock).toContain(+ 'const preserveAutoResumeIntent = shouldPreserveCodexReconnectStalledAutoResume(',+ );+ expect(closedBlock).toContain('if (preserveAutoResumeIntent) {');+ expect(closedBlock).toContain('autoResumeBookkeeping.teardown(session.id);');+ expect(closedBlock).toContain('preserveAutoResumeIntent,');+ });+it('clears Agent Island after mandatory closed-session cleanup', () => {const wireSessionSource = extractWireSessionSource();const closedBlock = wireSessionSource.slice(wireSessionSource.indexOf("if (status === 'closed') {"));diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.tsindex 7aa0bfc2d9..fdbcc6c2be 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@@ -7989,6 +7989,47 @@ describe('AgentInputCoordinator 中断自动续跑', () => {expect(projection.recovery?.kind).toBe('active-turn');});+ it('provider rebuild close 保留自动续跑意图,并仍由现有 retry 路径补发', async () => {+ const h = createHarness();+ const sid = 'takeover-preserved-across-provider-rebuild';+ h.setResumableTurnErrorTakeover(TAKEOVER_INFO);+ h.setHasAssistantProgressAfter(async () => true);+ await failAfterDispatch(h, sid);++ h.coordinator.onSessionClosed(sid, { preserveAutoResumeIntent: true });+ await flush();++ expect(h.coordinator.isAutoResumePending(sid)).toBe(true);+ expect(h.coordinator.getAutoResumeAttemptToken(sid)).toBe(TAKEOVER_INFO.sessionTotal);+ expect(latestProjection(h.projections)).toMatchObject({+ error: null,+ recovery: { kind: 'active-turn' },+ autoResumePending: TAKEOVER_INFO,+ });++ await expect(+ h.coordinator.autoRetryLastError(sid, TAKEOVER_INFO.sessionTotal),+ ).resolves.toBe('resumed');+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);+ expect(latestProjection(h.projections).autoResumePending).toBeUndefined();+ });++ it('plain session close 仍 supersede 自动续跑 token', async () => {+ const h = createHarness();+ const sid = 'takeover-superseded-by-plain-close';+ h.setResumableTurnErrorTakeover(TAKEOVER_INFO);+ await failAfterDispatch(h, sid);++ h.coordinator.onSessionClosed(sid);+ await flush();++ expect(h.coordinator.getAutoResumeAttemptToken(sid)).toBeNull();+ await expect(+ h.coordinator.autoRetryLastError(sid, TAKEOVER_INFO.sessionTotal),+ ).resolves.toBe('superseded');+ });+it('host 不接管时照常呈现错误(默认行为不变)', async () => {const h = createHarness();const sid = 'no-takeover-keeps-banner';diff --git a/apps/desktop/src/main/maker-ipc/__tests__/autoResumeBookkeeping.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/autoResumeBookkeeping.test.tsindex 4b83778cae..783059712e 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/autoResumeBookkeeping.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/autoResumeBookkeeping.test.ts@@ -371,9 +371,15 @@ describe('退避排期:必可撤销、必只认自己那次', () => {h.book.finalizeSuppressedError('s1', 7, { surfaceBanner: false });});+ expect(h.book.hasWaitingSchedule('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.hasWaitingSchedule('s1', 7),+ 'timer 已触发、async callback 在跑时不再属于 provider rebuild 交棒窗口',+ ).toBe(false);expect(callbackAttempt.isCurrent()).toBe(true);release();diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.tsindex daea415f77..c64e66069e 100644--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts@@ -2847,6 +2847,9 @@ export class AgentInputCoordinator {/*** @param opts.preserveInputBoundary 为 true 时跳过 abortInputBoundary。+ * @param opts.preserveAutoResumeIntent 为 true 时保留当前自动续跑接管态。+ * 仅用于 provider rebuild 在退避 timer 触发前关闭旧 Session 的交棒窗口;+ * active turn / steer / drain 等旧实例运行态仍照常清理。* 用于 rehydrate / 凭证切换 close-rebuild 窗口:abort 会取消驱动本次重建的* input signal(#1930),但**其余清理必须照常**(activeTurn / steer / queue* 状态不能残留,否则 rebuild 失败或 close 后不 rebuild 时 coordinator@@ -2854,10 +2857,12 @@ export class AgentInputCoordinator {*/onSessionClosed(sessionId: string,- opts?: { preserveInputBoundary?: boolean },+ opts?: { preserveInputBoundary?: boolean; preserveAutoResumeIntent?: boolean },): void {const state = this.getState(sessionId);- this.supersedePendingAutoResumeRecoveries(sessionId);+ if (!opts?.preserveAutoResumeIntent) {+ this.supersedePendingAutoResumeRecoveries(sessionId);+ }const releasedAbortLock = state.queueAbortPending;this.cancelScheduledDrain(state);this.clearAbortReconcileRetry(state);diff --git a/apps/desktop/src/main/maker-ipc/autoResumeBookkeeping.ts b/apps/desktop/src/main/maker-ipc/autoResumeBookkeeping.tsindex 36fc84f0ae..dd66182dc1 100644--- a/apps/desktop/src/main/maker-ipc/autoResumeBookkeeping.ts+++ b/apps/desktop/src/main/maker-ipc/autoResumeBookkeeping.ts@@ -701,6 +701,23 @@ export class AutoResumeBookkeeping {return this.schedules.has(sessionId);}+ /**+ * 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.+ */+ hasWaitingSchedule(sessionId: string, attemptToken: number): boolean {+ const scheduled = this.schedules.get(sessionId);+ return (+ scheduled?.attemptToken === attemptToken &&+ scheduled.timer !== null &&+ this.currentAttempts.get(sessionId) === attemptToken+ );+ }+// ── 会话终止收尾 ───────────────────────────────────────────────────────────/**diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 82c65fa53d..09f4cb8a23 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -23,6 +23,7 @@ import type {InteractionRequest,Maker,SendOrigin,+ Session,SessionSendOptions,SessionSendResult,UserMessage,@@ -311,6 +312,7 @@ import {ensureCodexMcpBridgeStartedForRemote,finalizeCodexAfterAuthModeChange,getMaker,+ getMakerIfReady,getPluginRegistry,prepareCodexForAuthModeChange,restartCodexAfterAuthModeChange,@@ -1018,6 +1020,14 @@ const autoResumeBookkeeping = new AutoResumeBookkeeping({log: (message, fields) => log.debug(message, fields),});+/**+ * A Codex reconnect-stall retry is scheduled against the current runtime+ * Session, but that provider may close/rebuild the 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.+ */+const pendingCodexReconnectStalledRebuilds = new WeakMap<Session, number>();+/*** 用户明确停止会话时统一撤销两类自动续跑与它们的退避簿记。*@@ -2412,6 +2422,31 @@ export async function withSendToSessionLock<T>(let agentInputCoordinatorHolder: AgentInputCoordinator | null = null;+function getWiredSessionCloseReason(session: WiredSession) {+ return getMakerIfReady()?.getSessionCloseReason(session) ?? 'unexpected';+}++/**+ * 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.+ */+function shouldPreserveCodexReconnectStalledAutoResume(+ 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);+}+/*** GoalController 已确认当前 turn 归自己所有后调用:复用输入协调器的 Stop 边界中断* vendor,同时保留用户已经排队的新指令并在终态收口后继续派发。@@ -4947,14 +4982,28 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): voidsession.id,session,);+ const closeReason = getWiredSessionCloseReason(session);+ const preserveAutoResumeIntent = shouldPreserveCodexReconnectStalledAutoResume(+ session,+ closeReason,+ );+ pendingCodexReconnectStalledRebuilds.delete(session);try {cleanupPendingInteractionsForSession(session.id, 'session_closed');- // 会话关闭同样是"终止":退避窗口有 3–20 秒,期间会话可能被独立关掉(切 agent、- // 远端断开、宿主回收)。只清 coordinator 不够 —— 排期中的定时器与悬空的重连记录- // 都还活着,前者会到点往已关闭的会话补发消息(coordinator 关闭路径保留 recovery,- // 补发会把用户关掉的会话重新拉起来),后者会把结果错绑到下一个会话实例(codex P1)。- interruptedTurnAutoResumeGuard.noteSessionReset(session.id);- autoResumeBookkeeping.teardown(session.id);+ if (preserveAutoResumeIntent) {+ log.info('preserving scheduled Codex reconnect-stall auto-resume across provider rebuild', {+ sessionId: session.id,+ attemptToken: agentInputCoordinatorHolder?.getAutoResumeAttemptToken(session.id),+ closeReason,+ });+ } else {+ // 会话关闭同样是"终止":退避窗口有 3–20 秒,期间会话可能被独立关掉(切 agent、+ // 远端断开、宿主回收)。只清 coordinator 不够 —— 排期中的定时器与悬空的重连记录+ // 都还活着,前者会到点往已关闭的会话补发消息(coordinator 关闭路径保留 recovery,+ // 补发会把用户关掉的会话重新拉起来),后者会把结果错绑到下一个会话实例(codex P1)。+ interruptedTurnAutoResumeGuard.noteSessionReset(session.id);+ autoResumeBookkeeping.teardown(session.id);+ }// rehydrate / 凭证切换 close-rebuild 窗口:同一逻辑会话进程内重建,// 协调器状态应连续。窗口内保留 input boundary(不 abort,避免取消// 驱动本次重建的 signal → #1930 cancelled-before-dispatch),但@@ -4964,6 +5013,7 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void// 标记 / wiring teardown)照常。agentInputCoordinatorHolder?.onSessionClosed(session.id, {preserveInputBoundary: rehydrateCloseSuppression.isSuppressed(session.id),+ preserveAutoResumeIntent,});// 会话关闭:兑现延迟凭证切换(直接写 route),并唤醒被它挡住的等待者。pendingCredentialSwitchHolder?.onSessionClosed(session.id);@@ -10533,6 +10583,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (schedulerRunId) {beginSchedulerAutoResume(sessionId, schedulerRunId, decision.attemptToken);}+ if (signals.reason === 'codex_reconnect_stalled') {+ const runtimeSession = getStableSessionForTurnBoundary(sessionId);+ if (runtimeSession) {+ pendingCodexReconnectStalledRebuilds.set(runtimeSession, decision.attemptToken);+ }+ }// 排期的撤旧、补落与令牌都在 AutoResumeBookkeeping.schedule 里(带单测),这里只给// 退避时长和到点要干的事。autoResumeBookkeeping.schedule(diff --git a/packages/maker-core/src/maker.shutdown.test.ts b/packages/maker-core/src/maker.shutdown.test.tsindex d8963557d9..0bafef7f7d 100644--- a/packages/maker-core/src/maker.shutdown.test.ts+++ b/packages/maker-core/src/maker.shutdown.test.ts@@ -104,11 +104,17 @@ describe('Maker.shutdown', () => {model: 'm',remoteHostId: 'host-1',});+ const closeReasons: string[] = [];+ maker.on((event) => {+ if (event.type === 'session:closed') closeReasons.push(event.reason);+ });expect(session.getStatus()).toBe('active');expect(maker.listActiveSessions()).toHaveLength(1);await maker.shutdown();expect(detach).toHaveBeenCalledTimes(1);expect(close).toHaveBeenCalledTimes(0);+ expect(closeReasons).toEqual(['requested']);+ expect(maker.getSessionCloseReason(session)).toBe('requested');});});diff --git a/packages/maker-core/src/maker.test.ts b/packages/maker-core/src/maker.test.tsindex 9997d9e89a..fdd9733815 100644--- a/packages/maker-core/src/maker.test.ts+++ b/packages/maker-core/src/maker.test.ts@@ -448,6 +448,7 @@ describe('Maker session close events', () => {await maker.closeSession('session-1', 'agent-switch');+ expect(maker.getSessionCloseReason(session)).toBe('agent-switch');expect(closed).toHaveBeenCalledWith({type: 'session:closed',sessionId: 'session-1',@@ -484,6 +485,7 @@ describe('Maker session close events', () => {maker.on((event) => {if (event.type === 'session:closed' && event.sessionId === 'session-crash') {expect(event.reason).toBe('unexpected');+ expect(maker.getSessionCloseReason(event.session)).toBe('unexpected');resolveClosed();}});diff --git a/packages/maker-core/src/maker.ts b/packages/maker-core/src/maker.tsindex 11a00d59ac..538f6160a8 100644--- a/packages/maker-core/src/maker.ts+++ b/packages/maker-core/src/maker.ts@@ -750,6 +750,17 @@ export class Maker {// 已经不在内存里就 no-op —— 没有持久化的运行态需要更新。}+ /**+ * Return the close cause for the exact runtime Session instance.+ *+ * A missing explicit cause means the vendor/Session closed itself. Keep this+ * keyed by instance rather than business session id: a replacement can be+ * created before a late close notification from the old instance arrives.+ */+ getSessionCloseReason(session: Session): MakerSessionCloseReason {+ return this.closeReasons.get(session) ?? 'unexpected';+ }+/*** Maker 进程级 shutdown — app.before-quit / 信号 / 崩溃 hook 调一次。*@@ -778,6 +789,14 @@ export class Maker {const errors: Array<{ kind: string; name: string; error: unknown }> = [];+ // shutdown() calls detach() directly instead of closeSession(), so record+ // the explicit cause before any asynchronous close callback can run. This+ // prevents app exit from looking like an unexpected provider rebuild and+ // accidentally preserving an automatic retry lease.+ for (const session of sessSnapshot) {+ if (!this.closeReasons.has(session)) this.closeReasons.set(session, 'requested');+ }+// **agent.dispose 优先排队**: 微任务 ordering 不是强保证 (dispose 内部还有 await// hostPromise 等 hop), 但先排队意味着 SIGTERM 那一步至少不会被 session-close// 的工作排在后面。真正的 safety net 是下面 Promise.allSettled 永不抛 + lifecycle