@devries-cameron20 / t3code Mirror · read-only / commits / 06e80ac27e
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 17:00 UTC

refactor(mobile): cloud account transitions run in the shared account service (#25150)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 25, 2026 at 18:24 UTC 06e80ac27e0e0d5f9668254cfb3cc8c291a5ce71
3 files changed +189 -197
apps/mobile/src/features/cloud/CloudAuthProvider.test.ts
+61 -1
@@ -2,8 +2,14 @@ import { managedRelaySessionAtom } from "@t3tools/client-runtime/relay";
2 import { afterEach, describe, expect, it, vi } from "vite-plus/test";
3
4 import { appAtomRegistry } from "../../state/atom-registry";
5 -import { activateCloudRelayAccount, deactivateCloudRelayAccount } from "./CloudAuthProvider";
5 +import {
6 + activateCloudRelayAccount,
7 + cloudAccountService,
8 + deactivateCloudRelayAccount,
9 +} from "./cloudAccountService";
10 import { setAgentAwarenessRelayTokenProvider } from "../agent-awareness/remoteRegistration";
11 +import { requestConnectOnboarding } from "./connectOnboarding";
12 +import { restoreCloudComposerDrafts } from "../../state/use-composer-drafts";
13
14 vi.mock("@clerk/expo", () => ({
15 ClerkProvider: vi.fn(),
@@ -27,6 +33,10 @@ vi.mock("../../connection/catalog", () => ({
33 }));
34
35 vi.mock("./cloud-drafts", () => ({ removeCloudEnvironments: {} }));
36 +vi.mock("./connectOnboarding", () => ({
37 + clearConnectOnboardingRequest: vi.fn(),
38 + requestConnectOnboarding: vi.fn(),
39 +}));
40 vi.mock("../../state/use-composer-drafts", () => ({
41 getComposerCloudAccountId: vi.fn(async () => null),
42 restoreCloudComposerDrafts: vi.fn(async () => undefined),
@@ -41,10 +51,28 @@ vi.mock("./publicConfig", () => ({
51 }));
52
53 vi.mock("../agent-awareness/remoteRegistration", () => ({
54 + releaseAgentAwarenessRelayTokenProvider: vi.fn(),
55 setAgentAwarenessRelayTokenProvider: vi.fn(),
56 unregisterAgentAwarenessDeviceForCurrentUser: vi.fn(),
57 }));
58
59 +type ClerkListener = (resources: { readonly user: { readonly id: string } | null }) => void;
60 +
61 +function fakeClerk() {
62 + const listeners = new Set<ClerkListener>();
63 + const clerk = {
64 + session: null,
65 + addListener: (listener: ClerkListener) => {
66 + listeners.add(listener);
67 + return () => listeners.delete(listener);
68 + },
69 + } as unknown as Parameters<typeof cloudAccountService.attach>[0];
70 + const emit = (userId: string | null) => {
71 + for (const listener of listeners) listener({ user: userId === null ? null : { id: userId } });
72 + };
73 + return { clerk, emit };
74 +}
75 +
76 afterEach(() => {
77 deactivateCloudRelayAccount();
78 vi.clearAllMocks();
@@ -64,3 +92,35 @@ describe("CloudAuthProvider relay account isolation", () => {
92 await cleanup;
93 });
94 });
95 +
96 +describe("cloudAccountService", () => {
97 + it("activates the signed-in account once its drafts are restored", async () => {
98 + const { clerk, emit } = fakeClerk();
99 + using _detach = { [Symbol.dispose]: cloudAccountService.attach(clerk) };
100 +
101 + emit("account-1");
102 + expect(appAtomRegistry.get(managedRelaySessionAtom)).toBeNull();
103 +
104 + await vi.waitFor(() =>
105 + expect(appAtomRegistry.get(managedRelaySessionAtom)?.accountId).toBe("account-1"),
106 + );
107 + expect(vi.mocked(restoreCloudComposerDrafts)).toHaveBeenCalledWith("account-1");
108 + // Clerk already had this account on its first emission, so this is not a fresh sign-in.
109 + expect(vi.mocked(requestConnectOnboarding)).not.toHaveBeenCalled();
110 + });
111 +
112 + it("retries an activation whose draft restore failed on the next emission", async () => {
113 + const { clerk, emit } = fakeClerk();
114 + using _detach = { [Symbol.dispose]: cloudAccountService.attach(clerk) };
115 + vi.mocked(restoreCloudComposerDrafts).mockRejectedValueOnce(new Error("Storage busy."));
116 +
117 + emit("account-1");
118 + await vi.waitFor(() => expect(cloudAccountService.getState()._tag).toBe("Failed"));
119 + expect(appAtomRegistry.get(managedRelaySessionAtom)).toBeNull();
120 +
121 + emit("account-1");
122 + await vi.waitFor(() =>
123 + expect(appAtomRegistry.get(managedRelaySessionAtom)?.accountId).toBe("account-1"),
124 + );
125 + });
126 +});
apps/mobile/src/features/cloud/CloudAuthProvider.tsx
+20 -196
@@ -1,208 +1,32 @@
1 -import { ClerkProvider, useAuth } from "@clerk/expo";
1 +import { ClerkProvider, getClerkInstance } from "@clerk/expo";
2 import { tokenCache } from "@clerk/expo/token-cache";
3 -import { ManagedRelay, setManagedRelaySession } from "@t3tools/client-runtime/relay";
4 -import {
5 - reportAtomCommandResult,
6 - settleAsyncResult,
7 - settlePromise,
8 - squashAtomCommandFailure,
9 -} from "@t3tools/client-runtime/state/runtime";
10 -import * as Effect from "effect/Effect";
11 -import { type ReactNode, useEffect, useRef } from "react";
12 -
13 -import { runtime } from "../../lib/runtime";
14 -import { appAtomRegistry } from "../../state/atom-registry";
15 -import { useAtomCommand } from "../../state/use-atom-command";
16 -import {
17 - getComposerCloudAccountId,
18 - restoreCloudComposerDrafts,
19 -} from "../../state/use-composer-drafts";
20 -import {
21 - releaseAgentAwarenessRelayTokenProvider,
22 - setAgentAwarenessRelayTokenProvider,
23 - unregisterAgentAwarenessDeviceForCurrentUser,
24 -} from "../agent-awareness/remoteRegistration";
25 -import { clearConnectOnboardingRequest, requestConnectOnboarding } from "./connectOnboarding";
26 -import { resolveCloudPublicConfig, resolveRelayClerkTokenOptions } from "./publicConfig";
27 -import { removeCloudEnvironments } from "./cloud-drafts";
28 -
29 -function resetManagedRelayTokenCache() {
30 - return settleAsyncResult(() =>
31 - runtime.runPromiseExit(
32 - ManagedRelay.ManagedRelayClient.pipe(Effect.flatMap((client) => client.resetTokenCache)),
33 - ),
34 - );
35 -}
36 -
37 -export function deactivateCloudRelayAccount(): void {
38 - setAgentAwarenessRelayTokenProvider(null);
39 - setManagedRelaySession(appAtomRegistry, null);
40 -}
41 -
42 -export function activateCloudRelayAccount(
43 - accountId: string,
44 - tokenProvider: () => Promise<string | null>,
45 -): void {
46 - setAgentAwarenessRelayTokenProvider(tokenProvider, accountId);
47 - setManagedRelaySession(appAtomRegistry, {
48 - accountId,
49 - readClerkToken: tokenProvider,
50 - });
51 -}
52 -
53 -function CloudAuthBridge(props: { readonly children: ReactNode }) {
54 - const { getToken, isLoaded, isSignedIn, userId } = useAuth({ treatPendingAsSignedOut: false });
55 - const removeRelayEnvironments = useAtomCommand(removeCloudEnvironments, {
56 - reportFailure: false,
57 - reportDefect: false,
58 - });
59 - const previousTokenProviderRef = useRef<{
60 - readonly userId: string;
61 - readonly provider: () => Promise<string | null>;
62 - } | null>(null);
63 - const observedAccountRef = useRef<string | null | undefined>(undefined);
64 - const accountTransitionRef = useRef<Promise<void> | null>(null);
65 -
66 - useEffect(() => {
67 - let cancelled = false;
68 - if (!isLoaded) {
69 - return;
70 - }
71 -
72 - const previousObservedAccount = observedAccountRef.current;
73 - const nextAccount = isSignedIn && userId ? userId : null;
74 - observedAccountRef.current = nextAccount;
75 -
76 - // Request after activateSession cleanup to avoid listing the previous account; sign-out drops pending requests.
77 - const isAccountTransition =
78 - previousObservedAccount !== undefined && previousObservedAccount !== nextAccount;
79 - if (isAccountTransition && nextAccount === null) {
80 - clearConnectOnboardingRequest();
81 - }
82 -
83 - const cleanUpAccount = async (
84 - previous: {
85 - readonly userId: string;
86 - readonly provider: () => Promise<string | null>;
87 - } | null,
88 - accountId: string | null,
89 - ) => {
90 - const removal = await removeRelayEnvironments(accountId);
91 - if (removal._tag !== "Success") throw squashAtomCommandFailure(removal);
92 - const cleanup = [
93 - resetManagedRelayTokenCache(),
94 - ...(previous
95 - ? [
96 - settleAsyncResult(() =>
97 - runtime.runPromiseExit(
98 - unregisterAgentAwarenessDeviceForCurrentUser(previous.provider),
99 - ),
100 - ),
101 - ]
102 - : []),
103 - ];
104 - const results = await Promise.all(cleanup);
105 - for (const result of results) {
106 - reportAtomCommandResult(result, { label: "cloud account cleanup" });
107 - }
108 - };
109 - const queueAccountCleanup = (previous: typeof previousTokenProviderRef.current) => {
110 - const previousTransition = accountTransitionRef.current ?? Promise.resolve();
111 - accountTransitionRef.current = previousTransition
112 - .catch(() => {})
113 - .then(() => cleanUpAccount(previous, previousObservedAccount ?? null));
114 - return accountTransitionRef.current;
115 - };
116 -
117 - if (!isSignedIn || !userId) {
118 - const previous = previousTokenProviderRef.current;
119 - previousTokenProviderRef.current = null;
120 - deactivateCloudRelayAccount();
121 - if (previousObservedAccount !== null) {
122 - void settlePromise(() => queueAccountCleanup(previous)).then((result) => {
123 - reportAtomCommandResult(result, { label: "cloud account cleanup" });
124 - });
125 - }
126 - return;
127 - }
128 -
129 - const previous = previousTokenProviderRef.current;
130 - const tokenProvider = () => getToken(resolveRelayClerkTokenOptions());
131 - const activateSession = () => {
132 - if (cancelled) {
133 - return;
134 - }
135 - previousTokenProviderRef.current = { userId, provider: tokenProvider };
136 - activateCloudRelayAccount(userId, tokenProvider);
137 - if (isAccountTransition) {
138 - requestConnectOnboarding(userId);
139 - }
140 - };
141 - const activateAfterTransition = (transition: Promise<void>) => {
142 - const activation = (async () => {
143 - await transition;
144 - if (cancelled) return;
145 - const storedAccount = await getComposerCloudAccountId();
146 - if (storedAccount !== null && storedAccount !== userId) {
147 - await cleanUpAccount(null, storedAccount);
148 - }
149 - if (cancelled) return;
150 - await restoreCloudComposerDrafts(userId);
151 - activateSession();
152 - })();
153 - accountTransitionRef.current = activation;
154 - void settlePromise(() => activation).then((result) => {
155 - reportAtomCommandResult(result, { label: "cloud account activation" });
156 - });
157 - };
158 - if (
159 - previousObservedAccount !== undefined &&
160 - previousObservedAccount !== null &&
161 - previousObservedAccount !== userId
162 - ) {
163 - previousTokenProviderRef.current = null;
164 - deactivateCloudRelayAccount();
165 - activateAfterTransition(queueAccountCleanup(previous));
166 - } else {
167 - activateAfterTransition((accountTransitionRef.current ?? Promise.resolve()).catch(() => {}));
168 - }
169 -
170 - return () => {
171 - cancelled = true;
172 - };
173 - }, [getToken, isLoaded, isSignedIn, removeRelayEnvironments, userId]);
174 -
175 - useEffect(
176 - () => () => {
177 - previousTokenProviderRef.current = null;
178 - // Unmounting does not imply sign-out; preserve registration and lock-screen activities.
179 - releaseAgentAwarenessRelayTokenProvider();
180 - setManagedRelaySession(appAtomRegistry, null);
181 - },
182 - [],
183 - );
184 -
185 - return props.children;
3 +import type { ReactNode } from "react";
4 +
5 +import { cloudAccountService, deactivateCloudRelayAccount } from "./cloudAccountService";
6 +import { resolveCloudPublicConfig } from "./publicConfig";
7 +
8 +const cloudConfig = resolveCloudPublicConfig();
9 +// Build-time constant: null when this build has no cloud config.
10 +const publishableKey = cloudConfig.relay.url ? cloudConfig.clerk.publishableKey : null;
11 +
12 +if (publishableKey) {
13 + // The same native singleton ClerkProvider renders with, so the service
14 + // observes it for the app's lifetime without a React subscription.
15 + cloudAccountService.attach(getClerkInstance({ publishableKey }));
16 +} else {
17 + // Without cloud config no account can ever activate, so drop anything a
18 + // previous build with cloud enabled left registered.
19 + deactivateCloudRelayAccount();
20 }
21
22 export function CloudAuthProvider(props: { readonly children: ReactNode }) {
189 - const config = resolveCloudPublicConfig();
190 - const publishableKey = config.clerk.publishableKey;
191 - const relayUrl = config.relay.url;
192 -
193 - useEffect(() => {
194 - if (!publishableKey || !relayUrl) {
195 - deactivateCloudRelayAccount();
196 - }
197 - }, [publishableKey, relayUrl]);
198 -
199 - if (!publishableKey || !relayUrl) {
23 + if (!publishableKey) {
24 return props.children;
25 }
26
27 return (
28 <ClerkProvider publishableKey={publishableKey} tokenCache={tokenCache}>
205 - <CloudAuthBridge>{props.children}</CloudAuthBridge>
29 + {props.children}
30 </ClerkProvider>
31 );
32 }
apps/mobile/src/features/cloud/cloudAccountService.ts new
+108
@@ -0,0 +1,108 @@
1 +import type { getClerkInstance } from "@clerk/expo";
2 +import {
3 + createCloudAccountService,
4 + ManagedRelay,
5 + setManagedRelaySession,
6 +} from "@t3tools/client-runtime/relay";
7 +import {
8 + reportAtomCommandResult,
9 + runAtomCommand,
10 + settleAsyncResult,
11 + squashAtomCommandFailure,
12 +} from "@t3tools/client-runtime/state/runtime";
13 +import * as Effect from "effect/Effect";
14 +
15 +import { runtime } from "../../lib/runtime";
16 +import { appAtomRegistry } from "../../state/atom-registry";
17 +import {
18 + getComposerCloudAccountId,
19 + restoreCloudComposerDrafts,
20 +} from "../../state/use-composer-drafts";
21 +import {
22 + releaseAgentAwarenessRelayTokenProvider,
23 + setAgentAwarenessRelayTokenProvider,
24 + unregisterAgentAwarenessDeviceForCurrentUser,
25 +} from "../agent-awareness/remoteRegistration";
26 +import { removeCloudEnvironments } from "./cloud-drafts";
27 +import { clearConnectOnboardingRequest, requestConnectOnboarding } from "./connectOnboarding";
28 +import { resolveRelayClerkTokenOptions } from "./publicConfig";
29 +
30 +type ClerkInstance = ReturnType<typeof getClerkInstance>;
31 +
32 +export function deactivateCloudRelayAccount(): void {
33 + setAgentAwarenessRelayTokenProvider(null);
34 + setManagedRelaySession(appAtomRegistry, null);
35 +}
36 +
37 +export function activateCloudRelayAccount(
38 + accountId: string,
39 + tokenProvider: () => Promise<string | null>,
40 +): void {
41 + setAgentAwarenessRelayTokenProvider(tokenProvider, accountId);
42 + setManagedRelaySession(appAtomRegistry, {
43 + accountId,
44 + readClerkToken: tokenProvider,
45 + });
46 +}
47 +
48 +function clerkTokenReader(clerk: ClerkInstance): () => Promise<string | null> {
49 + return async () =>
50 + clerk.session ? await clerk.session.getToken(resolveRelayClerkTokenOptions()) : null;
51 +}
52 +
53 +const cleanUpCloudAccount = async (
54 + clerk: ClerkInstance,
55 + accountId: string | null,
56 + wasActive: boolean,
57 +) => {
58 + const removal = await runAtomCommand(appAtomRegistry, removeCloudEnvironments, accountId, {
59 + reportFailure: false,
60 + reportDefect: false,
61 + });
62 + if (removal._tag !== "Success") throw squashAtomCommandFailure(removal);
63 + const results = await Promise.all([
64 + settleAsyncResult(() =>
65 + runtime.runPromiseExit(
66 + ManagedRelay.ManagedRelayClient.pipe(Effect.flatMap((client) => client.resetTokenCache)),
67 + ),
68 + ),
69 + ...(wasActive
70 + ? [
71 + settleAsyncResult(() =>
72 + runtime.runPromiseExit(
73 + unregisterAgentAwarenessDeviceForCurrentUser(clerkTokenReader(clerk)),
74 + ),
75 + ),
76 + ]
77 + : []),
78 + ]);
79 + for (const result of results) {
80 + reportAtomCommandResult(result, { label: "cloud account cleanup" });
81 + }
82 +};
83 +
84 +export const cloudAccountService = createCloudAccountService<ClerkInstance>({
85 + deactivate: deactivateCloudRelayAccount,
86 + // Detaching is not a sign-out: the user is usually still signed in, so keep
87 + // lock-screen activities and the persisted registration for the next attach.
88 + detach: () => {
89 + releaseAgentAwarenessRelayTokenProvider();
90 + setManagedRelaySession(appAtomRegistry, null);
91 + },
92 + // A not-yet-presented onboarding request belongs to the account that left.
93 + onSignOutTransition: clearConnectOnboardingRequest,
94 + cleanUp: ({ source, accountId, wasActive }) => cleanUpCloudAccount(source, accountId, wasActive),
95 + prepare: async ({ source, accountId, isCurrent }) => {
96 + const storedAccount = await getComposerCloudAccountId();
97 + if (storedAccount !== null && storedAccount !== accountId) {
98 + await cleanUpCloudAccount(source, storedAccount, false);
99 + }
100 + if (!isCurrent()) return;
101 + await restoreCloudComposerDrafts(accountId);
102 + },
103 + activate: ({ source, accountId, isAccountTransition }) => {
104 + activateCloudRelayAccount(accountId, clerkTokenReader(source));
105 + // Issued after cleanup so the sheet never lists the previous account's environments.
106 + if (isAccountTransition) requestConnectOnboarding(accountId);
107 + },
108 +});