Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): recover auth after credential backend failure (#3960)
Dashe9def8b34a24
diff --git a/apps/desktop/src/main/__tests__/authBrowserLaunch.test.ts b/apps/desktop/src/main/__tests__/authBrowserLaunch.test.tsnew file mode 100644index 0000000000..5e617ee508--- /dev/null+++ b/apps/desktop/src/main/__tests__/authBrowserLaunch.test.ts@@ -0,0 +1,52 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { AUTH_BROWSER_LAUNCH_TIMEOUT_MS, launchAuthBrowser } from '../authBrowserLaunch';++describe('system browser launch', () => {+ beforeEach(() => vi.useFakeTimers());+ afterEach(() => vi.useRealTimers());++ it('bounds a hung OS call and consumes its late rejection', async () => {+ let reject!: (reason: Error) => void;+ const open = vi.fn(() => new Promise<void>((_, fail) => { reject = fail; }));+ const result = launchAuthBrowser(open, new AbortController().signal);+ await vi.advanceTimersByTimeAsync(AUTH_BROWSER_LAUNCH_TIMEOUT_MS);+ await expect(result).resolves.toEqual({ opened: false, error: 'BROWSER_OPEN_TIMEOUT' });+ reject(new Error('late OS failure containing an auth URL'));+ await Promise.resolve();+ expect(open).toHaveBeenCalledTimes(1);+ expect(vi.getTimerCount()).toBe(0);+ });++ it('cancels promptly, ignoring a late successful OS response', async () => {+ let resolve!: () => void;+ const controller = new AbortController();+ const result = launchAuthBrowser(() => new Promise<void>((done) => { resolve = done; }), controller.signal);+ controller.abort();+ resolve();+ await expect(result).resolves.toEqual({ opened: false, error: 'USER_CANCELLED' });+ expect(vi.getTimerCount()).toBe(0);+ });++ it('does not launch a cancelled attempt', async () => {+ const controller = new AbortController();+ controller.abort();+ const open = vi.fn();+ await expect(launchAuthBrowser(open, controller.signal))+ .resolves.toEqual({ opened: false, error: 'USER_CANCELLED' });+ expect(open).not.toHaveBeenCalled();+ });++ it('clears the deadline after the OS accepts the request', async () => {+ await expect(launchAuthBrowser(async () => {}, new AbortController().signal))+ .resolves.toEqual({ opened: true });+ expect(vi.getTimerCount()).toBe(0);+ });++ it.each(['sync', 'async'])('reports a %s launch failure without exposing the OS error', async (mode) => {+ const error = new Error('https://auth.invalid/?secret=not-for-renderer');+ const open = mode === 'sync' ? () => { throw error; } : () => Promise.reject(error);+ await expect(launchAuthBrowser(open, new AbortController().signal))+ .resolves.toEqual({ opened: false, error: 'BROWSER_OPEN_FAILED' });+ expect(vi.getTimerCount()).toBe(0);+ });+});diff --git a/apps/desktop/src/main/__tests__/authCredentialRecovery.test.ts b/apps/desktop/src/main/__tests__/authCredentialRecovery.test.tsnew file mode 100644index 0000000000..d52da32bb4--- /dev/null+++ b/apps/desktop/src/main/__tests__/authCredentialRecovery.test.ts@@ -0,0 +1,187 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import {+ AUTH_CREDENTIAL_RECOVERY_ARG,+ createAuthCredentialRecovery,+ type AuthCredentialRecoveryDeps,+} from '../authCredentialRecovery';++function setup(overrides: Partial<AuthCredentialRecoveryDeps> = {}) {+ const deps: AuthCredentialRecoveryDeps = {+ enabled: true,+ argv: ['--profile=test', '--xdt-update-relaunch'],+ needsRecovery: vi.fn(() => true),+ readScreenState: vi.fn(() => 'active' as const),+ isQuitting: vi.fn(() => false),+ isBusy: vi.fn(async () => false),+ relaunch: vi.fn(),+ schedule: (callback, delayMs) => setTimeout(callback, delayMs),+ cancel: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),+ onEvent: vi.fn(),+ ...overrides,+ };+ return { deps, controller: createAuthCredentialRecovery(deps) };+}++describe('credential failure process recovery', () => {+ beforeEach(() => vi.useFakeTimers());+ afterEach(() => vi.useRealTimers());++ it('waits for unlock and a settle delay, then restarts once with the same profile', async () => {+ let state: 'locked' | 'active' = 'locked';+ const { deps, controller } = setup({ readScreenState: () => state });+ controller.request();+ await vi.advanceTimersByTimeAsync(3_000);+ expect(deps.relaunch).not.toHaveBeenCalled();+ state = 'active';+ controller.onScreenUnlock();+ await vi.advanceTimersByTimeAsync(2_999);+ expect(deps.relaunch).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(1);+ expect(deps.relaunch).toHaveBeenCalledWith([+ '--profile=test',+ '--xdt-update-relaunch',+ AUTH_CREDENTIAL_RECOVERY_ARG,+ ]);+ controller.request();+ controller.onScreenUnlock();+ await vi.advanceTimersByTimeAsync(60_000);+ expect(deps.relaunch).toHaveBeenCalledTimes(1);+ });++ it('does not loop if the successor also cannot read the keychain', async () => {+ const { deps, controller } = setup({ argv: [AUTH_CREDENTIAL_RECOVERY_ARG] });+ controller.request();+ controller.onScreenUnlock();+ controller.request();+ await vi.advanceTimersByTimeAsync(90_000);+ expect(deps.isBusy).not.toHaveBeenCalled();+ expect(deps.relaunch).not.toHaveBeenCalled();+ expect(deps.onEvent).toHaveBeenCalledExactlyOnceWith('attempt-exhausted');+ });++ it.each(['disabled', 'healthy', 'quitting'] as const)(+ 'does nothing when %s',+ async (condition) => {+ const { deps, controller } = setup({+ enabled: condition !== 'disabled',+ needsRecovery: () => condition !== 'healthy',+ isQuitting: () => condition === 'quitting',+ });+ controller.request();+ controller.onScreenUnlock();+ await vi.advanceTimersByTimeAsync(90_000);+ expect(deps.relaunch).not.toHaveBeenCalled();+ expect(deps.readScreenState).not.toHaveBeenCalled();+ },+ );++ it('defers for activity and retries when that work has finished', async () => {+ let busy = true;+ const { deps, controller } = setup({ isBusy: async () => busy });+ controller.request();+ await vi.advanceTimersByTimeAsync(3_000);+ expect(deps.onEvent).toHaveBeenLastCalledWith('waiting-for-idle');+ expect(deps.relaunch).not.toHaveBeenCalled();+ busy = false;+ await vi.advanceTimersByTimeAsync(30_000);+ expect(deps.relaunch).toHaveBeenCalledTimes(1);+ });++ it('fails closed on activity-query errors and unknown or failed screen queries', async () => {+ const { deps, controller } = setup();+ vi.mocked(deps.readScreenState)+ .mockReturnValueOnce('unknown')+ .mockImplementationOnce(() => {+ throw new Error('screen unavailable');+ });+ vi.mocked(deps.isBusy).mockRejectedValueOnce(new Error('storage unavailable'));+ controller.request();+ await vi.advanceTimersByTimeAsync(63_000);+ expect(deps.relaunch).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(30_000);+ expect(deps.relaunch).toHaveBeenCalledTimes(1);+ });++ it('recovers from a missed unlock event using the next screen observation', async () => {+ let state: 'locked' | 'idle' = 'locked';+ const { deps, controller } = setup({ readScreenState: () => state });+ controller.request();+ controller.onScreenLock();+ await vi.advanceTimersByTimeAsync(30_000);+ state = 'idle';+ await vi.advanceTimersByTimeAsync(30_000);+ expect(deps.relaunch).toHaveBeenCalledTimes(1);+ });++ it.each(['recovered', 'quitting', 'disposed', 'locked'] as const)(+ 'revalidates after the async busy query when %s',+ async (change) => {+ let finish!: (busy: boolean) => void;+ const { deps, controller } = setup({+ isBusy: () =>+ new Promise<boolean>((resolve) => {+ finish = resolve;+ }),+ });+ controller.request();+ await vi.advanceTimersByTimeAsync(3_000);+ if (change === 'recovered') vi.mocked(deps.needsRecovery).mockReturnValue(false);+ if (change === 'quitting') vi.mocked(deps.isQuitting).mockReturnValue(true);+ if (change === 'disposed') controller.dispose();+ if (change === 'locked') {+ vi.mocked(deps.readScreenState).mockReturnValue('locked');+ controller.onScreenLock();+ }+ finish(false);+ await vi.advanceTimersByTimeAsync(30_000);+ expect(deps.relaunch).not.toHaveBeenCalled();+ },+ );++ it('discards an idle result spanning lock/unlock and gives the new unlock time to settle', async () => {+ let finish!: (busy: boolean) => void;+ const { deps, controller } = setup();+ vi.mocked(deps.isBusy).mockImplementationOnce(+ () =>+ new Promise<boolean>((resolve) => {+ finish = resolve;+ }),+ );+ controller.request();+ await vi.advanceTimersByTimeAsync(3_000);+ controller.onScreenLock();+ controller.onScreenUnlock();+ finish(false);+ await vi.advanceTimersByTimeAsync(2_999);+ expect(deps.relaunch).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(1);+ expect(deps.relaunch).toHaveBeenCalledTimes(1);+ });++ it('cancels pending recovery on disposal and observes recovery before its timer fires', async () => {+ const first = setup();+ first.controller.request();+ first.controller.dispose();+ const second = setup();+ second.controller.request();+ vi.mocked(second.deps.needsRecovery).mockReturnValue(false);+ await vi.advanceTimersByTimeAsync(30_000);+ expect(first.deps.relaunch).not.toHaveBeenCalled();+ expect(second.deps.relaunch).not.toHaveBeenCalled();+ });++ it('consumes the attempt if relaunch throws and does not leak native error text', async () => {+ const { deps, controller } = setup({+ relaunch: vi.fn(() => {+ throw new Error('private native details');+ }),+ });+ controller.request();+ await vi.advanceTimersByTimeAsync(3_000);+ expect(deps.onEvent).toHaveBeenLastCalledWith('relaunch-failed');+ controller.request();+ controller.onScreenUnlock();+ await vi.advanceTimersByTimeAsync(60_000);+ expect(deps.relaunch).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/desktop/src/main/__tests__/authCredentialRecoveryWiring.test.ts b/apps/desktop/src/main/__tests__/authCredentialRecoveryWiring.test.tsnew file mode 100644index 0000000000..383133e2cc--- /dev/null+++ b/apps/desktop/src/main/__tests__/authCredentialRecoveryWiring.test.ts@@ -0,0 +1,74 @@+import { readFileSync } from 'node:fs';+import { ScriptTarget, transpileModule } from 'typescript';+import { describe, expect, it, vi } from 'vitest';++const bootstrap = readFileSync(new URL('../bootstrap-electron.ts', import.meta.url), 'utf8');++describe('production credential recovery wiring', () => {+ it('connects observed failures to recovery without probing the credential backend', () => {+ const wiring = bootstrap.match(+ /const authCredentialRecovery = createAuthCredentialRecovery\(\{([\s\S]*?)\n\}\);/,+ )?.[1];+ expect(wiring).toBeDefined();+ expect(wiring).toContain("enabled: process.platform === 'darwin' && app.isPackaged");+ expect(wiring).toContain('authManager.needsCredentialProcessRecovery()');+ expect(wiring).not.toContain('safeStorage');+ expect(wiring).toContain('authManager.isAuthFlowBusy()');+ expect(wiring).toContain('hasUpdateRelaunchBusyActivity');+ expect(wiring).toContain('evaluateRelaunchBusyActivity(readRelaunchActivitySources())');+ expect(wiring).toContain('app.relaunch({ args })');+ expect(wiring).toContain('app.quit()');+ });++ it.each([false, true])(+ 'requests recovery when initialization rejects=%s without replacing its outcome',+ async (rejects) => {+ const start = bootstrap.indexOf("ipcMain.handle('auth:initialize',");+ const end = bootstrap.indexOf("ipcMain.handle('auth:get-login-state',", start);+ expect(start).toBeGreaterThan(-1);+ expect(end).toBeGreaterThan(start);+ const compiled = transpileModule(bootstrap.slice(start, end), {+ compilerOptions: { target: ScriptTarget.ES2022 },+ }).outputText;+ let handler!: () => Promise<unknown>;+ const outcome = rejects ? new Error('owner teardown failed') : { isAuthenticated: false };+ const request = vi.fn();+ const deps = {+ ipcMain: {+ handle: (_channel: string, callback: typeof handler) => {+ handler = callback;+ },+ },+ authManager: {+ initialize: () => (rejects ? Promise.reject(outcome) : Promise.resolve(outcome)),+ ensureStableOwnerPostCommitTasks: vi.fn(async () => {}),+ },+ authCredentialRecovery: { request },+ app: { isPackaged: true },+ noteAuthColdStartState: vi.fn(),+ };+ new Function(...Object.keys(deps), compiled)(...Object.values(deps));+ if (rejects) await expect(handler()).rejects.toBe(outcome);+ else await expect(handler()).resolves.toBe(outcome);+ expect(request).toHaveBeenCalledTimes(1);+ },+ );++ it('requests recovery after resume, and removes screen listeners on quit', () => {+ expect(bootstrap).toMatch(+ /powerMonitor.on\('resume', \(\) => \{\s*authCredentialRecovery.request\(\)/,+ );+ for (const [event, handler] of [+ ['lock-screen', 'onScreenLock'],+ ['unlock-screen', 'onScreenUnlock'],+ ]) {+ expect(bootstrap).toContain(`powerMonitor.on('${event}', authCredentialRecovery.${handler})`);+ expect(bootstrap).toContain(+ `powerMonitor.removeListener('${event}', authCredentialRecovery.${handler})`,+ );+ }+ expect(bootstrap).toMatch(+ /onQuit\(\s*'auth-credential-recovery',\s*\(\) => \{\s*authCredentialRecovery.dispose\(\)/,+ );+ });+});diff --git a/apps/desktop/src/main/__tests__/authCredentialStoreHealth.test.ts b/apps/desktop/src/main/__tests__/authCredentialStoreHealth.test.tsindex e4831695ca..4fbaa0ea84 100644--- a/apps/desktop/src/main/__tests__/authCredentialStoreHealth.test.ts+++ b/apps/desktop/src/main/__tests__/authCredentialStoreHealth.test.ts@@ -15,6 +15,16 @@ import {* 强制登出」的历史问题)。连续 N 次失败才升级、任何一次成功读取立即复位。*/describe('authCredentialStoreHealth', () => {+ it('startup read failure surfaces immediately and a later successful read clears it', () => {+ const health = createCredentialStoreHealth();+ health.noteStartupFailure();+ expect(health.unavailable).toBe(true);+ expect(health.noteReadFailure()).toBe(false);+ expect(health.noteRecovered()).toBe(true);+ expect(health.unavailable).toBe(false);+ expect(health.noteReadFailure()).toBe(false);+ });+it('阈值之前保持瞬时语义,不升级', () => {const health = createCredentialStoreHealth(5);for (let i = 0; i < 4; i++) {@@ -82,10 +92,107 @@ describe('authCredentialStoreHealth', () => {* authSessionExpiredDetection.test.ts 的源码守卫模式)。*/describe('authManager credential-store escalation wiring', () => {- const authSource = readFileSync(resolve(process.cwd(), 'src/main/authManager.ts'), 'utf8').replace(- /\r\n/g,- '\n',- );+ const authSource = readFileSync(+ resolve(process.cwd(), 'src/main/authManager.ts'),+ 'utf8',+ ).replace(/\r\n/g, '\n');++ it('keeps explicit login available for corrupt vaults when encryption is healthy', () => {+ const expression = authSource.match(+ /'cold-start-credential-reconcile-unavailable',\s*([\s\S]*?),\s*\);/,+ )?.[1];+ expect(expression).toBeDefined();+ class AuthApiError extends Error {+ constructor(public code: string) {+ super(code);+ }+ }+ const classify = new Function(+ 'credentialEncryptionUnavailable',+ 'error',+ 'AuthApiError',+ 'hasPotentiallyPersistedAuthCredentials',+ `return (${expression});`,+ );+ const unavailable = new AuthApiError('CREDENTIAL_STORE_UNAVAILABLE');+ expect(classify(false, unavailable, AuthApiError, () => true)).toBe(false);+ expect(classify(true, unavailable, AuthApiError, () => true)).toBe(true);+ expect(classify(true, unavailable, AuthApiError, () => false)).toBe(false);+ expect(classify(true, new Error('unrelated'), AuthApiError, () => true)).toBe(false);+ });++ it('distinguishes an empty profile from records, backups, tombstones and access errors without decryption', () => {+ const body = authSource.match(+ /function hasPotentiallyPersistedAuthCredentials\(\): boolean \{([\s\S]*?)\n\}/,+ )?.[1];+ expect(body).toBeDefined();+ const keys = [+ 'AUTH_SESSION_KEY',+ 'AUTH_ACCOUNT_VAULT_KEY',+ 'AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY',+ 'LEGACY_RESOURCE_REFRESH_TOKEN_KEY',+ 'LEGACY_ACCOUNT_REFRESH_TOKEN_KEY',+ 'LEGACY_REFRESH_TOKEN_KEY',+ ];+ const check = new Function(+ 'fs',+ 'path',+ 'SAFE_STORAGE_DIR',+ ...keys,+ body!.replace(' as NodeJS.ErrnoException', ''),+ );+ const probe = (exists: string | null, errorCode = 'ENOENT') =>+ check(+ {+ constants: { F_OK: 0 },+ accessSync: (file: string) => {+ if (file !== exists) throw Object.assign(new Error(), { code: errorCode });+ },+ },+ { join: (...parts: string[]) => parts.join('/') },+ () => '/fake',+ ...keys,+ );+ expect(probe(null)).toBe(false);+ for (const key of keys) {+ expect(probe(`/fake/${key}.enc`)).toBe(true);+ expect(probe(`/fake/${key}.enc.bak`)).toBe(true);+ }+ expect(probe(null, 'EACCES')).toBe(true);+ expect(probe(null, 'EPERM')).toBe(true);+ expect(probe(null, 'EIO')).toBe(true);+ });++ it('retains startup failure across all owner cleanup paths and exposes it before loading providers', () => {+ const recovery = authSource.slice(+ authSource.indexOf('async function withAccountFreeOwnerCommit'),+ authSource.indexOf('interface CloudOwnerDataReservation'),+ );+ // Passive, normal commit and failed cleanup must all retain the same cause.+ expect(+ recovery.match(/credentialStoreUnavailable: opts\.credentialStoreUnavailable/g),+ ).toHaveLength(3);+ expect(recovery).toContain(+ 'if (credentialStoreUnavailable) credentialStoreHealth.noteStartupFailure();',+ );+ const clear = authSource.slice(+ authSource.indexOf('function clearAuth('),+ authSource.indexOf('// ── Public API'),+ );+ expect(clear.indexOf('credentialStoreHealth.noteStartupFailure()')).toBeGreaterThan(+ clear.indexOf('credentialStoreHealth.reset()'),+ );+ const login = authSource.slice(+ authSource.indexOf('export async function getLoginState()'),+ authSource.indexOf('async function completeLogin('),+ );+ expect(login.indexOf('credentialStoreHealth.unavailable')).toBeLessThan(+ login.indexOf('await loadLoginProviders'),+ );+ expect(login).toContain(+ "state: { step: 'error', code: 'CREDENTIAL_STORE_UNAVAILABLE', recoverTo: 'identifier' }",+ );+ });it('transient-unreadable 分支喂失败计数并在翻转时广播,但仍保持瞬时语义', () => {const start = authSource.indexOf('export async function refresh(): Promise<boolean> {');diff --git a/apps/desktop/src/main/__tests__/authHostedCallback.test.ts b/apps/desktop/src/main/__tests__/authHostedCallback.test.tsindex 4dd80a4902..ace441e3bb 100644--- a/apps/desktop/src/main/__tests__/authHostedCallback.test.ts+++ b/apps/desktop/src/main/__tests__/authHostedCallback.test.ts@@ -209,12 +209,12 @@ describe('runHostedCallbackPolling', () => {});});- it('总时长耗尽按用户放弃处理(与 loopback 超时口径一致)', async () => {+ it('总时长耗尽显示超时,而不是静默当成用户取消', async () => {const harness = createPollHarness([{ status: 'pending' }]);await expect(runHostedCallbackPolling({ ...harness.deps, timeoutMs: 3_000 }),- ).resolves.toEqual({ error: 'USER_CANCELLED' });+ ).resolves.toEqual({ error: 'REQUEST_TIMEOUT' });// 3s 预算 / 1s 间隔 = 3 次轮询后耗尽。expect(harness.calls).toBe(3);});@@ -317,8 +317,12 @@ describe('openSystemBrowserAuthorization 分流', () => {const hostedStart = source.indexOf('async function openHostedBrowserAuthorization(');const hostedBody = source.slice(hostedStart, source.indexOf('\n}\n', hostedStart));- expect(hostedBody).toContain('raceAuthBrowserCancellation(');- expect(hostedBody).toContain('AbortSignal.any([signal, launchDeadline])');+ expect(hostedBody).toContain('launchAuthBrowser(() => shell.openExternal(authUrl), signal)');+ expect(hostedBody).toContain('if (!launched.opened) return { error: launched.error };');+ const loopbackStart = source.indexOf('async function openLoopbackBrowserAuthorization(');+ const loopbackBody = source.slice(loopbackStart, source.indexOf('\n}\n', loopbackStart));+ expect(loopbackBody).toContain('launchAuthBrowser(() => shell.openExternal(authUrl), launchCancellation.signal)');+ expect(loopbackBody).toContain('launchCancellation.abort();');// 不能是裸 await:那样取消与超时都落不到这一步上expect(hostedBody).not.toMatch(/await shell\.openExternal\(authUrl\);/);// 轮询预算要扣掉唤起已花的时间,整次尝试仍是一个五分钟diff --git a/apps/desktop/src/main/__tests__/authSessionExpiredDetection.test.ts b/apps/desktop/src/main/__tests__/authSessionExpiredDetection.test.tsindex b6dc330896..f9f1edc946 100644--- a/apps/desktop/src/main/__tests__/authSessionExpiredDetection.test.ts+++ b/apps/desktop/src/main/__tests__/authSessionExpiredDetection.test.ts@@ -12,10 +12,10 @@ import { describe, expect, it } from 'vitest';* token 后,正式版进程自以为登录,模型源静默消失、device-link 无限 401。*/describe('desktop auth session-expiry detection', () => {- const authSource = readFileSync(resolve(process.cwd(), 'src/main/authManager.ts'), 'utf8').replace(- /\r\n/g,- '\n',- );+ const authSource = readFileSync(+ resolve(process.cwd(), 'src/main/authManager.ts'),+ 'utf8',+ ).replace(/\r\n/g, '\n');const deviceLinkSource = readFileSync(resolve(process.cwd(), 'src/main/device-link/index.ts'),'utf8',@@ -71,7 +71,9 @@ describe('desktop auth session-expiry detection', () => {const expireStart = authSource.indexOf('async function expireRuntimeAuth(');const expireEnd = authSource.indexOf('if (accountSwitchTeardown)', expireStart);const expireBody = authSource.slice(expireStart, expireEnd);- expect(expireBody).toContain('preservePersistedRefreshToken: opts.preservePersistedRefreshToken');+ expect(expireBody).toContain(+ 'preservePersistedRefreshToken: opts.preservePersistedRefreshToken',+ );});it('isPersistedSecretAbsent 只在文件确定不存在(ENOENT)时判缺席', () => {@@ -81,7 +83,13 @@ describe('desktop auth session-expiry detection', () => {// 加密不可用不判缺席;existsSync 对 EPERM/EACCES 也返回 false,必须用// accessSync 并只认 ENOENT 为真缺席,其它错误一律按瞬时故障。- expect(body).toContain('if (!safeStorage.isEncryptionAvailable()) return false;');+ expect(body).toContain('if (!isCredentialEncryptionAvailable()) return false;');+ const probe = authSource.slice(+ authSource.indexOf('function isCredentialEncryptionAvailable()'),+ authSource.indexOf('/** Main-process recovery signal'),+ );+ expect(probe).toContain('const available = safeStorage.isEncryptionAvailable();');+ expect(probe).toContain('return available;');expect(body).toContain('fs.accessSync(');expect(body).toContain("=== 'ENOENT'");expect(body).not.toContain('existsSync');@@ -94,7 +102,9 @@ describe('desktop auth session-expiry detection', () => {const end = authSource.indexOf("} else if (action.kind === 'replacement-retry') {", anchor);const body = authSource.slice(start, end);- expect(body).toContain('await expireRuntimeAuth(previousUserId, resolveSessionExpiredReason(code));');+ expect(body).toContain(+ 'await expireRuntimeAuth(previousUserId, resolveSessionExpiredReason(code));',+ );});it('session-expired 广播携带客户端内部分类 reason,不透传服务端原文', () => {@@ -103,7 +113,9 @@ describe('desktop auth session-expiry detection', () => {const body = authSource.slice(start, end);expect(body).toContain("reason: SessionExpiredReason = 'unknown'");- expect(body).toContain("broadcastToRenderers('auth:session-expired', { message: '', reason });");+ expect(body).toContain(+ "broadcastToRenderers('auth:session-expired', { message: '', reason });",+ );});it('invalidateSession 只显式归类 account-unavailable,其余走通用文案', () => {@@ -124,7 +136,9 @@ describe('desktop auth session-expiry detection', () => {const issueStart = deviceLinkSource.indexOf('client.onConnectionIssue((issue) => {');const issueEnd = deviceLinkSource.indexOf('client.onPresenceChanged', issueStart);const issueBody = deviceLinkSource.slice(issueStart, issueEnd);- expect(issueBody).toContain("if (issue?.kind === 'auth-failed') recoverFromRelayAuthFailure();");+ expect(issueBody).toContain(+ "if (issue?.kind === 'auth-failed') recoverFromRelayAuthFailure();",+ );// 自救函数:节流(token-rotating 端点不能每次重连都打)+ refresh 成功后立即重连。const recoverStart = deviceLinkSource.indexOf('function recoverFromRelayAuthFailure(): void {');diff --git a/apps/desktop/src/main/authBrowserLaunch.ts b/apps/desktop/src/main/authBrowserLaunch.tsnew file mode 100644index 0000000000..8fbc71c146--- /dev/null+++ b/apps/desktop/src/main/authBrowserLaunch.ts@@ -0,0 +1,38 @@+/** OS browser launch has a shorter budget than the user's authorization flow. */+export const AUTH_BROWSER_LAUNCH_TIMEOUT_MS = 15_000;++export type AuthBrowserLaunchResult =+ | { opened: true }+ | { opened: false; error: 'USER_CANCELLED' | 'BROWSER_OPEN_FAILED' | 'BROWSER_OPEN_TIMEOUT' };++/** Bound a non-cancellable OS call, consuming late rejections after cancellation/timeout. */+export function launchAuthBrowser(+ open: () => Promise<void>,+ signal: AbortSignal,+): Promise<AuthBrowserLaunchResult> {+ if (signal.aborted) return Promise.resolve({ opened: false, error: 'USER_CANCELLED' });+ return new Promise((resolve) => {+ let settled = false;+ const finish = (result: AuthBrowserLaunchResult) => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ signal.removeEventListener('abort', cancel);+ resolve(result);+ };+ const cancel = () => finish({ opened: false, error: 'USER_CANCELLED' });+ const timer = setTimeout(+ () => finish({ opened: false, error: 'BROWSER_OPEN_TIMEOUT' }),+ AUTH_BROWSER_LAUNCH_TIMEOUT_MS,+ );+ signal.addEventListener('abort', cancel, { once: true });+ try {+ void open().then(+ () => finish({ opened: true }),+ () => finish({ opened: false, error: 'BROWSER_OPEN_FAILED' }),+ );+ } catch {+ finish({ opened: false, error: 'BROWSER_OPEN_FAILED' });+ }+ });+}diff --git a/apps/desktop/src/main/authCredentialRecovery.ts b/apps/desktop/src/main/authCredentialRecovery.tsnew file mode 100644index 0000000000..a91f87635e--- /dev/null+++ b/apps/desktop/src/main/authCredentialRecovery.ts@@ -0,0 +1,130 @@+/** Electron's macOS OSCrypt caches the first keychain failure for the process.+ * Only a new process can retry that read. Consume observed auth failures; never+ * probe safeStorage here (the probe itself can request keychain access).+ */+export const AUTH_CREDENTIAL_RECOVERY_ARG = '--cindy-auth-recovery-attempted';++export interface AuthCredentialRecoveryDeps {+ enabled: boolean;+ argv: readonly string[];+ needsRecovery: () => boolean;+ readScreenState: () => 'active' | 'idle' | 'locked' | 'unknown';+ isQuitting: () => boolean;+ isBusy: () => Promise<boolean>;+ relaunch: (args: string[]) => void;+ schedule: (callback: () => void, delayMs: number) => unknown;+ cancel: (handle: unknown) => void;+ onEvent: (+ event:+ | 'waiting-for-unlock'+ | 'waiting-for-idle'+ | 'relaunching'+ | 'attempt-exhausted'+ | 'relaunch-failed',+ ) => void;+}++export function createAuthCredentialRecovery(deps: AuthCredentialRecoveryDeps) {+ let disposed = false;+ let attempted = deps.argv.includes(AUTH_CREDENTIAL_RECOVERY_ARG);+ let exhaustionReported = false;+ let checking = false;+ let timer: unknown | null = null;+ // Events invalidate an async busy result even if the screen has unlocked again.+ let screenEpoch = 0;+ let explicitlyLocked = false;+ let lastEvent: Parameters<AuthCredentialRecoveryDeps['onEvent']>[0] | null = null;++ const report: AuthCredentialRecoveryDeps['onEvent'] = (event) => {+ if (lastEvent === event) return;+ lastEvent = event;+ deps.onEvent(event);+ };+ const cancelTimer = () => {+ if (timer !== null) deps.cancel(timer);+ timer = null;+ };+ const eligible = () => !disposed && deps.enabled && !deps.isQuitting() && deps.needsRecovery();+ const screenUsable = () => {+ try {+ const state = deps.readScreenState();+ if (state !== 'active' && state !== 'idle') return false;+ explicitlyLocked = false;+ return true;+ } catch {+ return false;+ }+ };+ const request = (delayMs = 3_000): void => {+ if (!eligible() || timer !== null || checking) return;+ if (attempted) {+ if (!exhaustionReported) {+ exhaustionReported = true;+ report('attempt-exhausted');+ }+ return;+ }+ timer = deps.schedule(() => {+ timer = null;+ void check();+ }, delayMs);+ };+ const check = async (): Promise<void> => {+ if (!eligible() || attempted || checking) return;+ if (!screenUsable()) {+ report('waiting-for-unlock');+ // Also covers a missed unlock event or a temporarily unknown system state.+ request(30_000);+ return;+ }+ checking = true;+ const epoch = screenEpoch;+ let busy = true;+ try {+ busy = await deps.isBusy();+ } catch {+ // A failed activity query must never interrupt work.+ } finally {+ checking = false;+ }+ if (!eligible() || attempted) return;+ if (screenEpoch !== epoch || !screenUsable()) {+ request(explicitlyLocked ? 30_000 : 3_000);+ return;+ }+ if (busy) {+ report('waiting-for-idle');+ request(30_000);+ return;+ }+ attempted = true;+ exhaustionReported = true;+ report('relaunching');+ try {+ // Preserve profile/passive flags. The successor inherits the one-attempt+ // budget; a later ordinary user launch starts a fresh recovery episode.+ deps.relaunch([...deps.argv, AUTH_CREDENTIAL_RECOVERY_ARG]);+ } catch {+ report('relaunch-failed');+ }+ };+ return {+ request: () => request(),+ onScreenLock: () => {+ explicitlyLocked = true;+ screenEpoch += 1;+ cancelTimer();+ request(30_000);+ },+ onScreenUnlock: () => {+ explicitlyLocked = false;+ screenEpoch += 1;+ cancelTimer();+ request();+ },+ dispose: () => {+ disposed = true;+ cancelTimer();+ },+ };+}diff --git a/apps/desktop/src/main/authCredentialStoreHealth.ts b/apps/desktop/src/main/authCredentialStoreHealth.tsindex ada1780ed4..11290108c9 100644--- a/apps/desktop/src/main/authCredentialStoreHealth.ts+++ b/apps/desktop/src/main/authCredentialStoreHealth.ts@@ -32,6 +32,8 @@ export interface CredentialStoreHealth {* 已处于 unavailable 时继续失败不再返回 true,避免重复广播。*/noteReadFailure(): boolean;+ /** Startup cannot restore a saved login: surface recovery immediately, without a live session. */+ noteStartupFailure(): void;/*** 记一次成功的持久凭证读取,连续失败计数清零。* 返回 true 表示此前处于 unavailable、状态刚恢复(调用方应广播)。@@ -56,6 +58,10 @@ export function createCredentialStoreHealth(unavailable = true;return true;},+ noteStartupFailure(): void {+ consecutiveFailures = threshold;+ unavailable = true;+ },noteRecovered(): boolean {consecutiveFailures = 0;if (!unavailable) return false;diff --git a/apps/desktop/src/main/authHostedCallback.ts b/apps/desktop/src/main/authHostedCallback.tsindex 25b2339482..3ae4c16258 100644--- a/apps/desktop/src/main/authHostedCallback.ts+++ b/apps/desktop/src/main/authHostedCallback.ts@@ -130,9 +130,8 @@ export interface HostedCallbackPollingDeps {/*** 轮询直到拿到结论、被取消或超时。*- * 取消与超时都收敛成 `USER_CANCELLED`:这与 loopback 路径的超时处理一致- * (authManager 的 BROWSER_AUTH_TIMEOUT_MS 分支),且该码在 renderer 被特意映射成- * "不展示错误"——用户把浏览器晾在一边不算失败。+ * Explicit cancellation stays silent; an expired wait must explain why the+ * authorization screen stopped waiting, consistently with the loopback path.*/export async function runHostedCallbackPolling(deps: HostedCallbackPollingDeps,@@ -145,7 +144,7 @@ export async function runHostedCallbackPolling(for (;;) {if (deps.signal.aborted) return { error: 'USER_CANCELLED' };if (deps.now() - startedAt >= deps.timeoutMs) {- return { error: 'USER_CANCELLED' };+ return { error: 'REQUEST_TIMEOUT' };}try {diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.tsindex c117de257e..fd0ba9b71e 100644--- a/apps/desktop/src/main/authManager.ts+++ b/apps/desktop/src/main/authManager.ts@@ -13,7 +13,7 @@* exposed by this module and receives state updates via 'auth:state-change'.*/-import { BrowserWindow, net, safeStorage, app, shell } from 'electron';+import { BrowserWindow, net, safeStorage, app, shell, powerMonitor } from 'electron';import crypto from 'node:crypto';import { createServer } from 'node:http';import type { AddressInfo } from 'node:net';@@ -80,6 +80,7 @@ import {type AuthLoopbackDevBridge,} from './authLoopbackCallback';import { createDesktopPollCredentials, runHostedCallbackPolling } from './authHostedCallback';+import { launchAuthBrowser } from './authBrowserLaunch';import { reconcileSavedAccountMetadata, type StoredAccountMetadata } from './authAccountMetadata';import {isLoggedOutVaultAccount,@@ -520,6 +521,47 @@ const SAFE_STORAGE_DIR = () => path.join(app.getPath('userData'), 'safe-storage'// 不可用」的区分,review 反馈)。错误只记 code/name,不记 message——fs 错误的// message 携带 userData 绝对路径,不该进保留 30 天的日志;密文/明文更不落。const safeStorageIssueLogged = new Set<string>();+let credentialEncryptionUnavailable = false;+let credentialEncryptionFailureLogged = false;++function isCredentialEncryptionAvailable(): boolean {+ const available = safeStorage.isEncryptionAvailable();+ // Only consume a real credential operation after Electron is ready. Filesystem+ // contention and an individual bad ciphertext do not require a process restart.+ if (app.isReady()) credentialEncryptionUnavailable = !available;+ if (!available && !credentialEncryptionFailureLogged) {+ credentialEncryptionFailureLogged = true;+ let screenState = 'unknown';+ try {+ if (app.isReady()) screenState = powerMonitor.getSystemIdleState(1);+ } catch {+ // Diagnostics must not change credential read behavior.+ }+ log.warn('credential encryption backend unavailable', {+ appReady: app.isReady(),+ screenState,+ electronVersion: process.versions.electron,+ });+ }+ return available;+}++/** Main-process recovery signal; never expose credentials or probe the keychain. */+export function needsCredentialProcessRecovery(): boolean {+ return (+ credentialEncryptionUnavailable &&+ credentialStoreHealth.unavailable &&+ accessToken === null &&+ getActiveAppSession().mode === 'signed-out' &&+ !isPassiveSharedUserDataInstance()+ );+}++/** Prevent automatic process recovery from racing an explicit login action. */+export function isAuthFlowBusy(): boolean {+ return loginActionPromise !== null || loginFlowState?.step === 'browser-redirect';+}+function logSafeStorageIssueOnce(reason: string, key: string, err?: unknown): void {const issueKey = `${reason}:${key}`;if (safeStorageIssueLogged.has(issueKey)) return;@@ -529,7 +571,7 @@ function logSafeStorageIssueOnce(reason: string, key: string, err?: unknown): vofunction readSafe(key: string): string | null {try {- if (!safeStorage.isEncryptionAvailable()) {+ if (!isCredentialEncryptionAvailable()) {logSafeStorageIssueOnce('encryption unavailable (read)', key);return null;}@@ -543,6 +585,29 @@ function readSafe(key: string): string | null {}}+// Startup recovery must preserve existing records, including atomic backups and+// logout tombstones. Only definite absence permits the fresh-profile login UI;+// checking filenames does not probe the encryption backend or decrypt anything.+function hasPotentiallyPersistedAuthCredentials(): boolean {+ return [+ AUTH_SESSION_KEY,+ AUTH_ACCOUNT_VAULT_KEY,+ AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY,+ LEGACY_RESOURCE_REFRESH_TOKEN_KEY,+ LEGACY_ACCOUNT_REFRESH_TOKEN_KEY,+ LEGACY_REFRESH_TOKEN_KEY,+ ].some((key) =>+ ['', '.bak'].some((suffix) => {+ try {+ fs.accessSync(path.join(SAFE_STORAGE_DIR(), `${key}.enc${suffix}`), fs.constants.F_OK);+ return true;+ } catch (error) {+ return (error as NodeJS.ErrnoException)?.code !== 'ENOENT';+ }+ }),+ );+}+/*** 区分「凭证文件确实不存在」与「暂时读不出来」。*@@ -557,7 +622,7 @@ function readSafe(key: string): string | null {*/function isPersistedSecretAbsent(key: string): boolean {try {- if (!safeStorage.isEncryptionAvailable()) return false;+ if (!isCredentialEncryptionAvailable()) return false;fs.accessSync(path.join(SAFE_STORAGE_DIR(), `${key}.enc`), fs.constants.F_OK);return false;} catch (err) {@@ -567,7 +632,7 @@ function isPersistedSecretAbsent(key: string): boolean {function writeSafe(key: string, value: string): boolean {try {- if (!safeStorage.isEncryptionAvailable()) {+ if (!isCredentialEncryptionAvailable()) {logSafeStorageIssueOnce('encryption unavailable (write)', key);return false;}@@ -593,7 +658,7 @@ function writeSafe(key: string, value: string): boolean {*/function readAtomicSafe(key: string): string | null {try {- if (!safeStorage.isEncryptionAvailable()) {+ if (!isCredentialEncryptionAvailable()) {logSafeStorageIssueOnce('encryption unavailable (atomic read)', key);return null;}@@ -620,7 +685,7 @@ function readAtomicSafe(key: string): string | null {*/function readAtomicSafeCiphertext(key: string): string | null {try {- if (!safeStorage.isEncryptionAvailable()) return null;+ if (!isCredentialEncryptionAvailable()) return null;return readAtomicFileSync(path.join(SAFE_STORAGE_DIR(), `${key}.enc`));} catch (err) {if ((err as NodeJS.ErrnoException)?.code === 'ENOENT') return null;@@ -640,7 +705,7 @@ function writeAtomicSafeCiphertext(key: string, ciphertext: string): boolean {}function isAtomicPersistedSecretAbsent(key: string): boolean {- if (!safeStorage.isEncryptionAvailable()) return false;+ if (!isCredentialEncryptionAvailable()) return false;const filepath = path.join(SAFE_STORAGE_DIR(), `${key}.enc`);for (const candidate of [filepath, `${filepath}.bak`]) {try {@@ -655,7 +720,7 @@ function isAtomicPersistedSecretAbsent(key: string): boolean {function writeAtomicSafe(key: string, value: string): boolean {try {- if (!safeStorage.isEncryptionAvailable()) {+ if (!isCredentialEncryptionAvailable()) {logSafeStorageIssueOnce('encryption unavailable (atomic write)', key);return false;}@@ -2400,6 +2465,7 @@ async function withCloudOwnerCommit<T>(opts: {async function withAccountFreeOwnerCommit(opts: {reason: string;nextMode: Extract<AppSessionMode, 'signed-out' | 'local'>;+ credentialStoreUnavailable?: boolean;preservePersistedRefreshToken?: boolean;notify?: boolean;clearOnFailure?: boolean;@@ -2430,6 +2496,7 @@ async function withAccountFreeOwnerCommit(opts: {notify: false,nextMode: opts.nextMode,preservePersistedRefreshToken: true,+ credentialStoreUnavailable: opts.credentialStoreUnavailable,deferSessionCommit: true,});authCleared = true;@@ -2478,6 +2545,7 @@ async function withAccountFreeOwnerCommit(opts: {notify: false,nextMode: opts.nextMode,preservePersistedRefreshToken: opts.preservePersistedRefreshToken,+ credentialStoreUnavailable: opts.credentialStoreUnavailable,deferSessionCommit: true,});authCleared = true;@@ -2501,6 +2569,7 @@ async function withAccountFreeOwnerCommit(opts: {notify: false,nextMode: 'signed-out',preservePersistedRefreshToken: opts.preservePersistedRefreshToken,+ credentialStoreUnavailable: opts.credentialStoreUnavailable,deferSessionCommit: true,});authCleared = true;@@ -2531,9 +2600,11 @@ async function withAccountFreeOwnerCommit(opts: {async function recoverAccountFreeOwnerAtStartup(mode: Extract<AppSessionMode, 'signed-out' | 'local'>,reason: string,+ credentialStoreUnavailable = false,): Promise<void> {const ownerId = mode === 'local' ? LOCAL_DATA_OWNER_ID : null;if (isGhostSkillProjectionBoundaryStableForOwner(ownerId)) {+ if (credentialStoreUnavailable) credentialStoreHealth.noteStartupFailure();if (getActiveAppSession().mode !== mode || getActiveAppSession().dataOwnerId !== ownerId) {if (isPassiveSharedUserDataInstance()) {commitVolatileAppSession(mode);@@ -2547,6 +2618,7 @@ async function recoverAccountFreeOwnerAtStartup(await withAccountFreeOwnerCommit({reason,nextMode: mode,+ credentialStoreUnavailable,notify: false,clearOnFailure: mode === 'signed-out',preservePersistedRefreshToken: true,@@ -2757,8 +2829,11 @@ async function migrateLocalProviderBindingsAfterCloudCommit(ownerId: string): Pr}}-async function finishColdStartSignedOut(reason: string): Promise<AuthState> {- await recoverAccountFreeOwnerAtStartup('signed-out', reason);+async function finishColdStartSignedOut(+ reason: string,+ credentialStoreUnavailable = false,+): Promise<AuthState> {+ await recoverAccountFreeOwnerAtStartup('signed-out', reason, credentialStoreUnavailable);return snapshotLoggedOutAuthState();}@@ -2869,24 +2944,10 @@ async function openHostedBrowserAuthorization(// 分支「先起 timer 再 openExternal」的语义对齐。const deadline = Date.now() + BROWSER_AUTH_TIMEOUT_MS;- // shell.openExternal 必须与取消/超时竞速。它在某些环境下会长时间不返回(系统- // 默认浏览器正在冷启动、handler 注册异常等),而这一步发生在轮询开始之前——- // 若只是 await 它,取消信号和五分钟预算都够不着,cancel-browser 会一直等在同一个- // 未 settle 的登录动作上。- const launchDeadline = AbortSignal.timeout(BROWSER_AUTH_TIMEOUT_MS);- const launched = await raceAuthBrowserCancellation(- shell.openExternal(authUrl).then(- () => ({ ok: true }) as const,- (error: unknown) => {- log.warn('open auth URL in system browser failed', error);- return { ok: false } as const;- },- ),- AbortSignal.any([signal, launchDeadline]),- );- // 取消与超时都收敛成 USER_CANCELLED(renderer 特意不展示它),与 loopback 一致。- if (launched.cancelled) return { error: 'USER_CANCELLED' };- if (!launched.value.ok) return { error: 'BROWSER_OPEN_FAILED' };+ // Opening the OS handler gets its own short budget; it is not the time the+ // user spends authorizing. Do not hide a stuck launch as USER_CANCELLED.+ const launched = await launchAuthBrowser(() => shell.openExternal(authUrl), signal);+ if (!launched.opened) return { error: launched.error };return runHostedCallbackPolling({poll: async () => {@@ -2929,6 +2990,7 @@ async function openLoopbackBrowserAuthorization(return new Promise((resolve) => {let settled = false;let timeout: ReturnType<typeof setTimeout> | null = null;+ const launchCancellation = new AbortController();// 回调页语言跟随 app 当前 UI 语言(main 迷你 i18n 复用 renderer 五语文案,// {{appName}} 由 t() 注入品牌名);成功 / 失败分别渲染,失败附原始错误码。// 抽成局部渲染器供真实 HTTP 回调与 dev bridge 触发路径共用(同一 HTML)。@@ -2973,6 +3035,7 @@ async function openLoopbackBrowserAuthorization(const finish = (result: { code: string } | { error: string }) => {if (settled) return;settled = true;+ launchCancellation.abort();signal.removeEventListener('abort', cancel);if (timeout !== null) clearTimeout(timeout);if (server.listening) {@@ -2995,6 +3058,7 @@ async function openLoopbackBrowserAuthorization(cancel();return;}+ timeout = setTimeout(() => finish({ error: 'REQUEST_TIMEOUT' }), BROWSER_AUTH_TIMEOUT_MS);server.listen(0, '127.0.0.1', () => {if (settled) {server.close();@@ -3005,11 +3069,12 @@ async function openLoopbackBrowserAuthorization(const authUrl = client.buildAuthorizeUrl({ ...input, redirectUri });// dev bridge 挂接(packaged no-op):fixture 触发与真实回调走同一渲染/finish。authLoopbackDevBridgeSlot.attach(finish, renderCallbackPage);- timeout = setTimeout(() => finish({ error: 'USER_CANCELLED' }), BROWSER_AUTH_TIMEOUT_MS);- void shell.openExternal(authUrl).catch((error) => {- log.warn('open auth URL in system browser failed', error);- finish({ error: 'BROWSER_OPEN_FAILED' });- });+ if (settled) return;+ void launchAuthBrowser(() => shell.openExternal(authUrl), launchCancellation.signal).then(+ (launched) => {+ if (!launched.opened) finish({ error: launched.error });+ },+ );});});}@@ -3408,7 +3473,8 @@ function snapshotLoggedOutAuthState(): AuthState {deviceId,hasAccountDeletionReceipt: readPersistedAccountDeletionReceipt() !== null,accountDeletionRestored: false,- // 登出投影不携带升级态:登录页可见时用户已有明确的重新登录入口。+ // Startup recovery errors are returned by getLoginState; this projection+ // also serves stale/timeout paths and must not expose another owner's health.credentialStoreUnavailable: false,};}@@ -3561,6 +3627,8 @@ function clearAuth(opts: {notify?: boolean;nextMode?: Extract<AppSessionMode, 'signed-out' | 'local'>;+ /** Preserve the reason a saved login could not be restored through owner cleanup. */+ credentialStoreUnavailable?: boolean;/*** 为 true 时不删除磁盘上的 refresh token 文件。仅用于「凭证已确认缺席」的* 过期路径(credential-lost):此刻磁盘上没有属于本进程的 token 可清,而共享@@ -3580,9 +3648,10 @@ function clearAuth(const notify = opts.notify ?? true;authStateEpoch += 1; // 迟到的冷启动流程从此作废(见 authStateEpoch 注释)loginFlowEpoch += 1;- // #1687:登出 / 会话过期整体清态时复位凭证库升级态——升级提示只对「仍以为- // 自己登录着」的会话有意义,登录页自身就是恢复入口。+ // Explicit logout clears health. Failed startup keeps its recovery reason+ // in the same synchronous commit, so owner cleanup cannot erase the error.credentialStoreHealth.reset();+ if (opts.credentialStoreUnavailable) credentialStoreHealth.noteStartupFailure();accessToken = null;pendingAccountToken = null;pendingAccountRefreshToken = null;@@ -4508,12 +4577,19 @@ export async function initialize(options: AuthInitializeOptions = {}): Promise<Alet persistedSession: ReturnType<typeof readPersistedAuthSession>;try {persistedSession = await reconcileDesktopActiveAuthSession();+ credentialStoreHealth.noteRecovered();} catch (error) {log.warn('cold-start active credential reconciliation failed; preserving credentials for retry',error,);- return finishColdStartSignedOut('cold-start-credential-reconcile-unavailable');+ return finishColdStartSignedOut(+ 'cold-start-credential-reconcile-unavailable',+ credentialEncryptionUnavailable &&+ error instanceof AuthApiError &&+ error.code === 'CREDENTIAL_STORE_UNAVAILABLE' &&+ hasPotentiallyPersistedAuthCredentials(),+ );}if (!persistedSession) {// 旧版只保存裸 refresh token,没有 realm 可供校验。只有独占 userData 的@@ -4809,6 +4885,7 @@ async function runColdStartRefreshFlow(}accessToken = refreshData.accessToken;currentUser = mapMembershipToAuthUser(refreshData.membership);+ loginFlowState = { step: 'completed', membership: refreshData.membership };commitCloudAppSession(currentUser.id, authRealmChanged);persistedRefreshTokenNeedsIdentityCheck = false;clearReplacementIntegrationReloadTimers();@@ -4936,6 +5013,13 @@ export async function getLoginState(): Promise<DesktopLoginActionResult> {}const expectedLoginFlowEpoch = loginFlowEpoch;try {+ if (!accessToken && credentialStoreHealth.unavailable) {+ return {+ success: false,+ code: 'CREDENTIAL_STORE_UNAVAILABLE',+ state: { step: 'error', code: 'CREDENTIAL_STORE_UNAVAILABLE', recoverTo: 'identifier' },+ };+ }if (loginFlowState) return { success: true, state: loginFlowState };return { success: true, state: await loadLoginProviders(expectedLoginFlowEpoch) };} catch (error) {@@ -5054,6 +5138,7 @@ async function completeLogin(passiveLocalSignOut = false;foreignDeviceLocalSignOut = false;currentUser = nextUser;+ credentialStoreHealth.noteRecovered();if (!isPassiveSharedUserDataInstance()) {canaryFlagStore.clear();}@@ -5182,8 +5267,22 @@ async function runLoginAction(action: DesktopLoginAction): Promise<DesktopLoginAthrow new AuthApiError('INVALID_AUTH_ACTION', 400, 'Unexpected browser cancellation');}if (action.type === 'reset') {+ // Retry restoration before offering a new login. A temporary credential+ // failure must never make the user replace their still-saved session.+ if (!accessToken && credentialStoreHealth.unavailable) {+ await initialize();+ // Startup may itself clear an obsolete owner generation. Its current+ // recovery error is still safe to return, even when that cleared the+ // original login flow; successful/newer auth keeps the epoch guard.+ if (!accessToken && credentialStoreHealth.unavailable) return getLoginState();+ assertLoginFlowCurrent(actionLoginFlowEpoch);+ if (accessToken && loginFlowState?.step === 'completed') {+ return { success: true, state: loginFlowState };+ }+ }return { success: true, state: await loadLoginProviders(actionLoginFlowEpoch) };}+ if (!accessToken && credentialStoreHealth.unavailable) return getLoginState();if (action.type === 'confirm-sso-realm') {const confirmation = loginFlowState;if (@@ -5229,7 +5328,8 @@ async function runLoginAction(action: DesktopLoginAction): Promise<DesktopLoginA}if (confirmation.personalLoginAvailable) {const personal = pendingPersonalLogin;- if (!personal) throw new AuthApiError('INVALID_AUTH_ACTION', 400, 'Personal login unavailable');+ if (!personal)+ throw new AuthApiError('INVALID_AUTH_ACTION', 400, 'Personal login unavailable');pendingAuthRealm = personal.realm;const state = await completeLogin(personal.outcome, actionLoginFlowEpoch);pendingPersonalLogin = null;diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex aa295d6687..295c0e77ce 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -253,6 +253,11 @@ import {} from './im';import { setTelegramRemoteSource } from './device-link/telegramRemoteControl';import * as authManager from './authManager';+import { createAuthCredentialRecovery } from './authCredentialRecovery';+import {+ evaluateRelaunchBusyActivity,+ type RelaunchBusyActivitySources,+} from './relaunchBusyActivity';import { hasPersistedSessionHint } from './authSessionHint';import {hasExclusiveSharedLegacyUserDataAccess,@@ -1219,7 +1224,8 @@ async function attemptStartSchedulerOnce(): Promise<void> {startLearnHost({maker,broadcast: broadcastLearnEvent,- fetchHubSkill: (slug, catalogScope) => fetchHubSkillReference(learnMarketService, slug, catalogScope),+ fetchHubSkill: (slug, catalogScope) =>+ fetchHubSkillReference(learnMarketService, slug, catalogScope),...automationGitBaselineHooks,});} catch (err) {@@ -1385,8 +1391,8 @@ function scheduleChatEmbeddingRuntimeReconcile(): Promise<void> {chatEmbeddingRuntimeReconcile = chatEmbeddingRuntimeReconcile.then(async () => {if (- isChatEmbeddingAvailable()- && readChatEmbeddingSettings(chatEmbeddingDefaultContext()).enabled+ isChatEmbeddingAvailable() &&+ readChatEmbeddingSettings(chatEmbeddingDefaultContext()).enabled) {attemptStartEmbeddingHost();} else {@@ -1589,10 +1595,10 @@ function markAccountBoundaryAbortedMidTeardown(reason: string): void {if (accountBoundaryAbortedMidTeardown !== null) return;accountBoundaryAbortedMidTeardown = reason;authBoundaryLog.error(- `account handover on ${reason} was aborted after teardown had already run — this `- + 'account keeps its custom provider catalog cleared and its IM, scheduler, '- + 'embedding, Ghost projection and Learn services stopped until the app is '- + 'restarted or a later handover succeeds',+ `account handover on ${reason} was aborted after teardown had already run — this ` ++ 'account keeps its custom provider catalog cleared and its IM, scheduler, ' ++ 'embedding, Ghost projection and Learn services stopped until the app is ' ++ 'restarted or a later handover succeeds',);}@@ -2039,8 +2045,8 @@ authManager.setProjectionRepairTeardown(teardownGhostProjectionBoundary);// mid-relaunch) would otherwise refuse this instance's Subagent launches for as// long as the file sits there. Only fences whose owner is gone are dropped, so a// concurrent instance genuinely mid-relaunch keeps its own.-void clearStalePiSubagentLaunchFence(path.join(app.getPath('userData'), 'pi-agent-home'))- .catch((err: unknown) => {+void clearStalePiSubagentLaunchFence(path.join(app.getPath('userData'), 'pi-agent-home')).catch(+ (err: unknown) => {piSubagentLog.warn('stale Subagent launch fence cleanup failed (non-fatal):', err);},);@@ -3163,6 +3169,61 @@ const updatePresentationRecovery = isUpdateRelaunchCandidate// 直接 show 回来,renderer 不重新加载。Cmd+Q / before-quit 时把这个标志置 true,// 让窗口 close handler 放行真正的销毁。let isQuitting = false;+const authCredentialRecoveryLog = createLogger('auth-credential-recovery');++function readRelaunchActivitySources(): RelaunchBusyActivitySources {+ return {+ anySessionInTurn: () => {+ const maker = getMakerIfReady();+ return maker ? anySessionInTurn(maker) : false;+ },+ listClaudeBackgroundSessions: () => listActiveClaudeBackgroundActivitySessions(),+ anyGhostSessionBusy: () => getGhostSessionActivityTracker().anySessionBusy(),+ // run_in_background 的 Bash 不调模型、也不折算 running,前两个来源都看不到它。+ anyBackgroundBashRunning: () =>+ getMakerIfReady()+ ?.listActiveSessions()+ .some((session) => session.listBackgroundTasks().length > 0) ?? false,+ // Cindy slot 的全部在途工作:异步(mode:'submit' 的图 / 视频)与同步代办各自独立记账,+ // 都可能不伴随任何 turn 或 card-action,只查一半就漏一半。+ anyCindySlotJobRunning: () => getGhostCindySlot().anyInflightWork(),+ // Scope to this process: `pi-agent-home` is shared with a concurrent+ // dev/packaged/`--passive` instance, and its running Subagents are not+ // a reason to hold up *our* quit.+ anyPiSubagentRunning: () =>+ hasActivePiSubagentRunsSync(path.join(app.getPath('userData'), 'pi-agent-home'), {+ hostPid: process.pid,+ }),+ // script 模式 / pre-run hook 阶段的 run 不创建 session,内存来源看不到它们。+ anySchedulerRunRunning: () => readUpdateRelaunchScheduleBusy(getScheduleStorageIfInitialized()),+ };+}++const authCredentialRecovery = createAuthCredentialRecovery({+ enabled: process.platform === 'darwin' && app.isPackaged,+ argv: process.argv.slice(1),+ needsRecovery: () => authManager.needsCredentialProcessRecovery(),+ readScreenState: () => powerMonitor.getSystemIdleState(1),+ isQuitting: () => isQuitting,+ isBusy: () =>+ hasUpdateRelaunchBusyActivity({+ readSynchronousBusy: () =>+ isAppSessionBoundaryPending() ||+ authManager.isAuthFlowBusy() ||+ getUpdateRelaunchControllers().length > 0 ||+ hasInFlightRemoteInvokes(),+ readScheduleBusy: async () =>+ (await evaluateRelaunchBusyActivity(readRelaunchActivitySources())).busy,+ }),+ relaunch: (args) => {+ app.relaunch({ args });+ app.quit(); // Normal lifecycle: flush storage and dispose background services.+ },+ schedule: (callback, delayMs) => setTimeout(callback, delayMs),+ cancel: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),+ onEvent: (event) => authCredentialRecoveryLog.info(event),+});+let windowsTray: Tray | null = null;// 当前的托盘菜单。语言切换时置 null,下一次右键按新语言重建。let windowsTrayMenu: Menu | null = null;@@ -3417,6 +3478,7 @@ app.on('before-quit', () => {linuxClosePromptFallback.dispose();destroyWindowsTray();disposeUpdatePresentationRecovery();+ authCredentialRecovery.dispose();});function handleUpdatePresentationLock(): void {@@ -3758,15 +3820,15 @@ const createWindow = () => {// missing/invalid mirrors and other platforms keep the native OS-theme fallback.// mac:创建期即透明底+sidebar 材质(Electron setBackgroundColor 运行时改 alpha 不可靠,是 vibrancy 不透壁纸的根因;非 CINDY 皮肤 body 不透明会自然盖住,视觉无影响)const persistedTheme = process.platform === 'win32' ? readWindowThemeSnapshot() : null;- const isDark = process.platform === 'win32'+ const isDark =+ process.platform === 'win32'? resolveAppThemeIsDark(nativeTheme.shouldUseDarkColors,persistedTheme?.mode,persistedTheme?.resolvedIsDark,): nativeTheme.shouldUseDarkColors;- const bgColor =- process.platform === 'darwin' ? '#00000000' : isDark ? '#1f1f1e' : '#f8f8f6';+ const bgColor = process.platform === 'darwin' ? '#00000000' : isDark ? '#1f1f1e' : '#f8f8f6';const winBackdropConfig = resolveVibrancyConfig(persistedTheme?.familyId ?? 'cindy',isDark,@@ -4201,7 +4263,8 @@ function checkDatabaseSizeWarningAtStartup(): void {if (startupDatabaseSizeWarningStatusChecked &&startupDatabaseSizeWarningOwnerScope === ownerScope- ) return;+ )+ return;startupDatabaseSizeWarningStatus = collectCurrentDatabaseSizeWarningStatus();startupDatabaseSizeWarningStatusChecked = true;startupDatabaseSizeWarningOwnerScope = ownerScope;@@ -4219,10 +4282,7 @@ function syncPluginMarketForActiveOwner(minIntervalMs = 0): void {const scope = activeOwnerScopeKey();if (scope === pluginMarketSyncInFlightScope) return;const now = Date.now();- if (- scope === lastPluginMarketSyncScope &&- now - lastPluginMarketSyncAt < minIntervalMs- ) {+ if (scope === lastPluginMarketSyncScope && now - lastPluginMarketSyncAt < minIntervalMs) {return;}pluginMarketSyncInFlightScope = scope;@@ -4460,9 +4520,7 @@ const registerIpcHandlers = () => {applyVibrancyToSecondaryWindows(familyId, isDark);}- ipcMain.on(- 'theme:apply-vibrancy',- (event, rawPayload: unknown) => {+ ipcMain.on('theme:apply-vibrancy', (event, rawPayload: unknown) => {assertTrustedAppRendererEvent(event);const payload = parseWindowThemeVibrancyPayload(rawPayload);if (!payload) return;@@ -4721,7 +4779,9 @@ const registerIpcHandlers = () => {resetCompactionPct();return compactionWire();});- ipcMain.handle(MAKER_IPC_INVOKE.COMPACTION_SET_PCT, async (event, pct: unknown, owner: unknown) => {+ ipcMain.handle(+ MAKER_IPC_INVOKE.COMPACTION_SET_PCT,+ async (event, pct: unknown, owner: unknown) => {assertTrustedAppRendererEvent(event);if (typeof pct !== 'number' || !Number.isFinite(pct)) {throwIpcError('INVALID_PARAMS', 'compaction pct required (number)');@@ -4746,7 +4806,9 @@ const registerIpcHandlers = () => {resetPiCompactionPct();return piCompactionWire();});- ipcMain.handle(MAKER_IPC_INVOKE.PI_COMPACTION_SET_PCT, async (event, pct: unknown, owner: unknown) => {+ ipcMain.handle(+ MAKER_IPC_INVOKE.PI_COMPACTION_SET_PCT,+ async (event, pct: unknown, owner: unknown) => {assertTrustedAppRendererEvent(event);if (typeof pct !== 'number' || !Number.isFinite(pct)) {throwIpcError('INVALID_PARAMS', 'pi compaction pct required (number)');@@ -4868,9 +4930,7 @@ const registerIpcHandlers = () => {return chatEmbeddingWire();},);- ipcMain.handle(- MAKER_IPC_INVOKE.CHAT_EMBEDDING_RESET,- async (_e, owner: unknown) => {+ ipcMain.handle(MAKER_IPC_INVOKE.CHAT_EMBEDDING_RESET, async (_e, owner: unknown) => {assertChatEmbeddingMutationOwner(owner);try {await resetChatEmbeddingSettings(chatEmbeddingDefaultContext());@@ -4945,32 +5005,44 @@ const registerIpcHandlers = () => {ipcMain.handle(MAKER_IPC_INVOKE.CLAUDE_OAUTH_LOGIN, async (event, loginKey?: string) => {assertTrustedAppRendererEvent(event);const owner = activeOwnerScopeKey();- if (isAppSessionBoundaryPending() || !getActiveAppSession().dataOwnerId) return { ok: false, reason: 'login_cancelled', authorized: false };+ if (isAppSessionBoundaryPending() || !getActiveAppSession().dataOwnerId)+ return { ok: false, reason: 'login_cancelled', authorized: false };const signal = beginClaudeLocalLogin(loginKey);resetProviderModelAutoRefreshCooldowns('anthropic');await clearAnthropicDiscoveredModels();- if (signal.aborted || owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending()) return { ok: false, reason: 'login_cancelled', authorized: false };+ if (signal.aborted || owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending())+ return { ok: false, reason: 'login_cancelled', authorized: false };await ensureAnthropicCompatProxyReady();- if (signal.aborted || owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending()) return { ok: false, reason: 'login_cancelled', authorized: false };- if (!reconnectClaudeAiOAuth()) return { ok: false, reason: 'local_unavailable', authorized: false };+ if (signal.aborted || owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending())+ return { ok: false, reason: 'login_cancelled', authorized: false };+ if (!reconnectClaudeAiOAuth())+ return { ok: false, reason: 'local_unavailable', authorized: false };// Binding is the commit point; auxiliary refresh must not prolong the cancellable login.void broadcastClaudeAuthStateChanged();syncClaudeSubscriptionUsageForAuthChange();void refreshAnthropicModelsFromHttp();return { ok: true, authorized: hasClaudeAiOAuth() };});- ipcMain.handle(MAKER_IPC_INVOKE.CLAUDE_OAUTH_LOGOUT, async (event, ownerScope?: { dataOwnerId: string | null; ownerGeneration: number }) => {+ ipcMain.handle(+ MAKER_IPC_INVOKE.CLAUDE_OAUTH_LOGOUT,+ async (event, ownerScope?: { dataOwnerId: string | null; ownerGeneration: number }) => {assertTrustedAppRendererEvent(event);const active = getActiveAppSession();const owner = activeOwnerScopeKey();- if (isAppSessionBoundaryPending() || (ownerScope && (ownerScope.dataOwnerId !== active.dataOwnerId || ownerScope.ownerGeneration !== active.generation))) {+ if (+ isAppSessionBoundaryPending() ||+ (ownerScope &&+ (ownerScope.dataOwnerId !== active.dataOwnerId ||+ ownerScope.ownerGeneration !== active.generation))+ ) {throwIpcError('INVALID_PARAMS', 'Provider owner changed');}// Cancel pending Cindy login/refresh before revoking the binding; keep native credentials.try {cancelClaudeOAuthLogin();await disconnectClaudeAiOAuth();- if (owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending()) return { authorized: false };+ if (owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending())+ return { authorized: false };resetProviderModelAutoRefreshCooldowns('anthropic');} catch (err) {throwIpcError(@@ -4979,7 +5051,8 @@ const registerIpcHandlers = () => {);}await broadcastClaudeAuthStateChanged();- if (owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending()) return { authorized: false };+ if (owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending())+ return { authorized: false };// Binding revoked: read() clears the Cindy quota snapshot and broadcasts null.syncClaudeSubscriptionUsageForAuthChange();// 模型清单动态发现:登出完成前清空清单 + 删磁盘缓存,并等待旧 SDK 写盘收尾。@@ -5032,19 +5105,22 @@ const registerIpcHandlers = () => {// reason 是 renderer 决定提示用的结构化数据,不抛 throwIpcError(规则 13 查询型例外)。// 登录成功即生效:订阅直连 handler 每请求经 buildHeaders 现取凭证,无需任何"就绪"步骤。const result = await runGrokOAuthLogin();- if (owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending()) return { ok: false, reason: 'login_cancelled', authorized: false };+ if (owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending())+ return { ok: false, reason: 'login_cancelled', authorized: false };if (result.ok) {void retainProviderPresentationAfterAuthChange('xai');resetProviderModelAutoRefreshCooldowns('xai');// 新凭证在 runGrokOAuthLogin 返回前已经落盘。先同步关掉旧周用量读取窗口,// 再去做模型磁盘清理等 await,避免换号间隙里 IPC read 仍返回账号 A 的快照。await clearXaiSubscriptionUsageSnapshot();- if (owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending()) return { ok: false, reason: 'login_cancelled', authorized: false };+ if (owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending())+ return { ok: false, reason: 'login_cancelled', authorized: false };// 登录可直接覆盖旧 SuperGrok 账号:先清旧世代内存,再直接读新账号官方清单。// 这里不能先恢复同一 Cindy owner 的磁盘 LKG,否则 A→B 重登会短暂展示 A 的成员。clearXaiDiscoveredModels();await discardXaiModelsDiskCache();- if (owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending()) return { ok: false, reason: 'login_cancelled', authorized: false };+ if (owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending())+ return { ok: false, reason: 'login_cancelled', authorized: false };// 登录可直接覆盖旧账号凭证。先跨授权边界清掉旧账号发现快照,再补拉新账号;// 旧在途请求由 discovery generation + owner scope 双重守卫作废。clearXaiMediaModels();@@ -5053,7 +5129,8 @@ const registerIpcHandlers = () => {// 限流快照是账号级的:重登可能换账号,旧快照一并清掉(等新账号首个 xai/ 轮自然补上)。clearXaiRateLimitSnapshot();await syncXaiSubscriptionUsageForAuthChange();- if (owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending()) return { ok: false, reason: 'login_cancelled', authorized: false };+ if (owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending())+ return { ok: false, reason: 'login_cancelled', authorized: false };broadcastXaiAuthStateChanged();void refreshXaiModelsFromHttp();void refreshProviderModelsManually('xai').catch((error) => {@@ -5065,11 +5142,18 @@ const registerIpcHandlers = () => {}return { ok: false, reason: result.reason ?? 'unknown', authorized: hasGrokOAuthLogin() };});- ipcMain.handle(MAKER_IPC_INVOKE.XAI_OAUTH_LOGOUT, async (event, ownerScope?: { dataOwnerId: string | null; ownerGeneration: number }) => {+ ipcMain.handle(+ MAKER_IPC_INVOKE.XAI_OAUTH_LOGOUT,+ async (event, ownerScope?: { dataOwnerId: string | null; ownerGeneration: number }) => {assertTrustedAppRendererEvent(event);const active = getActiveAppSession();const owner = activeOwnerScopeKey();- if (isAppSessionBoundaryPending() || (ownerScope && (ownerScope.dataOwnerId !== active.dataOwnerId || ownerScope.ownerGeneration !== active.generation))) {+ if (+ isAppSessionBoundaryPending() ||+ (ownerScope &&+ (ownerScope.dataOwnerId !== active.dataOwnerId ||+ ownerScope.ownerGeneration !== active.generation))+ ) {throwIpcError('INVALID_PARAMS', 'Provider owner changed');}try {@@ -5079,7 +5163,8 @@ const registerIpcHandlers = () => {resetProviderModelAutoRefreshCooldowns('xai');await clearXaiSubscriptionUsageSnapshot();await presentation;- if (owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending()) return { ok: false, reason: 'login_cancelled', authorized: false };+ if (owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending())+ return { ok: false, reason: 'login_cancelled', authorized: false };clearXaiDiscoveredModels();clearXaiMediaModels();} catch (err) {@@ -5092,7 +5177,8 @@ const registerIpcHandlers = () => {// 并清掉账号级限流快照 —— 登出后没有下一个成功响应来覆盖,不清会一直挂着旧账号余量。clearXaiRateLimitSnapshot();await syncXaiSubscriptionUsageForAuthChange();- if (owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending()) return { ok: false, reason: 'login_cancelled', authorized: false };+ if (owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending())+ return { ok: false, reason: 'login_cancelled', authorized: false };broadcastXaiAuthStateChanged();return { authorized: hasGrokOAuthLogin() };},@@ -5705,7 +5791,13 @@ const registerIpcHandlers = () => {): Promise<void> => {assertTrustedAppRendererEvent(event);const active = getActiveAppSession();- if (isAppSessionBoundaryPending() || (ownerScope && (ownerScope.dataOwnerId !== active.dataOwnerId || ownerScope.ownerGeneration !== active.generation))) throwIpcError('INVALID_PARAMS', 'Provider owner changed');+ if (+ isAppSessionBoundaryPending() ||+ (ownerScope &&+ (ownerScope.dataOwnerId !== active.dataOwnerId ||+ ownerScope.ownerGeneration !== active.generation))+ )+ throwIpcError('INVALID_PARAMS', 'Provider owner changed');builtinApiKeyRemove(builtinApiKeyDeps, providerId);await retainProviderPresentationAfterAuthChange(builtinApiKeyPresentationId(providerId as string),@@ -5718,11 +5810,13 @@ const registerIpcHandlers = () => {ipcMain.handle('auth:initialize', async () => {try {let pendingCompletion: Promise<authManager.AuthState> | null = null;- const state = await authManager.initialize({- onColdStartPending: (completion) => {- pendingCompletion = completion;- },- });+ const state = await authManager+ .initialize({+ onColdStartPending: (completion) => {+ pendingCompletion = completion;+ },+ })+ .finally(() => authCredentialRecovery.request());await authManager.ensureStableOwnerPostCommitTasks('auth-initialize');if (!app.isPackaged) {recordDesktopDevAuthStartupResult(state, pendingCompletion, () =>@@ -5992,29 +6086,7 @@ const registerIpcHandlers = () => {//// 不进 device-link allowlist:updater 类 channel 按 allowlist 顶部注释属「永不放行」,// 且远程控制端不会代替用户点被控端的更新重启。- registerRelaunchBusyActivityIpc(() => ({- anySessionInTurn: () => anySessionInTurn(getMakerCore()),- listClaudeBackgroundSessions: () => listActiveClaudeBackgroundActivitySessions(),- anyGhostSessionBusy: () => getGhostSessionActivityTracker().anySessionBusy(),- // run_in_background 的 Bash 不调模型、也不折算 running,前两个来源都看不到它。- anyBackgroundBashRunning: () =>- getMakerCore()- .listActiveSessions()- .some((session) => session.listBackgroundTasks().length > 0),- // Cindy slot 的全部在途工作:异步(mode:'submit' 的图 / 视频)与同步代办各自独立记账,- // 都可能不伴随任何 turn 或 card-action,只查一半就漏一半。- anyCindySlotJobRunning: () => getGhostCindySlot().anyInflightWork(),- // Scope to this process: `pi-agent-home` is shared with a concurrent- // dev/packaged/`--passive` instance, and its running Subagents are not- // a reason to hold up *our* quit.- anyPiSubagentRunning: () =>- hasActivePiSubagentRunsSync(path.join(app.getPath('userData'), 'pi-agent-home'), {- hostPid: process.pid,- }),- // script 模式 / pre-run hook 阶段的 run 不创建 session,内存来源看不到它们。- anySchedulerRunRunning: () =>- readUpdateRelaunchScheduleBusy(getScheduleStorageIfInitialized()),- }));+ registerRelaunchBusyActivityIpc(readRelaunchActivitySources);// getMakerCore() 首次调用触发 Maker 构造,同时发起自定义 MCP 初始加载。// await 确保第一个会话的 mcpProviders 数组已填入已保存的自定义 MCP(P2 冷启动竞态修复)。getMakerCore();@@ -6395,7 +6467,8 @@ const registerIpcHandlers = () => {isGlobalVoiceInputOverlaySender(candidate.sender) &&candidate.senderFrame === candidate.sender.mainFrame &&isTrustedCindyRendererWindow(overlayWindow)- ) return;+ )+ return;assertTrustedAppRendererEvent(candidate);},openExternal: (url) => shell.openExternal(url),@@ -7431,9 +7504,7 @@ const registerIpcHandlers = () => {// Settings → Cindy Make: open Cindy's private managed-tool directory.// The path is derived in main so the renderer cannot choose an arbitrary folder.- ipcMain.handle(- 'app:open-cindy-make-tools-dir',- async (event): Promise<{ success: boolean }> => {+ ipcMain.handle('app:open-cindy-make-tools-dir', async (event): Promise<{ success: boolean }> => {assertTrustedAppRendererEvent(event);return openMakeToolsDirectory(app.getPath('userData'), {openPath: (directory) => shell.openPath(directory),@@ -8120,7 +8191,8 @@ const registerIpcHandlers = () => {>,};const ownerWindow = BrowserWindow.getFocusedWindow() ?? mainWindowRef;- const result = ownerWindow && !ownerWindow.isDestroyed()+ const result =+ ownerWindow && !ownerWindow.isDestroyed()? await dialog.showOpenDialog(ownerWindow, options): await dialog.showOpenDialog(options);return result.canceled ? null : (result.filePaths[0] ?? null);@@ -8148,7 +8220,8 @@ const registerIpcHandlers = () => {noLink: true,};const ownerWindow = BrowserWindow.getFocusedWindow() ?? mainWindowRef;- const result = ownerWindow && !ownerWindow.isDestroyed()+ const result =+ ownerWindow && !ownerWindow.isDestroyed()? await dialog.showMessageBox(ownerWindow, options): await dialog.showMessageBox(options);return result.response === 0;@@ -8168,7 +8241,8 @@ const registerIpcHandlers = () => {noLink: true,};const ownerWindow = BrowserWindow.getFocusedWindow() ?? mainWindowRef;- const result = ownerWindow && !ownerWindow.isDestroyed()+ const result =+ ownerWindow && !ownerWindow.isDestroyed()? await dialog.showMessageBox(ownerWindow, options): await dialog.showMessageBox(options);return result.response === 0;@@ -9308,6 +9382,7 @@ app.on('ready', async () => {// ── System resume: refresh tokens after sleep/hibernate ──powerMonitor.on('resume', () => {+ authCredentialRecovery.request();authManager.handleResume();handleProviderModelSystemResume();syncPluginMarketForActiveOwner(30_000);@@ -9315,6 +9390,18 @@ app.on('ready', async () => {handleDeviceLinkSystemResume();});powerMonitor.on('unlock-screen', handleProviderModelScreenUnlock);+ powerMonitor.on('lock-screen', authCredentialRecovery.onScreenLock);+ powerMonitor.on('unlock-screen', authCredentialRecovery.onScreenUnlock);+ onQuit(+ 'auth-credential-recovery',+ () => {+ authCredentialRecovery.dispose();+ powerMonitor.removeListener('lock-screen', authCredentialRecovery.onScreenLock);+ powerMonitor.removeListener('unlock-screen', authCredentialRecovery.onScreenUnlock);+ },+ 'sync',+ );+ authCredentialRecovery.request();// Memory diagnostics — dev only, log per-process memory every 30sif (!app.isPackaged) {@@ -9519,9 +9606,9 @@ onQuit(});if (!stopped) {piSubagentLog.error(- 'PI Subagent runners survived stop and identity-verified kill on quit — '- + 'runners this app could not confirm as stopped are still running with their '- + 'inherited credentials',+ 'PI Subagent runners survived stop and identity-verified kill on quit — ' ++ 'runners this app could not confirm as stopped are still running with their ' ++ 'inherited credentials',);}}@@ -9543,8 +9630,8 @@ onQuit(// failure means the parent is *not* confirmed down and the fence stays up.if (piSessionFailures > 0) {piSubagentLog.error(- `${piSessionFailures} PI session(s) failed to detach during quit — holding the `- + 'launch fence, since a surviving parent could still start a durable runner',+ `${piSessionFailures} PI session(s) failed to detach during quit — holding the ` ++ 'launch fence, since a surviving parent could still start a durable runner',);return;}@@ -9619,8 +9706,8 @@ onQuit(});if (!stopped) {piSubagentLog.error(- 'PI Subagent runners appeared after the first quit sweep and could not be '- + 'confirmed stopped — they are still running with their inherited credentials',+ 'PI Subagent runners appeared after the first quit sweep and could not be ' ++ 'confirmed stopped — they are still running with their inherited credentials',);}// No fence and no proof the parent is down: this pass is not conclusive,@@ -9669,9 +9756,9 @@ onQuit(// could still launch — so the fence stays up until the process exits,// and the next instance's stale sweep removes the file.piSubagentLog.error(- 'parent shutdown was not confirmed complete on quit — holding the PI Subagent '- + 'launch fence until this process exits so a still-live parent cannot start '- + 'a durable runner nothing is left to reclaim',+ 'parent shutdown was not confirmed complete on quit — holding the PI Subagent ' ++ 'launch fence until this process exits so a still-live parent cannot start ' ++ 'a durable runner nothing is left to reclaim',);} else {// Neither guarantee is available: the fence could not be raised on@@ -9681,9 +9768,9 @@ onQuit(// thing narrowing the window; state the exposure instead of implying it// is closed.piSubagentLog.error(- 'quit ended with no PI Subagent launch fence and no proof the parent is down — '- + 'a surviving parent could still publish a durable runner after the last scan, '- + 'and it would keep running with the credentials it inherited',+ 'quit ended with no PI Subagent launch fence and no proof the parent is down — ' ++ 'a surviving parent could still publish a durable runner after the last scan, ' ++ 'and it would keep running with the credentials it inherited',);}}@@ -9991,8 +10078,10 @@ let lastWorktreeMaintenanceDb: ReturnType<typeof tryGetDbClient> = null;/** Worktree maintenance needs both storage and runtime-close services. */function startReadyWorktreeMaintenance(): void {startWorktreeRecycleMaintenance({- isReady: () => worktreeRuntimeCloseReady && getMakerIfReady() !== null && tryGetDbClient() !== null,- recycleCurrentSession: (sessionId, status) => recycleSessionWorktreeForStatusChange(sessionId, status),+ isReady: () =>+ worktreeRuntimeCloseReady && getMakerIfReady() !== null && tryGetDbClient() !== null,+ recycleCurrentSession: (sessionId, status) =>+ recycleSessionWorktreeForStatusChange(sessionId, status),onAttemptComplete: auditRegisteredWorktrees,});const db = tryGetDbClient();diff --git a/apps/desktop/src/main/maker-host/__tests__/claudeLocalLoginCancellation.test.ts b/apps/desktop/src/main/maker-host/__tests__/claudeLocalLoginCancellation.test.tsindex 8b6a79ccb0..e85be8e8fc 100644--- a/apps/desktop/src/main/maker-host/__tests__/claudeLocalLoginCancellation.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/claudeLocalLoginCancellation.test.ts@@ -6,8 +6,9 @@ vi.mock('electron', () => ({ shell: { openExternal: vi.fn() }, app: { getPath: (import { beginClaudeLocalLogin, cancelClaudeOAuthLogin } from '../claude-oauth-login.js';const source = readFileSync(new URL('../../bootstrap-electron.ts', import.meta.url), 'utf8');-const start = source.indexOf(' ipcMain.handle(MAKER_IPC_INVOKE.CLAUDE_OAUTH_LOGIN,');-const end = source.indexOf(' ipcMain.handle(MAKER_IPC_INVOKE.CLAUDE_OAUTH_LOGOUT,', start);+const start = source.search(/ipcMain\.handle\(\s*MAKER_IPC_INVOKE\.CLAUDE_OAUTH_LOGIN,/);+const end = source.search(/ipcMain\.handle\(\s*MAKER_IPC_INVOKE\.CLAUDE_OAUTH_LOGOUT,/);+if (start < 0 || end <= start) throw new Error('Claude login handler boundaries not found');const compiled = transpileModule(source.slice(start, end), { compilerOptions: { target: ScriptTarget.ES2022 } }).outputText;it.each(['scan', 'proxy'] as const)('does not bind a cancelled local login while waiting for %s', async (stage) => {diff --git a/apps/desktop/src/renderer/components/login/LoginPage.tsx b/apps/desktop/src/renderer/components/login/LoginPage.tsxindex a1045168f4..7df39290e4 100644--- a/apps/desktop/src/renderer/components/login/LoginPage.tsx+++ b/apps/desktop/src/renderer/components/login/LoginPage.tsx@@ -354,7 +354,8 @@ export function LoginPage({}, [reportLoginPanelMounted, reportLoginPanelUnmounted]);// 「跳过登录」常驻入口在面板内(identifier 视图 SKIP_ENTRY 文字链);footer 仅保留// error 步的逃生入口——登录服务不可用时用户仍能进入本地模式(既有产品保证)。- const showLocalModeFooter = !isAddAccount && loginState?.step === 'error';+ const showLocalModeFooter =+ !isAddAccount && loginState?.step === 'error' && loginState.code !== 'CREDENTIAL_STORE_UNAVAILABLE';// 面板底部预留恒取全流程最大值(footer 124;协议行 48 被其覆盖):step 切换时// 面板/品牌层零跳位(规则 7,codex 审查 P1)。browser-redirect/completed 维持 0,// 与迁移前 main 口径一致(该两步由品牌 overlay/跳转态接管)。@@ -1293,7 +1294,12 @@ export function LoginPage({label={t('login.back')}onClick={reset}/>- <LoginTitleBlock title={t('login.unavailable')} subtitle={t('login.errors.fallback')} />+ <LoginTitleBlock+ title={t(loginState.code === 'CREDENTIAL_STORE_UNAVAILABLE'+ ? 'credentialStore.dialog.title' : 'login.unavailable')}+ subtitle={t(loginState.code === 'CREDENTIAL_STORE_UNAVAILABLE'+ ? 'login.savedLoginPreserved' : 'login.errors.fallback')}+ /><LoginPrimaryButtondisabled={isLoading}loading={isLoading}diff --git a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.errorCopy.harness.test.tsx b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.errorCopy.harness.test.tsxindex 54aa81707d..c556f0595f 100644--- a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.errorCopy.harness.test.tsx+++ b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.errorCopy.harness.test.tsx@@ -1,6 +1,6 @@// @vitest-environment jsdom-import { cleanup, render, screen } from '@testing-library/react';+import { cleanup, fireEvent, render, screen } from '@testing-library/react';import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';import i18next from 'i18next';import { initReactI18next } from 'react-i18next';@@ -126,6 +126,47 @@ function mountWithError(code: string) {}describe('error-copy 桌面 19 码表 + 兜底(现网 i18n verbatim,#D91F37 族)', () => {+ it('preserves the local-mode guard across remounts with no hook-local error', () => {+ loginHook.value.errorCode = null;+ loginHook.value.loginState = {+ step: 'error',+ code: 'CREDENTIAL_STORE_UNAVAILABLE',+ recoverTo: 'identifier',+ };+ const first = render(<LoginPage />);+ expect(screen.queryByTestId('login-local-mode')).toBeNull();+ first.unmount();+ const second = render(<LoginPage />);+ expect(screen.queryByTestId('login-local-mode')).toBeNull();+ second.unmount();+ loginHook.value.loginState = { step: 'error', code: 'NETWORK_ERROR', recoverTo: 'identifier' };+ render(<LoginPage />);+ expect(screen.getByTestId('login-local-mode')).toBeTruthy();+ });+ it.each(['BROWSER_OPEN_FAILED', 'BROWSER_OPEN_TIMEOUT'])(+ 'shows actionable local error %s',+ (code) => {+ mountWithError(code);+ expect(screen.getByTestId('login-error-text').textContent).toBe(zhErrors[code]);+ expect(zhErrors[code]).not.toBe(zhErrors.fallback);+ },+ );+ it('explains preserved sign-in and offers recovery when the saved credentials cannot be read', () => {+ loginHook.value.loginState = {+ step: 'error',+ code: 'CREDENTIAL_STORE_UNAVAILABLE',+ recoverTo: 'identifier',+ };+ render(<LoginPage />);+ expect(screen.getByText(zhCN.login.savedLoginPreserved)).toBeTruthy();+ expect(screen.getByText(zhCN.credentialStore.dialog.title)).toBeTruthy();+ expect(screen.getByTestId('login-error-text').textContent).toBe(+ zhErrors.CREDENTIAL_STORE_UNAVAILABLE,+ );+ fireEvent.click(screen.getByTestId('login-error-retry'));+ expect(loginHook.value.dispatch).toHaveBeenCalledWith({ type: 'reset' });+ });+for (const code of NAMED_CODES) {it(`error-copy ${code} 文案 verbatim`, async () => {expect(zhErrors[code], `zh-CN 缺 login.errors.${code}`).toBeTruthy();diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 6f9974c875..cc01e6b23b 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -5870,6 +5870,7 @@"login": {"title": "Welcome to Cindy","subtitle": "Choose a secure way to sign in",+ "savedLoginPreserved": "Your saved sign-in is still on this device","phonePlaceholder": "Enter your phone number","emailPlaceholder": "Enter your email","invalidEmail": "Please enter a valid email address",@@ -5969,6 +5970,9 @@"fallback": "Sign-in failed. Please try again.","AUTH_SERVICE_UNAVAILABLE": "The sign-in service is temporarily unavailable.","AUTH_REQUEST_FAILED": "The sign-in request failed. Please try again.",+ "CREDENTIAL_STORE_UNAVAILABLE": "Quit Cindy completely, then reopen it to restore sign-in.",+ "BROWSER_OPEN_FAILED": "Could not open the browser. Please try again.",+ "BROWSER_OPEN_TIMEOUT": "The browser did not start in time. Please try again.","NETWORK_ERROR": "Could not connect. Check your network and try again.","REQUEST_TIMEOUT": "The request timed out. Please try again.","INVALID_PARAMS": "Check the value you entered.",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 6310d96fb0..62e4a0f2a0 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -5868,6 +5868,7 @@"login": {"title": "Cindy へようこそ","subtitle": "安全なログイン方法を選択してください",+ "savedLoginPreserved": "保存済みのログイン情報はこの端末に残っています","phonePlaceholder": "電話番号を入力","emailPlaceholder": "メールアドレスを入力","invalidEmail": "正しいメールアドレスを入力してください",@@ -5967,6 +5968,9 @@"fallback": "ログインに失敗しました。再試行してください。","AUTH_SERVICE_UNAVAILABLE": "ログインサービスは一時的に利用できません。","AUTH_REQUEST_FAILED": "ログインリクエストに失敗しました。",+ "CREDENTIAL_STORE_UNAVAILABLE": "Cindy を完全に終了して開き直すと、ログインを復元できます。",+ "BROWSER_OPEN_FAILED": "ブラウザを開けませんでした。再試行してください。",+ "BROWSER_OPEN_TIMEOUT": "ブラウザの起動がタイムアウトしました。再試行してください。","NETWORK_ERROR": "ネットワーク接続を確認してください。","REQUEST_TIMEOUT": "リクエストがタイムアウトしました。","INVALID_PARAMS": "入力内容を確認してください。",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 684bb83aca..64ca6830c9 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -5868,6 +5868,7 @@"login": {"title": "Cindy에 오신 것을 환영합니다","subtitle": "안전한 로그인 방법을 선택하세요",+ "savedLoginPreserved": "저장된 로그인 정보는 이 기기에 남아 있습니다","phonePlaceholder": "휴대폰 번호 입력","emailPlaceholder": "이메일 입력","invalidEmail": "올바른 이메일 주소를 입력하세요",@@ -5967,6 +5968,9 @@"fallback": "로그인에 실패했습니다. 다시 시도하세요.","AUTH_SERVICE_UNAVAILABLE": "로그인 서비스를 일시적으로 사용할 수 없습니다.","AUTH_REQUEST_FAILED": "로그인 요청에 실패했습니다.",+ "CREDENTIAL_STORE_UNAVAILABLE": "Cindy를 완전히 종료한 뒤 다시 열어 로그인을 복구하세요.",+ "BROWSER_OPEN_FAILED": "브라우저를 열 수 없습니다. 다시 시도하세요.",+ "BROWSER_OPEN_TIMEOUT": "브라우저 시작 시간이 초과되었습니다. 다시 시도하세요.","NETWORK_ERROR": "네트워크 연결을 확인하세요.","REQUEST_TIMEOUT": "요청 시간이 초과되었습니다.","INVALID_PARAMS": "입력한 값을 확인하세요.",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 49224c5ebc..4608738f30 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -5868,6 +5868,7 @@"login": {"title": "欢迎使用 Cindy","subtitle": "选择一种方式安全登录",+ "savedLoginPreserved": "已保存的登录信息仍在本机","phonePlaceholder": "请输入手机号","emailPlaceholder": "请输入邮箱","invalidEmail": "请输入正确邮箱",@@ -5967,6 +5968,9 @@"fallback": "登录失败,请稍后重试","AUTH_SERVICE_UNAVAILABLE": "登录服务暂不可用","AUTH_REQUEST_FAILED": "登录请求失败,请重试",+ "CREDENTIAL_STORE_UNAVAILABLE": "请完全退出 Cindy 后重新打开,以恢复登录",+ "BROWSER_OPEN_FAILED": "无法打开浏览器,请重试",+ "BROWSER_OPEN_TIMEOUT": "浏览器未及时启动,请重试","NETWORK_ERROR": "网络连接失败,请检查网络","REQUEST_TIMEOUT": "请求超时,请重试","INVALID_PARAMS": "输入格式不正确",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 09833050d3..c153f9138b 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -5868,6 +5868,7 @@"login": {"title": "歡迎使用 Cindy","subtitle": "選擇一種方式安全登入",+ "savedLoginPreserved": "已儲存的登入資訊仍在本機","phonePlaceholder": "請輸入手機號碼","emailPlaceholder": "請輸入電子郵件","invalidEmail": "請輸入正確的電子郵件地址",@@ -5967,6 +5968,9 @@"fallback": "登入失敗,請稍後重試","AUTH_SERVICE_UNAVAILABLE": "登入服務暫不可用","AUTH_REQUEST_FAILED": "登入請求失敗,請重試",+ "CREDENTIAL_STORE_UNAVAILABLE": "請完全退出 Cindy 後重新開啟,以恢復登入",+ "BROWSER_OPEN_FAILED": "無法開啟瀏覽器,請重試",+ "BROWSER_OPEN_TIMEOUT": "瀏覽器未及時啟動,請重試","NETWORK_ERROR": "網路連線失敗,請檢查網路","REQUEST_TIMEOUT": "請求超時,請重試","INVALID_PARAMS": "輸入格式不正確",