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): close account boundary recovery races

DavidShen42cdf2e796a5
diff --git a/apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.ts b/apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.ts
index bc010c7ca0..b5ad259695 100644
--- a/apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.ts
+++ b/apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.ts
@@ -423,4 +423,17 @@ describe('passive shared-userData instance auth isolation', () => {
expect(passiveBranch).not.toContain('removeSafe(');
expect(passiveBranch).not.toContain('clearReloginFlag();');
});
+
+ it('keeps a renderer fail-closed when it initializes during an owner boundary', () => {
+ const initializeStart = authSource.indexOf(
+ 'export async function initialize(options: AuthInitializeOptions = {}): Promise<AuthState> {',
+ );
+ const localModeStart = authSource.indexOf(
+ "if (getActiveAppSession().mode === 'local') {",
+ initializeStart,
+ );
+ const initializePrefix = authSource.slice(initializeStart, localModeStart);
+ expect(initializePrefix).toContain('if (isOwnerChangeShellPending())');
+ expect(initializePrefix).toContain('return snapshotLoggedOutAuthState(true);');
+ });
});
diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.ts
index 31da28f1ce..0b12decea1 100644
--- a/apps/desktop/src/main/authManager.ts
+++ b/apps/desktop/src/main/authManager.ts
@@ -4472,6 +4472,12 @@ export async function updateServerProfile(
}
export async function initialize(options: AuthInitializeOptions = {}): Promise<AuthState> {
+ // A renderer can mount after the boundary-pending broadcast. Keep startup
+ // fail-closed until the serialized owner transition settles instead of
+ // restoring the outgoing owner's credentials and turns from disk.
+ if (isOwnerChangeShellPending()) {
+ return snapshotLoggedOutAuthState(true);
+ }
// Local mode is a committed account-free session. It must win before any
// persisted cloud refresh token is inspected or any auth network call runs.
if (getActiveAppSession().mode === 'local') {
diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreTaskUpdates.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreTaskUpdates.test.ts
index 1895eb27a8..e0d0a66b7d 100644
--- a/apps/desktop/src/renderer/__tests__/makerChatStoreTaskUpdates.test.ts
+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreTaskUpdates.test.ts
@@ -945,6 +945,38 @@ describe('getRunningSnapshot 后台 subagent 折算(真 store)', () => {
setDataOwnerGeneration('account-a', 1);
makerChatStore.__applyStatusUpdateForTest(sid, statusUpdate(sid, true));
applyTask(sid, { taskId: 't1', status: 'running', taskType: 'local_agent' });
+ const autoResume = {
+ clientId: 'auto-resume-owner-finalize',
+ text: '',
+ persistedContent: '',
+ model: 'model',
+ effort: 'medium',
+ permissionMode: 'default',
+ workingDir: '',
+ autoResume: true,
+ chatMessage: { clientId: 'auto-resume-owner-finalize', role: 'user' as const, content: '' },
+ createOpts: { agentKind: 'codex' as const, workingDir: '', model: 'model' },
+ };
+ const queuedByUser = {
+ ...autoResume,
+ clientId: 'user-queued-owner-finalize',
+ autoResume: false,
+ chatMessage: { clientId: 'user-queued-owner-finalize', role: 'user' as const, content: '' },
+ };
+ makerChatStore.__applyInputProjectionForTest({
+ sessionId: sid,
+ pendingQueue: [autoResume, queuedByUser],
+ steeringQueueClientIds: [],
+ queuePaused: false,
+ queueExpanded: false,
+ queueInteractionLocks: [],
+ queueEditLocks: [],
+ queueAbortPending: false,
+ error: null,
+ recovery: null,
+ errorRetryText: null,
+ credentialSwitchWait: null,
+ });
makerChatStore.__applyStatusUpdateForTest(remoteSid, statusUpdate(remoteSid, true));
applyTask(remoteSid, { taskId: 'remote-t1', status: 'running', taskType: 'local_agent' });
expect(makerChatStore.getSnapshot(sid).agentStatus.startedAt).toBeTruthy();
@@ -970,6 +1002,9 @@ describe('getRunningSnapshot 后台 subagent 折算(真 store)', () => {
expect(state.agentStatus.isRunning).toBe(false);
expect(state.agentStatus.startedAt).toBeNull();
expect(state.taskUpdates?.get('t1')?.status).toBe('stopped');
+ expect(state.pendingQueue.map((item) => item.clientId)).toEqual([
+ 'user-queued-owner-finalize',
+ ]);
expect(makerChatStore.getSnapshot(remoteSid).agentStatus.isRunning).toBe(true);
// Re-entering account A must observe the stopped snapshot, with no
@@ -1002,9 +1037,13 @@ describe('getRunningSnapshot 后台 subagent 折算(真 store)', () => {
makerChatStore.__applyStatusUpdateForTest(remoteSid, statusUpdate(remoteSid, true));
applyTask(remoteSid, { taskId: 'remote-t1', status: 'running', taskType: 'local_agent' });
let resolveListActive!: (value: unknown[]) => void;
- const listActive = vi.fn(
- () => new Promise<unknown[]>((resolve) => { resolveListActive = resolve; }),
- );
+ let listActiveCalls = 0;
+ const listActive = vi.fn(() => {
+ listActiveCalls += 1;
+ return listActiveCalls === 1
+ ? new Promise<unknown[]>((resolve) => { resolveListActive = resolve; })
+ : Promise.resolve([]);
+ });
globalWindow.window = {
electronAPI: { maker: { listActive } },
} as typeof globalWindow.window;
@@ -1319,4 +1358,40 @@ describe('getRunningSnapshot 后台 subagent 折算(真 store)', () => {
globalWindow.window = previousWindow;
}
});
+
+ it('rechecks Main before finalizing a same-session replacement turn', async () => {
+ const sid = 'rollback-same-session-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 resolveFirst!: (value: unknown[]) => void;
+ let listActiveCalls = 0;
+ const listActive = vi.fn(() => {
+ listActiveCalls += 1;
+ if (listActiveCalls === 1) {
+ return new Promise<unknown[]>((resolve) => { resolveFirst = resolve; });
+ }
+ return Promise.resolve([{ sessionId: sid, agentKind: 'codex', isTurnRunning: true }]);
+ });
+ globalWindow.window = {
+ electronAPI: { maker: { listActive } },
+ } as typeof globalWindow.window;
+
+ const reconciliation = reconcileSessionsAfterDataOwnerRollback();
+ await Promise.resolve();
+ resolveFirst([]);
+ await reconciliation;
+
+ expect(listActive).toHaveBeenCalledTimes(2);
+ expect(makerChatStore.getSnapshot(sid).agentStatus.isRunning).toBe(true);
+ } finally {
+ makerChatStore.purgeSession(sid);
+ dataOwnerGenerationTesting.reset();
+ globalWindow.window = previousWindow;
+ }
+ });
});
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index 46c1f99f5c..930e32217b 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -6768,6 +6768,7 @@ function forceFinalizeOnSessionClosed(state: SessionChatState): SessionChatState
message.clientId === AUTO_RESUME_PENDING_CLIENT_ID,
) &&
state.inputRecovery === null &&
+ !state.pendingQueue.some((item) => item.autoResume === true) &&
stoppedTasks === state.taskUpdates
) {
return state;
@@ -6802,6 +6803,10 @@ function forceFinalizeOnSessionClosed(state: SessionChatState): SessionChatState
errorRetryText: null,
errorPersistId: null,
inputRecovery: null,
+ // A successful owner commit closes the outgoing session. Automatic
+ // continuation entries belong to that owner and must not survive the
+ // boundary; user queued input remains available for the next owner.
+ pendingQueue: finalized.pendingQueue.filter((item) => item.autoResume !== true),
pendingPermission: null,
pendingAskUser: null,
pendingPluginSetup: null,
@@ -9924,6 +9929,17 @@ export async function reconcileSessionsAfterDataOwnerRollback(): Promise<void> {
const mainTurnRunning = liveTurns.get(id);
if (mainTurnRunning === true || !current || !sameActiveTurnBoundaryMarker(id, current, marker))
continue;
+ // The first query can legitimately race a replacement turn created by
+ // another renderer. Re-read an absent handle immediately before
+ // finalization so a stale absence cannot close that new turn.
+ if (mainTurnRunning === undefined) {
+ const latest = await listActive();
+ if (getDataOwnerGeneration() !== owner) return;
+ if (!Array.isArray(latest) || !latest.every(isActiveSessionSnapshot)) return;
+ if (latest.some((item) => item.sessionId === id && item.isTurnRunning === true)) {
+ continue;
+ }
+ }
// listActive keeps idle session handles that still own background work.
// isTurnRunning=false only says the foreground turn ended; do not close
// any task Main may still be running while rolling back a rejected owner