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

ServerUpdateAction.test.tsx

538 lines16.7 KB

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