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): 兜底代际改为绑定到具体那次推进,并修正登录后同步用的代际

CHEYANe18f9ba79408
diff --git a/apps/desktop/src/main/__tests__/authLoginFlowReset.contract.test.ts b/apps/desktop/src/main/__tests__/authLoginFlowReset.contract.test.ts
index bb7813b257..ec6bf167f2 100644
--- a/apps/desktop/src/main/__tests__/authLoginFlowReset.contract.test.ts
+++ b/apps/desktop/src/main/__tests__/authLoginFlowReset.contract.test.ts
@@ -893,26 +893,59 @@ 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);
- const timeoutRecovery = initializeBody.indexOf("recoverAccountFreeOwnerAtStartup('signed-out', 'cold-start-timeout-recovery')");
+ const timeoutRecovery = initializeBody.indexOf(
+ "recoverAccountFreeOwnerAtStartup('signed-out', 'cold-start-timeout-recovery'",
+ );
expect(timeoutRecovery).toBeGreaterThan(-1);
const recoveryGuard = initializeBody.lastIndexOf('ownerChangeShellGate.isPending()', timeoutRecovery);
expect(recoveryGuard).toBeGreaterThan(-1);
const recoveryWait = initializeBody.indexOf('await ownerChangeShellGate.waitForSettled();', recoveryGuard);
expect(recoveryWait).toBeGreaterThan(recoveryGuard);
expect(recoveryWait).toBeLessThan(timeoutRecovery);
- // The fallback must mark the epoch it raised; otherwise the in-flight refresh
- // that already rotated a valid token is discarded as a user auth change and
- // every launch falls back to the login page.
- expect(initializeBody.indexOf('coldStartTimeoutFallbackEpoch = authStateEpoch;', timeoutRecovery))
+ // 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);
});
+ it('records the fallback epoch synchronously with the epoch bump', () => {
+ const clearStart = source.indexOf('function clearAuth(');
+ 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 };');
+ expect(bump).toBeGreaterThan(-1);
+ expect(record).toBeGreaterThan(bump);
+ // Recording later (in the caller, after the recovery promise unwinds) leaves a
+ // window where a concurrent refresh already sees the new epoch while the marker
+ // is still null, so its successful result is discarded again.
+ 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:',
+ );
+ });
+
+ it('schedules post-login syncs with the epoch the flow commits under', () => {
+ 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('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.
+ expect(body).not.toContain('expectedAuthEpoch: epochAtStart,');
+ expect(body.match(/expectedAuthEpoch: flowAuthEpoch,/g)?.length).toBe(2);
+ });
+
it('lets a cold-start refresh outlive its own startup-gate timeout fallback', () => {
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('startupFallbackEpoch: coldStartTimeoutFallbackEpoch,');
+ expect(body).toContain('startupFallback: coldStartTimeoutFallback,');
// The real-supersession log stays exactly where it was, after the exemption.
const exemption = body.indexOf('supersededOnlyByOwnStartupFallback({');
const warn = body.indexOf('cold-start refresh flow superseded by manual auth change');
diff --git a/apps/desktop/src/main/__tests__/authStartupGate.test.ts b/apps/desktop/src/main/__tests__/authStartupGate.test.ts
index f93f53f63b..0d17e6fb2b 100644
--- a/apps/desktop/src/main/__tests__/authStartupGate.test.ts
+++ b/apps/desktop/src/main/__tests__/authStartupGate.test.ts
@@ -188,9 +188,9 @@ describe('supersededOnlyByOwnStartupFallback', () => {
it('keeps a cold-start flow alive when only its own timeout fallback advanced the epoch', () => {
expect(
supersededOnlyByOwnStartupFallback({
- epochAtStart: 7,
+ flowEpoch: 7,
currentEpoch: 8,
- startupFallbackEpoch: 8,
+ startupFallback: { from: 7, to: 8 },
}),
).toBe(false);
});
@@ -198,19 +198,44 @@ describe('supersededOnlyByOwnStartupFallback', () => {
it('still supersedes the flow after a later user auth change', () => {
expect(
supersededOnlyByOwnStartupFallback({
- epochAtStart: 7,
+ flowEpoch: 8,
currentEpoch: 9,
- startupFallbackEpoch: 8,
+ startupFallback: { from: 7, to: 8 },
}),
).toBe(true);
});
+ 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);
+ });
+
+ 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 treat an unrelated change as the flow\'s own fallback', () => {
expect(
supersededOnlyByOwnStartupFallback({
- epochAtStart: 7,
+ flowEpoch: 7,
currentEpoch: 8,
- startupFallbackEpoch: null,
+ startupFallback: null,
}),
).toBe(true);
});
@@ -218,9 +243,9 @@ describe('supersededOnlyByOwnStartupFallback', () => {
it('reports no supersession while the epoch is unchanged', () => {
expect(
supersededOnlyByOwnStartupFallback({
- epochAtStart: 7,
+ flowEpoch: 7,
currentEpoch: 7,
- startupFallbackEpoch: null,
+ startupFallback: null,
}),
).toBe(false);
});
diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.ts
index 96b2091538..877bb1497f 100644
--- a/apps/desktop/src/main/authManager.ts
+++ b/apps/desktop/src/main/authManager.ts
@@ -2491,6 +2491,8 @@ async function withAccountFreeOwnerCommit(opts: {
authAlreadyCleared?: boolean;
validateBeforeCommit?: () => boolean;
shouldClearOnFailure?: () => boolean;
+ /** 本次收敛是冷启动启动闸超时兜底;转发给 clearAuth 以便同步登记兜底代际。 */
+ coldStartTimeoutRecovery?: boolean;
}): Promise<void> {
let authCleared = opts.authAlreadyCleared ?? false;
let releaseBoundary: (() => void) | null = null;
@@ -2517,6 +2519,7 @@ async function withAccountFreeOwnerCommit(opts: {
preservePersistedRefreshToken: true,
credentialStoreUnavailable: opts.credentialStoreUnavailable,
deferSessionCommit: true,
+ coldStartTimeoutRecovery: opts.coldStartTimeoutRecovery,
});
authCleared = true;
}
@@ -2566,6 +2569,7 @@ async function withAccountFreeOwnerCommit(opts: {
preservePersistedRefreshToken: opts.preservePersistedRefreshToken,
credentialStoreUnavailable: opts.credentialStoreUnavailable,
deferSessionCommit: true,
+ coldStartTimeoutRecovery: opts.coldStartTimeoutRecovery,
});
authCleared = true;
}
@@ -2590,6 +2594,7 @@ async function withAccountFreeOwnerCommit(opts: {
preservePersistedRefreshToken: opts.preservePersistedRefreshToken,
credentialStoreUnavailable: opts.credentialStoreUnavailable,
deferSessionCommit: true,
+ coldStartTimeoutRecovery: opts.coldStartTimeoutRecovery,
});
authCleared = true;
}
@@ -2620,6 +2625,11 @@ async function recoverAccountFreeOwnerAtStartup(
mode: Extract<AppSessionMode, 'signed-out' | 'local'>,
reason: string,
credentialStoreUnavailable = false,
+ /**
+ * 本次收敛是冷启动启动闸超时兜底。必须由调用方显式声明并透传到 clearAuth:
+ * 兜底代际要在推进代际的同一同步时刻登记,不能等本函数返回(PR #6273 review P1)。
+ */
+ opts: { coldStartTimeoutRecovery?: boolean } = {},
): Promise<void> {
const ownerId = mode === 'local' ? LOCAL_DATA_OWNER_ID : null;
if (isGhostSkillProjectionBoundaryStableForOwner(ownerId)) {
@@ -2641,6 +2651,7 @@ async function recoverAccountFreeOwnerAtStartup(
notify: false,
clearOnFailure: mode === 'signed-out',
preservePersistedRefreshToken: true,
+ coldStartTimeoutRecovery: opts.coldStartTimeoutRecovery,
});
}
@@ -3165,14 +3176,15 @@ const COLD_START_AUTH_GATE_TIMEOUT_MS = 20_000;
let authStateEpoch = 0;
/**
- * 启动闸超时兜底(`cold-start-timeout-recovery`)自己推进到的 authStateEpoch。
+ * 启动闸超时兜底(`cold-start-timeout-recovery`)自己造成的代际推进:从 `from`
+ * 推到 `to`,在 clearAuth 推进代际的**同一同步时刻**记录。
*
- * 该兜底是冷启动流程自己的安全网,不是用户动作,但它同样会推进 authStateEpoch。
- * 把这个代际记下来,让同一轮冷启动的 refresh 迟到成功时不被误判成「用户改过登录态」
- * 而丢弃(token 已轮换,丢弃就等于每次启动都回落登录页)。
+ * 记成一对(而不是只记新代际)才能把豁免绑定到「这次兜底」:冷启动流程只在自己
+ * 当前代际等于 `from` 且现值为 `to` 时被豁免。若用户在该兜底之前已经显式登录过,
+ * 兜底的 `from` 就不等于流程起始代际,旧流程仍被正常作废(不会反过来覆盖新登录)。
* 见 authStartupGate 的 supersededOnlyByOwnStartupFallback。
*/
-let coldStartTimeoutFallbackEpoch: number | null = null;
+let coldStartTimeoutFallback: { from: number; to: number } | null = null;
/**
* 登录态落地后异步同步灰度标记,不阻塞 renderer 进入主界面。
@@ -3679,10 +3691,24 @@ function clearAuth(
* namespace during teardown.
*/
deferSessionCommit?: boolean;
+ /**
+ * 本次清理是冷启动启动闸超时的兜底(不是用户动作)。为 true 时在**推进代际的
+ * 同一同步时刻**记下该代际,让触发兜底的冷启动流程即使在本函数外层还没返回、
+ * 锁还没释放时也能认出「这一代是我自己的兜底」而不是用户改过登录态。
+ * 见 authStartupGate 的 supersededOnlyByOwnStartupFallback。
+ */
+ coldStartTimeoutRecovery?: boolean;
} = {},
): void {
const notify = opts.notify ?? true;
+ const epochBeforeClear = authStateEpoch;
authStateEpoch += 1; // 迟到的冷启动流程从此作废(见 authStateEpoch 注释)
+ // 必须与上一行同步记录:兜底流程外层还有 await commit / 释放锁 / 多层异步返回,
+ // 期间并发的刷新已经能看到新代际;若等到外层返回才登记,它仍会被误判为
+ // 「用户改过登录态」而丢弃(PR #6273 review P1)。
+ if (opts.coldStartTimeoutRecovery) {
+ coldStartTimeoutFallback = { from: epochBeforeClear, to: authStateEpoch };
+ }
refreshBackoff.clear();
loginFlowEpoch += 1;
// Explicit logout clears health. Failed startup keeps its recovery reason
@@ -4697,12 +4723,9 @@ export async function initialize(options: AuthInitializeOptions = {}): Promise<A
await ownerChangeShellGate.waitForSettled();
return snapshotAuthState();
}
- await recoverAccountFreeOwnerAtStartup('signed-out', 'cold-start-timeout-recovery');
- // This fallback is the cold-start flow's own safety net, not a user auth
- // action. Record the epoch it raised so the still-running refresh — which
- // already rotated a valid token — can still publish its result instead of
- // being discarded as "superseded by manual auth change".
- coldStartTimeoutFallbackEpoch = authStateEpoch;
+ await recoverAccountFreeOwnerAtStartup('signed-out', 'cold-start-timeout-recovery', false, {
+ coldStartTimeoutRecovery: true,
+ });
return snapshotLoggedOutAuthState();
},
onLateResult: (state) =>
@@ -4731,14 +4754,24 @@ async function runColdStartRefreshFlow(
const attemptedOwnershipTokens = new Set(ownershipRecovery.attemptedTokens);
attemptedOwnershipTokens.add(storedToken);
const epochAtStart = authStateEpoch;
+ /**
+ * 本流程当前认可的代际。接受「自己的启动闸超时兜底」后前移到兜底那一代:
+ * 提交后的灰度/组织默认同步必须用这个代际,否则本次恢复登录会被自己的兜底
+ * 判成 stale-auth 而跳过同步(PR #6273 review P2);之后任何真实用户动作仍会
+ * 再次推进代际,继续正确作废这些任务。
+ */
+ let flowAuthEpoch = epochAtStart;
const epochChanged = (point: string): boolean => {
if (
!supersededOnlyByOwnStartupFallback({
- epochAtStart,
+ flowEpoch: flowAuthEpoch,
currentEpoch: authStateEpoch,
- startupFallbackEpoch: coldStartTimeoutFallbackEpoch,
+ startupFallback: coldStartTimeoutFallback,
})
) {
+ // 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;
return false;
}
log.warn(
@@ -4746,7 +4779,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.
- coldStartTimeoutFallbackEpoch = null;
+ coldStartTimeoutFallback = null;
return true;
};
@@ -4959,13 +4992,17 @@ async function runColdStartRefreshFlow(
},
});
await migrateLocalProviderBindingsAfterCloudCommit(refreshData.membership.id);
+ // Schedule with the epoch this flow actually commits under (flowAuthEpoch, which
+ // moves forward when the flow accepts its own startup-gate fallback) — passing the
+ // original epochAtStart would make these tasks treat a recovery login as stale-auth
+ // and skip the canary flag / org beta sync (PR #6273 review P2).
scheduleCanaryFlagSync({
token: refreshData.accessToken,
- expectedAuthEpoch: epochAtStart,
+ expectedAuthEpoch: flowAuthEpoch,
expectedUserId: refreshData.membership.id,
});
scheduleXdOrgBetaDefault({
- expectedAuthEpoch: epochAtStart,
+ expectedAuthEpoch: flowAuthEpoch,
expectedUserId: refreshData.membership.id,
});
scheduleRefresh(refreshData.accessToken);
diff --git a/apps/desktop/src/main/authStartupGate.ts b/apps/desktop/src/main/authStartupGate.ts
index dae5120c91..d9bfbb9beb 100644
--- a/apps/desktop/src/main/authStartupGate.ts
+++ b/apps/desktop/src/main/authStartupGate.ts
@@ -85,19 +85,32 @@ export async function awaitWithStartupTimeout<T>(
* authStateEpoch,于是流程稍后**成功**(token 已轮换并落盘)时,`epochChanged`
* 把它误判为「用户改过登录态」而整体丢弃:进程停在未登录,每次启动都重现。
*
- * 只有「当前代际恰好等于兜底记下的那一代」才豁免;之后任何用户登录/登出都会再
- * 推进一次代际,流程重新被正常作废(旧 token family 已被新登录取代)。
+ * 豁免必须绑定到「这次兜底造成的那一次代际推进」,因此比对的是
+ * `startupFallback` 的 from/to 转换,而不是「当前代际恰好等于某个记录值」:
+ *
+ * - 流程当前代际 == from 且现值 == to → 只可能是这次兜底,豁免;
+ * - 用户在兜底之前已显式登录过 → 兜底的 from 不等于流程起始代际,照常作废,
+ * 旧流程不会反过来覆盖新登录;
+ * - 连续两次兜底 → 流程接受第一次后代际前移到 to,第二次的 from 正好等于它,
+ * 仍然豁免,不会因为多推进一次就误伤。
+ *
+ * 之后任何用户登录/登出都会再推进一次代际,流程重新被正常作废(旧 token family
+ * 已被新登录取代)。
*/
export function supersededOnlyByOwnStartupFallback(input: {
- /** 流程开跑时快照的代际。 */
- epochAtStart: number;
+ /** 流程当前认可的代际(接受过自己的兜底后会前移)。 */
+ flowEpoch: number;
/** 当前的 authStateEpoch。 */
currentEpoch: number;
- /** 启动闸超时兜底自己推进到的代际;未发生兜底时为 null。 */
- startupFallbackEpoch: number | null;
+ /** 兜底自己造成的那次代际推进;未发生兜底时为 null。 */
+ startupFallback: { from: number; to: number } | null;
}): boolean {
- if (input.currentEpoch === input.epochAtStart) return false;
- return input.startupFallbackEpoch === null || input.currentEpoch !== input.startupFallbackEpoch;
+ if (input.currentEpoch === input.flowEpoch) return false;
+ const fallback = input.startupFallback;
+ if (fallback && input.flowEpoch === fallback.from && input.currentEpoch === fallback.to) {
+ return false;
+ }
+ return true;
}
/**