Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): defer account teardown finalization until commit
DavidShen5e22f1c4d907
diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreTaskUpdates.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreTaskUpdates.test.tsindex ef9a881b45..599a8f8b91 100644--- a/apps/desktop/src/renderer/__tests__/makerChatStoreTaskUpdates.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreTaskUpdates.test.ts@@ -85,6 +85,7 @@ import {} from '@/lib/makerChatStore';import type { SessionChatState } from '@/lib/makerChatStore';import type { Message } from '@/lib/ccAgent.types';+import { setDataOwnerGeneration, __testing as dataOwnerGenerationTesting } from '@/contexts/dataOwnerGeneration';describe('makerChatStore IM source projection', () => {it.each(['imSource', 'hookSource'] as const)('projects %s into the common Desktop card', (field) => {@@ -939,26 +940,43 @@ describe('getRunningSnapshot 后台 subagent 折算(真 store)', () => {it('account teardown reuses the Stop/closed finalizer and does not revive on A→B→A', () => {const sid = `account-boundary-${Math.random().toString(36).slice(2, 8)}`;try {+ setDataOwnerGeneration('account-a', 1);makerChatStore.__applyStatusUpdateForTest(sid, statusUpdate(sid, true));applyTask(sid, { taskId: 't1', status: 'running', taskType: 'local_agent' });expect(makerChatStore.getSnapshot(sid).agentStatus.startedAt).toBeTruthy();// AuthContext invokes this synchronously when the outgoing owner enters// teardown; the old stamped status=closed push is no longer required.- cancelRemoteOptimisticSendsForDataOwnerBoundary();+ setDataOwnerGeneration(null, 2);+ cancelRemoteOptimisticSendsForDataOwnerBoundary({ finalizeSessions: false });let state = makerChatStore.getSnapshot(sid);+ // A rejected switch restores A, so the pre-commit invalidation must not+ // stop the task that still belongs to the active account.+ expect(state.agentStatus.isRunning).toBe(true);+ expect(state.agentStatus.startedAt).toBeTruthy();+ setDataOwnerGeneration('account-a', 3);++ // A successful A→B commit finalizes the old owner exactly once.+ setDataOwnerGeneration(null, 4);+ cancelRemoteOptimisticSendsForDataOwnerBoundary({ finalizeSessions: false });+ setDataOwnerGeneration('account-b', 5);+ cancelRemoteOptimisticSendsForDataOwnerBoundary();+ state = makerChatStore.getSnapshot(sid);expect(state.agentStatus.isRunning).toBe(false);expect(state.agentStatus.startedAt).toBeNull();expect(state.taskUpdates?.get('t1')?.status).toBe('stopped');// Re-entering account A must observe the stopped snapshot, with no// automatic continuation caused by the boundary cleanup.- cancelRemoteOptimisticSendsForDataOwnerBoundary();+ setDataOwnerGeneration(null, 6);+ cancelRemoteOptimisticSendsForDataOwnerBoundary({ finalizeSessions: false });+ setDataOwnerGeneration('account-a', 7);state = makerChatStore.getSnapshot(sid);expect(state.agentStatus.isRunning).toBe(false);expect(state.agentStatus.startedAt).toBeNull();} finally {makerChatStore.purgeSession(sid);+ dataOwnerGenerationTesting.reset();}});diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.tsindex 56897fc279..aa19e7a765 100644--- a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts@@ -5144,9 +5144,9 @@ describe('makerChatStore text delta batching', () => {expect(makerChatStore.getSnapshot(SESSION_ID).queueInteractionLocks).toEqual(['new-owner-lock',]);- expect(makerChatStore.getSnapshot(SESSION_ID).steeringQueueClientIds).toEqual([- 'already-steering',- ]);+ // Account teardown reuses the Stop/closed finalizer, so an in-flight steer+ // marker cannot survive into the next owner generation.+ expect(makerChatStore.getSnapshot(SESSION_ID).steeringQueueClientIds).toEqual([]);expect(input.getProjection).not.toHaveBeenCalled();});diff --git a/apps/desktop/src/renderer/contexts/AuthContext.tsx b/apps/desktop/src/renderer/contexts/AuthContext.tsxindex d50de4f8ee..18200a6f50 100644--- a/apps/desktop/src/renderer/contexts/AuthContext.tsx+++ b/apps/desktop/src/renderer/contexts/AuthContext.tsx@@ -121,11 +121,16 @@ const AuthContext = createContext<AuthContextValue | null>(null);const log = createLogger('AuthContext');-function publishDataOwnerGeneration(dataOwnerId: string | null, ownerGeneration?: number): void {+function publishDataOwnerGeneration(+ dataOwnerId: string | null,+ ownerGeneration?: number,+ options?: { finalizeSessions?: boolean },+): void {const previousOwnerId = getDataOwnerGeneration().dataOwnerId;if (previousOwnerId !== dataOwnerId) {resetTaskTagCatalogCache();- cancelRemoteOptimisticSendsForDataOwnerBoundary();+ if (options) cancelRemoteOptimisticSendsForDataOwnerBoundary(options);+ else cancelRemoteOptimisticSendsForDataOwnerBoundary();}setDataOwnerGeneration(dataOwnerId, ownerGeneration);recentWorkdirsStore.setDataOwner(getDataOwnerGeneration());@@ -172,9 +177,17 @@ export function AuthProvider({// the transition, restore the single authoritative owner ref (which successful siblings and// newer pushes both update), then rebuild the cache because React state may never have changed.const runDataOwnerBoundary = useCallback(async <T,>(operation: () => Promise<T>): Promise<T> => {- publishDataOwnerGeneration(null);+ // Invalidate old-owner ingress before crossing IPC, but defer stopping the+ // cached turn until the new owner has committed. A rejected switch must+ // leave the current account's task resumable in its original running state.+ publishDataOwnerGeneration(null, undefined, { finalizeSessions: false });try {- return await operation();+ const result = await operation();+ // The boundary has committed once the auth operation resolves. Finalize+ // here as well as on the pushed snapshot so a delayed auth event cannot+ // leave the old owner running after a successful switch.+ cancelRemoteOptimisticSendsForDataOwnerBoundary();+ return result;} catch (error) {// Restore the exact main-owned generation. Recomputing it locally would// make every stamped push from the still-active owner look stale after a@@ -182,6 +195,7 @@ export function AuthProvider({publishDataOwnerGeneration(activeDataOwnerIdRef.current,activeDataOwnerGenerationRef.current,+ { finalizeSessions: false },);setDataOwnerGenerationState(activeDataOwnerGenerationRef.current);setDataOwnerRecoveryEpoch((epoch) => epoch + 1);diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex 3584098720..3d9a07f9e4 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -2019,13 +2019,16 @@ function clearRemoteOptimisticSendsForSession(sessionId: string): void {* 恢复尚未确认受理的正文/附件,再清账本与 UI;之后任何迟到 invoke / projection* 都会同时被 Map identity 与 data-owner generation 挡住,不能跨账号继续投递或恢复。*/-export function cancelRemoteOptimisticSendsForDataOwnerBoundary(): void {+export function cancelRemoteOptimisticSendsForDataOwnerBoundary(+ options: { finalizeSessions?: boolean } = {},+): void {invalidateLiveIngressForDataOwnerBoundary();- // Account teardown intentionally stops the outgoing runtime. Its closed- // status push carries the old owner stamp and is therefore dropped by the- // owner fence; apply the same finalization used by the Stop/closed path- // synchronously before publishing the next owner.- finalizeSessionsForDataOwnerBoundary();+ // A committed account teardown intentionally stops the outgoing runtime. Its+ // closed status push carries the old owner stamp and is therefore dropped by+ // the owner fence; apply the same finalization used by the Stop/closed path.+ // AuthContext passes finalizeSessions=false for the pre-commit invalidation+ // so a failed switch can restore the still-running current owner.+ if (options.finalizeSessions !== false) finalizeSessionsForDataOwnerBoundary();// Invalidate standalone projection reads/operations before restoring drafts// or publishing the next owner. Their promises may settle independently of// the optimistic outbox and must not write old-owner state into the new slice.@@ -2155,8 +2158,14 @@ function hasActiveTurnStateForOwnerBoundary(state: SessionChatState): boolean {state.pendingRemoteDesktopConfirmation !== null ||state.pendingRemoteDesktopConfirmationQueue.length > 0 ||state.queueAbortPending ||+ state.steeringQueueClientIds.length > 0 ||state.continuationTurnClientId !== null ||state.pendingTaskWake > 0 ||+ state.messages.some(+ (message) =>+ message.clientId === CODEX_RECONNECT_PENDING_CLIENT_ID ||+ message.clientId === AUTO_RESUME_PENDING_CLIENT_ID,+ ) ||[...(state.taskUpdates?.values() ?? [])].some((task) => task.status === 'running'));}