Open History to see the last commit
1import { RegistryContext } from "@effect/atom-react";
2import { AuthSessionState, type EnvironmentId } from "@t3tools/contracts";
3import * as Cause from "effect/Cause";
4import * as Schema from "effect/Schema";
5import { AsyncResult, Atom } from "effect/reactivity";
6import type { ReactNode } from "react";
7import { describe, expect, it, vi } from "vite-plus/test";
8
9import { act, render, type Screen } from "../../test/render";
10
11type SessionResult = AsyncResult.AsyncResult<AuthSessionState, Error>;
12const testState = vi.hoisted(() => ({
13 updateServer: vi.fn(),
14 toast: vi.fn(),
15 clipboard: vi.fn(),
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("~/state/session"), async (original) => {
30 const actual = await original();
31 return {
32 ...actual,
33 environmentSession: {
34 ...actual.environmentSession,
35 sessionStateAtom: (() => testState.sessionAtom) as never,
36 },
37 };
38});
39vi.mock(import("~/state/use-atom-command"), async (original) => ({
40 ...(await original()),
41 useAtomCommand: (() => testState.updateServer) as never,
42}));
43vi.mock(import("./ui/toast"), async (original) => {
44 const actual = await original();
45 return { ...actual, toastManager: { ...actual.toastManager, add: testState.toast } };
46});
47
48import { resetConfirmDialogForTests } from "~/confirmDialog";
49import { appAtomRegistry } from "~/rpc/atomRegistry";
50import {
51 ServerUpdateAction,
52 ServerUpdatesAction,
53 type ServerUpdateTarget,
54} from "./ServerUpdateAction";
55
56const decodeSessionState = Schema.decodeUnknownSync(AuthSessionState);
57
58const legacyAuth = {
59 policy: "remote-reachable",
60 bootstrapMethods: ["one-time-token"],
61 sessionMethods: ["bearer-access-token"],
62 sessionCookieName: "t3_session",
63} as const;
64
65const currentSession = {
66 authenticated: true,
67 scopes: ["environment:maintain"],
68 auth: {
69 ...legacyAuth,
70 serverUpdateScope: "environment:maintain",
71 },
72} as const satisfies AuthSessionState;
73
74const success = (method: "boot-service" | "desktop-app" = "boot-service", version = "0.0.31") =>
75 AsyncResult.success({ targetVersion: version, method });
76
77let sessionAtom: Atom.Writable<SessionResult>;
78
79function setSession(session: SessionResult) {
80 appAtomRegistry.set(sessionAtom, session);
81}
82
83function setup(): Disposable {
84 testState.updateServer.mockReset();
85 testState.toast.mockReset();
86 testState.clipboard.mockReset();
87 sessionAtom = Atom.make<SessionResult>(AsyncResult.success(currentSession));
88 testState.sessionAtom = sessionAtom;
89 resetConfirmDialogForTests();
90 return { [Symbol.dispose]: resetConfirmDialogForTests };
91}
92
93function renderUpdate(element: ReactNode) {
94 return render(
95 <RegistryContext.Provider value={appAtomRegistry}>{element}</RegistryContext.Provider>,
96 );
97}
98
99function button(screen: Screen, name?: string) {
100 const buttons = [...screen.container.querySelectorAll("button")];
101 return name === undefined
102 ? buttons[0]
103 : buttons.find((element) => element.textContent?.trim() === name);
104}
105
106async function click(screen: Screen, name?: string) {
107 await act(async () => button(screen, name)!.click());
108}
109
110function renderAction(props: Partial<Parameters<typeof ServerUpdateAction>[0]> = {}) {
111 return renderUpdate(
112 <ServerUpdateAction
113 environmentId={"env-test" as EnvironmentId}
114 serverLabel="Test server"
115 selfUpdate="boot-service"
116 targetVersion="0.0.31"
117 {...props}
118 />,
119 );
120}
121
122describe("ServerUpdateAction", () => {
123 it.each([
124 { serverUpdateScope: undefined, scopes: ["orchestration:operate"], allowed: true },
125 { serverUpdateScope: undefined, scopes: ["orchestration:read"], allowed: false },
126 {
127 serverUpdateScope: "environment:maintain",
128 scopes: ["orchestration:operate"],
129 allowed: false,
130 },
131 {
132 serverUpdateScope: "environment:maintain",
133 scopes: ["environment:maintain"],
134 allowed: true,
135 },
136 ] as const)(
137 "uses the advertised update scope $serverUpdateScope with grant $scopes",
138 async ({ serverUpdateScope, scopes, allowed }) => {
139 using _state = setup();
140 setSession(
141 AsyncResult.success(
142 decodeSessionState({
143 ...currentSession,
144 scopes,
145 auth: {
146 ...legacyAuth,
147 ...(serverUpdateScope === undefined ? {} : { serverUpdateScope }),
148 },
149 }),
150 ),
151 );
152 testState.updateServer.mockResolvedValue(success());
153
154 await using screen = await renderAction();
155 expect(button(screen, "Update")!.disabled).toBe(!allowed);
156 await click(screen, "Update");
157
158 expect(testState.updateServer).toHaveBeenCalledTimes(allowed ? 1 : 0);
159 },
160 );
161
162 it("disables the action once maintenance access is removed", async () => {
163 using _state = setup();
164 await using screen = await renderAction();
165 await act(() => setSession(AsyncResult.success({ ...currentSession, scopes: [] })));
166 expect(button(screen, "Update")!.disabled).toBe(true);
167 await click(screen, "Update");
168 expect(testState.updateServer).not.toHaveBeenCalled();
169 });
170});
171
172describe("ServerUpdatesAction", () => {
173 const targets: ReadonlyArray<ServerUpdateTarget> = [
174 {
175 environmentId: "batch-a" as EnvironmentId,
176 serverLabel: "Laptop",
177 selfUpdate: "boot-service",
178 targetVersion: "0.0.31",
179 },
180 {
181 environmentId: "batch-b" as EnvironmentId,
182 serverLabel: "Office",
183 selfUpdate: "respawn",
184 targetVersion: "0.0.31",
185 },
186 {
187 environmentId: "batch-c" as EnvironmentId,
188 serverLabel: "Manual",
189 selfUpdate: null,
190 targetVersion: "0.0.31",
191 },
192 ];
193
194 const mount = (batch = targets) => renderUpdate(<ServerUpdatesAction targets={batch} />);
195
196 it("names a failed machine while letting the other machine complete", async () => {
197 using _state = setup();
198 testState.updateServer
199 .mockResolvedValueOnce(AsyncResult.failure(Cause.fail(new Error("Download failed"))))
200 .mockResolvedValueOnce(success());
201 await using screen = await mount();
202 await click(screen, "Update all");
203
204 expect(testState.updateServer).toHaveBeenCalledTimes(2);
205 expect(testState.toast).toHaveBeenCalledWith({
206 type: "error",
207 title: "Laptop update failed",
208 description: "Download failed",
209 });
210 expect(testState.toast).toHaveBeenCalledWith(
211 expect.objectContaining({ type: "success", title: "Office updated" }),
212 );
213 expect(button(screen, "Update all")!.disabled).toBe(false);
214 });
215});