From cd23dbfa3fcc775a4596adc205c4f6ea8bd48459 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 4 Nov 2026 13:51:04 +0000 Subject: [PATCH 1/9] test(mobile): reproduce #30861 Clerk sign-in dead end on native session These tests reproduce #30861: when Clerk JS reports signed out but the native-backed client already holds a signed-in session, the T3 Connect sign-in screen offers a sign-in that fails with session_exists instead of adopting that session. Co-Authored-By: Claude Opus 5.5 --- .../settings/SettingsAuthRouteScreen.test.tsx | 85 +++++++++++++++++++ apps/mobile/vite.config.ts | 1 + 2 files changed, 86 insertions(+) create mode 100644 apps/mobile/src/features/settings/SettingsAuthRouteScreen.test.tsx diff --git a/apps/mobile/src/features/settings/SettingsAuthRouteScreen.test.tsx b/apps/mobile/src/features/settings/SettingsAuthRouteScreen.test.tsx new file mode 100644 index 0000000000000..457c99852559f --- /dev/null +++ b/apps/mobile/src/features/settings/SettingsAuthRouteScreen.test.tsx @@ -0,0 +1,85 @@ +import type { ReactNode } from "react"; +import { act } from "react"; +import { createRoot } from "react-dom/client"; +import { expect, it, vi } from "vite-plus/test"; + +interface FakeSession { + readonly id: string; + readonly status: string; +} +interface FakeClient { + readonly id: string; + readonly lastActiveSessionId: string | null; + readonly signedInSessions: readonly FakeSession[]; + readonly fetch: () => Promise; + readonly reload: () => Promise; +} + +const { Children, harness } = vi.hoisted(() => ({ + Children: ({ children }: { children?: ReactNode }) => <>{children}, + harness: { + clerk: null as unknown as { + client: unknown; + session: unknown; + updateClient: (client: unknown) => void; + setActive: ReturnType; + }, + }, +})); + +vi.mock("react-native", () => ({ View: Children })); +vi.mock("@react-navigation/native", () => ({ useNavigation: () => ({ goBack: vi.fn() }) })); +vi.mock("@clerk/expo", () => ({ + useAuth: () => ({ isLoaded: true, isSignedIn: false }), + useClerk: () => harness.clerk, + getClerkInstance: () => harness.clerk, +})); +vi.mock("@clerk/expo/native-components", () => ({ + AuthView: () => null, + UserProfileView: () => null, +})); +vi.mock("../cloud/publicConfig", () => ({ hasCloudPublicConfig: () => true })); +vi.mock("../cloud/T3ConnectProfilePage", () => ({ T3ConnectProfilePage: () => null })); + +import { SettingsAuthRouteScreen } from "./SettingsAuthRouteScreen"; + +function client(sessions: readonly FakeSession[]): FakeClient { + const self: FakeClient = { + id: "client_device", + lastActiveSessionId: sessions[0]?.id ?? null, + signedInSessions: sessions, + fetch: async () => self, + reload: async () => self, + }; + return self; +} + +it("adopts the session the native-backed client already holds instead of offering a doomed sign-in", async () => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + const nativeSession = { id: "sess_native", status: "active" }; + // The JS client is stale and signed out; refreshing it from the shared device + // token returns the session native Clerk reports as `session_exists`. + const refreshed = client([nativeSession]); + const stale = { ...client([]), fetch: async () => refreshed, reload: async () => refreshed }; + harness.clerk = { + client: stale, + session: null, + updateClient: (next) => { + harness.clerk.client = next; + }, + setActive: vi.fn(async () => {}), + }; + + const root = createRoot(document.createElement("div")); + act(() => root.render()); + + await vi.waitFor(() => { + const activated = harness.clerk.setActive.mock.calls.map(([params]) => { + const session = (params as { session?: unknown } | undefined)?.session; + return typeof session === "string" ? session : (session as FakeSession | null)?.id; + }); + expect(activated, "the native session was never activated in JS").toContain("sess_native"); + }); + + act(() => root.unmount()); +}); diff --git a/apps/mobile/vite.config.ts b/apps/mobile/vite.config.ts index 6f5c4558b5a27..856b769381ae2 100644 --- a/apps/mobile/vite.config.ts +++ b/apps/mobile/vite.config.ts @@ -42,6 +42,7 @@ const reactTests = [ "src/features/home/home-list-options.test.tsx", "src/features/workspace/useSearchScrollRestoration.test.tsx", "src/features/connection/ConnectionsNewRouteScreen.test.tsx", + "src/features/settings/SettingsAuthRouteScreen.test.tsx", ]; const sourceRoot = `${normalizePath(NodeURL.fileURLToPath(new URL("./src", import.meta.url)))}/`; From 219ca3dd0eaa8c41ee852da472b4a6afdffecd21 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 4 Nov 2026 14:01:38 +0000 Subject: [PATCH 2/9] fix(mobile): adopt the native Clerk session instead of a dead-end sign-in Native Clerk could hold a session while the JS client reported signed out, so the T3 Account screen offered a native sign-in that only fails with "You're already signed in." and T3 Connect stayed signed out. When the screen opens signed out, reload the JS client once (its token cache reads the native-owned device token), apply it, and activate its last active or first signed-in session. The sign-in form renders immediately and a failed refresh is only logged. Co-Authored-By: Claude Opus 5.5 --- .../features/cloud/adoptNativeClerkSession.ts | 14 +++++++++++ .../settings/SettingsAuthRouteScreen.test.tsx | 25 ++++++++++++++----- .../settings/SettingsAuthRouteScreen.tsx | 9 +++++++ vite.config.ts | 1 + 4 files changed, 43 insertions(+), 6 deletions(-) create mode 100644 apps/mobile/src/features/cloud/adoptNativeClerkSession.ts diff --git a/apps/mobile/src/features/cloud/adoptNativeClerkSession.ts b/apps/mobile/src/features/cloud/adoptNativeClerkSession.ts new file mode 100644 index 0000000000000..9e251bf93e55c --- /dev/null +++ b/apps/mobile/src/features/cloud/adoptNativeClerkSession.ts @@ -0,0 +1,14 @@ +import { getClerkInstance } from "@clerk/expo"; + +// Native Clerk can hold a session the JS client never saw; the native AuthView then only fails +// with `session_exists`. The JS token cache reads the native-owned device token, so the reloaded +// client is the native one. Mirrors @clerk/expo's unexported native client sync `pull()`. +export async function adoptNativeClerkSession(): Promise { + const clerk = getClerkInstance(); + const client = await clerk.client?.reload(); + if (!client) return; + clerk.updateClient(client); + const sessions = client.signedInSessions; + const session = sessions.find(({ id }) => id === client.lastActiveSessionId) ?? sessions[0]; + if (session && clerk.session?.id !== session.id) await clerk.setActive({ session }); +} diff --git a/apps/mobile/src/features/settings/SettingsAuthRouteScreen.test.tsx b/apps/mobile/src/features/settings/SettingsAuthRouteScreen.test.tsx index 457c99852559f..71dda0f2c8d25 100644 --- a/apps/mobile/src/features/settings/SettingsAuthRouteScreen.test.tsx +++ b/apps/mobile/src/features/settings/SettingsAuthRouteScreen.test.tsx @@ -54,12 +54,8 @@ function client(sessions: readonly FakeSession[]): FakeClient { return self; } -it("adopts the session the native-backed client already holds instead of offering a doomed sign-in", async () => { +function setup(refreshed: FakeClient) { (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; - const nativeSession = { id: "sess_native", status: "active" }; - // The JS client is stale and signed out; refreshing it from the shared device - // token returns the session native Clerk reports as `session_exists`. - const refreshed = client([nativeSession]); const stale = { ...client([]), fetch: async () => refreshed, reload: async () => refreshed }; harness.clerk = { client: stale, @@ -69,9 +65,16 @@ it("adopts the session the native-backed client already holds instead of offerin }, setActive: vi.fn(async () => {}), }; - const root = createRoot(document.createElement("div")); act(() => root.render()); + return root; +} + +it("adopts the session the native-backed client already holds instead of offering a doomed sign-in", async () => { + const nativeSession = { id: "sess_native", status: "active" }; + // The JS client is stale and signed out; refreshing it from the shared device + // token returns the session native Clerk reports as `session_exists`. + const root = setup(client([nativeSession])); await vi.waitFor(() => { const activated = harness.clerk.setActive.mock.calls.map(([params]) => { @@ -83,3 +86,13 @@ it("adopts the session the native-backed client already holds instead of offerin act(() => root.unmount()); }); + +it("leaves a truly signed-out user on the sign-in form", async () => { + const refreshed = client([]); + const root = setup(refreshed); + + await vi.waitFor(() => expect(harness.clerk.client).toBe(refreshed)); + expect(harness.clerk.setActive).not.toHaveBeenCalled(); + + act(() => root.unmount()); +}); diff --git a/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx index 276f51fcb3891..bf561d9dcd8fe 100644 --- a/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx @@ -8,6 +8,7 @@ import { useNavigation } from "@react-navigation/native"; import { useEffect, useState } from "react"; import { View } from "react-native"; +import { adoptNativeClerkSession } from "../cloud/adoptNativeClerkSession"; import { hasCloudPublicConfig } from "../cloud/publicConfig"; import { T3ConnectProfilePage } from "../cloud/T3ConnectProfilePage"; @@ -34,6 +35,14 @@ function ConfiguredSettingsAuthRouteScreen() { const [hasBeenSignedIn, setHasBeenSignedIn] = useState(isSignedIn === true); if (isSignedIn && !hasBeenSignedIn) setHasBeenSignedIn(true); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- refreshes Clerk's JS client from the native device token once, so a session native Clerk already holds is adopted instead of AuthView failing with session_exists + useEffect(() => { + if (!isLoaded || hasBeenSignedIn) return; + adoptNativeClerkSession().catch((error: unknown) => { + console.warn("[clerk] could not refresh the client from the native session", error); + }); + }, [isLoaded, hasBeenSignedIn]); + // Clerk reports sign-out only through its auth store (the native profile view // and the T3 Connect page can both sign out), so this follows that store. // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- pops the navigator when Clerk's auth store reports a sign-out from the profile view or Connect page diff --git a/vite.config.ts b/vite.config.ts index c92ad24843f91..de8f01f1d61de 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -341,6 +341,7 @@ export default defineConfig({ files: [ "apps/web/src/components/settings/AuthorizedClientsSettings.tsx", "apps/mobile/src/features/updates/app-updates.ts", + "apps/mobile/src/features/cloud/adoptNativeClerkSession.ts", "apps/web/src/components/device/DevicePhoneViewport.tsx", "apps/web/src/components/device/DeviceDuoViewport.tsx", ], From 80cd6a71f241614a3b1429cc557289613b9b5d39 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 4 Nov 2026 14:15:55 +0000 Subject: [PATCH 3/9] fix(mobile): hold the Clerk sign-in form until the client refresh settles The one-time client refresh mutates Clerk's shared client in place. If the user signed in natively while it was in flight, the stale signed-out response landed last and cleared the new session. AuthView now appears only after the refresh succeeds, fails, or finds no session. Co-Authored-By: Claude Opus 5.5 --- .../settings/SettingsAuthRouteScreen.test.tsx | 33 ++++++++++++------- .../settings/SettingsAuthRouteScreen.tsx | 16 +++++---- 2 files changed, 32 insertions(+), 17 deletions(-) diff --git a/apps/mobile/src/features/settings/SettingsAuthRouteScreen.test.tsx b/apps/mobile/src/features/settings/SettingsAuthRouteScreen.test.tsx index 71dda0f2c8d25..426d1b4062363 100644 --- a/apps/mobile/src/features/settings/SettingsAuthRouteScreen.test.tsx +++ b/apps/mobile/src/features/settings/SettingsAuthRouteScreen.test.tsx @@ -35,7 +35,7 @@ vi.mock("@clerk/expo", () => ({ getClerkInstance: () => harness.clerk, })); vi.mock("@clerk/expo/native-components", () => ({ - AuthView: () => null, + AuthView: () => sign-in form, UserProfileView: () => null, })); vi.mock("../cloud/publicConfig", () => ({ hasCloudPublicConfig: () => true })); @@ -54,9 +54,10 @@ function client(sessions: readonly FakeSession[]): FakeClient { return self; } -function setup(refreshed: FakeClient) { +function setup(refreshed: FakeClient | Promise) { (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; - const stale = { ...client([]), fetch: async () => refreshed, reload: async () => refreshed }; + const refresh = async () => refreshed; + const stale = { ...client([]), fetch: refresh, reload: refresh }; harness.clerk = { client: stale, session: null, @@ -65,16 +66,17 @@ function setup(refreshed: FakeClient) { }, setActive: vi.fn(async () => {}), }; - const root = createRoot(document.createElement("div")); + const container = document.createElement("div"); + const root = createRoot(container); act(() => root.render()); - return root; + return { container, [Symbol.dispose]: () => act(() => root.unmount()) }; } it("adopts the session the native-backed client already holds instead of offering a doomed sign-in", async () => { const nativeSession = { id: "sess_native", status: "active" }; // The JS client is stale and signed out; refreshing it from the shared device // token returns the session native Clerk reports as `session_exists`. - const root = setup(client([nativeSession])); + using _screen = setup(client([nativeSession])); await vi.waitFor(() => { const activated = harness.clerk.setActive.mock.calls.map(([params]) => { @@ -83,16 +85,25 @@ it("adopts the session the native-backed client already holds instead of offerin }); expect(activated, "the native session was never activated in JS").toContain("sess_native"); }); - - act(() => root.unmount()); }); it("leaves a truly signed-out user on the sign-in form", async () => { const refreshed = client([]); - const root = setup(refreshed); + using screen = setup(refreshed); - await vi.waitFor(() => expect(harness.clerk.client).toBe(refreshed)); + await vi.waitFor(() => expect(screen.container.textContent).toContain("sign-in form")); + expect(harness.clerk.client).toBe(refreshed); expect(harness.clerk.setActive).not.toHaveBeenCalled(); +}); + +it("does not offer the sign-in form until the client refresh settles", async () => { + // A native sign-in during a slow refresh would be wiped when the stale response lands. + const { promise, resolve } = Promise.withResolvers(); + using screen = setup(promise); - act(() => root.unmount()); + expect(screen.container.textContent).not.toContain("sign-in form"); + + await act(async () => resolve(client([]))); + expect(screen.container.textContent).toContain("sign-in form"); + expect(harness.clerk.setActive).not.toHaveBeenCalled(); }); diff --git a/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx index bf561d9dcd8fe..6811958023d90 100644 --- a/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx @@ -34,14 +34,18 @@ function ConfiguredSettingsAuthRouteScreen() { // flashing the sign-in form. const [hasBeenSignedIn, setHasBeenSignedIn] = useState(isSignedIn === true); if (isSignedIn && !hasBeenSignedIn) setHasBeenSignedIn(true); + // AuthView waits for the refresh: a stale response landing after a native sign-in would wipe it. + const [isRefreshingClient, setIsRefreshingClient] = useState(isSignedIn !== true); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- refreshes Clerk's JS client from the native device token once, so a session native Clerk already holds is adopted instead of AuthView failing with session_exists useEffect(() => { - if (!isLoaded || hasBeenSignedIn) return; - adoptNativeClerkSession().catch((error: unknown) => { - console.warn("[clerk] could not refresh the client from the native session", error); - }); - }, [isLoaded, hasBeenSignedIn]); + if (!isLoaded || hasBeenSignedIn || !isRefreshingClient) return; + adoptNativeClerkSession() + .catch((error: unknown) => { + console.warn("[clerk] could not refresh the client from the native session", error); + }) + .finally(() => setIsRefreshingClient(false)); + }, [isLoaded, hasBeenSignedIn, isRefreshingClient]); // Clerk reports sign-out only through its auth store (the native profile view // and the T3 Connect page can both sign out), so this follows that store. @@ -61,7 +65,7 @@ function ConfiguredSettingsAuthRouteScreen() { isDismissible={false} onHostBack={handleHostBack} /> - ) : ( + ) : isRefreshingClient ? null : ( ) ) : null} From 18602f2fbd43478638f5f7800b55aac2c0192528 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 4 Nov 2026 14:27:16 +0000 Subject: [PATCH 4/9] fix(mobile): share one Clerk client refresh across sign-in screen mounts A sign-in screen dismissed mid-refresh left its reload in flight; a reopened screen then offered sign-in, and the older response could clear the new session when it landed. Reopened screens now wait on the same refresh. Co-Authored-By: Claude Opus 5.5 --- .../features/cloud/adoptNativeClerkSession.ts | 12 +++++++++- .../settings/SettingsAuthRouteScreen.test.tsx | 23 +++++++++++++++++-- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/apps/mobile/src/features/cloud/adoptNativeClerkSession.ts b/apps/mobile/src/features/cloud/adoptNativeClerkSession.ts index 9e251bf93e55c..1d662c73a4028 100644 --- a/apps/mobile/src/features/cloud/adoptNativeClerkSession.ts +++ b/apps/mobile/src/features/cloud/adoptNativeClerkSession.ts @@ -3,7 +3,17 @@ import { getClerkInstance } from "@clerk/expo"; // Native Clerk can hold a session the JS client never saw; the native AuthView then only fails // with `session_exists`. The JS token cache reads the native-owned device token, so the reloaded // client is the native one. Mirrors @clerk/expo's unexported native client sync `pull()`. -export async function adoptNativeClerkSession(): Promise { +export function adoptNativeClerkSession(): Promise { + // One refresh at a time: a reopened screen must not sign in while an older reload can still land. + pendingAdoption ??= adopt().finally(() => { + pendingAdoption = null; + }); + return pendingAdoption; +} + +let pendingAdoption: Promise | null = null; + +async function adopt(): Promise { const clerk = getClerkInstance(); const client = await clerk.client?.reload(); if (!client) return; diff --git a/apps/mobile/src/features/settings/SettingsAuthRouteScreen.test.tsx b/apps/mobile/src/features/settings/SettingsAuthRouteScreen.test.tsx index 426d1b4062363..6d641b2444ab1 100644 --- a/apps/mobile/src/features/settings/SettingsAuthRouteScreen.test.tsx +++ b/apps/mobile/src/features/settings/SettingsAuthRouteScreen.test.tsx @@ -54,9 +54,10 @@ function client(sessions: readonly FakeSession[]): FakeClient { return self; } -function setup(refreshed: FakeClient | Promise) { +function setup(...refreshes: readonly (FakeClient | Promise)[]) { (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; - const refresh = async () => refreshed; + let calls = 0; + const refresh = async () => refreshes[Math.min(calls++, refreshes.length - 1)]!; const stale = { ...client([]), fetch: refresh, reload: refresh }; harness.clerk = { client: stale, @@ -66,6 +67,10 @@ function setup(refreshed: FakeClient | Promise) { }, setActive: vi.fn(async () => {}), }; + return mount(); +} + +function mount() { const container = document.createElement("div"); const root = createRoot(container); act(() => root.render()); @@ -107,3 +112,17 @@ it("does not offer the sign-in form until the client refresh settles", async () expect(screen.container.textContent).toContain("sign-in form"); expect(harness.clerk.setActive).not.toHaveBeenCalled(); }); + +it("a reopened screen waits for the refresh a dismissed screen left in flight", async () => { + // The older reload mutates Clerk's shared client when it lands, so it must settle before sign-in. + const { promise, resolve } = Promise.withResolvers(); + const dismissed = setup(promise, client([])); + dismissed[Symbol.dispose](); + using reopened = mount(); + + await act(async () => {}); + expect(reopened.container.textContent).not.toContain("sign-in form"); + + await act(async () => resolve(client([]))); + expect(reopened.container.textContent).toContain("sign-in form"); +}); From 7ab735c4e0fe78ab074fd7b9434115abd2ad3fe8 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 4 Nov 2026 14:53:58 +0000 Subject: [PATCH 5/9] test(mobile): sign-in recovery tests assert the profile screen without polling The adoption test now drives the auth store and asserts the recovered profile view instead of a mocked setActive call, and the tests settle on act() instead of vi.waitFor polling. The signed-out case folds into the settle test. Co-Authored-By: Claude Opus 5.5 --- .../settings/SettingsAuthRouteScreen.test.tsx | 58 ++++++++++--------- 1 file changed, 30 insertions(+), 28 deletions(-) diff --git a/apps/mobile/src/features/settings/SettingsAuthRouteScreen.test.tsx b/apps/mobile/src/features/settings/SettingsAuthRouteScreen.test.tsx index 6d641b2444ab1..c1e03e62b838c 100644 --- a/apps/mobile/src/features/settings/SettingsAuthRouteScreen.test.tsx +++ b/apps/mobile/src/features/settings/SettingsAuthRouteScreen.test.tsx @@ -11,7 +11,6 @@ interface FakeClient { readonly id: string; readonly lastActiveSessionId: string | null; readonly signedInSessions: readonly FakeSession[]; - readonly fetch: () => Promise; readonly reload: () => Promise; } @@ -24,19 +23,30 @@ const { Children, harness } = vi.hoisted(() => ({ updateClient: (client: unknown) => void; setActive: ReturnType; }, + isSignedIn: false, + authListeners: new Set<() => void>(), }, })); vi.mock("react-native", () => ({ View: Children })); vi.mock("@react-navigation/native", () => ({ useNavigation: () => ({ goBack: vi.fn() }) })); -vi.mock("@clerk/expo", () => ({ - useAuth: () => ({ isLoaded: true, isSignedIn: false }), - useClerk: () => harness.clerk, - getClerkInstance: () => harness.clerk, -})); +vi.mock("@clerk/expo", async () => { + const { useSyncExternalStore } = await import("react"); + const subscribe = (listener: () => void) => { + harness.authListeners.add(listener); + return () => harness.authListeners.delete(listener); + }; + return { + useAuth: () => ({ + isLoaded: true, + isSignedIn: useSyncExternalStore(subscribe, () => harness.isSignedIn), + }), + getClerkInstance: () => harness.clerk, + }; +}); vi.mock("@clerk/expo/native-components", () => ({ AuthView: () => sign-in form, - UserProfileView: () => null, + UserProfileView: () => profile, })); vi.mock("../cloud/publicConfig", () => ({ hasCloudPublicConfig: () => true })); vi.mock("../cloud/T3ConnectProfilePage", () => ({ T3ConnectProfilePage: () => null })); @@ -48,7 +58,6 @@ function client(sessions: readonly FakeSession[]): FakeClient { id: "client_device", lastActiveSessionId: sessions[0]?.id ?? null, signedInSessions: sessions, - fetch: async () => self, reload: async () => self, }; return self; @@ -58,14 +67,18 @@ function setup(...refreshes: readonly (FakeClient | Promise)[]) { (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; let calls = 0; const refresh = async () => refreshes[Math.min(calls++, refreshes.length - 1)]!; - const stale = { ...client([]), fetch: refresh, reload: refresh }; + harness.isSignedIn = false; + harness.authListeners.clear(); harness.clerk = { - client: stale, + client: { ...client([]), reload: refresh }, session: null, updateClient: (next) => { harness.clerk.client = next; }, - setActive: vi.fn(async () => {}), + setActive: vi.fn(async () => { + harness.isSignedIn = true; + for (const listener of harness.authListeners) listener(); + }), }; return mount(); } @@ -78,29 +91,18 @@ function mount() { } it("adopts the session the native-backed client already holds instead of offering a doomed sign-in", async () => { - const nativeSession = { id: "sess_native", status: "active" }; // The JS client is stale and signed out; refreshing it from the shared device // token returns the session native Clerk reports as `session_exists`. - using _screen = setup(client([nativeSession])); + const { promise, resolve } = Promise.withResolvers(); + using screen = setup(promise); - await vi.waitFor(() => { - const activated = harness.clerk.setActive.mock.calls.map(([params]) => { - const session = (params as { session?: unknown } | undefined)?.session; - return typeof session === "string" ? session : (session as FakeSession | null)?.id; - }); - expect(activated, "the native session was never activated in JS").toContain("sess_native"); + await act(async () => resolve(client([{ id: "sess_native", status: "active" }]))); + expect(screen.container.textContent).toBe("profile"); + expect(harness.clerk.setActive).toHaveBeenCalledWith({ + session: expect.objectContaining({ id: "sess_native" }), }); }); -it("leaves a truly signed-out user on the sign-in form", async () => { - const refreshed = client([]); - using screen = setup(refreshed); - - await vi.waitFor(() => expect(screen.container.textContent).toContain("sign-in form")); - expect(harness.clerk.client).toBe(refreshed); - expect(harness.clerk.setActive).not.toHaveBeenCalled(); -}); - it("does not offer the sign-in form until the client refresh settles", async () => { // A native sign-in during a slow refresh would be wiped when the stale response lands. const { promise, resolve } = Promise.withResolvers(); From 32d75c55decff366265a854c4785cb8b8396f5b7 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 00:09:28 +0000 Subject: [PATCH 6/9] refactor(mobile): declare the shared Clerk refresh before its use AI-assisted; verified with the tests and tools listed above. --- apps/mobile/src/features/cloud/adoptNativeClerkSession.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/mobile/src/features/cloud/adoptNativeClerkSession.ts b/apps/mobile/src/features/cloud/adoptNativeClerkSession.ts index 1d662c73a4028..6d0e6d8f3173c 100644 --- a/apps/mobile/src/features/cloud/adoptNativeClerkSession.ts +++ b/apps/mobile/src/features/cloud/adoptNativeClerkSession.ts @@ -1,5 +1,7 @@ import { getClerkInstance } from "@clerk/expo"; +let pendingAdoption: Promise | null = null; + // Native Clerk can hold a session the JS client never saw; the native AuthView then only fails // with `session_exists`. The JS token cache reads the native-owned device token, so the reloaded // client is the native one. Mirrors @clerk/expo's unexported native client sync `pull()`. @@ -11,8 +13,6 @@ export function adoptNativeClerkSession(): Promise { return pendingAdoption; } -let pendingAdoption: Promise | null = null; - async function adopt(): Promise { const clerk = getClerkInstance(); const client = await clerk.client?.reload(); From c8850ff48213d67c893b205eda6e06f7691b79fd Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 03:08:59 +0000 Subject: [PATCH 7/9] test(mobile): drop the sign-in gating case the reopened-screen case covers AI-assisted; verified with the tests and tools listed above. --- .../settings/SettingsAuthRouteScreen.test.tsx | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/apps/mobile/src/features/settings/SettingsAuthRouteScreen.test.tsx b/apps/mobile/src/features/settings/SettingsAuthRouteScreen.test.tsx index c1e03e62b838c..d6e73cbb43d2a 100644 --- a/apps/mobile/src/features/settings/SettingsAuthRouteScreen.test.tsx +++ b/apps/mobile/src/features/settings/SettingsAuthRouteScreen.test.tsx @@ -103,18 +103,6 @@ it("adopts the session the native-backed client already holds instead of offerin }); }); -it("does not offer the sign-in form until the client refresh settles", async () => { - // A native sign-in during a slow refresh would be wiped when the stale response lands. - const { promise, resolve } = Promise.withResolvers(); - using screen = setup(promise); - - expect(screen.container.textContent).not.toContain("sign-in form"); - - await act(async () => resolve(client([]))); - expect(screen.container.textContent).toContain("sign-in form"); - expect(harness.clerk.setActive).not.toHaveBeenCalled(); -}); - it("a reopened screen waits for the refresh a dismissed screen left in flight", async () => { // The older reload mutates Clerk's shared client when it lands, so it must settle before sign-in. const { promise, resolve } = Promise.withResolvers(); From 6375735935a688d47ac81fa9e65ac89bce7ec3c3 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 13 Nov 2026 23:42:52 +0000 Subject: [PATCH 8/9] fix(mobile): sign-in form appears even when the Clerk client refresh stalls The sheet stayed blank for as long as reload() hung. Wait at most eight seconds, then show the form; the shared reload keeps running for later mounts. Co-Authored-By: Claude Opus 5.5 --- .../features/settings/SettingsAuthRouteScreen.test.tsx | 10 ++++++++++ .../src/features/settings/SettingsAuthRouteScreen.tsx | 10 +++++++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/apps/mobile/src/features/settings/SettingsAuthRouteScreen.test.tsx b/apps/mobile/src/features/settings/SettingsAuthRouteScreen.test.tsx index d6e73cbb43d2a..5a88b9e642a5b 100644 --- a/apps/mobile/src/features/settings/SettingsAuthRouteScreen.test.tsx +++ b/apps/mobile/src/features/settings/SettingsAuthRouteScreen.test.tsx @@ -116,3 +116,13 @@ it("a reopened screen waits for the refresh a dismissed screen left in flight", await act(async () => resolve(client([]))); expect(reopened.container.textContent).toContain("sign-in form"); }); + +it("offers the sign-in form when the client refresh stalls", async () => { + vi.useFakeTimers(); + using _timers = { [Symbol.dispose]: () => vi.useRealTimers() }; + using screen = setup(new Promise(() => {})); + expect(screen.container.textContent).not.toContain("sign-in form"); + + await act(async () => vi.advanceTimersByTime(8_000)); + expect(screen.container.textContent).toContain("sign-in form"); +}); diff --git a/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx index 6811958023d90..64e80a0ef098e 100644 --- a/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx @@ -21,6 +21,8 @@ const USER_PROFILE_CUSTOM_PAGES = [ }, ] satisfies UserProfileCustomPage[]; +const CLIENT_REFRESH_TIMEOUT_MS = 8_000; + // Without cloud config the app has no entry point here and appLinking drops the deep link. export function SettingsAuthRouteScreen() { return hasCloudPublicConfig() ? : null; @@ -40,11 +42,17 @@ function ConfiguredSettingsAuthRouteScreen() { // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- refreshes Clerk's JS client from the native device token once, so a session native Clerk already holds is adopted instead of AuthView failing with session_exists useEffect(() => { if (!isLoaded || hasBeenSignedIn || !isRefreshingClient) return; + // A stalled reload must not leave the sheet blank; past this, the form beats waiting. + const timeout = setTimeout(() => setIsRefreshingClient(false), CLIENT_REFRESH_TIMEOUT_MS); adoptNativeClerkSession() .catch((error: unknown) => { console.warn("[clerk] could not refresh the client from the native session", error); }) - .finally(() => setIsRefreshingClient(false)); + .finally(() => { + clearTimeout(timeout); + setIsRefreshingClient(false); + }); + return () => clearTimeout(timeout); }, [isLoaded, hasBeenSignedIn, isRefreshingClient]); // Clerk reports sign-out only through its auth store (the native profile view From d3c50371d4a2ec6a2c49d441ea9c4ba80f4b6749 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 13 Nov 2026 23:44:56 +0000 Subject: [PATCH 9/9] fix(mobile): a Clerk refresh past its deadline no longer adopts a session Move the deadline into adoptNativeClerkSession so a reload that lands after the sign-in form appeared skips updateClient and setActive. Co-Authored-By: Claude Opus 5.5 --- .../features/cloud/adoptNativeClerkSession.ts | 18 +++++++++++++++--- .../settings/SettingsAuthRouteScreen.test.tsx | 8 ++++++-- .../settings/SettingsAuthRouteScreen.tsx | 10 +--------- 3 files changed, 22 insertions(+), 14 deletions(-) diff --git a/apps/mobile/src/features/cloud/adoptNativeClerkSession.ts b/apps/mobile/src/features/cloud/adoptNativeClerkSession.ts index 6d0e6d8f3173c..989b12819045b 100644 --- a/apps/mobile/src/features/cloud/adoptNativeClerkSession.ts +++ b/apps/mobile/src/features/cloud/adoptNativeClerkSession.ts @@ -1,5 +1,7 @@ import { getClerkInstance } from "@clerk/expo"; +const ADOPTION_DEADLINE_MS = 8_000; + let pendingAdoption: Promise | null = null; // Native Clerk can hold a session the JS client never saw; the native AuthView then only fails @@ -7,16 +9,26 @@ let pendingAdoption: Promise | null = null; // client is the native one. Mirrors @clerk/expo's unexported native client sync `pull()`. export function adoptNativeClerkSession(): Promise { // One refresh at a time: a reopened screen must not sign in while an older reload can still land. - pendingAdoption ??= adopt().finally(() => { + pendingAdoption ??= new Promise((resolve, reject) => { + // A stalled reload must not hold sign-in back; once past the deadline its result is ignored. + let isStale = false; + const deadline = setTimeout(() => { + isStale = true; + resolve(); + }, ADOPTION_DEADLINE_MS); + adopt(() => isStale) + .then(resolve, reject) + .finally(() => clearTimeout(deadline)); + }).finally(() => { pendingAdoption = null; }); return pendingAdoption; } -async function adopt(): Promise { +async function adopt(isStale: () => boolean): Promise { const clerk = getClerkInstance(); const client = await clerk.client?.reload(); - if (!client) return; + if (!client || isStale()) return; clerk.updateClient(client); const sessions = client.signedInSessions; const session = sessions.find(({ id }) => id === client.lastActiveSessionId) ?? sessions[0]; diff --git a/apps/mobile/src/features/settings/SettingsAuthRouteScreen.test.tsx b/apps/mobile/src/features/settings/SettingsAuthRouteScreen.test.tsx index 5a88b9e642a5b..c5ef061068072 100644 --- a/apps/mobile/src/features/settings/SettingsAuthRouteScreen.test.tsx +++ b/apps/mobile/src/features/settings/SettingsAuthRouteScreen.test.tsx @@ -117,12 +117,16 @@ it("a reopened screen waits for the refresh a dismissed screen left in flight", expect(reopened.container.textContent).toContain("sign-in form"); }); -it("offers the sign-in form when the client refresh stalls", async () => { +it("offers the sign-in form when the client refresh stalls, and ignores its late result", async () => { vi.useFakeTimers(); using _timers = { [Symbol.dispose]: () => vi.useRealTimers() }; - using screen = setup(new Promise(() => {})); + const { promise, resolve } = Promise.withResolvers(); + using screen = setup(promise); expect(screen.container.textContent).not.toContain("sign-in form"); await act(async () => vi.advanceTimersByTime(8_000)); expect(screen.container.textContent).toContain("sign-in form"); + + await act(async () => resolve(client([{ id: "sess_late", status: "active" }]))); + expect(harness.clerk.setActive).not.toHaveBeenCalled(); }); diff --git a/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx index 64e80a0ef098e..6811958023d90 100644 --- a/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx @@ -21,8 +21,6 @@ const USER_PROFILE_CUSTOM_PAGES = [ }, ] satisfies UserProfileCustomPage[]; -const CLIENT_REFRESH_TIMEOUT_MS = 8_000; - // Without cloud config the app has no entry point here and appLinking drops the deep link. export function SettingsAuthRouteScreen() { return hasCloudPublicConfig() ? : null; @@ -42,17 +40,11 @@ function ConfiguredSettingsAuthRouteScreen() { // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- refreshes Clerk's JS client from the native device token once, so a session native Clerk already holds is adopted instead of AuthView failing with session_exists useEffect(() => { if (!isLoaded || hasBeenSignedIn || !isRefreshingClient) return; - // A stalled reload must not leave the sheet blank; past this, the form beats waiting. - const timeout = setTimeout(() => setIsRefreshingClient(false), CLIENT_REFRESH_TIMEOUT_MS); adoptNativeClerkSession() .catch((error: unknown) => { console.warn("[clerk] could not refresh the client from the native session", error); }) - .finally(() => { - clearTimeout(timeout); - setIsRefreshingClient(false); - }); - return () => clearTimeout(timeout); + .finally(() => setIsRefreshingClient(false)); }, [isLoaded, hasBeenSignedIn, isRefreshingClient]); // Clerk reports sign-out only through its auth store (the native profile view