GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — refactor(mobile): cloud account transitions run in the shared account service by juliusmarminge · Pull Request #25150 · pingdotgg/t3code

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

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.

Sign up for GitHub

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

Merged
juliusmarminge merged 1 commit into main from effect/split-client-cloud-account-service
Oct 26, 2026

Uh oh!

There was an error while loading. Please reload this page.

Merged

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

Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
1 commit
Select commit
7888339
refactor(mobile): cloud account transitions run in the shared account…
juliusmarminge Oct 25, 2026
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view

There are no files selected for viewing

62 changes: 61 additions & 1 deletion 62 apps/mobile/src/features/cloud/CloudAuthProvider.test.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand All @@ -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),
Expand All @@ -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<ClerkListener>();
const clerk = {
session: null,
addListener: (listener: ClerkListener) => {
listeners.add(listener);
return () => listeners.delete(listener);
},
} as unknown as Parameters<typeof cloudAccountService.attach>[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();
Expand All @@ -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"),
);
});
});
216 changes: 20 additions & 196 deletions 216 apps/mobile/src/features/cloud/CloudAuthProvider.tsx
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -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<string | null>,
): 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<string | null>;
} | null>(null);
const observedAccountRef = useRef<string | null | undefined>(undefined);
const accountTransitionRef = useRef<Promise<void> | 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<string | null>;
} | 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<void>) => {
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 (
<ClerkProvider publishableKey={publishableKey} tokenCache={tokenCache}>
<CloudAuthBridge>{props.children}</CloudAuthBridge>
{props.children}
</ClerkProvider>
);
}
Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

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.
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.