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): 冷启动超时兜底不再作废自己已成功的登录刷新

CHEYAN16d0e8d631e5
diff --git a/apps/desktop/src/main/__tests__/authLoginFlowReset.contract.test.ts b/apps/desktop/src/main/__tests__/authLoginFlowReset.contract.test.ts
index a5583f6482..bb7813b257 100644
--- a/apps/desktop/src/main/__tests__/authLoginFlowReset.contract.test.ts
+++ b/apps/desktop/src/main/__tests__/authLoginFlowReset.contract.test.ts
@@ -889,6 +889,37 @@ describe('auth login-flow reset', () => {
expect(getLoginBody).toContain('mapLoginProvidersLoadFailure(error)');
});
+ it('does not run the signed-out timeout recovery while a cloud owner transition is already pending', () => {
+ 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')");
+ 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))
+ .toBeGreaterThan(timeoutRecovery);
+ });
+
+ 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,');
+ // 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');
+ expect(exemption).toBeGreaterThan(-1);
+ expect(warn).toBeGreaterThan(exemption);
+ });
+
it('drops a runtime refresh result after logout or a newer login changes auth generation', () => {
const refreshStart = source.indexOf('export async function refresh(');
const refreshEnd = source.indexOf('\n}\n\nexport async function logout()', refreshStart);
diff --git a/apps/desktop/src/main/__tests__/authStartupGate.test.ts b/apps/desktop/src/main/__tests__/authStartupGate.test.ts
index 174e822a80..f93f53f63b 100644
--- a/apps/desktop/src/main/__tests__/authStartupGate.test.ts
+++ b/apps/desktop/src/main/__tests__/authStartupGate.test.ts
@@ -16,6 +16,7 @@ import {
awaitLoginProvidersWithPreparingGate,
awaitWithStartupTimeout,
mapLoginProvidersLoadFailure,
+ supersededOnlyByOwnStartupFallback,
} from '../authStartupGate';
describe('awaitWithStartupTimeout', () => {
@@ -183,6 +184,48 @@ describe('awaitWithStartupTimeout', () => {
});
});
+describe('supersededOnlyByOwnStartupFallback', () => {
+ it('keeps a cold-start flow alive when only its own timeout fallback advanced the epoch', () => {
+ expect(
+ supersededOnlyByOwnStartupFallback({
+ epochAtStart: 7,
+ currentEpoch: 8,
+ startupFallbackEpoch: 8,
+ }),
+ ).toBe(false);
+ });
+
+ it('still supersedes the flow after a later user auth change', () => {
+ expect(
+ supersededOnlyByOwnStartupFallback({
+ epochAtStart: 7,
+ currentEpoch: 9,
+ startupFallbackEpoch: 8,
+ }),
+ ).toBe(true);
+ });
+
+ it('does not treat an unrelated change as the flow\'s own fallback', () => {
+ expect(
+ supersededOnlyByOwnStartupFallback({
+ epochAtStart: 7,
+ currentEpoch: 8,
+ startupFallbackEpoch: null,
+ }),
+ ).toBe(true);
+ });
+
+ it('reports no supersession while the epoch is unchanged', () => {
+ expect(
+ supersededOnlyByOwnStartupFallback({
+ epochAtStart: 7,
+ currentEpoch: 7,
+ startupFallbackEpoch: null,
+ }),
+ ).toBe(false);
+ });
+});
+
describe('awaitLoginProvidersWithPreparingGate', () => {
beforeEach(() => {
vi.useFakeTimers();
diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.ts
index 2384fa5d94..96b2091538 100644
--- a/apps/desktop/src/main/authManager.ts
+++ b/apps/desktop/src/main/authManager.ts
@@ -65,6 +65,7 @@ import {
awaitLoginProvidersWithPreparingGate,
awaitWithStartupTimeout,
mapLoginProvidersLoadFailure,
+ supersededOnlyByOwnStartupFallback,
} from './authStartupGate';
import { syncCanaryFlagAfterAuth } from './canaryFlagSync';
import {
@@ -3163,6 +3164,16 @@ const COLD_START_AUTH_GATE_TIMEOUT_MS = 20_000;
*/
let authStateEpoch = 0;
+/**
+ * 启动闸超时兜底(`cold-start-timeout-recovery`)自己推进到的 authStateEpoch。
+ *
+ * 该兜底是冷启动流程自己的安全网,不是用户动作,但它同样会推进 authStateEpoch。
+ * 把这个代际记下来,让同一轮冷启动的 refresh 迟到成功时不被误判成「用户改过登录态」
+ * 而丢弃(token 已轮换,丢弃就等于每次启动都回落登录页)。
+ * 见 authStartupGate 的 supersededOnlyByOwnStartupFallback。
+ */
+let coldStartTimeoutFallbackEpoch: number | null = null;
+
/**
* 登录态落地后异步同步灰度标记,不阻塞 renderer 进入主界面。
*
@@ -4678,7 +4689,20 @@ export async function initialize(options: AuthInitializeOptions = {}): Promise<A
// A signed-out fallback is not safe until the shared Ghost projection
// has been swept. Otherwise the previous cloud owner's links remain
// available to local/anonymous Agent processes during a slow refresh.
+ // The refresh may already have crossed into its owner teardown while the
+ // startup deadline fires. Wait for that boundary to settle first: starting
+ // signed-out recovery concurrently would invalidate the successful refresh
+ // and make every subsequent launch appear logged out.
+ if (ownerChangeShellGate.isPending()) {
+ 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;
return snapshotLoggedOutAuthState();
},
onLateResult: (state) =>
@@ -4708,10 +4732,21 @@ async function runColdStartRefreshFlow(
attemptedOwnershipTokens.add(storedToken);
const epochAtStart = authStateEpoch;
const epochChanged = (point: string): boolean => {
- if (authStateEpoch === epochAtStart) return false;
+ if (
+ !supersededOnlyByOwnStartupFallback({
+ epochAtStart,
+ currentEpoch: authStateEpoch,
+ startupFallbackEpoch: coldStartTimeoutFallbackEpoch,
+ })
+ ) {
+ return false;
+ }
log.warn(
`cold-start refresh flow superseded by manual auth change (${point}) — discarding late result`,
);
+ // 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;
return true;
};
diff --git a/apps/desktop/src/main/authStartupGate.ts b/apps/desktop/src/main/authStartupGate.ts
index 24bc9b8dbb..dae5120c91 100644
--- a/apps/desktop/src/main/authStartupGate.ts
+++ b/apps/desktop/src/main/authStartupGate.ts
@@ -77,6 +77,29 @@ export async function awaitWithStartupTimeout<T>(
}
}
+/**
+ * 判断冷启动 refresh 流程的迟到结果是否「只被它自己的启动闸超时兜底」超越。
+ *
+ * 背景(2026-10-17 实机):splash 的启动闸超时后,兜底路径会把 owner 收敛回
+ * signed-out —— 那是流程自己的安全网,不是用户手动登录/登出。但它同样推进了
+ * authStateEpoch,于是流程稍后**成功**(token 已轮换并落盘)时,`epochChanged`
+ * 把它误判为「用户改过登录态」而整体丢弃:进程停在未登录,每次启动都重现。
+ *
+ * 只有「当前代际恰好等于兜底记下的那一代」才豁免;之后任何用户登录/登出都会再
+ * 推进一次代际,流程重新被正常作废(旧 token family 已被新登录取代)。
+ */
+export function supersededOnlyByOwnStartupFallback(input: {
+ /** 流程开跑时快照的代际。 */
+ epochAtStart: number;
+ /** 当前的 authStateEpoch。 */
+ currentEpoch: number;
+ /** 启动闸超时兜底自己推进到的代际;未发生兜底时为 null。 */
+ startupFallbackEpoch: number | null;
+}): boolean {
+ if (input.currentEpoch === input.epochAtStart) return false;
+ return input.startupFallbackEpoch === null || input.currentEpoch !== input.startupFallbackEpoch;
+}
+
/**
* 登录准备态(「正在连接登录服务」)最多阻塞 UI 的时长。getProviders 走
* CindyAuthClient 默认 15s AbortController,但黑洞 / captive-portal 下 Electron