Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): surface OAuth cancellation and callback failures
chenhongddaf468dfd7d
diff --git a/apps/mobile/app/add-account.tsx b/apps/mobile/app/add-account.tsxindex 8e47649b77..9ef1c3aec4 100644--- a/apps/mobile/app/add-account.tsx+++ b/apps/mobile/app/add-account.tsx@@ -21,7 +21,7 @@ export default function AddAccountScreen() {// Android 系统返回键可以直接移除路由。取消动作必须从卸载路径兜底,// 让验证码校验、账号选择等迟到结果在提交前失效。if (flowFinishedRef.current || closeStartedRef.current) return;- void auth.cancelAddAccount();+ void auth.cancelAddAccount().catch(() => undefined);},[auth.cancelAddAccount],);@@ -31,7 +31,10 @@ export default function AddAccountScreen() {additionalAccountonClose={() => {closeStartedRef.current = true;- void auth.cancelAddAccount().finally(() => router.replace('/devices'));+ void auth.cancelAddAccount().then(+ () => router.replace('/devices'),+ () => { closeStartedRef.current = false; },+ );}}/>);diff --git a/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts b/apps/mobile/src/__tests__/mobileAuthServerLogin.test.tsindex f6b82bbf83..236a259aff 100644--- a/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts+++ b/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts@@ -737,7 +737,8 @@ describe('mobile auth-server login', () => {'utf8',);expect(screenSource).toContain('() => () => {');- expect(screenSource).toContain('void auth.cancelAddAccount();');+ expect(screenSource).toContain('void auth.cancelAddAccount().catch(() => undefined);');+ expect(screenSource).not.toContain('cancelAddAccount().finally');expect(screenSource).toContain('flowFinishedRef.current');const beginStart = authSource.indexOf('const beginAddAccount = useCallback');diff --git a/apps/mobile/src/auth/AuthContext.tsx b/apps/mobile/src/auth/AuthContext.tsxindex 0934264d2e..e7527151ea 100644--- a/apps/mobile/src/auth/AuthContext.tsx+++ b/apps/mobile/src/auth/AuthContext.tsx@@ -1718,11 +1718,14 @@ export function AuthProvider({ children }: { children: ReactNode }) {if (!matchesOAuthCallbackUrl(callbackUrl, MOBILE_REDIRECT_URL)) {throw authCodeError('INVALID_AUTH_CODE');}- const callback = parseOAuthCallbackUrl(callbackUrl);+ // Establish ownership even for denial/malformed-code redirects before+ // parsing their terminal result. Unowned error links cannot cancel a flow.+ const callbackState = new URL(callbackUrl).searchParams.get('state');+ if (!callbackState) throw authCodeError('STATE_MISMATCH');const currentCompletion = () =>!oauthCancelledRef.current && loginFlowEpochRef.current === expectedLoginFlowEpoch &&browserCompletionEpochRef.current === expectedLoginFlowEpoch &&- browserCompletionStateRef.current === callback.state+ browserCompletionStateRef.current === callbackState? browserCompletionRef.current : null;const existing = currentCompletion();if (existing) return existing;@@ -1731,7 +1734,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {try {// Validate ownership before taking the single-flight slot. A stale// state must never swallow the current attempt's callback.- pending = await readPendingOAuth(callback.state);+ pending = await readPendingOAuth(callbackState);} catch (error) {const concurrent = currentCompletion();if (concurrent) return concurrent;@@ -1755,7 +1758,10 @@ export function AuthProvider({ children }: { children: ReactNode }) {suspendSessionRecoveryForLogin();const run = (async () => {setIsBusy(true);+ let parsedCallback = false;try {+ const callback = parseOAuthCallbackUrl(callbackUrl);+ parsedCallback = true;try {await loadMobileEndpointsForRealm(pending.realm);} catch {@@ -1784,6 +1790,19 @@ export function AuthProvider({ children }: { children: ReactNode }) {} catch (error) {if (loginFlowEpochRef.current !== expectedLoginFlowEpoch) throw error;const code = authErrorCode(error);+ if (!parsedCallback) {+ oauthCancelledRef.current = true;+ let reportedCode = code;+ try {+ await persistPendingOAuth(null);+ } catch (storageError) {+ reportedCode = authErrorCode(storageError);+ }+ assertLoginFlowCurrent(expectedLoginFlowEpoch);+ updateLoginState({ step: 'error', code: reportedCode, recoverTo: 'identifier' });+ setAuthError(reportedCode);+ throw error;+ }if (code === 'INVALID_AUTH_CODE') {await persistPendingOAuth(null).catch(() => undefined);assertLoginFlowCurrent(expectedLoginFlowEpoch);@@ -1801,7 +1820,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {})();browserCompletionRef.current = run;browserCompletionEpochRef.current = expectedLoginFlowEpoch;- browserCompletionStateRef.current = callback.state;+ browserCompletionStateRef.current = callbackState;// Keep successful completion for duplicate native/Linking notifications;// a different state or epoch cannot reuse it. Failed attempts may retry.void run.catch(() => {@@ -1992,7 +2011,15 @@ export function AuthProvider({ children }: { children: ReactNode }) {oauthCancelledRef.current = true;setIsBusy(false);const cancelledEpoch = ++loginFlowEpochRef.current;- await persistPendingOAuth(null).catch(() => undefined);+ try {+ await persistPendingOAuth(null);+ } catch (error) {+ assertLoginFlowCurrent(cancelledEpoch);+ const code = authErrorCode(error);+ updateLoginState({ step: 'error', code, recoverTo: 'identifier' });+ setAuthError(code);+ throw error;+ }assertLoginFlowCurrent(cancelledEpoch);pendingAuthRealmRef.current = null;updateLoginState(null);@@ -2760,6 +2787,16 @@ export function AuthProvider({ children }: { children: ReactNode }) {loginFlowEpochRef.current += 1;const cancelledEpoch = loginFlowEpochRef.current;setIsBusy(false);+ try {+ await persistPendingOAuth(null);+ } catch (error) {+ if (loginFlowEpochRef.current !== cancelledEpoch) return;+ const code = authErrorCode(error);+ updateLoginState({ step: 'error', code, recoverTo: 'identifier' });+ setAuthError(code);+ throw error;+ }+ if (loginFlowEpochRef.current !== cancelledEpoch) return;pendingAccountTokenRef.current = null;pendingAccountRefreshTokenRef.current = null;pendingAccountMembershipsRef.current = [];@@ -2772,8 +2809,6 @@ export function AuthProvider({ children }: { children: ReactNode }) {pendingAccountDeletionRestoredRef.current = false;additionalLoginRef.current = false;sessionRecoverySuspendedRef.current = false;- await persistPendingOAuth(null).catch(() => undefined);- if (loginFlowEpochRef.current !== cancelledEpoch) return;activateMobileSessionRealm(activeAuthRealmRef.current);setMobileAuthOwner(userRef.current?.id ?? null, activeAuthRealmRef.current);updateLoginState(null);diff --git a/apps/mobile/src/auth/__tests__/browserAuthSession.test.tsx b/apps/mobile/src/auth/__tests__/browserAuthSession.test.tsxindex b888006032..81d56addc4 100644--- a/apps/mobile/src/auth/__tests__/browserAuthSession.test.tsx+++ b/apps/mobile/src/auth/__tests__/browserAuthSession.test.tsx@@ -5,6 +5,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const native = vi.hoisted(() => ({platform: 'android',+ replaceRoute: vi.fn(),+ closeAccount: undefined as (() => void) | undefined,storage: new Map<string, string>(),readSecure: vi.fn(),deleteSecure: vi.fn(),@@ -25,6 +27,10 @@ const native = vi.hoisted(() => ({state: 0,}));+vi.mock('expo-router', () => ({ useRouter: () => ({ replace: native.replaceRoute }) }));+vi.mock('../../../app/(auth)/login', () => ({+ LoginScreen: ({ onClose }: { onClose?: () => void }) => { native.closeAccount = onClose; return null; },+}));vi.mock('react-native', () => ({Platform: { get OS() { return native.platform; } },AppState: { addEventListener: () => ({ remove() {} }) },@@ -108,6 +114,7 @@ vi.mock('@/update/betaChannelStore', () => ({ prepareBetaChannelForDevice: asyncvi.mock('@/update/fetchLatestRelease', () => ({}));import { AuthProvider, useAuth } from '../AuthContext';+import AddAccountScreen from '../../../app/add-account';const pendingKey = 'cindy.mobile.auth.pendingOAuth';const verifiedOutcome = {@@ -167,6 +174,8 @@ describe('browser auth session lifecycle (real AuthProvider, mocked native/netwobeforeEach(async () => {(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;native.platform = 'android';+ native.replaceRoute.mockReset();+ native.closeAccount = undefined;native.crossRealm = false;native.discoverOrganization.mockReset().mockResolvedValue({region: 'cn', orgName: 'Fixture Organization',@@ -213,6 +222,106 @@ describe('browser auth session lifecycle (real AuthProvider, mocked native/netwoexpect(native.storage.has(pendingKey)).toBe(false);});+ it.each(['access_denied', 'missing-code'])('surfaces a current terminal callback after dismiss (%s)', async error => {+ await start();+ const state = JSON.parse(native.storage.get(pendingKey)!).state;+ await emitLink(`cindycn://auth?state=${state}${error === 'access_denied' ? '&error=access_denied' : ''}`);+ expect(native.exchange).not.toHaveBeenCalled();+ expect(auth.loginState?.step).toBe('error');+ expect(auth.authError).toBe(error === 'access_denied' ? error : 'INVALID_AUTH_CODE');+ expect(native.storage.has(pendingKey)).toBe(false);+ await emitLink(callbackUrl(state));+ expect(native.exchange).not.toHaveBeenCalled();+ await act(async () => { await auth.dispatchLoginAction({ type: 'reset' }); });+ await start();+ await emitLink(callbackUrl());+ expect(auth.loginState?.step).toBe('sso-verification');+ });++ it.each(['wrong-state', 'missing-state'])('ignores an unowned error callback (%s)', async state => {+ await start();+ const pending = native.storage.get(pendingKey);+ await emitLink(`cindycn://auth?error=access_denied${state === 'wrong-state' ? '&state=old-state' : ''}`);+ expect(auth.loginState?.step).toBe('browser-redirect');+ expect(auth.authError).toBeNull();+ expect(native.storage.get(pendingKey)).toBe(pending);+ await emitLink(callbackUrl());+ expect(auth.loginState?.step).toBe('sso-verification');+ });++ it.each(['native-cancel', 'close-account', 'error-link'])('reports complete storage failure and permits cancellation retry (%s)', async entry => {+ if (entry === 'close-account') await act(async () => { await auth.beginAddAccount(); });+ let finish!: (v: {type: 'cancel'}) => void;+ let opening!: Promise<unknown>;+ if (entry === 'native-cancel') {+ native.open.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));+ await act(async () => { opening = auth.dispatchLoginAction({ type: 'start-social-browser', provider: 'wechat', label: 'WeChat' }).catch(e => e); });+ } else await start();+ const pending = native.storage.get(pendingKey);+ const url = callbackUrl();+ native.writeSecure.mockRejectedValueOnce(new Error('fixture storage unavailable'));+ native.deleteSecure.mockRejectedValueOnce(new Error('fixture storage unavailable'));+ await act(async () => {+ if (entry === 'native-cancel') { finish({type: 'cancel'}); await opening; }+ else if (entry === 'close-account') await auth.cancelAddAccount().catch(() => undefined);+ else for (const listener of native.links) listener({url: url.replace('code=fixture-code', 'error=access_denied')});+ });+ expect(auth.loginState?.step).toBe('error');+ expect(auth.authError).toBeTruthy();+ expect(native.storage.get(pendingKey)).toBe(pending);+ await emitLink(url);+ expect(native.exchange).not.toHaveBeenCalled();+ await act(async () => {+ if (entry === 'close-account') await auth.cancelAddAccount();+ else expect(await auth.dispatchLoginAction({type: 'reset'})).toBe(true);+ });+ expect(native.storage.has(pendingKey)).toBe(false);+ });++ it('keeps the add-account route open when cancellation fails and closes on retry', async () => {+ await act(async () => { await auth.beginAddAccount(); });+ await start();+ await act(async () => { root.render(<AuthProvider><Probe /><AddAccountScreen /></AuthProvider>); });+ native.writeSecure.mockRejectedValueOnce(new Error('fixture storage unavailable'));+ native.deleteSecure.mockRejectedValueOnce(new Error('fixture storage unavailable'));+ await act(async () => { native.closeAccount!(); });+ expect(auth.loginState?.step).toBe('error');+ expect(native.replaceRoute).not.toHaveBeenCalled();+ await act(async () => { native.closeAccount!(); });+ expect(native.replaceRoute).toHaveBeenCalledExactlyOnceWith('/devices');+ expect(native.storage.has(pendingKey)).toBe(false);+ });++ it('surfaces a failed unmount cancellation without an unhandled rejection', async () => {+ await act(async () => { await auth.beginAddAccount(); });+ await start();+ const url = callbackUrl();+ await act(async () => { root.render(<AuthProvider><Probe /><AddAccountScreen /></AuthProvider>); });+ native.writeSecure.mockRejectedValueOnce(new Error('fixture storage unavailable'));+ native.deleteSecure.mockRejectedValueOnce(new Error('fixture storage unavailable'));+ await act(async () => { root.render(<AuthProvider><Probe /></AuthProvider>); });+ expect(auth.loginState?.step).toBe('error');+ await emitLink(url);+ expect(native.exchange).not.toHaveBeenCalled();+ await act(async () => { await auth.beginAddAccount(); });+ expect(native.storage.has(pendingKey)).toBe(false);+ expect(auth.loginState?.step).toBe('identifier');+ });++ it('handles a terminal native success redirect on iOS through the same error path', async () => {+ native.platform = 'ios';+ native.open.mockImplementationOnce(async (url: string) => ({+ type: 'success', url: `cindycn://auth?state=${new URL(url).searchParams.get('state')}&error=access_denied`,+ }));+ await act(async () => {+ await auth.dispatchLoginAction({type: 'start-social-browser', provider: 'wechat', label: 'WeChat'}).catch(() => undefined);+ });+ expect(auth.loginState?.step).toBe('error');+ expect(auth.authError).toBe('access_denied');+ expect(native.storage.has(pendingKey)).toBe(false);+ expect(native.exchange).not.toHaveBeenCalled();+ });+it('explicit reset cancels the pending login; its late callback cannot authenticate', async () => {await start();const oldCallback = callbackUrl();