import { RegistryContext } from "@effect/atom-react"; import { AuthSessionState, type EnvironmentId } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; import * as Schema from "effect/Schema"; import { AsyncResult, Atom } from "effect/reactivity"; import type { ReactNode } from "react"; import { describe, expect, it, vi } from "vite-plus/test"; import { page, userEvent } from "vite-plus/test/browser"; import "~/index.css"; import { act, render, type Screen } from "../../test/render"; type SessionResult = AsyncResult.AsyncResult; const testState = vi.hoisted(() => ({ updateServer: vi.fn(), toast: vi.fn(), clipboard: vi.fn(), sessionAtom: null as unknown, })); vi.mock(import("~/hooks/useCopyToClipboard"), async (original) => ({ ...(await original()), useCopyToClipboard: ((options: { onCopy: (context: { command: string }) => void }) => ({ copyToClipboard: (command: string, context: { command: string }) => { testState.clipboard(command); options.onCopy(context); }, isCopied: false, })) as never, })); vi.mock(import("~/state/session"), async (original) => { const actual = await original(); return { ...actual, environmentSession: { ...actual.environmentSession, sessionStateAtom: (() => testState.sessionAtom) as never, }, }; }); vi.mock(import("~/state/use-atom-command"), async (original) => ({ ...(await original()), useAtomCommand: (() => testState.updateServer) as never, })); vi.mock(import("./ui/toast"), async (original) => { const actual = await original(); return { ...actual, toastManager: { ...actual.toastManager, add: testState.toast } }; }); import { resetConfirmDialogForTests } from "~/confirmDialog"; import { appAtomRegistry } from "~/rpc/atomRegistry"; import { ConfirmDialogHost } from "./ConfirmDialogHost"; import { ServerUpdateAction, ServerUpdatesAction, type ServerUpdateTarget, } from "./ServerUpdateAction"; const decodeSessionState = Schema.decodeUnknownSync(AuthSessionState); const legacyAuth = { policy: "remote-reachable", bootstrapMethods: ["one-time-token"], sessionMethods: ["bearer-access-token"], sessionCookieName: "t3_session", } as const; const currentSession = { authenticated: true, scopes: ["environment:maintain"], auth: { ...legacyAuth, serverUpdateScope: "environment:maintain", }, } as const satisfies AuthSessionState; const success = (method: "boot-service" | "desktop-app" = "boot-service", version = "0.0.31") => AsyncResult.success({ targetVersion: version, method }); let sessionAtom: Atom.Writable; function setSession(session: SessionResult) { appAtomRegistry.set(sessionAtom, session); } function setup(): Disposable { testState.updateServer.mockReset(); testState.toast.mockReset(); testState.clipboard.mockReset(); sessionAtom = Atom.make(AsyncResult.success(currentSession)); testState.sessionAtom = sessionAtom; resetConfirmDialogForTests(); return { [Symbol.dispose]: resetConfirmDialogForTests }; } function renderUpdate(element: ReactNode) { return render( {element}, ); } function renderWithConfirmHost(element: ReactNode) { return renderUpdate( <> {element} , ); } async function answerDesktopUpdateDialog(choice: "Cancel" | "Confirm") { await expect.element(page.getByRole("alertdialog")).toHaveAccessibleDescription(/interrupt/i); await userEvent.click(page.getByRole("button", { name: choice })); await vi.waitFor(() => expect(document.querySelector('[role="alertdialog"]')).toBeNull()); } function button(screen: Screen, name?: string) { const buttons = [...screen.container.querySelectorAll("button")]; return name === undefined ? buttons[0] : buttons.find((element) => element.textContent?.trim() === name); } async function click(screen: Screen, name?: string) { await act(async () => button(screen, name)!.click()); } function renderAction(props: Partial[0]> = {}) { return renderUpdate( , ); } describe("ServerUpdateAction", () => { it.each([ { serverUpdateScope: undefined, scopes: ["orchestration:operate"], allowed: true }, { serverUpdateScope: undefined, scopes: ["orchestration:read"], allowed: false }, { serverUpdateScope: "environment:maintain", scopes: ["orchestration:operate"], allowed: false, }, { serverUpdateScope: "environment:maintain", scopes: ["environment:maintain"], allowed: true, }, ] as const)( "uses the advertised update scope $serverUpdateScope with grant $scopes", async ({ serverUpdateScope, scopes, allowed }) => { using _state = setup(); setSession( AsyncResult.success( decodeSessionState({ ...currentSession, scopes, auth: { ...legacyAuth, ...(serverUpdateScope === undefined ? {} : { serverUpdateScope }), }, }), ), ); testState.updateServer.mockResolvedValue(success()); await using screen = await renderAction(); expect(button(screen, "Update")!.disabled).toBe(!allowed); await click(screen, "Update"); expect(testState.updateServer).toHaveBeenCalledTimes(allowed ? 1 : 0); }, ); const desktopProps = { selfUpdate: "desktop-managed", desktopAppUpdate: true } as const; it("does not update a desktop app when no confirmation dialog can be shown", async () => { using _state = setup(); testState.updateServer.mockResolvedValue(success("desktop-app")); await using screen = await renderAction(desktopProps); await click(screen, "Update"); expect(testState.updateServer).not.toHaveBeenCalled(); }); it.each([ { choice: "Cancel", updates: 0 }, { choice: "Confirm", updates: 1 }, ] as const)( "updates a desktop app only when confirmed ($choice)", async ({ choice, updates }) => { using _state = setup(); testState.updateServer.mockResolvedValue(success("desktop-app")); await using screen = await renderWithConfirmHost( , ); await click(screen, "Update"); await answerDesktopUpdateDialog(choice); await vi.waitFor(() => expect(testState.updateServer).toHaveBeenCalledTimes(updates)); }, ); it("disables the action once maintenance access is removed", async () => { using _state = setup(); await using screen = await renderAction(); await act(() => setSession(AsyncResult.success({ ...currentSession, scopes: [] }))); expect(button(screen, "Update")!.disabled).toBe(true); await click(screen, "Update"); expect(testState.updateServer).not.toHaveBeenCalled(); }); }); describe("ServerUpdatesAction", () => { const targets: ReadonlyArray = [ { environmentId: "batch-a" as EnvironmentId, serverLabel: "Laptop", selfUpdate: "boot-service", targetVersion: "0.0.31", }, { environmentId: "batch-b" as EnvironmentId, serverLabel: "Office", selfUpdate: "respawn", targetVersion: "0.0.31", }, { environmentId: "batch-c" as EnvironmentId, serverLabel: "Manual", selfUpdate: null, targetVersion: "0.0.31", }, ]; const mount = (batch = targets) => renderUpdate(); it("names a failed machine while letting the other machine complete", async () => { using _state = setup(); testState.updateServer .mockResolvedValueOnce(AsyncResult.failure(Cause.fail(new Error("Download failed")))) .mockResolvedValueOnce(success()); await using screen = await mount(); await click(screen, "Update all"); expect(testState.updateServer).toHaveBeenCalledTimes(2); expect(testState.toast).toHaveBeenCalledWith({ type: "error", title: "Laptop update failed", description: "Download failed", }); expect(testState.toast).toHaveBeenCalledWith( expect.objectContaining({ type: "success", title: "Office updated" }), ); expect(button(screen, "Update all")!.disabled).toBe(false); }); const withDesktop: ReadonlyArray = [ targets[0]!, { environmentId: "batch-desktop" as EnvironmentId, serverLabel: "Studio", selfUpdate: "desktop-managed", desktopAppUpdate: true, targetVersion: "0.0.31", }, ]; it("does not update any machine when a desktop app needs a confirmation that cannot be shown", async () => { using _state = setup(); testState.updateServer.mockResolvedValue(success()); await using screen = await mount(withDesktop); await click(screen, "Update all"); expect(testState.updateServer).not.toHaveBeenCalled(); expect(button(screen, "Update all")!.disabled).toBe(false); }); it.each([ { choice: "Cancel", updates: 0 }, { choice: "Confirm", updates: 2 }, ] as const)( "updates desktop apps in a batch only when confirmed ($choice)", async ({ choice, updates }) => { using _state = setup(); testState.updateServer.mockResolvedValue(success()); await using screen = await renderWithConfirmHost( , ); await click(screen, "Update all"); await answerDesktopUpdateDialog(choice); await vi.waitFor(() => expect(testState.updateServer).toHaveBeenCalledTimes(updates)); }, ); });