Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(auth): preserve consecutive cold-start timeout fallbacks
CHEYANc3a61133992c
diff --git a/apps/desktop/src/main/__tests__/authLoginFlowReset.contract.test.ts b/apps/desktop/src/main/__tests__/authLoginFlowReset.contract.test.tsindex ec6bf167f2..8ab1b29fe4 100644--- a/apps/desktop/src/main/__tests__/authLoginFlowReset.contract.test.ts+++ b/apps/desktop/src/main/__tests__/authLoginFlowReset.contract.test.ts@@ -913,7 +913,7 @@ describe('auth login-flow reset', () => {const clearEnd = source.indexOf('\n}\n', source.indexOf('authStateEpoch += 1;', clearStart));const clearBody = source.slice(clearStart, clearEnd);const bump = clearBody.indexOf('authStateEpoch += 1;');- const record = clearBody.indexOf('coldStartTimeoutFallback = { from: epochBeforeClear, to: authStateEpoch };');+ const record = clearBody.indexOf('coldStartTimeoutFallbacks.record(epochBeforeClear, authStateEpoch);');expect(bump).toBeGreaterThan(-1);expect(record).toBeGreaterThan(bump);// Recording later (in the caller, after the recovery promise unwinds) leaves a@@ -922,7 +922,7 @@ describe('auth login-flow reset', () => {expect(clearBody).toContain('if (opts.coldStartTimeoutRecovery)');expect(clearBody.indexOf('const epochBeforeClear = authStateEpoch;')).toBeLessThan(bump);expect(source.slice(source.indexOf('export async function initialize('))).not.toContain(- '\n coldStartTimeoutFallback = { from:',+ '\n coldStartTimeoutFallbacks.record(epochBeforeClear, authStateEpoch);');});@@ -932,7 +932,6 @@ describe('auth login-flow reset', () => {const body = source.slice(coldStart, coldStartEnd);expect(body).toContain('let flowAuthEpoch = epochAtStart;');expect(body).toContain('flowEpoch: flowAuthEpoch,');- expect(body).toContain('startupFallback: coldStartTimeoutFallback,');expect(body).toContain('flowAuthEpoch = authStateEpoch;');// Both post-commit schedulers must use the adopted epoch; passing epochAtStart// made them treat a recovery login as stale-auth and skip canary/beta sync.@@ -944,10 +943,9 @@ describe('auth login-flow reset', () => {const coldStart = source.indexOf('async function runColdStartRefreshFlow(');const coldStartEnd = source.indexOf('\n}\n\n/**\n * Called on system resume', coldStart);const body = source.slice(coldStart, coldStartEnd);- expect(body).toContain('supersededOnlyByOwnStartupFallback({');- expect(body).toContain('startupFallback: coldStartTimeoutFallback,');+ expect(body).toContain('coldStartTimeoutFallbacks.commitIfCurrent({');// The real-supersession log stays exactly where it was, after the exemption.- const exemption = body.indexOf('supersededOnlyByOwnStartupFallback({');+ const exemption = body.indexOf('coldStartTimeoutFallbacks.commitIfCurrent({');const warn = body.indexOf('cold-start refresh flow superseded by manual auth change');expect(exemption).toBeGreaterThan(-1);expect(warn).toBeGreaterThan(exemption);diff --git a/apps/desktop/src/main/__tests__/authStartupGate.test.ts b/apps/desktop/src/main/__tests__/authStartupGate.test.tsindex 0d17e6fb2b..1e98461d1d 100644--- a/apps/desktop/src/main/__tests__/authStartupGate.test.ts+++ b/apps/desktop/src/main/__tests__/authStartupGate.test.ts@@ -15,8 +15,8 @@ import {LOGIN_PREPARING_GATE_TIMEOUT_MS,awaitLoginProvidersWithPreparingGate,awaitWithStartupTimeout,+ ColdStartAuthFallbackRegistry,mapLoginProvidersLoadFailure,- supersededOnlyByOwnStartupFallback,} from '../authStartupGate';describe('awaitWithStartupTimeout', () => {@@ -184,70 +184,68 @@ describe('awaitWithStartupTimeout', () => {});});-describe('supersededOnlyByOwnStartupFallback', () => {- it('keeps a cold-start flow alive when only its own timeout fallback advanced the epoch', () => {- expect(- supersededOnlyByOwnStartupFallback({- flowEpoch: 7,- currentEpoch: 8,- startupFallback: { from: 7, to: 8 },- }),- ).toBe(false);- });+describe('ColdStartAuthFallbackRegistry', () => {+ it('preserves a late successful refresh across consecutive renderer startup timeouts', async () => {+ vi.useFakeTimers();+ const registry = new ColdStartAuthFallbackRegistry();+ const flowEpoch = 7;+ let currentEpoch = flowEpoch;+ let committedUser: string | null = null;+ let resolveRefresh!: (user: unknown) => void;+ const refresh = new Promise<unknown>((resolve) => {+ resolveRefresh = resolve;+ });+ const recover = () => {+ const previousEpoch = currentEpoch;+ currentEpoch += 1;+ registry.record(previousEpoch, currentEpoch);+ return { isAuthenticated: false };+ };- it('still supersedes the flow after a later user auth change', () => {- expect(- supersededOnlyByOwnStartupFallback({- flowEpoch: 8,- currentEpoch: 9,- startupFallback: { from: 7, to: 8 },- }),- ).toBe(true);- });+ // Two renderer windows share the same refresh, but each owns a startup timer.+ const primary = awaitWithStartupTimeout(refresh, { timeoutMs: 1000, onTimeout: recover });+ const secondary = awaitWithStartupTimeout(refresh, { timeoutMs: 1500, onTimeout: recover });+ await vi.advanceTimersByTimeAsync(1500);+ await expect(primary).resolves.toEqual({ isAuthenticated: false });+ await expect(secondary).resolves.toEqual({ isAuthenticated: false });+ expect(currentEpoch).toBe(9);- it('does not exempt a flow when a user signed in before the fallback ran', () => {- // User login moved 7 -> 8, then the fallback moved 8 -> 9. The flow started at 7,- // so this transition is not its own: the stale refresh must stay discarded- // instead of overwriting the fresh login.- expect(- supersededOnlyByOwnStartupFallback({- flowEpoch: 7,- currentEpoch: 9,- startupFallback: { from: 8, to: 9 },- }),- ).toBe(true);+ resolveRefresh('owner');+ const refreshedUser = await refresh;+ const commit = registry.commitIfCurrent({+ flowEpoch,+ currentEpoch,+ commit: () => {+ committedUser = refreshedUser;+ return committedUser;+ },+ });++ expect(commit).toEqual({ committed: true, value: 'owner' });+ expect(committedUser).toBe('owner');});- it('keeps exempting a flow that hit the fallback twice', () => {- // First fallback 7 -> 8 (adopted), second 8 -> 9: the second transition starts- // exactly where the flow now stands, so a repeated fallback must not discard it.- expect(- supersededOnlyByOwnStartupFallback({- flowEpoch: 8,- currentEpoch: 9,- startupFallback: { from: 8, to: 9 },- }),- ).toBe(false);+ it('does not commit a refresh after an explicit login interrupts the fallback chain', () => {+ const registry = new ColdStartAuthFallbackRegistry();+ registry.record(8, 9);+ const commit = vi.fn(() => 'stale-owner');++ expect(registry.commitIfCurrent({ flowEpoch: 7, currentEpoch: 9, commit })).toEqual({+ committed: false,+ });+ expect(commit).not.toHaveBeenCalled();});- it('does not treat an unrelated change as the flow\'s own fallback', () => {- expect(- supersededOnlyByOwnStartupFallback({- flowEpoch: 7,- currentEpoch: 8,- startupFallback: null,- }),- ).toBe(true);+ it('rejects a later user auth change after consecutive startup fallbacks', () => {+ const registry = new ColdStartAuthFallbackRegistry();+ registry.record(7, 8);+ registry.record(8, 9);+ expect(registry.containsOnlyFallbacks(7, 10)).toBe(false);});- it('reports no supersession while the epoch is unchanged', () => {- expect(- supersededOnlyByOwnStartupFallback({- flowEpoch: 7,- currentEpoch: 7,- startupFallback: null,- }),- ).toBe(false);+ it('accepts the unchanged generation without fallback records', () => {+ const registry = new ColdStartAuthFallbackRegistry();+ expect(registry.containsOnlyFallbacks(7, 7)).toBe(true);});});diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.tsindex 877bb1497f..f67d58c3dc 100644--- a/apps/desktop/src/main/authManager.ts+++ b/apps/desktop/src/main/authManager.ts@@ -65,7 +65,7 @@ import {awaitLoginProvidersWithPreparingGate,awaitWithStartupTimeout,mapLoginProvidersLoadFailure,- supersededOnlyByOwnStartupFallback,+ ColdStartAuthFallbackRegistry,} from './authStartupGate';import { syncCanaryFlagAfterAuth } from './canaryFlagSync';import {@@ -3184,7 +3184,7 @@ let authStateEpoch = 0;* 兜底的 `from` 就不等于流程起始代际,旧流程仍被正常作废(不会反过来覆盖新登录)。* 见 authStartupGate 的 supersededOnlyByOwnStartupFallback。*/-let coldStartTimeoutFallback: { from: number; to: number } | null = null;+const coldStartTimeoutFallbacks = new ColdStartAuthFallbackRegistry();/*** 登录态落地后异步同步灰度标记,不阻塞 renderer 进入主界面。@@ -3707,7 +3707,11 @@ function clearAuth(// 期间并发的刷新已经能看到新代际;若等到外层返回才登记,它仍会被误判为// 「用户改过登录态」而丢弃(PR #6273 review P1)。if (opts.coldStartTimeoutRecovery) {- coldStartTimeoutFallback = { from: epochBeforeClear, to: authStateEpoch };+ coldStartTimeoutFallbacks.record(epochBeforeClear, authStateEpoch);+ } else {+ // 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();}refreshBackoff.clear();loginFlowEpoch += 1;@@ -4698,6 +4702,9 @@ export async function initialize(options: AuthInitializeOptions = {}): Promise<Aif (coldStartAuthInFlight === null) {coldStartAuthInFlight = runColdStartRefreshFlow(storedToken, persistedSession.realm).finally(() => {+ // Keep every fallback edge until the shared refresh settles: sibling renderer+ // timeouts may append another edge while the network flow is still pending.+ coldStartTimeoutFallbacks.clear();coldStartAuthInFlight = null;},);@@ -4762,13 +4769,12 @@ async function runColdStartRefreshFlow(*/let flowAuthEpoch = epochAtStart;const epochChanged = (point: string): boolean => {- if (- !supersededOnlyByOwnStartupFallback({- flowEpoch: flowAuthEpoch,- currentEpoch: authStateEpoch,- startupFallback: coldStartTimeoutFallback,- })- ) {+ const fallbackCommit = coldStartTimeoutFallbacks.commitIfCurrent({+ flowEpoch: flowAuthEpoch,+ currentEpoch: authStateEpoch,+ commit: () => undefined,+ });+ if (!fallbackCommit.committed) {// Either nothing moved, or the only move was our own fallback — adopt the// current epoch as this flow's own. Assigning is a no-op in the former case.flowAuthEpoch = authStateEpoch;@@ -4779,7 +4785,7 @@ async function runColdStartRefreshFlow();// A real user auth change landed on top of the fallback: this flow's epoch is// now stale for good, so stop exempting it.- coldStartTimeoutFallback = null;+ coldStartTimeoutFallbacks.clear();return true;};diff --git a/apps/desktop/src/main/authStartupGate.ts b/apps/desktop/src/main/authStartupGate.tsindex d9bfbb9beb..e129e0d627 100644--- a/apps/desktop/src/main/authStartupGate.ts+++ b/apps/desktop/src/main/authStartupGate.ts@@ -88,29 +88,45 @@ export async function awaitWithStartupTimeout<T>(* 豁免必须绑定到「这次兜底造成的那一次代际推进」,因此比对的是* `startupFallback` 的 from/to 转换,而不是「当前代际恰好等于某个记录值」:*- * - 流程当前代际 == from 且现值 == to → 只可能是这次兜底,豁免;- * - 用户在兜底之前已显式登录过 → 兜底的 from 不等于流程起始代际,照常作废,- * 旧流程不会反过来覆盖新登录;- * - 连续两次兜底 → 流程接受第一次后代际前移到 to,第二次的 from 正好等于它,- * 仍然豁免,不会因为多推进一次就误伤。+ * - 多窗口连续兜底 → 每次同步记录一条代际转换。即使 refresh 尚未观察第一条转换,+ * 也能沿连续的兜底链识别到当前代际。*- * 之后任何用户登录/登出都会再推进一次代际,流程重新被正常作废(旧 token family- * 已被新登录取代)。+ * 任何用户登录/登出造成的转换没有兜底记录,会截断这条链,流程仍被正常作废。*/-export function supersededOnlyByOwnStartupFallback(input: {- /** 流程当前认可的代际(接受过自己的兜底后会前移)。 */- flowEpoch: number;- /** 当前的 authStateEpoch。 */- currentEpoch: number;- /** 兜底自己造成的那次代际推进;未发生兜底时为 null。 */- startupFallback: { from: number; to: number } | null;-}): boolean {- if (input.currentEpoch === input.flowEpoch) return false;- const fallback = input.startupFallback;- if (fallback && input.flowEpoch === fallback.from && input.currentEpoch === fallback.to) {- return false;+export class ColdStartAuthFallbackRegistry {+ private readonly fallbacks = new Map<number, number>();++ /** Called synchronously with the auth epoch increment in clearAuth. */+ record(fromEpoch: number, toEpoch: number): void {+ if (toEpoch > fromEpoch) this.fallbacks.set(fromEpoch, toEpoch);+ }++ /** A late refresh is valid only if every intervening epoch came from startup fallback. */+ containsOnlyFallbacks(fromEpoch: number, toEpoch: number): boolean {+ let epoch = fromEpoch;+ while (epoch < toEpoch) {+ const nextEpoch = this.fallbacks.get(epoch);+ if (nextEpoch === undefined || nextEpoch <= epoch || nextEpoch > toEpoch) return false;+ epoch = nextEpoch;+ }+ return epoch === toEpoch;+ }++ /** Apply a refresh commit only while no explicit auth change interrupted its flow. */+ commitIfCurrent<T>(input: {+ flowEpoch: number;+ currentEpoch: number;+ commit: () => T;+ }): { committed: true; value: T } | { committed: false } {+ if (!this.containsOnlyFallbacks(input.flowEpoch, input.currentEpoch)) {+ return { committed: false };+ }+ return { committed: true, value: input.commit() };+ }++ clear(): void {+ this.fallbacks.clear();}- return true;}/**