Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): harden account boundary rollback finalization

DavidShenb8227cf68056
diff --git a/apps/desktop/src/renderer/__tests__/authContextRace.test.ts b/apps/desktop/src/renderer/__tests__/authContextRace.test.ts
index d6694e9ad8..f12255ab5a 100644
--- a/apps/desktop/src/renderer/__tests__/authContextRace.test.ts
+++ b/apps/desktop/src/renderer/__tests__/authContextRace.test.ts
@@ -75,7 +75,7 @@ describe('AuthContext auth-state races', () => {
expect(source).toContain('recentWorkdirsStore.setDataOwner(getDataOwnerGeneration());');
expect(source).toContain('invalidateProvidersSnapshot();');
expect(source).toContain('publishDataOwnerGeneration(');
- expect(source).toContain('{ finalizeSessions: ownerChanged && !initialOwnerHydration }');
+ expect(source).toContain('{ finalizeSessions: ownerBoundaryCommitted && !initialOwnerHydration }');
expect(source).toContain(
'// Invalidate in-flight remote sends before the confirmation dialog resolves.',
);
diff --git a/apps/desktop/src/renderer/__tests__/authContextSessionBoundary.test.tsx b/apps/desktop/src/renderer/__tests__/authContextSessionBoundary.test.tsx
index 96e28f1783..65f3e2022d 100644
--- a/apps/desktop/src/renderer/__tests__/authContextSessionBoundary.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/authContextSessionBoundary.test.tsx
@@ -33,6 +33,8 @@ const mocks = vi.hoisted(() => {
setModelVisibilityOwner: vi.fn(),
invalidateProvidersSnapshot: vi.fn(),
preloadLocalCatalogSnapshot: vi.fn(async () => undefined),
+ setMemorySettingsOwner: vi.fn(),
+ bootstrapMemorySettingsFromMain: vi.fn(async () => undefined),
confirm: vi.fn(async () => true),
emitAuth(state: unknown) {
authStateListener?.(state);
@@ -74,6 +76,10 @@ vi.mock('@/lib/providersSnapshotStore', () => ({
vi.mock('@/lib/localCatalogSnapshot', () => ({
preloadLocalCatalogSnapshot: mocks.preloadLocalCatalogSnapshot,
}));
+vi.mock('@/lib/memorySettingsStore', () => ({
+ setMemorySettingsOwner: mocks.setMemorySettingsOwner,
+ bootstrapMemorySettingsFromMain: mocks.bootstrapMemorySettingsFromMain,
+}));
vi.mock('@/components/ui/confirm-dialog-provider', () => ({
useConfirmDialog: () => ({ confirm: mocks.confirm }),
}));
@@ -164,6 +170,8 @@ describe('AuthContext session cache boundaries', () => {
mocks.setModelVisibilityOwner.mockClear();
mocks.invalidateProvidersSnapshot.mockClear();
mocks.preloadLocalCatalogSnapshot.mockClear();
+ mocks.setMemorySettingsOwner.mockClear();
+ mocks.bootstrapMemorySettingsFromMain.mockClear();
dataOwnerGenerationTesting.reset();
mocks.service.consumeAccountDeletionRestoredNotice.mockClear();
restoredToast.mockClear();
@@ -248,6 +256,8 @@ describe('AuthContext session cache boundaries', () => {
});
expect(mocks.reconcileSessionsAfterDataOwnerRollback).toHaveBeenCalledOnce();
expect(view.result.current.dataOwnerId).toBe('account-a');
+ expect(mocks.setMemorySettingsOwner).toHaveBeenLastCalledWith('account-a');
+ expect(mocks.bootstrapMemorySettingsFromMain).toHaveBeenCalled();
});
it('preserves a pending rollback when the first snapshot has no owner stamp', async () => {
@@ -314,6 +324,28 @@ describe('AuthContext session cache boundaries', () => {
expect(view.result.current.dataOwnerId).toBe('account-b');
});
+ it('finalizes a fresh renderer when a pending projection commits to null', async () => {
+ mocks.service.initialize.mockResolvedValue({
+ ...authState(null),
+ ownerGeneration: 1,
+ ownerBoundaryPending: true,
+ });
+ const view = renderHook(() => useAuth(), { wrapper });
+ await waitFor(() => expect(view.result.current.dataOwnerId).toBeNull());
+
+ mocks.cancelRemoteOptimisticSendsForDataOwnerBoundary.mockClear();
+ act(() => mocks.emitAuth({ ...authState(null), ownerGeneration: 2 }));
+
+ expect(mocks.cancelRemoteOptimisticSendsForDataOwnerBoundary).toHaveBeenLastCalledWith({
+ finalizeSessions: true,
+ });
+ expect(mocks.reset).toHaveBeenCalled();
+ expect(mocks.clearWorkersCache).toHaveBeenCalled();
+ expect(mocks.setMemorySettingsOwner).toHaveBeenLastCalledWith(null);
+ expect(mocks.bootstrapMemorySettingsFromMain).toHaveBeenCalled();
+ expect(view.result.current.dataOwnerId).toBeNull();
+ });
+
it('resets sessions when authentication expires', async () => {
renderHook(() => useAuth(), { wrapper });
await waitFor(() => expect(mocks.service.initialize).toHaveBeenCalled());
diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreTaskUpdates.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreTaskUpdates.test.ts
index 2e86ee960b..1895eb27a8 100644
--- a/apps/desktop/src/renderer/__tests__/makerChatStoreTaskUpdates.test.ts
+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreTaskUpdates.test.ts
@@ -1240,4 +1240,83 @@ describe('getRunningSnapshot 后台 subagent 折算(真 store)', () => {
globalWindow.window = previousWindow;
}
});
+
+ it('owner finalization clears a queued input recovery marker', async () => {
+ const sid = 'rollback-queued-recovery-' + Math.random().toString(36).slice(2, 8);
+ const globalWindow = globalThis as typeof globalThis & {
+ window?: { electronAPI?: unknown };
+ };
+ const previousWindow = globalWindow.window;
+ try {
+ setDataOwnerGeneration('account-a', 1);
+ makerChatStore.__applyInputProjectionForTest({
+ sessionId: sid,
+ pendingQueue: [],
+ steeringQueueClientIds: [],
+ queuePaused: true,
+ queueExpanded: false,
+ queueInteractionLocks: [],
+ queueEditLocks: [],
+ queueAbortPending: false,
+ error: null,
+ recovery: { kind: 'queue-head', clientId: 'recovery-1' },
+ errorRetryText: null,
+ credentialSwitchWait: null,
+ });
+
+ globalWindow.window = {
+ electronAPI: {
+ maker: {
+ listActive: vi.fn(async () => [
+ { sessionId: sid, agentKind: 'codex', isTurnRunning: false },
+ ]),
+ },
+ },
+ } as typeof globalWindow.window;
+
+ await reconcileSessionsAfterDataOwnerRollback();
+ expect(makerChatStore.getSnapshot(sid).inputRecovery).toBeNull();
+ } finally {
+ makerChatStore.purgeSession(sid);
+ dataOwnerGenerationTesting.reset();
+ globalWindow.window = previousWindow;
+ }
+ });
+
+ it('does not finalize a replacement session created while Main is queried', async () => {
+ const sid = 'rollback-replaced-' + Math.random().toString(36).slice(2, 8);
+ const globalWindow = globalThis as typeof globalThis & {
+ window?: { electronAPI?: unknown };
+ };
+ const previousWindow = globalWindow.window;
+ try {
+ setDataOwnerGeneration('account-a', 1);
+ makerChatStore.__applyStatusUpdateForTest(sid, statusUpdate(sid, true));
+ let resolveListActive!: (value: unknown[]) => void;
+ globalWindow.window = {
+ electronAPI: {
+ maker: {
+ listActive: vi.fn(
+ () => new Promise<unknown[]>((resolve) => { resolveListActive = resolve; }),
+ ),
+ },
+ },
+ } as typeof globalWindow.window;
+
+ const reconciliation = reconcileSessionsAfterDataOwnerRollback();
+ await Promise.resolve();
+ makerChatStore.purgeSession(sid);
+ makerChatStore.__applyStatusUpdateForTest(sid, statusUpdate(sid, false));
+ resolveListActive([]);
+ await reconciliation;
+
+ const replacement = makerChatStore.getSnapshot(sid);
+ expect(replacement.agentStatus.isRunning).toBe(false);
+ expect(replacement.taskUpdates?.size ?? 0).toBe(0);
+ } finally {
+ makerChatStore.purgeSession(sid);
+ dataOwnerGenerationTesting.reset();
+ globalWindow.window = previousWindow;
+ }
+ });
});
diff --git a/apps/desktop/src/renderer/contexts/AuthContext.tsx b/apps/desktop/src/renderer/contexts/AuthContext.tsx
index 3f596fd645..308a6303ae 100644
--- a/apps/desktop/src/renderer/contexts/AuthContext.tsx
+++ b/apps/desktop/src/renderer/contexts/AuthContext.tsx
@@ -294,6 +294,17 @@ export function AuthProvider({
unknownOwnerRollbackProjection
|| (activeDataOwnerIdRef.current !== null && !ownerChanged)
);
+ // A fresh renderer starts with a null owner. When it observes the
+ // transient signed-out projection first, the successful null-owner
+ // commit keeps the same owner id but advances the generation. Treat
+ // that generation advance as the boundary commit so the renderer still
+ // finalizes the outgoing session cache and rehydrates owner-scoped data.
+ const committedNullOwnerProjection =
+ pendingOwnerProjectionRef.current
+ && !pendingSignedOutProjection
+ && state.dataOwnerId === null
+ && state.ownerGeneration !== activeDataOwnerGenerationRef.current;
+ const ownerBoundaryCommitted = ownerChanged || committedNullOwnerProjection;
if (pendingSignedOutProjection) pendingOwnerProjectionRef.current = true;
// A same-owner push can arrive while an auth boundary is still waiting
// for IPC. The pre-commit fence temporarily publishes null, so letting
@@ -303,9 +314,9 @@ export function AuthProvider({
publishDataOwnerGeneration(
state.dataOwnerId,
state.ownerGeneration,
- { finalizeSessions: ownerChanged && !initialOwnerHydration },
+ { finalizeSessions: ownerBoundaryCommitted && !initialOwnerHydration },
);
- if (ownerChanged) {
+ if (ownerBoundaryCommitted) {
pendingOwnerProjectionRef.current = false;
sessionsStore.reset();
clearWorkersCache();
@@ -343,7 +354,7 @@ export function AuthProvider({
&& state.user?.membershipKind === 'org',
);
if (chatEmbeddingOwnerChanged) void refreshChatEmbeddingFromMain();
- if (ownerChanged) {
+ if (ownerBoundaryCommitted || ownerRollbackProjection) {
setMemorySettingsOwner(state.dataOwnerId);
void bootstrapMemorySettingsFromMain();
}
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index 72d8740cd1..46c1f99f5c 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -2184,6 +2184,7 @@ function hasActiveTurnStateForOwnerBoundary(state: SessionChatState): boolean {
message.clientId === AUTO_RESUME_PENDING_CLIENT_ID,
) ||
[...(state.taskUpdates?.values() ?? [])].some((task) => task.status === 'running')
+ || state.inputRecovery !== null
|| hasSessionRecoveryPendingState(state)
);
}
@@ -3040,6 +3041,12 @@ export const EMPTY_LIGHT_STATE: SessionChatLightState = Object.freeze({
// ---------------------------------------------------------------------------
const sessions = new Map<string, SessionChatState>();
+// Keep a stable token for each cached session incarnation. A rollback query
+// may outlive a purge/recreate of the same session id; comparing this token
+// prevents an old query from finalizing the replacement while still allowing
+// ordinary state updates to proceed.
+let nextSessionIncarnation = 1;
+const sessionIncarnations = new Map<string, number>();
const listeners = new Map<string, Set<() => void>>();
const lightSnapshotCache = new Map<string, SessionChatLightState>();
@@ -4222,6 +4229,7 @@ function getOrCreateState(sessionId: string): SessionChatState {
let state = sessions.get(sessionId);
if (!state) {
state = createInitialState();
+ sessionIncarnations.set(sessionId, nextSessionIncarnation++);
sessions.set(sessionId, state);
_touchSession(sessionId);
_evictLruIfNeeded();
@@ -6759,6 +6767,7 @@ function forceFinalizeOnSessionClosed(state: SessionChatState): SessionChatState
message.clientId === CODEX_RECONNECT_PENDING_CLIENT_ID ||
message.clientId === AUTO_RESUME_PENDING_CLIENT_ID,
) &&
+ state.inputRecovery === null &&
stoppedTasks === state.taskUpdates
) {
return state;
@@ -6792,6 +6801,7 @@ function forceFinalizeOnSessionClosed(state: SessionChatState): SessionChatState
activeTurnRetryText: null,
errorRetryText: null,
errorPersistId: null,
+ inputRecovery: null,
pendingPermission: null,
pendingAskUser: null,
pendingPluginSetup: null,
@@ -9836,6 +9846,8 @@ interface ActiveSessionSnapshot {
}
interface ActiveTurnBoundaryMarker {
+ sessionIncarnation: number;
+ sdkSessionId: string | null;
startedAt: number | null;
streamingClientId: string | null;
continuationTurnClientId: string | null;
@@ -9843,8 +9855,13 @@ interface ActiveTurnBoundaryMarker {
isStreaming: boolean;
}
-function captureActiveTurnBoundaryMarker(state: SessionChatState): ActiveTurnBoundaryMarker {
+function captureActiveTurnBoundaryMarker(
+ sessionId: string,
+ state: SessionChatState,
+): ActiveTurnBoundaryMarker {
return {
+ sessionIncarnation: sessionIncarnations.get(sessionId) ?? 0,
+ sdkSessionId: state.sdkSessionId,
startedAt: state.agentStatus.startedAt,
streamingClientId: state.streamingClientId,
continuationTurnClientId: state.continuationTurnClientId,
@@ -9854,10 +9871,13 @@ function captureActiveTurnBoundaryMarker(state: SessionChatState): ActiveTurnBou
}
function sameActiveTurnBoundaryMarker(
+ sessionId: string,
state: SessionChatState,
marker: ActiveTurnBoundaryMarker,
): boolean {
return (
+ (sessionIncarnations.get(sessionId) ?? 0) === marker.sessionIncarnation &&
+ state.sdkSessionId === marker.sdkSessionId &&
state.agentStatus.startedAt === marker.startedAt &&
state.streamingClientId === marker.streamingClientId &&
state.continuationTurnClientId === marker.continuationTurnClientId &&
@@ -9884,7 +9904,7 @@ export async function reconcileSessionsAfterDataOwnerRollback(): Promise<void> {
if (owner.dataOwnerId === null) return;
const candidates = [...sessions].flatMap(([id, state]) => {
if (isRemoteSessionSticky(id) || !hasActiveTurnStateForOwnerBoundary(state)) return [];
- return [[id, captureActiveTurnBoundaryMarker(state)] as const];
+ return [[id, captureActiveTurnBoundaryMarker(id, state)] as const];
});
if (candidates.length === 0) return;
try {
@@ -9902,7 +9922,7 @@ export async function reconcileSessionsAfterDataOwnerRollback(): Promise<void> {
// same finalizer path.
const current = sessions.get(id);
const mainTurnRunning = liveTurns.get(id);
- if (mainTurnRunning === true || !current || !sameActiveTurnBoundaryMarker(current, marker))
+ if (mainTurnRunning === true || !current || !sameActiveTurnBoundaryMarker(id, current, marker))
continue;
// listActive keeps idle session handles that still own background work.
// isTurnRunning=false only says the foreground turn ended; do not close