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