Open History to see the last commit
1import {
2 AuthRelayReadScope,
3 AuthRelayWriteScope,
4 EnvironmentId,
5 type EnvironmentCloudLinkStateResult,
6} from "@t3tools/contracts";
7import type { RelayManagedEndpointProviderKind } from "@t3tools/contracts/relay";
8import { AsyncResult } from "effect/reactivity";
9import { useLayoutEffect } from "react";
10import { describe, expect, it, vi } from "vite-plus/test";
11
12import { act, render } from "../../test/render";
13
14const testState = vi.hoisted(() => ({
15 scopes: new Set<string>(),
16 snapshot: null as EnvironmentCloudLinkStateResult | null,
17 renderedSnapshot: null as EnvironmentCloudLinkStateResult | null,
18 relayProviderKind: null as RelayManagedEndpointProviderKind | null,
19 getToken: vi.fn<() => Promise<string | null>>(),
20 link: vi.fn(),
21 unlink: vi.fn(),
22 preferences: vi.fn(),
23 refreshDiscovery: vi.fn(),
24 refreshLink: vi.fn(),
25 toast: vi.fn(),
26}));
27
28vi.mock(import("@effect/atom-react"), async (original) => ({
29 ...(await original()),
30 useAtomValue: (() => ({
31 environments: new Map(
32 testState.relayProviderKind === null
33 ? []
34 : [
35 [
36 "primary",
37 { environment: { endpoint: { providerKind: testState.relayProviderKind } } },
38 ],
39 ],
40 ),
41 })) as never,
42}));
43vi.mock(import("@clerk/react"), async (original) => ({
44 ...(await original()),
45 useAuth: (() => ({ getToken: testState.getToken, isSignedIn: true })) as never,
46}));
47vi.mock(import("../components/ui/toast"), async (original) => {
48 const actual = await original();
49 return { ...actual, toastManager: { ...actual.toastManager, add: testState.toast } as never };
50});
51vi.mock(import("../state/relay"), async (original) => {
52 const actual = await original();
53 return {
54 ...actual,
55 relayEnvironmentDiscovery: {
56 ...actual.relayEnvironmentDiscovery,
57 refresh: testState.refreshDiscovery,
58 } as never,
59 };
60});
61vi.mock(import("../state/session"), async (original) => ({
62 ...(await original()),
63 readEnvironmentScope: (_environmentId, scope) => testState.scopes.has(scope),
64}));
65vi.mock(import("../state/use-atom-command"), async (original) => ({
66 ...(await original()),
67 useAtomCommand: ((command: unknown) => command) as never,
68}));
69vi.mock(import("./linkEnvironmentAtoms"), async (original) => ({
70 ...(await original()),
71 linkPrimaryEnvironment: testState.link as never,
72 unlinkPrimaryEnvironment: testState.unlink as never,
73 updatePrimaryEnvironmentPreferences: testState.preferences as never,
74}));
75vi.mock(import("./primaryCloudLinkState"), async (original) => ({
76 ...(await original()),
77 readCachedPrimaryCloudLinkState: () => testState.snapshot,
78 usePrimaryCloudLinkState: (() => ({
79 target,
80 data: testState.renderedSnapshot,
81 error: null,
82 isPending: false,
83 refresh: testState.refreshLink,
84 })) as never,
85}));
86vi.mock(import("./publicConfig"), async (original) => ({
87 ...(await original()),
88 resolveRelayClerkTokenOptions: () => ({}) as never,
89}));
90
91import { useCloudLinkController, type CloudLinkDesiredState } from "./useCloudLinkController";
92
93const target = {
94 environmentId: EnvironmentId.make("primary"),
95 label: "Primary",
96 httpBaseUrl: "http://localhost:3773",
97 wsBaseUrl: "ws://localhost:3773/ws",
98};
99const linkedState: EnvironmentCloudLinkStateResult = {
100 linked: true,
101 cloudUserId: "account-1",
102 relayUrl: "https://relay.example.com",
103 relayIssuer: "https://relay.example.com",
104 managedTunnelActive: true,
105 publishAgentActivity: false,
106};
107
108type Controller = ReturnType<typeof useCloudLinkController>;
109
110function ControllerProbe({ onRender }: { onRender: (controller: Controller) => void }) {
111 const value = useCloudLinkController();
112 useLayoutEffect(() => {
113 onRender(value);
114 });
115 return null;
116}
117
118async function mountController() {
119 let controller: Controller | null = null;
120 const screen = await render(
121 <ControllerProbe
122 onRender={(value) => {
123 controller = value;
124 }}
125 />,
126 );
127 return Object.assign(screen, {
128 get controller() {
129 return controller;
130 },
131 async reconcile(desired: CloudLinkDesiredState) {
132 let succeeded = false;
133 await act(async () => {
134 if (controller === null) throw new Error("Controller is not mounted.");
135 succeeded = await controller.reconcileCloudState(desired);
136 });
137 return succeeded;
138 },
139 });
140}
141
142function expectNoMutations() {
143 expect(testState.link).not.toHaveBeenCalled();
144 expect(testState.unlink).not.toHaveBeenCalled();
145 expect(testState.preferences).not.toHaveBeenCalled();
146}
147
148function setup() {
149 testState.scopes = new Set([AuthRelayReadScope, AuthRelayWriteScope]);
150 testState.snapshot = linkedState;
151 testState.renderedSnapshot = linkedState;
152 testState.relayProviderKind = null;
153 testState.getToken.mockReset().mockResolvedValue("clerk-token");
154 for (const command of [
155 testState.link,
156 testState.unlink,
157 testState.preferences,
158 testState.refreshDiscovery,
159 ]) {
160 command.mockReset().mockResolvedValue(AsyncResult.success({}));
161 }
162 testState.refreshLink.mockReset();
163 testState.toast.mockReset();
164 return vi.spyOn(console, "error").mockImplementation(() => undefined);
165}
166
167describe("useCloudLinkController", () => {
168 it.each([AuthRelayReadScope, AuthRelayWriteScope])(
169 "does not mutate without %s, even with a cached link snapshot",
170 async (scope) => {
171 using _setup = setup();
172 await using screen = await mountController();
173 testState.scopes.delete(scope);
174
175 expect(await screen.reconcile({ managedTunnel: true, publish: true })).toBe(false);
176 expect(testState.getToken).not.toHaveBeenCalled();
177 expectNoMutations();
178 },
179 );
180
181 it("does not interpret unavailable link state as an unlinked environment", async () => {
182 using _setup = setup();
183 testState.snapshot = null;
184 await using screen = await mountController();
185
186 expect(await screen.reconcile({ managedTunnel: false, publish: true })).toBe(false);
187 expect(testState.getToken).not.toHaveBeenCalled();
188 expectNoMutations();
189 });
190
191 it.each([AuthRelayReadScope, AuthRelayWriteScope])(
192 "rechecks %s after requesting the cloud token",
193 async (scope) => {
194 using _setup = setup();
195 await using screen = await mountController();
196 testState.getToken.mockImplementationOnce(async () => {
197 testState.scopes.delete(scope);
198 return "clerk-token";
199 });
200
201 expect(await screen.reconcile({ managedTunnel: false, publish: false })).toBe(false);
202 expectNoMutations();
203 },
204 );
205
206 it("stops if the link-state read fails while requesting the cloud token", async () => {
207 using _setup = setup();
208 await using screen = await mountController();
209 testState.getToken.mockImplementationOnce(async () => {
210 testState.snapshot = null;
211 return "clerk-token";
212 });
213
214 expect(await screen.reconcile({ managedTunnel: true, publish: true })).toBe(false);
215 expectNoMutations();
216 });
217
218 it("still lets an authorized user unlink when the cloud token is unavailable", async () => {
219 using _setup = setup();
220 await using screen = await mountController();
221 testState.getToken.mockRejectedValueOnce(new Error("Cloud sign-in unavailable"));
222
223 expect(await screen.reconcile({ managedTunnel: false, publish: false })).toBe(true);
224 expect(testState.unlink).toHaveBeenCalledExactlyOnceWith({ target, clerkToken: null });
225 expect(testState.link).not.toHaveBeenCalled();
226 expect(testState.preferences).not.toHaveBeenCalled();
227 });
228});