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(auth): 保留登录并持续随机退避恢复会话

Cindyd0499250d6c5
diff --git a/apps/desktop/src/main/__tests__/authColdStartRecovery.test.ts b/apps/desktop/src/main/__tests__/authColdStartRecovery.test.ts
new file mode 100644
index 0000000000..4393b01c8d
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/authColdStartRecovery.test.ts
@@ -0,0 +1,314 @@
+import { readFileSync } from 'node:fs';
+import ts from 'typescript';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { AuthRefreshBackoff } from '../authRefreshBackoff';
+import { AuthApiError, retryAfterDeadline } from '@cindy/auth-client';
+import { runRefreshWithReplacementRetry } from '../authRefreshFailure';
+import {
+ awaitWithStartupTimeout,
+ resolveColdStartTimeoutRecovery,
+ ColdStartAuthFallbackRegistry,
+ commitColdStartRefreshIfCurrent,
+} from '../authStartupGate';
+import { loginPreparingErrorState } from '../../shared/authIpc';
+
+// Test value (unit): execute the production cold-start and login-action entrypoints with
+// in-memory credentials/network. On 2026-10-29 three DNS failures stranded a valid login;
+// the pure startup-gate tests did not exercise ongoing retries or the reset action.
+// Minimal input: a saved session, repeated status=0 responses, then recovery/manual action.
+// Compile once; never load Electron, a real credential store, or sleep in wall-clock time.
+const source = ts.createSourceFile(
+ 'authManager.ts',
+ readFileSync(new URL('../authManager.ts', import.meta.url), 'utf8'),
+ ts.ScriptTarget.Latest,
+ true,
+);
+const names = new Set([
+ 'apiFetch',
+ 'initialize',
+ 'refresh',
+ 'runColdStartRefreshFlow',
+ 'runAuthRefreshWithReplacementRetry',
+ 'waitForColdStartRetry',
+ 'stopColdStartRecovery',
+ 'runLoginAction',
+]);
+const compiled = ts.transpileModule(
+ `
+let authStateEpoch = 0, loginFlowEpoch = 0, accessToken = null, currentUser = null;
+let activeAuthRealm = 'global', pendingAuthRealm = null, loginFlowState = null;
+let coldStartAuthInFlight = null, coldStartRetryWait = null, refreshTimer = null;
+let coldStartRecoveryStopped = false;
+let lastAcceptedRefreshToken = null, persistedRefreshTokenNeedsIdentityCheck = false;
+let foreignDeviceLocalSignOut = false;
+const passiveLocalSignOut = false, settledLoginCommitCount = 0;
+const API_FETCH_TIMEOUT_MS = 15000;
+const AUTH_REGION = 'global', RUNTIME_REFRESH_RETRY_MS = 60000;
+const COLD_START_AUTH_GATE_TIMEOUT_MS = 20000;
+const LEGACY_REFRESH_TOKEN_KEY = 'legacy', LEGACY_ACCOUNT_REFRESH_TOKEN_KEY = 'legacy-account';
+const REFRESH_TOKEN_REPLACEMENT_RETRY_LIMIT = 2;
+const COLD_START_REFRESH_TOKEN_REPLACEMENT_RECHECK_DELAYS_MS = [100, 250];
+const RUNTIME_REFRESH_TOKEN_REPLACEMENT_RECHECK_DELAYS_MS = [250, 1000];
+const credentialStoreHealth = { unavailable: false, noteRecovered() {} };
+const coldStartTimeoutFallbacks = new ColdStartAuthFallbackRegistry();
+const snapshotAuthState = () => ({ isAuthenticated: !!accessToken, user: currentUser });
+const snapshotLoggedOutAuthState = snapshotAuthState;
+const readPersistedAuthSession = () => saved.session;
+const readStoredRefreshTokenCandidates = () => [saved.session?.refreshToken];
+const hasPotentiallyPersistedAuthCredentials = () => !!saved.session;
+const assertLoginFlowCurrent = (epoch) => { if (epoch !== loginFlowEpoch) throw new Error('superseded'); };
+const finishColdStartSignedOut = async () => snapshotAuthState();
+const recoverAccountFreeOwnerAtStartup = async () => {
+ coldStartTimeoutFallbacks.record(authStateEpoch, authStateEpoch + 1);
+ authStateEpoch++; loginFlowEpoch++;
+};
+const reconcileDesktopActiveAuthSession = async () => saved.session;
+${source.statements
+ .filter((node) => ts.isFunctionDeclaration(node) && names.has(node.name?.text ?? ''))
+ .map((node) => node.getText(source).replace(/^export /, ''))
+ .join('\n')}
+return {
+ fetch: apiFetch, start: initialize, runtimeRefresh: refresh, reset: () => runLoginAction({ type: 'reset' }),
+ manualLogin: () => runLoginAction({ type: 'discover', identifier: '[email protected]' }),
+ state: snapshotAuthState,
+ fallback: () => { coldStartTimeoutFallbacks.record(authStateEpoch, authStateEpoch + 1); authStateEpoch++; loginFlowEpoch++; },
+ changeOwner: () => { authStateEpoch++; accessToken = 'test-new-login'; currentUser = { id: 'other' }; },
+};`,
+ { compilerOptions: { target: ts.ScriptTarget.ES2022 } },
+).outputText;
+
+function setup(random = 0) {
+ const saved = { session: { version: 1, realm: 'global', refreshToken: 'test-refresh' } };
+ const membership = { id: 'original', kind: 'personal' };
+ const ok = {
+ ok: true,
+ status: 200,
+ data: { accessToken: 'test-access', refreshToken: 'test-rotated', membership },
+ };
+ const request = vi
+ .fn<(...args: unknown[]) => Promise<any>>()
+ .mockResolvedValue({ ok: false, status: 0, data: null });
+ const loadProviders = vi.fn(async () => ({ step: 'identifier' }));
+ const commit = vi.fn(async (data) => {
+ saved.session.refreshToken = data.refreshToken;
+ return 'active';
+ });
+ const clear = vi.fn(async () => {
+ saved.session.refreshToken = '';
+ });
+ const deps = {
+ saved,
+ AuthRefreshBackoff: class extends AuthRefreshBackoff {
+ constructor() {
+ super(
+ () => Date.now(),
+ () => random,
+ );
+ }
+ },
+ AuthApiError,
+ retryAfterDeadline,
+ authServerUrl: () => 'https://auth.example.invalid',
+ net: { fetch: vi.fn() },
+ requestErrorMessage: String,
+ ColdStartAuthFallbackRegistry,
+ commitColdStartRefreshIfCurrent,
+ awaitWithStartupTimeout,
+ resolveColdStartTimeoutRecovery,
+ readReloginFlag: () => null,
+ removeSafe: vi.fn(),
+ isOwnerChangeShellPending: () => false,
+ ownerChangeShellGate: { isPending: () => false },
+ sealedLoginFlowCommitDepths: new Set(),
+ runRefreshWithReplacementRetry,
+ loginPreparingErrorState,
+ requestAuthRefresh: request,
+ loadClientEndpointsForRealm: vi.fn(async () => {}),
+ loadLoginProviders: loadProviders,
+ createAuthClient: () => ({ discover: vi.fn() }),
+ log: { warn: vi.fn(), info: vi.fn(), error: vi.fn() },
+ readActiveVaultRefreshCandidate: () => null,
+ clearConfirmedDeadRefreshTokens: clear,
+ resetActiveAuthRealmToBuild: vi.fn(),
+ isPassiveSharedUserDataInstance: () => false,
+ commitDesktopRefreshCredentials: commit,
+ canRestoreAuthSessionForMembership: () => true,
+ getActiveAppSession: () => ({ mode: 'signed-out', dataOwnerId: null }),
+ withCloudOwnerCommit: async (options: any) => {
+ await options.prepareTransition();
+ await options.prepareCommit?.();
+ options.commit();
+ },
+ accountSwitchTeardown: vi.fn(async () => {}),
+ claimLegacyNamespaceForVerifiedUser: vi.fn(async () => {}),
+ mapMembershipToAuthUser: (value: unknown) => value,
+ commitCloudAppSession: vi.fn(),
+ clearReplacementIntegrationReloadTimers: vi.fn(),
+ migrateLocalProviderBindingsAfterCloudCommit: vi.fn(async () => {}),
+ scheduleCanaryFlagSync: vi.fn(),
+ scheduleXdOrgBetaDefault: vi.fn(),
+ scheduleRefresh: vi.fn(),
+ getProviderSecretStore: () => ({ reconcileOwner: vi.fn() }),
+ notifyRenderer: vi.fn(),
+ notifyAuthListeners: vi.fn(),
+ };
+ const main = new Function(...Object.keys(deps), compiled)(...Object.values(deps));
+ return { ...main, saved, request, ok, commit, clear, loadProviders, deps };
+}
+
+describe('saved login recovery after startup network failure', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+ afterEach(() => {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ });
+
+ it('keeps slowly retrying beyond three failures and restores the original account after the startup fallback', async () => {
+ const h = setup();
+ const pending = h.start();
+ await vi.advanceTimersByTimeAsync(20_000);
+ await expect(pending).resolves.toMatchObject({ isAuthenticated: false });
+ await vi.advanceTimersByTimeAsync(400_000);
+ expect(h.request.mock.calls.length).toBeGreaterThan(3);
+ expect(h.clear).not.toHaveBeenCalled();
+ expect(h.saved.session.refreshToken).toBe('test-refresh');
+ h.request.mockResolvedValue(h.ok);
+ await vi.advanceTimersByTimeAsync(300_000);
+ expect(h.state()).toMatchObject({ isAuthenticated: true, user: { id: 'original' } });
+ expect(h.saved.session.refreshToken).toBe('test-rotated');
+ expect(h.deps.notifyAuthListeners).toHaveBeenCalled();
+ });
+
+ it('retry restores the saved login instead of fetching fresh login providers', async () => {
+ const h = setup();
+ h.request.mockResolvedValue(h.ok);
+ await expect(h.reset()).resolves.toMatchObject({ success: true, state: { step: 'completed' } });
+ expect(h.loadProviders).not.toHaveBeenCalled();
+ expect(h.saved.session.refreshToken).toBe('test-rotated');
+ });
+
+ it('manual login stops the waiting recovery without clearing the saved credential', async () => {
+ const h = setup();
+ const pending = h.start();
+ await vi.advanceTimersByTimeAsync(20_000);
+ await h.manualLogin();
+ const attempts = h.request.mock.calls.length;
+ await vi.advanceTimersByTimeAsync(180_000);
+ await pending;
+ await expect(h.start()).resolves.toMatchObject({ isAuthenticated: false });
+ expect(h.request).toHaveBeenCalledTimes(attempts);
+ expect(h.saved.session.refreshToken).toBe('test-refresh');
+ });
+
+ it('retry wakes a network backoff and reuses the saved session immediately', async () => {
+ const h = setup();
+ void h.start();
+ await vi.advanceTimersByTimeAsync(20_000);
+ expect(h.request).toHaveBeenCalledTimes(1);
+ h.request.mockResolvedValue(h.ok);
+ await expect(h.reset()).resolves.toMatchObject({ success: true, state: { step: 'completed' } });
+ expect(h.request).toHaveBeenCalledTimes(2);
+ expect(h.loadProviders).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(120_000);
+ expect(h.request).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not publish or persist an old successful response after an owner change', async () => {
+ const h = setup();
+ let resolve!: (value: unknown) => void;
+ h.request.mockImplementation(
+ () =>
+ new Promise((r) => {
+ resolve = r;
+ }),
+ );
+ const pending = h.start();
+ await vi.advanceTimersByTimeAsync(0);
+ h.changeOwner();
+ resolve(h.ok);
+ await expect(pending).resolves.toMatchObject({ user: { id: 'other' } });
+ expect(h.commit).not.toHaveBeenCalled();
+ });
+
+ it('coalesces multiple retry clicks and runtime refresh behind the pending request', async () => {
+ const h = setup();
+ let resolve!: (value: unknown) => void;
+ h.request.mockImplementation(
+ () =>
+ new Promise((r) => {
+ resolve = r;
+ }),
+ );
+ void h.start();
+ await vi.advanceTimersByTimeAsync(20_000);
+ const first = h.reset();
+ const second = h.reset();
+ await vi.advanceTimersByTimeAsync(0);
+ await expect(h.runtimeRefresh()).resolves.toBe(false);
+ expect(h.request).toHaveBeenCalledTimes(1);
+ resolve(h.ok);
+ await expect(first).resolves.toMatchObject({ success: true });
+ await expect(second).resolves.toMatchObject({ success: true });
+ expect(h.loadProviders).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { status: 429, serverWait: undefined },
+ { status: 429, serverWait: 120_000 },
+ { status: 503, serverWait: 120_000 },
+ ])(
+ 'keeps server cooldown and jitter across retry clicks ($status, $serverWait)',
+ async ({ status, serverWait }) => {
+ const h = setup(0.5);
+ // Exercise HTTP header parsing too: the old path dropped Retry-After on
+ // 503, so injecting retryAt directly would miss the premature retry bug.
+ h.deps.net.fetch.mockResolvedValue(
+ new Response('{}', {
+ status,
+ headers: serverWait === undefined ? {} : { 'Retry-After': String(serverWait / 1000) },
+ }),
+ );
+ h.request.mockImplementation(() => h.fetch('/api/auth/refresh', { timeoutMs: 0 }));
+ void h.start();
+ await vi.advanceTimersByTimeAsync(20_000);
+ const retry = h.reset();
+ await vi.advanceTimersByTimeAsync(20_000);
+ await expect(retry).resolves.toMatchObject({
+ success: false,
+ code: 'AUTH_SERVICE_UNAVAILABLE',
+ });
+ expect(h.request).toHaveBeenCalledTimes(1);
+ h.request.mockResolvedValue(h.ok);
+ await vi.advanceTimersByTimeAsync((serverWait ?? 60_000) + 30_000 - 40_001);
+ expect(h.request).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(h.state()).toMatchObject({ isAuthenticated: true });
+ },
+ );
+
+ it('retries endpoint discovery without sending the credential to a fallback realm', async () => {
+ const h = setup();
+ h.deps.loadClientEndpointsForRealm.mockRejectedValue(new Error('offline'));
+ void h.start();
+ await vi.advanceTimersByTimeAsync(120_000);
+ expect(h.request).not.toHaveBeenCalled();
+ h.deps.loadClientEndpointsForRealm.mockResolvedValue();
+ h.request.mockResolvedValue(h.ok);
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(h.state()).toMatchObject({ isAuthenticated: true });
+ });
+
+ it.each(['REFRESH_TOKEN_EXPIRED', 'DEVICE_MISMATCH'])(
+ 'stops after terminal response %s',
+ async (code) => {
+ const h = setup();
+ h.request.mockResolvedValue({ ok: false, status: 401, data: { error: { code } } });
+ await expect(h.start()).resolves.toMatchObject({ isAuthenticated: false });
+ await vi.advanceTimersByTimeAsync(300_000);
+ expect(h.request).toHaveBeenCalledTimes(1);
+ expect(h.clear).toHaveBeenCalledTimes(code === 'REFRESH_TOKEN_EXPIRED' ? 1 : 0);
+ },
+ );
+});
diff --git a/apps/desktop/src/main/__tests__/authCredentialLoginRecovery.test.ts b/apps/desktop/src/main/__tests__/authCredentialLoginRecovery.test.ts
index 34b5768fe0..fadb657931 100644
--- a/apps/desktop/src/main/__tests__/authCredentialLoginRecovery.test.ts
+++ b/apps/desktop/src/main/__tests__/authCredentialLoginRecovery.test.ts
@@ -48,6 +48,9 @@ function setup({
powerMonitor: { getSystemIdleState: () => 'active' },
code,
credentialStoreHealth: { unavailable: false },
+ stopColdStartRecovery: () => {},
+ coldStartAuthInFlight: null,
+ readPersistedAuthSession: () => null,
accessToken: authenticated ? 'test-only-token' : null,
getActiveAppSession: () => ({ mode: authenticated ? 'signed-in' : 'signed-out' }),
isPassiveSharedUserDataInstance: () => passive,
diff --git a/apps/desktop/src/main/__tests__/authLoginBack.test.ts b/apps/desktop/src/main/__tests__/authLoginBack.test.ts
index d8c14a0e0b..6e11b5fd34 100644
--- a/apps/desktop/src/main/__tests__/authLoginBack.test.ts
+++ b/apps/desktop/src/main/__tests__/authLoginBack.test.ts
@@ -44,6 +44,9 @@ function setup({ cached = false, sealed = false, credentialStoreUnavailable = fa
browserAuthorizationSlot: { cancelActive },
isLoginFlowCommitSealed: () => sealed,
isOwnerChangeShellPending: () => false,
+ stopColdStartRecovery: () => {},
+ coldStartAuthInFlight: null,
+ readPersistedAuthSession: () => null,
credentialStoreUnavailable,
log: { warn: vi.fn() },
cachedProviders: cached ? providers : null,
@@ -78,18 +81,21 @@ function setup({ cached = false, sealed = false, credentialStoreUnavailable = fa
}
describe('login Back without an auth-server round trip', () => {
- it.each([false, true])('preserves credential recovery and private progress (cached=%s)', async (cached) => {
- const main = setup({ cached, credentialStoreUnavailable: true });
- expect(await main.dispatch({ type: 'back' })).toEqual({
- success: false,
- code: 'CREDENTIAL_STORE_UNAVAILABLE',
- state: { step: 'error', code: 'CREDENTIAL_STORE_UNAVAILABLE', recoverTo: 'identifier' },
- });
- expect(main.snapshot().ticket).toBe('old-ticket');
- expect(main.snapshot().epoch).toBe(1);
- expect(main.cancelActive).not.toHaveBeenCalled();
- expect(main.getProviders).not.toHaveBeenCalled();
- });
+ it.each([false, true])(
+ 'preserves credential recovery and private progress (cached=%s)',
+ async (cached) => {
+ const main = setup({ cached, credentialStoreUnavailable: true });
+ expect(await main.dispatch({ type: 'back' })).toEqual({
+ success: false,
+ code: 'CREDENTIAL_STORE_UNAVAILABLE',
+ state: { step: 'error', code: 'CREDENTIAL_STORE_UNAVAILABLE', recoverTo: 'identifier' },
+ });
+ expect(main.snapshot().ticket).toBe('old-ticket');
+ expect(main.snapshot().epoch).toBe(1);
+ expect(main.cancelActive).not.toHaveBeenCalled();
+ expect(main.getProviders).not.toHaveBeenCalled();
+ },
+ );
it.each([false, true])(
'returns locally and clears private progress (cached=%s)',
diff --git a/apps/desktop/src/main/__tests__/authLoginFlowReset.contract.test.ts b/apps/desktop/src/main/__tests__/authLoginFlowReset.contract.test.ts
index 76b9d68b8d..5924c052dc 100644
--- a/apps/desktop/src/main/__tests__/authLoginFlowReset.contract.test.ts
+++ b/apps/desktop/src/main/__tests__/authLoginFlowReset.contract.test.ts
@@ -5,10 +5,7 @@ import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { describe, expect, it } from 'vitest';
-import {
- ColdStartAuthFallbackRegistry,
- commitColdStartRefreshIfCurrent,
-} from '../authStartupGate';
+import { ColdStartAuthFallbackRegistry, commitColdStartRefreshIfCurrent } from '../authStartupGate';
/** Regression guard for login progress that is intentionally owned by Electron main. */
describe('auth login-flow reset', () => {
@@ -52,26 +49,43 @@ describe('auth login-flow reset', () => {
const start = source.indexOf('async function finishFreshLogin(');
const finish = source.slice(start, source.indexOf('async function runLoginAction(', start));
expect(finish).toContain('discoverPersonalLoginOrganization(outcome.membership');
- expect(finish.indexOf('assertLoginFlowCurrent(expectedLoginFlowEpoch)')).toBeGreaterThan(finish.indexOf('await discoverPersonalLoginOrganization'));
+ expect(finish.indexOf('assertLoginFlowCurrent(expectedLoginFlowEpoch)')).toBeGreaterThan(
+ finish.indexOf('await discoverPersonalLoginOrganization'),
+ );
expect(finish).toContain('pendingPersonalLogin = { outcome, realm: personalRealm }');
expect(finish).toContain('personalLoginAvailable: true');
expect(finish).not.toContain('pendingAuthRealm = discovery.region');
expect(finish).toContain('return completeLogin(outcome, expectedLoginFlowEpoch)');
const lookupStart = source.indexOf('async function lookupOrganizationRealm(');
- const lookup = source.slice(lookupStart, source.indexOf('async function completeLogin(', lookupStart));
+ const lookup = source.slice(
+ lookupStart,
+ source.indexOf('async function completeLogin(', lookupStart),
+ );
expect(lookup).not.toContain('pendingAuthRealm =');
const continueStart = source.indexOf("if (action.type === 'cancel-sso-realm')");
- const continueBody = source.slice(continueStart, source.indexOf('if (!providerConfig)', continueStart));
+ const continueBody = source.slice(
+ continueStart,
+ source.indexOf('if (!providerConfig)', continueStart),
+ );
expect(continueBody).toContain('pendingAuthRealm = personal.realm');
expect(continueBody).toContain('await completeLogin(personal.outcome, actionLoginFlowEpoch)');
expect(continueBody).not.toContain('finishFreshLogin(');
const confirmStart = source.indexOf("if (action.type === 'confirm-sso-realm')");
const confirmBody = source.slice(confirmStart, continueStart);
- expect(confirmBody.indexOf('pendingPersonalLogin = null')).toBeLessThan(confirmBody.indexOf('pendingAuthRealm = confirmation.targetRegion'));
+ expect(confirmBody.indexOf('pendingPersonalLogin = null')).toBeLessThan(
+ confirmBody.indexOf('pendingAuthRealm = confirmation.targetRegion'),
+ );
expect(confirmBody).toContain('pendingAccountRefreshToken = null');
- expect(source.slice(0, source.indexOf('async function acceptLoginOutcome('))).not.toContain('await finishFreshLogin(');
- expect(source).toContain("await finishFreshLogin({ status: 'ok', ...pair }, actionLoginFlowEpoch)");
- const reset = source.slice(source.indexOf('function resetLoginFlowState()'), source.indexOf('function clearAuth('));
+ expect(source.slice(0, source.indexOf('async function acceptLoginOutcome('))).not.toContain(
+ 'await finishFreshLogin(',
+ );
+ expect(source).toContain(
+ "await finishFreshLogin({ status: 'ok', ...pair }, actionLoginFlowEpoch)",
+ );
+ const reset = source.slice(
+ source.indexOf('function resetLoginFlowState()'),
+ source.indexOf('function clearAuth('),
+ );
expect(reset).toContain('pendingPersonalLogin = null');
expect(reset).toContain('handledLoginEmail = null');
});
@@ -154,14 +168,23 @@ describe('auth login-flow reset', () => {
source.indexOf("if (action.type === 'discover-sso-org') {"),
);
expect(discover).toContain('discoverEmailLogin(action.email');
- expect(discover.indexOf('discoveredMethods = [];')).toBeLessThan(discover.indexOf('await discoverEmailLogin'));
+ expect(discover.indexOf('discoveredMethods = [];')).toBeLessThan(
+ discover.indexOf('await discoverEmailLogin'),
+ );
expect(discover).toContain('discoverOrganizationRealm(domain, actionLoginFlowEpoch)');
expect(discover).toContain('pendingAuthRealm = region;');
- expect(discover.indexOf("type: 'realm-switch-required'")).toBeLessThan(discover.indexOf('discoveredMethods = methods;'));
+ expect(discover.indexOf("type: 'realm-switch-required'")).toBeLessThan(
+ discover.indexOf('discoveredMethods = methods;'),
+ );
expect(source).toContain("email: confirmation.email ?? ''");
const requestStart = source.indexOf("if (action.type === 'request-code') {");
- const request = source.slice(requestStart, source.indexOf("if (action.type === 'verify-code') {", requestStart));
- expect(request.indexOf('pendingAuthRealm = AUTH_REGION;')).toBeGreaterThan(request.indexOf('await client.requestCode('));
+ const request = source.slice(
+ requestStart,
+ source.indexOf("if (action.type === 'verify-code') {", requestStart),
+ );
+ expect(request.indexOf('pendingAuthRealm = AUTH_REGION;')).toBeGreaterThan(
+ request.indexOf('await client.requestCode('),
+ );
expect(request).toContain('discoveredMethods = [];');
});
@@ -795,12 +818,16 @@ describe('auth login-flow reset', () => {
const initializeStart = source.indexOf('export async function initialize(');
const initializeEnd = source.indexOf('\n}\n\n/**\n * 冷启动 refresh 流程本体', initializeStart);
const initializeBody = source.slice(initializeStart, initializeEnd);
- expect(initializeBody).toContain('await loadClientEndpointsForRealm(persistedSession.realm);');
expect(initializeBody).not.toContain('activateClientEndpointRealm(persistedSession.realm);');
const coldStart = source.indexOf('async function runColdStartRefreshFlow(');
const coldEnd = source.indexOf('\n}\n\nasync function loadLoginProviders()', coldStart);
const coldBody = source.slice(coldStart, coldEnd);
+ // Endpoint discovery now runs inside the recoverable flow, still before any
+ // credential request or realm activation (cross-realm credential boundary).
+ expect(coldBody.indexOf('await loadClientEndpointsForRealm(storedRealm);')).toBeLessThan(
+ coldBody.indexOf('await runAuthRefreshWithReplacementRetry(storedToken,'),
+ );
const coldCredentialCommit = coldBody.indexOf('await commitDesktopRefreshCredentials(');
const coldPolicyGuard = coldBody.indexOf('!canRestoreAuthSessionForMembership(');
const coldRealmActivation = coldBody.indexOf('activateClientEndpointRealm(storedRealm);');
@@ -905,18 +932,24 @@ describe('auth login-flow reset', () => {
// The timeout boundary must go through the guarded helper so a still-pending
// owner transition is not awaited (its teardown awaits are unbounded) and no
// competing signed-out cleanup starts underneath it.
- const guardedRecovery = initializeBody.lastIndexOf('resolveColdStartTimeoutRecovery({', timeoutRecovery);
+ const guardedRecovery = initializeBody.lastIndexOf(
+ 'resolveColdStartTimeoutRecovery({',
+ timeoutRecovery,
+ );
expect(guardedRecovery).toBeGreaterThan(-1);
expect(guardedRecovery).toBeLessThan(timeoutRecovery);
expect(initializeBody).toContain('pendingState: snapshotLoggedOutAuthState(true)');
expect(initializeBody).toContain('timeoutStartEpoch: startupTimeoutEpoch');
expect(initializeBody).toContain('currentEpoch: authStateEpoch');
expect(initializeBody).toContain('currentState: snapshotAuthState()');
- expect(initializeBody).not.toContain('await ownerChangeShellGate.waitForSettled();\n return snapshotAuthState();');
+ expect(initializeBody).not.toContain(
+ 'await ownerChangeShellGate.waitForSettled();\n return snapshotAuthState();',
+ );
// The fallback must tell the recovery it is the startup-gate fallback, so the
// epoch it raises is recorded at the moment it is raised (see below).
- expect(initializeBody.indexOf('coldStartTimeoutRecovery: true', timeoutRecovery))
- .toBeGreaterThan(timeoutRecovery);
+ expect(
+ initializeBody.indexOf('coldStartTimeoutRecovery: true', timeoutRecovery),
+ ).toBeGreaterThan(timeoutRecovery);
});
it('accepts a late refresh when the fallback edge was recorded at bump time', () => {
@@ -1001,7 +1034,9 @@ describe('auth login-flow reset', () => {
expect(refreshBody).toContain('const authRealmChanged = refreshRealm !== activeAuthRealm;');
expect(refreshBody).toContain('await commitDesktopRefreshCredentials(');
expect(refreshBody).toContain('activeAuthRealm = refreshRealm;');
- expect(refreshBody.match(/commitCloudAppSession\(currentUser.id, authRealmChanged\);/g)).toHaveLength(2);
+ expect(
+ refreshBody.match(/commitCloudAppSession\(currentUser.id, authRealmChanged\);/g),
+ ).toHaveLength(2);
expect(refreshBody).toContain(
'const membershipKindChanged = previousMembershipKind !== nextUser.membershipKind;',
);
@@ -1185,7 +1220,9 @@ describe('auth login-flow reset', () => {
const completeEnd = source.indexOf('\n}\n\nasync function acceptLoginOutcome', completeStart);
const completeBody = source.slice(completeStart, completeEnd);
const acceptedUser = completeBody.indexOf('currentUser = nextUser;');
- const ownerCommit = completeBody.indexOf('commitCloudAppSession(currentUser.id, authRealmChanged);');
+ const ownerCommit = completeBody.indexOf(
+ 'commitCloudAppSession(currentUser.id, authRealmChanged);',
+ );
const clearPreviousFlag = completeBody.indexOf('canaryFlagStore.clear();', acceptedUser);
expect(acceptedUser).toBeGreaterThan(-1);
expect(clearPreviousFlag).toBeGreaterThan(acceptedUser);
diff --git a/apps/desktop/src/main/__tests__/authRefreshBackoff.test.ts b/apps/desktop/src/main/__tests__/authRefreshBackoff.test.ts
index d46a26e6f2..7059a84c68 100644
--- a/apps/desktop/src/main/__tests__/authRefreshBackoff.test.ts
+++ b/apps/desktop/src/main/__tests__/authRefreshBackoff.test.ts
@@ -32,8 +32,9 @@ function recoveryHarness() {
'refresh',
`
let refreshPromise = null;
+ const coldStartAuthInFlight = null;
let authStateEpoch = 1;
- const refreshBackoff = new AuthRefreshBackoff(() => 1_000_000);
+ const refreshBackoff = new AuthRefreshBackoff(() => 1_000_000, () => 0);
const getActiveAppSession = () => ({ mode: 'cloud' });
const log = { debug() {} };
${compiled}
@@ -59,41 +60,28 @@ function recoveryHarness() {
}
describe('network recovery during an in-flight refresh', () => {
- it('retries a late network failure once and retains the next failure cooldown', async () => {
+ it('shares a late network failure without launching a synchronized recovery request', async () => {
const h = recoveryHarness();
- h.retry.mockImplementation(async () => {
- h.backoff.defer(1, undefined, true);
- return false;
- });
const ordinary = h.call();
- const recovery = h.call({ networkRecovered: true });
- expect(h.retry).not.toHaveBeenCalled();
- h.backoff.defer(1, undefined, true);
+ const first = h.call({ networkRecovered: true });
+ const second = h.call({ networkRecovered: true });
+ h.backoff.defer(1);
h.finish();
- await expect(ordinary).resolves.toBe(false);
- await expect(recovery).resolves.toBe(false);
- expect(h.retry).toHaveBeenCalledExactlyOnceWith();
+ await expect(Promise.all([ordinary, first, second])).resolves.toEqual([false, false, false]);
+ expect(h.retry).not.toHaveBeenCalled();
expect(h.backoff.remaining(1)).toBe(60_000);
});
- it('coalesces concurrent recovery callers onto the new in-flight refresh', async () => {
+ it('does not bypass or reset backoff when recovery hints arrive after failure', async () => {
const h = recoveryHarness();
- let completeRetry!: (value: boolean) => void;
- const next = new Promise<boolean>((resolve) => {
- completeRetry = resolve;
- });
- h.retry.mockImplementation(() => {
- h.setPending(next);
- return next;
- });
- const first = h.call({ networkRecovered: true });
- const second = h.call({ networkRecovered: true });
- h.backoff.defer(1, undefined, true);
h.finish();
- await Promise.resolve();
- expect(h.retry).toHaveBeenCalledExactlyOnceWith();
- completeRetry(true);
- await expect(Promise.all([first, second])).resolves.toEqual([true, true]);
+ h.backoff.defer(1);
+ for (let attempt = 0; attempt < 5; attempt++) {
+ await expect(h.call({ networkRecovered: true })).resolves.toBe(false);
+ }
+ expect(h.retry).not.toHaveBeenCalled();
+ expect(h.backoff.remaining(1)).toBe(60_000);
+ expect(h.backoff.defer(1)).toBe(120_000);
});
it.each(['server failure', 'Retry-After', 'owner changed', 'succeeded'])(
@@ -103,11 +91,7 @@ describe('network recovery during an in-flight refresh', () => {
const recovery = h.call({ networkRecovered: true });
const epoch = outcome === 'owner changed' ? 2 : 1;
h.setEpoch(epoch);
- const delay = h.backoff.defer(
- epoch,
- outcome === 'Retry-After' ? 1_120_000 : undefined,
- outcome === 'owner changed',
- );
+ const delay = h.backoff.defer(epoch, outcome === 'Retry-After' ? 1_120_000 : undefined);
h.finish(outcome === 'succeeded');
await expect(recovery).resolves.toBe(outcome === 'succeeded');
expect(h.retry).not.toHaveBeenCalled();
@@ -117,31 +101,53 @@ describe('network recovery during an in-flight refresh', () => {
});
describe('runtime auth refresh backoff', () => {
- it('releases only a transport failure after a real response from the same login generation', () => {
- const backoff = new AuthRefreshBackoff(() => 1_000_000);
- backoff.defer(1, undefined, true);
- backoff.networkRecovered(2);
- expect(backoff.remaining(1)).toBe(60_000);
- backoff.networkRecovered(1);
- expect(backoff.remaining(1)).toBe(0);
- backoff.defer(1);
- backoff.networkRecovered(1);
- expect(backoff.remaining(1)).toBe(60_000);
+ // 2026-10-29: a fleet-wide outage must not synchronize all clients on a
+ // fixed retry interval or on the same Retry-After deadline (unit, fake time).
+ it('spreads clients across the retry window, including after a common server deadline', () => {
+ const clients = [0, 0.25, 0.5, 0.75, 0.999].map(
+ (random) =>
+ new AuthRefreshBackoff(
+ () => 1_000_000,
+ () => random,
+ ),
+ );
+ const delays = clients.map((client) => client.defer(1, 1_600_000));
+ expect(new Set(delays).size).toBe(clients.length);
+ expect(Math.min(...delays)).toBeGreaterThanOrEqual(600_000);
+ expect(Math.max(...delays) - Math.min(...delays)).toBeGreaterThan(50_000);
});
- it.each([undefined, 1_030_000, 1_120_000])(
- 'never bypasses server failure or rate limiting (%s)',
- (retryAt) => {
- const backoff = new AuthRefreshBackoff(() => 1_000_000);
- const delay = backoff.defer(1, retryAt);
- backoff.networkRecovered(1);
- expect(backoff.remaining(1)).toBe(delay);
- },
- );
+ it('backs off repeated failures, stays capped, and resets only for a new login or success', () => {
+ const backoff = new AuthRefreshBackoff(
+ () => 1_000_000,
+ () => 0.5,
+ );
+ const delays = Array.from({ length: 8 }, () => backoff.defer(1));
+ expect(delays.slice(0, 4)).toEqual([90_000, 180_000, 360_000, 450_000]);
+ expect(delays.slice(4)).toEqual([450_000, 450_000, 450_000, 450_000]);
+ expect(backoff.defer(2)).toBe(90_000);
+ backoff.clear();
+ expect(backoff.defer(2)).toBe(90_000);
+ });
+
+ it('continues to randomize retries after reaching the cap', () => {
+ let fraction = 0;
+ const backoff = new AuthRefreshBackoff(
+ () => 1_000_000,
+ () => fraction,
+ );
+ for (let attempt = 0; attempt < 4; attempt++) backoff.defer(1);
+ expect(backoff.defer(1)).toBe(300_000);
+ fraction = 0.999;
+ expect(backoff.defer(1)).toBe(599_700);
+ });
it('keeps an absolute deadline across two-second explicit calls and resumes at expiry', () => {
let now = 1_000_000;
- const backoff = new AuthRefreshBackoff(() => now);
+ const backoff = new AuthRefreshBackoff(
+ () => now,
+ () => 0,
+ );
expect(backoff.remaining(1)).toBe(0);
expect(backoff.defer(1)).toBe(60_000);
for (let elapsed = 2_000; elapsed < 60_000; elapsed += 2_000) {
@@ -154,7 +160,10 @@ describe('runtime auth refresh backoff', () => {
it('honors a longer server wait without applying the failed login generation to another account', () => {
let now = 1_000_000;
- const backoff = new AuthRefreshBackoff(() => now);
+ const backoff = new AuthRefreshBackoff(
+ () => now,
+ () => 0,
+ );
expect(backoff.defer(1, now + 120_000)).toBe(120_000);
now += 60_000;
expect(backoff.remaining(1)).toBe(60_000);
@@ -167,13 +176,19 @@ describe('runtime auth refresh backoff', () => {
it.each([undefined, 0, 999_999, Number.NaN, Number.POSITIVE_INFINITY])(
'retains the minimum wait for invalid or shorter deadline %s',
(retryAt) => {
- const backoff = new AuthRefreshBackoff(() => 1_000_000);
+ const backoff = new AuthRefreshBackoff(
+ () => 1_000_000,
+ () => 0,
+ );
expect(backoff.defer(1, retryAt)).toBe(60_000);
},
);
it('clears the failed wait when a successful login or refresh schedules normal renewal', () => {
- const backoff = new AuthRefreshBackoff(() => 1_000_000);
+ const backoff = new AuthRefreshBackoff(
+ () => 1_000_000,
+ () => 0,
+ );
backoff.defer(1);
backoff.clear();
expect(backoff.remaining(1)).toBe(0);
diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.ts
index a26237dc17..dac260f5e0 100644
--- a/apps/desktop/src/main/authManager.ts
+++ b/apps/desktop/src/main/authManager.ts
@@ -2305,11 +2305,18 @@ async function apiFetch<T>(
body: options?.body !== undefined ? JSON.stringify(options.body) : undefined,
signal: effectiveTimeout > 0 ? controller.signal : undefined,
});
- const retryAt = response.status === 429 ? retryAfterDeadline(response) : undefined;
+ const retryAt =
+ response.status === 429 || response.status === 503 ? retryAfterDeadline(response) : undefined;
let data: T;
- try { data = (await response.json()) as T; }
- catch (error) {
- log.warn('auth response read failed', apiPath, { status: response.status }, requestErrorMessage(error));
+ try {
+ data = (await response.json()) as T;
+ } catch (error) {
+ log.warn(
+ 'auth response read failed',
+ apiPath,
+ { status: response.status },
+ requestErrorMessage(error),
+ );
return { ok: false, status: response.status, data: null as T, retryAt };
}
const errorCode = (data as AuthErrorResponse | null)?.error?.code;
@@ -2318,8 +2325,12 @@ async function apiFetch<T>(
// through serverApiClient, but share the same terminal auth contract.
void invalidateSession('account-unavailable');
}
- return { ok: response.ok, status: response.status, data,
- ...(retryAt !== undefined ? { retryAt } : {}) };
+ return {
+ ok: response.ok,
+ status: response.status,
+ data,
+ ...(retryAt !== undefined ? { retryAt } : {}),
+ };
} catch (error) {
log.warn('auth request failed', apiPath, requestErrorMessage(error));
return { ok: false, status: 0, data: null as T };
@@ -3145,8 +3156,8 @@ function scheduleRefresh(token: string): void {
*
* 正常路径的 refreshTimer 在触发时即消耗;若这次 refresh 因网络抖动 / 429 / 5xx 失败,
* 不重排的话就再没有下一次尝试,access token 会在几分钟后静默过期(下一次自愈要等
- * 系统 resume 或冷启动)。access token 有 5 分钟的提前刷新余量,60s 间隔在过期前还有
- * 数次机会;确定性凭据失效不走这里(直接 clearAuth + 弹重登)。
+ * 系统 resume 或冷启动)。失败采用带随机抖动的指数退避,避免全体客户端集中重试;
+ * 确定性凭据失效不走这里(直接 clearAuth + 弹重登)。
*/
const RUNTIME_REFRESH_RETRY_MS = 60_000;
const REFRESH_TOKEN_REPLACEMENT_RETRY_LIMIT = 2;
@@ -3170,8 +3181,7 @@ let replacementIntegrationReloadTimers: ReturnType<typeof setTimeout>[] = [];
* per-request abort(见 requestAuthRefresh),黑洞 / captive-portal 网络下请求会
* 无限挂起——没有这道闸,initialize() 永不 resolve,splash 永不淡出。超时后先以
* 未登录返回解锁 UI,流程继续后台跑:迟到成功会正常广播登录态,renderer 的
- * GuestRoute 自动把用户从登录页带回主界面。20s 覆盖正常慢网(transient retry
- * 1s+2s 退避 × 3 次请求 + /me 的 15s 上限之内的绝大多数组合)。
+ * GuestRoute 自动把用户从登录页带回主界面。网络失败后的分钟级持续重试不阻塞 splash。
*/
const COLD_START_AUTH_GATE_TIMEOUT_MS = 20_000;
@@ -3359,10 +3369,55 @@ function scheduleNonXdOrgBetaDefault(input: {
* 并发轮换同一枚 refresh token 互相打成 INVALID_REFRESH_TOKEN。
*/
let coldStartAuthInFlight: Promise<AuthState> | null = null;
+// A newly mounted window must not restart recovery after the user took over.
+let coldStartRecoveryStopped = false;
+
+// Wakes only the delay between attempts, never aborts a rotating refresh request.
+let coldStartRetryWait: ((cancel?: boolean) => void) | null = null;
+
+function waitForColdStartRetry(
+ result: AuthRefreshResult,
+ backoff: AuthRefreshBackoff,
+): Promise<void> {
+ // The backoff belongs to this recovery flow, so startup UI fallback epochs
+ // cannot reset its failure count and synchronize clients again.
+ const retryAt = Date.now() + backoff.defer(0, result.retryAt);
+ return new Promise((resolve) => {
+ let timer: ReturnType<typeof setTimeout>;
+ const finish = () => {
+ clearTimeout(timer);
+ if (coldStartRetryWait === wake) coldStartRetryWait = null;
+ resolve();
+ };
+ const wake = (cancel = false) => {
+ // Only an explicit retry of a transport failure can accelerate recovery.
+ // Server failures and their randomized cooldown must remain protected.
+ if (cancel || (result.status === 0 && !Number.isFinite(result.retryAt))) finish();
+ };
+ const tick = () => {
+ const remaining = retryAt - Date.now();
+ if (remaining <= 0) finish();
+ else {
+ timer = setTimeout(tick, Math.min(remaining, 2_147_483_647));
+ timer.unref?.();
+ }
+ };
+ coldStartRetryWait = wake;
+ tick();
+ });
+}
-function scheduleRefreshRetryAfterTransientFailure(epoch: number, retryAt?: number, networkFailure = false): void {
+function stopColdStartRecovery(): void {
+ coldStartRecoveryStopped = true;
+ if (coldStartAuthInFlight === null) return;
+ authStateEpoch += 1;
+ coldStartTimeoutFallbacks.clear();
+ coldStartRetryWait?.(true);
+}
+
+function scheduleRefreshRetryAfterTransientFailure(epoch: number, retryAt?: number): void {
if (epoch !== authStateEpoch) return;
- const delay = refreshBackoff.defer(epoch, retryAt, networkFailure);
+ const delay = refreshBackoff.defer(epoch, retryAt);
if (refreshTimer !== null) {
clearTimeout(refreshTimer);
refreshTimer = null;
@@ -3373,7 +3428,10 @@ function scheduleRefreshRetryAfterTransientFailure(epoch: number, retryAt?: numb
if (authStateEpoch !== epoch) return;
const remaining = refreshBackoff.remaining(epoch);
if (remaining > 0) refreshTimer = setTimeout(retry, Math.min(remaining, 2_147_483_647));
- else { refreshTimer = null; void refresh(); }
+ else {
+ refreshTimer = null;
+ void refresh();
+ }
};
refreshTimer = setTimeout(retry, Math.min(delay, 2_147_483_647));
}
@@ -3720,6 +3778,7 @@ function clearAuth(
// A user logout/login or any non-timeout clear breaks the fallback chain even
// when no refresh guard ran between that action and a sibling window timeout.
coldStartTimeoutFallbacks.clear();
+ coldStartRetryWait?.(true);
}
refreshBackoff.clear();
loginFlowEpoch += 1;
@@ -4075,6 +4134,7 @@ export async function switchSavedAccount(
),
)?.realm;
if (!realm) throw new AuthApiError('ACCOUNT_NOT_FOUND', 404, 'Saved account realm missing');
+ stopColdStartRecovery();
await loadClientEndpointsForRealm(realm);
assertLoginFlowCurrent(switchLoginFlowEpoch);
const client = createAuthClient(realm);
@@ -4147,6 +4207,7 @@ export async function beginAddAccountLogin(): Promise<DesktopLoginActionResult>
'This shared-data instance cannot add accounts',
);
}
+ stopColdStartRecovery();
loginFlowEpoch += 1;
browserAuthorizationSlot.cancelActive();
resetLoginFlowState();
@@ -4197,6 +4258,7 @@ export function hasNoPersistedAuthCredentials(): boolean {
/** Enter the account-free local session through the shared projection boundary. */
export async function enterLocalMode(): Promise<AuthState> {
+ stopColdStartRecovery();
browserAuthorizationSlot.cancelActive();
// Local mode has a different data owner. Drop process-local generic OAuth
// tokens before switching the committed owner so cloud credentials cannot
@@ -4608,6 +4670,7 @@ export async function initialize(options: AuthInitializeOptions = {}): Promise<A
commitVolatileAppSession('signed-out');
return snapshotLoggedOutAuthState();
}
+ if (coldStartRecoveryStopped) return snapshotLoggedOutAuthState();
// release-relogin-on-update: if the auto-updater dropped a relogin marker
// for *this* version, wipe persisted auth and force the user back to the
@@ -4697,15 +4760,10 @@ export async function initialize(options: AuthInitializeOptions = {}): Promise<A
if (!persistedSession) {
return finishColdStartSignedOut('cold-start-no-persisted-session');
}
- try {
- await loadClientEndpointsForRealm(persistedSession.realm);
- } catch (error) {
- // 对端区域清单暂不可用时保留原子凭据;退回构建区 refresh 会把有效 token
- // 当成非法凭据,因此本次仅以未登录放行 UI,下一次 initialize/重启可重试。
- log.warn('persisted auth realm manifest unavailable; keeping session for retry', error);
- return finishColdStartSignedOut('cold-start-realm-manifest-unavailable');
- }
const storedToken = persistedSession.refreshToken;
+ // Credential reconciliation above can yield to a manual login or owner change.
+ if (coldStartRecoveryStopped || authStateEpoch !== initializeStartEpoch)
+ return snapshotAuthState();
// 进程内去重:主窗流程还挂着(黑洞网络)时,副窗 / 右侧栏窗口 mount 触发的
// initialize() 复用同一个 in-flight promise,避免并发轮换同一枚 refresh token。
@@ -4747,8 +4805,7 @@ export async function initialize(options: AuthInitializeOptions = {}): Promise<A
// the durable commit), so the epoch guards above cannot see it. Treat a
// settled login as an auth change that must never be cleared by the
// startup deadline; its own commit already published the settled state.
- loginCommittedSinceInitialize:
- settledLoginCommitCount !== settledLoginsAtInitialize,
+ loginCommittedSinceInitialize: settledLoginCommitCount !== settledLoginsAtInitialize,
isStartupFallbackEpoch: (epoch) =>
epoch > initializeStartEpoch &&
coldStartTimeoutFallbacks.containsOnlyFallbacks(initializeStartEpoch, epoch),
@@ -4821,31 +4878,50 @@ async function runColdStartRefreshFlow(
return true;
};
+ const backoff = new AuthRefreshBackoff();
try {
- // 瞬时失败(断网 / 5xx)短暂退避后重试,而不是一次失败就以未登录进登录页——
- // 否则冷启动撞上一次网络抖动,用户看到的就是「重启莫名被登出、重开一次又好了」。
- // 注意:
- // - refresh 是 token-rotating 端点,不设 per-request timeout(timeoutMs:0)——
- // 若服务端已轮换但客户端 abort,重试以旧 token 触发 INVALID_REFRESH_TOKEN 永久登出。
- // - 429 不重试(rateLimitDelayMs:0):服务端窗口 60s,短退避必然还在同一窗口内失败,
- // 长退避(60s)则会把 splash 阻塞分钟级——两种都不合适;直接放弃本次保留 token,
- // 下次启动或运行时 refresh(非阻塞)自愈。
- const {
- result: refreshResult,
- attempts,
- failureAction,
- rejectedTokens,
- requestedToken,
- } = await runAuthRefreshWithReplacementRetry(storedToken, {
- phase: 'cold-start',
- realm: storedRealm,
- withTransientRetry: true,
- rateLimitDelayMs: 0,
- onFailure: ({ attempt, status, code, definitive, willRetry }) =>
- log.warn(
- `cold-start refresh attempt ${attempt} failed status=${status} code=${code ?? '<none>'} definitive=${definitive} transientWillRetry=${willRetry}`,
- ),
- });
+ // Keep the shared recovery alive beyond the splash deadline. A network outage
+ // must not turn a saved session into a fresh-login requirement. Each failed
+ // attempt uses jittered exponential backoff; manual auth always wins.
+ let run: Awaited<ReturnType<typeof runAuthRefreshWithReplacementRetry>>;
+ for (;;) {
+ if (epochChanged('before-recovery-attempt')) return snapshotAuthState();
+ if (!ownershipRecovery.expectedActiveVaultAccountKey) {
+ const latest = readPersistedAuthSession();
+ if (!latest || latest.realm !== storedRealm) {
+ return finishColdStartSignedOut('cold-start-persisted-session-changed');
+ }
+ storedToken = latest.refreshToken;
+ }
+ try {
+ // Realm discovery can fail while offline too. Never fall back to sending
+ // a saved credential to a different realm's refresh endpoint.
+ await loadClientEndpointsForRealm(storedRealm);
+ } catch (error) {
+ if (epochChanged('after-realm-discovery')) return snapshotAuthState();
+ log.warn('persisted auth realm manifest unavailable; keeping session for retry', error);
+ await waitForColdStartRetry({ ok: false, status: 0, data: {} }, backoff);
+ continue;
+ }
+ if (epochChanged('before-refresh')) return snapshotAuthState();
+ run = await runAuthRefreshWithReplacementRetry(storedToken, {
+ phase: 'cold-start',
+ realm: storedRealm,
+ withTransientRetry: false,
+ });
+ if (epochChanged('after-recovery-attempt')) return snapshotAuthState();
+ if (
+ run.result.ok ||
+ (run.failureAction?.kind !== 'transient-failure' &&
+ run.failureAction?.kind !== 'replacement-retry')
+ )
+ break;
+ log.warn(
+ `cold-start refresh failed status=${run.result.status} — keeping saved login and retrying in the background`,
+ );
+ await waitForColdStartRetry(run.result, backoff);
+ }
+ const { result: refreshResult, attempts, failureAction, rejectedTokens, requestedToken } = run;
// 迟到守卫①:refresh 期间用户手动登录 / 登出过 → 丢弃结果。成功也丢
// (旧 token family 已被新登录取代);失败更不能把新登录的 token 删掉。
if (epochChanged('after-refresh')) {
@@ -5396,6 +5472,7 @@ async function finishFreshLogin(
async function runLoginAction(
action: Exclude<DesktopLoginAction, { type: 'back' }>,
): Promise<DesktopLoginActionResult> {
+ if (action.type !== 'reset') stopColdStartRecovery();
const actionLoginFlowEpoch = loginFlowEpoch;
const startsBuildRealmFlow =
action.type === 'discover' ||
@@ -5414,12 +5491,24 @@ async function runLoginAction(
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) {
+ if (
+ !accessToken &&
+ (coldStartAuthInFlight || credentialStoreHealth.unavailable || readPersistedAuthSession())
+ ) {
+ coldStartRecoveryStopped = false;
+ coldStartRetryWait?.();
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();
+ if (!accessToken && coldStartAuthInFlight) {
+ return {
+ success: false,
+ code: 'AUTH_SERVICE_UNAVAILABLE',
+ state: loginPreparingErrorState(),
+ };
+ }
assertLoginFlowCurrent(actionLoginFlowEpoch);
if (accessToken && loginFlowState?.step === 'completed') {
return { success: true, state: loginFlowState };
@@ -5807,6 +5896,7 @@ export async function dispatchLoginAction(action: unknown): Promise<DesktopLogin
if (isLoginFlowCommitSealed(loginFlowEpoch)) {
return { success: false, code: 'LOGIN_BUSY', state: loginFlowState };
}
+ stopColdStartRecovery();
if (!accessToken && credentialStoreHealth.unavailable) return getLoginState();
const providers = providerConfig;
loginFlowEpoch += 1;
@@ -5845,24 +5935,17 @@ export async function dispatchLoginAction(action: unknown): Promise<DesktopLogin
}
}
-export async function refresh(options?: { networkRecovered?: boolean }): Promise<boolean> {
+export async function refresh(_options?: { networkRecovered?: boolean }): Promise<boolean> {
if (getActiveAppSession().mode === 'local') {
log.debug('runtime refresh skipped in local mode');
return false;
}
- if (refreshPromise !== null) {
- if (!options?.networkRecovered) return refreshPromise;
- const recoveryEpoch = authStateEpoch;
- const refreshed = await refreshPromise;
- if (refreshed || authStateEpoch !== recoveryEpoch) return refreshed;
- // Another recovery caller may already have started the next single flight.
- if (refreshPromise !== null) return refreshPromise;
- if (!refreshBackoff.networkRecovered(recoveryEpoch)) return false;
- // Consume this hint once, including when the old network failure arrived
- // after it. A failure of the new attempt must retain its own cooldown.
- return refresh();
- }
- if (options?.networkRecovered) refreshBackoff.networkRecovered(authStateEpoch);
+ // Cold-start recovery owns rotation until it settles. Runtime callers must
+ // not consume the same saved refresh token concurrently, or wait indefinitely.
+ if (coldStartAuthInFlight !== null && (!accessToken || !currentUser)) return false;
+ // A fleet may observe relay recovery at once. Keep accepting the legacy hint,
+ // but never let it reset the failure count or bypass the randomized deadline.
+ if (refreshPromise !== null) return refreshPromise;
// Explicit callers (including chat polling and resume) share the same wait
// as the retry timer; skipped calls must not move the deadline forward.
if (refreshBackoff.remaining(authStateEpoch) > 0) return false;
@@ -5988,12 +6071,12 @@ export async function refresh(options?: { networkRecovered?: boolean }): Promise
log.warn(
`runtime refresh failed for a stale token after replacement retries status=${result.status} code=${code ?? '<none>'} — retrying no sooner than ${RUNTIME_REFRESH_RETRY_MS / 1000}s`,
);
- scheduleRefreshRetryAfterTransientFailure(refreshEpoch, result.retryAt, result.status === 0);
+ scheduleRefreshRetryAfterTransientFailure(refreshEpoch, result.retryAt);
} else {
log.warn(
`runtime refresh failed transiently status=${result.status} code=${code ?? '<none>'} — retrying no sooner than ${RUNTIME_REFRESH_RETRY_MS / 1000}s`,
);
- scheduleRefreshRetryAfterTransientFailure(refreshEpoch, result.retryAt, result.status === 0);
+ scheduleRefreshRetryAfterTransientFailure(refreshEpoch, result.retryAt);
}
return false;
}
@@ -6231,6 +6314,7 @@ export async function logout(): Promise<void> {
if (!activeUser) {
throw new AuthApiError('UNAUTHENTICATED', 401, 'No current account to log out');
}
+ stopColdStartRecovery();
const logoutAuthEpoch = authStateEpoch;
const isLogoutStillCurrent = (expectedAuthEpoch = logoutAuthEpoch): boolean =>
authStateEpoch === expectedAuthEpoch &&
@@ -6407,6 +6491,7 @@ export function handleResume(): void {
}
export function dispose(): void {
+ stopColdStartRecovery();
browserAuthorizationSlot.cancelActive();
if (refreshTimer !== null) {
clearTimeout(refreshTimer);
diff --git a/apps/desktop/src/main/authRefreshBackoff.ts b/apps/desktop/src/main/authRefreshBackoff.ts
index 0368953aca..e577f635fc 100644
--- a/apps/desktop/src/main/authRefreshBackoff.ts
+++ b/apps/desktop/src/main/authRefreshBackoff.ts
@@ -1,32 +1,35 @@
-/** Process-local retry deadline, scoped to the current login generation. */
+/** Process-local, jittered exponential retry deadline for one login generation. */
export class AuthRefreshBackoff {
private epoch = -1;
private retryAt = 0;
- private networkFailure = false;
+ private failures = 0;
- constructor(private readonly now: () => number = () => Date.now()) {}
+ constructor(
+ private readonly now: () => number = () => Date.now(),
+ private readonly random: () => number = () => Math.random(),
+ ) {}
remaining(epoch: number): number {
return this.epoch === epoch ? Math.max(0, this.retryAt - this.now()) : 0;
}
- defer(epoch: number, serverRetryAt?: number, networkFailure = false): number {
+ defer(epoch: number, serverRetryAt?: number): number {
+ if (this.epoch !== epoch) this.failures = 0;
this.epoch = epoch;
- this.retryAt = Math.max(this.now() + 60_000, Number.isFinite(serverRetryAt) ? serverRetryAt! : 0);
- this.networkFailure = networkFailure && serverRetryAt === undefined;
+ // Equal jitter: 1–2m, 2–4m, 4–8m, then 5–10m indefinitely. Add the
+ // random spread AFTER a shared server deadline, not before a max() that
+ // would collapse every client's retry back onto the same Retry-After time.
+ const floor = Math.min(60_000 * 2 ** this.failures, 300_000);
+ this.failures = Math.min(this.failures + 1, 3);
+ this.retryAt =
+ Math.max(this.now() + floor, Number.isFinite(serverRetryAt) ? serverRetryAt! : 0) +
+ Math.floor(this.random() * floor);
return this.remaining(epoch);
}
- /** A real server response proves reachability; interface hints do not. */
- networkRecovered(epoch: number): boolean {
- if (this.epoch !== epoch || !this.networkFailure) return false;
- this.clear();
- return true;
- }
-
clear(): void {
this.epoch = -1;
this.retryAt = 0;
- this.networkFailure = false;
+ this.failures = 0;
}
}
diff --git a/docs/dev-rules/credentials-and-local-storage.md b/docs/dev-rules/credentials-and-local-storage.md
index 5b6dd9d79d..75edb8b342 100644
--- a/docs/dev-rules/credentials-and-local-storage.md
+++ b/docs/dev-rules/credentials-and-local-storage.md
@@ -179,16 +179,26 @@ Claude.ai 登录,也不得收集、存储或中转订阅凭证。Cindy 因此
### 运行时会话续期退避
-Desktop 的运行时 refresh 遇到瞬时失败后,主动调用与定时重试共用至少 60 秒的等待;
-429 的有效 `Retry-After` 更长时按服务器等待时间执行。等待期间的调用不发请求、不延长
-原期限,也不清除凭证。成功续期/登录清除等待,登录代次改变后旧等待不约束新账号。
-唯一提前结束等待的情形是:此前失败为无服务端响应的网络错误(status 0),且 relay
-随后明确返回鉴权拒绝,证明网络路径已可达。同登录代次的自救可提前续期,仍复用在途
-refresh 与 relay 自救节流。在途 refresh 尚未返回时收到的恢复信号等待其结束;若同代次
-请求随后以网络错误失败,只补一次续期,并发恢复调用仍共享该次请求,新失败保留自己的
-等待期限。网卡变化提示不能触发该例外,429、Retry-After 和服务端错误
-仍遵守原期限。续期完成后的立即重连须复验 client、owner 与持有权,不能唤醒旧实例。
-冷启动、确定性失效和同机 token 替换恢复继续沿用原有判定。状态只留在进程内存中。
+Desktop 冷启动恢复已保存的登录时,DNS/断网、服务端临时错误及区域端点清单暂不可用
+不会清除凭证,也不在有限次数失败后放弃。启动画面仍只等待原有的 20 秒,恢复流程在
+后台持续按下述随机退避策略重试;直到恢复成功、凭证明确
+失效,或用户开始新的登录/退出/切换账号/进入未登录模式。人工操作使旧流程失效,
+迟到响应不能覆盖新状态;不通过中断正在轮换凭证的网络请求来实现取消。
+登录页「重试」优先恢复已保存的登录,复用正在进行的请求,并可提前结束普通网络失败
+的等待,但不能绕过服务端冷却时间。运行时续期也不与冷启动流程并发轮换同一凭证。
+实现与回归见 `authManager.ts`、`authColdStartRecovery.test.ts`。
+
+Desktop 冷启动恢复与运行时 refresh 共用随机指数退避策略:连续失败后的等待区间依次为
+1–2 分钟、2–4 分钟、4–8 分钟,之后持续在 5–10 分钟内重新随机取值,不设次数上限。
+429/503 的有效 `Retry-After` 更长时先遵守服务器期限,再追加当前退避档位的随机间隔,
+防止所有客户端在同一个服务器恢复时间一起重试。等待期间的主动调用不发请求、不延长
+原期限,也不清除凭证。成功续期/登录清除等待,登录代次改变后旧等待不约束新账号;
+冷启动画面超时转后台不能重置失败次数。
+网络变化、resume 或 relay 恢复信号均不能跳过等待或清零失败次数;在途请求仍复用同一个
+promise,恢复信号不能在旧请求结束后追加立即续期。只有用户主动点击登录页重试,且
+此前失败没有服务端响应、没有服务端等待期限时,才能提前结束冷启动等待。
+续期完成后的立即重连须复验 client、owner 与持有权,不能唤醒旧实例。
+确定性失效和同机 token 替换恢复继续沿用原有判定。状态只留在进程内存中。
实现见 `main/authRefreshBackoff.ts`、`main/authManager.ts`;回归见
`main/__tests__/authRefreshBackoff.test.ts`。