Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 修复高负载会话无法停止 (#1362)
Dash59a9cef68b05
diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.tsindex d5661491c6..e3c8215c5d 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 goalStorageSourcePath = resolve(__dirname, '..', 'goal-host', 'storage.ts');+const goalStorageSource = readFileSync(goalStorageSourcePath, 'utf8').replace(/\r\n?/g, '\n');describe('maker:event hot path ordering', () => {it('rewires a replacement Session instance that retains the same business id', () => {@@ -248,12 +250,12 @@ describe('maker:event hot path ordering', () => {expectOrder(directAbortSource,'const sess = getStableSessionForTurnBoundary(sessionId);',- 'if (!sess) return;',+ 'if (!sess) {',);expect(directAbortSource).not.toContain('const sess = maker.getSession(sessionId);');expectOrder(directAbortSource,- 'if (!sess) return;',+ 'if (!sess) {','handleAgentIslandSessionStopped(sess);',);expectOrder(@@ -301,6 +303,89 @@ describe('maker:event hot path ordering', () => {);});+ it('tears down every automatic recovery path before an explicit Stop aborts the session', () => {+ const resetStart = source.indexOf('function resetAutomaticRecoveryForExplicitStop(');+ const resetEnd = source.indexOf('\n}\n\nfunction settleUndispatchedAutoResumeOutcome', resetStart) + 2;+ const resetSource = source.slice(resetStart, resetEnd);+ const coordinatorAbortStart = source.indexOf('abortSession: async (sessionId) => {');+ const coordinatorAbortEnd = source.indexOf('\n isTurnRunning:', coordinatorAbortStart);+ const coordinatorAbortSource = source.slice(coordinatorAbortStart, coordinatorAbortEnd);+ const inputStopStart = source.indexOf('ipcMain.handle(MAKER_INVOKE.INPUT_STOP');+ const inputStopEnd = source.indexOf('\n ipcMain.handle(MAKER_INVOKE.INPUT_RESUME', inputStopStart);+ const inputStopSource = source.slice(inputStopStart, inputStopEnd);+ 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 goalPauseStart = source.indexOf('async function pauseGoalBeforeExplicitStop(');+ const goalPauseEnd = source.indexOf('\n}\n// (Option B)', goalPauseStart) + 2;+ const goalPauseSource = source.slice(goalPauseStart, goalPauseEnd);++ expect(resetStart).toBeGreaterThanOrEqual(0);+ expect(resetSource).toContain('silentStopAutoResumeGuard.noteSessionReset(sessionId);');+ expect(resetSource).toContain('interruptedTurnAutoResumeGuard.noteSessionReset(sessionId);');+ expect(resetSource).toContain('autoResumeBookkeeping.teardown(sessionId);');+ expect(source).toContain('noteSessionReset: resetAutomaticRecoveryForExplicitStop,');+ expect(source).toContain('resetAutomaticRecoveryForExplicitStop(sid);');++ expectOrder(+ coordinatorAbortSource,+ 'resetAutomaticRecoveryForExplicitStop(sessionId);',+ 'const sess = getStableSessionForTurnBoundary(sessionId);',+ );+ expectOrder(+ directAbortSource,+ 'resetAutomaticRecoveryForExplicitStop(sessionId);',+ 'const goalPause = pauseGoalBeforeExplicitStop(sessionId);',+ );+ expectOrder(+ directAbortSource,+ 'const goalPause = pauseGoalBeforeExplicitStop(sessionId);',+ 'const sess = getStableSessionForTurnBoundary(sessionId);',+ );+ // no-session 分支会先 await goalPause 后返回;有 live session 时真正的 abort 必须+ // 立即启动,只在 abort/reconcile 之后读取 Goal 持久化结果。+ expect(directAbortSource.indexOf('const settledGoalPause = await goalPauseResult;')).toBeGreaterThan(+ directAbortSource.indexOf('await sess.abort();'),+ );+ expectOrder(+ inputStopSource,+ 'resetAutomaticRecoveryForExplicitStop(sid);',+ 'const goalPause = pauseGoalBeforeExplicitStop(sid);',+ );+ expectOrder(+ inputStopSource,+ 'const goalPause = pauseGoalBeforeExplicitStop(sid);',+ 'inputCoordinator.stop(',+ );+ expectOrder(inputStopSource, 'inputCoordinator.stop(', 'await goalPause;');+ expect(goalPauseStart).toBeGreaterThanOrEqual(0);+ expect(goalPauseSource).toContain('catch (err)');+ expect(goalPauseSource).toContain('await Promise.resolve(observer(sessionId));');+ expect(goalPauseSource).toContain("log.error('goal pause persistence failed during explicit stop'");+ expect(goalPauseSource).toContain(+ "throwIpcError('INTERNAL', 'Failed to persist the stopped Goal state');",+ );+ expect(goalPauseSource).not.toContain('throw err;');+ expect(goalPauseSource).not.toContain('Promise.race');+ expect(goalPauseSource).not.toContain('setTimeout');+ expect(directAbortSource).toContain('const goalPauseResult = goalPause.then(');+ expectOrder(directAbortSource, 'await sess.abort();', 'const settledGoalPause = await goalPauseResult;');+ expectOrder(directAbortSource, 'if (abortFailed)', 'if (!settledGoalPause.ok) throw settledGoalPause.error;');+ });++ it('commits a Goal state update before its post-write readback', () => {+ const updateStart = goalStorageSource.indexOf('async update(sessionId: string');+ const updateEnd = goalStorageSource.indexOf('\n async clear(', updateStart);+ const updateSource = goalStorageSource.slice(updateStart, updateEnd);++ expect(updateStart).toBeGreaterThanOrEqual(0);+ expect(updateSource).not.toContain('const existing = await this.get(sessionId);');+ const writeIndex = updateSource.indexOf('await this.getDb().update(sessionGoals)');+ const postWriteReadIndex = updateSource.lastIndexOf('return this.get(sessionId);');+ expect(writeIndex).toBeGreaterThanOrEqual(0);+ expect(postWriteReadIndex).toBeGreaterThan(writeIndex);+ });+it('uses the wired Session snapshot while reconciling owner-boundary aborts', () => {const stableLookupStart = source.indexOf('const getStableSessionForTurnBoundary =');const stableLookupEnd = source.indexOf('\n const reconcileSessionTurnIdle =', stableLookupStart);diff --git a/apps/desktop/src/main/goal-host/__tests__/controller.test.ts b/apps/desktop/src/main/goal-host/__tests__/controller.test.tsindex e549c43943..7c0f702d97 100644--- a/apps/desktop/src/main/goal-host/__tests__/controller.test.ts+++ b/apps/desktop/src/main/goal-host/__tests__/controller.test.ts@@ -2,7 +2,15 @@ import { describe, expect, it, beforeEach, vi } from 'vitest';import type { AgentEvent, SessionSendResult } from '@cindy/maker-core';-import { GoalController, decideNextGoalState, deriveObjectiveFromAnswers, questionsLookLikeGoalClarification, type TurnOutcome, type GoalCounters } from '../controller';+import {+ GoalController,+ GoalUpdateSupersededError,+ decideNextGoalState,+ deriveObjectiveFromAnswers,+ questionsLookLikeGoalClarification,+ type TurnOutcome,+ type GoalCounters,+} from '../controller';import { buildContinuationDirective, buildFirstTurnDirective } from '../directive';import { MAX_CONSECUTIVE_OVERLOAD_TURNS } from '../usageLimit';import type {@@ -569,6 +577,103 @@ describe('GoalController', () => {expect(h.persistedLimits).toHaveLength(0);});+ it('keeps a goal edit alive when a normal turn resets while session hydration is pending', async () => {+ let ensureCalls = 0;+ let releaseEnsure!: (session: SessionLike | undefined) => void;+ const blockedEnsure = new Promise<SessionLike | undefined>((resolve) => {+ releaseEnsure = resolve;+ });+ const liveSession = new FakeSession('s1');+ const local = makeController({+ getSession: () => liveSession,+ ensureSession: async () => {+ ensureCalls += 1;+ return ensureCalls === 3 ? blockedEnsure : liveSession;+ },+ continuationDebounceMs: 60_000,+ });+ await local.controller.setGoal({ sessionId: 's1', objective: 'old objective' });++ const editPromise = local.controller.setGoal({ sessionId: 's1', objective: 'new objective' });+ await vi.waitFor(() => expect(ensureCalls).toBe(3));++ liveSession.emitGoalTurn({+ toolUse: true,+ verdictJson: '```json\n{"goal_status":"continue","reason":"normal turn finished"}\n```',+ tokens: 25,+ });+ await vi.waitFor(async () => {+ expect((await local.storage.get('s1'))?.turnsUsed).toBe(1);+ });++ releaseEnsure(liveSession);+ await expect(editPromise).resolves.toMatchObject({+ status: 'active',+ objective: 'new objective',+ turnsUsed: 1,+ });+ expect(await local.storage.get('s1')).toMatchObject({+ status: 'active',+ objective: 'new objective',+ turnsUsed: 1,+ });+ expect(liveSession.sends.at(-1)?.content).toContain('new objective');+ });++ it('does not let a goal edit waiting for session hydration overwrite a later Stop', async () => {+ let ensureCalls = 0;+ let releaseEnsure!: (session: SessionLike | undefined) => void;+ const blockedEnsure = new Promise<SessionLike | undefined>((resolve) => {+ releaseEnsure = resolve;+ });+ const liveSession = new FakeSession('s1');+ const local = makeController({+ getSession: () => liveSession,+ ensureSession: async () => {+ ensureCalls += 1;+ return blockedEnsure;+ },+ });+ await local.storage.set(seededGoal({ status: 'active', objective: 'old objective' }));++ const editPromise = local.controller.setGoal({ sessionId: 's1', objective: 'stale edit' });+ await vi.waitFor(() => expect(ensureCalls).toBe(1));+ await local.controller.pauseGoal('s1');+ releaseEnsure(liveSession);++ await expect(editPromise).resolves.toBeNull();+ expect(await local.storage.get('s1')).toMatchObject({+ status: 'paused',+ objective: 'old objective',+ });+ expect(liveSession.sends).toHaveLength(0);+ });++ it('cancels goal creation when Stop lands while the new session is hydrating', async () => {+ let ensureCalls = 0;+ let releaseEnsure!: (session: SessionLike | undefined) => void;+ const blockedEnsure = new Promise<SessionLike | undefined>((resolve) => {+ releaseEnsure = resolve;+ });+ const liveSession = new FakeSession('s1');+ const local = makeController({+ getSession: () => liveSession,+ ensureSession: async () => {+ ensureCalls += 1;+ return blockedEnsure;+ },+ });++ const createPromise = local.controller.setGoal({ sessionId: 's1', objective: 'do not resurrect' });+ await vi.waitFor(() => expect(ensureCalls).toBe(1));+ await local.controller.pauseGoal('s1');+ releaseEnsure(liveSession);++ await expect(createPromise).resolves.toBeNull();+ expect(await local.storage.get('s1')).toBeNull();+ expect(liveSession.sends).toHaveLength(0);+ });+it('buildFirstTurnDirective tells the agent to use AskUserQuestion when concerned, mentions the budget, and keeps a blocked fallback', () => {const text = buildFirstTurnDirective('do the thing', { maxTurns: 20 });expect(text).toContain('AskUserQuestion');@@ -665,6 +770,314 @@ describe('GoalController', () => {expect(h.session.sends[0].content).toContain('updated after usage limit');});+ it('does not let an objective update consume a later Stop boundary', async () => {+ let persistCalls = 0;+ let releasePersist!: () => void;+ const blockedPersist = new Promise<void>((resolve) => {+ releasePersist = resolve;+ });+ const local = makeController({+ persistUserMessage: async () => {+ persistCalls += 1;+ await blockedPersist;+ },+ });+ await local.storage.set(seededGoal({ status: 'paused', objective: 'old objective' }));++ const updatePromise = local.controller.updateGoal('s1', { objective: 'updated objective' });+ await vi.waitFor(() => expect(persistCalls).toBe(1));+ let stopSettled = false;+ const stopPromise = local.controller.pauseGoal('s1').then(() => {+ stopSettled = true;+ });+ await tick();+ expect(stopSettled).toBe(false);+ releasePersist();++ const [updated] = await Promise.all([updatePromise, stopPromise]);+ expect(updated).toMatchObject({+ status: 'paused',+ objective: 'updated objective',+ });+ expect(await local.storage.get('s1')).toMatchObject({+ status: 'paused',+ objective: 'updated objective',+ });+ expect(persistCalls).toBe(1);+ expect(local.updates.at(-1)?.goal).toMatchObject({+ status: 'paused',+ objective: 'updated objective',+ });+ expect(local.session.sends).toHaveLength(0);+ });++ it('reports a superseded update instead of GOAL_NOT_FOUND when Stop wins before the patch is written', async () => {+ const initial = seededGoal({ status: 'active', objective: 'old objective' });+ await h.storage.set(initial);+ let releaseGet!: (state: GoalState | null) => void;+ const blockedGet = new Promise<GoalState | null>((resolve) => {+ releaseGet = resolve;+ });+ const getSpy = vi.spyOn(h.storage, 'get').mockReturnValueOnce(blockedGet);++ const updatePromise = h.controller.updateGoal('s1', { objective: 'stale objective' });+ await vi.waitFor(() => expect(getSpy).toHaveBeenCalledTimes(1));+ await h.controller.pauseGoal('s1');+ releaseGet(initial);++ await expect(updatePromise).rejects.toBeInstanceOf(GoalUpdateSupersededError);+ expect(await h.storage.get('s1')).toMatchObject({+ status: 'paused',+ objective: 'old objective',+ });+ expect(h.userMessages).toHaveLength(0);+ expect(h.session.sends).toHaveLength(0);+ });++ it('keeps a later setGoal authoritative over a dormant objective update already writing', async () => {+ const local = makeController();+ await local.storage.set(seededGoal({ status: 'active', objective: 'old objective' }));+ const originalUpdate = local.storage.update.bind(local.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(local.storage, 'update').mockImplementationOnce(async (sessionId, patch) => {+ markUpdateStarted();+ await blockedUpdate;+ return originalUpdate(sessionId, patch);+ });++ const staleUpdate = local.controller.updateGoal('s1', { objective: 'stale objective' });+ await updateStarted;+ const replacement = local.controller.setGoal({ sessionId: 's1', objective: 'replacement objective' });+ await tick();+ expect((await local.storage.get('s1'))?.objective).toBe('old objective');++ releaseUpdate();+ await Promise.allSettled([staleUpdate, replacement]);++ expect(await local.storage.get('s1')).toMatchObject({+ status: 'active',+ objective: 'replacement objective',+ });+ expect(local.session.sends.at(-1)?.content).toContain('replacement objective');+ });++ it('keeps a later setGoal authoritative over a clarification objective write', async () => {+ const local = makeController();+ await local.storage.set(seededGoal({ status: 'active', objective: 'old objective', turnsUsed: 0 }));+ const originalUpdate = local.storage.update.bind(local.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(local.storage, 'update').mockImplementationOnce(async (sessionId, patch) => {+ markUpdateStarted();+ await blockedUpdate;+ return originalUpdate(sessionId, patch);+ });++ const clarification = local.controller.applyClarificationAnswer(+ 's1',+ { q: 'clarified objective' },+ [{ options: [{ label: 'old objective' }, { label: 'clarified objective' }] }],+ );+ await updateStarted;+ const replacement = local.controller.setGoal({ sessionId: 's1', objective: 'replacement objective' });++ releaseUpdate();+ await Promise.allSettled([clarification, replacement]);++ expect(await local.storage.get('s1')).toMatchObject({+ status: 'active',+ objective: 'replacement objective',+ });+ expect(local.userMessages.map((message) => message.content)).toEqual([+ 'clarified objective',+ 'replacement objective',+ ]);+ });++ it('does not emit an old budgetLimited snapshot after a newer setGoal wins during its marker write', async () => {+ let releaseLimitedMarker!: () => void;+ const blockedLimitedMarker = new Promise<void>((resolve) => {+ releaseLimitedMarker = resolve;+ });+ let limitedMarkerStarted = false;+ const local = makeController({+ persistUserMessage: async (_sessionId, content, opts) => {+ if (opts?.goalObjective?.updated && content === 'limited objective') {+ limitedMarkerStarted = true;+ await blockedLimitedMarker;+ }+ },+ });+ await startGoal(local, 'old objective');+ const active = await local.storage.get('s1');+ await local.storage.set({ ...active!, turnsUsed: 5, maxTurns: 10 });++ const limitedUpdate = local.controller.updateGoal('s1', {+ objective: 'limited objective',+ maxTurns: 3,+ });+ await vi.waitFor(() => expect(limitedMarkerStarted).toBe(true));++ let replacementSettled = false;+ const replacement = local.controller+ .setGoal({ sessionId: 's1', objective: 'replacement objective' })+ .then((goal) => {+ replacementSettled = true;+ return goal;+ });+ await tick();+ expect(replacementSettled).toBe(false);+ releaseLimitedMarker();+ await replacement;+ const updatesAfterReplacement = local.updates.length;+ await expect(limitedUpdate).rejects.toBeInstanceOf(GoalUpdateSupersededError);++ expect(await local.storage.get('s1')).toMatchObject({+ status: 'budgetLimited',+ objective: 'replacement objective',+ });+ expect(+ local.updates+ .slice(updatesAfterReplacement)+ .some((update) => update.goal?.objective === 'limited objective'),+ ).toBe(false);+ expect(local.updates.at(-1)?.goal).toMatchObject({+ status: 'budgetLimited',+ objective: 'replacement objective',+ });+ });++ it('returns the authoritative paused goal when Stop wins while a budget edit is hydrating the session', async () => {+ let ensureCalls = 0;+ let releaseEnsure!: (session: SessionLike | undefined) => void;+ const blockedEnsure = new Promise<SessionLike | undefined>((resolve) => {+ releaseEnsure = resolve;+ });+ const liveSession = new FakeSession('s1');+ const local = makeController({+ getSession: () => liveSession,+ ensureSession: async () => {+ ensureCalls += 1;+ return blockedEnsure;+ },+ });+ await local.storage.set(seededGoal({+ status: 'budgetLimited',+ maxTurns: 5,+ turnsUsed: 5,+ lastReason: 'max turns reached',+ }));++ const updatePromise = local.controller.updateGoal('s1', { maxTurns: 6 });+ await vi.waitFor(() => expect(ensureCalls).toBe(1));+ await local.controller.pauseGoal('s1');+ releaseEnsure(liveSession);++ await expect(updatePromise).resolves.toMatchObject({+ status: 'paused',+ maxTurns: 6,+ });+ expect(await local.storage.get('s1')).toMatchObject({+ status: 'paused',+ maxTurns: 6,+ });+ expect(local.updates.at(-1)?.goal).toMatchObject({ status: 'paused', maxTurns: 6 });+ expect(liveSession.sends).toHaveLength(0);+ });++ it('returns and re-emits the committed objective when a turn finalizes during marker persistence', async () => {+ let updatedMarkerCalls = 0;+ let releaseMarker!: () => void;+ const blockedMarker = new Promise<void>((resolve) => {+ releaseMarker = resolve;+ });+ const local = makeController({+ persistUserMessage: async (_sessionId, _content, opts) => {+ if (opts?.goalObjective?.updated) {+ updatedMarkerCalls += 1;+ await blockedMarker;+ }+ },+ });+ await local.controller.setGoal({ sessionId: 's1', objective: 'old objective' });++ const updatePromise = local.controller.updateGoal('s1', { objective: 'updated objective' });+ await vi.waitFor(() => expect(updatedMarkerCalls).toBe(1));+ local.session.emitGoalTurn({+ toolUse: true,+ verdictJson: '```json\n{"goal_status":"continue","reason":"keep going"}\n```',+ tokens: 25,+ });+ await vi.waitFor(async () => {+ expect((await local.storage.get('s1'))?.turnsUsed).toBe(1);+ });+ releaseMarker();++ await expect(updatePromise).resolves.toMatchObject({+ objective: 'updated objective',+ turnsUsed: 1,+ });+ expect(updatedMarkerCalls).toBe(1);+ expect(local.updates.at(-1)?.goal).toMatchObject({+ objective: 'updated objective',+ turnsUsed: 1,+ });+ });++ it('rejects a committed update when a turn refinement supersedes its objective', async () => {+ let requestedMarkerCalls = 0;+ let refinedMarkerCalls = 0;+ let releaseRequestedMarker!: () => void;+ const blockedRequestedMarker = new Promise<void>((resolve) => {+ releaseRequestedMarker = resolve;+ });+ const local = makeController({+ persistUserMessage: async (_sessionId, content, opts) => {+ if (!opts?.goalObjective?.updated) return;+ if (content === 'requested objective') {+ requestedMarkerCalls += 1;+ await blockedRequestedMarker;+ } else if (content === 'refined by turn') {+ refinedMarkerCalls += 1;+ }+ },+ });+ await local.controller.setGoal({ sessionId: 's1', objective: 'old objective' });++ const updatePromise = local.controller.updateGoal('s1', { objective: 'requested objective' });+ await vi.waitFor(() => expect(requestedMarkerCalls).toBe(1));+ local.session.emitGoalTurn({+ toolUse: true,+ verdictJson:+ '```json\n{"goal_status":"continue","reason":"clarified","refined_objective":"refined by turn"}\n```',+ tokens: 25,+ });+ await vi.waitFor(async () => {+ expect((await local.storage.get('s1'))?.objective).toBe('refined by turn');+ expect(refinedMarkerCalls).toBe(1);+ });+ releaseRequestedMarker();++ await expect(updatePromise).rejects.toBeInstanceOf(GoalUpdateSupersededError);+ expect(await local.storage.get('s1')).toMatchObject({+ objective: 'refined by turn',+ turnsUsed: 1,+ });+ });+// ── active-goal lifecycle ──it('setGoal persists active state and fires the first turn (goal origin)', async () => {await startGoal(h);@@ -827,6 +1240,465 @@ describe('GoalController', () => {expect(h.session.sends.length).toBe(sendsAfterPause);});+ it('detaches goal continuation synchronously before pause persistence can block', async () => {+ await startGoal(h);+ const active = await h.storage.get('s1');+ expect(active?.status).toBe('active');++ let releaseGet!: (state: GoalState | null) => void;+ const blockedGet = new Promise<GoalState | null>((resolve) => {+ releaseGet = resolve;+ });+ vi.spyOn(h.storage, 'get').mockReturnValueOnce(blockedGet);++ const sendsBeforePause = h.session.sends.length;+ const pausePromise = h.controller.pauseGoal('s1');++ // 模拟 Stop 之后立刻到达旧 turn 的终态。即使 pause 的 DB 读仍悬着,listener+ // 也必须已经摘掉,不能让 idle 兜底再 fire 一轮。+ h.session.emitGoalTurn({+ toolUse: true,+ verdictJson: '```json\n{"goal_status":"continue","reason":"late done"}\n```',+ });+ await tick();+ expect(h.session.sends).toHaveLength(sendsBeforePause);++ // 打开会话触发的 dormant resume 也不能越过正在落盘的 Stop 边界。+ await h.controller.resumeOnOpen('s1');+ expect(h.session.sends).toHaveLength(sendsBeforePause);++ releaseGet(active);+ await pausePromise;+ expect((await h.storage.get('s1'))?.status).toBe('paused');+ });++ it('keeps the Stop boundary fail-closed when paused persistence fails', async () => {+ await startGoal(h);+ const sendsBeforeStop = h.session.sends.length;+ const updateSpy = vi+ .spyOn(h.storage, 'update')+ .mockRejectedValueOnce(new Error('goal storage unavailable'));++ await expect(h.controller.pauseGoal('s1')).rejects.toThrow('goal storage unavailable');+ expect((await h.storage.get('s1'))?.status).toBe('active');++ // GET_GOAL_STATUS 会 fire-and-forget 调 resumeOnOpen;失败的 Stop 仍必须挡住它。+ await h.controller.resumeOnOpen('s1');+ expect(h.session.sends).toHaveLength(sendsBeforeStop);++ updateSpy.mockRestore();+ await h.controller.pauseGoal('s1');+ expect((await h.storage.get('s1'))?.status).toBe('paused');+ });++ it('keeps the Stop boundary fail-closed when reading Goal state fails', async () => {+ await startGoal(h);+ const sendsBeforeStop = h.session.sends.length;+ const getSpy = vi+ .spyOn(h.storage, 'get')+ .mockRejectedValueOnce(new Error('goal storage read unavailable'));++ await expect(h.controller.pauseGoal('s1')).rejects.toThrow('goal storage read unavailable');+ await h.controller.resumeOnOpen('s1');+ expect(h.session.sends).toHaveLength(sendsBeforeStop);++ getSpy.mockRestore();+ await h.controller.pauseGoal('s1');+ expect((await h.storage.get('s1'))?.status).toBe('paused');+ });++ it('persists an explicitly stopped usage-limited goal as paused so restart cannot auto-resume it', async () => {+ await h.storage.set(seededGoal({+ status: 'usageLimited',+ usageResetAt: 9_999,+ lastReason: 'usage limit reached',+ }));++ await h.controller.pauseGoal('s1');++ expect(await h.storage.get('s1')).toMatchObject({+ status: 'paused',+ usageResetAt: null,+ lastReason: 'paused by user',+ });+ });++ it('cancels a goal fire that was already waiting across an async boundary', async () => {+ const liveSession = new FakeSession('s1');+ let ensureCalls = 0;+ let releaseEnsure!: (session: SessionLike | undefined) => void;+ const blockedEnsure = new Promise<SessionLike | undefined>((resolve) => {+ releaseEnsure = resolve;+ });+ const local = makeController({+ getSession: () => liveSession,+ ensureSession: async () => {+ ensureCalls += 1;+ return ensureCalls <= 2 ? liveSession : blockedEnsure;+ },+ });+ await startGoal(local);+ expect(liveSession.sends).toHaveLength(1);++ const firePromise = (+ local.controller as unknown as { fireTurn(sessionId: string): Promise<void> }+ ).fireTurn('s1');+ await vi.waitFor(() => expect(ensureCalls).toBe(3));++ await local.controller.pauseGoal('s1');+ releaseEnsure(liveSession);+ await firePromise;++ expect(liveSession.sends).toHaveLength(1);+ expect((await local.storage.get('s1'))?.status).toBe('paused');+ });++ it('does not rehydrate a session after Stop cancels a fire waiting on the route lock', async () => {+ const liveSession = new FakeSession('s1');+ let acquireCalls = 0;+ let ensureCalls = 0;+ let releaseAcquire!: (release: () => void) => void;+ const blockedAcquire = new Promise<() => void>((resolve) => {+ releaseAcquire = resolve;+ });+ const local = makeController({+ getSession: () => liveSession,+ ensureSession: async () => {+ ensureCalls += 1;+ return liveSession;+ },+ acquirePendingAgentSwitch: async () => {+ acquireCalls += 1;+ return acquireCalls === 1 ? () => {} : blockedAcquire;+ },+ });+ await startGoal(local);+ expect(ensureCalls).toBe(2);++ const firePromise = (+ local.controller as unknown as { fireTurn(sessionId: string): Promise<void> }+ ).fireTurn('s1');+ await vi.waitFor(() => expect(acquireCalls).toBe(2));++ await local.controller.pauseGoal('s1');+ releaseAcquire(() => {});+ await firePromise;++ expect(ensureCalls).toBe(2);+ expect(liveSession.sends).toHaveLength(1);+ expect((await local.storage.get('s1'))?.status).toBe('paused');+ });++ it('does not let stale budget preflight cleanup delete the Stop boundary', async () => {+ const local = makeController();+ await startGoal(local);+ const active = await local.storage.get('s1');+ expect(active).not.toBeNull();+ await local.storage.set({ ...active!, turnsUsed: 1, maxTurns: 1 });++ const originalUpdate = local.storage.update.bind(local.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(local.storage, 'update').mockImplementationOnce(async (sessionId, patch) => {+ const result = await originalUpdate(sessionId, patch);+ markUpdateStarted();+ await blockedUpdate;+ return result;+ });+ const internals = local.controller as unknown as {+ fireTurn(sessionId: string): Promise<void>;+ turns: Map<string, { cancelled: boolean }>;+ };++ const staleFire = internals.fireTurn('s1');+ await updateStarted;+ const pausePromise = local.controller.pauseGoal('s1');+ const stopBoundary = internals.turns.get('s1');+ expect(stopBoundary?.cancelled).toBe(true);++ releaseUpdate();+ await Promise.all([staleFire, pausePromise]);+ expect(internals.turns.get('s1')).toBe(stopBoundary);+ expect((await local.storage.get('s1'))?.status).toBe('budgetLimited');+ expect(local.session.sends).toHaveLength(1);+ });++ it('does not let an old fire cleanup clear the resumed generation firing owner', async () => {+ const liveSession = new FakeSession('s1');+ let acquireCalls = 0;+ let releaseOldAcquire!: (release: () => void) => void;+ let releaseNewAcquire!: (release: () => void) => void;+ const blockedOldAcquire = new Promise<() => void>((resolve) => {+ releaseOldAcquire = resolve;+ });+ const blockedNewAcquire = new Promise<() => void>((resolve) => {+ releaseNewAcquire = resolve;+ });+ const local = makeController({+ getSession: () => liveSession,+ ensureSession: async () => liveSession,+ acquirePendingAgentSwitch: async () => {+ acquireCalls += 1;+ if (acquireCalls === 1) return () => {};+ return acquireCalls === 2 ? blockedOldAcquire : blockedNewAcquire;+ },+ });+ await startGoal(local);+ const internals = local.controller as unknown as {+ fireTurn(sessionId: string): Promise<void>;+ firing: Map<string, object>;+ };++ const oldFire = internals.fireTurn('s1');+ await vi.waitFor(() => expect(acquireCalls).toBe(2));+ await local.controller.pauseGoal('s1');++ const resumePromise = local.controller.resumeGoal('s1');+ await vi.waitFor(() => expect(acquireCalls).toBe(3));+ expect(internals.firing.has('s1')).toBe(true);++ releaseOldAcquire(() => {});+ await oldFire;+ expect(internals.firing.has('s1')).toBe(true);++ releaseNewAcquire(() => {});+ await resumePromise;+ expect(liveSession.sends).toHaveLength(2);+ });++ it('does not let a stale send result erase the resumed goal turn marker', async () => {+ const local = makeController();+ let sendCalls = 0;+ let releaseOldSend!: (result: SessionSendResult) => void;+ const blockedOldSend = new Promise<SessionSendResult>((resolve) => {+ releaseOldSend = resolve;+ });+ vi.spyOn(local.session, 'send').mockImplementation(async (+ message: Parameters<FakeSession['send']>[0],+ opts: Parameters<FakeSession['send']>[1],+ ): Promise<SessionSendResult> => {+ const content = typeof message === 'string' ? message : message.content;+ local.session.sends.push({ content, originKind: opts?.origin?.kind });+ sendCalls += 1;+ return sendCalls === 2 ? blockedOldSend : { accepted: true };+ });+ await startGoal(local);+ const internals = local.controller as unknown as {+ fireTurn(sessionId: string): Promise<void>;+ goalTurnsInFlight: Set<string>;+ };++ const oldFire = internals.fireTurn('s1');+ await vi.waitFor(() => expect(sendCalls).toBe(2));+ await local.controller.pauseGoal('s1');+ await local.controller.resumeGoal('s1');+ expect(sendCalls).toBe(3);+ expect(internals.goalTurnsInFlight.has('s1')).toBe(true);++ releaseOldSend({ accepted: false, reason: 'cancelled-before-dispatch' });+ await oldFire;+ expect(internals.goalTurnsInFlight.has('s1')).toBe(true);+ });++ it('cancels an in-flight turn finalizer when Stop pauses the goal', async () => {+ let limitCalls = 0;+ let releaseLimit!: (limit: AccountLimitInfo | null) => void;+ const blockedLimit = new Promise<AccountLimitInfo | null>((resolve) => {+ releaseLimit = resolve;+ });+ const local = makeController({+ getAccountLimit: async () => {+ limitCalls += 1;+ return blockedLimit;+ },+ });+ await startGoal(local);+ const sendsBeforeStop = local.session.sends.length;++ // continue 裁决会在账号限额查询处跨 async 边界。Stop 必须让这条旧 finalize+ // 失效,查询回来后不能再以旧 active 快照覆盖 pauseGoal 写下的 paused。+ local.session.emitGoalTurn({+ toolUse: true,+ verdictJson: '```json\n{"goal_status":"continue","reason":"late finalize"}\n```',+ tokens: 20,+ });+ await vi.waitFor(() => expect(limitCalls).toBe(1));++ await local.controller.pauseGoal('s1');+ releaseLimit(null);+ await tick();++ expect((await local.storage.get('s1'))?.status).toBe('paused');+ expect(local.session.sends).toHaveLength(sendsBeforeStop);+ });++ it('keeps repeated Stop behind an already-issued finalize write so paused wins last', async () => {+ const local = makeController();+ await startGoal(local);+ const originalUpdate = local.storage.update.bind(local.storage);+ let markFinalizeWriteStarted!: () => void;+ const finalizeWriteStarted = new Promise<void>((resolve) => {+ markFinalizeWriteStarted = resolve;+ });+ let releaseFinalizeWrite!: () => void;+ const blockedFinalizeWrite = new Promise<void>((resolve) => {+ releaseFinalizeWrite = resolve;+ });+ vi.spyOn(local.storage, 'update').mockImplementationOnce(async (sessionId, patch) => {+ markFinalizeWriteStarted();+ await blockedFinalizeWrite;+ return originalUpdate(sessionId, patch);+ });+ const sendsBeforeStop = local.session.sends.length;++ local.session.emitGoalTurn({+ toolUse: true,+ verdictJson: '```json\n{"goal_status":"continue","reason":"late finalize"}\n```',+ tokens: 20,+ });+ await finalizeWriteStarted;++ const updatesBeforeStop = local.updates.length;+ let firstSettled = false;+ let secondSettled = false;+ const firstStop = local.controller.pauseGoal('s1');+ void firstStop.then(() => { firstSettled = true; });+ const secondStop = local.controller.pauseGoal('s1');+ void secondStop.then(() => { secondSettled = true; });+ await tick();+ expect(firstSettled).toBe(false);+ expect(secondSettled).toBe(false);++ releaseFinalizeWrite();+ await Promise.all([firstStop, secondStop]);+ await tick();++ expect(await local.storage.get('s1')).toMatchObject({+ status: 'paused',+ turnsUsed: 1,+ tokensUsed: 20,+ });+ expect(local.session.sends).toHaveLength(sendsBeforeStop);+ expect(+ local.updates.slice(updatesBeforeStop).some((update) => update.goal?.status === 'active'),+ ).toBe(false);+ });++ it('lets Stop persist paused while completion-message persistence is still pending', async () => {+ let completionCalls = 0;+ let releaseCompletion!: () => void;+ const blockedCompletion = new Promise<void>((resolve) => {+ releaseCompletion = resolve;+ });+ const local = makeController({+ persistGoalCompletion: async () => {+ completionCalls += 1;+ await blockedCompletion;+ },+ });+ await startGoal(local);++ local.session.emitGoalTurn({+ toolUse: true,+ verdictJson: '```json\n{"goal_status":"complete","reason":"done"}\n```',+ });+ await vi.waitFor(() => expect(completionCalls).toBe(1));++ await local.controller.pauseGoal('s1');+ expect((await local.storage.get('s1'))?.status).toBe('paused');+ expect(local.updates.filter((update) => update.goal === null)).toHaveLength(0);++ releaseCompletion();+ await tick();++ expect(await local.storage.get('s1')).toBeNull();+ expect(local.updates.at(-1)).toEqual({ sessionId: 's1', goal: null });+ expect(local.updates.filter((update) => update.goal === null)).toHaveLength(1);+ });++ it('finishes the completion commit if Stop arrives while clearing goal storage', 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));++ await local.controller.pauseGoal('s1');+ expect((await local.storage.get('s1'))?.status).toBe('paused');+ releaseClear();+ await tick();++ expect(await local.storage.get('s1')).toBeNull();+ expect(local.updates.at(-1)).toEqual({ sessionId: 's1', goal: null });+ });++ it('waits for an old completion clear before creating a replacement Goal', 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, 'completed objective');++ local.session.emitGoalTurn({+ toolUse: true,+ verdictJson: '```json\n{"goal_status":"complete","reason":"done"}\n```',+ });+ await vi.waitFor(() => expect(clearCalls).toBe(1));+ await local.controller.pauseGoal('s1');++ let replacementSettled = false;+ const replacement = local.controller.setGoal({+ sessionId: 's1',+ objective: 'replacement objective',+ });+ void replacement.then(() => { replacementSettled = true; });+ await tick();+ expect(replacementSettled).toBe(false);+ expect((await local.storage.get('s1'))?.status).toBe('paused');++ releaseClear();+ await expect(replacement).resolves.toMatchObject({+ status: 'active',+ objective: 'replacement objective',+ });+ expect(await local.storage.get('s1')).toMatchObject({+ status: 'active',+ objective: 'replacement objective',+ });+ expect(local.updates.at(-1)?.goal).toMatchObject({+ status: 'active',+ objective: 'replacement objective',+ });+ });+it('resumeGoal resumes a paused goal: preserves counters, fires a continuation', async () => {await startGoal(h);h.session.emitGoalTurn({ verdictJson: '```json\n{"goal_status":"continue","reason":""}\n```', tokens: 30 });@@ -842,6 +1714,139 @@ describe('GoalController', () => {expect(h.session.sends.length).toBe(sendsBeforeResume + 1);});+ it('keeps Stop behind every active write from concurrent Resume calls', async () => {+ const local = makeController();+ await local.storage.set(seededGoal({ status: 'paused', lastReason: 'paused by user' }));+ const originalUpdate = local.storage.update.bind(local.storage);+ let activeWrites = 0;+ let releaseFirst!: () => void;+ const blockedFirst = new Promise<void>((resolve) => {+ releaseFirst = resolve;+ });+ let releaseSecond!: () => void;+ const blockedSecond = new Promise<void>((resolve) => {+ releaseSecond = resolve;+ });+ vi.spyOn(local.storage, 'update').mockImplementation(async (sessionId, patch) => {+ if (patch.status === 'active') {+ activeWrites += 1;+ await (activeWrites === 1 ? blockedFirst : blockedSecond);+ }+ return originalUpdate(sessionId, patch);+ });++ const firstResume = local.controller.resumeGoal('s1');+ const secondResume = local.controller.resumeGoal('s1');+ await vi.waitFor(() => expect(activeWrites).toBe(2));+ releaseFirst();+ await firstResume;++ const updatesBeforeStop = local.updates.length;+ let stopSettled = false;+ const stop = local.controller.pauseGoal('s1');+ void stop.then(() => { stopSettled = true; });+ await tick();+ expect(stopSettled).toBe(false);++ releaseSecond();+ await Promise.all([secondResume, stop]);++ expect((await local.storage.get('s1'))?.status).toBe('paused');+ expect(+ local.updates.slice(updatesBeforeStop).some((update) => update.goal?.status === 'active'),+ ).toBe(false);+ });++ it('does not bind Resume to the old vendor turn before Stop reaches idle', async () => {+ let sessionInTurn = false;+ const local = makeController({ isSessionInTurn: () => sessionInTurn });+ await startGoal(local);+ await local.controller.pauseGoal('s1');+ const sendsBeforeResume = local.session.sends.length;++ sessionInTurn = true;+ await local.controller.pauseGoal('s1'); // 连续第二次 Stop 也必须保留同一取消边界。+ await local.controller.resumeGoal('s1');+ expect((await local.storage.get('s1'))?.status).toBe('paused');+ expect(local.session.sends).toHaveLength(sendsBeforeResume);++ // 旧 abort terminal 在 cancelled boundary 期间没有 listener,不能结算到下一代。+ local.session.emitErrorTurn({ message: 'AbortError: interrupted' });+ sessionInTurn = false;+ await local.controller.resumeGoal('s1');++ expect((await local.storage.get('s1'))?.status).toBe('active');+ expect(local.session.sends).toHaveLength(sendsBeforeResume + 1);+ });++ it('does not let an older Resume consume the fresh boundary from a later Stop', async () => {+ await startGoal(h);+ await h.controller.pauseGoal('s1');+ const paused = await h.storage.get('s1');+ const sendsBeforeResume = h.session.sends.length;+ let releaseGet!: (state: GoalState | null) => void;+ const blockedGet = new Promise<GoalState | null>((resolve) => {+ releaseGet = resolve;+ });+ const getSpy = vi.spyOn(h.storage, 'get').mockReturnValueOnce(blockedGet);++ const olderResume = h.controller.resumeGoal('s1');+ await vi.waitFor(() => expect(getSpy).toHaveBeenCalledTimes(1));+ await h.controller.pauseGoal('s1');+ releaseGet(paused);+ await olderResume;++ expect((await h.storage.get('s1'))?.status).toBe('paused');+ expect(h.session.sends).toHaveLength(sendsBeforeResume);+ });++ it('keeps a manual Resume paused when the session cannot hydrate, then allows retry', async () => {+ await startGoal(h);+ await h.controller.pauseGoal('s1');+ const sendsBeforeResume = h.session.sends.length;++ h.setHydratable(false);+ await h.controller.resumeGoal('s1');+ expect((await h.storage.get('s1'))?.status).toBe('paused');+ expect(h.session.sends).toHaveLength(sendsBeforeResume);++ h.setHydratable(true);+ await h.controller.resumeGoal('s1');+ expect((await h.storage.get('s1'))?.status).toBe('active');+ expect(h.session.sends).toHaveLength(sendsBeforeResume + 1);+ });++ it('does not reattach or emit stale active when Stop cancels resume during ensureSession', async () => {+ const liveSession = new FakeSession('s1');+ let ensureCalls = 0;+ let releaseEnsure!: (session: SessionLike | undefined) => void;+ const blockedEnsure = new Promise<SessionLike | undefined>((resolve) => {+ releaseEnsure = resolve;+ });+ const local = makeController({+ getSession: () => liveSession,+ ensureSession: async () => {+ ensureCalls += 1;+ return ensureCalls <= 2 ? liveSession : blockedEnsure;+ },+ });+ await startGoal(local);+ await local.controller.pauseGoal('s1');+ const sendsBeforeResume = liveSession.sends.length;++ const resumePromise = local.controller.resumeGoal('s1');+ await vi.waitFor(() => expect(ensureCalls).toBe(3));+ await local.controller.pauseGoal('s1');+ expect((await local.storage.get('s1'))?.status).toBe('paused');++ releaseEnsure(liveSession);+ await resumePromise;++ expect((await local.storage.get('s1'))?.status).toBe('paused');+ expect(local.updates.at(-1)?.goal?.status).toBe('paused');+ expect(liveSession.sends).toHaveLength(sendsBeforeResume);+ });+it('resumeGoal is a no-op for a non-paused/blocked goal (e.g. active)', async () => {await startGoal(h);const sends = h.session.sends.length;@@ -858,6 +1863,27 @@ describe('GoalController', () => {expect(h.session.sends.at(-1)?.content).toContain('keep going');});+ 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);+ let releaseList!: (states: GoalState[]) => void;+ const blockedList = new Promise<GoalState[]>((resolve) => {+ releaseList = resolve;+ });+ vi.spyOn(h.storage, 'listActive').mockReturnValueOnce(blockedList);++ const startupResume = h.controller.resumeActiveGoals();+ await h.controller.pauseGoal('s1');+ expect((await h.storage.get('s1'))?.status).toBe('paused');++ releaseList([active]);+ await startupResume;++ expect((await h.storage.get('s1'))?.status).toBe('paused');+ expect(h.updates.at(-1)?.goal?.status).toBe('paused');+ expect(h.session.sends).toHaveLength(0);+ });+it('resumeOnOpen 在释放 route 锁前挂 listener,并在会话随即关闭后迁移到重建会话', async () => {const firstSession = new FakeSession('s1', 'claude-code');const recreatedSession = new FakeSession('s1', 'claude-code');@@ -945,6 +1971,181 @@ describe('GoalController', () => {expect(h.updates.at(-1)?.goal?.objective).toBe('整理工作环境');});+ it('keeps a clarification objective and marker committed before a later Stop settles', async () => {+ const markers: string[] = [];+ let releaseMarker!: () => void;+ const blockedMarker = new Promise<void>((resolve) => {+ releaseMarker = resolve;+ });+ const local = makeController({+ persistUserMessage: async (_sessionId, content, opts) => {+ if (!opts?.goalObjective?.updated) return;+ markers.push(content);+ await blockedMarker;+ },+ });+ await local.storage.set(+ seededGoal({ status: 'active', objective: 'old objective', turnsUsed: 0 }),+ );++ const clarification = local.controller.applyClarificationAnswer(+ 's1',+ { q: 'clarified objective' },+ [{ options: [{ label: 'old objective' }, { label: 'clarified objective' }] }],+ );+ await vi.waitFor(() => expect(markers).toEqual(['clarified objective']));+ expect(await local.storage.get('s1')).toMatchObject({+ status: 'active',+ objective: 'clarified objective',+ });++ let stopSettled = false;+ const stop = local.controller.pauseGoal('s1').then(() => {+ stopSettled = true;+ });+ await tick();+ expect(stopSettled).toBe(false);++ releaseMarker();+ await Promise.all([clarification, stop]);+ expect(await local.storage.get('s1')).toMatchObject({+ status: 'paused',+ objective: 'clarified objective',+ });+ expect(markers).toEqual(['clarified objective']);++ await local.controller.resumeGoal('s1');+ await local.controller.applyClarificationAnswer(+ 's1',+ { q: 'second objective' },+ [{ options: [{ label: 'clarified objective' }, { label: 'second objective' }] }],+ );+ expect((await local.storage.get('s1'))?.objective).toBe('clarified objective');+ expect(markers).toEqual(['clarified objective']);+ });++ it('releases only its own clarification claim when persistence fails after Stop takes over', async () => {+ const local = makeController();+ await local.storage.set(+ seededGoal({ status: 'active', objective: 'old objective', turnsUsed: 0 }),+ );+ let markUpdateStarted!: () => void;+ const updateStarted = new Promise<void>((resolve) => {+ markUpdateStarted = resolve;+ });+ let releaseUpdate!: () => void;+ const blockedUpdate = new Promise<void>((resolve) => {+ releaseUpdate = resolve;+ });+ vi.spyOn(local.storage, 'update').mockImplementationOnce(async () => {+ markUpdateStarted();+ await blockedUpdate;+ throw new Error('clarification write failed');+ });++ const clarification = local.controller.applyClarificationAnswer(+ 's1',+ { q: 'failed objective' },+ [{ options: [{ label: 'old objective' }, { label: 'failed objective' }] }],+ );+ await updateStarted;+ const stop = local.controller.pauseGoal('s1');+ releaseUpdate();++ await expect(clarification).rejects.toThrow('clarification write failed');+ await stop;+ expect(await local.storage.get('s1')).toMatchObject({+ status: 'paused',+ objective: 'old objective',+ });++ await local.controller.resumeGoal('s1');+ await local.controller.applyClarificationAnswer(+ 's1',+ { q: 'retry objective' },+ [{ options: [{ label: 'old objective' }, { label: 'retry objective' }] }],+ );+ expect(await local.storage.get('s1')).toMatchObject({+ status: 'active',+ objective: 'retry objective',+ });+ expect(local.userMessages.filter((message) => message.updated === true)).toEqual([+ { sessionId: 's1', content: 'retry objective', updated: true },+ ]);+ });++ it('ignores a clarification answer that arrives after its first turn has begun finalizing', async () => {+ const local = makeController();+ await startGoal(local, 'old objective');+ const initial = await local.storage.get('s1');+ let releaseGet!: (state: GoalState | null) => void;+ const blockedGet = new Promise<GoalState | null>((resolve) => {+ releaseGet = resolve;+ });+ const getSpy = vi.spyOn(local.storage, 'get').mockReturnValueOnce(blockedGet);++ const clarification = local.controller.applyClarificationAnswer(+ 's1',+ { q: 'late objective' },+ [{ options: [{ label: 'old objective' }, { label: 'late objective' }] }],+ );+ await vi.waitFor(() => expect(getSpy).toHaveBeenCalledTimes(1));+ local.session.emitGoalTurn({+ toolUse: true,+ verdictJson: '```json\n{"goal_status":"continue","reason":"keep going"}\n```',+ tokens: 10,+ });+ await vi.waitFor(async () => expect((await local.storage.get('s1'))?.turnsUsed).toBe(1));++ releaseGet(initial);+ await clarification;+ expect(await local.storage.get('s1')).toMatchObject({+ turnsUsed: 1,+ objective: 'old objective',+ });+ expect(local.userMessages.filter((message) => message.updated === true)).toHaveLength(0);+ });++ it('allows only one concurrent clarification answer to commit per goal', async () => {+ const local = makeController();+ await startGoal(local, 'old objective');+ const initial = await local.storage.get('s1');+ let releaseFirstGet!: (state: GoalState | null) => void;+ let releaseSecondGet!: (state: GoalState | null) => void;+ const firstGet = new Promise<GoalState | null>((resolve) => {+ releaseFirstGet = resolve;+ });+ const secondGet = new Promise<GoalState | null>((resolve) => {+ releaseSecondGet = resolve;+ });+ const getSpy = vi+ .spyOn(local.storage, 'get')+ .mockReturnValueOnce(firstGet)+ .mockReturnValueOnce(secondGet);++ const first = local.controller.applyClarificationAnswer(+ 's1',+ { q: 'first objective' },+ [{ options: [{ label: 'old objective' }, { label: 'first objective' }] }],+ );+ const second = local.controller.applyClarificationAnswer(+ 's1',+ { q: 'second objective' },+ [{ options: [{ label: 'old objective' }, { label: 'second objective' }] }],+ );+ await vi.waitFor(() => expect(getSpy).toHaveBeenCalledTimes(2));+ releaseFirstGet(initial);+ releaseSecondGet(initial);+ await Promise.all([first, second]);++ expect((await local.storage.get('s1'))?.objective).toBe('first objective');+ expect(+ local.userMessages+ .filter((message) => message.updated === true)+ .map((message) => message.content),+ ).toEqual(['first objective']);+ });+it('applyClarificationAnswer does NOT rewrite for an arbitrary first-turn work question (no verbatim-goal option)', async () => {// reviewer #354:模型首轮问个普通工作问题(选项是环境名,不含原目标 verbatim)→ 不得被当成目标改写。await h.storage.set(seededGoal({ status: 'active', objective: '修复登录 bug', turnsUsed: 0 }));@@ -1072,6 +2273,94 @@ describe('GoalController', () => {expect(h.session.sends.length).toBe(sendsBefore); // 不触发新一轮});+ it('rechecks the latest counters before lowering an active maxTurns to budgetLimited', async () => {+ const local = makeController();+ await startGoal(local);+ const originalUpdate = local.storage.update.bind(local.storage);+ let markFinalizeWriteStarted!: () => void;+ const finalizeWriteStarted = new Promise<void>((resolve) => {+ markFinalizeWriteStarted = resolve;+ });+ let releaseFinalizeWrite!: () => void;+ const blockedFinalizeWrite = new Promise<void>((resolve) => {+ releaseFinalizeWrite = resolve;+ });+ vi.spyOn(local.storage, 'update').mockImplementationOnce(async (sessionId, patch) => {+ markFinalizeWriteStarted();+ await blockedFinalizeWrite;+ return originalUpdate(sessionId, patch);+ });++ local.session.emitGoalTurn({+ toolUse: true,+ verdictJson: '```json\n{"goal_status":"continue","reason":"one turn used"}\n```',+ tokens: 25,+ });+ await finalizeWriteStarted;++ const limitUpdate = local.controller.updateGoal('s1', { maxTurns: 1 });+ await tick();+ expect((await local.storage.get('s1'))?.turnsUsed).toBe(0);++ releaseFinalizeWrite();+ await expect(limitUpdate).resolves.toMatchObject({+ status: 'budgetLimited',+ maxTurns: 1,+ turnsUsed: 1,+ });+ expect(await local.storage.get('s1')).toMatchObject({+ status: 'budgetLimited',+ maxTurns: 1,+ turnsUsed: 1,+ });+ });++ it('rechecks budget limits when a turn finalizes after the edit read but before its write', async () => {+ const local = makeController();+ await startGoal(local);+ const originalUpdate = local.storage.update.bind(local.storage);+ let updateCalls = 0;+ let markLimitWriteStarted!: () => void;+ const limitWriteStarted = new Promise<void>((resolve) => {+ markLimitWriteStarted = resolve;+ });+ let releaseLimitWrite!: () => void;+ const blockedLimitWrite = new Promise<void>((resolve) => {+ releaseLimitWrite = resolve;+ });+ vi.spyOn(local.storage, 'update').mockImplementation(async (sessionId, patch) => {+ updateCalls += 1;+ if (updateCalls === 1) {+ markLimitWriteStarted();+ await blockedLimitWrite;+ }+ return originalUpdate(sessionId, patch);+ });++ const limitUpdate = local.controller.updateGoal('s1', { maxTurns: 1 });+ await limitWriteStarted;+ local.session.emitGoalTurn({+ toolUse: true,+ verdictJson: '```json\n{"goal_status":"continue","reason":"finished concurrently"}\n```',+ tokens: 25,+ });+ await vi.waitFor(async () => {+ expect((await local.storage.get('s1'))?.turnsUsed).toBe(1);+ });++ releaseLimitWrite();+ await expect(limitUpdate).resolves.toMatchObject({+ status: 'budgetLimited',+ maxTurns: 1,+ turnsUsed: 1,+ });+ expect(await local.storage.get('s1')).toMatchObject({+ status: 'budgetLimited',+ maxTurns: 1,+ turnsUsed: 1,+ });+ });+it('updateGoal transitions to budgetLimited when budgetTokens is lowered below tokensUsed', async () => {await h.storage.set(seededGoal({ status: 'active', budgetTokens: 5000, tokensUsed: 3000 }));const res = await h.controller.updateGoal('s1', { budgetTokens: 1000 });@@ -1126,6 +2415,8 @@ describe('GoalController', () => {await expect(h.controller.updateGoal('s1', { maxTurns: 0 })).rejects.toThrow('positive number');await expect(h.controller.updateGoal('s1', { budgetTokens: Number.NaN })).rejects.toThrow('positive number');await expect(h.controller.updateGoal('s1', { objective: ' ' })).rejects.toThrow('objective must not be empty');+ const internals = h.controller as unknown as { turns: Map<string, unknown> };+ expect(internals.turns.has('s1')).toBe(false);});it('updateGoal accepts null as no limit and can unblock budgetLimited', async () => {@@ -1173,6 +2464,74 @@ describe('GoalController', () => {expect(h.session.sends.length).toBeGreaterThanOrEqual(2); // 自动续了一轮});+ it('Stop cancels auto-resume while session hydration is pending without persisting a recovery notice', async () => {+ let ensureCalls = 0;+ let releaseEnsure!: (session: SessionLike | undefined) => void;+ const blockedEnsure = new Promise<SessionLike | undefined>((resolve) => {+ releaseEnsure = resolve;+ });+ const liveSession = new FakeSession('s1');+ const local = makeController({+ getSession: () => liveSession,+ ensureSession: async () => {+ ensureCalls += 1;+ return blockedEnsure;+ },+ });+ await local.storage.set(seededGoal({+ status: 'usageLimited',+ usageResetAt: 1_000,+ lastReason: 'usage limit reached',+ }));++ const autoResume = (+ local.controller as unknown as { autoResumeFromUsageLimit(id: string): Promise<void> }+ ).autoResumeFromUsageLimit('s1');+ await vi.waitFor(() => expect(ensureCalls).toBe(1));+ await local.controller.pauseGoal('s1');+ releaseEnsure(liveSession);+ await autoResume;++ expect(local.notices).toEqual([]);+ expect(await local.storage.get('s1')).toMatchObject({ status: 'paused' });+ expect(local.updates.at(-1)?.goal?.status).toBe('paused');+ expect(liveSession.sends).toHaveLength(0);+ });++ it('Stop prevents resume and dispatch when recovery notice persistence is pending', async () => {+ let noticeCalls = 0;+ let releaseNotice!: () => void;+ const blockedNotice = new Promise<void>((resolve) => {+ releaseNotice = resolve;+ });+ const liveSession = new FakeSession('s1');+ const local = makeController({+ getSession: () => liveSession,+ ensureSession: async () => liveSession,+ persistGoalNotice: async () => {+ noticeCalls += 1;+ await blockedNotice;+ },+ });+ await local.storage.set(seededGoal({+ status: 'usageLimited',+ usageResetAt: 1_000,+ lastReason: 'usage limit reached',+ }));++ const autoResume = (+ local.controller as unknown as { autoResumeFromUsageLimit(id: string): Promise<void> }+ ).autoResumeFromUsageLimit('s1');+ await vi.waitFor(() => expect(noticeCalls).toBe(1));+ await local.controller.pauseGoal('s1');+ releaseNotice();+ await autoResume;++ expect(await local.storage.get('s1')).toMatchObject({ status: 'paused' });+ expect(local.updates.at(-1)?.goal?.status).toBe('paused');+ expect(liveSession.sends).toHaveLength(0);+ });+it('resumeGoal recovers a usageLimited goal (manual), preserving counts', async () => {h.setAccountLimit({ limited: true, resetAtMs: 3_601_000 });await startGoal(h);diff --git a/apps/desktop/src/main/goal-host/controller.ts b/apps/desktop/src/main/goal-host/controller.tsindex c60e2f0430..ebdb124e7a 100644--- a/apps/desktop/src/main/goal-host/controller.ts+++ b/apps/desktop/src/main/goal-host/controller.ts@@ -45,6 +45,16 @@ export class GoalControllerInputError extends Error {readonly code = 'INVALID_PARAMS';}+/** Goal 仍存在,但本次编辑已被更新的生命周期或状态覆盖。 */+export class GoalUpdateSupersededError extends Error {+ readonly code = 'PRECONDITION_FAILED';++ constructor() {+ super('goal changed while the update was being saved; review the latest state and try again');+ this.name = 'GoalUpdateSupersededError';+ }+}+function resolveLimitPatchValue(value: number | null | undefined): number | null {if (value === null) return null;if (typeof value === 'number' && Number.isFinite(value) && value > 0) {@@ -115,6 +125,15 @@ export function normalizeGoalUpdatePatch(patch: GoalUpdatePatch): GoalUpdatePatcreturn next;}+function goalStateMatchesPatch(state: GoalState, patch: GoalUpdatePatch): boolean {+ return (+ (!('objective' in patch) || state.objective === patch.objective) &&+ (!('maxTurns' in patch) || state.maxTurns === patch.maxTurns) &&+ (!('budgetTokens' in patch) || state.budgetTokens === patch.budgetTokens) &&+ (!('noProgressLimit' in patch) || state.noProgressLimit === patch.noProgressLimit)+ );+}+function exceedsGoalBudget(state: Pick<GoalState, 'maxTurns' | 'turnsUsed' | 'budgetTokens' | 'tokensUsed'>): boolean {return ((state.maxTurns != null && state.turnsUsed >= state.maxTurns) ||@@ -299,10 +318,31 @@ interface TurnAccumulator {tokensThisTurn: number;/** 本轮是否已 finalize(去重 done / 终止 error 双触发)。 */finalized: boolean;+ /** 正常 turn 换代只递增 generation,不替换整个 Goal 生命周期 owner。 */+ generation: number;+ /** 显式 Stop 正在把 paused 落盘;迟到事件与自动恢复都必须停在这条边界外。 */+ cancelled: boolean;+ /** 本生命周期已经发出、但尚未全部 settle 的 Goal 状态持久化写入。 */+ pendingPersistence: Promise<void> | null;+ /** 已进入“达成记录 → clear”顺序提交区;Stop 不等待,但新目标必须等旧 clear 结束。 */+ pendingCompletion: Promise<void> | null;}-function freshTurn(): TurnAccumulator {- return { text: '', sawToolUse: false, tokensThisTurn: 0, finalized: false };+function freshTurn(+ cancelled = false,+ pendingPersistence: Promise<void> | null = null,+ pendingCompletion: Promise<void> | null = null,+): TurnAccumulator {+ return {+ text: '',+ sawToolUse: false,+ tokensThisTurn: 0,+ finalized: false,+ generation: 0,+ cancelled,+ pendingPersistence,+ pendingCompletion,+ };}// ── 控制器 ──────────────────────────────────────────────────────────────────@@ -317,13 +357,14 @@ export class GoalController {*/private readonly listenerSessions = new Map<string, SessionLike>();private readonly turns = new Map<string, TurnAccumulator>();- private readonly firing = new Set<string>();+ /** 正在派发的 fire 及其 owner;旧代 finally 只能清理自己,不能删掉 Resume 新代。 */+ private readonly firing = new Map<string, object>();private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();/** goal controller 自己发起且尚未收到终止事件的 turn。用于编辑时区分 goal turn / user turn。 */private readonly goalTurnsInFlight = new Set<string>();- /** (Option B)已经用 AskUserQuestion 答案改写过目标的会话 —— 每个目标只允许澄清改写一次,- * 防首轮内模型二次提问(如工作型提问)把目标覆盖错。setGoal(新建/编辑)与 clearGoal 时重置。 */- private readonly clarificationApplied = new Set<string>();+ /** (Option B)已经用 AskUserQuestion 答案改写、或正在提交改写的会话。token 让失败调用+ * 只能释放自己的 claim,不能误删新目标 / 后续调用的闸门。setGoal 与 clearGoal 时重置。 */+ private readonly clarificationApplied = new Map<string, object>();/** usageLimited 到点自动续跑 timer,按 sessionId。**stopSession 不清它**(它要熬到限额重置),* 只在 clearGoal / resumeGoal / dispose 取消。 */private readonly usageResumeTimers = new Map<string, ReturnType<typeof setTimeout>>();@@ -352,139 +393,332 @@ export class GoalController {const sessionId = input.sessionId;const objective = input.objective.trim();if (!objective) throw new GoalControllerInputError('objective must not be empty');- // 新建 / 编辑目标 → 重置"已澄清"闸门(新目标允许重新澄清改写一次)。- this.clarificationApplied.delete(sessionId);+ let entryBoundary = this.turns.get(sessionId);// 连续过载计数是 per-goal 状态:换目标(含替换既有目标的编辑路径)必须清零,// 否则上一个目标撞过载上限变 blocked 后,新目标会继承耗尽的计数,第一次容量// 错误就直接 blocked、拿不到自己的重试预算。this.consecutiveOverloadTurns.delete(sessionId);+ if (entryBoundary?.pendingCompletion) {+ // 旧目标已经进入“达成记录 → clear”顺序提交区。新 /goal 先同步接管 owner,+ // 等旧 clear 完成后再读行;否则旧 clear 可能在新目标 upsert 之后把它删掉。+ const takeoverBoundary = freshTurn(+ false,+ entryBoundary.pendingPersistence,+ entryBoundary.pendingCompletion,+ );+ this.stopSession(sessionId);+ this.turns.set(sessionId, takeoverBoundary);+ await this.awaitPendingLifecycle(takeoverBoundary);+ if (this.turns.get(sessionId) !== takeoverBoundary) return null;+ entryBoundary = takeoverBoundary;+ }const existing = await this.deps.storage.get(sessionId);+ if (this.turns.get(sessionId) !== entryBoundary) return null;const ts = this.now();if (existing) {const session = await this.deps.ensureSession(sessionId);+ if (this.turns.get(sessionId) !== entryBoundary) return null;if (!session) {this.deps.logger.warn('[goal] setGoal edit: no live session', { sessionId });return null;}- if (this.isBusy(sessionId)) {+ const sessionWasBusy = this.isBusy(sessionId);+ if (sessionWasBusy) {if (!this.goalTurnsInFlight.has(sessionId)) {throw new GoalControllerInputError('current conversation is still running; edit the goal after it becomes idle');}// 先 stopSession(detach listener + 清 goalTurnsInFlight/turn),再 abort:否则 abort 触发的// 终止事件可能在 detach 前被 onEvent 消费 → 并发 finalizeTurn 把下面刚写的 active 覆盖成// paused(用户编辑目标后 chip 误显"暂停")。detach 在前,abort 的终止事件就不再触达裁决。- this.stopSession(sessionId);- await session.abort();- } else {- this.stopSession(sessionId);}- this.cancelUsageResume(sessionId);- const updated = await this.deps.storage.update(sessionId, {+ const previousBoundary = this.turns.get(sessionId);+ this.stopSession(sessionId);+ const editBoundary = freshTurn(+ false,+ previousBoundary?.pendingPersistence ?? null,+ previousBoundary?.pendingCompletion ?? null,+ );+ this.turns.set(sessionId, editBoundary);+ try {+ if (sessionWasBusy) {+ await session.abort();+ if (this.turns.get(sessionId) !== editBoundary) return null;+ }+ await this.awaitPendingLifecycle(editBoundary);+ if (this.turns.get(sessionId) !== editBoundary) return null;+ this.cancelUsageResume(sessionId);+ const updated = await this.trackPersistence(+ editBoundary,+ this.deps.storage.update(sessionId, {+ objective,+ status: 'active',+ noProgressStreak: 0,+ usageResetAt: null,+ lastReason: null,+ updatedAt: ts,+ }),+ async (persisted) => {+ if (!persisted) return;+ // 新目标已经提交后才重置澄清闸门;被 Stop 取消或写入失败的 setGoal+ // 不能重新开放旧目标的澄清改写。+ this.clarificationApplied.delete(sessionId);+ await this.deps.persistUserMessage?.(sessionId, objective, {+ goalObjective: { updated: true },+ });+ },+ );+ if (this.turns.get(sessionId) !== editBoundary) return null;+ if (!updated) {+ this.turns.delete(sessionId);+ return null;+ }+ this.resetTurn(sessionId);+ const activeBoundary = this.turns.get(sessionId);+ this.attachListener(sessionId);+ this.emit(updated);+ if (this.turns.get(sessionId) === activeBoundary) {+ await this.fireTurn(sessionId);+ }+ return updated;+ } catch (error) {+ if (this.turns.get(sessionId) === editBoundary) this.turns.delete(sessionId);+ throw error;+ }+ }++ const limits = input.limits ?? this.deps.getDefaults();+ const previousBoundary = this.turns.get(sessionId);+ this.stopSession(sessionId);+ const createBoundary = freshTurn(+ false,+ previousBoundary?.pendingPersistence ?? null,+ previousBoundary?.pendingCompletion ?? null,+ );+ this.turns.set(sessionId, createBoundary);+ try {+ // 先活化(resume)会话,再据活化后的会话定 agentKind:dormant(重启后尚未活化)会话此刻+ // getSession 为空,若直接 fallback 'claude-code' 会把 Codex 目标错存成 claude-code,后续+ // getAccountLimit 读错账号配额快照 → Codex 限流目标的 reset/auto-resume 错位(reviewer #354)。+ const ensured = await this.deps.ensureSession(sessionId);+ if (this.turns.get(sessionId) !== createBoundary) return null;+ 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';+ const state: GoalState = {+ sessionId,objective,status: 'active',+ budgetTokens: limits.budgetTokens,+ maxTurns: limits.maxTurns,+ noProgressLimit: limits.noProgressLimit,+ turnsUsed: 0,+ tokensUsed: 0,noProgressStreak: 0,usageResetAt: null,lastReason: null,+ agentKind,+ startedAt: ts,updatedAt: ts,+ };+ await this.trackPersistence(createBoundary, this.deps.storage.upsert(state), async () => {+ this.clarificationApplied.delete(sessionId);+ // 目标创建 → 落一条目标文案作对话起点(updated:false),**只此一次**。+ // 不放进 fireTurn(Fix A 后 'first' 可能重发,会重复落库;编辑路径自己落 updated:true)。+ await this.deps.persistUserMessage?.(sessionId, objective, {+ goalObjective: { updated: false },+ });});- if (!updated) return null;+ if (this.turns.get(sessionId) !== createBoundary) return null;this.resetTurn(sessionId);+ const activeBoundary = this.turns.get(sessionId);this.attachListener(sessionId);- this.emit(updated);- // 编辑目标 → 在对话里落一条「目标已更新」标记消息(气泡徽标),排在续轮之前。- await this.deps.persistUserMessage?.(sessionId, objective, { goalObjective: { updated: true } });- await this.fireTurn(sessionId);- return updated;+ this.emit(state);+ if (this.turns.get(sessionId) === activeBoundary) {+ await this.fireTurn(sessionId);+ }+ return state;+ } catch (error) {+ if (this.turns.get(sessionId) === createBoundary) this.turns.delete(sessionId);+ throw error;}-- const limits = input.limits ?? this.deps.getDefaults();- // 先活化(resume)会话,再据活化后的会话定 agentKind:dormant(重启后尚未活化)会话此刻- // getSession 为空,若直接 fallback 'claude-code' 会把 Codex 目标错存成 claude-code,后续- // getAccountLimit 读错账号配额快照 → Codex 限流目标的 reset/auto-resume 错位(reviewer #354)。- const ensured = await this.deps.ensureSession(sessionId);- const agentKind = input.agentKind ?? ensured?.agentKind ?? this.deps.getSession(sessionId)?.agentKind ?? 'claude-code';- const state: GoalState = {- sessionId,- objective,- status: 'active',- budgetTokens: limits.budgetTokens,- maxTurns: limits.maxTurns,- noProgressLimit: limits.noProgressLimit,- turnsUsed: 0,- tokensUsed: 0,- noProgressStreak: 0,- usageResetAt: null,- lastReason: null,- agentKind,- startedAt: ts,- updatedAt: ts,- };- await this.deps.storage.upsert(state);- this.resetTurn(sessionId);- this.attachListener(sessionId);- this.emit(state);- // 目标创建 → 落一条目标文案作对话起点(updated:false),**只此一次**。- // 不放进 fireTurn(Fix A 后 'first' 可能重发,会重复落库;编辑路径自己落 updated:true)。- await this.deps.persistUserMessage?.(sessionId, objective, { goalObjective: { updated: false } });- await this.fireTurn(sessionId);- return state;}async updateGoal(sessionId: string, patch: GoalUpdatePatch): Promise<GoalState | null> {const normalized = normalizeGoalUpdatePatch(patch);- const state = await this.deps.storage.get(sessionId);- if (!state) return null;- const objectiveChanged = normalized.objective != null && normalized.objective !== state.objective;- const ts = this.now();- const changed = await this.deps.storage.update(sessionId, {- ...normalized,- updatedAt: ts,- });- if (!changed) return null;- // 改了目标内容 → 在对话里落一条「目标已更新」标记消息(气泡徽标),排在任何续轮之前。- if (objectiveChanged) {- await this.deps.persistUserMessage?.(sessionId, changed.objective, { goalObjective: { updated: true } });- }- let next = changed;- if (changed.status === 'budgetLimited' && !exceedsGoalBudget(changed)) {- const resumed = await this.deps.storage.update(sessionId, {- status: 'active',- lastReason: null,- updatedAt: this.now(),- });- if (resumed) {- next = resumed;- this.resetTurn(sessionId);- await this.deps.ensureSession(sessionId);- this.attachListener(sessionId);+ const existingBoundary = this.turns.get(sessionId);+ const operationBoundary = existingBoundary ?? freshTurn();+ const ownsOperationBoundary = existingBoundary === undefined;+ if (ownsOperationBoundary) this.turns.set(sessionId, operationBoundary);+ let entryGeneration = operationBoundary.generation;+ const entryChanged = (): boolean => {+ const current = this.turns.get(sessionId);+ return current !== operationBoundary || current.generation !== entryGeneration;+ };++ // `null` 只表示权威存储里确实没有 Goal。turn 收尾 / Stop 换代时重读当前行:+ // 本次 patch 仍在就按成功返回并广播最新状态;已被后续操作覆盖则明确报竞态,+ // 不能把生命周期取消伪装成 GOAL_NOT_FOUND,也不能把未应用的编辑谎报成功。+ const reconcileLifecycleChange = async (): Promise<GoalState | null> => {+ const readSettledState = async (): Promise<GoalState | null> => {+ while (true) {+ const boundary = this.turns.get(sessionId);+ await this.awaitPendingLifecycle(boundary);+ if (this.turns.get(sessionId) !== boundary) continue;+ const current = await this.deps.storage.get(sessionId);+ if (this.turns.get(sessionId) === boundary) return current;+ }+ };+ const current = await readSettledState();+ if (!current) return null;+ if (!goalStateMatchesPatch(current, normalized)) {+ throw new GoalUpdateSupersededError();}- } else if (next.status === 'active' && exceedsGoalBudget(next)) {- // 反向:把 active 目标的 maxTurns/budgetTokens 调小到已被 turnsUsed/tokensUsed 超过- // → 立即转 budgetLimited 并停续跑。否则 row 仍 active,下一轮 fireTurn 会越过新上限再- // 多跑一轮(预算守卫原本只在 turn 跑完后才生效;reviewer #354)。fireTurn preflight 再兜一层。- const limited = await this.deps.storage.update(sessionId, {- status: 'budgetLimited',- lastReason: 'budget limit lowered below current usage',- updatedAt: this.now(),- });- if (limited) {- next = limited;+ // 正常 turn 可能在本次编辑读完旧计数后才 finalize。patch 已成功并不代表后置+ // 预算条件仍成立;必须用 settle 后的最新 counters 再判一次,不能返回超限 active。+ if (current.status === 'active' && exceedsGoalBudget(current)) {+ const previousBoundary = this.turns.get(sessionId);this.stopSession(sessionId);+ const limitBoundary = freshTurn(+ true,+ previousBoundary?.pendingPersistence ?? null,+ previousBoundary?.pendingCompletion ?? null,+ );+ this.turns.set(sessionId, limitBoundary);+ await this.awaitPendingLifecycle(limitBoundary);+ if (this.turns.get(sessionId) !== limitBoundary) return reconcileLifecycleChange();+ const limited = await this.trackPersistence(+ limitBoundary,+ this.deps.storage.update(sessionId, {+ status: 'budgetLimited',+ lastReason: 'budget limit lowered below current usage',+ updatedAt: this.now(),+ }),+ );+ if (this.turns.get(sessionId) !== limitBoundary) return reconcileLifecycleChange();+ if (limited) {+ this.stopSession(sessionId);+ this.emit(limited);+ }+ return limited;+ }+ this.emit(current);+ return current;+ };++ try {+ await this.awaitPendingLifecycle(operationBoundary);+ if (this.turns.get(sessionId) !== operationBoundary) return reconcileLifecycleChange();+ entryGeneration = operationBoundary.generation;+ const state = await this.deps.storage.get(sessionId);+ if (entryChanged()) return reconcileLifecycleChange();+ if (!state) return null;+ const objectiveChanged =+ normalized.objective != null && normalized.objective !== state.objective;+ const ts = this.now();+ const preview = { ...state, ...normalized };+ const shouldLimit = state.status === 'active' && exceedsGoalBudget(preview);+ const persistObjectiveMarker = async (changed: GoalState | null): Promise<void> => {+ if (!objectiveChanged || !changed) return;+ await this.deps.persistUserMessage?.(sessionId, changed.objective, {+ goalObjective: { updated: true },+ });+ };++ let changed: GoalState | null;+ let limitBoundary: TurnAccumulator | undefined;+ if (shouldLimit) {+ // 降低上限是显式生命周期接管:同步摘掉旧 listener/timer,等旧 finalize 写完后,+ // 用同一条 UPDATE 同时提交新上限与 budgetLimited,避免暴露可被旧写覆盖的 active 中间态。+ const previousBoundary = this.turns.get(sessionId);+ this.stopSession(sessionId);+ limitBoundary = freshTurn(+ true,+ previousBoundary?.pendingPersistence ?? null,+ previousBoundary?.pendingCompletion ?? null,+ );+ this.turns.set(sessionId, limitBoundary);+ await this.awaitPendingLifecycle(limitBoundary);+ if (this.turns.get(sessionId) !== limitBoundary) return reconcileLifecycleChange();+ changed = await this.trackPersistence(+ limitBoundary,+ this.deps.storage.update(sessionId, {+ ...normalized,+ status: 'budgetLimited',+ lastReason: 'budget limit lowered below current usage',+ updatedAt: ts,+ }),+ persistObjectiveMarker,+ );+ if (this.turns.get(sessionId) !== limitBoundary) return reconcileLifecycleChange();+ if (!changed) {+ this.turns.delete(sessionId);+ return null;+ }+ } else {+ changed = await this.trackPersistence(+ operationBoundary,+ this.deps.storage.update(sessionId, {+ ...normalized,+ updatedAt: ts,+ }),+ persistObjectiveMarker,+ );+ if (entryChanged()) return reconcileLifecycleChange();+ }+ if (!changed) return null;+ if (shouldLimit) {+ if (this.turns.get(sessionId) !== limitBoundary) return reconcileLifecycleChange();+ this.stopSession(sessionId);+ }+ let next = changed;+ if (changed.status === 'budgetLimited' && !exceedsGoalBudget(changed)) {+ const previousBoundary = this.turns.get(sessionId);+ this.stopSession(sessionId);+ const resumeBoundary = freshTurn(+ false,+ previousBoundary?.pendingPersistence ?? null,+ previousBoundary?.pendingCompletion ?? null,+ );+ this.turns.set(sessionId, resumeBoundary);+ await this.awaitPendingLifecycle(resumeBoundary);+ if (this.turns.get(sessionId) !== resumeBoundary) return reconcileLifecycleChange();+ const resumed = await this.trackPersistence(+ resumeBoundary,+ this.deps.storage.update(sessionId, {+ status: 'active',+ lastReason: null,+ updatedAt: this.now(),+ }),+ );+ if (this.turns.get(sessionId) !== resumeBoundary) return reconcileLifecycleChange();+ if (resumed) {+ next = resumed;+ this.resetTurn(sessionId);+ await this.deps.ensureSession(sessionId);+ if (this.turns.get(sessionId) !== resumeBoundary) return reconcileLifecycleChange();+ this.attachListener(sessionId);+ } else if (this.turns.get(sessionId) === resumeBoundary) {+ this.turns.delete(sessionId);+ }+ }+ if (+ objectiveChanged &&+ (changed.status === 'paused' || changed.status === 'blocked' || changed.status === 'usageLimited')+ ) {+ await this.resumeGoal(sessionId);+ return reconcileLifecycleChange();+ }+ this.emit(next);+ if (next.status === 'active' && state.status === 'budgetLimited' && !this.isBusy(sessionId)) {+ this.scheduleContinuation(sessionId);+ }+ return next;+ } finally {+ if (ownsOperationBoundary && this.turns.get(sessionId) === operationBoundary) {+ this.turns.delete(sessionId);}}- if (- objectiveChanged &&- (changed.status === 'paused' || changed.status === 'blocked' || changed.status === 'usageLimited')- ) {- await this.resumeGoal(sessionId);- return this.deps.storage.get(sessionId);- }- this.emit(next);- if (next.status === 'active' && state.status === 'budgetLimited' && !this.isBusy(sessionId)) {- this.scheduleContinuation(sessionId);- }- return next;}/**@@ -507,19 +741,64 @@ export class GoalController {if (this.clarificationApplied.has(sessionId)) return; // 每目标只澄清改写一次const next = deriveObjectiveFromAnswers(answers);if (!next) return;- const state = await this.deps.storage.get(sessionId);- if (!state || state.status !== 'active') return;- if (state.turnsUsed !== 0) return;- // 确定性标记:只认 directive 约定形状的"目标澄清问题",否则不改写(见函数注释)。- if (!questionsLookLikeGoalClarification(questions, state.objective)) return;- if (next === state.objective) {- this.clarificationApplied.add(sessionId); // 选了"保持原目标"也算已澄清,封住后续覆盖- return;+ const existingBoundary = this.turns.get(sessionId);+ const operationBoundary = existingBoundary ?? freshTurn();+ const ownsOperationBoundary = existingBoundary === undefined;+ if (ownsOperationBoundary) this.turns.set(sessionId, operationBoundary);+ const entryGeneration = operationBoundary.generation;+ const isCurrentOperation = (): boolean =>+ this.turns.get(sessionId) === operationBoundary &&+ operationBoundary.generation === entryGeneration &&+ !operationBoundary.cancelled &&+ !operationBoundary.finalized;+ const clarificationClaim = {};+ const releaseClarificationClaim = (): void => {+ if (this.clarificationApplied.get(sessionId) === clarificationClaim) {+ this.clarificationApplied.delete(sessionId);+ }+ };+ let objectiveCommitted = false;+ try {+ await this.awaitPendingLifecycle(operationBoundary);+ if (!isCurrentOperation()) return;+ const state = await this.deps.storage.get(sessionId);+ if (!isCurrentOperation()) return;+ if (!state || state.status !== 'active') return;+ if (state.turnsUsed !== 0) return;+ // 确定性标记:只认 directive 约定形状的"目标澄清问题",否则不改写(见函数注释)。+ if (!questionsLookLikeGoalClarification(questions, state.objective)) return;+ // 入口 fast-path 之后可能已有另一个澄清调用完成了读取;在首次写入前同步 claim,+ // JS 同一事件循环内没有 await,保证每个目标最多一个答案进入提交路径。+ if (this.clarificationApplied.has(sessionId)) return;+ this.clarificationApplied.set(sessionId, clarificationClaim);+ if (next === state.objective) {+ return;+ }+ const updated = await this.trackPersistence(+ operationBoundary,+ this.deps.storage.update(sessionId, { objective: next, updatedAt: this.now() }),+ async (persisted) => {+ if (!persisted) return;+ objectiveCommitted = true;+ await this.deps.persistUserMessage?.(sessionId, next, {+ goalObjective: { updated: true },+ });+ },+ );+ if (!updated) {+ releaseClarificationClaim();+ return;+ }+ if (!isCurrentOperation()) return;+ if (updated) this.emit(updated);+ } catch (error) {+ if (!objectiveCommitted) releaseClarificationClaim();+ throw error;+ } finally {+ if (ownsOperationBoundary && this.turns.get(sessionId) === operationBoundary) {+ this.turns.delete(sessionId);+ }}- const updated = await this.deps.storage.update(sessionId, { objective: next, updatedAt: this.now() });- if (updated) this.emit(updated);- this.clarificationApplied.add(sessionId);- await this.deps.persistUserMessage?.(sessionId, next, { goalObjective: { updated: true } });}/** 清除目标(用户主动)。删行 + 停止一切续跑 + 取消 usage 自动续 + 通知 renderer 隐藏指示器。 */@@ -527,9 +806,20 @@ export class GoalController {this.clarificationApplied.delete(sessionId);this.consecutiveOverloadTurns.delete(sessionId);this.cancelUsageResume(sessionId);+ const previousBoundary = this.turns.get(sessionId);this.stopSession(sessionId);- await this.deps.storage.clear(sessionId);+ const clearBoundary = freshTurn(+ true,+ previousBoundary?.pendingPersistence ?? null,+ previousBoundary?.pendingCompletion ?? null,+ );+ this.turns.set(sessionId, clearBoundary);+ await this.awaitPendingLifecycle(clearBoundary);+ if (this.turns.get(sessionId) !== clearBoundary) return;+ await this.trackPersistence(clearBoundary, this.deps.storage.clear(sessionId));+ if (this.turns.get(sessionId) !== clearBoundary) return;this.deps.emitStatus({ sessionId, goal: null });+ this.turns.delete(sessionId);}/**@@ -538,15 +828,51 @@ export class GoalController {* reason 供 UI 展示(如 rewind 传 "paused: conversation rewound")。*/async pauseGoal(sessionId: string, reason?: string): Promise<void> {- const state = await this.deps.storage.get(sessionId);- if (!state || state.status !== 'active') return;- const updated = await this.deps.storage.update(sessionId, {- status: 'paused',- lastReason: reason ?? 'paused by user',- updatedAt: this.now(),- });- // 停续跑(detach listener + 清 timer/firing)。在途 turn 即便后续 done 也不再触发续跑。+ // Stop 的控制边界不能排在存储 IO 后面:读写一旦卡住,在途 turn 的终态事件仍会+ // 落到旧 listener,idle 兜底会把 active goal 立即续起来。先同步 detach listener、+ // continuation timer 与 firing 状态,再用同一 turns owner 留下 cancelled 边界,+ // 阻止 pause 落盘期间的 resume-on-open / 迟到事件重建旧生命周期。+ this.cancelUsageResume(sessionId);+ const previousBoundary = this.turns.get(sessionId);this.stopSession(sessionId);+ // 每次 Stop 都换新对象身份:后来的 Stop 必须能超越已在 await 中的 Resume,+ // 不能复用旧 cancelled 对象形成 ABA。边界留到后续显式 Resume / setGoal / clearGoal,+ // 也让暂停落盘失败、乃至目标行尚未创建时的 Stop 都保持 fail-closed。+ const pauseBoundary = freshTurn(+ true,+ previousBoundary?.pendingPersistence ?? null,+ previousBoundary?.pendingCompletion ?? null,+ );+ this.turns.set(sessionId, pauseBoundary);+ await this.awaitPendingPersistence(pauseBoundary);+ if (this.turns.get(sessionId) !== pauseBoundary) return;+ const state = await this.deps.storage.get(sessionId);+ if (this.turns.get(sessionId) !== pauseBoundary) return;+ if (!state) return;+ if (state.status === 'usageLimited') {+ const updated = await this.trackPersistence(+ pauseBoundary,+ this.deps.storage.update(sessionId, {+ status: 'paused',+ usageResetAt: null,+ lastReason: reason ?? 'paused by user',+ updatedAt: this.now(),+ }),+ );+ if (this.turns.get(sessionId) !== pauseBoundary) return;+ if (updated) this.emit(updated);+ return;+ }+ if (state.status !== 'active') return;+ const updated = await this.trackPersistence(+ pauseBoundary,+ this.deps.storage.update(sessionId, {+ status: 'paused',+ lastReason: reason ?? 'paused by user',+ updatedAt: this.now(),+ }),+ );+ if (this.turns.get(sessionId) !== pauseBoundary) return;if (updated) this.emit(updated);}@@ -556,11 +882,48 @@ export class GoalController {* /已 active 不处理。*/async resumeGoal(sessionId: string, opts?: { auto?: boolean }): Promise<void> {- const state = await this.deps.storage.get(sessionId);+ let existingBoundary = this.turns.get(sessionId);+ let state: GoalState | null | undefined;+ if (existingBoundary?.cancelled) {+ if (opts?.auto) return;+ await this.awaitPendingLifecycle(existingBoundary);+ if (this.turns.get(sessionId) !== existingBoundary) return;+ // Stop 持久化失败时保留 fail-closed 边界;读取失败也不能据此放行恢复。+ state = await this.deps.storage.get(sessionId);+ if (this.turns.get(sessionId) !== existingBoundary) return;+ if (+ !state ||+ (state.status !== 'paused' && state.status !== 'blocked' && state.status !== 'usageLimited') ||+ this.isBusy(sessionId)+ ) {+ return;+ }+ this.turns.delete(sessionId);+ existingBoundary = undefined;+ }+ const lookupBoundary = existingBoundary ?? freshTurn();+ const ownsLookupBoundary = existingBoundary === undefined;+ if (ownsLookupBoundary) this.turns.set(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 (ownsLookupBoundary && this.turns.get(sessionId) === lookupBoundary) {+ this.turns.delete(sessionId);+ }+ throw error;+ }+ }+ if (this.turns.get(sessionId) !== lookupBoundary) return;if (!state ||(state.status !== 'paused' && state.status !== 'blocked' && state.status !== 'usageLimited')) {+ if (ownsLookupBoundary && this.turns.get(sessionId) === lookupBoundary) {+ this.turns.delete(sessionId);+ }return;}this.cancelUsageResume(sessionId); // 早恢复 / 手动恢复 → 取消挂着的自动续 timer@@ -569,16 +932,54 @@ export class GoalController {// **自动续跑(opts.auto)绝不清零**:到点自动续跑正是过载循环的一环,在这里清// 等于让计数永远回到 0,止损闸门形同不存在。if (!opts?.auto) this.consecutiveOverloadTurns.delete(sessionId);- const updated = await this.deps.storage.update(sessionId, {- status: 'active',- noProgressStreak: 0, // 给一次干净续跑机会(原暂停可能正是空轮触顶)- usageResetAt: null, // 恢复后清掉限额重置标记- lastReason: null,- updatedAt: this.now(),- });- if (!updated) return;- this.resetTurn(sessionId);- await this.deps.ensureSession(sessionId);+ const budgetAlreadyExhausted = exceedsGoalBudget(state);+ if (!budgetAlreadyExhausted) {+ let ensured: SessionLike | undefined;+ try {+ ensured = await this.deps.ensureSession(sessionId);+ } catch (error) {+ 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);+ return;+ }+ }+ let updated: GoalState | null;+ try {+ updated = await this.trackPersistence(+ lookupBoundary,+ this.deps.storage.update(sessionId, {+ status: 'active',+ noProgressStreak: 0, // 给一次干净续跑机会(原暂停可能正是空轮触顶)+ usageResetAt: null, // 恢复后清掉限额重置标记+ lastReason: null,+ updatedAt: this.now(),+ }),+ );+ } catch (error) {+ if (ownsLookupBoundary && this.turns.get(sessionId) === lookupBoundary) {+ this.turns.delete(sessionId);+ }+ throw error;+ }+ if (this.turns.get(sessionId) !== lookupBoundary) return;+ if (!updated) {+ if (ownsLookupBoundary && this.turns.get(sessionId) === lookupBoundary) {+ this.turns.delete(sessionId);+ }+ return;+ }+ // 并发 Resume 可能已经在同一个 lookup owner 上登记了另一笔 active 写;新 active+ // owner 必须继承整个 barrier,后续 Stop 才能等所有较早 Resume settle 后最后写 paused。+ const resumedBoundary = freshTurn(+ false,+ lookupBoundary.pendingPersistence,+ lookupBoundary.pendingCompletion,+ );+ this.turns.set(sessionId, resumedBoundary);this.attachListener(sessionId);this.emit(updated);if (!this.isBusy(sessionId)) {@@ -620,27 +1021,45 @@ export class GoalController {* 这样重开会话能让 active 目标自己跑下去,而不是卡死等用户重发 /goal。*/async resumeOnOpen(sessionId: string): Promise<void> {- if (this.unsubscribers.has(sessionId)) return; // 已在管(非 dormant)- const state = await this.deps.storage.get(sessionId);- if (!state || state.status !== 'active') return; // 只续 active dormant;paused/blocked 走手动 resume+ if (this.unsubscribers.has(sessionId) || this.turns.has(sessionId)) return; // 已在管或正在 Stop+ const lifecycleBoundary = freshTurn();+ this.turns.set(sessionId, lifecycleBoundary);+ let state: GoalState | null;+ try {+ state = await this.deps.storage.get(sessionId);+ } catch (error) {+ if (this.turns.get(sessionId) === lifecycleBoundary) this.turns.delete(sessionId);+ throw error;+ }+ if (this.turns.get(sessionId) !== lifecycleBoundary) return;+ if (!state || state.status !== 'active') {+ if (this.turns.get(sessionId) === lifecycleBoundary) this.turns.delete(sessionId);+ return; // 只续 active dormant;paused/blocked 走手动 resume+ }// deferred agent switch 的 commit 会关闭旧 live session。必须在 ensureSession// 之前执行,随后重新读取/bootstrap 的才是目标引擎;否则这一轮 directive 会继续// 发给 fireTurn 开始时捕获的旧 session。- const releaseAgentSwitchLock =- (await this.deps.acquirePendingAgentSwitch?.(sessionId)) ?? (() => {});+ let releaseAgentSwitchLock = (): void => {};let session: SessionLike | undefined;try {+ releaseAgentSwitchLock =+ (await this.deps.acquirePendingAgentSwitch?.(sessionId)) ?? (() => {});+ if (this.turns.get(sessionId) !== lifecycleBoundary) return;session = await this.deps.ensureSession(sessionId);+ if (this.turns.get(sessionId) !== lifecycleBoundary) return;if (session) {// 锁内先建立 listener 身份。释放后即使 queued SET_MODEL 立刻关闭该 session,// fireTurn 也能凭 unsubscribers 标记把 listener 迁移到重新创建的新 session。- this.resetTurn(sessionId);this.attachListener(sessionId);}} finally {releaseAgentSwitchLock();+ if (!session && this.turns.get(sessionId) === lifecycleBoundary) {+ this.turns.delete(sessionId);+ }}if (!session) return; // 活化失败(如 device-link 远程不可用)→ 留 dormant,下次打开再试+ if (this.turns.get(sessionId) !== lifecycleBoundary) return;this.emit(state);if (!this.isBusy(sessionId)) {await this.fireTurn(sessionId);@@ -655,7 +1074,11 @@ export class GoalController {async resumeActiveGoals(): Promise<void> {const active = await this.deps.storage.listActive();let resumed = 0;- for (const state of active) {+ for (const snapshot of active) {+ // listActive 是启动扫描快照;并发 Stop 可能已经立 cancelled boundary 或写成 paused。+ if (this.turns.has(snapshot.sessionId)) continue;+ const state = await this.deps.storage.get(snapshot.sessionId);+ if (!state || state.status !== 'active' || this.turns.has(snapshot.sessionId)) continue;// 保守:只对**已经活着**的会话重挂 + 续跑;不在启动时强行 spawn agent//(开机就偷偷跑目标过于激进)。没活的留 dormant,等用户重发 /goal 时由// setGoal 的 ensureSession 接管。@@ -666,7 +1089,7 @@ export class GoalController {});continue;}- this.resetTurn(state.sessionId);+ this.turns.set(state.sessionId, freshTurn());this.attachListener(state.sessionId);this.emit(state);resumed += 1;@@ -700,6 +1123,7 @@ export class GoalController {for (const sessionId of [...this.usageResumeTimers.keys()]) {this.cancelUsageResume(sessionId);}+ this.turns.clear();this.consecutiveOverloadTurns.clear();}@@ -723,8 +1147,90 @@ export class GoalController {this.turns.delete(sessionId);}+ /**+ * 开始下一轮时原地清 accumulator,保留稳定的 Goal 生命周期 owner。+ * 显式 Stop / Resume / setGoal 会另建 owner;generation 只用于淘汰旧 turn finalizer。+ */private resetTurn(sessionId: string): void {- this.turns.set(sessionId, freshTurn());+ const turn = this.turns.get(sessionId);+ if (!turn || turn.cancelled) return;+ turn.text = '';+ turn.sawToolUse = false;+ turn.tokensThisTurn = 0;+ turn.finalized = false;+ turn.generation += 1;+ }++ /**+ * 登记已经启动的 Goal 状态写入。显式生命周期接管会先同步换 owner,再等待这里的+ * barrier,保证旧写全部 settle 后才提交自己的最终状态;写入本身仍可并发执行。+ */+ private trackPersistence<T>(+ turn: TurnAccumulator,+ operation: Promise<T>,+ afterPersist?: (value: T) => void | Promise<void>,+ ): Promise<T> {+ const committed = operation.then(async (value) => {+ await afterPersist?.(value);+ return value;+ });+ const settled = committed.then(+ () => undefined,+ () => undefined,+ );+ const previous = turn.pendingPersistence;+ const barrier = previous+ ? Promise.all([previous, settled]).then(() => undefined)+ : settled;+ turn.pendingPersistence = barrier;+ void barrier.then(() => {+ if (turn.pendingPersistence === barrier) turn.pendingPersistence = null;+ });+ return committed;+ }++ private async awaitPendingPersistence(turn: TurnAccumulator | undefined): Promise<void> {+ while (turn?.pendingPersistence) {+ const pending = turn.pendingPersistence;+ await pending;+ if (turn.pendingPersistence === pending) {+ turn.pendingPersistence = null;+ return;+ }+ }+ }++ /**+ * completion commit 保持“达成记录 → clear”的耐久顺序,但不进入 Stop 的等待集合。+ * setGoal / update / resume 等会等待它,确保旧 clear 绝不落在新目标写入之后。+ */+ private trackCompletion<T>(turn: TurnAccumulator, operation: Promise<T>): Promise<T> {+ const settled = operation.then(+ () => undefined,+ () => undefined,+ );+ const previous = turn.pendingCompletion;+ const barrier = previous+ ? Promise.all([previous, settled]).then(() => undefined)+ : settled;+ turn.pendingCompletion = barrier;+ void barrier.then(() => {+ if (turn.pendingCompletion === barrier) turn.pendingCompletion = null;+ });+ return operation;+ }++ private async awaitPendingLifecycle(turn: TurnAccumulator | undefined): Promise<void> {+ while (turn?.pendingPersistence || turn?.pendingCompletion) {+ const persistence = turn.pendingPersistence;+ const completion = turn.pendingCompletion;+ await Promise.all([+ persistence ?? Promise.resolve(),+ completion ?? Promise.resolve(),+ ]);+ if (turn.pendingPersistence === persistence) turn.pendingPersistence = null;+ if (turn.pendingCompletion === completion) turn.pendingCompletion = null;+ }}private isBusy(sessionId: string): boolean {@@ -769,6 +1275,7 @@ export class GoalController {turn = freshTurn();this.turns.set(sessionId, turn);}+ if (turn.cancelled) return;switch (event.type) {case 'text': {const d = event.data as { text?: string; isFinal?: boolean } | null;@@ -817,10 +1324,17 @@ export class GoalController {private async finalizeTurn(sessionId: string, event: AgentEvent, errored: boolean): Promise<void> {const turn = this.turns.get(sessionId);- if (turn?.finalized) return; // done + 终止 error 双触发去重(同步置位,后续 await 不影响去重)- if (turn) turn.finalized = true;+ // Stop / Pause 会同步删除当前 turn。已经跨过 async 边界的旧 finalize 必须把这个+ // 对象身份当作取消令牌:否则它可能在 paused 落库之后继续把状态写回 active,表现为+ // 用户刚点 Stop 就立刻重新 Running。resume 会创建新 turn,因此也不能只检查 key 存在。+ if (!turn || turn.cancelled || turn.finalized) return;+ turn.finalized = true; // done + 终止 error 双触发去重(同步置位,后续 await 不影响去重)+ const generation = turn.generation;+ const isCurrentTurn = (): boolean =>+ this.turns.get(sessionId) === turn && turn.generation === generation;const state = await this.deps.storage.get(sessionId);+ if (!isCurrentTurn()) return;// goal 已不存在(被 clear)→ 收尾 detach。if (!state) {this.stopSession(sessionId);@@ -898,23 +1412,32 @@ export class GoalController {// 记录(role:'assistant' + agentMeta.goalCompletion,重开会话仍在),随后删 goal// 行让 chip 消失。视觉由 renderer 渲成"目标已达成 · N 轮 · 耗时 X"分隔条。if (decision.status === 'complete') {+ // completion commit 保持“达成记录 → clear”的耐久顺序,但单独登记:Stop 会同步+ // detach 并把 paused 落盘后立即返回;新 setGoal / update / resume 则必须等旧 clear,+ // 防止旧目标的删除迟到并抹掉新目标。const elapsedMs = Math.max(0, this.now() - state.startedAt);- if (this.deps.persistGoalCompletion) {- try {- await this.deps.persistGoalCompletion(sessionId, {- turnsUsed: decision.turnsUsed,- tokensUsed: decision.tokensUsed,- elapsedMs,- reason: decision.lastReason,- });- } catch (e) {- this.deps.logger.warn('[goal] persistGoalCompletion failed', { sessionId, error: String(e) });- }- }- await this.deps.storage.clear(sessionId);- this.deps.emitStatus({ sessionId, goal: null });- this.resetTurn(sessionId);- this.stopSession(sessionId);+ await this.trackCompletion(+ turn,+ (async () => {+ if (this.deps.persistGoalCompletion) {+ try {+ await this.deps.persistGoalCompletion(sessionId, {+ turnsUsed: decision.turnsUsed,+ tokensUsed: decision.tokensUsed,+ elapsedMs,+ reason: decision.lastReason,+ });+ } catch (e) {+ this.deps.logger.warn('[goal] persistGoalCompletion failed', { sessionId, error: String(e) });+ }+ }+ await this.deps.storage.clear(sessionId);+ // null emit 属于同一顺序提交;后续新目标必须在它之后再 emit active,+ // 否则旧 completion 的迟到 null 会把新 chip 隐藏。+ this.deps.emitStatus({ sessionId, goal: null });+ })(),+ );+ if (isCurrentTurn()) this.stopSession(sessionId);return;}@@ -935,6 +1458,7 @@ export class GoalController {const limit = this.deps.getAccountLimit? await this.deps.getAccountLimit(state.agentKind).catch(() => null): null;+ if (!isCurrentTurn()) return;if (status === 'usageLimited') {usageResetAt = limit?.resetAtMs ?? null; // 被动:补 resetAt(可能拿不到→null,留待手动 resume)shouldFire = false;@@ -958,26 +1482,37 @@ export class GoalController {? refined: null;- const updated = await this.deps.storage.update(sessionId, {- status,- lastReason,- turnsUsed: decision.turnsUsed,- tokensUsed: decision.tokensUsed,- noProgressStreak: decision.noProgressStreak,- usageResetAt: status === 'usageLimited' ? usageResetAt : null,- ...(objectiveRewrite ? { objective: objectiveRewrite } : {}),- updatedAt: this.now(),- });+ if (!isCurrentTurn()) return;+ const updated = await this.trackPersistence(+ turn,+ this.deps.storage.update(sessionId, {+ // active 是保持态,不是 transition;省略它可让迟到 continuation 写在任何+ // 防线失效时仍只能补计数,绝不能把显式 Stop 的 paused 改回 active。+ ...(status === 'active' ? {} : { status }),+ lastReason,+ turnsUsed: decision.turnsUsed,+ tokensUsed: decision.tokensUsed,+ noProgressStreak: decision.noProgressStreak,+ usageResetAt: status === 'usageLimited' ? usageResetAt : null,+ ...(objectiveRewrite ? { objective: objectiveRewrite } : {}),+ updatedAt: this.now(),+ }),+ async (persisted) => {+ // objective 与对应 marker 是同一个可观察提交;Stop 必须等二者都 settle,+ // 不能留下“文案已改但更新标记缺失”的半提交。+ if (objectiveRewrite && persisted) {+ await this.deps.persistUserMessage?.(sessionId, objectiveRewrite, {+ goalObjective: { updated: true },+ });+ }+ },+ );+ if (!isCurrentTurn()) return;if (updated) this.emit(updated);- // 改写了目标 → 在对话里落一条「目标已更新」标记(气泡徽标),与 setGoal/updateGoal 改目标一致。- if (objectiveRewrite) {- await this.deps.persistUserMessage?.(sessionId, objectiveRewrite, { goalObjective: { updated: true } });- }-this.resetTurn(sessionId);- if (shouldFire) {+ if (shouldFire && updated?.status === 'active') {this.scheduleContinuation(sessionId);} else {// 停:budgetLimited(终态)/ blocked / paused / usageLimited 都 detach。@@ -1032,71 +1567,104 @@ export class GoalController {*/private async autoResumeFromUsageLimit(sessionId: string): Promise<void> {this.usageResumeTimers.delete(sessionId);- const state = await this.deps.storage.get(sessionId).catch(() => null);- if (!state || state.status !== 'usageLimited') return; // 用户可能已 clear / 手动 resume- // 预算已经用尽时一条都不该说:下面的 resumeGoal → fireTurn 有 preflight 预算守卫,- // 会立刻把目标转成 budgetLimited、一轮都不发,而这张卡片已经落库,会在会话里永久- // 留下一句「正在重试目标 / 用量已恢复」——那次重试根本没发生(review #844 codex P1)。- // 判据与 fireTurn 用的是同一个 exceedsGoalBudget,结论必然一致;仍照常走 resumeGoal,- // 由它把状态转成 budgetLimited。- const budgetAlreadyExhausted = exceedsGoalBudget(state);- // 同理的第二种"这条重试根本没发生":会话此刻拿不到 live session(已关闭 / 暂时 hydrate- // 不出来)。resumeGoal 忽略 ensureSession 的结果、照样把目标转 active,而 fireTurn 拿不到- // session 就直接 return —— 既没有 listener 也没有续跑 timer,目标停在 active 不动,而卡片- // 已经落库说"正在重试目标"(review #844 codex P1)。- //- // 这里先探一次:拿不到就**原样留在 usageLimited**(可恢复态)——存档里 usageResetAt 还在,- // 用户手动 resume 或下次启动的 usageLimited 重排(见 start() 里按 listUsageLimited 补排- // timer)都会再试一次;既不落假卡片,也不把目标推进一个停滞的 active。- // 刻意不在这里重排 timer:hydrate 不出来通常不是几十秒能自愈的,循环重排只会空转。- // ensureSession 是幂等的 ensure 语义,下面 resumeGoal 再调一次拿到的是同一个 session。- // **预算已耗尽的目标不需要 live session 就能收口**: fireTurn 的预算 preflight 跑在- // ensureSession 之前, 会把状态转成 budgetLimited(终态)并 stopSession。把下面的- // hydrate 守卫排在它前面, 会让这种目标停在 usageLimited + 已过期的 usageResetAt,- // 直到手动 resume 或进程重启才收口(review #844 codex P1)。- const liveSession = budgetAlreadyExhausted- ? null- : await this.deps.ensureSession(sessionId).catch(() => null);- if (!budgetAlreadyExhausted && !liveSession) {- this.deps.logger.warn('[goal] skipped auto resume — no live session; staying usageLimited', {- sessionId,- lastReason: state.lastReason ?? null,- });- return;- }- if (this.deps.persistGoalNotice && !budgetAlreadyExhausted) {- // 过载与账号限流共用 usageLimited 状态和这同一个 timer,但说法必须分开:- // 账号从没被限流时报「额度已重置」是假信息(review #844 codex P1)。- // 判据用存档的 lastReason 而不是内存计数——后者在进程重启后会丢,而- // usageLimited 目标恰好会在重启后按存档的 usageResetAt 重排 timer。- const noticeKind =- state.lastReason === OVERLOAD_LAST_REASON ? 'capacity-resumed' : 'usage-resumed';- try {- await this.deps.persistGoalNotice(sessionId, noticeKind);- } catch (e) {- this.deps.logger.warn('[goal] persistGoalNotice failed', { sessionId, error: String(e) });+ // usageLimited 停驻态正常没有 turn owner。为本次 timer 建一代临时 owner,所有 await+ // 都用对象身份复核;Stop 会同步换成 fresh cancelled owner,旧自动恢复因而不能落提示、+ // 不能恢复,也不会误删 Stop 的新边界。已有 owner 表示其它生命周期操作正在接管。+ if (this.turns.has(sessionId)) return;+ const lifecycleBoundary = freshTurn();+ this.turns.set(sessionId, lifecycleBoundary);+ const isCurrent = (): boolean => this.turns.get(sessionId) === lifecycleBoundary;++ try {+ const state = await this.deps.storage.get(sessionId).catch(() => null);+ if (!isCurrent()) return;+ if (!state || state.status !== 'usageLimited') return; // 用户可能已 clear / 手动 resume+ // 预算已经用尽时一条都不该说:下面的 resumeGoal → fireTurn 有 preflight 预算守卫,+ // 会立刻把目标转成 budgetLimited、一轮都不发,而这张卡片已经落库,会在会话里永久+ // 留下一句「正在重试目标 / 用量已恢复」——那次重试根本没发生(review #844 codex P1)。+ // 判据与 fireTurn 用的是同一个 exceedsGoalBudget,结论必然一致;仍照常走 resumeGoal,+ // 由它把状态转成 budgetLimited。+ const budgetAlreadyExhausted = exceedsGoalBudget(state);+ // 同理的第二种"这条重试根本没发生":会话此刻拿不到 live session(已关闭 / 暂时 hydrate+ // 不出来)。resumeGoal 忽略 ensureSession 的结果、照样把目标转 active,而 fireTurn 拿不到+ // session 就直接 return —— 既没有 listener 也没有续跑 timer,目标停在 active 不动,而卡片+ // 已经落库说"正在重试目标"(review #844 codex P1)。+ //+ // 这里先探一次:拿不到就**原样留在 usageLimited**(可恢复态)——存档里 usageResetAt 还在,+ // 用户手动 resume 或下次启动的 usageLimited 重排(见 start() 里按 listUsageLimited 补排+ // timer)都会再试一次;既不落假卡片,也不把目标推进一个停滞的 active。+ // 刻意不在这里重排 timer:hydrate 不出来通常不是几十秒能自愈的,循环重排只会空转。+ // ensureSession 是幂等的 ensure 语义,下面 resumeGoal 再调一次拿到的是同一个 session。+ // **预算已耗尽的目标不需要 live session 就能收口**: fireTurn 的预算 preflight 跑在+ // ensureSession 之前, 会把状态转成 budgetLimited(终态)并 stopSession。把下面的+ // hydrate 守卫排在它前面, 会让这种目标停在 usageLimited + 已过期的 usageResetAt,+ // 直到手动 resume 或进程重启才收口(review #844 codex P1)。+ const liveSession = budgetAlreadyExhausted+ ? null+ : await this.deps.ensureSession(sessionId).catch(() => null);+ if (!isCurrent()) return;+ if (!budgetAlreadyExhausted && !liveSession) {+ this.deps.logger.warn('[goal] skipped auto resume — no live session; staying usageLimited', {+ sessionId,+ lastReason: state.lastReason ?? null,+ });+ return;}- } else if (budgetAlreadyExhausted) {- this.deps.logger.info('[goal] skipped resume notice — budget already exhausted', {- sessionId,- });+ if (this.deps.persistGoalNotice && !budgetAlreadyExhausted) {+ // 过载与账号限流共用 usageLimited 状态和这同一个 timer,但说法必须分开:+ // 账号从没被限流时报「额度已重置」是假信息(review #844 codex P1)。+ // 判据用存档的 lastReason 而不是内存计数——后者在进程重启后会丢,而+ // usageLimited 目标恰好会在重启后按存档的 usageResetAt 重排 timer。+ const noticeKind =+ state.lastReason === OVERLOAD_LAST_REASON ? 'capacity-resumed' : 'usage-resumed';+ try {+ await this.deps.persistGoalNotice(sessionId, noticeKind);+ } catch (e) {+ this.deps.logger.warn('[goal] persistGoalNotice failed', { sessionId, error: String(e) });+ }+ if (!isCurrent()) return;+ } else if (budgetAlreadyExhausted) {+ this.deps.logger.info('[goal] skipped resume notice — budget already exhausted', {+ sessionId,+ });+ }+ // auto:true —— 这是到点自动续跑,不是用户显式恢复,不得清零连续过载计数。+ await this.resumeGoal(sessionId, { auto: true });+ } finally {+ // 早退 / resume no-op 时释放自己;成功 resume 会换成新的 active owner,Stop 会留下它的+ // cancelled owner,二者都不能被旧 timer 的 finally 删除。+ if (isCurrent()) this.turns.delete(sessionId);}- // auto:true —— 这是到点自动续跑,不是用户显式恢复,不得清零连续过载计数。- await this.resumeGoal(sessionId, { auto: true });}private async fireTurn(sessionId: string): Promise<void> {+ const lifecycleBoundary = this.turns.get(sessionId);+ if (!lifecycleBoundary || lifecycleBoundary.cancelled) return;+ const lifecycleGeneration = lifecycleBoundary.generation;+ const isCurrentLifecycle = (): boolean =>+ this.turns.get(sessionId) === lifecycleBoundary &&+ lifecycleBoundary.generation === lifecycleGeneration;const state = await this.deps.storage.get(sessionId);- if (!state || state.status !== 'active') return;+ // owner 身份拒绝 Stop / Resume 换代,generation 拒绝另一轮正常推进后的旧 fire;+ // 两者都不能只信上面读到的 active 存档快照。+ if (+ !state ||+ state.status !== 'active' ||+ !isCurrentLifecycle()+ ) return;// preflight 预算守卫:用户可能把 maxTurns/budgetTokens 调小到已超当前用量(updateGoal 会即时// 转 budgetLimited,但调度链上可能仍有在途 fireTurn / continuation timer 指向旧 active 状态)。// 超(新)预算就转 budgetLimited 并停,绝不越过新上限再发一轮(reviewer #354)。if (exceedsGoalBudget(state)) {- const limited = await this.deps.storage.update(sessionId, {- status: 'budgetLimited',- lastReason: 'budget limit reached',- updatedAt: this.now(),- });+ const limited = await this.trackPersistence(+ lifecycleBoundary,+ this.deps.storage.update(sessionId, {+ status: 'budgetLimited',+ lastReason: 'budget limit reached',+ updatedAt: this.now(),+ }),+ );+ if (!isCurrentLifecycle()) return;this.stopSession(sessionId);if (limited) this.emit(limited);return;@@ -1117,7 +1685,15 @@ export class GoalController {this.scheduleContinuation(sessionId);return;}- this.firing.add(sessionId);+ const firingOwner = {};+ this.firing.set(sessionId, firingOwner);+ let dispatchBoundary: TurnAccumulator | undefined;+ let dispatchGeneration: number | undefined;+ const isCurrentDispatch = (): boolean =>+ dispatchBoundary != null &&+ dispatchGeneration != null &&+ this.turns.get(sessionId) === dispatchBoundary &&+ dispatchBoundary.generation === dispatchGeneration;let releaseAgentSwitchLock = (): void => {};let baselineStarted = false;try {@@ -1126,12 +1702,15 @@ export class GoalController {// session 创建后、send 前再次换 route,让本轮落到 UI 未显示的来源。releaseAgentSwitchLock =(await this.deps.acquirePendingAgentSwitch?.(sessionId)) ?? (() => {});+ 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,});+ if (isCurrentLifecycle()) this.stopSession(sessionId);return;}// deferred switch 可能刚把 live session 换成目标引擎的新对象;本会话若有 goal@@ -1143,6 +1722,9 @@ export class GoalController {}this.resetTurn(sessionId);+ dispatchBoundary = this.turns.get(sessionId);+ if (!dispatchBoundary) return;+ dispatchGeneration = dispatchBoundary.generation;const content =kind === 'first'? buildFirstTurnDirective(state.objective, { maxTurns: state.maxTurns })@@ -1159,6 +1741,13 @@ export class GoalController {// 交接注入自己接——切换后 goal 循环的下一轮 directive 同样要带交接上下文// (2026-07-20 审计)。const pendingHandoff = await agentHandoffPending.peek(sessionId);+ if (!isCurrentDispatch()) {+ if (baselineStarted) {+ this.deps.onUndispatchedUserTurn?.(sessionId);+ baselineStarted = false;+ }+ return;+ }const outgoing = pendingHandoff? prependHandoffToUserMessage({ type: 'user', content }, pendingHandoff): { type: 'user' as const, content };@@ -1174,9 +1763,14 @@ export class GoalController {this.deps.onUndispatchedUserTurn?.(sessionId);baselineStarted = false;}+ if (!isCurrentDispatch()) return;this.goalTurnsInFlight.delete(sessionId);this.deps.logger.warn('[goal] send not accepted', { sessionId, kind, reason: result.reason });} else {+ if (!isCurrentDispatch()) {+ baselineStarted = false;+ return;+ }this.goalTurnsInFlight.add(sessionId);baselineStarted = false;}@@ -1185,12 +1779,16 @@ export class GoalController {this.deps.onUndispatchedUserTurn?.(sessionId);baselineStarted = false;}- this.goalTurnsInFlight.delete(sessionId);+ if (dispatchBoundary ? isCurrentDispatch() : isCurrentLifecycle()) {+ this.goalTurnsInFlight.delete(sessionId);+ }// SESSION_RUNNING:会话已有 turn 在跑(用户抢发等);该 turn 的 done 会再触发裁决。this.deps.logger.warn('[goal] fireTurn send failed', { sessionId, kind, error: String(e) });} finally {releaseAgentSwitchLock();- this.firing.delete(sessionId);+ if (this.firing.get(sessionId) === firingOwner) {+ this.firing.delete(sessionId);+ }}}}diff --git a/apps/desktop/src/main/goal-host/storage.ts b/apps/desktop/src/main/goal-host/storage.tsindex 8f2924d389..6a4273853e 100644--- a/apps/desktop/src/main/goal-host/storage.ts+++ b/apps/desktop/src/main/goal-host/storage.ts@@ -88,10 +88,14 @@ export class GoalStorage implements GoalStorageLike {.onConflictDoUpdate({ target: sessionGoals.sessionId, set: row });}- /** 部分更新;找不到行返回 null(不 throw),与 scheduler storage 契约一致。 */+ /**+ * 部分更新;找不到行返回 null(不 throw),与 scheduler storage 契约一致。+ *+ * 写操作必须先以单条 UPDATE 提交,再读回结果。写前先 get 会把一次状态提交拆成+ * get → update → get 三个可交错步骤:旧 finalize 已经开始 update 后,显式 Stop+ * 可能先写 paused,随后旧快照再把它覆盖回 active。+ */async update(sessionId: string, patch: Partial<GoalState>): Promise<GoalState | null> {- const existing = await this.get(sessionId);- if (!existing) return null;// 只挑允许更新的列,避免把 sessionId/startedAt 等覆盖掉。const set: Partial<GoalInsert> = {};if (patch.objective !== undefined) set.objective = patch.objective;@@ -105,7 +109,7 @@ export class GoalStorage implements GoalStorageLike {if (patch.usageResetAt !== undefined) set.usageResetAt = patch.usageResetAt;if (patch.lastReason !== undefined) set.lastReason = patch.lastReason;if (patch.updatedAt !== undefined) set.updatedAt = patch.updatedAt;- if (Object.keys(set).length === 0) return existing;+ if (Object.keys(set).length === 0) return this.get(sessionId);await this.getDb().update(sessionGoals).set(set).where(eq(sessionGoals.sessionId, sessionId));return this.get(sessionId);}diff --git a/apps/desktop/src/main/maker-ipc/__tests__/goalHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/goalHandlers.test.tsnew file mode 100644index 0000000000..f12afedc59--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/goalHandlers.test.ts@@ -0,0 +1,73 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ handlers: new Map<string, (...args: unknown[]) => unknown>(),+ updateGoal: vi.fn(),+}));++vi.mock('electron', () => ({+ BrowserWindow: { getAllWindows: () => [] },+ ipcMain: {+ handle: (channel: string, handler: (...args: unknown[]) => unknown) => {+ mocks.handlers.set(channel, handler);+ },+ },+}));++vi.mock('../../goal-host/index.js', () => ({+ getGoalController: () => ({ updateGoal: mocks.updateGoal }),+}));++vi.mock('../../logger.js', () => ({+ createLogger: () => ({ info: vi.fn(), warn: vi.fn() }),+}));++vi.mock('../../device-link/broadcast-tap.js', () => ({+ tapWindowBroadcast: vi.fn(),+}));++import { 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');+ return handler;+}++describe('goal update IPC errors', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.handlers.clear();+ registerGoalHandlers();+ });++ it('maps a superseded lifecycle update to PRECONDITION_FAILED', async () => {+ mocks.updateGoal.mockRejectedValueOnce(new GoalUpdateSupersededError());++ const result = updateHandler()(+ {},+ {+ sessionId: 's1',+ patch: { objective: 'updated objective' },+ },+ );++ await expect(result).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });+ });++ it('keeps GOAL_NOT_FOUND for an authoritative missing row', async () => {+ mocks.updateGoal.mockResolvedValueOnce(null);++ const result = updateHandler()(+ {},+ {+ sessionId: 's1',+ patch: { maxTurns: 10 },+ },+ );++ await expect(result).rejects.toMatchObject({ code: 'GOAL_NOT_FOUND' });+ });+});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/stopSessionBackgroundTasksHandler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/stopSessionBackgroundTasksHandler.test.tsindex 5f9495afdf..38937dbf79 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/stopSessionBackgroundTasksHandler.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/stopSessionBackgroundTasksHandler.test.ts@@ -79,12 +79,13 @@ describe('stop session background tasks IPC handler', () => {expect(clearBackgroundActivity).not.toHaveBeenCalled();});- it('still closes the session when notifyGoalStop rejects', async () => {+ it('still closes the session but reports failure when notifyGoalStop rejects', async () => {const harness = new IpcHarness();+ const error = new Error('goal observer crashed');const closeSession = vi.fn().mockResolvedValue(undefined);const clearBackgroundActivity = vi.fn();const noteSessionReset = vi.fn();- const notifyGoalStop = vi.fn().mockRejectedValue(new Error('goal observer crashed'));+ const notifyGoalStop = vi.fn().mockRejectedValue(error);registerStopSessionBackgroundTasksHandler(harness, {closeSession,@@ -95,8 +96,74 @@ describe('stop session background tasks IPC handler', () => {await expect(harness.invoke(MAKER_INVOKE.STOP_SESSION_BACKGROUND_TASKS, 'session-1'),- ).resolves.toEqual({ ok: true });+ ).rejects.toBe(error);expect(closeSession).toHaveBeenCalledWith('session-1');expect(clearBackgroundActivity).toHaveBeenCalledWith('session-1');});++ it('still closes the session and reports a synchronous notifyGoalStop failure', async () => {+ const harness = new IpcHarness();+ const error = new Error('goal observer failed synchronously');+ const closeSession = vi.fn().mockResolvedValue(undefined);+ const clearBackgroundActivity = vi.fn();++ registerStopSessionBackgroundTasksHandler(harness, {+ closeSession,+ clearBackgroundActivity,+ noteSessionReset: vi.fn(),+ notifyGoalStop: vi.fn(() => {+ throw error;+ }),+ });++ await expect(+ harness.invoke(MAKER_INVOKE.STOP_SESSION_BACKGROUND_TASKS, 'session-1'),+ ).rejects.toBe(error);+ expect(closeSession).toHaveBeenCalledWith('session-1');+ expect(clearBackgroundActivity).toHaveBeenCalledWith('session-1');+ });++ it('preserves the close failure when close and Goal persistence both reject', async () => {+ const harness = new IpcHarness();+ const closeError = new Error('close failed');+ const goalError = new Error('goal persistence failed');+ const clearBackgroundActivity = vi.fn();++ registerStopSessionBackgroundTasksHandler(harness, {+ closeSession: vi.fn().mockRejectedValue(closeError),+ clearBackgroundActivity,+ noteSessionReset: vi.fn(),+ notifyGoalStop: vi.fn().mockRejectedValue(goalError),+ });++ await expect(+ harness.invoke(MAKER_INVOKE.STOP_SESSION_BACKGROUND_TASKS, 'session-1'),+ ).rejects.toBe(closeError);+ expect(clearBackgroundActivity).not.toHaveBeenCalled();+ });++ it('starts the emergency close before goal persistence settles', async () => {+ const harness = new IpcHarness();+ let releaseGoalPause!: () => void;+ const goalPause = new Promise<void>((resolve) => {+ releaseGoalPause = resolve;+ });+ const closeSession = vi.fn().mockResolvedValue(undefined);+ const clearBackgroundActivity = vi.fn();++ registerStopSessionBackgroundTasksHandler(harness, {+ closeSession,+ clearBackgroundActivity,+ noteSessionReset: vi.fn(),+ notifyGoalStop: vi.fn(() => goalPause),+ });++ const stop = harness.invoke(MAKER_INVOKE.STOP_SESSION_BACKGROUND_TASKS, 'session-1');+ await vi.waitFor(() => expect(closeSession).toHaveBeenCalledWith('session-1'));+ expect(clearBackgroundActivity).not.toHaveBeenCalled();++ releaseGoalPause();+ await expect(stop).resolves.toEqual({ ok: true });+ expect(clearBackgroundActivity).toHaveBeenCalledWith('session-1');+ });});diff --git a/apps/desktop/src/main/maker-ipc/goal.ts b/apps/desktop/src/main/maker-ipc/goal.tsindex 2a2f1d661a..7d1a3f3c52 100644--- a/apps/desktop/src/main/maker-ipc/goal.ts+++ b/apps/desktop/src/main/maker-ipc/goal.ts@@ -16,7 +16,10 @@ import { ipcMain, BrowserWindow } from 'electron';import { createLogger } from '../logger.js';import { throwIpcError, requireString, requireObject } from '../utils/ipcValidate.js';-import { GoalControllerInputError } from '../goal-host/controller.js';+import {+ GoalControllerInputError,+ GoalUpdateSupersededError,+} from '../goal-host/controller.js';import { getGoalController } from '../goal-host/index.js';import { tapWindowBroadcast } from '../device-link/broadcast-tap.js';import type { GoalUpdatePatch, GoalStatusUpdate } from '../goal-host/types.js';@@ -144,6 +147,9 @@ export function registerGoalHandlers(): void {if (err instanceof GoalControllerInputError) {throwIpcError('INVALID_PARAMS', err.message);}+ if (err instanceof GoalUpdateSupersededError) {+ throwIpcError('PRECONDITION_FAILED', err.message);+ }throw err;}});diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex bea53bba76..71ed389574 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -751,6 +751,18 @@ const autoResumeBookkeeping = new AutoResumeBookkeeping({log: (message, fields) => log.debug(message, fields),});+/**+ * 用户明确停止会话时统一撤销两类自动续跑与它们的退避簿记。+ *+ * 这个边界必须早于 live Session 查询:owner 切换期间可能暂时拿不到 Session,+ * 但已经排期的 timer / scheduler takeover 仍然存在,不能因此漏清后原地复活。+ */+function resetAutomaticRecoveryForExplicitStop(sessionId: string): void {+ silentStopAutoResumeGuard.noteSessionReset(sessionId);+ interruptedTurnAutoResumeGuard.noteSessionReset(sessionId);+ autoResumeBookkeeping.teardown(sessionId);+}+function settleUndispatchedAutoResumeOutcome(sessionId: string,item: AgentInputQueuedMessage,@@ -772,12 +784,11 @@ export function noteSilentStopUserSend(sessionId: string): void {}/**- * 非 renderer 中止路径(IM `!stop` 等)调用:重置 silent-stop 守卫,让挂在- * 1.5s 决策窗里的自动续跑判为 superseded(经 settle('skip') 收口),不在用户- * 明确喊停后"原地复活"。renderer 走 ABORT_SESSION handler 内的同名调用。+ * 非 renderer 中止路径(IM `!stop` 等)调用。历史名称保留给现有调用方;实际必须+ * 同时撤掉 silent-stop、中断续跑及退避簿记,保证所有明确 Stop 入口同一语义。*/export function noteSilentStopSessionReset(sessionId: string): void {- silentStopAutoResumeGuard.noteSessionReset(sessionId);+ resetAutomaticRecoveryForExplicitStop(sessionId);}/**@@ -2557,8 +2568,8 @@ 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)。- * - goalStopObserver:用户 Stop 当前 turn(ABORT_SESSION)时把 active 目标暂停。**在 sess.abort()- * 之前 await** —— 让 pauseGoal 先置 paused + detach 监听,abort 产生的终止事件不再触达目标续跑判定。+ * - goalStopObserver:用户 Stop 当前 turn(ABORT_SESSION)时把 active 目标暂停。调用 observer+ * 会同步 detach 监听/续跑资格;paused 持久化与 vendor abort 并行,回执等落盘收口。* bootstrap 在启动期接上 getGoalController()?.clearGoal / maybeContinueActiveGoal / pauseGoal。*/let goalClearObserver: ((sessionId: string) => void) | null = null;@@ -2575,6 +2586,21 @@ export function setGoalStopObserver(): void {goalStopObserver = observer;}++/** Goal 的同步 detach 是 Stop 边界;vendor abort 先启动,IPC 回执等待 paused 落定。 */+async function pauseGoalBeforeExplicitStop(sessionId: string): Promise<void> {+ const observer = goalStopObserver;+ if (!observer) return;+ try {+ await Promise.resolve(observer(sessionId));+ } catch (err) {+ log.error('goal pause persistence failed during explicit stop', {+ sessionId,+ error: err instanceof Error ? err.message : String(err),+ });+ throwIpcError('INTERNAL', 'Failed to persist the stopped Goal state');+ }+}// (Option B)用户答完 AskUserQuestion 时,把结构化答案 + 本次问题(含选项)交给 goal controller// 即时改写目标(仅首轮、且确认这次问的就是"目标澄清问题"时,controller 内部再 guard)。// 透传 questions 是为了让 controller 用确定性标记(选项里是否含原目标 verbatim)区分目标澄清 vs@@ -4186,13 +4212,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)registerStopSessionBackgroundTasksHandler(createElectronIpcHandlerRegistry(), {closeSession: (sessionId) => maker.closeSession(sessionId),clearBackgroundActivity: clearClaudeSessionBackgroundActivity,- noteSessionReset: (sessionId) => {- silentStopAutoResumeGuard.noteSessionReset(sessionId);- interruptedTurnAutoResumeGuard.noteSessionReset(sessionId);- // 「全部停止」是会话级止损:已排期的自动续跑必须撤掉,别在用户喊停后又补发一条。- autoResumeBookkeeping.teardown(sessionId);- },- notifyGoalStop: (sessionId) => goalStopObserver?.(sessionId),+ // 「全部停止」是会话级止损:已排期的自动续跑必须撤掉,别在用户喊停后又补发一条。+ noteSessionReset: resetAutomaticRecoveryForExplicitStop,+ notifyGoalStop: pauseGoalBeforeExplicitStop,});// 单个后台任务的精确停止(消息流任务卡 / 状态栏停止按钮)。只停指定 taskId,@@ -8162,6 +8184,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)steerToAgent: (sessionId, message, sendOpts) =>steerToAgentAccepted(sessionId, message, sendOpts),abortSession: async (sessionId) => {+ resetAutomaticRecoveryForExplicitStop(sessionId);markWorkerManualInterruptIfKnown(sessionId, 'input_stop');const sess = getStableSessionForTurnBoundary(sessionId);if (!sess) return;@@ -8847,10 +8870,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)ipcMain.handle(MAKER_INVOKE.INPUT_STOP, async (_e, sessionId: unknown, opts?: unknown) => {const sid = requireSessionId(sessionId);- // 用户 Stop 当前 turn(composer Stop 走这条)→ 先暂停 active 目标(置 paused + 停续跑 +- // detach 监听 + 移除 unsubscriber),**再** stop。否则 turn 中止后 idle 兜底- // (maybeContinueActiveGoal)会因目标仍 active 把它又续起来。null-safe;无 active goal 时 no-op。- await goalStopObserver?.(sid);+ // 这三类续跑撤销都是同步操作,必须早于 goal/DB await;+ // 否则退避 timer 能在用户已点 Stop 后抢先发出下一轮。+ resetAutomaticRecoveryForExplicitStop(sid);+ // pauseGoal 调用同步 detach listener/timer,持久化可以与 vendor abort 并行;真正的+ // turn/interrupt 先启动,IPC 回执再等待 paused 落盘。+ const goalPause = pauseGoalBeforeExplicitStop(sid);const result = inputCoordinator.stop(sid,opts && typeof opts === 'object'@@ -8863,6 +8888,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (!inputCoordinator.hasPendingQueuedWork(sid)) {getAgentIslandService()?.notifyQueueEmptied(sid);}+ await goalPause;return result;});@@ -8975,9 +9001,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)isRemoteInvoke: remoteInvoke,});const projection = inputCoordinator.clearSession(sid, clearBoundary);- silentStopAutoResumeGuard.noteSessionReset(sid);- interruptedTurnAutoResumeGuard.noteSessionReset(sid);- autoResumeBookkeeping.teardown(sid);+ resetAutomaticRecoveryForExplicitStop(sid);// 丢弃缓存的待注入交接 / fork 来源标记:它们是按 clear 之前的历史算出来的,// DB 侧的 cleared_at 抑制拦不住已经落进 registry 内存的那一份(首发被拒后// 缓存仍在),下次 send 会把旧血缘灌进用户刚显式清空的上下文。@@ -9022,19 +9046,29 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)ipcMain.handle(MAKER_INVOKE.ABORT_SESSION, async (_e, sessionId: unknown) => {if (typeof sessionId !== 'string') throwIpcError('INVALID_PARAMS', 'sessionId required');markWorkerManualInterruptIfKnown(sessionId, 'abort_session');- silentStopAutoResumeGuard.noteSessionReset(sessionId);- interruptedTurnAutoResumeGuard.noteSessionReset(sessionId);- autoResumeBookkeeping.teardown(sessionId);+ resetAutomaticRecoveryForExplicitStop(sessionId);+ // 调用本身先同步撤销 Goal 续跑资格;paused 落库与 vendor abort 并行。+ const goalPause = pauseGoalBeforeExplicitStop(sessionId);const sess = getStableSessionForTurnBoundary(sessionId);- if (!sess) return;+ if (!sess) {+ await goalPause;+ return;+ }handleAgentIslandSessionStopped(sess);- // 用户 Stop 当前 turn → 若该会话有 active goal,先暂停目标(置 paused + 停续跑 + detach- // 监听),**再** abort。这样 abort 产生的终止事件到来时目标已暂停、监听已摘,不会被误判成- // 续跑(原本依赖 error 文案正则判 paused/blocked,不可靠)。null-safe;无 active goal 时 no-op。- await goalStopObserver?.(sessionId);const directAbortBoundary = beginDirectAbortReconciliation(sessionId, sess);+ // Attach the rejection handler immediately: Goal storage can fail while a slow+ // vendor abort is still settling, and that failure must not become unhandled.+ const goalPauseResult = goalPause.then(+ () => ({ ok: true as const }),+ (error: unknown) => ({ ok: false as const, error }),+ );+ let abortFailed = false;+ let abortError: unknown;try {await sess.abort();+ } catch (error) {+ abortFailed = true;+ abortError = error;} finally {// The stable lookup may still be inside an owner-boundary transition;// reconciliation owns its own safe live-state lookup and must run even@@ -9045,6 +9079,20 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)cleanupPendingInteractionsForSession(sessionId, 'session_aborted');}}+ const settledGoalPause = await goalPauseResult;+ if (abortFailed) {+ if (!settledGoalPause.ok) {+ log.error('goal pause persistence also failed after session abort failure', {+ sessionId,+ error:+ settledGoalPause.error instanceof Error+ ? settledGoalPause.error.message+ : String(settledGoalPause.error),+ });+ }+ throw abortError;+ }+ if (!settledGoalPause.ok) throw settledGoalPause.error;});ipcMain.handle(MAKER_INVOKE.CLOSE_SESSION, async (_e, sessionId: unknown, opts?: unknown) => {diff --git a/apps/desktop/src/main/maker-ipc/stopSessionBackgroundTasksHandler.ts b/apps/desktop/src/main/maker-ipc/stopSessionBackgroundTasksHandler.tsindex c7deffe4ef..804273b9f4 100644--- a/apps/desktop/src/main/maker-ipc/stopSessionBackgroundTasksHandler.ts+++ b/apps/desktop/src/main/maker-ipc/stopSessionBackgroundTasksHandler.ts@@ -29,11 +29,26 @@ export function registerStopSessionBackgroundTasksHandler(}deps.noteSessionReset(sessionId);- // Best-effort: goal pause must not block the emergency close path.- await Promise.resolve(deps.notifyGoalStop(sessionId)).catch(() => {});- await deps.closeSession(sessionId);- // closed 事件的统一清理也会清账;这里显式清一次,确保 renderer 立即收到熄灭广播。- deps.clearBackgroundActivity(sessionId);+ // notifyGoalStop 调用同步摘 listener/timer,paused 落库可与紧急 close 并行;+ // 不能让存储等待挡住最终止损。+ let goalPause: Promise<void>;+ try {+ goalPause = Promise.resolve(deps.notifyGoalStop(sessionId));+ } catch (error) {+ goalPause = Promise.reject(error);+ }+ const [closeResult, goalPauseResult] = await Promise.allSettled([+ deps.closeSession(sessionId),+ goalPause,+ ]);+ if (closeResult.status === 'fulfilled') {+ // closed 事件的统一清理也会清账;这里显式清一次,确保 renderer 立即收到熄灭广播。+ deps.clearBackgroundActivity(sessionId);+ }+ // close 是主要止损动作:两边同时失败时保留它的原始错误;Goal pause 自身已经+ // 在 register.ts 记录了可诊断日志。任一边失败都不得向 renderer 谎报成功。+ if (closeResult.status === 'rejected') throw closeResult.reason;+ if (goalPauseResult.status === 'rejected') throw goalPauseResult.reason;return { ok: true as const };},);diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.tsindex 53f12a63ca..d390d45bf0 100644--- a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts@@ -97,6 +97,7 @@ vi.mock('@/lib/composerDraftStore', () => ({import { makerChatStore, type ChatMessage } from '@/lib/makerChatStore';import * as messageService from '@/lib/messageService';import * as sessionService from '@/lib/sessionService';+import * as sessionsBus from '@/lib/sessionsBus';import { CONTINUE_AFTER_APP_EXIT_PROMPT } from '../../shared/interruptedTurn';const SESSION_ID = 'text-delta-batching';@@ -998,6 +999,124 @@ describe('makerChatStore text delta batching', () => {unsubscribe();});+ it('coalesces 1000 high-frequency thinking updates into one subscriber notification', () => {+ let notifyCount = 0;+ const unsubscribe = makerChatStore.subscribe(SESSION_ID, () => {+ notifyCount += 1;+ });++ onEvent?.({+ sessionId: SESSION_ID,+ event: {+ type: 'thinking',+ source: 'codex',+ data: { stage: 'start', blockId: 'thinking-flood', startedAt: Date.now() },+ },+ });+ for (let i = 0; i < 999; i++) {+ onEvent?.({+ sessionId: SESSION_ID,+ event: {+ type: 'thinking',+ source: 'codex',+ data: { stage: 'delta', blockId: 'thinking-flood', text: 'x' },+ },+ });+ }++ expect(notifyCount).toBe(0);+ expect(makerChatStore.getSnapshot(SESSION_ID).messages[0]).toMatchObject({+ clientId: 'thinking-flood',+ content: 'x'.repeat(999),+ });++ vi.advanceTimersByTime(32);+ expect(notifyCount).toBe(1);+ unsubscribe();+ });++ it('keeps coalescing live tool DB echoes after Stop has optimistically gone idle', () => {+ emitStatus({ status: 'Running', isRunning: true });+ makerChatStore.stopSession(SESSION_ID);+ expect(makerChatStore.getSnapshot(SESSION_ID).agentStatus.isRunning).toBe(false);+ const eventCount = 800;+ let notifyCount = 0;+ const unsubscribe = makerChatStore.subscribe(SESSION_ID, () => {+ notifyCount += 1;+ });+ vi.mocked(sessionsBus.emitPatch).mockClear();++ for (let i = 0; i < eventCount; i++) {+ onEvent?.({+ sessionId: SESSION_ID,+ event: {+ type: 'tool_use',+ source: 'codex',+ data: {+ toolUseId: `tool-use-${i}`,+ toolName: 'Read',+ input: { file_path: `file-${i}.ts` },+ },+ },+ persistId: `tool-row-${i}`,+ });+ emitDbMessageCreated({+ clientId: `tool-row-${i}`,+ role: 'tool_use',+ content: {+ toolUseId: `tool-use-${i}`,+ toolName: 'Read',+ input: { file_path: `file-${i}.ts` },+ },+ toolUseId: `tool-use-${i}`,+ createdAt: new Date(Date.UTC(2026, 5, 15) + i).toISOString(),+ });+ }++ expect(notifyCount).toBe(0);+ expect(sessionsBus.emitPatch).not.toHaveBeenCalled();+ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toHaveLength(eventCount);+ expect(makerChatStore.getSnapshot(SESSION_ID).messages[eventCount - 1]).toMatchObject({+ clientId: 'tool-row-799',+ role: 'tool_use',+ toolUseId: 'tool-use-799',+ toolName: 'Read',+ });++ vi.advanceTimersByTime(32);+ expect(notifyCount).toBe(1);+ expect(sessionsBus.emitPatch).toHaveBeenCalledTimes(1);+ unsubscribe();+ });++ it('flushes a pending high-frequency batch immediately when terminal done arrives', () => {+ let notifyCount = 0;+ const unsubscribe = makerChatStore.subscribe(SESSION_ID, () => {+ notifyCount += 1;+ });++ onEvent?.({+ sessionId: SESSION_ID,+ event: {+ type: 'tool_use',+ source: 'codex',+ data: { toolUseId: 'tool-flood', toolName: 'exec', input: {} },+ },+ persistId: 'tool-flood-row',+ });+ expect(notifyCount).toBe(0);++ onEvent?.({+ sessionId: SESSION_ID,+ event: { type: 'done', source: 'codex', data: {} },+ });+ expect(notifyCount).toBe(1);++ vi.advanceTimersByTime(32);+ expect(notifyCount).toBe(1);+ unsubscribe();+ });+it('flushes at most 8 streaming sessions per timer tick', () => {for (const [index, sessionId] of MULTI_SESSION_IDS.entries()) {emitTextDelta(`s${index}`, sessionId);@@ -1025,6 +1144,66 @@ describe('makerChatStore text delta batching', () => {}});+ it('does not starve a Map-only sidebar patch behind 8 continuously active sessions', () => {+ const patchOnlySessionId = MULTI_SESSION_IDS[8];+ onEvent?.({+ sessionId: patchOnlySessionId,+ event: {+ type: 'tool_use',+ source: 'codex',+ data: { toolUseId: 'fair-tool', toolName: 'Read', input: { file_path: 'fair.ts' } },+ },+ persistId: 'fair-tool-row',+ });+ const persistedTool = {+ clientId: 'fair-tool-row',+ role: 'tool_use' as const,+ content: {+ toolUseId: 'fair-tool',+ toolName: 'Read',+ input: { file_path: 'fair.ts' },+ },+ toolUseId: 'fair-tool',+ createdAt: '2026-06-15T00:00:00.000Z',+ };+ emitDbMessageCreated(persistedTool, patchOnlySessionId);+ vi.advanceTimersByTime(32);+ vi.mocked(sessionsBus.emitPatch).mockClear();++ for (const sessionId of MULTI_SESSION_IDS.slice(0, 8)) {+ onEvent?.({+ sessionId,+ event: {+ type: 'thinking',+ source: 'codex',+ data: { stage: 'delta', blockId: 'fairness', text: 'a' },+ },+ });+ }+ // 完全相同的 DB echo 让 setState 走 no-op,只剩 sidebar patch 待发。+ emitDbMessageCreated(persistedTool, patchOnlySessionId);++ vi.advanceTimersByTime(32);+ expect(sessionsBus.emitPatch).not.toHaveBeenCalled();++ for (const sessionId of MULTI_SESSION_IDS.slice(0, 8)) {+ onEvent?.({+ sessionId,+ event: {+ type: 'thinking',+ source: 'codex',+ data: { stage: 'delta', blockId: 'fairness', text: 'b' },+ },+ });+ }+ vi.advanceTimersByTime(32);++ expect(sessionsBus.emitPatch).toHaveBeenCalledTimes(1);+ expect(sessionsBus.emitPatch).toHaveBeenCalledWith(patchOnlySessionId, {+ updatedAt: expect.any(String),+ });+ });+it('flushes pending text before a closed status finalizes the session', () => {emitTextDelta('a');@@ -1056,6 +1235,27 @@ describe('makerChatStore text delta batching', () => {]);});+ it('sends Stop IPC before flushing pending renderer work', () => {+ emitStatus({ status: 'Running', isRunning: true });+ const order: string[] = [];+ input.stop.mockImplementationOnce(async (sessionId: string) => {+ order.push('ipc');+ return projection(sessionId);+ });+ const unsubscribe = makerChatStore.subscribe(SESSION_ID, () => {+ order.push('notify');+ });+ emitTextDelta('pending');++ makerChatStore.stopSession(SESSION_ID);++ expect(input.stop).toHaveBeenCalledWith(SESSION_ID, undefined);+ expect(order[0]).toBe('ipc');+ expect(order).toContain('notify');+ expect(makerChatStore.getSnapshot(SESSION_ID).agentStatus.isRunning).toBe(false);+ unsubscribe();+ });+it('ignores placeholder 0/0 context snapshots on Done status', () => {emitStatus({status: 'Done',diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex bd5ec08eb3..742616c525 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -1215,6 +1215,87 @@ const lightSnapshotCache = new Map<string, SessionChatLightState>();*/const globalListeners = new Set<() => void>();+// 工具事件风暴时仍同步写入权威 state,但把 React/sidebar 订阅通知压成每会话每帧一次。+// Stop、terminal、interaction 等控制路径会取消该会话的待发通知并立即广播最新快照。+const HIGH_FREQUENCY_NOTIFY_INTERVAL_MS = 32;+const HIGH_FREQUENCY_NOTIFY_MAX_SESSIONS_PER_TICK = 8;+const pendingDeferredStateNotifications = new Set<string>();+const pendingMessageCreatedPatches = new Map<string, string>();+let deferredStateNotificationTimer: ReturnType<typeof setTimeout> | null = null;++function hasDeferredStateWork(): boolean {+ return pendingDeferredStateNotifications.size > 0 || pendingMessageCreatedPatches.size > 0;+}++function clearDeferredStateNotificationTimer(): void {+ if (!deferredStateNotificationTimer) return;+ clearTimeout(deferredStateNotificationTimer);+ deferredStateNotificationTimer = null;+}++function scheduleDeferredStateNotifications(): void {+ if (deferredStateNotificationTimer) return;+ deferredStateNotificationTimer = setTimeout(+ flushDeferredStateNotifications,+ HIGH_FREQUENCY_NOTIFY_INTERVAL_MS,+ );+}++function emitStateNotifications(sessionId: string): void {+ listeners.get(sessionId)?.forEach((cb) => {+ cb();+ });+}++function flushPendingMessageCreatedPatch(sessionId: string): void {+ const updatedAt = pendingMessageCreatedPatches.get(sessionId);+ if (!updatedAt) return;+ pendingMessageCreatedPatches.delete(sessionId);+ emitPatch(sessionId, { updatedAt });+}++function flushDeferredStateNotifications(): void {+ deferredStateNotificationTimer = null;+ const sessionIds = [+ ...new Set([+ ...pendingDeferredStateNotifications,+ ...pendingMessageCreatedPatches.keys(),+ ]),+ ].slice(0, HIGH_FREQUENCY_NOTIFY_MAX_SESSIONS_PER_TICK);+ let stateChanged = false;+ for (const sessionId of sessionIds) {+ if (pendingDeferredStateNotifications.delete(sessionId)) {+ stateChanged = true;+ emitStateNotifications(sessionId);+ }+ }+ if (stateChanged) {+ globalListeners.forEach((cb) => {+ cb();+ });+ }+ for (const sessionId of sessionIds) flushPendingMessageCreatedPatch(sessionId);+ if (hasDeferredStateWork()) scheduleDeferredStateNotifications();+}++function queueDeferredStateNotification(sessionId: string): void {+ pendingDeferredStateNotifications.add(sessionId);+ scheduleDeferredStateNotifications();+}++function queueMessageCreatedPatch(sessionId: string, updatedAt: string): void {+ pendingMessageCreatedPatches.set(sessionId, updatedAt);+ // patch 也进入同一个 FIFO session 集合。否则 Map-only 的 no-op DB echo 会永远排在+ // 持续活跃的前 8 个 state session 之后,slice 上限会让 sidebar patch 饥饿。+ queueDeferredStateNotification(sessionId);+}++function discardDeferredStateWork(sessionId: string): void {+ pendingDeferredStateNotifications.delete(sessionId);+ pendingMessageCreatedPatches.delete(sessionId);+ if (!hasDeferredStateWork()) clearDeferredStateNotificationTimer();+}+/*** Per-session onTitleUpdate callback. Registered lazily by `useCCAgentChat`* and invoked on `done` / sendMessage (auto-naming, sidebar refresh). We keep@@ -1299,6 +1380,7 @@ function isBeforeOrAtRendererClearBoundary(sessionId: string, createdAt: string)*/function _purgeSession(sessionId: string): void {discardPendingTextDelta(sessionId);+ discardDeferredStateWork(sessionId);clearIssueConfirmDraftsForSession(sessionId);// 代际递增(bump 而非 delete,原因见 _messagesEpoch 注释):作废 in-flight 翻页,// 避免其提交把旧窗口 merge 进 purge 后重建的空 slice。@@ -1539,7 +1621,11 @@ function getOrCreateState(sessionId: string): SessionChatState {return state;}-function setState(sessionId: string, updater: (prev: SessionChatState) => SessionChatState): void {+function setState(+ sessionId: string,+ updater: (prev: SessionChatState) => SessionChatState,+ opts: { deferNotification?: boolean } = {},+): void {const prev = getOrCreateState(sessionId);const next = updater(prev);if (next === prev) return;@@ -1551,19 +1637,25 @@ function setState(sessionId: string, updater: (prev: SessionChatState) => Sessio// running-status 快照缓存失效(getRunningSnapshot 纯 getter 契约:只有// mutation 才允许让下一次读重算)。必须在 notify 之前置位。markStatusSnapshotDirty();- listeners.get(sessionId)?.forEach((cb) => {- cb();- });+ if (opts.deferNotification) {+ queueDeferredStateNotification(sessionId);+ return;+ }+ // 控制事件优先:当前通知已经包含此前同步写入的所有高频状态,撤掉迟到批次。+ pendingDeferredStateNotifications.delete(sessionId);+ if (!hasDeferredStateWork()) clearDeferredStateNotificationTimer();+ emitStateNotifications(sessionId);// F-SB-7: notify global listeners so Sidebar can track all sessionsglobalListeners.forEach((cb) => {cb();});+ // messages:created 的侧栏时间戳与 chat state 保持原有先后:先通知消息,再 patch 列表。+ flushPendingMessageCreatedPatch(sessionId);+ if (!hasDeferredStateWork()) clearDeferredStateNotificationTimer();}function notify(sessionId: string): void {- listeners.get(sessionId)?.forEach((cb) => {- cb();- });+ emitStateNotifications(sessionId);}/**@@ -3386,11 +3478,24 @@ function isTextDeltaEvent(event: NonNullable<MakerEventPayload>['event']): boolereturn data?.isFinal === false && typeof data.text === 'string';}+function isHighFrequencyStreamEvent(+ event: NonNullable<MakerEventPayload>['event'],+): boolean {+ return (+ !!event &&+ (event.type === 'tool_use' ||+ event.type === 'tool_result' ||+ event.type === 'tool_result_full' ||+ event.type === 'thinking')+ );+}+function dispatchStreamEventPayload(sessionId: string,event: NonNullable<MakerEventPayload>['event'],persistId?: string,resolvedContent?: string,+ deferNotification = false,): void {if (!event) return;const streamEvent = {@@ -3403,7 +3508,7 @@ function dispatchStreamEventPayload(resolvedContent,} as CCAgentStreamEvent;supersedeInputProjectionOnTerminalEvent(sessionId, streamEvent);- setState(sessionId, (s) => handleStreamEvent(s, streamEvent));+ setState(sessionId, (s) => handleStreamEvent(s, streamEvent), { deferNotification });}function clearTextDeltaFlushTimer(): void {@@ -3417,7 +3522,7 @@ function discardPendingTextDelta(sessionId: string): void {if (pendingTextDeltaBatches.size === 0) clearTextDeltaFlushTimer();}-function flushPendingTextDelta(sessionId: string): void {+function flushPendingTextDelta(sessionId: string, deferNotification = false): void {const pending = pendingTextDeltaBatches.get(sessionId);if (!pending) return;pendingTextDeltaBatches.delete(sessionId);@@ -3432,6 +3537,8 @@ function flushPendingTextDelta(sessionId: string): void {...(pending.agentMeta ? { agentMeta: pending.agentMeta } : {}),},pending.persistId,+ undefined,+ deferNotification,);}@@ -3718,7 +3825,8 @@ function initGlobalListeners(): void {enqueueTextDeltaPayload(sessionId, event, persistId);return;}- flushPendingTextDelta(sessionId);+ const deferNotification = isHighFrequencyStreamEvent(event);+ flushPendingTextDelta(sessionId, deferNotification);// session_id: 老链路是单独 IPC channel, 新链路融进 maker:event (Claude / Codex 同源)if (event.type === 'session_id') {@@ -3893,7 +4001,13 @@ function initGlobalListeners(): void {}}- dispatchStreamEventPayload(sessionId, event, persistId, resolvedContent);+ dispatchStreamEventPayload(+ sessionId,+ event,+ persistId,+ resolvedContent,+ deferNotification,+ );// done / error 副作用 (从老 stream listener 搬过来)if (event.type === 'done') {@@ -4199,30 +4313,62 @@ function initGlobalListeners(): void {if (isBeforeOrAtRendererClearBoundary(sessionId, message.createdAt)) return;const [mapped] = mapServerMessages([message]);if (!mapped) return;- setState(sessionId, (s) => {- const idx = s.messages.findIndex((m) => m.clientId === mapped.clientId);- if (idx >= 0) {- const nextMessages = mergeMessages([mapped], s.messages, {+ const current = getOrCreateState(sessionId);+ const existing = current.messages.find((candidate) => candidate.clientId === mapped.clientId);+ const isLiveToolEcho =+ existing?.role === mapped.role &&+ (mapped.role === 'tool_use' || mapped.role === 'tool_result');+ // Stop 会乐观置 Idle,但真正的 interrupt 可能还在 IPC 队列里;此时旧 turn 继续喷出的+ // live tool + DB echo 仍必须走批通知,否则按钮一按下就退化回事故中的逐行 React fan-out。+ const deferNotification =+ current.agentStatus.isRunning || current.isStreaming || isLiveToolEcho;+ setState(+ sessionId,+ (s) => {+ const hydrateOptions = {preserveExistingToolResultContent: true,preserveExistingCodexPlanContent: true,- });+ } as const;+ const existingIdx = s.messages.findIndex((m) => m.clientId === mapped.clientId);+ const existing = existingIdx >= 0 ? s.messages[existingIdx] : undefined;+ const canHydrateInPlace =+ existing !== undefined &&+ existing.role === mapped.role &&+ (mapped.role === 'tool_use' || mapped.role === 'tool_result');+ if (canHydrateInPlace) {+ // live tool 事件先建行、DB onCreated 随后回声是事故现场的绝大多数路径。+ // 位置已经确定,直接原位 hydrate;旧实现仍调用 mergeMessages,导致每一条+ // 回声都对不断增长的整段消息重新遍历并排序,1,500+ 行时拖死 Renderer。+ // 仅限 tool 行:thinking 的 persisted createdAt 会回填块开始时间,必须让+ // mergeMessages 重排;assistant 等其它角色也保留原有权威时间线语义。+ const hydrated = hydratePersistedMessage(+ existing,+ mapped,+ hydrateOptions,+ );+ if (hydrated === existing) return s;+ const nextMessages = s.messages.slice();+ nextMessages[existingIdx] = hydrated;+ return {+ ...s,+ messages: nextMessages,+ isFirstMessage: mapped.role === 'user' ? false : s.isFirstMessage,+ };+ }+ const nextMessages = mergeMessages([mapped], s.messages, hydrateOptions);+ if (nextMessages === s.messages) return s;return {...s,messages: nextMessages,isFirstMessage: mapped.role === 'user' ? false : s.isFirstMessage,};- }- return {- ...s,- messages: mergeMessages([mapped], s.messages, {- preserveExistingToolResultContent: true,- preserveExistingCodexPlanContent: true,- }),- isFirstMessage: mapped.role === 'user' ? false : s.isFirstMessage,- };- });+ },+ { deferNotification },+ );// sidebar 排序时间轴 — 让接管路径下新消息也能 bump session 顺序。- emitPatch(sessionId, { updatedAt: new Date().toISOString() });+ const updatedAt = new Date().toISOString();+ if (deferNotification) queueMessageCreatedPatch(sessionId, updatedAt);+ else emitPatch(sessionId, { updatedAt });}// 消息本地删除推送:本机多窗口与 device-link 控制端共用同一 reducer。@@ -4806,6 +4952,9 @@ function __teardownGlobalListeners(): void {_stopDemoteTimer();clearTextDeltaFlushTimer();pendingTextDeltaBatches.clear();+ clearDeferredStateNotificationTimer();+ pendingDeferredStateNotifications.clear();+ pendingMessageCreatedPatches.clear();_pendingErrorClearOnLeave.clear();// Stage 2 C1: 老的 cc-agent:* fan-out 已退役, __resetCCAgentFanOuts 也跟着删了。// 新链路 maker:* fan-out 当前不会泄漏 (initGlobalListeners 顶部 if guard +@@ -8027,7 +8176,6 @@ function stopSession(opts?: { keepQueue?: boolean; pauseQueue?: boolean },): void {if (!sessionId) return;- flushPendingTextDelta(sessionId);const api = makerApiFor(sessionId);// Stop 的乐观终态必须立即作废此前同源查询与旧操作;不能等响应回来,// 否则旧结果会在 abort 往返期间把刚清掉的 owner 重新写回。先推进再捕获,@@ -8044,6 +8192,9 @@ function stopSession(applyInputProjectionOperationResponse(sessionId, operation, projection);}).catch((err) => log.warn('maker.input.stop failed:', err));+ // 控制请求必须先跨过 preload IPC。事故现场积压了 1,500+ 条大体积 tool/DB 事件;+ // 本地文本与 DB 批次收口即便变慢,也不能把真正的 turn/interrupt 挡在它们后面。+ flushPendingTextDelta(sessionId);setState(sessionId, (s) => {const id = s.streamingClientId;// F7.6 / FP-3: expire any pending ask_user + plan_review messages on stop