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): 完善切账号后的任务回滚收口 #4766

DavidShena72543c18536
diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.ts
index fd0ba9b71e..31da28f1ce 100644
--- a/apps/desktop/src/main/authManager.ts
+++ b/apps/desktop/src/main/authManager.ts
@@ -288,6 +288,8 @@ export interface AuthState {
dataOwnerId: string | null;
/** Main-owned owner boundary generation used to fence late renderer pushes. */
ownerGeneration: number;
+ /** True only for the transient signed-out projection published before an owner boundary commits. */
+ ownerBoundaryPending?: boolean;
/** Local and cloud sessions may enter the main application. */
canEnterApp: boolean;
isAuthenticated: boolean;
@@ -3460,13 +3462,14 @@ function snapshotAuthState(): AuthState {
}
/** Logged-out projection used by stale/timeout paths that must not expose newer auth state. */
-function snapshotLoggedOutAuthState(): AuthState {
+function snapshotLoggedOutAuthState(ownerBoundaryPending = false): AuthState {
const appSession = getActiveAppSession();
return {
user: null,
mode: 'signed-out',
dataOwnerId: null,
ownerGeneration: appSession.generation,
+ ownerBoundaryPending,
canEnterApp: false,
isAuthenticated: false,
isCanary: false,
@@ -3484,7 +3487,7 @@ function notifyRenderer(): void {
}
function notifyRendererAuthBoundaryPending(): void {
- broadcastToRenderers('auth:state-change', snapshotLoggedOutAuthState());
+ broadcastToRenderers('auth:state-change', snapshotLoggedOutAuthState(true));
}
/**
diff --git a/apps/desktop/src/renderer/__tests__/authContextSessionBoundary.test.tsx b/apps/desktop/src/renderer/__tests__/authContextSessionBoundary.test.tsx
index 60c4bbcdb4..6c72af6a06 100644
--- a/apps/desktop/src/renderer/__tests__/authContextSessionBoundary.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/authContextSessionBoundary.test.tsx
@@ -269,6 +269,33 @@ describe('AuthContext session cache boundaries', () => {
expect(view.result.current.dataOwnerId).toBe('account-a');
});
+ it('preserves a generation-zero pending rollback from a startup-local boundary', async () => {
+ // A renderer opened while a process that started in local mode is leaving
+ // that owner receives the transient signed-out projection at generation 0.
+ // The explicit pending marker disambiguates it from a stable signed-out
+ // startup snapshot.
+ mocks.service.initialize.mockResolvedValue({
+ ...authState(null),
+ ownerGeneration: 0,
+ ownerBoundaryPending: true,
+ });
+ const view = renderHook(() => useAuth(), { wrapper });
+ await waitFor(() => expect(view.result.current.dataOwnerId).toBeNull());
+
+ expect(mocks.cancelRemoteOptimisticSendsForDataOwnerBoundary).not.toHaveBeenCalledWith({
+ finalizeSessions: true,
+ });
+ mocks.cancelRemoteOptimisticSendsForDataOwnerBoundary.mockClear();
+
+ act(() => mocks.emitAuth({ ...localAuthState(), ownerGeneration: 0 }));
+
+ expect(mocks.cancelRemoteOptimisticSendsForDataOwnerBoundary).toHaveBeenLastCalledWith({
+ finalizeSessions: false,
+ });
+ expect(mocks.reconcileSessionsAfterDataOwnerRollback).toHaveBeenCalledOnce();
+ expect(view.result.current.dataOwnerId).toBe('local-v1');
+ });
+
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 2963a213b0..2e86ee960b 100644
--- a/apps/desktop/src/renderer/__tests__/makerChatStoreTaskUpdates.test.ts
+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreTaskUpdates.test.ts
@@ -1181,4 +1181,63 @@ describe('getRunningSnapshot 后台 subagent 折算(真 store)', () => {
globalWindow.window = previousWindow;
}
});
+
+ it('rollback reconciliation preserves an automatic-resume item during backoff', async () => {
+ const sid = 'rollback-auto-resume-' + 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));
+ makerChatStore.__applyStatusUpdateForTest(sid, statusUpdate(sid, false));
+ const clientId = 'auto-resume-backoff';
+ const queuedAutoResume = {
+ clientId,
+ text: '',
+ persistedContent: '',
+ model: 'model',
+ effort: 'medium',
+ permissionMode: 'default',
+ workingDir: '',
+ autoResume: true,
+ chatMessage: { clientId, role: 'user' as const, content: '' },
+ createOpts: { agentKind: 'codex' as const, workingDir: '', model: 'model' },
+ };
+ makerChatStore.__applyInputProjectionForTest({
+ sessionId: sid,
+ pendingQueue: [queuedAutoResume],
+ steeringQueueClientIds: [],
+ queuePaused: false,
+ queueExpanded: false,
+ queueInteractionLocks: [],
+ queueEditLocks: [],
+ queueAbortPending: false,
+ error: null,
+ recovery: null,
+ errorRetryText: null,
+ credentialSwitchWait: null,
+ });
+
+ globalWindow.window = {
+ electronAPI: {
+ maker: {
+ listActive: vi.fn(async () => [
+ { sessionId: sid, agentKind: 'codex', isTurnRunning: false },
+ ]),
+ },
+ },
+ } as typeof globalWindow.window;
+
+ await reconcileSessionsAfterDataOwnerRollback();
+ const state = makerChatStore.getSnapshot(sid);
+ expect(state.pendingQueue.some((item) => item.clientId === clientId)).toBe(true);
+ expect(state.agentStatus.isRunning).toBe(false);
+ } 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 8738b55699..68e5850e83 100644
--- a/apps/desktop/src/renderer/contexts/AuthContext.tsx
+++ b/apps/desktop/src/renderer/contexts/AuthContext.tsx
@@ -257,6 +257,8 @@ export function AuthProvider({
&& activeDataOwnerIdRef.current === null
&& signedOutProjection
&& (
+ state.ownerBoundaryPending === true
+ ||
(rendererOwnerGeneration.dataOwnerId !== null
&& state.ownerGeneration === rendererOwnerGeneration.generation)
// A newly opened renderer has no synchronous owner stamp. Main's
diff --git a/apps/desktop/src/renderer/lib/authService.ts b/apps/desktop/src/renderer/lib/authService.ts
index dd98e233e0..d59a21c898 100644
--- a/apps/desktop/src/renderer/lib/authService.ts
+++ b/apps/desktop/src/renderer/lib/authService.ts
@@ -39,6 +39,8 @@ export interface AuthState {
mode: 'signed-out' | 'local' | 'cloud';
dataOwnerId: string | null;
ownerGeneration: number;
+ /** Main marks the transient signed-out projection while an owner boundary is pending. */
+ ownerBoundaryPending?: boolean;
canEnterApp: boolean;
isAuthenticated: boolean;
isCanary: boolean;
@@ -80,6 +82,7 @@ export function createAuthService(): AuthService {
mode: rawState.mode,
dataOwnerId: rawState.dataOwnerId,
ownerGeneration: rawState.ownerGeneration,
+ ownerBoundaryPending: rawState.ownerBoundaryPending === true,
canEnterApp: rawState.canEnterApp,
isAuthenticated: rawState.isAuthenticated,
isCanary: rawState.isCanary === true,
@@ -99,6 +102,7 @@ export function createAuthService(): AuthService {
mode: raw.mode,
dataOwnerId: raw.dataOwnerId,
ownerGeneration: raw.ownerGeneration,
+ ownerBoundaryPending: raw.ownerBoundaryPending === true,
canEnterApp: raw.canEnterApp,
isAuthenticated: raw.isAuthenticated,
isCanary: raw.isCanary === true,
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index 3e9ebd90ff..72d8740cd1 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')
+ || hasSessionRecoveryPendingState(state)
);
}
@@ -9804,12 +9805,23 @@ function hasSessionTerminalError(sessionId: string): boolean {
/** Non-creating read: recovery can outlive the one-generation stop snapshot. */
function hasSessionRecoveryPending(sessionId: string): boolean {
const state = sessions.get(sessionId);
- return !!state && (
+ return !!state && hasSessionRecoveryPendingState(state);
+}
+
+/**
+ * Automatic continuation can be in its retry backoff after the foreground
+ * turn has gone idle. In that window Main keeps the session handle alive, but
+ * the renderer may only have the typed recovery marker (or a queued auto-resume
+ * item), rather than a running task snapshot.
+ */
+function hasSessionRecoveryPendingState(state: SessionChatState): boolean {
+ return (
state.messages.some((message) =>
message.clientId === AUTO_RESUME_PENDING_CLIENT_ID ||
message.clientId === CODEX_RECONNECT_PENDING_CLIENT_ID,
) ||
- (!state.queuePaused && state.pendingQueue.some((item) => item.autoResume === true))
+ (!state.queuePaused && state.pendingQueue.some((item) => item.autoResume === true)) ||
+ (state.inputRecovery?.kind === 'active-turn' && state.inputRecovery.item.autoResume === true)
);
}
@@ -9896,7 +9908,10 @@ export async function reconcileSessionsAfterDataOwnerRollback(): Promise<void> {
// isTurnRunning=false only says the foreground turn ended; do not close
// any task Main may still be running while rolling back a rejected owner
// transition (wake and non-wake tasks alike).
- if (mainTurnRunning === false && hasRunningBackgroundTask(current)) continue;
+ if (
+ mainTurnRunning === false &&
+ (hasRunningBackgroundTask(current) || hasSessionRecoveryPendingState(current))
+ ) continue;
bumpInteractionReconcileEpoch(id);
supersedeInputProjectionRequests(id, { supersedeOperations: true });
flushPendingTextDelta(id);
@@ -16966,6 +16981,10 @@ export const makerChatStore = {
setState(sessionId, (s) => handleStatusUpdate(s, update));
scheduleWakeBridgeReconciliation(sessionId);
},
+ /** Exposed for tests only: apply a main input projection without IPC wiring. */
+ __applyInputProjectionForTest: (projection: AgentInputProjection): void => {
+ applyInputProjection(projection);
+ },
/** Exposed for tests only. */
__hydratePersistedMessageForTest: hydratePersistedMessage,
/** Exposed for tests only. */
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 2001486fac..64b1e1d7f5 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -583,6 +583,8 @@ interface AuthStateChangePayload {
mode: 'signed-out' | 'local' | 'cloud';
dataOwnerId: string | null;
ownerGeneration: number;
+ /** Main marks the transient signed-out projection while an owner boundary is pending. */
+ ownerBoundaryPending?: boolean;
canEnterApp: boolean;
isAuthenticated: boolean;
/** 当前账号是否加入 Canary 发布通道;由 main 的 feature-flags 同步结果驱动。 */
@@ -2140,6 +2142,7 @@ interface ElectronAPI {
mode: 'signed-out' | 'local' | 'cloud';
dataOwnerId: string | null;
ownerGeneration: number;
+ ownerBoundaryPending?: boolean;
canEnterApp: boolean;
isAuthenticated: boolean;
isCanary: boolean;