Skip to content

Commit 074a69c

Browse files
authored
fix(mobile): retry Clerk startup after a failed or stalled load (#436)
> [!NOTE] > On mobile, if Clerk's first load fails or stalls (for example, right after joining a new WiFi network), the app stays signed out of styal Link until it is restarted. Clerk requests now time out, and failed loads are retried until one succeeds. ## Problem On a cold start, `CloudAuthProvider` activates the styal Link relay session only after Clerk has loaded. Two things can keep `useAuth().isLoaded` false until the app is restarted: - React Native on Android creates its OkHttp client with no connect or read timeout, so Clerk's initial `/environment` and `/client` requests can wait forever on a network that is still coming up. - When the headless load fails, `@clerk/react` sets its status to `"error"` and never calls `load()` again. While this lasts, Settings shows the account as "Checking", and every styal Link environment fails with "Sign in to styal Link to connect this environment." even though the user is signed in. ## Change - `limitClerkRequestDuration` adds a Clerk `onBeforeRequest` hook that aborts GET requests after 15 seconds, so a stalled load fails instead of hanging. The hook is installed on the `getClerkInstance()` singleton before `ClerkProvider` renders, because the provider starts loading during its first render. Requests that already have an abort signal, and non-GET requests, are left unchanged. - `retryFailedClerkLoads` listens for the `"error"` status and calls `loadHeadlessClerk()` again, after 2, 4, 8 and 16 seconds, then every 30 seconds. A pending retry runs right away when the app returns to the foreground. - Both use Clerk members that are not in its public types. They check for these members at runtime and do nothing if a Clerk upgrade removes them. - Until the first load has activated a relay session, found none, or failed to activate one, the relay connection error says "Waiting for the styal Link sign-in to load." instead of asking the user to sign in. - Adds the `mobile-clerk-load-recovery` entry to the fork feature ledger. Upstream (`pingdotgg/t3code`) uses the same `ClerkProvider` setup and has no equivalent fix. ## Validation Tested on an Android emulator (API 37) running the dev client with the production Clerk publishable key, signed out. For each scenario I watched the Settings account label, which reads "Checking" while `isLoaded` is false and "Sign in" once Clerk has loaded. | Scenario | Before | After | |---|---|---| | Network off at launch, turned back on | Still "Checking" 1m45s after the network came back | "Sign in" 13 seconds after the network came back | | Clerk requests never answered (local proxy that accepts `CONNECT clerk.styal.build` and never replies), then allowed through | One pair of requests, never retried. Still "Checking" 1m20s after unblocking | Requests aborted after 15 seconds and retried after 2, 4, 8 and 16 seconds. "Sign in" on the first retry after unblocking | | Network off at launch, back on, then background and reopen the app | not run | "Sign in" 2 seconds after reopening, without waiting for the next scheduled retry | Before / after (network restored while the app stayed open): | Before | After | |---|---| | ![Before: account still shows Checking after the network is restored](https://github.com/user-attachments/assets/dc7e5cd5-dc8b-401e-895b-f84bf3d3245b) | ![After: account shows Sign in after the retry](https://github.com/user-attachments/assets/ada330b7-e80e-4796-95ca-a3d38e03a529) | `clerkLoadRecovery.test.ts` covers the backoff schedule, retrying a load that failed before the listener subscribed, retrying when the app returns to the foreground, cleanup, and aborting only stalled GET requests. Not verified: - The signed-in path, because there is no account on the test device. Clerk emits the loaded client to existing listeners when the retried load succeeds, so the relay session should activate the same way as on a normal launch. - The "Waiting for the styal Link sign-in to load." message, which needs a signed-in account with a styal Link environment. - iOS. The code is shared, but there a stalled request gives up after 60 seconds instead of waiting forever. - Web, which has a different Clerk startup and is not changed. --- Written by an agent (Claude Code, claude-opus-5-5).
1 parent ed0ea87 commit 074a69c

7 files changed

Lines changed: 336 additions & 2 deletions

File tree

‎.github/fork-features.yml‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1152,6 +1152,27 @@ features:
11521152
- https://github.com/pingdotgg/t3code/pull/9135
11531153
retire_when: Upstream validates missing project and worktree paths before every provider starts. Retire the Claude fallback message mapping and assistant error tracking earlier, when intake takes upstream's shared result outcome and expired login and usage limit messages, keeping the stream failure guard only if upstream still lets a later stream failure replace a failed result's error.
11541154

1155+
- id: mobile-clerk-load-recovery
1156+
title: Recover mobile styal Link sign-in after a failed Clerk startup
1157+
status: maintained
1158+
prs: [436]
1159+
invariants:
1160+
- A Clerk GET request on mobile that has no caller abort signal is aborted after 15 seconds, so a stalled startup load fails instead of keeping the account in the loading state.
1161+
- A failed headless Clerk load is retried with backoff capped at 30 seconds, and a pending retry runs immediately when the app returns to the foreground, so the relay session activates without restarting the app.
1162+
- Until the first Clerk load has activated a relay session, found none, or failed to activate one, relay connections report that the sign-in is still loading rather than asking the user to sign in.
1163+
implementation_paths:
1164+
- apps/mobile/src/features/cloud/clerkLoadRecovery.ts
1165+
- apps/mobile/src/features/cloud/cloudAuthState.ts
1166+
upstream_paths:
1167+
- apps/mobile/src/connection/platform.ts
1168+
- apps/mobile/src/features/cloud/CloudAuthProvider.tsx
1169+
tests:
1170+
- apps/mobile/src/features/cloud/clerkLoadRecovery.test.ts
1171+
upstream:
1172+
status: unassessed
1173+
tracking: []
1174+
retire_when: Upstream or Clerk retries a failed headless Clerk load and bounds stalled Clerk requests on mobile.
1175+
11551176
- id: preview-hidden-tab-capture
11561177
title: Capture hidden preview tabs reliably
11571178
status: maintained

‎apps/mobile/src/connection/platform.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import Constants from "expo-constants";
2525
import * as Network from "expo-network";
2626
import { AppState } from "react-native";
2727

28+
import { cloudAuthCheckingAtom } from "../features/cloud/cloudAuthState";
2829
import { authClientMetadata } from "../lib/authClientMetadata";
2930
import * as Runtime from "../lib/runtime";
3031
import * as MobileStorage from "../persistence/mobile-storage";
@@ -123,7 +124,9 @@ const capabilitiesLayer = Layer.effectContext(
123124
if (session === null) {
124125
return yield* new ConnectionBlockedError({
125126
reason: "authentication",
126-
detail: "Sign in to styal Link to connect this environment.",
127+
detail: appAtomRegistry.get(cloudAuthCheckingAtom)
128+
? "Waiting for the styal Link sign-in to load."
129+
: "Sign in to styal Link to connect this environment.",
127130
});
128131
}
129132
const token = yield* session.readClerkToken().pipe(

‎apps/mobile/src/features/cloud/CloudAuthProvider.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,10 @@ vi.mock("@clerk/expo", () => ({
1717
useAuth: vi.fn(),
1818
}));
1919

20+
vi.mock("react-native", () => ({
21+
AppState: { addEventListener: vi.fn() },
22+
}));
23+
2024
vi.mock("@clerk/expo/token-cache", () => ({
2125
tokenCache: {},
2226
}));

‎apps/mobile/src/features/cloud/CloudAuthProvider.tsx‎

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { ClerkProvider, useAuth } from "@clerk/expo";
1+
import { ClerkProvider, getClerkInstance, useAuth, useClerk } from "@clerk/expo";
22
import { tokenCache } from "@clerk/expo/token-cache";
33
import { ManagedRelay, setManagedRelaySession } from "@t3tools/client-runtime/relay";
44
import {
@@ -9,6 +9,7 @@ import {
99
} from "@t3tools/client-runtime/state/runtime";
1010
import * as Effect from "effect/Effect";
1111
import { type ReactNode, useEffect, useRef } from "react";
12+
import { AppState } from "react-native";
1213

1314
import { runtime } from "../../lib/runtime";
1415
import { appAtomRegistry } from "../../state/atom-registry";
@@ -22,7 +23,9 @@ import {
2223
setAgentAwarenessRelayTokenProvider,
2324
unregisterAgentAwarenessDeviceForCurrentUser,
2425
} from "../agent-awareness/remoteRegistration";
26+
import { limitClerkRequestDuration, retryFailedClerkLoads } from "./clerkLoadRecovery";
2527
import { clearConnectOnboardingRequest, requestConnectOnboarding } from "./connectOnboarding";
28+
import { cloudAuthCheckingAtom } from "./cloudAuthState";
2629
import { resolveCloudPublicConfig, resolveRelayClerkTokenOptions } from "./publicConfig";
2730
import { removeCloudEnvironments } from "./cloud-drafts";
2831

@@ -63,6 +66,7 @@ export async function cleanUpCloudRelayAccount(
6366
export function deactivateCloudRelayAccount(): void {
6467
setAgentAwarenessRelayTokenProvider(null);
6568
setManagedRelaySession(appAtomRegistry, null);
69+
appAtomRegistry.set(cloudAuthCheckingAtom, false);
6670
}
6771

6872
export function activateCloudRelayAccount(
@@ -74,6 +78,22 @@ export function activateCloudRelayAccount(
7478
accountId,
7579
readClerkToken: tokenProvider,
7680
});
81+
appAtomRegistry.set(cloudAuthCheckingAtom, false);
82+
}
83+
84+
function ClerkLoadRecovery() {
85+
const clerk = useClerk();
86+
useEffect(
87+
() =>
88+
retryFailedClerkLoads(clerk, (listener) => {
89+
const subscription = AppState.addEventListener("change", (state) => {
90+
if (state === "active") listener();
91+
});
92+
return () => subscription.remove();
93+
}),
94+
[clerk],
95+
);
96+
return null;
7797
}
7898

7999
function CloudAuthBridge(props: { readonly children: ReactNode }) {
@@ -170,6 +190,11 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) {
170190
})();
171191
accountTransitionRef.current = activation;
172192
void settlePromise(() => activation).then((result) => {
193+
// A failed activation leaves no relay session, so connections must stop
194+
// reporting that the sign-in is still loading.
195+
if (result._tag !== "Success" && !cancelled) {
196+
appAtomRegistry.set(cloudAuthCheckingAtom, false);
197+
}
173198
reportAtomCommandResult(result, { label: "cloud account activation" });
174199
});
175200
};
@@ -222,8 +247,11 @@ export function CloudAuthProvider(props: { readonly children: ReactNode }) {
222247
return props.children;
223248
}
224249

250+
limitClerkRequestDuration(getClerkInstance({ publishableKey }));
251+
225252
return (
226253
<ClerkProvider publishableKey={publishableKey} tokenCache={tokenCache}>
254+
<ClerkLoadRecovery />
227255
<CloudAuthBridge>{props.children}</CloudAuthBridge>
228256
</ClerkProvider>
229257
);
Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
1+
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
2+
3+
import {
4+
CLERK_LOAD_RETRY_INITIAL_DELAY_MS,
5+
CLERK_LOAD_RETRY_MAX_DELAY_MS,
6+
CLERK_REQUEST_TIMEOUT_MS,
7+
limitClerkRequestDuration,
8+
retryFailedClerkLoads,
9+
} from "./clerkLoadRecovery";
10+
11+
type Listener = (status: string) => void;
12+
13+
// Mirrors @clerk/react's IsomorphicClerk: each failed load emits "error" again.
14+
function fakeClerk(outcomes: ReadonlyArray<"error" | "ready">) {
15+
const listeners = new Set<Listener>();
16+
const remaining = [...outcomes];
17+
const clerk = {
18+
loaded: false,
19+
status: "loading",
20+
loadAttempts: 0,
21+
on: (_event: "status", listener: Listener) => void listeners.add(listener),
22+
off: (_event: "status", listener: Listener) => void listeners.delete(listener),
23+
loadHeadlessClerk: () => {
24+
clerk.loadAttempts += 1;
25+
clerk.emit(remaining.shift() ?? "ready");
26+
},
27+
emit: (status: string) => {
28+
clerk.status = status;
29+
clerk.loaded = status === "ready";
30+
for (const listener of listeners) listener(status);
31+
},
32+
};
33+
return clerk;
34+
}
35+
36+
function appActiveSource() {
37+
const listeners = new Set<() => void>();
38+
return {
39+
subscribe: (listener: () => void) => {
40+
listeners.add(listener);
41+
return () => void listeners.delete(listener);
42+
},
43+
becomeActive: () => {
44+
for (const listener of listeners) listener();
45+
},
46+
};
47+
}
48+
49+
beforeEach(() => {
50+
vi.useFakeTimers();
51+
});
52+
53+
afterEach(() => {
54+
vi.useRealTimers();
55+
});
56+
57+
describe("retryFailedClerkLoads", () => {
58+
it("reloads after each failure with capped exponential backoff until Clerk loads", () => {
59+
const clerk = fakeClerk(["error", "error", "error", "error", "error"]);
60+
const appActive = appActiveSource();
61+
retryFailedClerkLoads(clerk, appActive.subscribe);
62+
63+
clerk.emit("error");
64+
const delays = [2_000, 4_000, 8_000, 16_000, 30_000, 30_000];
65+
for (const [index, delay] of delays.entries()) {
66+
vi.advanceTimersByTime(delay - 1);
67+
expect(clerk.loadAttempts).toBe(index);
68+
vi.advanceTimersByTime(1);
69+
expect(clerk.loadAttempts).toBe(index + 1);
70+
}
71+
72+
expect(clerk.loaded).toBe(true);
73+
vi.advanceTimersByTime(CLERK_LOAD_RETRY_MAX_DELAY_MS * 2);
74+
expect(clerk.loadAttempts).toBe(delays.length);
75+
});
76+
77+
it("retries a load that had already failed before it subscribed", () => {
78+
const clerk = fakeClerk([]);
79+
clerk.emit("error");
80+
retryFailedClerkLoads(clerk, appActiveSource().subscribe);
81+
82+
vi.advanceTimersByTime(CLERK_LOAD_RETRY_INITIAL_DELAY_MS);
83+
expect(clerk.loadAttempts).toBe(1);
84+
expect(clerk.loaded).toBe(true);
85+
});
86+
87+
it("runs a pending retry immediately when the app returns to the foreground", () => {
88+
const clerk = fakeClerk([]);
89+
const appActive = appActiveSource();
90+
retryFailedClerkLoads(clerk, appActive.subscribe);
91+
92+
appActive.becomeActive();
93+
expect(clerk.loadAttempts).toBe(0);
94+
95+
clerk.emit("error");
96+
appActive.becomeActive();
97+
expect(clerk.loadAttempts).toBe(1);
98+
expect(clerk.loaded).toBe(true);
99+
100+
vi.advanceTimersByTime(CLERK_LOAD_RETRY_MAX_DELAY_MS);
101+
appActive.becomeActive();
102+
expect(clerk.loadAttempts).toBe(1);
103+
});
104+
105+
it("stops retrying after cleanup", () => {
106+
const clerk = fakeClerk([]);
107+
const appActive = appActiveSource();
108+
const stop = retryFailedClerkLoads(clerk, appActive.subscribe);
109+
110+
clerk.emit("error");
111+
stop();
112+
appActive.becomeActive();
113+
vi.advanceTimersByTime(CLERK_LOAD_RETRY_MAX_DELAY_MS);
114+
clerk.emit("error");
115+
vi.advanceTimersByTime(CLERK_LOAD_RETRY_MAX_DELAY_MS);
116+
expect(clerk.loadAttempts).toBe(0);
117+
});
118+
});
119+
120+
describe("limitClerkRequestDuration", () => {
121+
function clerkWithRequestHooks() {
122+
const hooks: Array<(requestInit: { method?: string; signal?: AbortSignal | null }) => void> =
123+
[];
124+
return {
125+
hooks,
126+
__internal_onBeforeRequest: (hook: (typeof hooks)[number]) => void hooks.push(hook),
127+
prepare: (requestInit: { method?: string; signal?: AbortSignal | null }) => {
128+
for (const hook of hooks) hook(requestInit);
129+
return requestInit;
130+
},
131+
};
132+
}
133+
134+
it("aborts GET requests that outlast the timeout and leaves writes unbounded", () => {
135+
const clerk = clerkWithRequestHooks();
136+
limitClerkRequestDuration(clerk);
137+
limitClerkRequestDuration(clerk);
138+
expect(clerk.hooks).toHaveLength(1);
139+
140+
const get = clerk.prepare({ method: "GET" });
141+
const post = clerk.prepare({ method: "POST" });
142+
expect(post.signal).toBeUndefined();
143+
144+
vi.advanceTimersByTime(CLERK_REQUEST_TIMEOUT_MS - 1);
145+
expect(get.signal?.aborted).toBe(false);
146+
vi.advanceTimersByTime(1);
147+
expect(get.signal?.aborted).toBe(true);
148+
});
149+
150+
it("keeps a caller-provided abort signal", () => {
151+
const clerk = clerkWithRequestHooks();
152+
limitClerkRequestDuration(clerk);
153+
const callerSignal = new AbortController().signal;
154+
155+
expect(clerk.prepare({ method: "GET", signal: callerSignal }).signal).toBe(callerSignal);
156+
});
157+
});

0 commit comments

Comments
 (0)