1import { managedRelaySessionAtom } from "@t3tools/client-runtime/relay";
2import { afterEach, describe, expect, it, vi } from "vite-plus/test";
3
4import { appAtomRegistry } from "../../state/atom-registry";
5import { activateCloudRelayAccount, deactivateCloudRelayAccount } from "./CloudAuthProvider";
6import { setAgentAwarenessRelayTokenProvider } from "../agent-awareness/remoteRegistration";
7
8vi.mock("@clerk/expo", () => ({
9 ClerkProvider: vi.fn(),
10 useAuth: vi.fn(),
11}));
12
13vi.mock("@clerk/expo/token-cache", () => ({
14 tokenCache: {},
15}));
16
17vi.mock("../../lib/runtime", () => ({
18 runtime: {
19 runPromiseExit: vi.fn(),
20 },
21}));
22
23vi.mock("../../connection/catalog", () => ({
24 environmentCatalog: {
25 removeRelayEnvironments: {},
26 },
27}));
28
29vi.mock("./cloud-drafts", () => ({ removeCloudEnvironments: {} }));
30vi.mock("../../state/preferences", () => ({ mobilePreferencesAtom: {} }));
31vi.mock("../../state/use-composer-drafts", () => ({
32 getComposerCloudAccountId: vi.fn(async () => null),
33 restoreCloudComposerDrafts: vi.fn(async () => undefined),
34}));
35
36vi.mock("./publicConfig", () => ({
37 resolveCloudPublicConfig: vi.fn(() => ({
38 clerk: { publishableKey: null },
39 relay: { url: null },
40 })),
41 resolveRelayClerkTokenOptions: vi.fn(),
42}));
43
44vi.mock("../agent-awareness/remoteRegistration", () => ({
45 setAgentAwarenessRelayTokenProvider: vi.fn(),
46 unregisterAgentAwarenessDeviceForCurrentUser: vi.fn(),
47}));
48
49afterEach(() => {
50 deactivateCloudRelayAccount();
51 vi.clearAllMocks();
52});
53
54describe("CloudAuthProvider relay account isolation", () => {
55 it("clears relay and agent-awareness credentials before cleanup can fail", async () => {
56 const tokenProvider = async () => "account-1-token";
57 activateCloudRelayAccount("account-1", tokenProvider);
58 expect(appAtomRegistry.get(managedRelaySessionAtom)?.accountId).toBe("account-1");
59
60 deactivateCloudRelayAccount();
61 const cleanup = Promise.reject(new Error("Persistence removal failed.")).catch(() => undefined);
62
63 expect(appAtomRegistry.get(managedRelaySessionAtom)).toBeNull();
64 expect(vi.mocked(setAgentAwarenessRelayTokenProvider)).toHaveBeenLastCalledWith(null);
65 await cleanup;
66 });
67});