Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 修复受阻 Goal 无法继续 (#1827)
Chris Zhangfdb0f8adb92a
diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.tsindex 5674239f0f..0aacec37db 100644--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts@@ -16,6 +16,8 @@ const usageSourcePath = resolve(__dirname, '..', 'maker-ipc', 'usage.ts');const usageSource = readFileSync(usageSourcePath, 'utf8').replace(/\r\n?/g, '\n');const hookControlSourcePath = resolve(__dirname, '..', 'hook-control', 'ipc.ts');const hookControlSource = readFileSync(hookControlSourcePath, 'utf8').replace(/\r\n?/g, '\n');+const bootstrapSourcePath = resolve(__dirname, '..', 'bootstrap-electron.ts');+const bootstrapSource = readFileSync(bootstrapSourcePath, 'utf8').replace(/\r\n?/g, '\n');const goalStorageSourcePath = resolve(__dirname, '..', 'goal-host', 'storage.ts');const goalStorageSource = readFileSync(goalStorageSourcePath, 'utf8').replace(/\r\n?/g, '\n');@@ -69,6 +71,81 @@ describe('maker:event hot path ordering', () => {expect(wireSessionSource.slice(0, broadcastIndex)).not.toContain('handleAgentEvent(sessionMetaForIsland');});+ it('wakes deferred Goal resumes from the shared product-terminal idle boundary', () => {+ const wireSessionSource = extractWireSessionSource();+ const broadcastIndex = wireSessionSource.indexOf('broadcastToAllWindows(MAKER_PUSH.EVENT');+ const terminalIdleStart = wireSessionSource.indexOf(+ 'if (shouldMarkTurnTerminalIdleAfterBroadcast) {',+ broadcastIndex,+ );+ const terminalIdleEnd = wireSessionSource.indexOf(+ '} else if (shouldMarkTurnStatusIdleAfterBroadcast) {',+ terminalIdleStart,+ );+ const terminalIdleBlock = wireSessionSource.slice(terminalIdleStart, terminalIdleEnd);++ expect(terminalIdleStart).toBeGreaterThan(broadcastIndex);+ expect(terminalIdleEnd).toBeGreaterThan(terminalIdleStart);+ expectOrder(+ terminalIdleBlock,+ 'sessionTurnActivityTracker.scheduleIdleAfterTerminalBroadcast(session.id);',+ 'notifyGoalIdleAfterTurnSettled(session.id);',+ );+ expect(+ [...terminalIdleBlock.matchAll(/notifyGoalIdleAfterTurnSettled\(session\.id\);/g)],+ ).toHaveLength(1);+ });++ it('wakes deferred Goal resumes after direct-abort and authoritative-idle reconciliation', () => {+ const observerHelperStart = source.indexOf('function notifyGoalIdleAfterTurnSettled(');+ const observerHelperEnd = source.indexOf('\n}\n', observerHelperStart) + 2;+ const observerHelperSource = source.slice(observerHelperStart, observerHelperEnd);+ const reconcileStart = source.indexOf('const reconcileSessionTurnIdle =');+ const reconcileEnd = source.indexOf('\n\n const readDirectAbortTurnId =', reconcileStart);+ const reconcileSource = source.slice(reconcileStart, reconcileEnd);+ const directAbortStart = source.indexOf('ipcMain.handle(MAKER_INVOKE.ABORT_SESSION');+ const directAbortEnd = source.indexOf(+ '\n ipcMain.handle(MAKER_INVOKE.CLOSE_SESSION',+ directAbortStart,+ );+ const directAbortSource = source.slice(directAbortStart, directAbortEnd);+ const coordinatorStart = source.indexOf('const inputCoordinator:');+ const coordinatorEnd = source.indexOf(+ '\n agentInputCoordinatorHolder = inputCoordinator;',+ coordinatorStart,+ );+ const coordinatorSource = source.slice(coordinatorStart, coordinatorEnd);++ expect(observerHelperStart).toBeGreaterThanOrEqual(0);+ expect(observerHelperEnd).toBeGreaterThan(observerHelperStart);+ expect(observerHelperSource).toContain('goalIdleObserver?.(sessionId);');+ expect([...source.matchAll(/goalIdleObserver\?\.\(sessionId\);/g)]).toHaveLength(1);++ expect(reconcileStart).toBeGreaterThanOrEqual(0);+ expect(reconcileEnd).toBeGreaterThan(reconcileStart);+ expectOrder(+ reconcileSource,+ 'sessionTurnActivityTracker.setSessionInTurn(sessionId, false);',+ 'notifyGoalIdleAfterTurnSettled(sessionId);',+ );++ // ABORT_SESSION reconciles from finally, so vendor abort rejection still reaches the+ // shared idle wake-up once the exact Session/generation boundary proves idle.+ expect(directAbortStart).toBeGreaterThanOrEqual(0);+ expect(directAbortEnd).toBeGreaterThan(directAbortStart);+ expect(directAbortSource).toMatch(+ /finally \{[\s\S]*reconcileDirectAbortBoundary\(sessionId, directAbortBoundary, 'direct-abort'\);/,+ );+ expect(source).toContain('reconciledIdle = reconcileSessionTurnIdle(sessionId, source);');++ // Coordinator NO_ACTIVE_TURN / settled-abort fallback shares the same reconciliation exit.+ expect(coordinatorStart).toBeGreaterThanOrEqual(0);+ expect(coordinatorEnd).toBeGreaterThan(coordinatorStart);+ expect(coordinatorSource).toContain(+ "return reconcileSessionTurnIdle(sessionId, 'authoritative-idle');",+ );+ });+it('defers remote auth island errors until the renderer reports retry failure', () => {const wireSessionSource = extractWireSessionSource();const deferredHandler = source.match(@@ -504,6 +581,9 @@ describe('maker:event hot path ordering', () => {});it('keeps direct abort reconciliation fail-closed across owner replacement and new turns', () => {+ const closeBoundaryStart = source.indexOf('function getDirectAbortBoundaryForClosingSession(');+ const closeBoundaryEnd = source.indexOf('\n}\n', closeBoundaryStart) + 2;+ const closeBoundarySource = source.slice(closeBoundaryStart, closeBoundaryEnd);const helperStart = source.indexOf('const readDirectAbortTurnId =');const helperEnd = source.indexOf('\n\n const inputCoordinator:', helperStart);const helperSource = source.slice(helperStart, helperEnd);@@ -512,11 +592,22 @@ describe('maker:event hot path ordering', () => {expect(source).toContain('const sessionTurnBoundaryGenerationById = new Map<string, number>();');expect(source).toContain('const directAbortReconcileBoundaries = new Map<string, DirectAbortReconcileBoundary>();');+ expect(closeBoundaryStart).toBeGreaterThanOrEqual(0);+ expect(closeBoundaryEnd).toBeGreaterThan(closeBoundaryStart);+ expect(closeBoundarySource).toContain('boundary.session !== session');+ expect(closeBoundarySource).toContain(+ 'currentSessionTurnBoundaryGeneration(sessionId) !== boundary.generation',+ );expect(helperSource).toContain('wiredSessionsById.get(sessionId)?.session !== boundary.session');expect(helperSource).toContain('currentSessionTurnBoundaryGeneration(sessionId) !== boundary.generation');expect(helperSource).toContain('direct-abort-retry');expect(helperSource).toContain('cancelDirectAbortReconciliation(sessionId, boundary);');expect(wireSessionSource).toContain('if (!wasInTurn) advanceSessionTurnBoundaryGeneration(session.id);');+ expectOrder(+ closedBlock,+ 'const closedDirectAbortBoundary = getDirectAbortBoundaryForClosingSession(',+ 'cancelDirectAbortReconciliation(session.id);',+ );expect(closedBlock).toContain('cancelDirectAbortReconciliation(session.id);');expectOrder(closedBlock,@@ -524,6 +615,45 @@ describe('maker:event hot path ordering', () => {'pendingFailedTurnAssistantPersistId.delete(session.id);',);expect(closedBlock).toContain('sessionTurnBoundaryGenerationById.delete(session.id);');+ expectOrder(+ closedBlock,+ 'sessionTurnActivityTracker.deleteSession(session.id);',+ 'if (closedDirectAbortBoundary) {',+ );+ expect(closedBlock).toContain('notifyGoalIdleAfterTurnSettled(session.id);');+ expect(+ closedBlock.indexOf('notifyGoalIdleAfterTurnSettled(session.id);'),+ ).toBeGreaterThan(closedBlock.indexOf('sessionTurnBoundaryGenerationById.delete(session.id);'));+ });++ it('cancels deferred Goal resumes when non-abort session teardown supersedes them', () => {+ const wireSessionSource = extractWireSessionSource();+ const replacementStart = wireSessionSource.indexOf('if (existing) {');+ const replacementEnd = wireSessionSource.indexOf(+ '\n }\n advanceSessionTurnBoundaryGeneration',+ replacementStart,+ );+ const replacementBlock = wireSessionSource.slice(replacementStart, replacementEnd);+ const closedStart = wireSessionSource.indexOf("if (status === 'closed') {");+ const closedBlock = wireSessionSource.slice(closedStart);++ expect(source).toContain('let goalDeferredResumeCancelObserver:');+ expect(source).toContain('export function setGoalDeferredResumeCancelObserver(');+ expect(bootstrapSource).toContain('setGoalDeferredResumeCancelObserver((sid) => {');+ expect(bootstrapSource).toContain(+ 'getGoalController()?.cancelDeferredManualResume(sid, { restoreUsageResume: true });',+ );+ expect(replacementStart).toBeGreaterThanOrEqual(0);+ expect(replacementEnd).toBeGreaterThan(replacementStart);+ expectOrder(+ replacementBlock,+ 'cancelDirectAbortReconciliation(session.id);',+ 'goalDeferredResumeCancelObserver?.(session.id);',+ );+ expect(closedStart).toBeGreaterThanOrEqual(0);+ expect(closedBlock).toMatch(+ /if \(closedDirectAbortBoundary\) \{[\s\S]*notifyGoalIdleAfterTurnSettled\(session\.id\);[\s\S]*\} else \{[\s\S]*goalDeferredResumeCancelObserver\?\.\(session\.id\);/,+ );});it('keeps Codex subscription value out of real session cost totals', () => {diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 069112320e..5b78d5bfcf 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -443,6 +443,7 @@ import {isSessionTurnPendingCompletion,stopOrcaIdleWatcher,setGoalClearObserver,+ setGoalDeferredResumeCancelObserver,setGoalIdleObserver,setGoalStopObserver,setGoalAskAnswerObserver,@@ -4095,6 +4096,9 @@ const registerIpcHandlers = () => {setGoalIdleObserver((sid) => {void getGoalController()?.maybeContinueActiveGoal(sid);});+ setGoalDeferredResumeCancelObserver((sid) => {+ getGoalController()?.cancelDeferredManualResume(sid, { restoreUsageResume: true });+ });// 用户 Stop 当前 turn → 暂停 active 目标。返回 Promise 让 ABORT_SESSION 在 abort 前 await,// 确保目标先 paused + detach 监听,abort 终止事件不再触发续跑判定。setGoalStopObserver((sid) => getGoalController()?.pauseGoal(sid, 'paused: stopped by user'));diff --git a/apps/desktop/src/main/goal-host/__tests__/controller.test.ts b/apps/desktop/src/main/goal-host/__tests__/controller.test.tsindex a3075ee058..3f1bf99d0b 100644--- a/apps/desktop/src/main/goal-host/__tests__/controller.test.ts+++ b/apps/desktop/src/main/goal-host/__tests__/controller.test.ts@@ -1834,6 +1834,196 @@ describe('GoalController', () => {expect(local.session.sends).toHaveLength(sendsBeforeResume + 1);});+ it.each([+ ['normal completion', 'blocked', 'done'],+ ['terminal error', 'blocked', 'error'],+ ['abort', 'paused', 'abort'],+ ['provider close without a terminal event', 'paused', 'closed'],+ ] as const)(+ 'honors one manual Resume for a %s turn while a %s goal waits for the old turn to settle',+ async (_label, status, terminalKind) => {+ let sessionInTurn = true;+ const local = makeController({ isSessionInTurn: () => sessionInTurn });+ await local.storage.set(seededGoal({ status, lastReason: 'waiting for old turn to settle' }));+ await local.controller.pauseGoal('s1'); // Explicit Stop leaves a cancelled lifecycle boundary.+ const sendsBeforeResume = local.session.sends.length;++ await local.controller.resumeGoal('s1');+ expect((await local.storage.get('s1'))?.status).toBe(status);+ expect(local.session.sends).toHaveLength(sendsBeforeResume);++ if (terminalKind === 'done') {+ local.session.emitGoalTurn({});+ } else if (terminalKind !== 'closed') {+ local.session.emitErrorTurn({+ message: terminalKind === 'abort' ? 'AbortError: interrupted' : 'old turn failed',+ });+ }+ sessionInTurn = false;+ // Production wires reconciliation, provider close, and every product-terminal event to+ // this observer. A close/retry followed by a late terminal tail must still coalesce once.+ await Promise.all([+ local.controller.maybeContinueActiveGoal('s1'),+ local.controller.maybeContinueActiveGoal('s1'),+ local.controller.maybeContinueActiveGoal('s1'),+ ]);+ await tick();++ expect((await local.storage.get('s1'))?.status).toBe('active');+ expect(local.session.sends).toHaveLength(sendsBeforeResume + 1);+ },+ );++ it('lets a later Stop cancel a deferred manual Resume', async () => {+ let sessionInTurn = true;+ const local = makeController({ isSessionInTurn: () => sessionInTurn });+ await local.storage.set(seededGoal({ status: 'blocked', lastReason: 'waiting for input' }));+ await local.controller.pauseGoal('s1');++ await local.controller.resumeGoal('s1');+ await local.controller.pauseGoal('s1');+ sessionInTurn = false;+ await local.controller.maybeContinueActiveGoal('s1');+ await tick();++ expect((await local.storage.get('s1'))?.status).toBe('blocked');+ expect(local.session.sends).toHaveLength(0);+ });++ it('lets session teardown cancel a deferred Resume timer before a reused id goes idle', async () => {+ let sessionInTurn = true;+ const local = makeController({ isSessionInTurn: () => sessionInTurn });+ await local.storage.set(seededGoal({ status: 'paused', lastReason: 'old session settling' }));+ await local.controller.pauseGoal('s1');++ await local.controller.resumeGoal('s1');+ await local.controller.maybeContinueActiveGoal('s1'); // schedules the deferred retry timer+ local.controller.cancelDeferredManualResume('s1');+ local.controller.cancelDeferredManualResume('s1'); // repeated close/teardown is idempotent++ sessionInTurn = false;+ await local.controller.maybeContinueActiveGoal('s1'); // late idle from a reused session id+ await tick();++ expect((await local.storage.get('s1'))?.status).toBe('paused');+ expect(local.session.sends).toHaveLength(0);+ });++ it('keeps the usage reset timer until a deferred manual Resume commits', async () => {+ vi.useFakeTimers();+ vi.setSystemTime(1_000);+ let sessionInTurn = true;+ const local = makeController({+ isSessionInTurn: () => sessionInTurn,+ now: () => Date.now(),+ });+ try {+ await local.storage.set(seededGoal({+ status: 'usageLimited',+ usageResetAt: 2_000,+ lastReason: 'usage limit reached',+ }));+ await local.controller.resumeActiveGoals();++ await local.controller.resumeGoal('s1');+ expect((await local.storage.get('s1'))?.status).toBe('usageLimited');++ sessionInTurn = false;+ await local.controller.maybeContinueActiveGoal('s1');+ await vi.advanceTimersByTimeAsync(0);+ await Promise.resolve();++ expect((await local.storage.get('s1'))?.status).toBe('active');+ expect(local.session.sends).toHaveLength(1);+ expect(local.notices).toEqual([]);++ // active 已真正落库后,旧 quota-reset timer 必须被清掉,不能再启动第二轮。+ await vi.advanceTimersByTimeAsync(1_000);+ await Promise.resolve();+ expect(local.session.sends).toHaveLength(1);+ expect(local.notices).toEqual([]);+ } finally {+ local.controller.dispose();+ vi.useRealTimers();+ }+ });++ it('restores quota auto-resume when teardown cancels a deferred Resume after resetAt', async () => {+ vi.useFakeTimers();+ vi.setSystemTime(1_000);+ let sessionInTurn = true;+ const local = makeController({+ isSessionInTurn: () => sessionInTurn,+ now: () => Date.now(),+ });+ try {+ await local.storage.set(seededGoal({+ status: 'usageLimited',+ usageResetAt: 2_000,+ lastReason: 'usage limit reached',+ }));+ await local.controller.resumeActiveGoals();+ await local.controller.resumeGoal('s1');++ // resetAt 先到,但 deferred Resume 的 boundary 仍占着 turns;原 timer 会被消费。+ await vi.advanceTimersByTimeAsync(1_000);+ await Promise.resolve();+ expect((await local.storage.get('s1'))?.status).toBe('usageLimited');+ expect(local.notices).toEqual([]);++ sessionInTurn = false;+ local.controller.cancelDeferredManualResume('s1', { restoreUsageResume: true });+ local.controller.cancelDeferredManualResume('s1', { restoreUsageResume: true });+ await vi.advanceTimersByTimeAsync(0);+ await Promise.resolve();++ expect((await local.storage.get('s1'))?.status).toBe('active');+ expect(local.notices).toEqual([{ sessionId: 's1', kind: 'usage-resumed' }]);+ expect(local.session.sends).toHaveLength(1);++ // 重复 close / terminal tail 不得再建一条 reset timer 或启动第二轮。+ await vi.advanceTimersByTimeAsync(0);+ await Promise.resolve();+ expect(local.notices).toHaveLength(1);+ expect(local.session.sends).toHaveLength(1);+ } finally {+ local.controller.dispose();+ vi.useRealTimers();+ }+ });++ it('lets clearGoal cancel a deferred manual Resume without reviving the old Goal', async () => {+ let sessionInTurn = true;+ const local = makeController({ isSessionInTurn: () => sessionInTurn });+ await local.storage.set(seededGoal({ status: 'blocked', lastReason: 'waiting for input' }));+ await local.controller.pauseGoal('s1');++ await local.controller.resumeGoal('s1');+ await local.controller.clearGoal('s1');+ sessionInTurn = false;+ await local.controller.maybeContinueActiveGoal('s1');+ await tick();++ expect(await local.storage.get('s1')).toBeNull();+ expect(local.session.sends).toHaveLength(0);+ });++ it('lets dispose cancel a deferred manual Resume without starting a turn', async () => {+ let sessionInTurn = true;+ const local = makeController({ isSessionInTurn: () => sessionInTurn });+ await local.storage.set(seededGoal({ status: 'paused', lastReason: 'waiting for input' }));+ await local.controller.pauseGoal('s1');++ await local.controller.resumeGoal('s1');+ local.controller.dispose();+ sessionInTurn = false;+ await local.controller.maybeContinueActiveGoal('s1');+ await tick();++ expect((await local.storage.get('s1'))?.status).toBe('paused');+ expect(local.session.sends).toHaveLength(0);+ });+it('does not let an older Resume consume the fresh boundary from a later Stop', async () => {await startGoal(h);await h.controller.pauseGoal('s1');diff --git a/apps/desktop/src/main/goal-host/controller.ts b/apps/desktop/src/main/goal-host/controller.tsindex ab01024a99..3ba74ba40c 100644--- a/apps/desktop/src/main/goal-host/controller.ts+++ b/apps/desktop/src/main/goal-host/controller.ts@@ -377,6 +377,29 @@ export class GoalController {/** usageLimited 到点自动续跑 timer,按 sessionId。**stopSession 不清它**(它要熬到限额重置),* 只在 clearGoal / resumeGoal / dispose 取消。 */private readonly usageResumeTimers = new Map<string, ReturnType<typeof setTimeout>>();+ /**+ * 用户在旧 vendor turn 尚未完全 idle 时点下 Resume 的一次性意图。+ *+ * 此时不能立刻挂 listener / 改 active,否则旧 turn 的迟到终态会被算进新一代 Goal;+ * 也不能静默 return,否则用户必须猜何时 idle 后再点一次。由 turn idle observer 在+ * 安全边界后重试,Stop / clear / setGoal / session teardown 会显式取消。+ */+ private readonly deferredManualResumes = new Set<string>();+ private readonly deferredManualResumeTimers = new Map<+ string,+ ReturnType<typeof setTimeout>+ >();+ /**+ * deferred Resume 从等待 idle 到 active 落库之间的生命周期上下文。+ *+ * waiting set 会在真正重试时先被 claim,避免重复 observer 再排一轮;这里继续保留+ * boundary + usageResetAt,供并发 close/replacement 精确释放本次边界,并在提交前被+ * 取消时恢复 usageLimited 的自动续跑 timer。+ */+ private readonly deferredManualResumeContexts = new Map<+ string,+ { boundary: TurnAccumulator; usageResetAt: number | null }+ >();/*** 连续以"上游没容量"收尾的轮数,按 sessionId。*@@ -402,6 +425,7 @@ export class GoalController {const sessionId = input.sessionId;const objective = input.objective.trim();if (!objective) throw new GoalControllerInputError('objective must not be empty');+ this.cancelDeferredManualResume(sessionId);let entryBoundary = this.turns.get(sessionId);// 连续过载计数是 per-goal 状态:换目标(含替换既有目标的编辑路径)必须清零,// 否则上一个目标撞过载上限变 blocked 后,新目标会继承耗尽的计数,第一次容量@@ -814,6 +838,7 @@ export class GoalController {async clearGoal(sessionId: string): Promise<void> {this.clarificationApplied.delete(sessionId);this.consecutiveOverloadTurns.delete(sessionId);+ this.cancelDeferredManualResume(sessionId);this.cancelUsageResume(sessionId);// 只中断 GoalController 自己发起的 turn。目标仍挂着时,用户可能已经让一条普通// 消息进入队列;clear 必须保留它,并在旧 goal turn 终止后让 coordinator 正常@@ -860,6 +885,7 @@ export class GoalController {// 落到旧 listener,idle 兜底会把 active goal 立即续起来。先同步 detach listener、// continuation timer 与 firing 状态,再用同一 turns owner 留下 cancelled 边界,// 阻止 pause 落盘期间的 resume-on-open / 迟到事件重建旧生命周期。+ this.cancelDeferredManualResume(sessionId);this.cancelUsageResume(sessionId);const previousBoundary = this.turns.get(sessionId);this.stopSession(sessionId);@@ -921,9 +947,13 @@ export class GoalController {if (this.turns.get(sessionId) !== existingBoundary) return;if (!state ||- (state.status !== 'paused' && state.status !== 'blocked' && state.status !== 'usageLimited') ||- this.isBusy(sessionId)+ (state.status !== 'paused' && state.status !== 'blocked' && state.status !== 'usageLimited')) {+ this.cancelDeferredManualResume(sessionId);+ return;+ }+ if (this.isBusy(sessionId)) {+ this.deferManualResumeUntilIdle(sessionId, existingBoundary, state);return;}this.turns.delete(sessionId);@@ -932,12 +962,16 @@ export class GoalController {const lookupBoundary = existingBoundary ?? freshTurn();const ownsLookupBoundary = existingBoundary === undefined;if (ownsLookupBoundary) this.turns.set(sessionId, lookupBoundary);+ if (!opts?.auto) this.rebindDeferredManualResumeBoundary(sessionId, lookupBoundary);await this.awaitPendingLifecycle(lookupBoundary);if (this.turns.get(sessionId) !== lookupBoundary) return;if (state === undefined) {try {state = await this.deps.storage.get(sessionId);} catch (error) {+ if (!opts?.auto) {+ this.cancelDeferredManualResume(sessionId, { restoreUsageResume: true });+ }if (ownsLookupBoundary && this.turns.get(sessionId) === lookupBoundary) {this.turns.delete(sessionId);}@@ -949,12 +983,17 @@ export class GoalController {!state ||(state.status !== 'paused' && state.status !== 'blocked' && state.status !== 'usageLimited')) {+ if (!opts?.auto) this.cancelDeferredManualResume(sessionId);if (ownsLookupBoundary && this.turns.get(sessionId) === lookupBoundary) {this.turns.delete(sessionId);}return;}- this.cancelUsageResume(sessionId); // 早恢复 / 手动恢复 → 取消挂着的自动续 timer+ if (!opts?.auto && this.isBusy(sessionId)) {+ this.deferManualResumeUntilIdle(sessionId, lookupBoundary, state);+ return;+ }+ if (!opts?.auto) this.claimDeferredManualResume(sessionId, lookupBoundary);// 用户显式恢复 = 给一次干净的重来机会,连续过载计数清零(否则上次被过载掐停// 的目标一恢复就立刻又撞上限)。// **自动续跑(opts.auto)绝不清零**:到点自动续跑正是过载循环的一环,在这里清@@ -966,12 +1005,22 @@ export class GoalController {try {ensured = await this.deps.ensureSession(sessionId);} catch (error) {+ if (!opts?.auto) {+ this.cancelDeferredManualResume(sessionId, { restoreUsageResume: true });+ }if (this.turns.get(sessionId) === lookupBoundary) this.turns.delete(sessionId);throw error;}if (this.turns.get(sessionId) !== lookupBoundary) return;if (!ensured) {- this.turns.delete(sessionId);+ if (!opts?.auto) {+ this.cancelDeferredManualResume(sessionId, { restoreUsageResume: true });+ }+ if (this.turns.get(sessionId) === lookupBoundary) this.turns.delete(sessionId);+ return;+ }+ if (!opts?.auto && this.isBusy(sessionId)) {+ this.deferManualResumeUntilIdle(sessionId, lookupBoundary, state);return;}}@@ -988,6 +1037,9 @@ export class GoalController {}),);} catch (error) {+ if (!opts?.auto) {+ this.cancelDeferredManualResume(sessionId, { restoreUsageResume: true });+ }if (ownsLookupBoundary && this.turns.get(sessionId) === lookupBoundary) {this.turns.delete(sessionId);}@@ -995,11 +1047,18 @@ export class GoalController {}if (this.turns.get(sessionId) !== lookupBoundary) return;if (!updated) {+ if (!opts?.auto) {+ this.cancelDeferredManualResume(sessionId, { restoreUsageResume: true });+ }if (ownsLookupBoundary && this.turns.get(sessionId) === lookupBoundary) {this.turns.delete(sessionId);}return;}+ if (!opts?.auto) this.completeDeferredManualResume(sessionId);+ // usageLimited 的 reset timer 必须活到 active 写真正提交;否则 deferred Resume 在+ // close/replacement 或持久化失败前被取消时,会同时失去手动意图和唯一自动恢复机会。+ this.cancelUsageResume(sessionId);// 并发 Resume 可能已经在同一个 lookup owner 上登记了另一笔 active 写;新 active// owner 必须继承整个 barrier,后续 Stop 才能等所有较早 Resume settle 后最后写 paused。const resumedBoundary = freshTurn(@@ -1017,13 +1076,18 @@ export class GoalController {/*** idle 兜底(#9):会话转 idle 时由 main 的 turn-complete observer 调用。- * 仅当该会话有 controller 挂着的 active goal(unsubscribers.has)、未在 firing、- * 会话空闲时,走防抖续跑路径补一轮。**race-free**:scheduleContinuation 幂等+ * 有待兑现的手动 Resume 时先在防抖边界后重试;否则仅当该会话有 controller 挂着的+ * active goal(unsubscribers.has)、未在 firing、会话空闲时,走防抖续跑路径补一轮。+ * **race-free**:scheduleContinuation 幂等* (清旧 timer)、stopSession 会清 timer、fireTurn 内再从 storage 重校 status——* 与 finalizeTurn 的 scheduleContinuation 任意交错都只会有一次有效续跑。* dormant(没挂 listener)的 goal 不归这里管,由 resume-on-open 处理。*/async maybeContinueActiveGoal(sessionId: string): Promise<void> {+ if (this.deferredManualResumes.has(sessionId)) {+ this.scheduleDeferredManualResume(sessionId);+ return;+ }if (!this.unsubscribers.has(sessionId)) return;if (this.firing.has(sessionId)) return;const state = await this.deps.storage.get(sessionId);@@ -1035,6 +1099,32 @@ export class GoalController {this.scheduleContinuation(sessionId);}+ /** Session lifecycle superseded the pending Resume; cancel it without changing Goal state. */+ cancelDeferredManualResume(+ sessionId: string,+ opts?: { restoreUsageResume?: boolean },+ ): void {+ this.clearDeferredManualResumeRetry(sessionId);+ const context = this.deferredManualResumeContexts.get(sessionId);+ this.deferredManualResumeContexts.delete(sessionId);+ if (!context) return;+ // 普通 Stop / clear / setGoal 仍要继承当前 barrier;只有 session teardown 或提交失败+ // 需要把本次 deferred Resume 自己登记的 boundary 精确释放,让恢复后的 usage timer 可跑。+ if (+ opts?.restoreUsageResume &&+ this.turns.get(sessionId) === context.boundary+ ) {+ this.turns.delete(sessionId);+ }+ if (+ opts?.restoreUsageResume &&+ context.usageResetAt != null &&+ !this.usageResumeTimers.has(sessionId)+ ) {+ this.scheduleUsageResume(sessionId, context.usageResetAt);+ }+ }+/** GET_GOAL_STATUS:返回当前状态扁平 payload(无 goal 返回 null)。 */async getStatus(sessionId: string): Promise<GoalStatusPayload | null> {const state = await this.deps.storage.get(sessionId);@@ -1151,6 +1241,11 @@ export class GoalController {for (const sessionId of [...this.usageResumeTimers.keys()]) {this.cancelUsageResume(sessionId);}+ for (const sessionId of [...this.deferredManualResumeTimers.keys()]) {+ this.cancelDeferredManualResume(sessionId);+ }+ this.deferredManualResumes.clear();+ this.deferredManualResumeContexts.clear();this.turns.clear();this.consecutiveOverloadTurns.clear();}@@ -1583,6 +1678,78 @@ export class GoalController {this.timers.set(sessionId, timer);}+ private deferManualResumeUntilIdle(+ sessionId: string,+ boundary: TurnAccumulator,+ state: Pick<GoalState, 'status' | 'usageResetAt'>,+ ): void {+ if (this.turns.get(sessionId) !== boundary) return;+ let deferredBoundary = boundary;+ if (!boundary.cancelled) {+ deferredBoundary = freshTurn(+ true,+ boundary.pendingPersistence,+ boundary.pendingCompletion,+ );+ this.stopSession(sessionId);+ this.turns.set(sessionId, deferredBoundary);+ }+ this.deferredManualResumes.add(sessionId);+ this.deferredManualResumeContexts.set(sessionId, {+ boundary: deferredBoundary,+ usageResetAt: state.status === 'usageLimited' ? state.usageResetAt : null,+ });+ // busy 可能只来自一个尚未 dispatch 的旧 Goal fire;上面的 stopSession 已同步+ // 取消它,不会再有 turn terminal 触发 idle observer。此时主动排一次即可。+ if (!this.isBusy(sessionId)) this.scheduleDeferredManualResume(sessionId);+ }++ private rebindDeferredManualResumeBoundary(+ sessionId: string,+ boundary: TurnAccumulator,+ ): void {+ const context = this.deferredManualResumeContexts.get(sessionId);+ if (!context) return;+ this.deferredManualResumeContexts.set(sessionId, { ...context, boundary });+ }++ private claimDeferredManualResume(sessionId: string, boundary: TurnAccumulator): void {+ if (!this.deferredManualResumeContexts.has(sessionId)) return;+ this.clearDeferredManualResumeRetry(sessionId);+ this.rebindDeferredManualResumeBoundary(sessionId, boundary);+ }++ private completeDeferredManualResume(sessionId: string): void {+ this.clearDeferredManualResumeRetry(sessionId);+ this.deferredManualResumeContexts.delete(sessionId);+ }++ private clearDeferredManualResumeRetry(sessionId: string): void {+ this.deferredManualResumes.delete(sessionId);+ const timer = this.deferredManualResumeTimers.get(sessionId);+ if (!timer) return;+ clearTimeout(timer);+ this.deferredManualResumeTimers.delete(sessionId);+ }++ private scheduleDeferredManualResume(sessionId: string): void {+ if (!this.deferredManualResumes.has(sessionId)) return;+ const existing = this.deferredManualResumeTimers.get(sessionId);+ if (existing) clearTimeout(existing);+ const timer = setTimeout(() => {+ this.deferredManualResumeTimers.delete(sessionId);+ if (!this.deferredManualResumes.has(sessionId)) return;+ void this.resumeGoal(sessionId).catch((error) => {+ this.deps.logger.warn('[goal] deferred manual resume failed', {+ sessionId,+ error: String(error),+ });+ });+ }, this.debounceMs);+ (timer as { unref?: () => void }).unref?.();+ this.deferredManualResumeTimers.set(sessionId, timer);+ }+/*** usageLimited 到点自动续跑:resetAtMs 已知则排 timer(已过点 → delay 0 下一 tick 触发);* null = 不知道何时恢复,不排 timer,留待用户手动 resume。幂等(清旧 timer)。diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 41f805344f..19bc57d07e 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -2152,6 +2152,21 @@ function cancelDirectAbortReconciliation(directAbortReconcileBoundaries.delete(sessionId);}+/**+ * Capture only the exact direct-abort owner that a provider-driven close is+ * about to tear down. Ordinary closes and stale owner/turn generations must+ * not wake a paused Goal after their routing identity has been discarded.+ */+function getDirectAbortBoundaryForClosingSession(+ sessionId: string,+ session: WiredSession,+): DirectAbortReconcileBoundary | null {+ const boundary = directAbortReconcileBoundaries.get(sessionId);+ if (!boundary || boundary.session !== session) return null;+ if (currentSessionTurnBoundaryGeneration(sessionId) !== boundary.generation) return null;+ return boundary;+}+/*** SDK result 事件的 total_cost_usd 是 session 累计 (不是 per-turn) ——* 老 vendor/claude/usageExtractor.ts:72-74 也确认过。要算"这一 turn 花了多少"@@ -2908,9 +2923,11 @@ export function anySessionInTurn(maker?: Pick<Maker, 'listActiveSessions'> | nul* /goal 生命周期旁路(setter 注入避免 register↔goal-host 环):* - goalClearObserver:clear-context(INPUT_CLEAR_SESSION)时清除该会话目标(上下文已抹,目标失去依据)。* - goalIdleObserver:会话 turn 收尾(idle)时让 controller 兜底续跑 active 目标(#9,race-free,见 controller.maybeContinueActiveGoal)。+ * - goalDeferredResumeCancelObserver:非 abort 的 session close/replacement 取消一次性 Resume,+ * 防止同 sessionId 的后续实例被迟到 idle 误唤醒。* - goalStopObserver:用户 Stop 当前 turn(ABORT_SESSION)时把 active 目标暂停。调用 observer* 会同步 detach 监听/续跑资格;paused 持久化与 vendor abort 并行,回执等落盘收口。- * bootstrap 在启动期接上 getGoalController()?.clearGoal / maybeContinueActiveGoal / pauseGoal。+ * bootstrap 在启动期接上对应 GoalController API。*/let goalClearObserver: ((sessionId: string) => void) | null = null;export function setGoalClearObserver(observer: ((sessionId: string) => void) | null): void {@@ -2920,6 +2937,23 @@ let goalIdleObserver: ((sessionId: string) => void) | null = null;export function setGoalIdleObserver(observer: ((sessionId: string) => void) | null): void {goalIdleObserver = observer;}++let goalDeferredResumeCancelObserver: ((sessionId: string) => void) | null = null;+export function setGoalDeferredResumeCancelObserver(+ observer: ((sessionId: string) => void) | null,+): void {+ goalDeferredResumeCancelObserver = observer;+}++/**+ * Shared Goal wake-up boundary after the desktop turn tracker is idle.+ * Normal terminal events and authoritative reconciliation both pass through+ * here; the Goal controller coalesces duplicate or late terminal tails.+ */+function notifyGoalIdleAfterTurnSettled(sessionId: string): void {+ goalIdleObserver?.(sessionId);+}+let goalStopObserver: ((sessionId: string) => void | Promise<void>) | null = null;export function setGoalStopObserver(observer: ((sessionId: string) => void | Promise<void>) | null,@@ -3204,6 +3238,7 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void// A runtime replacement invalidates any delayed direct-abort callback that// still belongs to the old Session instance.cancelDirectAbortReconciliation(session.id);+ goalDeferredResumeCancelObserver?.(session.id);for (const dispose of existing.disposers) dispose();existing.session.setInteractionListener(null);}@@ -3402,8 +3437,6 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void// 还没进入 renderer 时就重新被 Chromium 节流。shouldMarkTurnTerminalIdleAfterBroadcast = true;agentInputCoordinatorHolder?.onTurnEvent(session.id, 'done');- // #9 idle 兜底:turn 收尾后让 goal controller 决定是否补一轮(无 goal/非 active 时 no-op)。- goalIdleObserver?.(session.id);} else {// silent-stop 自动续跑:translator 判定本 turn 被上游空内容消息静默收尾时在// done.data 附加 silentStop 标记(见 maker-core translator)。延迟一拍再决策,@@ -3575,6 +3608,9 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): voidhandleAgentIslandEventAfterBroadcast(session, broadcastEvent);if (shouldMarkTurnTerminalIdleAfterBroadcast) {sessionTurnActivityTracker.scheduleIdleAfterTerminalBroadcast(session.id);+ // #9 idle 兜底:正常 done、终止型 error(含 abort)统一在 tracker 已置 idle 后+ // 唤醒 Goal controller。无 goal / 非 active / 已取消的 deferred Resume 均为 no-op。+ notifyGoalIdleAfterTurnSettled(session.id);// 后台活动检测:done / 终止型 error = 逻辑 turn 结束,记录结束时刻。// 此后若该会话进程仍有 API 流量(后台子 agent),record 路径会点亮横幅。noteClaudeSessionTurnState(session.id, false);@@ -4475,6 +4511,10 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void});}if (status === 'closed') {+ const closedDirectAbortBoundary = getDirectAbortBoundaryForClosingSession(+ session.id,+ session,+ );try {cleanupPendingInteractionsForSession(session.id, 'session_closed');// 会话关闭同样是"终止":退避窗口有 3–20 秒,期间会话可能被独立关掉(切 agent、@@ -4537,6 +4577,17 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): voidsessionTurnActivityTracker.deleteSession(session.id);sessionTurnBoundaryGenerationById.delete(session.id);markSessionTurnEnded(session.id);+ if (closedDirectAbortBoundary) {+ // Provider close is authoritative that this exact abort-owned turn+ // is idle. Its reconciliation chain was cancelled by teardown, so+ // preserve the shared terminal wake-up before the intent is orphaned.+ notifyGoalIdleAfterTurnSettled(session.id);+ } else {+ // A close that did not settle this exact abort generation supersedes+ // any Resume intent keyed by the reusable session id. Cancel it and+ // its retry timer so a later Session instance cannot revive the Goal.+ goalDeferredResumeCancelObserver?.(session.id);+ }}}}),@@ -8857,6 +8908,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)});}sessionTurnActivityTracker.setSessionInTurn(sessionId, false);+ // 与正常 product-terminal 事件共享同一条 Goal idle 唤醒语义。direct abort+ // 与 coordinator 的 authoritative-idle 都从本 reconciliation 成功出口经过;+ // 迟到终态或重复尾巴由 Goal controller 的 deferred intent 防抖幂等收敛。+ notifyGoalIdleAfterTurnSettled(sessionId);try {// The marker write is best-effort and ordered behind pending message// persistence. It may retry/settle after an owner boundary is available.