Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): reset GoalController on logout/account switch (#3124)
Battleplusc18b54857740
diff --git a/apps/desktop/src/main/__tests__/piSubagentQuitEscalation.test.ts b/apps/desktop/src/main/__tests__/piSubagentQuitEscalation.test.tsindex 3de433bf1a..239e7ac991 100644--- a/apps/desktop/src/main/__tests__/piSubagentQuitEscalation.test.ts+++ b/apps/desktop/src/main/__tests__/piSubagentQuitEscalation.test.ts@@ -252,13 +252,61 @@ describe('PI Subagent quit sweep', () => {expect(teardown.indexOf('lifecycleDbClientManager.dispose(reason)', sweep)).toBeGreaterThan(sweep);});- it('raises the account-boundary fence before anything destructive runs', () => {+ it('disposes goals before waiting for the account-boundary fence', () => {+ const teardown = source.slice(+ source.indexOf('async function teardownAuthAccountBoundary(reason: string)'),+ source.indexOf('authManager.setAccountSwitchTeardown('),+ );+ const reset = teardown.indexOf('resetGoalController();');+ const firstAwait = teardown.indexOf('await ');+ const acquire = teardown.indexOf('acquirePiSubagentLaunchFence(');+ expect(reset).toBeGreaterThan(-1);+ expect(firstAwait).toBeGreaterThan(reset);+ expect(acquire).toBeGreaterThan(firstAwait);+ // Fence acquisition can queue behind filesystem work. The synchronous reset+ // must already have cancelled continuation and usage-resume timers while it waits.+ expect(teardown.slice(firstAwait, acquire)).toBe('await ');+ });++ it('restores the outgoing account goals when launch-fence acquisition aborts', () => {+ const teardown = source.slice(+ source.indexOf('async function teardownAuthAccountBoundary(reason: string)'),+ source.indexOf('authManager.setAccountSwitchTeardown('),+ );+ const acquire = teardown.indexOf('acquirePiSubagentLaunchFence(');+ const acquireCatch = teardown.indexOf('} catch (err) {', acquire);+ const abort = teardown.indexOf('throw new PiSubagentAccountBoundaryError(', acquireCatch);+ const restore = teardown.indexOf('startGoalController({', acquireCatch);+ expect(acquireCatch).toBeGreaterThan(acquire);+ expect(restore).toBeGreaterThan(acquireCatch);+ expect(restore).toBeLessThan(abort);+ const recovery = teardown.slice(acquireCatch, abort);+ expect(recovery).toContain('const maker = getMakerCore();');+ expect(recovery).toContain('getDb: () => getDbClient().drizzle');+ expect(recovery).toContain('createAutomationUserTurnGitBaselineHooks()');+ // Goal IPC is restored synchronously, while the full Scheduler/Goal/Learn+ // startup is queued behind any superseded in-flight attempt. The original+ // fence error is still surfaced without awaiting that background recovery.+ expect(recovery).toContain('void attemptStartScheduler();');+ expect(recovery).not.toContain('await attemptStartScheduler()');+ const startup = source.slice(+ source.indexOf('let attemptStartSchedulerBarrier: Promise<void>'),+ source.indexOf('const _scheduleIpcRegistered'),+ );+ expect(startup).toContain(+ 'attemptStartSchedulerBarrier.then(() => attemptStartSchedulerOnce())',+ );+ expect(startup).toContain('attemptStartSchedulerBarrier = attempt.catch(() => undefined)');+ });++ it('raises the account-boundary fence before the remaining destructive teardown', () => {// Failing to raise it aborts the handover. It used to do that from the// middle of the teardown: input device slots suspended, the custom provider// catalog cleared, IM / scheduler / embedding / Ghost projection already// stopped — and the abort path rebuilds none of them, so the user was left// on a half-dismantled account until a restart. Raised first, the abort- // costs nothing because nothing has been taken apart yet.+ // leaves only the deliberately synchronous GoalController invalidation done;+ // no owner-scoped service has been drained or discarded yet.const teardown = source.slice(source.indexOf('async function teardownAuthAccountBoundary(reason: string)'),source.indexOf('authManager.setAccountSwitchTeardown('),diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 60922494d4..69c0101056 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -875,7 +875,7 @@ import {resetSchedulerReady,} from './maker-ipc/schedule.js';import { registerProjectAutomationIpc } from './maker-ipc/project-automation.js';-import { startGoalController, getGoalController } from './goal-host/index.js';+import { startGoalController, getGoalController, resetGoalController, getGoalTeardownGeneration } from './goal-host/index.js';import { startLearnHost, getLearnController, resetLearnController } from './learn-host/index.js';import { fetchHubSkillReference } from './learn-host/hubReference.js';import { registerLearnIpc, broadcastLearnEvent } from './learn-host/registerIpc.js';@@ -932,7 +932,19 @@ async function waitForCurrentAccountProviderModelsReady(): Promise<void> {* startScheduler 返回同一实例,WeakSet 防止 scheduler.on 重复挂 listener。切账号后* resetScheduler 把 _scheduler 置 null,新实例不在 WeakSet 里,会重新 attach 一次。*/-async function attemptStartScheduler(): Promise<void> {+// Provider/DB readiness can trigger this entry from several places. Serialize+// complete account-host attempts, not only Scheduler construction: when an+// account-boundary reset supersedes an older attempt, its cleanup must finish+// before an abort recovery starts Scheduler, GoalController, and Learn again.+let attemptStartSchedulerBarrier: Promise<void> = Promise.resolve();++function attemptStartScheduler(): Promise<void> {+ const attempt = attemptStartSchedulerBarrier.then(() => attemptStartSchedulerOnce());+ attemptStartSchedulerBarrier = attempt.catch(() => undefined);+ return attempt;+}++async function attemptStartSchedulerOnce(): Promise<void> {// 两个前置条件必须满足才能启动:// 1. maker 单例已构造 (splash check-environment 完成 → registerMakerIpcsAfterSplash)// 2. DbClient 已 smoke 通过 (user login → renderer 触发 'local-db:ensure-ready' IPC)@@ -960,7 +972,14 @@ async function attemptStartScheduler(): Promise<void> {// 触发时可能发生),_initialCustomMcpRefresh 刚启动但尚未落地;在 startScheduler 前// await,确保第一个 scheduler tick 能看到用户已保存的自定义 MCP 配置。// 若 Maker 已被 registerMakerIpcsAfterSplash 构造过,promise 早已 resolve,no-op。+ const goalGenBefore = getGoalTeardownGeneration();await waitForInitialCustomMcpRefresh();+ // If a teardown raced the await, bail out — the next account's activation+ // pass will re-trigger attemptStartScheduler with fresh state.+ if (getGoalTeardownGeneration() !== goalGenBefore) {+ console.log('[bootstrap-electron] attemptStartScheduler: teardown raced await, aborting');+ return;+ }const automationGitBaselineHooks = createAutomationUserTurnGitBaselineHooks();try {const scheduler = await startScheduler({@@ -971,6 +990,14 @@ async function attemptStartScheduler(): Promise<void> {logger: createSchedulerLogger('scheduler-host'),...automationGitBaselineHooks,});+ // startScheduler fences resets while its async startup is in flight. Keep+ // the boundary check immediately before listener publication as a second+ // guard so a stale generation can never make readiness visible.+ if (getGoalTeardownGeneration() !== goalGenBefore) {+ console.log('[bootstrap-electron] attemptStartScheduler: teardown raced scheduler start, aborting stale scheduler attach');+ await resetScheduler();+ return;+ }// scheduler 真正 ready 后挂 listener + 喂入 readiness holder。WeakSet 按实例// 去重:localDb onReady 重试可能再次拿到同实例,此时 no-op;// 切账号后新实例不在 set 里,会重新 attach。@@ -985,6 +1012,13 @@ async function attemptStartScheduler(): Promise<void> {} catch (err) {console.error('[bootstrap-electron] startScheduler failed (non-fatal):', err);}+ // A superseded startup is reported as a non-fatal error by the catch above;+ // keep the old post-await fence as well so it cannot continue into+ // GoalController/learn-host startup with the stale maker.+ if (getGoalTeardownGeneration() !== goalGenBefore) {+ console.log('[bootstrap-electron] attemptStartScheduler: teardown raced scheduler start, aborting stale account startup');+ return;+ }// GoalController 与 scheduler 同就绪点启动(maker + localDb 均 ready):内部幂等// (_controller 已存在则直接返回),启动时 resume 所有 active goal。失败非致命。try {@@ -1327,13 +1361,19 @@ function clearAccountBoundaryAbortMark(): void {async function teardownAuthAccountBoundary(reason: string): Promise<void> {const blockingFailures: unknown[] = [];- // Raised before anything else in this function, because everything below- // it is destructive: input device slots are suspended, the custom provider- // catalog is cleared, IM, the scheduler, embedding and the Ghost projection- // are stopped. Failing to raise it aborts the handover — and it used to do- // that *after* those services were already down, leaving the user on a- // half-dismantled old account with no way back except a restart. From here- // the abort costs nothing: nothing has been taken apart yet.+ // Goal timers can dispatch through the outgoing Maker while launch-fence+ // acquisition waits behind queued filesystem work. Invalidate them before+ // the first await; resetGoalController() synchronously disposes the current+ // controller and cancels continuation / usage-resume timers.+ // Start disposal synchronously, then drain it before waiting on the+ // cross-process launch fence. This closes the Goal boundary immediately;+ // disposal itself only settles owner-scoped persistence and cannot launch a+ // new durable runner after the controller has been fenced.+ const goalDispose = resetGoalController();+ // Raise the durable-run fence before the remaining destructive teardown:+ // input device slots are suspended, the custom provider catalog is cleared,+ // and IM, scheduler, embedding and Ghost projection are stopped. Failing to+ // raise it still aborts the handover before those services are taken apart.//// Holding it for the whole teardown rather than only the shutdown+sweep is// the intended widening: a durable launch is exactly what must not start@@ -1347,6 +1387,36 @@ async function teardownAuthAccountBoundary(reason: string): Promise<void> {path.join(app.getPath('userData'), 'pi-agent-home'),);} catch (err) {+ try {+ await goalDispose;+ } catch (disposeErr) {+ authBoundaryLog.error(`resetGoalController on ${reason} failed (non-fatal):`, disposeErr);+ }+ // The handover is aborting before the owner commit, so the outgoing Maker+ // and DB remain authoritative. Recreate the controller disposed above;+ // otherwise a transient fence failure leaves the still-active account with+ // no goal IPC/runtime until the whole app restarts.+ try {+ const maker = getMakerCore();+ const automationGitBaselineHooks = createAutomationUserTurnGitBaselineHooks();+ startGoalController({+ maker,+ getDb: () => getDbClient().drizzle,+ broadcastStatus: broadcastGoalStatus,+ ...automationGitBaselineHooks,+ });+ // A startup already in flight before resetGoalController() will exit on+ // its generation fence (and may stop a scheduler it just constructed).+ // Queue a fresh full account-host attempt behind that cleanup so the+ // still-active account also regains Scheduler and Learn. Do not await it:+ // the original fence error must remain the handover result.+ void attemptStartScheduler();+ } catch (restoreErr) {+ authBoundaryLog.error(+ `restore GoalController after launch-fence failure on ${reason} failed:`,+ restoreErr,+ );+ }// Fail closed, unlike quit and the relaunch. Those two are allowed to// continue without a fence because the process is about to disappear// (quit) or the operation is cancelled outright (relaunch). Here the@@ -1361,6 +1431,11 @@ async function teardownAuthAccountBoundary(reason: string): Promise<void> {'the PI Subagent launch fence could not be raised',);}+ try {+ await goalDispose;+ } catch (err) {+ authBoundaryLog.error(`resetGoalController on ${reason} failed (non-fatal):`, err);+ }try {// Hardware must stop before the long async drain. Otherwise a held stick or// microphone keeps acting on the outgoing account while caches and IM stop.diff --git a/apps/desktop/src/main/goal-host/__tests__/controller.test.ts b/apps/desktop/src/main/goal-host/__tests__/controller.test.tsindex 745a368d88..ec6c593761 100644--- a/apps/desktop/src/main/goal-host/__tests__/controller.test.ts+++ b/apps/desktop/src/main/goal-host/__tests__/controller.test.ts@@ -2509,6 +2509,67 @@ describe('GoalController', () => {expect(local.updates.filter((update) => update.goal === null)).toHaveLength(1);});+ it('drains a pending completion commit before controller disposal completes', async () => {+ let completionCalls = 0;+ let releaseCompletion!: () => void;+ const blockedCompletion = new Promise<void>((resolve) => {+ releaseCompletion = resolve;+ });+ const local = makeController({+ persistGoalCompletion: async () => {+ completionCalls += 1;+ await blockedCompletion;+ },+ });+ const clear = vi.spyOn(local.storage, 'clear');+ await startGoal(local);++ local.session.emitGoalTurn({+ toolUse: true,+ verdictJson: '```json\n{"goal_status":"complete","reason":"done"}\n```',+ });+ await vi.waitFor(() => expect(completionCalls).toBe(1));++ const disposing = local.controller.dispose();+ releaseCompletion();+ await disposing;+ await tick();++ expect(clear).toHaveBeenCalledWith('s1');+ expect(await local.storage.get('s1')).toBeNull();+ expect(local.updates.filter((update) => update.goal === null)).toHaveLength(0);+ });++ it('drains an in-flight completion clear during disposal without publishing stale status', async () => {+ const local = makeController();+ const originalClear = local.storage.clear.bind(local.storage);+ let clearCalls = 0;+ let releaseClear!: () => void;+ const blockedClear = new Promise<void>((resolve) => {+ releaseClear = resolve;+ });+ vi.spyOn(local.storage, 'clear').mockImplementation(async (sessionId) => {+ clearCalls += 1;+ await blockedClear;+ await originalClear(sessionId);+ });+ await startGoal(local);++ local.session.emitGoalTurn({+ toolUse: true,+ verdictJson: '```json\n{"goal_status":"complete","reason":"done"}\n```',+ });+ await vi.waitFor(() => expect(clearCalls).toBe(1));++ const disposing = local.controller.dispose();+ releaseClear();+ await disposing;+ await tick();++ expect(await local.storage.get('s1')).toBeNull();+ expect(local.updates.filter((update) => update.goal === null)).toHaveLength(0);+ });+it('finishes the completion commit if Stop arrives while clearing goal storage', async () => {const local = makeController();const originalClear = local.storage.clear.bind(local.storage);@@ -4305,3 +4366,139 @@ describe('GoalController', () => {});});++// ── dispose / GoalControllerDisposedError ───────────────────────────────────++describe('GoalController disposal', () => {+ it('setGoal rejects after dispose', async () => {+ const h = makeController();+ h.controller.dispose();+ await expect(+ h.controller.setGoal({ sessionId: 's1', objective: 'x', agentKind: 'claude-code' }),+ ).rejects.toThrow('GoalController has been disposed');+ });++ it('resumeGoal is no-op after dispose (auto)', async () => {+ const h = makeController();+ await startGoal(h);+ h.controller.dispose();+ // resumeGoal with auto:true returns early when turns map is empty (no throw).+ await expect(h.controller.resumeGoal('s1', { auto: true })).resolves.toBeUndefined();+ });++ it('clearGoal is no-op after dispose', async () => {+ const h = makeController();+ await startGoal(h);+ h.controller.dispose();+ // clearGoal does not call assertActive — it is a safe cleanup operation.+ // After dispose it should not throw; the turns map is already empty.+ await expect(h.controller.clearGoal('s1')).resolves.toBeUndefined();+ });++ it('all public lifecycle entry points stay inert after dispose', async () => {+ const h = makeController();+ await h.storage.set(seededGoal({ status: 'paused' }));+ h.controller.dispose();++ await expect(h.controller.updateGoal('s1', { objective: 'later' })).resolves.toBeNull();+ await expect(h.controller.pauseGoal('s1')).resolves.toBeUndefined();+ await expect(h.controller.resumeGoal('s1')).resolves.toBeUndefined();+ await expect(h.controller.maybeContinueActiveGoal('s1')).resolves.toBeUndefined();+ await expect(h.controller.resumeOnOpen('s1')).resolves.toBeUndefined();+ await expect(h.controller.resumeActiveGoals()).resolves.toBeUndefined();+ await expect(h.controller.getStatus('s1')).resolves.toBeNull();+ await expect(+ h.controller.applyClarificationAnswer(+ 's1',+ { objective: 'later' },+ [{ options: [{ label: 'task' }] }],+ ),+ ).resolves.toBeUndefined();++ expect(await h.storage.get('s1')).toMatchObject({+ status: 'paused',+ objective: 'old objective',+ });+ expect(h.session.sends).toHaveLength(0);+ expect(h.updates).toHaveLength(0);+ });++ it('dispose clears turns and listeners', async () => {+ const h = makeController();+ await startGoal(h);+ // Start a turn to register listeners.+ h.session.emitGoalTurn({ toolUse: true, tokens: 100 });+ await new Promise((r) => setTimeout(r, 0));+ const updatesBefore = h.updates.length;+ h.controller.dispose();+ // After dispose, no more status updates should be emitted.+ h.session.emitGoalTurn({ toolUse: true, tokens: 200 });+ await new Promise((r) => setTimeout(r, 0));+ expect(h.updates.length).toBe(updatesBefore);+ });++ it('dispose is idempotent', () => {+ const h = makeController();+ h.controller.dispose();+ h.controller.dispose(); // should not throw+ });++ it('drains a create marker before disposal completes', async () => {+ const h = makeController();+ const originalUpsert = h.storage.upsert.bind(h.storage);+ let markUpsertStarted!: () => void;+ const upsertStarted = new Promise<void>((resolve) => {+ markUpsertStarted = resolve;+ });+ let releaseUpsert!: () => void;+ const blockedUpsert = new Promise<void>((resolve) => {+ releaseUpsert = resolve;+ });+ vi.spyOn(h.storage, 'upsert').mockImplementationOnce(async (state) => {+ markUpsertStarted();+ await blockedUpsert;+ return originalUpsert(state);+ });++ const create = h.controller.setGoal({ sessionId: 's1', objective: 'outgoing objective' });+ await upsertStarted;+ const disposing = h.controller.dispose();+ releaseUpsert();+ await disposing;++ await expect(create).resolves.toBeNull();+ expect(await h.storage.get('s1')).toMatchObject({ status: 'active', objective: 'outgoing objective' });+ expect(h.userMessages).toHaveLength(1);+ expect(h.session.sends).toHaveLength(0);+ });++ it('drains an edit marker before disposal completes', async () => {+ const h = makeController();+ await h.storage.set(seededGoal({ status: 'paused', objective: 'old objective' }));+ const originalUpdate = h.storage.update.bind(h.storage);+ let markUpdateStarted!: () => void;+ const updateStarted = new Promise<void>((resolve) => {+ markUpdateStarted = resolve;+ });+ let releaseUpdate!: () => void;+ const blockedUpdate = new Promise<void>((resolve) => {+ releaseUpdate = resolve;+ });+ vi.spyOn(h.storage, 'update').mockImplementationOnce(async (sessionId, patch) => {+ markUpdateStarted();+ await blockedUpdate;+ return originalUpdate(sessionId, patch);+ });++ const edit = h.controller.setGoal({ sessionId: 's1', objective: 'outgoing edit' });+ await updateStarted;+ const disposing = h.controller.dispose();+ releaseUpdate();+ await disposing;++ await expect(edit).resolves.toBeNull();+ expect(await h.storage.get('s1')).toMatchObject({ status: 'active', objective: 'outgoing edit' });+ expect(h.userMessages).toHaveLength(1);+ expect(h.session.sends).toHaveLength(0);+ });+});diff --git a/apps/desktop/src/main/goal-host/controller.ts b/apps/desktop/src/main/goal-host/controller.tsindex 83ea5e5189..a3746c5ccb 100644--- a/apps/desktop/src/main/goal-host/controller.ts+++ b/apps/desktop/src/main/goal-host/controller.ts@@ -52,6 +52,16 @@ export class GoalControllerInputError extends Error {readonly code = 'INVALID_PARAMS';}+/** GoalController has been disposed; all public entry points should reject. */+export class GoalControllerDisposedError extends Error {+ readonly code = 'GONE';++ constructor() {+ super('GoalController has been disposed');+ this.name = 'GoalControllerDisposedError';+ }+}+/** Goal 已保守收敛,但本次入口无法恢复其底层 Agent Session。 */export class GoalSessionRestoreError extends Error {readonly code = 'PRECONDITION_FAILED';@@ -444,6 +454,15 @@ export class GoalController {private readonly consecutiveOverloadTurns = new Map<string, number>();private readonly now: () => number;private readonly debounceMs: number;+ private disposed = false;+ /** Disposal is two-phase: detach synchronously, then drain old-owner writes. */+ private disposing = false;+ private disposePromise: Promise<void> | null = null;++ /** Throw if the controller has been disposed. */+ private assertActive(): void {+ if (this.disposed || this.disposing) throw new GoalControllerDisposedError();+ }constructor(private readonly deps: GoalControllerDeps) {this.now = deps.now ?? (() => Date.now());@@ -454,6 +473,7 @@ export class GoalController {/** `/goal X` 入口:无既有 goal 直接创建;已有 goal 直接改 objective 并续跑。 */async setGoal(input: SetGoalInput): Promise<GoalState | null> {+ this.assertActive();const sessionId = input.sessionId;const objective = input.objective.trim();if (!objective) throw new GoalControllerInputError('objective must not be empty');@@ -522,6 +542,8 @@ export class GoalController {throw error;}if (this.turns.get(sessionId) !== entryBoundary) return null;+ // Guard: dispose() may have been called during the await above.+ this.assertActive();const ts = this.now();if (existing) {@@ -533,6 +555,7 @@ export class GoalController {let session: SessionLike | undefined;try {session = await this.deps.ensureSession(sessionId);+ this.assertActive();} catch (error) {if (this.turns.get(sessionId) !== failureBoundary) return null;this.deps.logger.warn('[goal] setGoal edit: session restore failed', {@@ -713,6 +736,7 @@ export class GoalController {}async updateGoal(sessionId: string, patch: GoalUpdatePatch): Promise<GoalState | null> {+ if (this.disposed || this.disposing) return null;const normalized = normalizeGoalUpdatePatch(patch);const existingBoundary = this.turns.get(sessionId);const operationBoundary = existingBoundary ?? freshTurn();@@ -749,10 +773,13 @@ export class GoalController {const reconcileLifecycleChange = async (): Promise<GoalState | null> => {const readSettledState = async (): Promise<GoalState | null> => {while (true) {+ if (this.disposed) return null;const boundary = this.turns.get(sessionId);await this.awaitPendingLifecycle(boundary);+ if (this.disposed) return null;if (this.turns.get(sessionId) !== boundary) continue;const current = await this.deps.storage.get(sessionId);+ if (this.disposed) return null;if (this.turns.get(sessionId) === boundary) return current;}};@@ -971,6 +998,7 @@ export class GoalController {answers: Record<string, string>,questions?: readonly GoalClarifyQuestion[],): Promise<void> {+ if (this.disposed || this.disposing) return;if (this.clarificationApplied.has(sessionId)) return; // 每目标只澄清改写一次const next = deriveObjectiveFromAnswers(answers);if (!next) return;@@ -1036,6 +1064,7 @@ export class GoalController {/** 清除目标(用户主动)。删行 + 停止一切续跑 + 取消 usage 自动续 + 通知 renderer 隐藏指示器。 */async clearGoal(sessionId: string): Promise<void> {+ if (this.disposed || this.disposing) return;this.clarificationApplied.delete(sessionId);this.consecutiveOverloadTurns.delete(sessionId);this.cancelDeferredManualResume(sessionId);@@ -1081,6 +1110,7 @@ export class GoalController {* reason 供 UI 展示(如 rewind 传 "paused: conversation rewound")。*/async pauseGoal(sessionId: string, reason?: string): Promise<void> {+ if (this.disposed || this.disposing) return;// Stop 的控制边界不能排在存储 IO 后面:读写一旦卡住,在途 turn 的终态事件仍会// 落到旧 listener,idle 兜底会把 active goal 立即续起来。先同步 detach listener、// continuation timer 与 firing 状态,再用同一 turns owner 留下 cancelled 边界,@@ -1136,6 +1166,7 @@ export class GoalController {* /已 active 不处理。*/async resumeGoal(sessionId: string, opts?: { auto?: boolean }): Promise<void> {+ if (this.disposed || this.disposing) return;let existingBoundary = this.turns.get(sessionId);let state: GoalState | null | undefined;if (existingBoundary?.cancelled) {@@ -1295,6 +1326,7 @@ export class GoalController {* dormant(没挂 listener)的 goal 不归这里管,由 resume-on-open 处理。*/async maybeContinueActiveGoal(sessionId: string): Promise<void> {+ if (this.disposed) return;if (this.deferredManualResumes.has(sessionId)) {this.scheduleDeferredManualResume(sessionId);return;@@ -1302,6 +1334,7 @@ export class GoalController {if (!this.unsubscribers.has(sessionId)) return;if (this.firing.has(sessionId)) return;const state = await this.deps.storage.get(sessionId);+ if (this.disposed) return;if (!state || state.status !== 'active') return;// 不在这里查 isBusy:本方法由 turn 收尾 observer 调用,而 turn idle 标记是延迟生效的// (scheduleIdleAfterTerminalBroadcast),此刻查 isBusy 多半仍为真。改走防抖续跑:@@ -1338,7 +1371,9 @@ export class GoalController {/** GET_GOAL_STATUS:返回当前状态扁平 payload(无 goal 返回 null)。 */async getStatus(sessionId: string): Promise<GoalStatusPayload | null> {+ if (this.disposed || this.disposing) return null;const state = await this.deps.storage.get(sessionId);+ if (this.disposed) return null;return state ? toPayload(state) : null;}@@ -1354,6 +1389,7 @@ export class GoalController {sessionId: string,opts?: { waitForDispatch?: boolean },): Promise<void> {+ if (this.disposed || this.disposing) return;const pendingFailure = this.unpersistedDispatchFailures.get(sessionId);if (pendingFailure) {const persisted = await this.blockDispatchFailure(@@ -1362,6 +1398,7 @@ export class GoalController {pendingFailure.lastReason,() => this.turns.get(sessionId) === pendingFailure.boundary,);+ if (this.disposed) return;if (!persisted) throw new GoalSessionRestoreError();return;}@@ -1375,6 +1412,7 @@ export class GoalController {if (this.turns.get(sessionId) === lifecycleBoundary) this.turns.delete(sessionId);throw error;}+ if (this.disposed || this.disposing) return;if (this.turns.get(sessionId) !== lifecycleBoundary) return;if (!state || state.status !== 'active') {if (this.turns.get(sessionId) === lifecycleBoundary) this.turns.delete(sessionId);@@ -1390,8 +1428,10 @@ export class GoalController {try {releaseAgentSwitchLock =(await this.deps.acquirePendingAgentSwitch?.(sessionId)) ?? (() => {});+ if (this.disposed) return;if (this.turns.get(sessionId) !== lifecycleBoundary) return;session = await this.deps.ensureSession(sessionId);+ if (this.disposed) return;if (this.turns.get(sessionId) !== lifecycleBoundary) return;if (session) {// 锁内先建立 listener 身份。释放后即使 queued SET_MODEL 立刻关闭该 session,@@ -1420,6 +1460,7 @@ export class GoalController {'turn dispatch failed: unable to restore the agent session',() => this.turns.get(sessionId) === lifecycleBoundary,);+ if (this.disposed) return;if (!persisted) throw new GoalSessionRestoreError(restoreError);return;}@@ -1430,6 +1471,7 @@ export class GoalController {'turn dispatch failed: unable to restore the agent session',() => this.turns.get(sessionId) === lifecycleBoundary,);+ if (this.disposed) return;if (!persisted) throw new GoalSessionRestoreError();return;}@@ -1458,12 +1500,20 @@ export class GoalController {* "active 却永远不动"的 dormant 死状态。*/async resumeActiveGoals(): Promise<void> {+ // Startup recovery is intentionally fire-and-forget. A logout/account+ // switch can dispose the controller while either storage query is waiting;+ // check the terminal fence after every await so the old maker cannot be+ // reattached or receive a resumed turn after teardown.+ if (this.disposed) return;const active = await this.deps.storage.listActive();+ if (this.disposed) return;let resumed = 0;for (const snapshot of active) {+ if (this.disposed) return;// listActive 是启动扫描快照;并发 Stop 可能已经立 cancelled boundary 或写成 paused。if (this.turns.has(snapshot.sessionId)) continue;const state = await this.deps.storage.get(snapshot.sessionId);+ if (this.disposed) return;if (!state || state.status !== 'active' || this.turns.has(snapshot.sessionId)) continue;// 保守:只对**已经活着**的会话重挂 + 续跑;不在启动时强行 spawn agent//(开机就偷偷跑目标过于激进)。没活的留 dormant,等用户重发 /goal 时由@@ -1494,9 +1544,12 @@ export class GoalController {// usageLimited 行:重启后 timer 丢了,按存档的 usageResetAt 重排自动续跑//(已过点 → delay 0 触发;未知 resetAt → 不排,留待手动 resume)。+ if (this.disposed) return;const limited = await this.deps.storage.listUsageLimited();+ if (this.disposed) return;let rescheduled = 0;for (const g of limited) {+ if (this.disposed) return;if (g.usageResetAt == null) continue;this.scheduleUsageResume(g.sessionId, g.usageResetAt);rescheduled += 1;@@ -1507,8 +1560,22 @@ export class GoalController {}/** 关停所有监听 + 计时器(测试 / 进程退出)。 */- dispose(): void {- for (const sessionId of [...this.unsubscribers.keys()]) {+ async dispose(): Promise<void> {+ if (this.disposePromise) return this.disposePromise;+ this.disposing = true;+ // Snapshot all old-owner persistence barriers before stopSession removes+ // their owners. The DB may be closed as soon as account teardown returns;+ // dropping either a completion clear or a goal-state write leaves stale+ // active rows behind (or lets a late write hit the next account).+ const pendingWrites = [...this.turns.values()].flatMap((turn) =>+ [turn.pendingPersistence, turn.pendingCompletion].filter(+ (pending): pending is Promise<void> => Boolean(pending),+ ),+ );+ for (const sessionId of new Set([+ ...this.unsubscribers.keys(),+ ...this.turns.keys(),+ ])) {this.stopSession(sessionId);}for (const sessionId of [...this.usageResumeTimers.keys()]) {@@ -1520,9 +1587,13 @@ export class GoalController {this.deferredManualResumes.clear();this.deferredManualResumeContexts.clear();this.unpersistedDispatchFailures.clear();- this.turns.clear();this.consecutiveOverloadTurns.clear();this.dispatchRejectionRetries.clear();+ this.disposePromise = Promise.allSettled(pendingWrites).then(() => {+ this.disposed = true;+ this.turns.clear();+ });+ return this.disposePromise;}// ── 内部 ───────────────────────────────────────────────────────────────────@@ -1577,6 +1648,11 @@ export class GoalController {afterPersist?: (value: T) => void | Promise<void>,): Promise<T> {const committed = operation.then(async (value) => {+ // Account teardown makes disposal terminal. The storage write may already+ // be in flight and cannot be cancelled, but its follow-up callback must+ // not start a new account-scoped message write after the controller has+ // been detached from its owner.+ if (this.disposed) return value;await afterPersist?.(value);return value;});@@ -1650,6 +1726,7 @@ export class GoalController {}private emit(state: GoalState): void {+ if (this.disposed || this.disposing) return;this.deps.emitStatus({ sessionId: state.sessionId, goal: toPayload(state) });}@@ -1660,6 +1737,7 @@ export class GoalController {* listener 再重挂到新 session,保证新引擎 turn 的 done/error 事件仍进 finalizeTurn。*/private attachListener(sessionId: string): void {+ if (this.disposed || this.disposing) return;const session = this.deps.getSession(sessionId);if (!session) return;if (this.unsubscribers.has(sessionId)) {@@ -1679,6 +1757,7 @@ export class GoalController {}private onEvent(sessionId: string, event: AgentEvent): void {+ if (this.disposed) return;let turn = this.turns.get(sessionId);if (!turn) {turn = freshTurn();@@ -1843,6 +1922,11 @@ export class GoalController {await this.trackCompletion(turn,(async () => {+ // Account teardown disposes the controller synchronously before the+ // owner DB is released. Every lazy completion side effect must honor+ // that terminal fence so a continuation that was waiting on message+ // persistence cannot resolve getDb() against the next account.+ if (this.disposed) return;if (this.deps.persistGoalCompletion) {try {await this.deps.persistGoalCompletion(sessionId, {@@ -1855,7 +1939,11 @@ export class GoalController {this.deps.logger.warn('[goal] persistGoalCompletion failed', { sessionId, error: String(e) });}}+ if (this.disposed) return;await this.deps.storage.clear(sessionId);+ // A retiring controller still drains the old owner's durable clear,+ // but must not publish a status into the next account's renderer.+ if (this.disposed || this.disposing) return;// null emit 属于同一顺序提交;后续新目标必须在它之后再 emit active,// 否则旧 completion 的迟到 null 会把新 chip 隐藏。this.deps.emitStatus({ sessionId, goal: null });@@ -1989,6 +2077,7 @@ export class GoalController {}private scheduleContinuation(sessionId: string): void {+ if (this.disposed) return;const existing = this.timers.get(sessionId);if (existing) clearTimeout(existing);const rejectionRetry = this.dispatchRejectionRetries.get(sessionId);@@ -2064,6 +2153,7 @@ export class GoalController {}private scheduleDeferredManualResume(sessionId: string): void {+ if (this.disposed) return;if (!this.deferredManualResumes.has(sessionId)) return;const existing = this.deferredManualResumeTimers.get(sessionId);if (existing) clearTimeout(existing);@@ -2087,6 +2177,7 @@ export class GoalController {*/private scheduleUsageResume(sessionId: string, resetAtMs: number | null): void {this.cancelUsageResume(sessionId);+ if (this.disposed) return;if (resetAtMs == null) return;// clamp 到 setTimeout 的 32-bit 上限(~24.8 天):否则超大 delay 会溢出、被当成 1ms// 立刻触发(限额窗口正常是 5h / weekly,远小于上限;clamp 只是防御异常 resetAt)。@@ -2119,6 +2210,7 @@ export class GoalController {*/private async autoResumeFromUsageLimit(sessionId: string): Promise<void> {this.usageResumeTimers.delete(sessionId);+ if (this.disposed) return;// usageLimited 停驻态正常没有 turn owner。为本次 timer 建一代临时 owner,所有 await// 都用对象身份复核;Stop 会同步换成 fresh cancelled owner,旧自动恢复因而不能落提示、// 不能恢复,也不会误删 Stop 的新边界。已有 owner 表示其它生命周期操作正在接管。@@ -2196,6 +2288,7 @@ export class GoalController {throwOnUnpersistedRestoreFailure?: boolean;},): Promise<void> {+ if (this.disposed) return;const lifecycleBoundary = this.turns.get(sessionId);if (!lifecycleBoundary || lifecycleBoundary.cancelled) return;const lifecycleGeneration = lifecycleBoundary.generation;diff --git a/apps/desktop/src/main/goal-host/index.ts b/apps/desktop/src/main/goal-host/index.tsindex 33d465d074..a7003b5293 100644--- a/apps/desktop/src/main/goal-host/index.ts+++ b/apps/desktop/src/main/goal-host/index.ts@@ -36,6 +36,10 @@ export interface StartGoalControllerDeps {let _controller: GoalController | null = null;+/** Incremented on every resetGoalController call. attemptStartScheduler uses+ * this to bail out if a teardown raced its await. */+let _teardownGeneration = 0;+export function startGoalController(deps: StartGoalControllerDeps): GoalController {if (_controller) return _controller;const logger = createLogger('goal-host');@@ -141,7 +145,15 @@ export function getGoalController(): GoalController | null {}/** 切账号 / 登出时调(与 resetScheduler 对齐;当前 bootstrap 不联动)。 */-export function resetGoalController(): void {- if (_controller) _controller.dispose();+export async function resetGoalController(): Promise<void> {+ const controller = _controller;_controller = null;+ _teardownGeneration++;+ if (controller) await controller.dispose();+}++/** Return current teardown generation. Callers that await across a teardown+ * boundary should compare before/after to detect stale continuations. */+export function getGoalTeardownGeneration(): number {+ return _teardownGeneration;}diff --git a/apps/desktop/src/main/maker-ipc/goal.ts b/apps/desktop/src/main/maker-ipc/goal.tsindex 5bf8f9950b..a9be4cb448 100644--- a/apps/desktop/src/main/maker-ipc/goal.ts+++ b/apps/desktop/src/main/maker-ipc/goal.ts@@ -20,6 +20,7 @@ import {GoalControllerInputError,GoalSessionRestoreError,GoalUpdateSupersededError,+ GoalControllerDisposedError,} from '../goal-host/controller.js';import { getGoalController } from '../goal-host/index.js';import { tapWindowBroadcast } from '../device-link/broadcast-tap.js';@@ -36,7 +37,8 @@ function throwGoalControllerIpcError(error: unknown): never {}if (error instanceof GoalSessionRestoreError ||- error instanceof GoalUpdateSupersededError+ error instanceof GoalUpdateSupersededError ||+ error instanceof GoalControllerDisposedError) {throwIpcError('PRECONDITION_FAILED', error.message);}diff --git a/apps/desktop/src/main/scheduler-host/__tests__/schedulerStartupLifecycle.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/schedulerStartupLifecycle.test.tsnew file mode 100644index 0000000000..4405d5f3d0--- /dev/null+++ b/apps/desktop/src/main/scheduler-host/__tests__/schedulerStartupLifecycle.test.ts@@ -0,0 +1,58 @@+import { describe, expect, it, vi } from 'vitest';+import type { Scheduler } from '@cindy/maker-scheduler';++import { runSchedulerStartup } from '../scheduler-startup-lifecycle';++function deferred(): { promise: Promise<void>; resolve: () => void } {+ let resolve!: () => void;+ const promise = new Promise<void>((done) => {+ resolve = done;+ });+ return { promise, resolve };+}++describe('runSchedulerStartup', () => {+ it('stops a startup superseded while scheduler.start is pending', async () => {+ let generation = 0;+ const startGate = deferred();+ const scheduler = {+ start: vi.fn(() => startGate.promise),+ stop: vi.fn(async () => {}),+ } as unknown as Scheduler;+ const publish = vi.fn();++ const startup = runSchedulerStartup(0, () => generation, {+ create: () => scheduler,+ publish,+ });+ generation += 1;+ startGate.resolve();++ await expect(startup).rejects.toThrow('scheduler startup superseded by reset');+ expect(scheduler.stop).toHaveBeenCalledOnce();+ expect(publish).not.toHaveBeenCalled();+ });++ it('stops a startup superseded during post-start cleanup', async () => {+ let generation = 0;+ const cleanupGate = deferred();+ const scheduler = {+ start: vi.fn(async () => {}),+ stop: vi.fn(async () => {}),+ } as unknown as Scheduler;+ const publish = vi.fn();++ const startup = runSchedulerStartup(0, () => generation, {+ create: () => scheduler,+ afterStart: () => cleanupGate.promise,+ publish,+ });+ await Promise.resolve();+ generation += 1;+ cleanupGate.resolve();++ await expect(startup).rejects.toThrow('scheduler startup superseded by reset');+ expect(scheduler.stop).toHaveBeenCalledOnce();+ expect(publish).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/scheduler-host/index.ts b/apps/desktop/src/main/scheduler-host/index.tsindex f9206be645..7f51478cab 100644--- a/apps/desktop/src/main/scheduler-host/index.ts+++ b/apps/desktop/src/main/scheduler-host/index.ts@@ -53,6 +53,7 @@ import { SchedulerScriptCapabilityBroker } from './script-capability-broker';import { DesktopNotifier } from './notifier';import { withScheduleLock } from './scheduleLock';import { wecomGroupNotificationService } from '../wecomGroupNotification';+import { runSchedulerStartup } from './scheduler-startup-lifecycle';export interface StartSchedulerDeps {maker: Maker;@@ -67,9 +68,27 @@ export interface StartSchedulerDeps {let _scheduler: Scheduler | null = null;let _storage: DrizzleScheduleStorage | null = null;let _loader: ProjectAutomationLoader | null = null;+// Reset increments this before awaiting stop(). A start that was already+// blocked in scheduler.start() must not publish its stale instance after the+// account boundary has moved on.+let _startupGeneration = 0;+// resetScheduler must wait for the old account's complete startup operation,+// not only fence its eventual publication.+let _startupPromise: Promise<Scheduler> | null = null;-export async function startScheduler(deps: StartSchedulerDeps): Promise<Scheduler> {- if (_scheduler) return _scheduler;+export function startScheduler(deps: StartSchedulerDeps): Promise<Scheduler> {+ if (_scheduler) return Promise.resolve(_scheduler);+ if (_startupPromise) return _startupPromise;+ const startup = startSchedulerInternal(deps);+ _startupPromise = startup;+ void startup.finally(() => {+ if (_startupPromise === startup) _startupPromise = null;+ }).catch(() => {});+ return startup;+}++async function startSchedulerInternal(deps: StartSchedulerDeps): Promise<Scheduler> {+ const startupGeneration = _startupGeneration;const storage = new DrizzleScheduleStorage(deps.getDb);_storage = storage;@@ -190,13 +209,17 @@ export async function startScheduler(deps: StartSchedulerDeps): Promise<SchedulepromptRunner.attachScheduler(scheduler);scriptRunner.attachScheduler(scheduler);- await scheduler.start();- try {- const orphans = await storage.deleteOrphanRuns();- if (orphans > 0) deps.logger.info?.(`[scheduler-host] cleaned ${orphans} orphan run(s)`);- } catch (err) {- deps.logger.warn?.(`[scheduler-host] deleteOrphanRuns failed (non-fatal): ${String(err)}`);- }+ await runSchedulerStartup(startupGeneration, () => _startupGeneration, {+ create: () => scheduler,+ afterStart: async () => {+ try {+ const orphans = await storage.deleteOrphanRuns();+ if (orphans > 0) deps.logger.info?.(`[scheduler-host] cleaned ${orphans} orphan run(s)`);+ } catch (err) {+ deps.logger.warn?.(`[scheduler-host] deleteOrphanRuns failed (non-fatal): ${String(err)}`);+ }+ },+ });_scheduler = scheduler;_loader = loader;deps.logger.info?.(`[scheduler-host] started${passive ? ' (passive: auto-fire disabled)' : ''}`);@@ -243,6 +266,15 @@ export function getProjectAutomationLoader(): ProjectAutomationLoader {* 当前 resetMaker(maker-host:131)也不会调本函数。*/export async function resetScheduler(): Promise<void> {+ _startupGeneration++;+ const pendingStartup = _startupPromise;+ if (pendingStartup) {+ try {+ await pendingStartup;+ } catch {+ // Superseded startup rejects after stopping itself; teardown continues.+ }+ }if (_scheduler) {await _scheduler.stop();}diff --git a/apps/desktop/src/main/scheduler-host/scheduler-startup-lifecycle.ts b/apps/desktop/src/main/scheduler-host/scheduler-startup-lifecycle.tsnew file mode 100644index 0000000000..e97cca8228--- /dev/null+++ b/apps/desktop/src/main/scheduler-host/scheduler-startup-lifecycle.ts@@ -0,0 +1,32 @@+import type { Scheduler } from '@cindy/maker-scheduler';++interface StartSchedulerLifecycleHooks {+ create: () => Scheduler;+ afterStart?: (scheduler: Scheduler) => void | Promise<void>;+ publish?: (scheduler: Scheduler) => void;+}++/**+ * Run the asynchronous scheduler startup behind an account-generation fence.+ * The helper is Electron-free so the reset/start race stays deterministic in+ * unit tests.+ */+export async function runSchedulerStartup(+ startupGeneration: number,+ getGeneration: () => number,+ hooks: StartSchedulerLifecycleHooks,+): Promise<Scheduler> {+ const scheduler = hooks.create();+ await scheduler.start();+ if (getGeneration() !== startupGeneration) {+ await scheduler.stop();+ throw new Error('scheduler startup superseded by reset');+ }+ await hooks.afterStart?.(scheduler);+ if (getGeneration() !== startupGeneration) {+ await scheduler.stop();+ throw new Error('scheduler startup superseded by reset');+ }+ hooks.publish?.(scheduler);+ return scheduler;+}