From 7888339bc80b49e113685e8b4b5dbd4664c11da7 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Sun, 25 Oct 2026 15:35:36 -0700 Subject: [PATCH] refactor(mobile): cloud account transitions run in the shared account service Problem: CloudAuthBridge handled Clerk sign-in, sign-out and account switches in a useEffect keyed on useAuth state, with refs carrying the observed account, the last token provider and a promise chain across renders. A failed activation (for example a draft restore that threw) stayed failed until the account id changed. Fix: mobile now uses createCloudAccountService (added in #24974), wired in cloudAccountService.ts. CloudAuthProvider attaches it once at module load to the native Clerk singleton (getClerkInstance with the same publishable key ClerkProvider renders with), so no React subscription is involved and the provider no longer re-renders on auth changes. Cleanup before activation, draft restore, onboarding requests and sign-out clearing keep their order. Effects: CloudAuthProvider.tsx 3 -> 0 (the transition effect, the unmount release effect, and the no-config deactivate effect, now a module-scope branch on the build-time config). Co-Authored-By: Claude Opus 5.5 --- .../features/cloud/CloudAuthProvider.test.ts | 62 ++++- .../src/features/cloud/CloudAuthProvider.tsx | 216 ++---------------- .../src/features/cloud/cloudAccountService.ts | 108 +++++++++ 3 files changed, 189 insertions(+), 197 deletions(-) create mode 100644 apps/mobile/src/features/cloud/cloudAccountService.ts diff --git a/apps/mobile/src/features/cloud/CloudAuthProvider.test.ts b/apps/mobile/src/features/cloud/CloudAuthProvider.test.ts index 5fe74f6731418..de4726f06d276 100644 --- a/apps/mobile/src/features/cloud/CloudAuthProvider.test.ts +++ b/apps/mobile/src/features/cloud/CloudAuthProvider.test.ts @@ -2,8 +2,14 @@ import { managedRelaySessionAtom } from "@t3tools/client-runtime/relay"; import { afterEach, describe, expect, it, vi } from "vite-plus/test"; import { appAtomRegistry } from "../../state/atom-registry"; -import { activateCloudRelayAccount, deactivateCloudRelayAccount } from "./CloudAuthProvider"; +import { + activateCloudRelayAccount, + cloudAccountService, + deactivateCloudRelayAccount, +} from "./cloudAccountService"; import { setAgentAwarenessRelayTokenProvider } from "../agent-awareness/remoteRegistration"; +import { requestConnectOnboarding } from "./connectOnboarding"; +import { restoreCloudComposerDrafts } from "../../state/use-composer-drafts"; vi.mock("@clerk/expo", () => ({ ClerkProvider: vi.fn(), @@ -27,6 +33,10 @@ vi.mock("../../connection/catalog", () => ({ })); vi.mock("./cloud-drafts", () => ({ removeCloudEnvironments: {} })); +vi.mock("./connectOnboarding", () => ({ + clearConnectOnboardingRequest: vi.fn(), + requestConnectOnboarding: vi.fn(), +})); vi.mock("../../state/use-composer-drafts", () => ({ getComposerCloudAccountId: vi.fn(async () => null), restoreCloudComposerDrafts: vi.fn(async () => undefined), @@ -41,10 +51,28 @@ vi.mock("./publicConfig", () => ({ })); vi.mock("../agent-awareness/remoteRegistration", () => ({ + releaseAgentAwarenessRelayTokenProvider: vi.fn(), setAgentAwarenessRelayTokenProvider: vi.fn(), unregisterAgentAwarenessDeviceForCurrentUser: vi.fn(), })); +type ClerkListener = (resources: { readonly user: { readonly id: string } | null }) => void; + +function fakeClerk() { + const listeners = new Set(); + const clerk = { + session: null, + addListener: (listener: ClerkListener) => { + listeners.add(listener); + return () => listeners.delete(listener); + }, + } as unknown as Parameters[0]; + const emit = (userId: string | null) => { + for (const listener of listeners) listener({ user: userId === null ? null : { id: userId } }); + }; + return { clerk, emit }; +} + afterEach(() => { deactivateCloudRelayAccount(); vi.clearAllMocks(); @@ -64,3 +92,35 @@ describe("CloudAuthProvider relay account isolation", () => { await cleanup; }); }); + +describe("cloudAccountService", () => { + it("activates the signed-in account once its drafts are restored", async () => { + const { clerk, emit } = fakeClerk(); + using _detach = { [Symbol.dispose]: cloudAccountService.attach(clerk) }; + + emit("account-1"); + expect(appAtomRegistry.get(managedRelaySessionAtom)).toBeNull(); + + await vi.waitFor(() => + expect(appAtomRegistry.get(managedRelaySessionAtom)?.accountId).toBe("account-1"), + ); + expect(vi.mocked(restoreCloudComposerDrafts)).toHaveBeenCalledWith("account-1"); + // Clerk already had this account on its first emission, so this is not a fresh sign-in. + expect(vi.mocked(requestConnectOnboarding)).not.toHaveBeenCalled(); + }); + + it("retries an activation whose draft restore failed on the next emission", async () => { + const { clerk, emit } = fakeClerk(); + using _detach = { [Symbol.dispose]: cloudAccountService.attach(clerk) }; + vi.mocked(restoreCloudComposerDrafts).mockRejectedValueOnce(new Error("Storage busy.")); + + emit("account-1"); + await vi.waitFor(() => expect(cloudAccountService.getState()._tag).toBe("Failed")); + expect(appAtomRegistry.get(managedRelaySessionAtom)).toBeNull(); + + emit("account-1"); + await vi.waitFor(() => + expect(appAtomRegistry.get(managedRelaySessionAtom)?.accountId).toBe("account-1"), + ); + }); +}); diff --git a/apps/mobile/src/features/cloud/CloudAuthProvider.tsx b/apps/mobile/src/features/cloud/CloudAuthProvider.tsx index 055dee23f2ccf..df20ef805cd1d 100644 --- a/apps/mobile/src/features/cloud/CloudAuthProvider.tsx +++ b/apps/mobile/src/features/cloud/CloudAuthProvider.tsx @@ -1,208 +1,32 @@ -import { ClerkProvider, useAuth } from "@clerk/expo"; +import { ClerkProvider, getClerkInstance } from "@clerk/expo"; import { tokenCache } from "@clerk/expo/token-cache"; -import { ManagedRelay, setManagedRelaySession } from "@t3tools/client-runtime/relay"; -import { - reportAtomCommandResult, - settleAsyncResult, - settlePromise, - squashAtomCommandFailure, -} from "@t3tools/client-runtime/state/runtime"; -import * as Effect from "effect/Effect"; -import { type ReactNode, useEffect, useRef } from "react"; - -import { runtime } from "../../lib/runtime"; -import { appAtomRegistry } from "../../state/atom-registry"; -import { useAtomCommand } from "../../state/use-atom-command"; -import { - getComposerCloudAccountId, - restoreCloudComposerDrafts, -} from "../../state/use-composer-drafts"; -import { - releaseAgentAwarenessRelayTokenProvider, - setAgentAwarenessRelayTokenProvider, - unregisterAgentAwarenessDeviceForCurrentUser, -} from "../agent-awareness/remoteRegistration"; -import { clearConnectOnboardingRequest, requestConnectOnboarding } from "./connectOnboarding"; -import { resolveCloudPublicConfig, resolveRelayClerkTokenOptions } from "./publicConfig"; -import { removeCloudEnvironments } from "./cloud-drafts"; - -function resetManagedRelayTokenCache() { - return settleAsyncResult(() => - runtime.runPromiseExit( - ManagedRelay.ManagedRelayClient.pipe(Effect.flatMap((client) => client.resetTokenCache)), - ), - ); -} - -export function deactivateCloudRelayAccount(): void { - setAgentAwarenessRelayTokenProvider(null); - setManagedRelaySession(appAtomRegistry, null); -} - -export function activateCloudRelayAccount( - accountId: string, - tokenProvider: () => Promise, -): void { - setAgentAwarenessRelayTokenProvider(tokenProvider, accountId); - setManagedRelaySession(appAtomRegistry, { - accountId, - readClerkToken: tokenProvider, - }); -} - -function CloudAuthBridge(props: { readonly children: ReactNode }) { - const { getToken, isLoaded, isSignedIn, userId } = useAuth({ treatPendingAsSignedOut: false }); - const removeRelayEnvironments = useAtomCommand(removeCloudEnvironments, { - reportFailure: false, - reportDefect: false, - }); - const previousTokenProviderRef = useRef<{ - readonly userId: string; - readonly provider: () => Promise; - } | null>(null); - const observedAccountRef = useRef(undefined); - const accountTransitionRef = useRef | null>(null); - - useEffect(() => { - let cancelled = false; - if (!isLoaded) { - return; - } - - const previousObservedAccount = observedAccountRef.current; - const nextAccount = isSignedIn && userId ? userId : null; - observedAccountRef.current = nextAccount; - - // Request after activateSession cleanup to avoid listing the previous account; sign-out drops pending requests. - const isAccountTransition = - previousObservedAccount !== undefined && previousObservedAccount !== nextAccount; - if (isAccountTransition && nextAccount === null) { - clearConnectOnboardingRequest(); - } - - const cleanUpAccount = async ( - previous: { - readonly userId: string; - readonly provider: () => Promise; - } | null, - accountId: string | null, - ) => { - const removal = await removeRelayEnvironments(accountId); - if (removal._tag !== "Success") throw squashAtomCommandFailure(removal); - const cleanup = [ - resetManagedRelayTokenCache(), - ...(previous - ? [ - settleAsyncResult(() => - runtime.runPromiseExit( - unregisterAgentAwarenessDeviceForCurrentUser(previous.provider), - ), - ), - ] - : []), - ]; - const results = await Promise.all(cleanup); - for (const result of results) { - reportAtomCommandResult(result, { label: "cloud account cleanup" }); - } - }; - const queueAccountCleanup = (previous: typeof previousTokenProviderRef.current) => { - const previousTransition = accountTransitionRef.current ?? Promise.resolve(); - accountTransitionRef.current = previousTransition - .catch(() => {}) - .then(() => cleanUpAccount(previous, previousObservedAccount ?? null)); - return accountTransitionRef.current; - }; - - if (!isSignedIn || !userId) { - const previous = previousTokenProviderRef.current; - previousTokenProviderRef.current = null; - deactivateCloudRelayAccount(); - if (previousObservedAccount !== null) { - void settlePromise(() => queueAccountCleanup(previous)).then((result) => { - reportAtomCommandResult(result, { label: "cloud account cleanup" }); - }); - } - return; - } - - const previous = previousTokenProviderRef.current; - const tokenProvider = () => getToken(resolveRelayClerkTokenOptions()); - const activateSession = () => { - if (cancelled) { - return; - } - previousTokenProviderRef.current = { userId, provider: tokenProvider }; - activateCloudRelayAccount(userId, tokenProvider); - if (isAccountTransition) { - requestConnectOnboarding(userId); - } - }; - const activateAfterTransition = (transition: Promise) => { - const activation = (async () => { - await transition; - if (cancelled) return; - const storedAccount = await getComposerCloudAccountId(); - if (storedAccount !== null && storedAccount !== userId) { - await cleanUpAccount(null, storedAccount); - } - if (cancelled) return; - await restoreCloudComposerDrafts(userId); - activateSession(); - })(); - accountTransitionRef.current = activation; - void settlePromise(() => activation).then((result) => { - reportAtomCommandResult(result, { label: "cloud account activation" }); - }); - }; - if ( - previousObservedAccount !== undefined && - previousObservedAccount !== null && - previousObservedAccount !== userId - ) { - previousTokenProviderRef.current = null; - deactivateCloudRelayAccount(); - activateAfterTransition(queueAccountCleanup(previous)); - } else { - activateAfterTransition((accountTransitionRef.current ?? Promise.resolve()).catch(() => {})); - } - - return () => { - cancelled = true; - }; - }, [getToken, isLoaded, isSignedIn, removeRelayEnvironments, userId]); - - useEffect( - () => () => { - previousTokenProviderRef.current = null; - // Unmounting does not imply sign-out; preserve registration and lock-screen activities. - releaseAgentAwarenessRelayTokenProvider(); - setManagedRelaySession(appAtomRegistry, null); - }, - [], - ); - - return props.children; +import type { ReactNode } from "react"; + +import { cloudAccountService, deactivateCloudRelayAccount } from "./cloudAccountService"; +import { resolveCloudPublicConfig } from "./publicConfig"; + +const cloudConfig = resolveCloudPublicConfig(); +// Build-time constant: null when this build has no cloud config. +const publishableKey = cloudConfig.relay.url ? cloudConfig.clerk.publishableKey : null; + +if (publishableKey) { + // The same native singleton ClerkProvider renders with, so the service + // observes it for the app's lifetime without a React subscription. + cloudAccountService.attach(getClerkInstance({ publishableKey })); +} else { + // Without cloud config no account can ever activate, so drop anything a + // previous build with cloud enabled left registered. + deactivateCloudRelayAccount(); } export function CloudAuthProvider(props: { readonly children: ReactNode }) { - const config = resolveCloudPublicConfig(); - const publishableKey = config.clerk.publishableKey; - const relayUrl = config.relay.url; - - useEffect(() => { - if (!publishableKey || !relayUrl) { - deactivateCloudRelayAccount(); - } - }, [publishableKey, relayUrl]); - - if (!publishableKey || !relayUrl) { + if (!publishableKey) { return props.children; } return ( - {props.children} + {props.children} ); } diff --git a/apps/mobile/src/features/cloud/cloudAccountService.ts b/apps/mobile/src/features/cloud/cloudAccountService.ts new file mode 100644 index 0000000000000..aa7bff16b1548 --- /dev/null +++ b/apps/mobile/src/features/cloud/cloudAccountService.ts @@ -0,0 +1,108 @@ +import type { getClerkInstance } from "@clerk/expo"; +import { + createCloudAccountService, + ManagedRelay, + setManagedRelaySession, +} from "@t3tools/client-runtime/relay"; +import { + reportAtomCommandResult, + runAtomCommand, + settleAsyncResult, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import * as Effect from "effect/Effect"; + +import { runtime } from "../../lib/runtime"; +import { appAtomRegistry } from "../../state/atom-registry"; +import { + getComposerCloudAccountId, + restoreCloudComposerDrafts, +} from "../../state/use-composer-drafts"; +import { + releaseAgentAwarenessRelayTokenProvider, + setAgentAwarenessRelayTokenProvider, + unregisterAgentAwarenessDeviceForCurrentUser, +} from "../agent-awareness/remoteRegistration"; +import { removeCloudEnvironments } from "./cloud-drafts"; +import { clearConnectOnboardingRequest, requestConnectOnboarding } from "./connectOnboarding"; +import { resolveRelayClerkTokenOptions } from "./publicConfig"; + +type ClerkInstance = ReturnType; + +export function deactivateCloudRelayAccount(): void { + setAgentAwarenessRelayTokenProvider(null); + setManagedRelaySession(appAtomRegistry, null); +} + +export function activateCloudRelayAccount( + accountId: string, + tokenProvider: () => Promise, +): void { + setAgentAwarenessRelayTokenProvider(tokenProvider, accountId); + setManagedRelaySession(appAtomRegistry, { + accountId, + readClerkToken: tokenProvider, + }); +} + +function clerkTokenReader(clerk: ClerkInstance): () => Promise { + return async () => + clerk.session ? await clerk.session.getToken(resolveRelayClerkTokenOptions()) : null; +} + +const cleanUpCloudAccount = async ( + clerk: ClerkInstance, + accountId: string | null, + wasActive: boolean, +) => { + const removal = await runAtomCommand(appAtomRegistry, removeCloudEnvironments, accountId, { + reportFailure: false, + reportDefect: false, + }); + if (removal._tag !== "Success") throw squashAtomCommandFailure(removal); + const results = await Promise.all([ + settleAsyncResult(() => + runtime.runPromiseExit( + ManagedRelay.ManagedRelayClient.pipe(Effect.flatMap((client) => client.resetTokenCache)), + ), + ), + ...(wasActive + ? [ + settleAsyncResult(() => + runtime.runPromiseExit( + unregisterAgentAwarenessDeviceForCurrentUser(clerkTokenReader(clerk)), + ), + ), + ] + : []), + ]); + for (const result of results) { + reportAtomCommandResult(result, { label: "cloud account cleanup" }); + } +}; + +export const cloudAccountService = createCloudAccountService({ + deactivate: deactivateCloudRelayAccount, + // Detaching is not a sign-out: the user is usually still signed in, so keep + // lock-screen activities and the persisted registration for the next attach. + detach: () => { + releaseAgentAwarenessRelayTokenProvider(); + setManagedRelaySession(appAtomRegistry, null); + }, + // A not-yet-presented onboarding request belongs to the account that left. + onSignOutTransition: clearConnectOnboardingRequest, + cleanUp: ({ source, accountId, wasActive }) => cleanUpCloudAccount(source, accountId, wasActive), + prepare: async ({ source, accountId, isCurrent }) => { + const storedAccount = await getComposerCloudAccountId(); + if (storedAccount !== null && storedAccount !== accountId) { + await cleanUpCloudAccount(source, storedAccount, false); + } + if (!isCurrent()) return; + await restoreCloudComposerDrafts(accountId); + }, + activate: ({ source, accountId, isAccountTransition }) => { + activateCloudRelayAccount(accountId, clerkTokenReader(source)); + // Issued after cleanup so the sheet never lists the previous account's environments. + if (isAccountTransition) requestConnectOnboarding(accountId); + }, +});