Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): reconcile sessions after boundary rollback
DavidShen4d9b7d3d47e1
diff --git a/apps/desktop/src/renderer/__tests__/authContextSessionBoundary.test.tsx b/apps/desktop/src/renderer/__tests__/authContextSessionBoundary.test.tsxindex 25ca4e563c..8929132ec6 100644--- a/apps/desktop/src/renderer/__tests__/authContextSessionBoundary.test.tsx+++ b/apps/desktop/src/renderer/__tests__/authContextSessionBoundary.test.tsx@@ -27,6 +27,7 @@ const mocks = vi.hoisted(() => {service,reset: vi.fn(),cancelRemoteOptimisticSendsForDataOwnerBoundary: vi.fn(),+ reconcileSessionsAfterDataOwnerRollback: vi.fn(async () => undefined),getMe: vi.fn(async () => ({ role: 'user' })),clearWorkersCache: vi.fn(),setModelVisibilityOwner: vi.fn(),@@ -54,6 +55,7 @@ vi.mock('@/lib/authService', () => ({vi.mock('@/lib/makerChatStore', () => ({cancelRemoteOptimisticSendsForDataOwnerBoundary:mocks.cancelRemoteOptimisticSendsForDataOwnerBoundary,+ reconcileSessionsAfterDataOwnerRollback: mocks.reconcileSessionsAfterDataOwnerRollback,setCurrentUserName: vi.fn(),}));vi.mock('@/lib/sessionsStore', () => ({@@ -155,6 +157,7 @@ describe('AuthContext session cache boundaries', () => {beforeEach(() => {mocks.reset.mockClear();mocks.cancelRemoteOptimisticSendsForDataOwnerBoundary.mockClear();+ mocks.reconcileSessionsAfterDataOwnerRollback.mockClear();mocks.getMe.mockClear();mocks.clearWorkersCache.mockClear();mocks.setModelVisibilityOwner.mockClear();@@ -339,7 +342,7 @@ describe('AuthContext session cache boundaries', () => {expect(mocks.cancelRemoteOptimisticSendsForDataOwnerBoundary).toHaveBeenCalledTimes(2);});- it('does not finalize when a failed boundary rolls back from a pending signed-out push', async () => {+ it('reconciles Main runtime on a rollback push before the auth IPC rejects', async () => {let rejectLogout!: (error: Error) => void;mocks.service.logout.mockReturnValueOnce(new Promise<void>((_resolve, reject) => {@@ -360,12 +363,45 @@ describe('AuthContext session cache boundaries', () => {expect(mocks.cancelRemoteOptimisticSendsForDataOwnerBoundary).toHaveBeenLastCalledWith({finalizeSessions: false,});+ expect(mocks.reconcileSessionsAfterDataOwnerRollback).toHaveBeenCalledTimes(1);await act(async () => {rejectLogout(new Error('logout failed'));await expect(logout).rejects.toThrow('logout failed');});- expect(view.result.current.dataOwnerId).toBe('account-a');+ expect(getDataOwnerGeneration().dataOwnerId).toBe('account-a');+ });++ it('reconciles Main runtime on IPC rejection without a rollback push', async () => {+ let rejectLogout!: (error: Error) => void;+ mocks.service.logout.mockReturnValueOnce(+ new Promise<void>((_resolve, reject) => {+ rejectLogout = reject;+ }),+ );+ const view = renderHook(() => useAuth(), { wrapper });+ await waitFor(() => expect(view.result.current.dataOwnerId).toBe('account-a'));+ mocks.cancelRemoteOptimisticSendsForDataOwnerBoundary.mockClear();++ let logout!: Promise<void>;+ act(() => {+ logout = view.result.current.logout();+ });+ act(() => mocks.emitAuth({ ...authState(null), ownerGeneration: 1 }));+ expect(mocks.cancelRemoteOptimisticSendsForDataOwnerBoundary).toHaveBeenLastCalledWith({+ finalizeSessions: false,+ });++ await act(async () => {+ rejectLogout(new Error('logout failed'));+ await expect(logout).rejects.toThrow('logout failed');+ });++ expect(mocks.cancelRemoteOptimisticSendsForDataOwnerBoundary).toHaveBeenLastCalledWith({+ finalizeSessions: false,+ });+ expect(mocks.reconcileSessionsAfterDataOwnerRollback).toHaveBeenCalledTimes(1);+ expect(getDataOwnerGeneration().dataOwnerId).toBe('account-a');});it('keeps a newer pushed owner when an older auth boundary later rejects', async () => {diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreTaskUpdates.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreTaskUpdates.test.tsindex 599a8f8b91..9d22184416 100644--- a/apps/desktop/src/renderer/__tests__/makerChatStoreTaskUpdates.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreTaskUpdates.test.ts@@ -78,6 +78,7 @@ vi.mock('@/lib/makerTransport', () => ({import {cancelRemoteOptimisticSendsForDataOwnerBoundary,+ reconcileSessionsAfterDataOwnerRollback,EMPTY_SESSION_STATE,handleStreamEvent,makerChatStore,@@ -980,6 +981,31 @@ describe('getRunningSnapshot 后台 subagent 折算(真 store)', () => {}});+ it('rollback reconciliation finalizes only sessions absent from Main after teardown', async () => {+ const sid = 'rollback-reconcile-' + Math.random().toString(36).slice(2, 8);+ const globalWindow = globalThis as typeof globalThis & {+ window?: { electronAPI?: unknown };+ };+ const previousWindow = globalWindow.window;+ const previousElectronApi = previousWindow?.electronAPI;+ try {+ setDataOwnerGeneration('account-a', 1);+ makerChatStore.__applyStatusUpdateForTest(sid, statusUpdate(sid, true));+ applyTask(sid, { taskId: 't1', status: 'running', taskType: 'local_agent' });+ globalWindow.window = {+ electronAPI: { maker: { listActive: vi.fn(async () => []) } },+ } as typeof globalWindow.window;++ await reconcileSessionsAfterDataOwnerRollback();+ expect(makerChatStore.getSnapshot(sid).agentStatus.isRunning).toBe(false);+ expect(makerChatStore.getSnapshot(sid).taskUpdates?.get('t1')?.status).toBe('stopped');+ } finally {+ makerChatStore.purgeSession(sid);+ dataOwnerGenerationTesting.reset();+ globalWindow.window = previousWindow;+ }+ });+it('session closed 兜底(finalizeStuckRemoteTurn → forceFinalize):running 任务全收口、桥接清零', () => {const sid = `remote-closed-${Math.random().toString(36).slice(2, 8)}`;try {diff --git a/apps/desktop/src/renderer/contexts/AuthContext.tsx b/apps/desktop/src/renderer/contexts/AuthContext.tsxindex d1eb545784..b166ce0780 100644--- a/apps/desktop/src/renderer/contexts/AuthContext.tsx+++ b/apps/desktop/src/renderer/contexts/AuthContext.tsx@@ -30,6 +30,7 @@ import {} from '@/lib/authService';import {cancelRemoteOptimisticSendsForDataOwnerBoundary,+ reconcileSessionsAfterDataOwnerRollback,setCurrentUserName,} from '@/lib/makerChatStore';import { isSecondaryWindow } from '@/lib/secondaryWindow';@@ -177,14 +178,15 @@ export function AuthProvider({const activeDataOwnerIdRef = useRef<string | null>(null);const activeDataOwnerGenerationRef = useRef(0);const authStateVersionRef = useRef(0);+ const pendingOwnerProjectionRef = useRef(false);// Auth mutations invalidate owner-bound in-flight reads before crossing IPC. If Main rejects// 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> => {// 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.+ // cached turn until the new owner has committed. On failure, reconcile+ // against Main: an early rejection keeps the runtime, a late one may not.publishDataOwnerGeneration(null, undefined, { finalizeSessions: false });try {return await operation();@@ -197,6 +199,11 @@ export function AuthProvider({activeDataOwnerGenerationRef.current,{ finalizeSessions: false },);+ const rollbackNeedsReconcile = pendingOwnerProjectionRef.current;+ pendingOwnerProjectionRef.current = false;+ if (rollbackNeedsReconcile) {+ void reconcileSessionsAfterDataOwnerRollback();+ }setDataOwnerGenerationState(activeDataOwnerGenerationRef.current);setDataOwnerRecoveryEpoch((epoch) => epoch + 1);void preloadLocalCatalogSnapshot();@@ -230,6 +237,9 @@ export function AuthProvider({&& state.ownerGeneration === activeDataOwnerGenerationRef.current;const ownerChanged =!pendingSignedOutProjection && activeDataOwnerIdRef.current !== state.dataOwnerId;+ const ownerRolledBack =+ pendingOwnerProjectionRef.current && !pendingSignedOutProjection && !ownerChanged;+ pendingOwnerProjectionRef.current = pendingSignedOutProjection;// A same-owner push can arrive while an auth boundary is still waiting// for IPC. The pre-commit fence temporarily publishes null, so letting// that push use the default finalizer would stop the current owner's@@ -240,6 +250,7 @@ export function AuthProvider({state.ownerGeneration,{ finalizeSessions: ownerChanged },);+ if (ownerRolledBack) void reconcileSessionsAfterDataOwnerRollback();if (ownerChanged) {sessionsStore.reset();clearWorkersCache();diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex 3d9a07f9e4..583716c9c5 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -9785,6 +9785,38 @@ function isActiveSessionSnapshot(value: unknown): value is ActiveSessionSnapshot);}+/** A rejected account change can leave the old owner with already-closed SDK sessions. */+export async function reconcileSessionsAfterDataOwnerRollback(): Promise<void> {+ const listActive = typeof window === 'undefined' ? undefined : window.electronAPI?.maker?.listActive;+ if (typeof listActive !== 'function') return;+ const owner = getDataOwnerGeneration();+ if (owner.dataOwnerId === null) return;+ const candidates = [...sessions].filter(([id, state]) =>+ !isRemoteSession(id) && hasActiveTurnStateForOwnerBoundary(state),+ );+ if (candidates.length === 0) return;+ try {+ const active = await listActive();+ // Compare the publication object too: A -> null -> A may reuse the same+ // main generation on rollback, but must invalidate the older read.+ if (getDataOwnerGeneration() !== owner) return;+ if (!Array.isArray(active) || !active.every(isActiveSessionSnapshot)) return;+ const liveTurns = new Map(active.map((item) => [item.sessionId, item.isTurnRunning]));+ for (const [id, state] of candidates) {+ // Keep a turn that Main still reports running, and never apply a delayed+ // absence to a new turn or changed session. A live-but-idle handle has+ // already stopped its turn and must take the same finalizer path.+ if (liveTurns.get(id) === true || sessions.get(id) !== state) continue;+ bumpInteractionReconcileEpoch(id);+ supersedeInputProjectionRequests(id, { supersedeOperations: true });+ flushPendingTextDelta(id);+ setState(id, forceFinalizeOnSessionClosed);+ }+ } catch (error) {+ log.warn('Failed to reconcile maker sessions after auth rollback:', error);+ }+}+/*** Renderer reload recovery: main keeps the live SDK sessions, but this module's* in-memory `isStreaming` state is lost. Pull the main-side turn snapshot once