diff --git a/apps/mobile/src/features/cloud/adoptNativeClerkSession.ts b/apps/mobile/src/features/cloud/adoptNativeClerkSession.ts new file mode 100644 index 0000000000000..989b12819045b --- /dev/null +++ b/apps/mobile/src/features/cloud/adoptNativeClerkSession.ts @@ -0,0 +1,36 @@ +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 +// 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 function adoptNativeClerkSession(): Promise { + // One refresh at a time: a reopened screen must not sign in while an older reload can still land. + 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(isStale: () => boolean): Promise { + const clerk = getClerkInstance(); + const client = await clerk.client?.reload(); + if (!client || isStale()) 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 new file mode 100644 index 0000000000000..c5ef061068072 --- /dev/null +++ b/apps/mobile/src/features/settings/SettingsAuthRouteScreen.test.tsx @@ -0,0 +1,132 @@ +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 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; + }, + 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", 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: () => profile, +})); +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, + reload: async () => self, + }; + return self; +} + +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)]!; + harness.isSignedIn = false; + harness.authListeners.clear(); + harness.clerk = { + client: { ...client([]), reload: refresh }, + session: null, + updateClient: (next) => { + harness.clerk.client = next; + }, + setActive: vi.fn(async () => { + harness.isSignedIn = true; + for (const listener of harness.authListeners) listener(); + }), + }; + return mount(); +} + +function mount() { + const container = document.createElement("div"); + const root = createRoot(container); + act(() => root.render()); + 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 () => { + // 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 { promise, resolve } = Promise.withResolvers(); + using screen = setup(promise); + + 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("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"); +}); + +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() }; + 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 276f51fcb3891..6811958023d90 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"; @@ -33,6 +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 || !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. @@ -52,7 +65,7 @@ function ConfiguredSettingsAuthRouteScreen() { isDismissible={false} onHostBack={handleHostBack} /> - ) : ( + ) : isRefreshingClient ? null : ( ) ) : null} diff --git a/apps/mobile/vite.config.ts b/apps/mobile/vite.config.ts index 2b688fee30ad2..1d3c852eef60a 100644 --- a/apps/mobile/vite.config.ts +++ b/apps/mobile/vite.config.ts @@ -48,6 +48,7 @@ const reactTests = [ "src/features/connection/ConnectionsNewRouteScreen.test.tsx", "src/features/devices/device-stream.browser.test.ts", "src/features/keyboard/keyboardControllerState.test.tsx", + "src/features/settings/SettingsAuthRouteScreen.test.tsx", ]; const sourceRoot = `${normalizePath(NodeURL.fileURLToPath(new URL("./src", import.meta.url)))}/`; diff --git a/vite.config.ts b/vite.config.ts index c7a92ccbc9ad1..eef8103e302f8 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -369,6 +369,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", ],