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(mobile): isolate login initialization from user actions

chenhong4953e4dc8d0b
diff --git a/apps/mobile/src/auth/AuthContext.tsx b/apps/mobile/src/auth/AuthContext.tsx
index 461ab38a28..8d2e0ae5d4 100644
--- a/apps/mobile/src/auth/AuthContext.tsx
+++ b/apps/mobile/src/auth/AuthContext.tsx
@@ -429,6 +429,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
} | null>(null);
const accountDeletionReceiptRealmRef = useRef<AuthRegion | null>(null);
const pendingAccountDeletionRestoredRef = useRef(false);
+ const loginInitializationRef = useRef<{ epoch: number; promise: Promise<boolean> } | null>(null);
const loginActionInFlightRef = useRef<Promise<boolean> | null>(null);
const loginActionInFlightEpochRef = useRef<number | null>(null);
const browserCompletionRef = useRef<Promise<void> | null>(null);
@@ -1692,6 +1693,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
) {
return browserCompletionRef.current;
}
+ loginInitializationRef.current = null;
suspendSessionRecoveryForLogin();
const run = (async () => {
setIsBusy(true);
@@ -1789,14 +1791,50 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const dispatchLoginAction = useCallback(
(action: MobileLoginAction): Promise<boolean> => {
- // Mounting a login screen only initializes an absent flow. Existing state
- // and callbacks belong to AuthProvider, not to the route's lifetime.
- if (
- action.type === 'initialize' &&
- (loginStateRef.current || browserCompletionRef.current)
- ) {
- return Promise.resolve(true);
+ if (action.type === 'initialize') {
+ const epoch = loginFlowEpochRef.current;
+ // Initialization has its own deduplication slot. A callback or explicit
+ // action takes ownership immediately, even if providers are still loading.
+ if (
+ loginStateRef.current ||
+ (browserCompletionRef.current && browserCompletionEpochRef.current === epoch) ||
+ (loginActionInFlightRef.current && loginActionInFlightEpochRef.current === epoch)
+ ) {
+ return Promise.resolve(true);
+ }
+ if (loginInitializationRef.current?.epoch === epoch) {
+ return loginInitializationRef.current.promise;
+ }
+ let promise: Promise<boolean>;
+ const isCurrent = () => loginInitializationRef.current?.promise === promise &&
+ loginFlowEpochRef.current === epoch;
+ promise = (async () => {
+ setIsBusy(true);
+ setAuthError(null);
+ suspendSessionRecoveryForLogin();
+ try {
+ const did = await (deviceIdRef.current ?? prepareBetaChannelForCurrentDevice());
+ if (!isCurrent()) return false;
+ const providers = await authClientFor(did, BUILD_AUTH_REGION).getProviders();
+ if (!isCurrent()) return false;
+ deviceIdRef.current = did;
+ setDeviceId(did);
+ updateLoginState(reduceAuthFlow(null, { type: 'providers-loaded', providers }));
+ return true;
+ } catch (error) {
+ if (isCurrent()) setAuthError(authErrorCode(error));
+ return false;
+ } finally {
+ if (isCurrent()) {
+ loginInitializationRef.current = null;
+ setIsBusy(false);
+ }
+ }
+ })();
+ loginInitializationRef.current = { epoch, promise };
+ return promise;
}
+ loginInitializationRef.current = null;
// Cancelling a browser login must invalidate its in-flight callback before
// any await or deduplication. Other login actions retain their lifecycle.
if (action.type === 'reset' && loginStateRef.current?.step === 'browser-redirect') {
@@ -1906,16 +1944,6 @@ export function AuthProvider({ children }: { children: ReactNode }) {
pendingAuthRealmRef.current = discovery.region;
return discovery;
};
- if (action.type === 'initialize') {
- const providers = await authClientFor(did, BUILD_AUTH_REGION).getProviders();
- assertLoginFlowCurrent(expectedLoginFlowEpoch);
- // A cold-start callback may begin or finish while providers load.
- // Never clear PKCE/tickets or overwrite the state it has established.
- if (!loginStateRef.current && !browserCompletionRef.current) {
- updateLoginState(reduceAuthFlow(null, { type: 'providers-loaded', providers }));
- }
- return true;
- }
if (action.type === 'reset') {
pendingAccountTokenRef.current = null;
pendingAccountRefreshTokenRef.current = null;
@@ -2303,12 +2331,6 @@ export function AuthProvider({ children }: { children: ReactNode }) {
return true;
} catch (error) {
if (loginFlowEpochRef.current !== expectedLoginFlowEpoch) return false;
- if (action.type === 'initialize') {
- if (!loginStateRef.current && !browserCompletionRef.current) {
- setAuthError(authErrorCode(error));
- }
- return false;
- }
const code = authErrorCode(error);
if (
code === 'INVALID_LOGIN_TICKET' ||
@@ -2335,10 +2357,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
setAuthError(code);
return false;
} finally {
- if (
- loginFlowEpochRef.current === expectedLoginFlowEpoch &&
- (action.type !== 'initialize' || !browserCompletionRef.current)
- ) {
+ if (loginFlowEpochRef.current === expectedLoginFlowEpoch) {
setIsBusy(false);
}
}
diff --git a/apps/mobile/src/auth/__tests__/browserAuthSession.test.tsx b/apps/mobile/src/auth/__tests__/browserAuthSession.test.tsx
index df9dd3508e..fb89982e54 100644
--- a/apps/mobile/src/auth/__tests__/browserAuthSession.test.tsx
+++ b/apps/mobile/src/auth/__tests__/browserAuthSession.test.tsx
@@ -579,6 +579,103 @@ describe('browser auth session lifecycle (real AuthProvider, mocked native/netwo
expect(auth.authError).toBeNull();
});
+ it.each([
+ { name: 'select-account', outcome: { status: 'select_account', loginTicket: 'fixture-select', accounts: [] },
+ action: { type: 'select-account', accountId: 'fixture-account' }, request: native.selectAccount },
+ { name: 'binding', outcome: { status: 'binding_required', bindType: 'email', bindTicket: 'fixture-bind' },
+ action: { type: 'request-binding-code', contact: '[email protected]' }, request: native.requestBinding },
+ { name: 'verification', outcome: verifiedOutcome,
+ action: { type: 'request-sso-verification-code' }, request: native.requestVerification },
+ { name: 'back', outcome: verifiedOutcome, action: { type: 'reset' }, request: native.providers },
+ ] as const)('executes $name immediately while initialization is still awaiting providers', async fixture => {
+ await act(async () => { await auth.cancelAddAccount(); });
+ native.storage.set(pendingKey, JSON.stringify({ state: 'fixture-cold-state', codeVerifier: 'fixture-verifier',
+ deviceId: 'fixture-device', realm: 'cn', label: 'Fixture SSO', createdAt: Date.now() }));
+ let finishProviders!: (value: unknown) => void;
+ native.providers.mockImplementationOnce(() => new Promise(resolve => { finishProviders = resolve; }));
+ native.exchange.mockResolvedValueOnce(fixture.outcome);
+ await mountLoginScreen('initial');
+ await emitLink(callbackUrl());
+ expect(auth.isBusy).toBe(false);
+ fixture.request.mockClear();
+ let actionFinished = false;
+ await act(async () => {
+ void auth.dispatchLoginAction(fixture.action).then(result => { actionFinished = result; });
+ });
+ expect(fixture.request).toHaveBeenCalledTimes(1);
+ expect(actionFinished).toBe(true);
+ const state = auth.loginState;
+ await act(async () => { finishProviders({ social: ['wechat'], emailCode: true, smsCode: false }); });
+ expect(auth.loginState).toBe(state);
+ expect(auth.authError).toBeNull();
+ });
+
+ it.each(['success', 'failure'] as const)('ignores late initialization %s while the next user request is running', async result => {
+ await act(async () => { await auth.cancelAddAccount(); });
+ native.storage.set(pendingKey, JSON.stringify({ state: 'fixture-cold-state', codeVerifier: 'fixture-verifier',
+ deviceId: 'fixture-device', realm: 'cn', label: 'Fixture SSO', createdAt: Date.now() }));
+ let finish!: (value: unknown) => void;
+ let fail!: (error: Error) => void;
+ native.providers.mockImplementationOnce(() => new Promise((resolve, reject) => { finish = resolve; fail = reject; }));
+ await mountLoginScreen('initial');
+ await emitLink(callbackUrl());
+ let finishCode!: () => void;
+ native.requestVerification.mockImplementationOnce(() => new Promise<void>(resolve => { finishCode = resolve; }));
+ let codeRequest!: Promise<boolean>;
+ await act(async () => { codeRequest = auth.dispatchLoginAction({ type: 'request-sso-verification-code' }); });
+ expect(native.requestVerification).toHaveBeenCalledTimes(1);
+ expect(auth.isBusy).toBe(true);
+ const state = auth.loginState;
+ await act(async () => {
+ if (result === 'success') finish({ social: ['wechat'], emailCode: true, smsCode: false });
+ else fail(new Error('fixture obsolete initialization failure'));
+ });
+ expect(auth.loginState).toBe(state);
+ expect(auth.isBusy).toBe(true);
+ expect(auth.authError).toBeNull();
+ await act(async () => { finishCode(); expect(await codeRequest).toBe(true); });
+ expect(auth.loginState).toMatchObject({ step: 'sso-verification', codeRequested: true });
+ expect(auth.isBusy).toBe(false);
+ });
+
+ it('deduplicates initialization independently and abandons it on explicit reset', async () => {
+ await act(async () => { await auth.cancelAddAccount(); });
+ let finish!: (value: unknown) => void;
+ native.providers.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
+ let first!: Promise<boolean>;
+ await act(async () => {
+ first = auth.dispatchLoginAction({ type: 'initialize' });
+ expect(auth.dispatchLoginAction({ type: 'initialize' })).toBe(first);
+ });
+ await act(async () => { expect(await auth.dispatchLoginAction({ type: 'reset' })).toBe(true); });
+ expect(auth.loginState?.step).toBe('identifier');
+ const state = auth.loginState;
+ await act(async () => { finish({ social: [], emailCode: false, smsCode: true }); expect(await first).toBe(false); });
+ expect(auth.loginState).toBe(state);
+ expect(auth.isBusy).toBe(false);
+ });
+
+ it('does not reuse or clear a new initialization after add-account cancellation changes the epoch', async () => {
+ await act(async () => { await auth.cancelAddAccount(); });
+ let finishOld!: (value: unknown) => void;
+ let finishNew!: (value: unknown) => void;
+ native.providers
+ .mockImplementationOnce(() => new Promise(resolve => { finishOld = resolve; }))
+ .mockImplementationOnce(() => new Promise(resolve => { finishNew = resolve; }));
+ let old!: Promise<boolean>;
+ let current!: Promise<boolean>;
+ await act(async () => { old = auth.dispatchLoginAction({ type: 'initialize' }); });
+ await act(async () => { await auth.cancelAddAccount(); });
+ await act(async () => { current = auth.dispatchLoginAction({ type: 'initialize' }); });
+ expect(current).not.toBe(old);
+ await act(async () => { finishOld({ social: [], emailCode: true, smsCode: false }); expect(await old).toBe(false); });
+ expect(auth.loginState).toBeNull();
+ expect(auth.isBusy).toBe(true);
+ await act(async () => { finishNew({ social: ['wechat'], emailCode: true, smsCode: false }); expect(await current).toBe(true); });
+ expect(auth.loginState?.step).toBe('identifier');
+ expect(auth.isBusy).toBe(false);
+ });
+
it('still exchanges only once when Linking and the browser both report success', async () => {
native.open.mockImplementation(async () => {
const url = callbackUrl();