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}));
86// The Clerk JWT template is build-time config the test environment does not set.
87vi.mock(import("./publicConfig"), async (original) => ({
88 ...(await original()),
89 resolveRelayClerkTokenOptions: () => ({}) as never,
90}));
91
92import { useCloudLinkController, type CloudLinkDesiredState } from "./useCloudLinkController";
93
94const target = {
95 environmentId: EnvironmentId.make("primary"),
96 label: "Primary",
97 httpBaseUrl: "http://localhost:3773",
98 wsBaseUrl: "ws://localhost:3773/ws",
99};
100const linkedState: EnvironmentCloudLinkStateResult = {
101 linked: true,
102 cloudUserId: "account-1",
103 relayUrl: "https://relay.example.com",
104 relayIssuer: "https://relay.example.com",
105 managedTunnelActive: true,
106 publishAgentActivity: false,
107};
108
109type Controller = ReturnType<typeof useCloudLinkController>;
110
111function ControllerProbe({ onRender }: { onRender: (controller: Controller) => void }) {
112 const value = useCloudLinkController();
113 useLayoutEffect(() => {
114 onRender(value);
115 });
116 return null;
117}
118
119async function mountController() {
120 let controller: Controller | null = null;
121 const screen = await render(
122 <ControllerProbe
123 onRender={(value) => {
124 controller = value;
125 }}
126 />,
127 );
128 return Object.assign(screen, {
129 get controller() {
130 return controller;
131 },
132 async reconcile(desired: CloudLinkDesiredState) {
133 let succeeded = false;
134 await act(async () => {
135 if (controller === null) throw new Error("Controller is not mounted.");
136 succeeded = await controller.reconcileCloudState(desired);
137 });
138 return succeeded;
139 },
140 });
141}
142
143function expectNoMutations() {
144 expect(testState.link).not.toHaveBeenCalled();
145 expect(testState.unlink).not.toHaveBeenCalled();
146 expect(testState.preferences).not.toHaveBeenCalled();
147}
148
149function setup() {
150 testState.scopes = new Set([AuthRelayReadScope, AuthRelayWriteScope]);
151 testState.snapshot = linkedState;
152 testState.renderedSnapshot = linkedState;
153 testState.relayProviderKind = null;
154 testState.getToken.mockReset().mockResolvedValue("clerk-token");
155 for (const command of [
156 testState.link,
157 testState.unlink,
158 testState.preferences,
159 testState.refreshDiscovery,
160 ]) {
161 command.mockReset().mockResolvedValue(AsyncResult.success({}));
162 }
163 testState.refreshLink.mockReset();
164 testState.toast.mockReset();
165 return vi.spyOn(console, "error").mockImplementation(() => undefined);
166}
167
168describe("useCloudLinkController", () => {
169 it.each([AuthRelayReadScope, AuthRelayWriteScope])(
170 "does not mutate without %s, even with a cached link snapshot",
171 async (scope) => {
172 using _setup = setup();
173 await using screen = await mountController();
174 testState.scopes.delete(scope);
175
176 expect(await screen.reconcile({ managedTunnel: true, publish: true })).toBe(false);
177 expect(testState.getToken).not.toHaveBeenCalled();
178 expectNoMutations();
179 },
180 );
181
182 it("does not interpret unavailable link state as an unlinked environment", async () => {
183 using _setup = setup();
184 testState.snapshot = null;
185 await using screen = await mountController();
186
187 expect(await screen.reconcile({ managedTunnel: false, publish: true })).toBe(false);
188 expect(testState.getToken).not.toHaveBeenCalled();
189 expectNoMutations();
190 });
191
192 it.each([AuthRelayReadScope, AuthRelayWriteScope])(
193 "rechecks %s after requesting the cloud token",
194 async (scope) => {
195 using _setup = setup();
196 await using screen = await mountController();
197 testState.getToken.mockImplementationOnce(async () => {
198 testState.scopes.delete(scope);
199 return "clerk-token";
200 });
201
202 expect(await screen.reconcile({ managedTunnel: false, publish: false })).toBe(false);
203 expectNoMutations();
204 },
205 );
206
207 it("stops if the link-state read fails while requesting the cloud token", async () => {
208 using _setup = setup();
209 await using screen = await mountController();
210 testState.getToken.mockImplementationOnce(async () => {
211 testState.snapshot = null;
212 return "clerk-token";
213 });
214
215 expect(await screen.reconcile({ managedTunnel: true, publish: true })).toBe(false);
216 expectNoMutations();
217 });
218
219 it("still lets an authorized user unlink when the cloud token is unavailable", async () => {
220 using _setup = setup();
221 await using screen = await mountController();
222 testState.getToken.mockRejectedValueOnce(new Error("Cloud sign-in unavailable"));
223
224 expect(await screen.reconcile({ managedTunnel: false, publish: false })).toBe(true);
225 expect(testState.unlink).toHaveBeenCalledExactlyOnceWith({ target, clerkToken: null });
226 expect(testState.link).not.toHaveBeenCalled();
227 expect(testState.preferences).not.toHaveBeenCalled();
228 });
229});