Open History to see the last commit
1import type { Discovery } from "@t3tools/client-runtime/relay";
2import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
3import { EnvironmentId, ORCHESTRATION_PROTOCOL_VERSION } from "@t3tools/contracts";
4import * as Option from "effect/Option";
5import { AsyncResult } from "effect/unstable/reactivity";
6import { act, useState, type ButtonHTMLAttributes, type ReactNode } from "react";
7import { create, type ReactTestRenderer } from "react-test-renderer";
8import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
9
10type DiscoveredEnvironments = Discovery.RelayEnvironmentDiscoveryState["environments"];
11
12const discovery = vi.hoisted(() => ({
13 state: null as Discovery.RelayEnvironmentDiscoveryState | null,
14 listeners: new Set<() => void>(),
15 refreshCommand: Symbol("refresh"),
16 registerCommand: Symbol("register"),
17 refresh: vi.fn<() => Promise<AtomCommandResult<void, never>>>(),
18 register: vi.fn(),
19 listEnvironments: vi.fn<() => Promise<DiscoveredEnvironments>>(),
20}));
21
22vi.mock("~/state/relay", () => ({
23 relayEnvironmentDiscovery: { refresh: discovery.refreshCommand },
24}));
25vi.mock("~/connection/catalog", () => ({
26 environmentCatalog: { register: discovery.registerCommand },
27}));
28vi.mock("~/state/use-atom-command", () => ({
29 useAtomCommand: (command: unknown) =>
30 command === discovery.refreshCommand ? discovery.refresh : discovery.register,
31}));
32vi.mock("~/state/environments", async () => {
33 const { useSyncExternalStore } = await import("react");
34 const subscribe = (listener: () => void) => {
35 discovery.listeners.add(listener);
36 return () => discovery.listeners.delete(listener);
37 };
38 const read = () => {
39 if (discovery.state === null) throw new Error("Discovery fixture is not initialized");
40 return discovery.state;
41 };
42 return { useRelayEnvironmentDiscovery: () => useSyncExternalStore(subscribe, read, read) };
43});
44vi.mock("../ConnectionStatusDot", () => ({ ConnectionStatusDot: () => null }));
45vi.mock("../ui/tooltip", () => ({
46 Tooltip: ({ children }: { children: ReactNode }) => children,
47 TooltipTrigger: ({ children }: { children: ReactNode }) => <span>{children}</span>,
48 TooltipPopup: () => null,
49}));
50vi.mock("../ui/checkbox", () => ({
51 Checkbox: (props: {
52 checked: boolean;
53 disabled: boolean;
54 onCheckedChange: (checked: boolean) => void;
55 }) => (
56 <input
57 type="checkbox"
58 checked={props.checked}
59 disabled={props.disabled}
60 onChange={(event) => props.onCheckedChange(event.target.checked)}
61 />
62 ),
63}));
64vi.mock("../ui/button", () => ({
65 Button: ({ children, ...props }: ButtonHTMLAttributes<HTMLButtonElement>) => (
66 <button {...props}>{children}</button>
67 ),
68}));
69vi.mock("../ui/toast", () => ({ toastManager: { add: vi.fn() } }));
70
71import { CloudEnvironmentConnectRows } from "./CloudEnvironmentConnectList";
72
73const newMachineId = EnvironmentId.make("new-computer");
74const linkedMachines: DiscoveredEnvironments = new Map([
75 [
76 newMachineId,
77 {
78 environment: {
79 environmentId: newMachineId,
80 label: "Work laptop",
81 endpoint: {
82 httpBaseUrl: "https://relay.example.test",
83 wsBaseUrl: "wss://relay.example.test/ws",
84 providerKind: "manual",
85 },
86 linkedAt: "2026-09-05T12:00:00.000Z",
87 },
88 availability: "online",
89 status: Option.none(),
90 error: Option.none(),
91 },
92 ],
93]);
94
95let renderer: ReactTestRenderer | null;
96let page: EventTarget & { visibilityState: DocumentVisibilityState };
97let browserWindow: EventTarget;
98
99function publish(state: Discovery.RelayEnvironmentDiscoveryState) {
100 discovery.state = state;
101 for (const listener of discovery.listeners) listener();
102}
103
104async function mount(refreshWhileEmpty = true) {
105 await act(async () => {
106 renderer = create(
107 <CloudEnvironmentConnectRows
108 primaryEnvironmentId={null}
109 savedEnvironments={[]}
110 showSavedEnvironments
111 refreshWhileEmpty={refreshWhileEmpty}
112 empty={<p>Waiting for your computer to connect.</p>}
113 />,
114 );
115 });
116}
117
118async function advance(milliseconds: number) {
119 await act(async () => {
120 await vi.advanceTimersByTimeAsync(milliseconds);
121 });
122}
123
124beforeEach(() => {
125 vi.useFakeTimers();
126 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
127 page = Object.assign(new EventTarget(), { visibilityState: "visible" as const });
128 browserWindow = new EventTarget();
129 vi.stubGlobal("document", page);
130 vi.stubGlobal("window", browserWindow);
131 renderer = null;
132 discovery.listeners.clear();
133 discovery.state = {
134 environments: new Map(),
135 refreshing: false,
136 offline: false,
137 error: Option.none(),
138 };
139 discovery.listEnvironments.mockReset().mockResolvedValue(new Map());
140 discovery.register.mockReset().mockResolvedValue(AsyncResult.success(undefined));
141 discovery.refresh.mockReset().mockImplementation(async () => {
142 publish({ environments: new Map(), refreshing: true, offline: false, error: Option.none() });
143 const environments = await discovery.listEnvironments();
144 publish({ environments, refreshing: false, offline: false, error: Option.none() });
145 return AsyncResult.success(undefined);
146 });
147});
148
149afterEach(async () => {
150 await act(async () => renderer?.unmount());
151 vi.useRealTimers();
152 vi.unstubAllGlobals();
153});
154
155describe("cloud onboarding discovery", () => {
156 it("signals that the section can expand after initial discovery settles", async () => {
157 let finishDiscovery!: (environments: DiscoveredEnvironments) => void;
158 discovery.listEnvironments.mockReturnValue(
159 new Promise((resolve) => {
160 finishDiscovery = resolve;
161 }),
162 );
163 const onDiscoveryReady = vi.fn();
164 await act(async () => {
165 renderer = create(
166 <CloudEnvironmentConnectRows
167 primaryEnvironmentId={null}
168 savedEnvironments={[]}
169 onDiscoveryReady={onDiscoveryReady}
170 />,
171 );
172 });
173 expect(onDiscoveryReady).not.toHaveBeenCalled();
174 await act(async () => {
175 finishDiscovery(linkedMachines);
176 });
177 expect(onDiscoveryReady).toHaveBeenCalledTimes(1);
178 expect(renderer!.root.findByType("button").children).toEqual(["Add"]);
179 });
180
181 it("keeps incompatible discoveries unselected until the user enables a compatible server", async () => {
182 const base = linkedMachines.get(newMachineId)!;
183 const entry = (protocolVersion: number) => ({
184 ...base,
185 status: Option.some({
186 environmentId: newMachineId,
187 endpoint: base.environment.endpoint,
188 status: "online" as const,
189 checkedAt: "2026-09-15T00:00:00Z",
190 descriptor: {
191 environmentId: newMachineId,
192 label: base.environment.label,
193 platform: { os: "linux" as const, arch: "x64" as const },
194 serverVersion: "1.0.0",
195 orchestrationProtocolVersion: protocolVersion,
196 capabilities: { repositoryIdentity: true },
197 },
198 }),
199 });
200 discovery.listEnvironments.mockResolvedValue(
201 new Map([[newMachineId, entry(ORCHESTRATION_PROTOCOL_VERSION + 1)]]),
202 );
203 const onSelectionChange = vi.fn();
204 const autoSelectedComputers = new Set<EnvironmentId>();
205 function Setup() {
206 const [selectedIds, setSelectedIds] = useState<ReadonlySet<EnvironmentId>>(
207 new Set([newMachineId]),
208 );
209 return (
210 <CloudEnvironmentConnectRows
211 primaryEnvironmentId={null}
212 savedEnvironments={[]}
213 showSavedEnvironments
214 selection={{
215 autoSelectedComputers,
216 selectedIds,
217 onChange: (id, checked) => {
218 onSelectionChange(id, checked);
219 setSelectedIds((current) => {
220 const next = new Set(current);
221 if (checked) next.add(id);
222 else next.delete(id);
223 return next;
224 });
225 },
226 }}
227 />
228 );
229 }
230 await act(async () => {
231 renderer = create(<Setup />);
232 });
233 expect(discovery.register).not.toHaveBeenCalled();
234 expect(onSelectionChange).toHaveBeenCalledWith(newMachineId, false);
235 expect(renderer!.root.findByType("input").props.checked).toBe(false);
236 expect(renderer!.root.findByType("input").props.disabled).toBe(true);
237 expect(renderer!.root.findAllByType("span").flatMap((span) => span.children)).toContain(
238 "Client not supported",
239 );
240 await act(async () => {
241 await renderer!.root.findByType("input").props.onChange({ target: { checked: true } });
242 });
243 expect(discovery.register).not.toHaveBeenCalled();
244 await act(async () =>
245 publish({
246 ...discovery.state!,
247 environments: new Map([[newMachineId, entry(ORCHESTRATION_PROTOCOL_VERSION)]]),
248 }),
249 );
250 expect(discovery.register).not.toHaveBeenCalled();
251 expect(renderer!.root.findByType("input").props.checked).toBe(false);
252 expect(renderer!.root.findByType("input").props.disabled).toBe(false);
253 await act(async () => {
254 await renderer!.root.findByType("input").props.onChange({ target: { checked: true } });
255 });
256 expect(discovery.register).toHaveBeenCalledTimes(1);
257 });
258
259 it("connects and selects discovered computers by default without overwriting deselection", async () => {
260 discovery.listEnvironments.mockResolvedValue(linkedMachines);
261 const autoSelectedComputers = new Set<EnvironmentId>();
262 function Setup() {
263 const [selectedIds, setSelectedIds] = useState<ReadonlySet<EnvironmentId>>(new Set());
264 return (
265 <CloudEnvironmentConnectRows
266 primaryEnvironmentId={null}
267 savedEnvironments={[]}
268 showSavedEnvironments
269 selection={{
270 autoSelectedComputers,
271 selectedIds,
272 onChange: (id, checked) =>
273 setSelectedIds((current) => {
274 const next = new Set(current);
275 if (checked) next.add(id);
276 else next.delete(id);
277 return next;
278 }),
279 }}
280 />
281 );
282 }
283 await act(async () => {
284 renderer = create(<Setup />);
285 });
286
287 expect(discovery.register).toHaveBeenCalledTimes(1);
288 expect(renderer!.root.findByType("input").props.checked).toBe(true);
289 await act(async () => {
290 await renderer!.root.findByType("input").props.onChange({ target: { checked: false } });
291 });
292 await act(async () => {
293 publish({ ...discovery.state!, environments: new Map(linkedMachines) });
294 });
295 expect(renderer!.root.findByType("input").props.checked).toBe(false);
296 expect(discovery.register).toHaveBeenCalledTimes(1);
297 });
298
299 it("shows a newly linked computer without remounting and stops polling once found", async () => {
300 discovery.listEnvironments
301 .mockResolvedValueOnce(new Map())
302 .mockResolvedValueOnce(linkedMachines);
303 await mount();
304 expect(renderer!.root.findByType("p").children).toEqual([
305 "Waiting for your computer to connect.",
306 ]);
307
308 await advance(5_000);
309
310 expect(renderer!.root.findAllByType("p").map((node) => node.children)).toContainEqual([
311 "Work laptop",
312 ]);
313 expect(renderer!.root.findByType("button").children).toEqual(["Add"]);
314 await advance(30_000);
315 expect(discovery.listEnvironments).toHaveBeenCalledTimes(2);
316 });
317
318 it("keeps a discovered computer visible when it is added to the browser", async () => {
319 discovery.listEnvironments.mockResolvedValue(linkedMachines);
320 await mount();
321 expect(renderer!.root.findByType("button").children).toEqual(["Add"]);
322 await act(async () => {
323 renderer!.update(
324 <CloudEnvironmentConnectRows
325 primaryEnvironmentId={null}
326 savedEnvironments={[
327 {
328 environmentId: newMachineId,
329 connection: { phase: "connected", error: null, traceId: null },
330 },
331 ]}
332 showSavedEnvironments
333 refreshWhileEmpty
334 />,
335 );
336 });
337 expect(renderer!.root.findAllByType("p").map((node) => node.children)).toContainEqual([
338 "Work laptop",
339 ]);
340 expect(renderer!.root.findByType("button").children).toEqual(["Connected"]);
341 });
342
343 it("waits while hidden and refreshes immediately when visible again", async () => {
344 page.visibilityState = "hidden";
345 await mount();
346 await advance(30_000);
347 expect(discovery.listEnvironments).not.toHaveBeenCalled();
348
349 await act(async () => {
350 page.visibilityState = "visible";
351 page.dispatchEvent(new Event("visibilitychange"));
352 });
353 expect(discovery.listEnvironments).toHaveBeenCalledTimes(1);
354
355 page.visibilityState = "hidden";
356 page.dispatchEvent(new Event("visibilitychange"));
357 browserWindow.dispatchEvent(new Event("focus"));
358 await advance(30_000);
359 expect(discovery.listEnvironments).toHaveBeenCalledTimes(1);
360 });
361
362 it("does not overlap a slow refresh or restart polling after unmount", async () => {
363 let resolveRefresh!: (environments: DiscoveredEnvironments) => void;
364 const pending = new Promise<DiscoveredEnvironments>((resolve) => {
365 resolveRefresh = resolve;
366 });
367 discovery.listEnvironments.mockResolvedValueOnce(new Map()).mockReturnValueOnce(pending);
368 await mount();
369 await advance(5_000);
370 expect(renderer!.root.findByType("p").children).toEqual([
371 "Waiting for your computer to connect.",
372 ]);
373
374 browserWindow.dispatchEvent(new Event("focus"));
375 page.dispatchEvent(new Event("visibilitychange"));
376 await advance(30_000);
377 expect(discovery.listEnvironments).toHaveBeenCalledTimes(2);
378
379 await act(async () => renderer!.unmount());
380 renderer = null;
381 await act(async () => resolveRefresh(new Map()));
382 await advance(30_000);
383 expect(discovery.listEnvironments).toHaveBeenCalledTimes(2);
384 });
385
386 it("pauses while offline and resumes when discovery is online", async () => {
387 await mount();
388 await act(async () => publish({ ...discovery.state!, offline: true }));
389 await advance(30_000);
390 expect(discovery.listEnvironments).toHaveBeenCalledTimes(1);
391
392 await act(async () => publish({ ...discovery.state!, offline: false }));
393 await advance(5_000);
394 expect(discovery.listEnvironments).toHaveBeenCalledTimes(2);
395 });
396
397 it("does not add polling to other cloud lists", async () => {
398 await mount(false);
399 await advance(30_000);
400 expect(discovery.listEnvironments).toHaveBeenCalledTimes(1);
401 });
402});