Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ServerUpdateAction.test.tsx

457 lines14.2 KB

1import { act, type ReactElement } from "react";
2import { create, type ReactTestRenderer } from "react-test-renderer";
3import { renderToStaticMarkup } from "react-dom/server";
4import type { EnvironmentId, ServerInstallation } from "@t3tools/contracts";
5import * as Cause from "effect/Cause";
6import { AsyncResult } from "effect/reactivity";
7import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
8​
9const testState = vi.hoisted(() => ({
10 updateServer: vi.fn(),
11 toast: vi.fn(),
12 clipboard: vi.fn(),
13 continueThreadsAfterServerUpdate: false,
14}));
15​
16vi.mock("~/hooks/useCopyToClipboard", () => ({
17 useCopyToClipboard: (options: { onCopy: (context: { command: string }) => void }) => ({
18 copyToClipboard: (command: string, context: { command: string }) => {
19 testState.clipboard(command);
20 options.onCopy(context);
21 },
22 }),
23}));
24vi.mock("~/hooks/useSettings", () => ({
25 useEnvironmentSettings: (
26 _environmentId: EnvironmentId,
27 selector: (settings: { continueThreadsAfterServerUpdate: boolean }) => unknown,
28 ) => selector({ continueThreadsAfterServerUpdate: testState.continueThreadsAfterServerUpdate }),
29}));
30vi.mock("~/state/server", () => ({
31 serverEnvironment: { updateServer: Symbol("updateServer") },
32}));
33vi.mock("~/state/use-atom-command", () => ({
34 useAtomCommand: () => testState.updateServer,
35}));
36vi.mock("./ui/toast", () => ({
37 toastManager: { add: testState.toast },
38}));
39​
40import {
41 readConfirmDialogState,
42 registerConfirmDialogHost,
43 resetConfirmDialogForTests,
44 respondToConfirmDialog,
45} from "~/confirmDialog";
46import {
47 ServerUpdateAction,
48 ServerUpdateProgress,
49 ServerUpdatesAction,
50 type ServerUpdateTarget,
51} from "./ServerUpdateAction";
52​
53type ActionElement = ReactElement<{
54 readonly onClick?: () => void;
55}>;
56​
57function renderAction(): ActionElement {
58 return ServerUpdateAction({
59 environmentId: "env-test" as EnvironmentId,
60 serverLabel: "Test server",
61 selfUpdate: "boot-service",
62 targetVersion: "0.0.31",
63 }) as ActionElement;
65​
66async function flushPromises(): Promise<void> {
67 await Promise.resolve();
68 await Promise.resolve();
70​
71describe("ServerUpdateAction", () => {
72 beforeEach(() => {
73 testState.updateServer.mockReset();
74 testState.toast.mockReset();
75 testState.clipboard.mockReset();
76 testState.continueThreadsAfterServerUpdate = false;
77 });
78​
79 it.each([
80 [
81 { kind: "npm-global", prefix: "/opt/node" },
82 "npm install --global --prefix '/opt/node' t3@0.0.45",
83 "Update command copied",
84 "then restart t3",
85 ],
86 [
87 { kind: "npx" },
88 "npx t3@0.0.45",
89 "Relaunch command copied",
90 "This does not update an installed t3 command.",
91 ],
92 [
93 undefined,
94 "npx t3@0.0.45",
95 "Relaunch command copied",
96 "This does not update an installed t3 command.",
97 ],
98 ] satisfies ReadonlyArray<readonly [ServerInstallation | undefined, string, string, string]>)(
99 "copies an honest manual command for %j without invoking remote update",
100 (installation, command, title, guidance) => {
101 const action = ServerUpdateAction({
102 environmentId: "env-test" as EnvironmentId,
103 serverLabel: "Test server",
104 selfUpdate: null,
105 installation,
106 targetVersion: "0.0.45",
107 }) as ActionElement;
108 action.props.onClick?.();
109 expect(testState.clipboard).toHaveBeenCalledWith(command);
110 expect(testState.toast).toHaveBeenCalledWith(
111 expect.objectContaining({
112 title,
113 description: expect.stringContaining(guidance),
114 }),
115 );
116 expect(testState.updateServer).not.toHaveBeenCalled();
117 },
118 );
119​
120 it("reports success only after the shared update flow reconnects", async () => {
121 testState.updateServer.mockResolvedValue(
122 AsyncResult.success({ targetVersion: "0.0.31", method: "boot-service" as const }),
123 );
124​
125 renderAction().props.onClick?.();
126 await flushPromises();
127​
128 expect(testState.updateServer).toHaveBeenCalledWith({
129 environmentId: "env-test",
130 input: { targetVersion: "0.0.31" },
131 });
132 expect(testState.toast).toHaveBeenCalledWith({
133 type: "success",
134 title: "Test server updated",
135 description: "Reconnected on t3@0.0.31.",
136 });
137 });
138​
139 it("reports one result when the update action is double-clicked", async () => {
140 let finishUpdate: (() => void) | undefined;
141 testState.updateServer.mockImplementation(
142 () =>
143 new Promise((resolve) => {
144 finishUpdate = () =>
145 resolve(
146 AsyncResult.success({ targetVersion: "0.0.31", method: "boot-service" as const }),
147 );
148 }),
149 );
150​
151 const action = renderAction();
152 action.props.onClick?.();
153 action.props.onClick?.();
154​
155 expect(testState.updateServer).toHaveBeenCalledTimes(1);
156 finishUpdate?.();
157 await flushPromises();
158 expect(testState.toast).toHaveBeenCalledTimes(1);
159 });
160​
161 it("quietly releases the action when the operation is interrupted", async () => {
162 testState.updateServer.mockResolvedValue(AsyncResult.failure(Cause.interrupt()));
163​
164 renderAction().props.onClick?.();
165 await flushPromises();
166​
167 expect(testState.toast).not.toHaveBeenCalled();
168 });
169​
170 it("keeps the manual instruction for desktop servers without remote update support", () => {
171 const markup = renderToStaticMarkup(
172 <ServerUpdateAction
173 environmentId={"env-test" as EnvironmentId}
174 serverLabel="Test server"
175 selfUpdate="desktop-managed"
176 targetVersion="0.0.31"
177 />,
178 );
179​
180 expect(markup).toContain("Update the desktop app on that machine to update this server.");
181 expect(markup).not.toContain("<button");
182 });
183​
184 it("updates remote desktop apps through the shared update flow", async () => {
185 testState.updateServer.mockResolvedValue(
186 AsyncResult.success({ targetVersion: "0.0.34", method: "desktop-app" as const }),
187 );
188​
189 const action = ServerUpdateAction({
190 environmentId: "env-test" as EnvironmentId,
191 serverLabel: "Test server",
192 selfUpdate: "desktop-managed",
193 desktopAppUpdate: true,
194 targetVersion: "0.0.31",
195 }) as ActionElement;
196​
197 // No confirm-dialog host is mounted in this test, which the component
198 // treats as consent: the click itself was the request.
199 action.props.onClick?.();
200 await flushPromises();
201​
202 expect(testState.updateServer).toHaveBeenCalledWith({
203 environmentId: "env-test",
204 input: { targetVersion: "0.0.31" },
205 });
206 expect(testState.toast).toHaveBeenCalledWith({
207 type: "success",
208 title: "Test server updated",
209 description: "Desktop app relaunched on 0.0.34.",
210 });
211 });
212​
213 it("leaves thread continuation off by default", async () => {
214 testState.updateServer.mockResolvedValue(
215 AsyncResult.success({ targetVersion: "0.0.31", method: "boot-service" as const }),
216 );
217 const action = ServerUpdateAction({
218 environmentId: "env-test" as EnvironmentId,
219 serverLabel: "Test server",
220 selfUpdate: "boot-service",
221 threadContinuation: true,
222 targetVersion: "0.0.31",
223 }) as ActionElement;
224​
225 action.props.onClick?.();
226 await flushPromises();
227​
228 expect(testState.updateServer).toHaveBeenCalledWith({
229 environmentId: "env-test",
230 input: { targetVersion: "0.0.31" },
231 });
232 });
233​
234 it("applies the saved thread continuation preference automatically", async () => {
235 testState.updateServer.mockResolvedValue(
236 AsyncResult.success({ targetVersion: "0.0.31", method: "boot-service" as const }),
237 );
238 testState.continueThreadsAfterServerUpdate = true;
239 const action = ServerUpdateAction({
240 environmentId: "env-test" as EnvironmentId,
241 serverLabel: "Test server",
242 selfUpdate: "boot-service",
243 threadContinuation: true,
244 targetVersion: "0.0.31",
245 }) as ActionElement;
246​
247 action.props.onClick?.();
248 await flushPromises();
249​
250 expect(testState.updateServer).toHaveBeenCalledWith({
251 environmentId: "env-test",
252 input: { targetVersion: "0.0.31", continueRunningThreads: true },
253 });
254 });
255});
256​
257describe("ServerUpdatesAction", () => {
258 let renderer: ReactTestRenderer | undefined;
259 const targets: ReadonlyArray<ServerUpdateTarget> = [
260 {
261 environmentId: "batch-a" as EnvironmentId,
262 serverLabel: "Laptop",
263 selfUpdate: "boot-service",
264 targetVersion: "0.0.31",
265 threadContinuation: true,
266 continueThreadsAfterServerUpdate: true,
267 },
268 {
269 environmentId: "batch-b" as EnvironmentId,
270 serverLabel: "Office",
271 selfUpdate: "respawn",
272 targetVersion: "0.0.31",
273 threadContinuation: true,
274 continueThreadsAfterServerUpdate: false,
275 },
276 {
277 environmentId: "batch-c" as EnvironmentId,
278 serverLabel: "Manual",
279 selfUpdate: null,
280 targetVersion: "0.0.31",
281 },
282 ];
283 const success = AsyncResult.success({ targetVersion: "0.0.31", method: "boot-service" as const });
284​
285 async function mount(batch = targets) {
286 await act(async () => {
287 renderer = create(<ServerUpdatesAction targets={batch} />);
288 });
289 return renderer!.root.findByType("button");
290 }
291​
292 beforeEach(() => {
293 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
294 testState.updateServer.mockReset();
295 testState.toast.mockReset();
296 resetConfirmDialogForTests();
297 });
298 afterEach(async () => {
299 await act(async () => {
300 renderer?.unmount();
301 });
302 renderer = undefined;
303 resetConfirmDialogForTests();
304 vi.unstubAllGlobals();
305 });
306​
307 it("updates both supported machines with their own continuation preference and skips the manual machine", async () => {
308 testState.updateServer.mockResolvedValue(success);
309 const button = await mount();
310 await act(async () => {
311 button.props.onClick();
312 });
313​
314 expect(testState.updateServer.mock.calls.map(([target]) => target)).toEqual([
315 {
316 environmentId: "batch-a",
317 input: { targetVersion: "0.0.31", continueRunningThreads: true },
318 },
319 { environmentId: "batch-b", input: { targetVersion: "0.0.31" } },
320 ]);
321 expect(testState.toast.mock.calls.map(([toast]) => toast.title)).toEqual([
322 "Laptop updated",
323 "Office updated",
324 ]);
325 });
326​
327 it("names a failed machine while letting the other machine complete", async () => {
328 testState.updateServer
329 .mockResolvedValueOnce(AsyncResult.failure(Cause.fail(new Error("Download failed"))))
330 .mockResolvedValueOnce(success);
331 const button = await mount();
332 await act(async () => {
333 button.props.onClick();
334 });
335​
336 expect(testState.updateServer).toHaveBeenCalledTimes(2);
337 expect(testState.toast).toHaveBeenCalledWith({
338 type: "error",
339 title: "Laptop update failed",
340 description: "Download failed",
341 });
342 expect(testState.toast).toHaveBeenCalledWith(
343 expect.objectContaining({ type: "success", title: "Office updated" }),
344 );
345 expect(button.props.disabled).toBe(false);
346 });
347​
348 it("starts each machine once when double-clicked and disables the action until both finish", async () => {
349 const completions: Array<() => void> = [];
350 testState.updateServer.mockImplementation(
351 () =>
352 new Promise((resolve) => {
353 completions.push(() => resolve(success));
354 }),
355 );
356 const button = await mount();
357 await act(async () => {
358 button.props.onClick();
359 button.props.onClick();
360 });
361 expect(testState.updateServer).toHaveBeenCalledTimes(2);
362 expect(button.props.disabled).toBe(true);
363 await act(async () => {
364 completions[0]!();
365 });
366 expect(button.props.disabled).toBe(true);
367 await act(async () => {
368 completions[1]!();
369 });
370 expect(button.props.disabled).toBe(false);
371 expect(testState.toast).toHaveBeenCalledTimes(2);
372 });
373​
374 it("asks once for desktop machines and cancels the entire batch", async () => {
375 registerConfirmDialogHost();
376 const button = await mount(
377 targets.map((target, index) =>
378 index < 2 ? { ...target, selfUpdate: "desktop-managed", desktopAppUpdate: true } : target,
379 ),
380 );
381 await act(async () => {
382 button.props.onClick();
383 });
384 const confirmation = readConfirmDialogState();
385 expect(confirmation).toEqual(
386 expect.objectContaining({
387 status: "confirming",
388 message: expect.stringContaining("Laptop, Office"),
389 }),
390 );
391 expect(testState.updateServer).not.toHaveBeenCalled();
392 await act(async () => {
393 respondToConfirmDialog(false);
394 });
395 expect(testState.updateServer).not.toHaveBeenCalled();
396 expect(button.props.disabled).toBe(false);
397 });
398});
399​
400describe("ServerUpdateProgress", () => {
401 it("shows one calm status row for the restart wait", () => {
402 const markup = renderToStaticMarkup(
403 <ServerUpdateProgress
404 state={{
405 status: "running",
406 stage: "resuming",
407 fromVersion: "0.0.30",
408 targetVersion: "0.0.31",
409 }}
410 />,
411 );
412​
413 expect(markup).toContain("Restarting…");
414 // The wait state is monochrome and calm: no versions, no step rail, no
415 // success/warning colors, one duty-cycled pulse on the dot.
416 expect(markup).not.toContain("0.0.30");
417 expect(markup).not.toContain("Resum");
418 expect(markup).not.toContain("text-success");
419 expect(markup).not.toContain("text-primary");
420 expect(markup).toContain("animate-status-pulse");
421 expect(markup).not.toContain("animate-spin");
422 });
423​
424 it("folds the sub-second installing handoff into the download phase", () => {
425 const markup = renderToStaticMarkup(
426 <ServerUpdateProgress
427 state={{
428 status: "running",
429 stage: "installing",
430 fromVersion: "0.0.30",
431 targetVersion: "0.0.31",
432 }}
433 />,
434 );
435​
436 expect(markup).toContain("Downloading…");
437 expect(markup).not.toContain("Install");
438 });
439​
440 it("keeps the failure visible with its retryable error", () => {
441 const markup = renderToStaticMarkup(
442 <ServerUpdateProgress
443 state={{
444 status: "failed",
445 stage: "installing",
446 fromVersion: "0.0.30",
447 targetVersion: "0.0.31",
448 message: "The package could not be verified.",
449 }}
450 />,
451 );
452​
453 expect(markup).toContain('role="alert"');
454 expect(markup).toContain("The package could not be verified.");
455 expect(markup).not.toContain("animate-status-pulse");
456 });
457});