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