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