Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(auth): allow leaving login while provider requests are pending
Dash841fa7c30f9c
diff --git a/apps/desktop/src/main/__tests__/authLoginBack.test.ts b/apps/desktop/src/main/__tests__/authLoginBack.test.tsnew file mode 100644index 0000000000..e5ed8a0616--- /dev/null+++ b/apps/desktop/src/main/__tests__/authLoginBack.test.ts@@ -0,0 +1,128 @@+import { readFileSync } from 'node:fs';+import { ScriptTarget, transpileModule } from 'typescript';+import { AuthApiError, reduceAuthFlow, type ProviderConfig } from '@cindy/auth-client';+import { describe, expect, it, vi } from 'vitest';+import { loginPreparingErrorState, parseDesktopLoginAction } from '../../shared/authIpc';++// Exercise production flow functions without initializing Electron or credentials.+const source = readFileSync(new URL('../authManager.ts', import.meta.url), 'utf8');+function functionSource(start: string, end: string): string {+ const offset = source.indexOf(start);+ return source+ .slice(offset, source.indexOf(end, offset))+ .replaceAll('export async function', 'async function');+}++const providers: ProviderConfig = {+ region: 'global',+ attribution: 'email',+ email: true,+ phone: false,+ social: ['google'],+};++function deferred<T>() {+ let resolve!: (value: T) => void;+ let reject!: (error: unknown) => void;+ const promise = new Promise<T>((yes, no) => {+ resolve = yes;+ reject = no;+ });+ return { promise, resolve, reject };+}++function setup({ cached = false, sealed = false } = {}) {+ const getProviders = vi.fn<() => Promise<ProviderConfig>>();+ const cancelActive = vi.fn();+ const deps = {+ AuthApiError,+ reduceAuthFlow,+ parseDesktopLoginAction,+ loginPreparingErrorState,+ createAuthClient: () => ({ getProviders }),+ awaitLoginProvidersWithPreparingGate: (promise: Promise<ProviderConfig>) => promise,+ browserAuthorizationSlot: { cancelActive },+ isLoginFlowCommitSealed: () => sealed,+ log: { warn: vi.fn() },+ cachedProviders: cached ? providers : null,+ };+ const compiled = transpileModule(+ `+ let loginFlowEpoch = 1, loginFlowState = { step: 'error', code: 'REQUEST_TIMEOUT', recoverTo: 'identifier' };+ let providerConfig = cachedProviders, sessionInvalidationPromise = null;+ let loginActionPromise = null, loginActionPromiseEpoch = null, accessToken = null;+ const AUTH_REGION = 'global', activeAuthRealm = 'global';+ const credentialStoreHealth = { unavailable: false };+ let handledLoginEmail = null, pendingPersonalLogin = null, discoveredMethods = [];+ let pendingAccountToken = null, pendingAccountRefreshToken = null, pendingAccountMemberships = [];+ let pendingLoginTicket = 'old-ticket', pendingBindTicket = null, pendingSsoVerificationTicket = null;+ let pendingAuthRealm = null, pendingAccountDeletionRestored = false;+ ${functionSource('function resetLoginFlowState()', 'function sealLoginFlowCommit(')}+ ${functionSource('async function loadLoginProviders(', 'async function discoverOrganizationRealm(')}+ ${functionSource('async function runLoginAction(', 'export async function refresh(')}+ return {+ dispatch: dispatchLoginAction,+ snapshot: () => ({ state: loginFlowState, ticket: pendingLoginTicket, epoch: loginFlowEpoch }),+ };+ `,+ { compilerOptions: { target: ScriptTarget.ES2022 } },+ ).outputText;+ return {+ ...new Function(...Object.keys(deps), compiled)(...Object.values(deps)),+ getProviders,+ cancelActive,+ };+}++describe('login Back without an auth-server round trip', () => {+ it.each([false, true])(+ 'returns locally and clears private progress (cached=%s)',+ async (cached) => {+ const main = setup({ cached });+ const result = await main.dispatch({ type: 'back' });+ expect(result).toEqual({+ success: true,+ state: cached ? { step: 'identifier', providers } : { step: 'entry' },+ });+ expect(main.getProviders).not.toHaveBeenCalled();+ expect(main.snapshot().ticket).toBeNull();+ expect(main.snapshot().epoch).toBe(2);+ expect(main.cancelActive).toHaveBeenCalledOnce();+ },+ );++ it.each(['resolve', 'reject'] as const)(+ 'abandons a retry and ignores its late %s',+ async (settle) => {+ const main = setup();+ const old = deferred<ProviderConfig>();+ main.getProviders.mockReturnValueOnce(old.promise);+ const retry = main.dispatch({ type: 'reset' });+ expect(await main.dispatch({ type: 'back' })).toEqual({+ success: true,+ state: { step: 'entry' },+ });+ const next = deferred<ProviderConfig>();+ main.getProviders.mockReturnValueOnce(next.promise);+ const nextRetry = main.dispatch({ type: 'reset' });+ if (settle === 'resolve') old.resolve(providers);+ else old.reject(new AuthApiError('REQUEST_TIMEOUT', 0, 'timeout'));+ expect(await retry).toMatchObject({ success: false, code: 'AUTH_FLOW_SUPERSEDED' });+ expect(main.snapshot().state).toBeNull();+ expect(await main.dispatch({ type: 'reset' })).toMatchObject({ code: 'LOGIN_BUSY' });+ next.resolve(providers);+ expect(await nextRetry).toEqual({ success: true, state: { step: 'identifier', providers } });+ expect(main.getProviders).toHaveBeenCalledTimes(2);+ },+ );++ it('does not interrupt an accepted credential commit', async () => {+ const main = setup({ sealed: true });+ expect(await main.dispatch({ type: 'back' })).toMatchObject({+ success: false,+ code: 'LOGIN_BUSY',+ });+ expect(main.snapshot().epoch).toBe(1);+ expect(main.cancelActive).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.tsindex cabdefecf4..ae9d070cfd 100644--- a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts+++ b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts@@ -120,7 +120,8 @@ describe('auth login-flow reset', () => {const discoveryBody = source.slice(discoveryStart, source.indexOf('\n}', discoveryStart));expect(discoveryBody).toContain('pendingAuthRealm = null;');- const actionStart = source.indexOf('async function runLoginAction(action: DesktopLoginAction)');+ const actionStart = source.indexOf('async function runLoginAction(');+ expect(actionStart).toBeGreaterThan(-1);const actionPreamble = source.slice(actionStart,source.indexOf('const stateBeforeAction', actionStart),@@ -449,7 +450,8 @@ describe('auth login-flow reset', () => {});it('invalidates pending add-account actions without cancelling an accepted login commit', () => {- const runStart = source.indexOf('async function runLoginAction(action: DesktopLoginAction)');+ const runStart = source.indexOf('async function runLoginAction(');+ expect(runStart).toBeGreaterThan(-1);const runEnd = source.indexOf('\n}\n\nexport async function dispatchLoginAction', runStart);const runBody = source.slice(runStart, runEnd);expect(runBody).toContain('const actionLoginFlowEpoch = loginFlowEpoch;');diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.tsindex c080f496b6..3626ab41a5 100644--- a/apps/desktop/src/main/authManager.ts+++ b/apps/desktop/src/main/authManager.ts@@ -408,7 +408,8 @@ function isOwnerChangeShellPending(): boolean {*/const deviceId = process.env.XDT_DEVICE_ID_OVERRIDE?.trim() || machineIdSync();-let loginFlowState: DesktopLoginState | null = null;+// The offline entry is a renderer landing page, not an auth-server flow step.+let loginFlowState: Exclude<DesktopLoginState, { step: 'entry' }> | null = null;let providerConfig: ProviderConfig | null = null;let discoveredMethods: LoginMethod[] = [];// These live only within the current fresh-login flow; no credentials reach Renderer.@@ -5279,7 +5280,9 @@ async function finishFreshLogin(return completeLogin(outcome, expectedLoginFlowEpoch);}-async function runLoginAction(action: DesktopLoginAction): Promise<DesktopLoginActionResult> {+async function runLoginAction(+ action: Exclude<DesktopLoginAction, { type: 'back' }>,+): Promise<DesktopLoginActionResult> {const actionLoginFlowEpoch = loginFlowEpoch;const startsBuildRealmFlow =action.type === 'discover' ||@@ -5685,6 +5688,23 @@ export async function dispatchLoginAction(action: unknown): Promise<DesktopLoginif (!parsedAction) {return { success: false, code: 'INVALID_AUTH_ACTION', state: loginFlowState };}+ if (parsedAction.type === 'back') {+ // Navigation must not wait for the provider request it is abandoning.+ // Keep an accepted credential commit atomic, just like cancelAddAccountLogin.+ if (isLoginFlowCommitSealed(loginFlowEpoch)) {+ return { success: false, code: 'LOGIN_BUSY', state: loginFlowState };+ }+ const providers = providerConfig;+ loginFlowEpoch += 1;+ browserAuthorizationSlot.cancelActive();+ resetLoginFlowState();+ if (providers) {+ providerConfig = providers;+ loginFlowState = reduceAuthFlow(null, { type: 'providers-loaded', providers });+ return { success: true, state: loginFlowState };+ }+ return { success: true, state: { step: 'entry' } };+ }if (parsedAction.type === 'cancel-browser') {const pendingAction = loginActionPromiseEpoch === loginFlowEpoch ? loginActionPromise : null;const cancelled = browserAuthorizationSlot.cancelActive();diff --git a/apps/desktop/src/renderer/components/login/LoginPage.tsx b/apps/desktop/src/renderer/components/login/LoginPage.tsxindex ff0fdfc06a..bdce35fd4b 100644--- a/apps/desktop/src/renderer/components/login/LoginPage.tsx+++ b/apps/desktop/src/renderer/components/login/LoginPage.tsx@@ -149,6 +149,8 @@ export function LoginPage({(loginState?.step === 'error' && loginState.code === 'RATE_LIMITED'));const handoff = useLoginHandoff();const isAddAccount = intent === 'add-account';+ const canLeaveProviderLoad =+ !loginState || loginState.step === 'error' || loginState.step === 'entry';const accountListRef = useRef<HTMLDivElement>(null);const accountCount = loginState?.step === 'account-selection' ? loginState.accounts.length : 0;@@ -188,7 +190,7 @@ export function LoginPage({* 在会话切过去之后落,不能由 requireConsent 提前落(竞态原因见那里的注释)。*/const openLocalMode = async () => {- if (isLoading || localModePendingRef.current || !enterLocalMode) return;+ if ((isLoading && !canLeaveProviderLoad) || localModePendingRef.current || !enterLocalMode) return;markLocalModeTransition(true);try {// 必须走 AuthContext.enterLocalMode():它调同一条 IPC,并用返回值立刻改@@ -281,7 +283,11 @@ export function LoginPage({}pendingConsentAction.current = {action,- stamp: makeConsentStamp(loginState?.step, isLoading, loginState?.step === 'completed'),+ stamp: makeConsentStamp(+ loginState?.step,+ isLoading && !(deferConsentPersist && canLeaveProviderLoad),+ loginState?.step === 'completed',+ ),deferConsentPersist,};setConsentDialogOpen(true);@@ -299,7 +305,11 @@ export function LoginPage({if (!pending?.deferConsentPersist) persistPrivacyConsent();if (!pending) return;// 复验:弹窗期间 auth 状态被异步推进(登录完成/步骤切换/in-flight)则丢弃动作- const current = makeConsentStamp(loginState?.step, isLoading, loginState?.step === 'completed');+ const current = makeConsentStamp(+ loginState?.step,+ isLoading && !(pending.deferConsentPersist && canLeaveProviderLoad),+ loginState?.step === 'completed',+ );if (canResumePendingConsent(pending.stamp, current)) pending.action();};const dismissConsent = () => {@@ -334,9 +344,9 @@ export function LoginPage({return () => reportLoginPanelUnmounted();}, [reportLoginPanelMounted, reportLoginPanelUnmounted]);// 「跳过登录」常驻入口在面板内(identifier 视图 SKIP_ENTRY 文字链);footer 仅保留- // error 步的逃生入口——登录服务不可用时用户仍能进入本地模式(既有产品保证)。+ // 准备态、离线入口和 error 步的逃生入口,不依赖登录服务恢复。const showLocalModeFooter =- !isAddAccount && loginState?.step === 'error' && !credentialStoreFailed;+ !isAddAccount && canLeaveProviderLoad && !credentialStoreFailed;// 面板底部预留恒取全流程最大值(footer 124;协议行 48 被其覆盖):step 切换时// 面板/品牌层零跳位(规则 7,codex 审查 P1)。browser-redirect/completed 维持 0,// 与迁移前 main 口径一致(该两步由品牌 overlay/跳转态接管)。@@ -1250,15 +1260,47 @@ export function LoginPage({};const renderContent = (): { node: ReactNode; ssoOrgGroupY: boolean } => {+ const backToEntry = () => {+ if (localModePendingRef.current) return;+ setCredentialHelpOpen(false);+ clearError();+ setIdentifierFormatError(null);+ if (isAddAccount && onClose) onClose();+ else void dispatch({ type: 'back' });+ };+ if (loginState?.step === 'entry') {+ // No provider config has arrived yet. Offer an explicit retry without+ // inventing server-enabled login methods or automatically starting a load.+ return {+ ssoOrgGroupY: false,+ node: (+ <LoginPanel testId="login-panel-entry">+ {isLoading && (+ <LoginBackButton+ label={t('login.back')}+ disabled={localModePending}+ onClick={backToEntry}+ />+ )}+ <LoginTitleBlock title={t('login.title')} subtitle={t('login.subtitle')} />+ <LoginPrimaryButton loading={isLoading} onClick={reset} testId="login-entry-continue">+ {t(isLoading ? 'login.working' : 'login.continue')}+ </LoginPrimaryButton>+ </LoginPanel>+ ),+ };+ }// preparing 伪态(loginState 尚未就绪;figma 5.2 准备态:loading 64 @(308,193))if (!loginState) {return {ssoOrgGroupY: false,node: (<LoginPanel testId="login-panel-preparing">- {isAddAccount && onClose ? (- <LoginBackButton label={t('login.back')} onClick={onClose} />- ) : null}+ <LoginBackButton+ label={t('login.back')}+ disabled={localModePending}+ onClick={backToEntry}+ /><LoginTitleBlock title={t('login.preparing')} subtitle={t('login.preparingSubtitle')} /><LoginLoadingRing y={LOADING_RING.yPreparing} label={t('login.working')} /></LoginPanel>@@ -1269,19 +1311,25 @@ export function LoginPage({// A rate limit can cover a still-valid form. Dismiss only the notice:// resetting main's flow would discard its ticket and require another code.const resumeForm = rateLimited && loginState.step !== 'error';- const returnFromError = resumeForm- ? () => {- if (localModePendingRef.current) return;- setCredentialHelpOpen(false);- clearError();- }- : reset;+ const returnFromError = () => {+ if (localModePendingRef.current) return;+ if (isAddAccount && onClose) {+ backToEntry();+ } else if (credentialStoreFailed) {+ reset();+ } else if (resumeForm) {+ setCredentialHelpOpen(false);+ clearError();+ } else {+ backToEntry();+ }+ };return {ssoOrgGroupY: false,node: (<LoginPanel testId="login-panel-error"><LoginBackButton- disabled={isLoading || localModePending}+ disabled={localModePending || (credentialStoreFailed && isLoading && !isAddAccount)}label={t('login.back')}onClick={returnFromError}/>@@ -1304,7 +1352,7 @@ export function LoginPage({{(credentialStoreFailed || rateLimited) && (<LoginTextLinkdisabled={isLoading}- onClick={returnFromError}+ onClick={resumeForm ? returnFromError : reset}testId="login-credential-recheck">{t(resumeForm ? 'login.back' : 'credentialStore.recheck')}@@ -1395,7 +1443,7 @@ export function LoginPage({<buttondata-testid="login-local-mode"type="button"- disabled={localModePending || isLoading}+ disabled={localModePending}// error 步逃生入口与面板内文字按钮同口径:过协议门(2026-07-29 拍板)onClick={() => requireConsent(() => void openLocalMode(), { deferConsentPersist: true })}aria-describedby="login-local-mode-description"diff --git a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.browserRedirect.test.tsx b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.browserRedirect.test.tsxindex 6853e4eb46..47437f1f6e 100644--- a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.browserRedirect.test.tsx+++ b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.browserRedirect.test.tsx@@ -145,7 +145,7 @@ describe('LoginPage browser redirect waiting state', () => {expect(screen.queryByRole('button', { name: 'sidebar.accountSwitcher.title' })).toBeNull();});- it('disables local entry while a login request is pending', () => {+ it('keeps local entry available while a provider retry is pending', () => {loginHook.value = {isLoading: true,errorCode: null,@@ -158,6 +158,6 @@ describe('LoginPage browser redirect waiting state', () => {expect((screen.getByRole('button', { name: 'login.localModeEntry' }) as HTMLButtonElement).disabled,- ).toBe(true);+ ).toBe(false);});});diff --git a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.consent.test.tsx b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.consent.test.tsxindex bf1a17922d..7fe720325b 100644--- a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.consent.test.tsx+++ b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.consent.test.tsx@@ -374,8 +374,8 @@ describe('consent guard(未勾选拦截个人登录链路)', () => {recoverTo: 'identifier',} as unknown as AuthFlowState;- it('error 步逃生入口未勾选 → 弹协议弹窗;同意 → 进本地模式并写同意记录', async () => {- mount(errorState, { errorCode: 'NETWORK_ERROR' });+ it.each([false, true])('error 步逃生入口过协议门后进入本地模式(请求等待=%s)', async (isLoading) => {+ mount(errorState, { errorCode: 'NETWORK_ERROR', isLoading });await act(async () => {fireEvent.click(screen.getByTestId('login-local-mode'));});diff --git a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.harness.test.tsx b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.harness.test.tsxindex eda100a850..9fee813cc1 100644--- a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.harness.test.tsx+++ b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.harness.test.tsx@@ -147,13 +147,13 @@ describe('error screen recovery', () => {recoverTo: 'identifier',};- it('does not dispatch a second reset while sign-in is loading', () => {+ it('allows back navigation without another reset while sign-in is loading', () => {mount(errorState, { isLoading: true });const back = screen.getByRole('button', { name: 'login.back' }) as HTMLButtonElement;- expect(back.disabled).toBe(true);+ expect(back.disabled).toBe(false);fireEvent.click(back);- expect(loginHook.value.dispatch).not.toHaveBeenCalled();+ expect(loginHook.value.dispatch).toHaveBeenCalledExactlyOnceWith({ type: 'back' });});});@@ -597,7 +597,10 @@ describe('method-choice(附录 A sso 场景)', () => {describe('preparing 伪态', () => {it('loginState 未就绪 → preparing 面板 + 64 loading 环 @(308,193)', () => {mount(null);- expect(screen.queryByTestId('login-back-button')).toBeNull();+ expect((screen.getByTestId('login-back-button') as HTMLButtonElement).disabled).toBe(false);+ expect((screen.getByTestId('login-local-mode') as HTMLButtonElement).disabled).toBe(false);+ fireEvent.click(screen.getByTestId('login-back-button'));+ expect(loginHook.value.dispatch).toHaveBeenCalledWith({ type: 'back' });expect(screen.getByTestId('login-panel-preparing')).toBeTruthy();expect(screen.getByText('login.preparing')).toBeTruthy();expect(screen.getByText('login.preparingSubtitle')).toBeTruthy();diff --git a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.initialization.test.tsx b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.initialization.test.tsxindex d90b3cbae8..6026ab216c 100644--- a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.initialization.test.tsx+++ b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.initialization.test.tsx@@ -1,12 +1,16 @@// @vitest-environment jsdomimport { useState } from 'react';-import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { MemoryRouter } from 'react-router-dom';import { CindyAuthClient, reduceAuthFlow, type AuthFlowState } from '@cindy/auth-client';import { createScenarioFetch } from '@cindy/auth-client/fixtures';-import type { DesktopLoginAction, DesktopLoginActionResult } from '../../../../shared/authIpc';+import type {+ DesktopLoginAction,+ DesktopLoginActionResult,+ DesktopLoginState,+} from '../../../../shared/authIpc';const auth = vi.hoisted(() => ({value: {} as Record<string, unknown>,@@ -30,11 +34,11 @@ import { AddAccountLoginPage } from '../AddAccountLoginPage';import { LoginPage } from '../LoginPage';let identifierState: AuthFlowState;-let publishState: (state: AuthFlowState | null) => void;+let publishState: (state: DesktopLoginState | null) => void;let epoch: number;function Harness({ addAccount = false }: { addAccount?: boolean }) {- const [loginState, setLoginState] = useState<AuthFlowState | null>(null);+ const [loginState, setLoginState] = useState<DesktopLoginState | null>(null);publishState = setLoginState;auth.value = {loginState,@@ -89,7 +93,7 @@ afterEach(() => {describe('login initialization ownership', () => {it.each([false, true])(- 'returns from an initialization error to the login entry (addAccount=%s)',+ 'leaves an initialization error without requesting providers (addAccount=%s)',async (addAccount) => {const initialize = addAccount ? auth.beginAddAccount : auth.loadLoginState;initialize.mockImplementation(async () => {@@ -101,12 +105,12 @@ describe('login initialization ownership', () => {publishState(state);return { success: false, code: state.code, state };});- // Publish the successful reset result through the same auth-state boundary- // consumed by the real useLogin hook and LoginPage.+ // Navigation remains local even though no provider config was loaded.auth.dispatchLoginAction.mockImplementation(async (action) => {- if (action.type !== 'reset') throw new Error('expected reset');- publishState(identifierState);- return { success: true, state: identifierState };+ if (action.type !== 'back') throw new Error('back must not retry');+ const state = { step: 'entry' } as const;+ publishState(state);+ return { success: true, state };});render(<Harness addAccount={addAccount} />);@@ -117,16 +121,58 @@ describe('login initialization ownership', () => {fireEvent.click(back);- await screen.findByTestId('login-panel-identifier');- expect(screen.getByTestId('login-input')).toBeTruthy();+ if (addAccount) {+ await waitFor(() => expect(auth.cancelAddAccount).toHaveBeenCalledOnce());+ expect(auth.dispatchLoginAction).not.toHaveBeenCalled();+ return;+ }+ await screen.findByTestId('login-panel-entry');+ expect(screen.getByTestId('login-entry-continue')).toBeTruthy();expect(screen.queryByTestId('login-panel-error')).toBeNull();expect(screen.queryByTestId('login-error-text')).toBeNull();expect(screen.queryByTestId('login-error-retry')).toBeNull();- expect(auth.dispatchLoginAction).toHaveBeenCalledExactlyOnceWith({ type: 'reset' });+ expect(auth.dispatchLoginAction).toHaveBeenCalledExactlyOnceWith({ type: 'back' });expect(auth.cancelAddAccount).not.toHaveBeenCalled();},);+ it('allows Back and Skip Sign-In while an error retry is still pending', async () => {+ auth.loadLoginState.mockImplementation(async () => {+ const state = { step: 'error', code: 'REQUEST_TIMEOUT', recoverTo: 'identifier' } as const;+ publishState(state);+ return { success: false, code: state.code, state };+ });+ let finishRetry!: (result: DesktopLoginActionResult) => void;+ auth.dispatchLoginAction.mockImplementation(async (action) => {+ if (action.type === 'back') {+ const state = { step: 'entry' } as const;+ publishState(state);+ return { success: true, state };+ }+ return new Promise((resolve) => {+ finishRetry = resolve;+ });+ });+ render(<Harness />);+ await waitFor(() =>+ expect((screen.getByTestId('login-error-retry') as HTMLButtonElement).disabled).toBe(false),+ );+ fireEvent.click(screen.getByTestId('login-error-retry'));+ expect((screen.getByTestId('login-error-retry') as HTMLButtonElement).disabled).toBe(true);+ expect((screen.getByTestId('login-back-button') as HTMLButtonElement).disabled).toBe(false);+ expect((screen.getByTestId('login-local-mode') as HTMLButtonElement).disabled).toBe(false);+ fireEvent.click(screen.getByTestId('login-back-button'));+ await screen.findByTestId('login-panel-entry');+ await act(async () => finishRetry({ success: false, code: 'REQUEST_TIMEOUT', state: null }));+ expect(screen.queryByTestId('login-error-text')).toBeNull();+ expect((screen.getByTestId('login-entry-continue') as HTMLButtonElement).disabled).toBe(false);+ expect(auth.loadLoginState).toHaveBeenCalledOnce();+ expect(auth.dispatchLoginAction.mock.calls.map(([action]) => action.type)).toEqual([+ 'reset',+ 'back',+ ]);+ });+it('opens add-account login without an invalidated load or a false failure', async () => {render(<Harness addAccount />);diff --git a/apps/desktop/src/renderer/contexts/AuthContext.tsx b/apps/desktop/src/renderer/contexts/AuthContext.tsxindex 72623722a1..c8b06c035b 100644--- a/apps/desktop/src/renderer/contexts/AuthContext.tsx+++ b/apps/desktop/src/renderer/contexts/AuthContext.tsx@@ -179,6 +179,9 @@ export function AuthProvider({const [accountDeletionRestored, setAccountDeletionRestored] = useState(false);const [credentialStoreUnavailable, setCredentialStoreUnavailable] = useState(false);const [loginState, setLoginState] = useState<DesktopLoginState | null>(null);+ // Main rejects superseded credentials; this also prevents late IPC responses+ // from repainting a login page the user has already left.+ const loginOperationRef = useRef(0);const { confirm } = useConfirmDialog();const { t } = useTranslation();@@ -504,22 +507,30 @@ export function AuthProvider({}, [confirm, enableSessionExpiredPrompt, t]);const loadLoginState = useCallback(async (): Promise<DesktopLoginActionResult> => {+ const operation = ++loginOperationRef.current;// preparing 只允许在 load 进行中出现。settle / throw / 30s 超时都必须落到// identifier 或既有 error 步,避免 AUTH_FLOW_SUPERSEDED + state=null 或 IPC// 挂起把「正在连接登录服务」变成永不结束。const result = await awaitDesktopLoginStateLoad(() => authServiceRef.current!.getLoginState());+ if (operation !== loginOperationRef.current) {+ return { success: false, code: 'AUTH_FLOW_SUPERSEDED', state: null };+ }setLoginState(presentLoginResult(result));return result;}, []);const dispatchLoginAction = useCallback(async (action: DesktopLoginAction): Promise<DesktopLoginActionResult> => {+ const operation = ++loginOperationRef.current;// Main keeps the browser request open until its loopback callback arrives,// so project the waiting screen immediately to expose the cancel action.if (action.type === 'start-browser') {setLoginState({ step: 'browser-redirect', label: action.label });}const result = await authServiceRef.current!.dispatchLoginAction(action);+ if (operation !== loginOperationRef.current) {+ return { success: false, code: 'AUTH_FLOW_SUPERSEDED', state: null };+ }// Org discovery can auto-start a sole SSO browser flow below. Persist at// the successful discovery boundary so a later browser cancel/timeout// does not erase a valid organization from local history.@@ -544,6 +555,9 @@ export function AuthProvider({// global 开启 captcha 后不带 token 发码直接吃 400。const captchaGate = getLoginEmailCaptchaGate();const captchaToken = captchaGate ? await captchaGate() : undefined;+ if (operation !== loginOperationRef.current) {+ return { success: false, code: 'AUTH_FLOW_SUPERSEDED', state: null };+ }if (captchaToken === null) {// 用户取消挑战:停在 method-choice,个人行可再次发起(会重新过闸)setLoginState(presentLoginResult(result));@@ -580,17 +594,23 @@ export function AuthProvider({);const beginAddAccount = useCallback(async () => {+ const operation = ++loginOperationRef.current;const result = await authServiceRef.current!.beginAddAccount();+ if (operation !== loginOperationRef.current) {+ return { success: false as const, code: 'AUTH_FLOW_SUPERSEDED', state: null };+ }setLoginState(presentLoginResult(result));return result;}, []);const cancelAddAccount = useCallback(async () => {+ const operation = ++loginOperationRef.current;await authServiceRef.current!.cancelAddAccount();- setLoginState(null);+ if (operation === loginOperationRef.current) setLoginState(null);}, []);const enterLocalMode = useCallback(async () => {+ loginOperationRef.current += 1;// 本地模式也是一次 dataOwnerId 切换。必须走 applyIncomingState,不能自己拼半套// setter:漏接草稿 / prompt / 模型可见性 / 记忆分区会让跳过登录进主界面后仍读写// signed-out 槽(2026-08-21 #3201 Codex P1)。diff --git a/apps/desktop/src/renderer/contexts/__tests__/AuthContextInitializeCatch.test.tsx b/apps/desktop/src/renderer/contexts/__tests__/AuthContextInitializeCatch.test.tsxindex 180a1dc5f8..db8e8a2be7 100644--- a/apps/desktop/src/renderer/contexts/__tests__/AuthContextInitializeCatch.test.tsx+++ b/apps/desktop/src/renderer/contexts/__tests__/AuthContextInitializeCatch.test.tsx@@ -86,6 +86,103 @@ afterEach(() => {vi.clearAllMocks();});+describe('login recovery ignores abandoned IPC results', () => {+ it.each(['load', 'reset', 'add-account'] as const)(+ 'keeps the entry and the new loading state when an earlier %s finishes',+ async (kind) => {+ mocks.service.initialize.mockResolvedValue({ isAuthenticated: false, isCanary: false });+ const hook = renderHook(() => ({ auth: useAuth(), login: useLogin({ autoLoad: false }) }), {+ wrapper: AuthProvider,+ });+ await waitFor(() => expect(hook.result.current.auth.isInitializing).toBe(false));+ let finishOld!: (result: DesktopLoginActionResult) => void;+ const old = new Promise<DesktopLoginActionResult>((resolve) => {+ finishOld = resolve;+ });+ const service =+ kind === 'load'+ ? mocks.service.getLoginState+ : kind === 'add-account'+ ? mocks.service.beginAddAccount+ : mocks.service.dispatchLoginAction;+ service.mockReturnValueOnce(old);+ let oldAction!: Promise<unknown>;+ act(() => {+ oldAction =+ kind === 'load'+ ? hook.result.current.auth.loadLoginState()+ : kind === 'add-account'+ ? hook.result.current.auth.beginAddAccount()+ : hook.result.current.login.dispatch({ type: 'reset' });+ });+ mocks.service.dispatchLoginAction.mockResolvedValueOnce({+ success: true,+ state: { step: 'entry' },+ });+ await act(async () => {+ await hook.result.current.login.dispatch({ type: 'back' });+ });+ expect(hook.result.current.auth.loginState).toEqual({ step: 'entry' });+ expect(hook.result.current.login.isLoading).toBe(false);++ let finishNext!: (result: DesktopLoginActionResult) => void;+ mocks.service.dispatchLoginAction.mockReturnValueOnce(+ new Promise((resolve) => {+ finishNext = resolve;+ }),+ );+ let nextAction!: Promise<boolean>;+ act(() => {+ nextAction = hook.result.current.login.dispatch({ type: 'reset' });+ });+ await act(async () => {+ finishOld({+ success: false,+ code: 'REQUEST_TIMEOUT',+ state: { step: 'error', code: 'REQUEST_TIMEOUT', recoverTo: 'identifier' },+ });+ await oldAction;+ });+ expect(hook.result.current.auth.loginState).toEqual({ step: 'entry' });+ expect(hook.result.current.login.errorCode).toBeNull();+ expect(hook.result.current.login.isLoading).toBe(true);+ await act(async () => {+ finishNext({ success: true, state: { step: 'entry' } });+ await nextAction;+ });+ expect(hook.result.current.login.isLoading).toBe(false);+ },+ );++ it('does not reopen add-account login after it was closed', async () => {+ mocks.service.initialize.mockResolvedValue({ isAuthenticated: false, isCanary: false });+ const hook = renderHook(() => useAuth(), { wrapper: AuthProvider });+ await waitFor(() => expect(hook.result.current.isInitializing).toBe(false));+ let finish!: (result: DesktopLoginActionResult) => void;+ mocks.service.beginAddAccount.mockReturnValueOnce(+ new Promise((resolve) => {+ finish = resolve;+ }),+ );+ let begin!: Promise<DesktopLoginActionResult>;+ act(() => {+ begin = hook.result.current.beginAddAccount();+ });+ await act(async () => {+ await hook.result.current.cancelAddAccount();+ });+ await act(async () => {+ finish({+ success: false,+ code: 'REQUEST_TIMEOUT',+ state: { step: 'error', code: 'REQUEST_TIMEOUT', recoverTo: 'identifier' },+ });+ await begin;+ });+ expect(hook.result.current.loginState).toBeNull();+ });+});+describe('AuthContext initialize .catch 归一未登录', () => {it.each(['load', 'add-account', 'dispatch'] as const)('keeps Retry-After with the %s result through retries, success, rejection and cancellation',diff --git a/apps/desktop/src/renderer/hooks/useLogin.ts b/apps/desktop/src/renderer/hooks/useLogin.tsindex 8d82abaa1f..4591d2c280 100644--- a/apps/desktop/src/renderer/hooks/useLogin.ts+++ b/apps/desktop/src/renderer/hooks/useLogin.ts@@ -46,19 +46,25 @@ export function useLogin({ autoLoad = true }: { autoLoad?: boolean } = {}): UseLconst [isLoading, setIsLoading] = useState(false);const [errorCode, setErrorCode] = useState<string | null>(null);const loadingRef = useRef(false);+ const operationRef = useRef(0);useEffect(() => {if (!autoLoad || loginState || loadingRef.current) return;+ const operation = ++operationRef.current;loadingRef.current = true;setIsLoading(true);void loadLoginState().then((result) => {+ if (operation !== operationRef.current) return;if (!result.success) {setErrorCode(result.code);}})- .catch(() => setErrorCode('AUTH_SERVICE_UNAVAILABLE'))+ .catch(() => {+ if (operation === operationRef.current) setErrorCode('AUTH_SERVICE_UNAVAILABLE');+ }).finally(() => {+ if (operation !== operationRef.current) return;loadingRef.current = false;setIsLoading(false);});@@ -66,25 +72,30 @@ export function useLogin({ autoLoad = true }: { autoLoad?: boolean } = {}): UseLconst dispatchWithResult = useCallback(async (action: DesktopLoginAction): Promise<{ success: boolean; code: string | null }> => {- if (loadingRef.current && action.type !== 'cancel-browser') {+ if (loadingRef.current && action.type !== 'cancel-browser' && action.type !== 'back') {return { success: false, code: null };}+ const operation = ++operationRef.current;loadingRef.current = true;setIsLoading(true);setErrorCode(null);try {const result = await dispatchLoginAction(action);+ if (operation !== operationRef.current) return { success: false, code: null };if (!result.success) {setErrorCode(result.code === 'USER_CANCELLED' ? null : result.code);return { success: false, code: result.code };}return { success: true, code: null };} catch {+ if (operation !== operationRef.current) return { success: false, code: null };setErrorCode('AUTH_REQUEST_FAILED');return { success: false, code: 'AUTH_REQUEST_FAILED' };} finally {- loadingRef.current = false;- setIsLoading(false);+ if (operation === operationRef.current) {+ loadingRef.current = false;+ setIsLoading(false);+ }}},[dispatchLoginAction],diff --git a/apps/desktop/src/shared/__tests__/authIpc.test.ts b/apps/desktop/src/shared/__tests__/authIpc.test.tsindex e3014a8103..39347109e5 100644--- a/apps/desktop/src/shared/__tests__/authIpc.test.ts+++ b/apps/desktop/src/shared/__tests__/authIpc.test.ts@@ -119,6 +119,7 @@ describe('desktop auth IPC validation', () => {it('accepts each non-browser action shape', () => {expect(parseDesktopLoginAction({ type: 'reset' })).toEqual({ type: 'reset' });+ expect(parseDesktopLoginAction({ type: 'back', token: 'ignored' })).toEqual({ type: 'back' });expect(parseDesktopLoginAction({ type: 'cancel-browser' })).toEqual({type: 'cancel-browser',});diff --git a/apps/desktop/src/shared/authIpc.ts b/apps/desktop/src/shared/authIpc.tsindex b656ea4b22..32aea2a615 100644--- a/apps/desktop/src/shared/authIpc.ts+++ b/apps/desktop/src/shared/authIpc.ts@@ -8,6 +8,7 @@ import type {export type DesktopLoginAction =| { type: 'reset' }+ | { type: 'back' }| { type: 'cancel-browser' }| { type: 'discover'; email: string }| { type: 'discover-sso-org'; org: string }@@ -28,7 +29,7 @@ export type DesktopLoginAction =| { type: 'verify-binding'; contact: string; code: string };/** In-memory presentation metadata; never a persisted cooldown or retry budget. */-export type DesktopLoginState = AuthFlowState & { retryAt?: number };+export type DesktopLoginState = (AuthFlowState | { step: 'entry' }) & { retryAt?: number };export type DesktopLoginActionResult =| { success: true; state: DesktopLoginState }@@ -175,6 +176,8 @@ export function parseDesktopLoginAction(value: unknown): DesktopLoginAction | nuswitch (value.type) {case 'reset':return { type: 'reset' };+ case 'back':+ return { type: 'back' };case 'cancel-browser':return { type: 'cancel-browser' };case 'discover':diff --git a/docs/design-rules/DESIGN.md b/docs/design-rules/DESIGN.mdindex 5653cadc5e..067473aade 100644--- a/docs/design-rules/DESIGN.md+++ b/docs/design-rules/DESIGN.md@@ -1992,7 +1992,7 @@ and media position (`ui/media-scrubber`, seconds in/out). Native media controls| `binding` | 身份未绑 membership,补绑 phone / email(`codeRequested` 两子态;**无重发钮**,桌面 harness 锁定) | `LoginInput` / `LoginSkinPhoneInput` → `LoginInput`(center) + `LoginPrimaryButton` || `account-deletion`(状态浮层) | 账号删除**状态展示**(发起流程在 Settings 的 `AccountDeletionSection`;登录页仅在存在删除回执时以**根层浮层气泡**展示 status,非主状态机 step;详见下方「注销状态浮层气泡」) | `AccountDeletionStatusPanel`(**登录皮容器外**的根层浮层,非面板内) || `browser-redirect` | 社交 / SSO 跳浏览器验证,等待回调 | `LoginLoadingRing` + Desktop `LoginBackButton`(`cancel-browser`;Mobile 保留原取消入口)+ `LoginTitleBlock` |-| `completed` / `error` | 登录成功 / 失败(含 browser 回调终态页);`error` 步桌面另有面板下方 footer 的「跳过登录」**逃生入口**(登录服务不可用时仍能进未登录状态,与面板内入口同口径**过协议门**——2026-07-29 拍板) | 成功无面板(进主界面);error = `LoginBackButton`(仅桌面,复用 reset;普通登录与添加账号均重新加载登录入口)+ `LoginTitleBlock` + `LoginPrimaryButton`(重试)+ `LoginErrorText` + footer「跳过登录」按钮(桌面);browser 回调页 `oauthResultPage`(系统浏览器独立 HTML,main 侧内联常量,色值与 `--login-callback-*` token 同源——renderer CSS var 不可达,改值需两处同步) |+| `completed` / `error` | 登录成功 / 失败(含 browser 回调终态页);`error` 步桌面另有面板下方 footer 的「跳过登录」**逃生入口**(登录服务不可用时仍能进未登录状态,与面板内入口同口径**过协议门**——2026-07-29 拍板) | 成功无面板(进主界面);error = `LoginBackButton`(仅桌面:普通登录网络错误取消当前等待,使用已取得的配置返回入口;配置尚未取得时显示「继续登录/跳过登录」的离线入口,不自动联网;添加账号则关闭流程)+ `LoginTitleBlock` + `LoginPrimaryButton`(重试)+ `LoginErrorText` + footer「跳过登录」按钮(桌面);browser 回调页 `oauthResultPage`(系统浏览器独立 HTML,main 侧内联常量,色值与 `--login-callback-*` token 同源——renderer CSS var 不可达,改值需两处同步) |**~~配置错误屏同样承载「跳过登录」逃生入口(移动端)~~〔已作废 2026-07-28:手机端整体剥离,配置错误屏无该入口〕**:`getMobileConfigIssues()` 命中(如 auth base URL 非法)时面板切到 config 提示态,该面板内仍渲染同一个 `LoginSkipLoginLink`(同槽 @(0,430)、同 handler、同 in-flight 门)——跳过登录不发任何网络请求,配置坏掉时恰恰最需要这个入口。@@ -2026,6 +2026,8 @@ and media position (`ui/media-scrubber`, seconds in/out). Native media controls- **颜色**:底 `--login-deletion-bubble-bg`(#FFFFFF / #1F1F1E)、描边 `--login-deletion-bubble-border`(#D7D7D4 / #3C3C3A),均为**固定亮 / 暗二值**——与 §16.2「`--login-*` 只分 light / dark、不随扩展主题」一致,**不得**改用 `var(--surface)` / `var(--chat-input-*)` 等会被扩展主题 override 的 alias(同 `--login-bg-base` 的改判先例);移动端色板逐值一致。- **状态与文案**:`pending`(预计删除日期 + 重新登录可取消)/ `processing`(等待期结束、正在删除)/ `completed`(已删除 + 「我知道了」)三态;`cancelled` 在轮询侧拦截、不渲染气泡(改为登录后的一次性「注销已取消」提示)。五语言(zh-CN / zh-TW / en / ja / ko)× light / dark 全覆盖。+桌面登录恢复:准备态、错误态及离线入口的返回与「跳过登录」不因登录方式请求仍在等待而禁用;重试仍单次执行。凭证存储错误保留原有的检查与帮助流程,不绕过存储恢复限制。返回使旧请求失效,迟到结果不得覆盖新入口;「跳过登录」保留协议同意门与先切换本地会话、再保存同意的顺序。覆盖见 `LoginPage.initialization.test.tsx`、`LoginPage.consent.test.tsx` 与 `authLoginBack.test.ts`。+### 16.5 深色模式与主题跟随> 深色受 §10「Light / Dark 双模式交付门槛」约束,是**必须交付**的另一模式,非可选愿景。深色色值经 Figma 组件库 Dark symbol 逐个核验(见 §16.1 双态表),为目标规格——token dark 槽位已预留,待实现 PR 填入真实值并补齐 overlay token、深色资产切换及主题跟随逻辑。落地机制如下。