Repository navigation
fix(mobile): sign-in adopts the session native Clerk already holds #30893
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
juliusmarminge
wants to merge
15
commits into
main
Choose a base branch
from
fix/issue-30861
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+184
−1
Open
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
cd23dbf
test(mobile): reproduce #30861 Clerk sign-in dead end on native session
juliusmarminge 219ca3d
fix(mobile): adopt the native Clerk session instead of a dead-end sig…
juliusmarminge 80cd6a7
fix(mobile): hold the Clerk sign-in form until the client refresh set…
juliusmarminge 18602f2
fix(mobile): share one Clerk client refresh across sign-in screen mounts
juliusmarminge 864a34a
Merge origin/main into fix/issue-30861
juliusmarminge 7ab735c
test(mobile): sign-in recovery tests assert the profile screen withou…
juliusmarminge 4ab6649
Merge remote-tracking branch 'origin/main' into fix/issue-30861
juliusmarminge 43a1ef5
Merge commit 'refs/factory/gh-main' into fix/issue-30861
juliusmarminge 32d75c5
refactor(mobile): declare the shared Clerk refresh before its use
juliusmarminge 2d09c36
Merge remote-tracking branch 'origin/main' into fix/issue-30861
juliusmarminge c8850ff
test(mobile): drop the sign-in gating case the reopened-screen case c…
juliusmarminge 4fd4341
Merge remote-tracking branch 'origin/main' into fix/issue-30861
juliusmarminge b728eed
Merge remote-tracking branch 'origin/main' into fix/issue-30861
juliusmarminge 6375735
fix(mobile): sign-in form appears even when the Clerk client refresh …
juliusmarminge d3c5037
fix(mobile): a Clerk refresh past its deadline no longer adopts a ses…
juliusmarminge File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| import { getClerkInstance } from "@clerk/expo"; | ||
|
|
||
| const ADOPTION_DEADLINE_MS = 8_000; | ||
|
|
||
| let pendingAdoption: Promise<void> | 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<void> { | ||
| // One refresh at a time: a reopened screen must not sign in while an older reload can still land. | ||
| pendingAdoption ??= new Promise<void>((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<void> { | ||
| 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 }); | ||
| } | ||
132 changes: 132 additions & 0 deletions
132
apps/mobile/src/features/settings/SettingsAuthRouteScreen.test.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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<FakeClient>; | ||
| } | ||
|
|
||
| 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<typeof vi.fn>; | ||
| }, | ||
| 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: () => <span>sign-in form</span>, | ||
| UserProfileView: () => <span>profile</span>, | ||
| })); | ||
| 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<FakeClient>)[]) { | ||
| (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(<SettingsAuthRouteScreen />)); | ||
| 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<FakeClient>(); | ||
| 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<FakeClient>(); | ||
| 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<FakeClient>(); | ||
| 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(); | ||
| }); |
|
macroscopeapp[bot] marked this conversation as resolved.
Resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Script executed:
Repository: pingdotgg/t3code
Length of output: 10092
Script executed:
Repository: pingdotgg/t3code
Length of output: 13732
Script executed:
Repository: pingdotgg/t3code
Length of output: 7664
Script executed:
Repository: pingdotgg/t3code
Length of output: 36601
Script executed:
Repository: pingdotgg/t3code
Length of output: 17646
Bound the client refresh before blocking sign-in.
If the reload stalls, the screen can remain blank while the user is signed out. Add a deadline and prevent a late response from updating Clerk before showing sign-in. A timeout around
reload()alone leaves that update possible.