Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix: address review — close Goal restore failure paths
Chris8062c072907d
diff --git a/apps/desktop/src/main/goal-host/__tests__/controller.test.ts b/apps/desktop/src/main/goal-host/__tests__/controller.test.tsindex 4f0d93f6c1..c9ad05b1ca 100644--- a/apps/desktop/src/main/goal-host/__tests__/controller.test.ts+++ b/apps/desktop/src/main/goal-host/__tests__/controller.test.ts@@ -5,6 +5,7 @@ import type { AgentEvent, SessionSendResult } from '@cindy/maker-core';import {GoalController,+ GoalSessionRestoreError,GoalUpdateSupersededError,decideNextGoalState,deriveObjectiveFromAnswers,@@ -422,33 +423,50 @@ describe('GoalController', () => {});});- it('blocks a new Goal when its dormant agent session cannot be restored', async () => {+ it('rejects a new Goal when its dormant agent session cannot be restored', async () => {const local = makeController();local.setHydratable(false);- await local.controller.setGoal({+ await expect(local.controller.setGoal({sessionId: 's1',objective: 'finish the work',agentKind: 'pi',- });+ })).rejects.toBeInstanceOf(GoalSessionRestoreError);expect(local.session.sends).toHaveLength(0);+ expect(await local.storage.get('s1')).toBeNull();+ });++ it('blocks and rejects a Goal edit when its session cannot be restored', async () => {+ const local = makeController();+ await local.storage.set(seededGoal({ status: 'active', objective: 'old objective' }));+ local.setHydratable(false);++ await expect(local.controller.setGoal({+ sessionId: 's1',+ objective: 'new objective',+ })).rejects.toBeInstanceOf(GoalSessionRestoreError);+expect(await local.storage.get('s1')).toMatchObject({status: 'blocked',- turnsUsed: 0,+ objective: 'old objective',lastReason: expect.stringContaining('unable to restore the agent session'),});+ expect(local.session.sends).toHaveLength(0);});- it('blocks and rejects a Goal edit when its session cannot be restored', async () => {- const local = makeController();+ it('blocks a Goal edit when session restoration throws and preserves the old objective', async () => {+ const local = makeController({+ ensureSession: async () => {+ throw new Error('agent bootstrap failed');+ },+ });await local.storage.set(seededGoal({ status: 'active', objective: 'old objective' }));- local.setHydratable(false);await expect(local.controller.setGoal({sessionId: 's1',objective: 'new objective',- })).rejects.toThrow('unable to restore the agent session for Goal');+ })).rejects.toBeInstanceOf(GoalSessionRestoreError);expect(await local.storage.get('s1')).toMatchObject({status: 'blocked',@@ -471,6 +489,77 @@ describe('GoalController', () => {});});+ it('keeps dispatch owners clean when the route-lock release throws', async () => {+ const releaseAgentSwitchLock = vi.fn(() => {+ throw new Error('route lock release failed');+ });+ const acquirePendingAgentSwitch = vi.fn(async () => releaseAgentSwitchLock);+ const local = makeController({ acquirePendingAgentSwitch });++ await local.controller.setGoal({ sessionId: 's1', objective: 'keep advancing' });+ expect(local.session.sends).toHaveLength(1);++ local.session.emitGoalTurn({+ toolUse: true,+ verdictJson: '```json\n{"goal_status":"continue","reason":"next"}\n```',+ tokens: 10,+ });+ await tick();++ expect(local.session.sends).toHaveLength(2);+ expect(acquirePendingAgentSwitch).toHaveBeenCalledTimes(2);+ expect(releaseAgentSwitchLock).toHaveBeenCalledTimes(2);+ });++ it('propagates a typed restore error when the route switch closes the initially ensured session', async () => {+ const session = new FakeSession('s1', 'pi');+ let ensureCalls = 0;+ const local = makeController({+ getSession: () => session,+ ensureSession: async () => {+ ensureCalls += 1;+ return ensureCalls === 1 ? session : undefined;+ },+ acquirePendingAgentSwitch: async () => () => {},+ });++ await expect(local.controller.setGoal({+ sessionId: 's1',+ objective: 'recover after the switch',+ agentKind: 'pi',+ })).rejects.toBeInstanceOf(GoalSessionRestoreError);++ expect(await local.storage.get('s1')).toMatchObject({+ status: 'blocked',+ lastReason: expect.stringContaining('unable to restore the agent session'),+ });+ expect(session.sends).toHaveLength(0);+ });++ it('propagates a typed restore error when manual Resume loses its session after route switching', async () => {+ const session = new FakeSession('s1', 'pi');+ let ensureCalls = 0;+ const local = makeController({+ getSession: () => session,+ ensureSession: async () => {+ ensureCalls += 1;+ return ensureCalls === 1 ? session : undefined;+ },+ acquirePendingAgentSwitch: async () => () => {},+ });+ await local.storage.set(seededGoal({ status: 'blocked', agentKind: 'pi' }));++ await expect(local.controller.resumeGoal('s1')).rejects.toBeInstanceOf(+ GoalSessionRestoreError,+ );++ expect(await local.storage.get('s1')).toMatchObject({+ status: 'blocked',+ lastReason: expect.stringContaining('unable to restore the agent session'),+ });+ expect(session.sends).toHaveLength(0);+ });+it('setGoal creates a new goal directly with default limits and fires the first turn', async () => {await h.controller.setGoal({ sessionId: 's1', objective: 'ship the feature' });const st = await h.storage.get('s1');@@ -2128,8 +2217,8 @@ describe('GoalController', () => {const sendsBeforeResume = h.session.sends.length;h.setHydratable(false);- await expect(h.controller.resumeGoal('s1')).rejects.toThrow(- 'unable to restore the agent session for Goal',+ await expect(h.controller.resumeGoal('s1')).rejects.toBeInstanceOf(+ GoalSessionRestoreError,);expect((await h.storage.get('s1'))?.status).toBe('blocked');expect((await h.storage.get('s1'))?.lastReason).toContain('unable to restore the agent session');@@ -2202,6 +2291,118 @@ describe('GoalController', () => {expect(local.session.sends).toHaveLength(0);});+ it('blocks and releases a dormant lifecycle boundary when agent-switch bootstrap rejects', async () => {+ let acquireCalls = 0;+ const acquirePendingAgentSwitch = vi.fn(async () => {+ acquireCalls += 1;+ if (acquireCalls === 1) throw new Error('agent switch bootstrap failed');+ return () => {};+ });+ const local = makeController({ acquirePendingAgentSwitch });+ await local.storage.set(seededGoal({ status: 'active', objective: 'recover safely' }));++ await local.controller.resumeOnOpen('s1');++ expect(await local.storage.get('s1')).toMatchObject({+ status: 'blocked',+ lastReason: expect.stringContaining('unable to restore the agent session'),+ });+ expect(local.session.sends).toHaveLength(0);++ await local.controller.resumeGoal('s1');++ expect((await local.storage.get('s1'))?.status).toBe('active');+ expect(local.session.sends).toHaveLength(1);+ expect(acquirePendingAgentSwitch).toHaveBeenCalledTimes(2);+ });++ it('keeps a fail-closed owner when persisting a restore failure is unavailable', async () => {+ const acquirePendingAgentSwitch = vi.fn(async () => {+ throw new Error('agent switch bootstrap failed');+ });+ const local = makeController({ acquirePendingAgentSwitch });+ await local.storage.set(seededGoal({ status: 'active', objective: 'do not replay' }));+ const update = vi.spyOn(local.storage, 'update').mockRejectedValueOnce(+ new Error('goal storage unavailable'),+ );++ await expect(local.controller.resumeOnOpen('s1')).rejects.toBeInstanceOf(+ GoalSessionRestoreError,+ );+ await local.controller.resumeOnOpen('s1');++ expect(await local.storage.get('s1')).toMatchObject({+ status: 'blocked',+ objective: 'do not replay',+ lastReason: expect.stringContaining('unable to restore the agent session'),+ });+ expect(update).toHaveBeenCalledTimes(2);+ expect(acquirePendingAgentSwitch).toHaveBeenCalledTimes(1);+ expect(local.session.sends).toHaveLength(0);+ });++ it('propagates an unpersisted second restore failure through resume-on-open', async () => {+ const session = new FakeSession('s1', 'pi');+ let ensureCalls = 0;+ const local = makeController({+ getSession: () => session,+ ensureSession: async () => {+ ensureCalls += 1;+ return ensureCalls === 1 ? session : undefined;+ },+ acquirePendingAgentSwitch: async () => () => {},+ });+ await local.storage.set(seededGoal({ status: 'active', objective: 'recover once' }));+ const update = vi.spyOn(local.storage, 'update').mockRejectedValueOnce(+ new Error('goal storage unavailable'),+ );++ await expect(local.controller.resumeOnOpen('s1')).rejects.toBeInstanceOf(+ GoalSessionRestoreError,+ );+ expect(await local.storage.get('s1')).toMatchObject({ status: 'active' });++ await local.controller.resumeOnOpen('s1');++ expect(await local.storage.get('s1')).toMatchObject({+ status: 'blocked',+ lastReason: expect.stringContaining('unable to restore the agent session'),+ });+ expect(update).toHaveBeenCalledTimes(2);+ expect(ensureCalls).toBe(2);+ expect(session.sends).toHaveLength(0);+ });++ it('does not let a late resume-on-open bootstrap failure overwrite a newer Stop boundary', async () => {+ let markBootstrapStarted!: () => void;+ const bootstrapStarted = new Promise<void>((resolve) => {+ markBootstrapStarted = resolve;+ });+ let rejectBootstrap!: (error: Error) => void;+ const bootstrap = new Promise<() => void>((_resolve, reject) => {+ rejectBootstrap = reject;+ });+ const local = makeController({+ acquirePendingAgentSwitch: () => {+ markBootstrapStarted();+ return bootstrap;+ },+ });+ await local.storage.set(seededGoal({ status: 'active', objective: 'stay paused' }));++ const resuming = local.controller.resumeOnOpen('s1');+ await bootstrapStarted;+ await local.controller.pauseGoal('s1');+ rejectBootstrap(new Error('late bootstrap failure'));+ await resuming;++ expect(await local.storage.get('s1')).toMatchObject({+ status: 'paused',+ lastReason: 'paused by user',+ });+ expect(local.session.sends).toHaveLength(0);+ });+it('does not let a stale startup active snapshot overwrite a concurrent Stop', async () => {const active = seededGoal({ status: 'active', objective: 'stay stopped' });await h.storage.set(active);diff --git a/apps/desktop/src/main/goal-host/controller.ts b/apps/desktop/src/main/goal-host/controller.tsindex 1477d0373a..6b356460b6 100644--- a/apps/desktop/src/main/goal-host/controller.ts+++ b/apps/desktop/src/main/goal-host/controller.ts@@ -46,6 +46,19 @@ export class GoalControllerInputError extends Error {readonly code = 'INVALID_PARAMS';}+/** Goal 已保守收敛,但本次入口无法恢复其底层 Agent Session。 */+export class GoalSessionRestoreError extends Error {+ readonly code = 'PRECONDITION_FAILED';++ constructor(cause?: unknown) {+ super(+ 'unable to restore the agent session for Goal',+ cause === undefined ? undefined : { cause },+ );+ this.name = 'GoalSessionRestoreError';+ }+}+/** Goal 仍存在,但本次编辑已被更新的生命周期或状态覆盖。 */export class GoalUpdateSupersededError extends Error {readonly code = 'PRECONDITION_FAILED';@@ -361,6 +374,11 @@ export class GoalController {*/private readonly listenerSessions = new Map<string, SessionLike>();private readonly turns = new Map<string, TurnAccumulator>();+ /** blocked 落盘失败时保留同一 fail-closed owner,GET_STATUS 可重试而不是回报旧 active。 */+ private readonly unpersistedDispatchFailures = new Map<+ string,+ { boundary: TurnAccumulator; lastReason: string }+ >();/** 正在派发的 fire 及其 owner;旧代 finally 只能清理自己,不能删掉 Resume 新代。 */private readonly firing = new Map<string, object>();/** 尚在 Session.send 派发边界内的 Goal fire;Stop 必须能取消 dispatch 前的异步 gate。 */@@ -450,19 +468,38 @@ export class GoalController {const ts = this.now();if (existing) {- const session = await this.deps.ensureSession(sessionId);+ const failureBoundary = entryBoundary ?? freshTurn();+ if (!entryBoundary) {+ entryBoundary = failureBoundary;+ this.turns.set(sessionId, failureBoundary);+ }+ let session: SessionLike | undefined;+ try {+ session = await this.deps.ensureSession(sessionId);+ } catch (error) {+ if (this.turns.get(sessionId) !== failureBoundary) return null;+ this.deps.logger.warn('[goal] setGoal edit: session restore failed', {+ sessionId,+ error: String(error),+ });+ await this.blockDispatchFailure(+ sessionId,+ failureBoundary,+ 'turn dispatch failed: unable to restore the agent session',+ () => this.turns.get(sessionId) === failureBoundary,+ );+ throw new GoalSessionRestoreError(error);+ }if (this.turns.get(sessionId) !== entryBoundary) return null;if (!session) {this.deps.logger.warn('[goal] setGoal edit: no live session', { sessionId });- const failureBoundary = entryBoundary ?? freshTurn();- if (!entryBoundary) this.turns.set(sessionId, failureBoundary);await this.blockDispatchFailure(sessionId,failureBoundary,'turn dispatch failed: unable to restore the agent session',() => this.turns.get(sessionId) === failureBoundary,);- throw new Error('unable to restore the agent session for Goal');+ throw new GoalSessionRestoreError();}const sessionWasBusy = this.isBusy(sessionId);if (sessionWasBusy) {@@ -519,7 +556,7 @@ export class GoalController {this.attachListener(sessionId);this.emit(updated);if (this.turns.get(sessionId) === activeBoundary) {- await this.fireTurn(sessionId);+ await this.fireTurn(sessionId, { throwOnRestoreFailure: true });}return (await this.deps.storage.get(sessionId)) ?? updated;} catch (error) {@@ -541,8 +578,14 @@ export class GoalController {// 先活化(resume)会话,再据活化后的会话定 agentKind:dormant(重启后尚未活化)会话此刻// getSession 为空,若直接 fallback 'claude-code' 会把 Codex 目标错存成 claude-code,后续// getAccountLimit 读错账号配额快照 → Codex 限流目标的 reset/auto-resume 错位(reviewer #354)。- const ensured = await this.deps.ensureSession(sessionId);+ let ensured: SessionLike | undefined;+ try {+ ensured = await this.deps.ensureSession(sessionId);+ } catch (error) {+ throw new GoalSessionRestoreError(error);+ }if (this.turns.get(sessionId) !== createBoundary) return null;+ if (!ensured) throw new GoalSessionRestoreError();await this.awaitPendingLifecycle(createBoundary);if (this.turns.get(sessionId) !== createBoundary) return null;const agentKind = input.agentKind ?? ensured?.agentKind ?? this.deps.getSession(sessionId)?.agentKind ?? 'claude-code';@@ -576,7 +619,7 @@ export class GoalController {this.attachListener(sessionId);this.emit(state);if (this.turns.get(sessionId) === activeBoundary) {- await this.fireTurn(sessionId);+ await this.fireTurn(sessionId, { throwOnRestoreFailure: true });}return (await this.deps.storage.get(sessionId)) ?? state;} catch (error) {@@ -1017,7 +1060,7 @@ export class GoalController {this.cancelDeferredManualResume(sessionId, { restoreUsageResume: true });}if (this.turns.get(sessionId) === lookupBoundary) this.turns.delete(sessionId);- throw error;+ throw new GoalSessionRestoreError(error);}if (this.turns.get(sessionId) !== lookupBoundary) return;if (!ensured) {@@ -1033,7 +1076,7 @@ export class GoalController {'turn dispatch failed: unable to restore the agent session',() => this.turns.get(sessionId) === lookupBoundary,);- throw new Error('unable to restore the agent session for Goal');+ throw new GoalSessionRestoreError();}if (!opts?.auto && this.isBusy(sessionId)) {this.deferManualResumeUntilIdle(sessionId, lookupBoundary, state);@@ -1086,7 +1129,7 @@ export class GoalController {this.attachListener(sessionId);this.emit(updated);if (!this.isBusy(sessionId)) {- await this.fireTurn(sessionId);+ await this.fireTurn(sessionId, { throwOnRestoreFailure: !opts?.auto });}}@@ -1156,6 +1199,17 @@ export class GoalController {* 这样重开会话能让 active 目标自己跑下去,而不是卡死等用户重发 /goal。*/async resumeOnOpen(sessionId: string): Promise<void> {+ const pendingFailure = this.unpersistedDispatchFailures.get(sessionId);+ if (pendingFailure) {+ const persisted = await this.blockDispatchFailure(+ sessionId,+ pendingFailure.boundary,+ pendingFailure.lastReason,+ () => this.turns.get(sessionId) === pendingFailure.boundary,+ );+ if (!persisted) throw new GoalSessionRestoreError();+ return;+ }if (this.unsubscribers.has(sessionId) || this.turns.has(sessionId)) return; // 已在管或正在 Stopconst lifecycleBoundary = freshTurn();this.turns.set(sessionId, lifecycleBoundary);@@ -1176,6 +1230,8 @@ export class GoalController {// 发给 fireTurn 开始时捕获的旧 session。let releaseAgentSwitchLock = (): void => {};let session: SessionLike | undefined;+ let restoreFailed = false;+ let restoreError: unknown;try {releaseAgentSwitchLock =(await this.deps.acquirePendingAgentSwitch?.(sessionId)) ?? (() => {});@@ -1187,22 +1243,45 @@ export class GoalController {// fireTurn 也能凭 unsubscribers 标记把 listener 迁移到重新创建的新 session。this.attachListener(sessionId);}+ } catch (error) {+ restoreFailed = true;+ restoreError = error;} finally {- releaseAgentSwitchLock();+ try {+ releaseAgentSwitchLock();+ } catch (error) {+ restoreFailed = true;+ restoreError ??= error;+ }+ }+ if (restoreFailed) {+ this.deps.logger.warn('[goal] resumeOnOpen: session restore failed', {+ sessionId,+ error: String(restoreError),+ });+ const persisted = await this.blockDispatchFailure(+ sessionId,+ lifecycleBoundary,+ 'turn dispatch failed: unable to restore the agent session',+ () => this.turns.get(sessionId) === lifecycleBoundary,+ );+ if (!persisted) throw new GoalSessionRestoreError(restoreError);+ return;}if (!session) {- await this.blockDispatchFailure(+ const persisted = await this.blockDispatchFailure(sessionId,lifecycleBoundary,'turn dispatch failed: unable to restore the agent session',() => this.turns.get(sessionId) === lifecycleBoundary,);+ if (!persisted) throw new GoalSessionRestoreError();return;}if (this.turns.get(sessionId) !== lifecycleBoundary) return;this.emit(state);if (!this.isBusy(sessionId)) {- await this.fireTurn(sessionId);+ await this.fireTurn(sessionId, { throwOnUnpersistedRestoreFailure: true });}}@@ -1234,7 +1313,12 @@ export class GoalController {this.emit(state);resumed += 1;if (!this.isBusy(state.sessionId)) {- void this.fireTurn(state.sessionId);+ void this.fireTurn(state.sessionId).catch((error) => {+ this.deps.logger.warn('[goal] detached startup fire failed', {+ sessionId: state.sessionId,+ error: String(error),+ });+ });}}if (active.length > 0) {@@ -1268,6 +1352,7 @@ export class GoalController {}this.deferredManualResumes.clear();this.deferredManualResumeContexts.clear();+ this.unpersistedDispatchFailures.clear();this.turns.clear();this.consecutiveOverloadTurns.clear();}@@ -1294,6 +1379,7 @@ export class GoalController {}this.firing.delete(sessionId);this.goalTurnsInFlight.delete(sessionId);+ this.unpersistedDispatchFailures.delete(sessionId);this.turns.delete(sessionId);}@@ -1696,7 +1782,8 @@ export class GoalController {boundary: TurnAccumulator,lastReason: string,isCurrent: () => boolean,- ): Promise<void> {+ ): Promise<boolean> {+ if (!isCurrent()) return true;try {const blocked = await this.trackPersistence(boundary,@@ -1706,15 +1793,30 @@ export class GoalController {updatedAt: this.now(),}),);- if (!isCurrent()) return;+ if (!isCurrent()) return true;if (blocked) this.emit(blocked);} catch (persistError) {this.deps.logger.error('[goal] failed to persist dispatch failure', {sessionId,error: String(persistError),});+ if (isCurrent()) {+ const failClosedBoundary = freshTurn(+ true,+ boundary.pendingPersistence,+ boundary.pendingCompletion,+ );+ this.stopSession(sessionId);+ this.turns.set(sessionId, failClosedBoundary);+ this.unpersistedDispatchFailures.set(sessionId, {+ boundary: failClosedBoundary,+ lastReason,+ });+ }+ return false;}if (isCurrent()) this.stopSession(sessionId);+ return true;}private scheduleContinuation(sessionId: string): void {@@ -1722,7 +1824,12 @@ export class GoalController {if (existing) clearTimeout(existing);const timer = setTimeout(() => {this.timers.delete(sessionId);- void this.fireTurn(sessionId);+ void this.fireTurn(sessionId).catch((error) => {+ this.deps.logger.warn('[goal] detached continuation fire failed', {+ sessionId,+ error: String(error),+ });+ });}, this.debounceMs);// Node 环境;不 block 进程退出。(timer as { unref?: () => void }).unref?.();@@ -1812,7 +1919,12 @@ export class GoalController {// 立刻触发(限额窗口正常是 5h / weekly,远小于上限;clamp 只是防御异常 resetAt)。const delay = Math.min(Math.max(0, resetAtMs - this.now()), 2_147_483_647);const timer = setTimeout(() => {- void this.autoResumeFromUsageLimit(sessionId);+ void this.autoResumeFromUsageLimit(sessionId).catch((error) => {+ this.deps.logger.warn('[goal] detached usage resume failed', {+ sessionId,+ error: String(error),+ });+ });}, delay);(timer as { unref?: () => void }).unref?.();this.usageResumeTimers.set(sessionId, timer);@@ -1904,7 +2016,13 @@ export class GoalController {}}- private async fireTurn(sessionId: string): Promise<void> {+ private async fireTurn(+ sessionId: string,+ opts?: {+ throwOnRestoreFailure?: boolean;+ throwOnUnpersistedRestoreFailure?: boolean;+ },+ ): Promise<void> {const lifecycleBoundary = this.turns.get(sessionId);if (!lifecycleBoundary || lifecycleBoundary.cancelled) return;const lifecycleGeneration = lifecycleBoundary.generation;@@ -1967,6 +2085,7 @@ export class GoalController {this.turns.get(sessionId) === dispatchBoundary &&dispatchBoundary.generation === dispatchGeneration;let releaseAgentSwitchLock = (): void => {};+ let restoringSession = true;let baselineStarted = false;try {// fireTurn 每次都可能是登记 deferred intent 后的第一条直发消息。锁必须覆盖@@ -1977,19 +2096,8 @@ export class GoalController {if (!isCurrentLifecycle()) return;const session = await this.deps.ensureSession(sessionId);if (!isCurrentLifecycle()) return;- if (!session) {- this.deps.logger.warn('[goal] no live session to fire (resume failed)', {- sessionId,- kind,- });- await this.blockDispatchFailure(- sessionId,- lifecycleBoundary,- 'turn dispatch failed: unable to restore the agent session',- isCurrentLifecycle,- );- return;- }+ if (!session) throw new GoalSessionRestoreError();+ restoringSession = false;// deferred switch 可能刚把 live session 换成目标引擎的新对象;本会话若有 goal// listener,必须迁到新 session,否则这轮 turn 的 done/error 事件进不了 finalizeTurn,// 目标卡死在 active(reviewer P1)。attachListener 按 session 身份判等,未换则 no-op;@@ -2091,14 +2199,30 @@ export class GoalController {}const errorMessage = e instanceof Error ? e.message : String(e);- await this.blockDispatchFailure(+ const persisted = await this.blockDispatchFailure(sessionId,failureBoundary,`turn dispatch failed: ${errorMessage}`,isCurrentFailure,);+ if (+ restoringSession &&+ (opts?.throwOnRestoreFailure ||+ (!persisted && opts?.throwOnUnpersistedRestoreFailure))+ ) {+ throw e instanceof GoalSessionRestoreError+ ? e+ : new GoalSessionRestoreError(e);+ }} finally {- releaseAgentSwitchLock();+ try {+ releaseAgentSwitchLock();+ } catch (error) {+ this.deps.logger.warn('[goal] failed to release agent switch lock', {+ sessionId,+ error: String(error),+ });+ }if (this.goalDispatchAbortControllers.get(sessionId)?.owner === firingOwner) {this.goalDispatchAbortControllers.delete(sessionId);}diff --git a/apps/desktop/src/main/maker-ipc/__tests__/goalHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/goalHandlers.test.tsindex 1a66908270..4fbc05da3a 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/goalHandlers.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/goalHandlers.test.ts@@ -2,6 +2,11 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => ({handlers: new Map<string, (...args: unknown[]) => unknown>(),+ controllerAvailable: true,+ setGoal: vi.fn(),+ getStatus: vi.fn(),+ resumeOnOpen: vi.fn(),+ resumeGoal: vi.fn(),updateGoal: vi.fn(),}));@@ -15,7 +20,15 @@ vi.mock('electron', () => ({}));vi.mock('../../goal-host/index.js', () => ({- getGoalController: () => ({ updateGoal: mocks.updateGoal }),+ getGoalController: () => mocks.controllerAvailable+ ? {+ setGoal: mocks.setGoal,+ getStatus: mocks.getStatus,+ resumeOnOpen: mocks.resumeOnOpen,+ resumeGoal: mocks.resumeGoal,+ updateGoal: mocks.updateGoal,+ }+ : null,}));vi.mock('../../logger.js', () => ({@@ -27,23 +40,127 @@ vi.mock('../../device-link/broadcast-tap.js', () => ({tapWindowBroadcast: vi.fn(),}));-import { GoalUpdateSupersededError } from '../../goal-host/controller.js';+import {+ GoalSessionRestoreError,+ GoalUpdateSupersededError,+} from '../../goal-host/controller.js';import { MAKER_INVOKE } from '../channels.js';import { registerGoalHandlers } from '../goal.js';-function updateHandler(): (...args: unknown[]) => unknown {- const handler = mocks.handlers.get(MAKER_INVOKE.GOAL_UPDATE);- if (!handler) throw new Error('goal update handler was not registered');+function handlerFor(channel: string): (...args: unknown[]) => unknown {+ const handler = mocks.handlers.get(channel);+ if (!handler) throw new Error(`goal handler was not registered: ${channel}`);return handler;}+function updateHandler(): (...args: unknown[]) => unknown {+ return handlerFor(MAKER_INVOKE.GOAL_UPDATE);+}+describe('goal update IPC errors', () => {beforeEach(() => {vi.clearAllMocks();mocks.handlers.clear();+ mocks.controllerAvailable = true;registerGoalHandlers();});+ it('returns INTERNAL when the Goal controller is not ready', async () => {+ mocks.controllerAvailable = false;++ const result = handlerFor(MAKER_INVOKE.GOAL_GET_STATUS)({}, 's1');++ await expect(result).rejects.toMatchObject({+ code: 'INTERNAL',+ message: expect.stringContaining('goal controller not started'),+ });+ });++ it('maps the initial Goal status read failure to INTERNAL without leaking storage details', async () => {+ mocks.getStatus.mockRejectedValueOnce(new Error('sqlite path /private/user-data failed'));++ const result = handlerFor(MAKER_INVOKE.GOAL_GET_STATUS)({}, 's1');++ await expect(result).rejects.toMatchObject({+ code: 'INTERNAL',+ message: expect.stringContaining('failed to read goal status'),+ });+ });++ it('maps the post-recovery Goal status read failure to INTERNAL', async () => {+ mocks.getStatus+ .mockResolvedValueOnce({ sessionId: 's1', status: 'active' })+ .mockRejectedValueOnce(new Error('second read failed'));+ mocks.resumeOnOpen.mockResolvedValueOnce(undefined);++ const result = handlerFor(MAKER_INVOKE.GOAL_GET_STATUS)({}, 's1');++ await expect(result).rejects.toMatchObject({+ code: 'INTERNAL',+ message: expect.stringContaining('failed to read goal status'),+ });+ expect(mocks.resumeOnOpen).toHaveBeenCalledWith('s1');+ });++ it('returns the post-recovery blocked state instead of a stale active snapshot', async () => {+ const active = { sessionId: 's1', status: 'active' };+ const blocked = {+ sessionId: 's1',+ status: 'blocked',+ lastReason: 'turn dispatch failed: unable to restore the agent session',+ };+ mocks.getStatus+ .mockResolvedValueOnce(active)+ .mockResolvedValueOnce(blocked);+ mocks.resumeOnOpen.mockResolvedValueOnce(undefined);++ const result = await handlerFor(MAKER_INVOKE.GOAL_GET_STATUS)({}, 's1');++ expect(result).toEqual(blocked);+ expect(mocks.resumeOnOpen).toHaveBeenCalledWith('s1');+ expect(mocks.getStatus).toHaveBeenCalledTimes(2);+ });++ it('returns a structured error when dormant recovery cannot persist blocked state', async () => {+ mocks.getStatus.mockResolvedValueOnce({ sessionId: 's1', status: 'active' });+ mocks.resumeOnOpen.mockRejectedValueOnce(+ new GoalSessionRestoreError(new Error('goal storage unavailable')),+ );++ const result = handlerFor(MAKER_INVOKE.GOAL_GET_STATUS)({}, 's1');++ await expect(result).rejects.toMatchObject({+ code: 'PRECONDITION_FAILED',+ message: expect.stringContaining('unable to restore the agent session'),+ });+ expect(mocks.getStatus).toHaveBeenCalledTimes(1);+ });++ it('maps GOAL_SET session restore failures to PRECONDITION_FAILED', async () => {+ mocks.setGoal.mockRejectedValueOnce(new GoalSessionRestoreError());++ const result = handlerFor(MAKER_INVOKE.GOAL_SET)(+ {},+ { sessionId: 's1', objective: 'recover the goal' },+ );++ await expect(result).rejects.toMatchObject({+ code: 'PRECONDITION_FAILED',+ message: expect.stringContaining('unable to restore the agent session'),+ });+ });++ it('maps GOAL_RESUME session restore failures to PRECONDITION_FAILED', async () => {+ mocks.resumeGoal.mockRejectedValueOnce(new GoalSessionRestoreError());++ const result = handlerFor(MAKER_INVOKE.GOAL_RESUME)({}, 's1');++ await expect(result).rejects.toMatchObject({+ code: 'PRECONDITION_FAILED',+ message: expect.stringContaining('unable to restore the agent session'),+ });+ });+it('maps a superseded lifecycle update to PRECONDITION_FAILED', async () => {mocks.updateGoal.mockRejectedValueOnce(new GoalUpdateSupersededError());diff --git a/apps/desktop/src/main/maker-ipc/goal.ts b/apps/desktop/src/main/maker-ipc/goal.tsindex 7d1a3f3c52..1e4b6e5fb8 100644--- a/apps/desktop/src/main/maker-ipc/goal.ts+++ b/apps/desktop/src/main/maker-ipc/goal.ts@@ -18,6 +18,7 @@ import { createLogger } from '../logger.js';import { throwIpcError, requireString, requireObject } from '../utils/ipcValidate.js';import {GoalControllerInputError,+ GoalSessionRestoreError,GoalUpdateSupersededError,} from '../goal-host/controller.js';import { getGoalController } from '../goal-host/index.js';@@ -29,6 +30,30 @@ const log = createLogger('maker-ipc:goal');type GoalLimitPatchKey = 'maxTurns' | 'budgetTokens' | 'noProgressLimit';+function throwGoalControllerIpcError(error: unknown): never {+ if (error instanceof GoalControllerInputError) {+ throwIpcError('INVALID_PARAMS', error.message);+ }+ if (+ error instanceof GoalSessionRestoreError ||+ error instanceof GoalUpdateSupersededError+ ) {+ throwIpcError('PRECONDITION_FAILED', error.message);+ }+ throw error;+}++async function readGoalStatusForIpc(+ controller: NonNullable<ReturnType<typeof getGoalController>>,+ sessionId: string,+) {+ try {+ return await controller.getStatus(sessionId);+ } catch {+ throwIpcError('INTERNAL', 'failed to read goal status');+ }+}+function readOptionalLimit(value: unknown, name: GoalLimitPatchKey, patch: GoalUpdatePatch): void {if (value === undefined) return;if (value === null || typeof value === 'number') {@@ -82,10 +107,7 @@ export function registerGoalHandlers(): void {try {await controller.setGoal({ sessionId, objective, ...(limits ? { limits } : {}) });} catch (err) {- if (err instanceof GoalControllerInputError) {- throwIpcError('INVALID_PARAMS', err.message);- }- throw err;+ throwGoalControllerIpcError(err);}return { ok: true };});@@ -101,12 +123,18 @@ export function registerGoalHandlers(): void {ipcMain.handle(MAKER_INVOKE.GOAL_GET_STATUS, async (_e, sessionId: unknown) => {const id = requireString(sessionId, 'sessionId');const controller = getGoalController();- const status = (await controller?.getStatus(id)) ?? null;- // resume-on-open:打开会话时若有 dormant 的 active 目标(重启后未活化、无 listener),- // 顺带把它续上(controller.resumeOnOpen 内部自守卫:已在管 / 非 active / 活化失败均 no-op)。- // fire-and-forget,不阻塞 status 返回;只针对当前打开的这个会话,不会批量 spawn。+ if (!controller) throwIpcError('INTERNAL', 'goal controller not started');+ let status = await readGoalStatusForIpc(controller, id);+ // Dormant recovery may synchronously converge an apparently active Goal to+ // blocked. Wait and re-read so this invoke response cannot overwrite the+ // newer status push with its stale pre-recovery active snapshot.if (status?.status === 'active') {- void controller?.resumeOnOpen(id).catch(() => {});+ try {+ await controller.resumeOnOpen(id);+ } catch (error) {+ throwGoalControllerIpcError(error);+ }+ status = await readGoalStatusForIpc(controller, id);}return status;});@@ -122,7 +150,11 @@ export function registerGoalHandlers(): void {// 保留计数继续;终态/active 是 no-op。ipcMain.handle(MAKER_INVOKE.GOAL_RESUME, async (_e, sessionId: unknown) => {const id = requireString(sessionId, 'sessionId');- await getGoalController()?.resumeGoal(id);+ try {+ await getGoalController()?.resumeGoal(id);+ } catch (error) {+ throwGoalControllerIpcError(error);+ }return { ok: true };});@@ -144,13 +176,7 @@ export function registerGoalHandlers(): void {if (!updated) throwIpcError('GOAL_NOT_FOUND', 'goal not found');return { ok: true };} catch (err) {- if (err instanceof GoalControllerInputError) {- throwIpcError('INVALID_PARAMS', err.message);- }- if (err instanceof GoalUpdateSupersededError) {- throwIpcError('PRECONDITION_FAILED', err.message);- }- throw err;+ throwGoalControllerIpcError(err);}});