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