perf(webui): defer non-chat startup interfaces
This commit is contained in:
1 parent
ae7fed88e2
commit
4bd1b74c6b
20 files changed
+710
-70
No files matched your search
@@ -0,0 +1,197 @@
|
||||
import { Buffer } from "node:buffer";
|
||||
import { act, cleanup, render, screen, waitFor } from "@testing-library/react";
|
||||
import type { QRCodeToDataURLOptions } from "qrcode";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type { ChannelQrConnectFlowViewProps } from "@/components/settings/channels/ChannelQrConnectFlowView";
|
||||
import type { ChannelConnectPayload } from "@/lib/types";
|
||||
|
||||
const props: ChannelQrConnectFlowViewProps = {
|
||||
connect: null,
|
||||
busy: false,
|
||||
error: null,
|
||||
onStart: () => {},
|
||||
onCancel: () => {},
|
||||
onPoll: async () => null,
|
||||
labels: {
|
||||
qrAlt: "Connection QR code",
|
||||
scanTitle: "Scan to connect",
|
||||
scanDescription: "Scan with your app",
|
||||
waiting: "Waiting",
|
||||
connected: "Connected",
|
||||
stopped: "Stopped",
|
||||
connecting: "Connecting",
|
||||
scanAgain: "Scan again",
|
||||
connect: "Connect",
|
||||
},
|
||||
};
|
||||
|
||||
const firstUrl = "https://example.com/connect/first";
|
||||
const nextUrl = "https://example.com/connect/next";
|
||||
const currentImage = "data:image/png;base64,current";
|
||||
const qrOptions = {
|
||||
width: 184,
|
||||
margin: 1,
|
||||
color: { dark: "#111827", light: "#ffffff" },
|
||||
};
|
||||
|
||||
function pending(qr_url?: string): ChannelConnectPayload {
|
||||
return { session_id: "qr-session", status: "pending", qr_url };
|
||||
}
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (error: Error) => void;
|
||||
const promise = new Promise<T>((res, rej) => { resolve = res; reject = rej; });
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
function mockQrModule(ready: Promise<void> = Promise.resolve()) {
|
||||
const toDataURL = vi.fn<(text: string, options: QRCodeToDataURLOptions) => Promise<string>>()
|
||||
.mockResolvedValue(currentImage);
|
||||
const load = vi.fn(async () => {
|
||||
await ready;
|
||||
return { default: { toDataURL } };
|
||||
});
|
||||
vi.doMock("qrcode", load);
|
||||
return { toDataURL, load };
|
||||
}
|
||||
|
||||
async function loadView() {
|
||||
const { ChannelQrConnectFlowView } = await import("@/components/settings/channels/ChannelQrConnectFlowView");
|
||||
return ChannelQrConnectFlowView;
|
||||
}
|
||||
|
||||
beforeEach(() => { vi.resetModules(); });
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.doUnmock("qrcode");
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("channel QR encoder loading", () => {
|
||||
it("loads and encodes only when a visible QR URL is available", async () => {
|
||||
const { toDataURL, load } = mockQrModule();
|
||||
toDataURL.mockImplementation(async (text, options) => {
|
||||
const actual = await vi.importActual<typeof import("qrcode")>("qrcode");
|
||||
return actual.toDataURL(text, options);
|
||||
});
|
||||
const View = await loadView();
|
||||
const view = render(<View {...props} />);
|
||||
await vi.dynamicImportSettled();
|
||||
expect(load).not.toHaveBeenCalled();
|
||||
expect(toDataURL).not.toHaveBeenCalled();
|
||||
|
||||
view.rerender(<View {...props} connect={pending()} />);
|
||||
await vi.dynamicImportSettled();
|
||||
expect(screen.getByRole("status")).toHaveTextContent("Connecting");
|
||||
expect(load).not.toHaveBeenCalled();
|
||||
expect(toDataURL).not.toHaveBeenCalled();
|
||||
|
||||
view.rerender(<View {...props} connect={pending(firstUrl)} showQrCode={false} />);
|
||||
await vi.dynamicImportSettled();
|
||||
expect(screen.getByRole("status")).toHaveTextContent("Waiting");
|
||||
expect(screen.getByText("Scan with your app")).toBeVisible();
|
||||
expect(screen.queryByRole("img")).not.toBeInTheDocument();
|
||||
expect(load).not.toHaveBeenCalled();
|
||||
expect(toDataURL).not.toHaveBeenCalled();
|
||||
|
||||
view.rerender(<View {...props} connect={pending(firstUrl)} />);
|
||||
const image = await screen.findByRole("img", { name: "Connection QR code" });
|
||||
expect(load).toHaveBeenCalledOnce();
|
||||
expect(toDataURL).toHaveBeenCalledOnce();
|
||||
expect(toDataURL).toHaveBeenCalledWith(firstUrl, qrOptions);
|
||||
expect(image).toHaveClass("h-[184px]", "w-[184px]");
|
||||
expect(screen.getByRole("status")).toHaveTextContent("Waiting");
|
||||
const source = image.getAttribute("src")!;
|
||||
expect(source).toMatch(/^data:image\/png;base64,/);
|
||||
const png = Buffer.from(source.split(",")[1], "base64");
|
||||
expect(png.subarray(0, 8).toString("hex")).toBe("89504e470d0a1a0a");
|
||||
expect(png.readUInt32BE(16)).toBe(184);
|
||||
expect(png.readUInt32BE(20)).toBe(184);
|
||||
});
|
||||
|
||||
it.each(["removed", "hidden", "unmounted"] as const)(
|
||||
"does not encode if the QR is %s while the library loads",
|
||||
async (change) => {
|
||||
const ready = deferred<void>();
|
||||
const { toDataURL, load } = mockQrModule(ready.promise);
|
||||
const View = await loadView();
|
||||
const view = render(<View {...props} connect={pending(firstUrl)} />);
|
||||
await waitFor(() => expect(load).toHaveBeenCalledOnce());
|
||||
if (change === "unmounted") {
|
||||
view.unmount();
|
||||
} else {
|
||||
view.rerender(<View {...props}
|
||||
connect={pending(change === "removed" ? undefined : firstUrl)}
|
||||
showQrCode={change !== "hidden"} />);
|
||||
}
|
||||
|
||||
await act(async () => {
|
||||
ready.resolve(undefined);
|
||||
await vi.dynamicImportSettled();
|
||||
});
|
||||
expect(toDataURL).not.toHaveBeenCalled();
|
||||
expect(screen.queryByRole("img")).not.toBeInTheDocument();
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["result", "failure"] as const)(
|
||||
"ignores a late encoder %s after a newer QR is displayed",
|
||||
async (outcome) => {
|
||||
const stale = deferred<string>();
|
||||
const current = deferred<string>();
|
||||
const { toDataURL } = mockQrModule();
|
||||
toDataURL.mockReturnValueOnce(stale.promise).mockReturnValueOnce(current.promise);
|
||||
const View = await loadView();
|
||||
const view = render(<View {...props} connect={pending(firstUrl)} />);
|
||||
await waitFor(() => expect(toDataURL).toHaveBeenCalledTimes(1));
|
||||
view.rerender(<View {...props} connect={pending(nextUrl)} />);
|
||||
await waitFor(() => expect(toDataURL).toHaveBeenCalledTimes(2));
|
||||
await act(async () => { current.resolve(currentImage); });
|
||||
expect(screen.getByRole("img")).toHaveAttribute("src", currentImage);
|
||||
|
||||
await act(async () => {
|
||||
if (outcome === "result") stale.resolve("data:image/png;base64,stale");
|
||||
else stale.reject(new Error("Old QR encoding failed"));
|
||||
});
|
||||
expect(screen.getByRole("img")).toHaveAttribute("src", currentImage);
|
||||
expect(screen.getByRole("status")).toHaveTextContent("Waiting");
|
||||
},
|
||||
);
|
||||
|
||||
it("does not resurrect a hidden QR from a late encoder result when shown again", async () => {
|
||||
const stale = deferred<string>();
|
||||
const current = deferred<string>();
|
||||
const { toDataURL } = mockQrModule();
|
||||
toDataURL.mockReturnValueOnce(stale.promise).mockReturnValueOnce(current.promise);
|
||||
const View = await loadView();
|
||||
const view = render(<View {...props} connect={pending(firstUrl)} />);
|
||||
await waitFor(() => expect(toDataURL).toHaveBeenCalledTimes(1));
|
||||
view.rerender(<View {...props} connect={pending(firstUrl)} showQrCode={false} />);
|
||||
await act(async () => { stale.resolve("data:image/png;base64,stale"); });
|
||||
view.rerender(<View {...props} connect={pending(firstUrl)} />);
|
||||
await waitFor(() => expect(toDataURL).toHaveBeenCalledTimes(2));
|
||||
expect(screen.queryByRole("img")).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("status")).toHaveTextContent("Connecting");
|
||||
|
||||
await act(async () => { current.resolve(currentImage); });
|
||||
expect(screen.getByRole("img")).toHaveAttribute("src", currentImage);
|
||||
});
|
||||
|
||||
it.each(["loading", "encoding"] as const)("keeps the existing placeholder on %s failure", async (stage) => {
|
||||
const { toDataURL } = mockQrModule();
|
||||
if (stage === "loading") {
|
||||
vi.doMock("qrcode", () => { throw new Error("QR chunk unavailable"); });
|
||||
} else {
|
||||
toDataURL.mockRejectedValue(new Error("QR encoding failed"));
|
||||
}
|
||||
const View = await loadView();
|
||||
render(<View {...props} connect={pending(firstUrl)} />);
|
||||
await act(async () => { await vi.dynamicImportSettled(); });
|
||||
expect(screen.queryByRole("img")).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("status")).toHaveTextContent("Connecting");
|
||||
expect(screen.getByRole("button", { name: "Cancel" })).toBeEnabled();
|
||||
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,255 @@
|
||||
import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { Window as HappyWindow } from "happy-dom";
|
||||
import type { InboundEvent, Outbound } from "@/lib/types";
|
||||
|
||||
(window as unknown as HappyWindow).happyDOM.settings.disableIframePageLoading = true;
|
||||
|
||||
vi.mock("@/lib/bootstrap", async (original) => ({
|
||||
...await original<typeof import("@/lib/bootstrap")>(),
|
||||
fetchBootstrap: vi.fn(async () => ({ token: "test", api_token: "test", ws_path: "/" })),
|
||||
deriveWsUrl: () => "ws://test",
|
||||
}));
|
||||
// Keep this suite focused on App's remote boundary rather than the chat implementation.
|
||||
vi.mock("@/components/thread/ThreadShell", () => ({
|
||||
ThreadShell: () => <textarea aria-label="Local draft" />,
|
||||
}));
|
||||
|
||||
const profile = {
|
||||
id: "3b968d52-081d-4898-9970-ff0a1fc93817", name: "Team server", host: "ubuntu@example.test",
|
||||
port: 22, config_path: "~/.nanobot/config.json", ssh_config: "", identity_file: "", runtime_user: "", connected: false,
|
||||
};
|
||||
const connection = {
|
||||
...profile, hostname: "team-host", gateway_id: "gateway-1",
|
||||
url: "http://127.0.0.1:23456/#/?bootstrapSecret=test-only",
|
||||
};
|
||||
|
||||
class TestSocket {
|
||||
static current: TestSocket;
|
||||
readyState = 0;
|
||||
sent: Outbound[] = [];
|
||||
onopen: (() => void) | null = null;
|
||||
onmessage: ((event: MessageEvent) => void) | null = null;
|
||||
onclose: (() => void) | null = null;
|
||||
|
||||
constructor() { TestSocket.current = this; }
|
||||
open() { this.readyState = 1; this.onopen?.(); }
|
||||
close() { this.readyState = 3; this.onclose?.(); }
|
||||
receive(event: InboundEvent) {
|
||||
this.onmessage?.(new MessageEvent("message", { data: JSON.stringify(event) }));
|
||||
}
|
||||
send(data: string) {
|
||||
const frame = JSON.parse(data) as Outbound;
|
||||
this.sent.push(frame);
|
||||
if (frame.type !== "webui_request") return;
|
||||
const result = frame.action === "remote.connect" ? connection
|
||||
: frame.action === "remote.pair_start" ? { id: "test-pair", command: "nanobot remote pair nbpr1.test", expires: Date.now() / 1000 + 600 }
|
||||
: frame.action === "remote.discover" ? { hosts: [], files: [], incomplete: false } : {};
|
||||
queueMicrotask(() => this.receive({
|
||||
event: "webui_response", request_id: frame.request_id, ok: true, result,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
let releaseManagement: (() => void) | undefined;
|
||||
let managementImport: Promise<typeof import("@/components/remote/RemoteConnectionsPage")> | undefined;
|
||||
|
||||
async function finishManagementImport() {
|
||||
await act(async () => { releaseManagement?.(); await managementImport; });
|
||||
}
|
||||
|
||||
async function loadApp(deferManagement = false, importError?: Error) {
|
||||
const loaded = vi.fn();
|
||||
const gate = new Promise<void>((resolve) => { releaseManagement = resolve; });
|
||||
vi.doMock("@/components/remote/RemoteConnectionsPage", (original) => {
|
||||
loaded();
|
||||
if (importError) return Promise.reject(importError);
|
||||
managementImport = (async () => {
|
||||
if (deferManagement) await gate;
|
||||
return original<typeof import("@/components/remote/RemoteConnectionsPage")>();
|
||||
})();
|
||||
return managementImport;
|
||||
});
|
||||
const { initializeI18n, loadAllLocaleResources } = await import("@/i18n");
|
||||
await initializeI18n();
|
||||
await loadAllLocaleResources();
|
||||
const { default: App } = await import("@/App");
|
||||
return { App, loaded };
|
||||
}
|
||||
|
||||
async function readyShell() {
|
||||
await screen.findByRole("button", { name: "Switch host" });
|
||||
await act(async () => { TestSocket.current.open(); });
|
||||
}
|
||||
|
||||
async function manageConnections() {
|
||||
fireEvent.pointerDown(screen.getByRole("button", { name: "Switch host" }), { button: 0, ctrlKey: false });
|
||||
fireEvent.click(await screen.findByRole("menuitem", { name: "Manage connections" }));
|
||||
}
|
||||
|
||||
function managementSkeleton() {
|
||||
const status = screen.getByText("Loading nanobot…", { selector: "[role=status]" });
|
||||
const skeleton = status.closest("section");
|
||||
expect(skeleton).toBeVisible();
|
||||
expect(skeleton).toHaveAttribute("aria-busy", "true");
|
||||
expect(skeleton).toHaveAttribute("data-startup-surface", "remote");
|
||||
expect(skeleton).toHaveAttribute("data-embedded", "true");
|
||||
return skeleton;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
localStorage.clear();
|
||||
sessionStorage.clear();
|
||||
window.history.replaceState(null, "", "/#/new");
|
||||
vi.stubGlobal("WebSocket", TestSocket);
|
||||
vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {
|
||||
const path = String(input);
|
||||
if (path === "/api/remote-instances") return Response.json({ available: true, machine_name: "Local machine", profiles: [profile] });
|
||||
if (path === "/api/sessions") return Response.json({ sessions: [] });
|
||||
if (path === "/api/webui/sidebar-state") return Response.json({});
|
||||
return new Response(null, { status: 404 });
|
||||
}));
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
cleanup();
|
||||
await finishManagementImport();
|
||||
releaseManagement = undefined;
|
||||
managementImport = undefined;
|
||||
if (TestSocket.current) {
|
||||
TestSocket.current.onclose = null;
|
||||
TestSocket.current.close();
|
||||
}
|
||||
vi.doUnmock("@/components/remote/RemoteConnectionsPage");
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe("lazy remote management", () => {
|
||||
it("keeps chat and the host picker ready before loading management from the local menu", async () => {
|
||||
const { App, loaded } = await loadApp();
|
||||
expect(loaded).not.toHaveBeenCalled();
|
||||
render(<App />);
|
||||
await readyShell();
|
||||
const draft = await screen.findByRole("textbox", { name: "Local draft" });
|
||||
fireEvent.change(draft, { target: { value: "Keep my local draft" } });
|
||||
fireEvent.pointerDown(screen.getByRole("button", { name: "Switch host" }), { button: 0, ctrlKey: false });
|
||||
const host = await screen.findByRole("menuitem", { name: "Team server ubuntu@example.test" });
|
||||
expect(within(host).getByRole("status")).toHaveTextContent("Disconnected");
|
||||
expect(loaded).not.toHaveBeenCalled();
|
||||
fireEvent.click(screen.getByRole("menuitem", { name: "Manage connections" }));
|
||||
await screen.findByRole("heading", { name: "Remote connections" });
|
||||
expect(loaded).toHaveBeenCalledTimes(1);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Back" }));
|
||||
expect(screen.getByRole("textbox", { name: "Local draft" })).toBe(draft);
|
||||
expect(draft).toHaveValue("Keep my local draft");
|
||||
await manageConnections();
|
||||
await screen.findByRole("heading", { name: "Remote connections" });
|
||||
expect(loaded).toHaveBeenCalledTimes(1);
|
||||
expect(TestSocket.current.sent.filter((frame) => frame.type === "webui_request" && frame.action.startsWith("remote."))).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps the shell and local draft when the management import rejects, and can go back", async () => {
|
||||
vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
const { App, loaded } = await loadApp(false, new Error("Failed to fetch dynamically imported module"));
|
||||
render(<App />);
|
||||
await readyShell();
|
||||
const draft = await screen.findByRole("textbox", { name: "Local draft" });
|
||||
fireEvent.change(draft, { target: { value: "Keep my draft after a chunk failure" } });
|
||||
const hostPicker = screen.getByRole("button", { name: "Switch host" });
|
||||
await manageConnections();
|
||||
const alert = await screen.findByRole("alert");
|
||||
expect(alert).toHaveTextContent("Couldn't load this view. Go back, or reload the page to try again.");
|
||||
expect(screen.getByRole("button", { name: "Switch host" })).toBe(hostPicker);
|
||||
expect(hostPicker).toBeVisible();
|
||||
expect(draft).toBeInTheDocument();
|
||||
expect(draft).toHaveValue("Keep my draft after a chunk failure");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Back" }));
|
||||
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("textbox", { name: "Local draft" })).toBe(draft);
|
||||
expect(draft).toBeVisible();
|
||||
expect(draft).toHaveValue("Keep my draft after a chunk failure");
|
||||
expect(loaded).toHaveBeenCalledTimes(1);
|
||||
expect(TestSocket.current.sent.filter((frame) => frame.type === "webui_request" && frame.action.startsWith("remote."))).toEqual([]);
|
||||
});
|
||||
|
||||
it("shows the existing skeleton on a cold remote route, then opens pairing and SSH controls", async () => {
|
||||
window.history.replaceState(null, "", "/#/remote");
|
||||
const { App, loaded } = await loadApp(true);
|
||||
render(<App />);
|
||||
await readyShell();
|
||||
await waitFor(() => expect(loaded).toHaveBeenCalledTimes(1));
|
||||
managementSkeleton();
|
||||
await finishManagementImport();
|
||||
await screen.findByRole("heading", { name: "Remote connections" });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Connect to remote nanobot" }));
|
||||
await screen.findByText("nanobot remote pair nbpr1.test");
|
||||
fireEvent.pointerDown(screen.getByRole("button", { name: "Other ways" }), { button: 0, ctrlKey: false });
|
||||
fireEvent.click(screen.getByRole("menuitem", { name: "SSH connection" }));
|
||||
expect(await screen.findByRole("textbox", { name: "SSH address" })).toBeVisible();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Back to chat" }));
|
||||
expect(await screen.findByRole("textbox", { name: "Local draft" })).toBeVisible();
|
||||
expect(loaded).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("can leave local management while its chunk is pending without reopening it on completion", async () => {
|
||||
const { App, loaded } = await loadApp(true);
|
||||
render(<App />);
|
||||
await readyShell();
|
||||
const draft = await screen.findByRole("textbox", { name: "Local draft" });
|
||||
fireEvent.change(draft, { target: { value: "Unsent local draft" } });
|
||||
await manageConnections();
|
||||
await waitFor(() => expect(loaded).toHaveBeenCalledTimes(1));
|
||||
managementSkeleton();
|
||||
fireEvent.click(screen.getByRole("button", { name: "New topic" }));
|
||||
expect(screen.getByRole("textbox", { name: "Local draft" })).toBe(draft);
|
||||
expect(draft).toHaveValue("Unsent local draft");
|
||||
await finishManagementImport();
|
||||
expect(screen.queryByRole("region", { name: "Remote connections" })).not.toBeInTheDocument();
|
||||
expect(screen.queryByText("Loading nanobot…")).not.toBeInTheDocument();
|
||||
expect(TestSocket.current.sent.filter((frame) => frame.type === "webui_request" && frame.action.startsWith("remote."))).toEqual([]);
|
||||
});
|
||||
|
||||
it("restores the host before loading management and preserves its frame, selection and route", async () => {
|
||||
const { rememberSelectedRemote, readSelectedRemote } = await import("@/lib/remote-instances");
|
||||
rememberSelectedRemote(connection);
|
||||
const { App, loaded } = await loadApp(true);
|
||||
render(<App />);
|
||||
await readyShell();
|
||||
const frame = await screen.findByTitle("nanobot on Team server");
|
||||
await act(async () => { fireEvent.load(frame); });
|
||||
await waitFor(() => expect(readSelectedRemote()?.id).toBe(profile.id));
|
||||
expect(loaded).not.toHaveBeenCalled();
|
||||
const hash = window.location.hash;
|
||||
const title = document.title;
|
||||
const requests = TestSocket.current.sent.filter((frame) => frame.type === "webui_request");
|
||||
await manageConnections();
|
||||
await waitFor(() => expect(loaded).toHaveBeenCalledTimes(1));
|
||||
managementSkeleton();
|
||||
expect(screen.getByTestId("remote-management-surface")).toBeVisible();
|
||||
expect(screen.getByTitle("nanobot on Team server")).toBe(frame);
|
||||
expect(readSelectedRemote()?.id).toBe(profile.id);
|
||||
expect(window.location.hash).toBe(hash);
|
||||
expect(document.title).toBe(title);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Back" }));
|
||||
expect(frame).toBeVisible();
|
||||
expect(readSelectedRemote()?.id).toBe(profile.id);
|
||||
await manageConnections();
|
||||
managementSkeleton();
|
||||
await finishManagementImport();
|
||||
const page = await screen.findByRole("region", { name: "Remote connections" });
|
||||
const host = within(page).getByRole("button", { name: "Team server ubuntu@example.test" });
|
||||
expect(host).toHaveAttribute("aria-current", "true");
|
||||
expect(within(host).getByRole("status")).toHaveTextContent("Connected");
|
||||
fireEvent.click(within(page).getByRole("button", { name: "Back" }));
|
||||
expect(screen.getByTitle("nanobot on Team server")).toBe(frame);
|
||||
expect(frame).toBeVisible();
|
||||
expect(frame).toHaveAttribute("src", connection.url);
|
||||
expect(readSelectedRemote()?.id).toBe(profile.id);
|
||||
expect(window.location.hash).toBe(hash);
|
||||
expect(document.title).toBe(title);
|
||||
expect(TestSocket.current.sent.filter((frame) => frame.type === "webui_request")).toEqual(requests);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,97 @@
|
||||
import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { SessionAutomationJob } from "@/lib/types";
|
||||
|
||||
const job: SessionAutomationJob = {
|
||||
id: "job-1", name: "Morning check", enabled: true,
|
||||
schedule: { kind: "every", every_ms: 3_600_000 },
|
||||
payload: { message: "Check the project status" },
|
||||
state: { next_run_at_ms: Date.now() + 3_600_000 },
|
||||
};
|
||||
let release: (() => void) | undefined;
|
||||
let moduleLoad: Promise<unknown> | undefined;
|
||||
|
||||
async function loadView(fail = false) {
|
||||
const loaded = vi.fn();
|
||||
const gate = new Promise<void>((resolve) => { release = resolve; });
|
||||
vi.doMock("@/components/settings/system/AutomationsSettings", (original) => {
|
||||
loaded();
|
||||
moduleLoad = gate.then(() => {
|
||||
if (fail) throw new Error("Automation chunk unavailable");
|
||||
return original<typeof import("@/components/settings/system/AutomationsSettings")>();
|
||||
});
|
||||
return moduleLoad;
|
||||
});
|
||||
const { initializeI18n, loadAllLocaleResources } = await import("@/i18n");
|
||||
await initializeI18n();
|
||||
await loadAllLocaleResources();
|
||||
const { SessionInfoPopoverView } = await import("@/components/thread/SessionInfoPopoverView");
|
||||
render(<><textarea aria-label="Unsent draft" defaultValue="Keep this draft" /><SessionInfoPopoverView
|
||||
title="Release work" jobs={[job]} loading={false} loadFailed={false} now={Date.now()}
|
||||
onAction={async () => []} onEdit={async () => [job]}
|
||||
/></>);
|
||||
return loaded;
|
||||
}
|
||||
|
||||
async function selectJob() {
|
||||
fireEvent.click(screen.getByRole("button", { name: "Session details" }));
|
||||
fireEvent.click(await screen.findByRole("button", { name: /Morning check/ }));
|
||||
return screen.findByRole("dialog", { name: "Morning check" });
|
||||
}
|
||||
|
||||
beforeEach(() => { vi.resetModules(); localStorage.clear(); });
|
||||
afterEach(async () => {
|
||||
cleanup();
|
||||
await act(async () => { release?.(); await moduleLoad?.catch(() => {}); });
|
||||
release = undefined;
|
||||
moduleLoad = undefined;
|
||||
vi.doUnmock("@/components/settings/system/AutomationsSettings");
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("session automation dialog loading", () => {
|
||||
it("loads only on inspection and replaces a named loading dialog with the real controls", async () => {
|
||||
const loaded = await loadView();
|
||||
await vi.dynamicImportSettled();
|
||||
expect(loaded).not.toHaveBeenCalled();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Session details" }));
|
||||
const row = await screen.findByRole("button", { name: /Morning check/ });
|
||||
expect(loaded).not.toHaveBeenCalled();
|
||||
fireEvent.click(row);
|
||||
const pending = await screen.findByRole("dialog", { name: "Morning check" });
|
||||
expect(within(pending).getByRole("status", { name: "Loading automations..." })).toHaveAttribute("aria-busy", "true");
|
||||
await act(async () => { release?.(); await moduleLoad; });
|
||||
await screen.findByText("Check the project status");
|
||||
expect(screen.getAllByRole("dialog")).toHaveLength(1);
|
||||
expect(screen.getByRole("button", { name: "Edit" })).toBeEnabled();
|
||||
expect(screen.getByRole("textbox", { name: "Unsent draft", hidden: true })).toHaveValue("Keep this draft");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Close" }));
|
||||
await waitFor(() => expect(screen.getByRole("button", { name: "Session details" })).toHaveFocus());
|
||||
});
|
||||
|
||||
it("can close during download without a late dialog reopening", async () => {
|
||||
const loaded = await loadView();
|
||||
const dialog = await selectJob();
|
||||
await waitFor(() => expect(loaded).toHaveBeenCalledOnce());
|
||||
fireEvent.click(within(dialog).getByRole("button", { name: "Close" }));
|
||||
await waitFor(() => expect(screen.getByRole("button", { name: "Session details" })).toHaveFocus());
|
||||
await act(async () => { release?.(); await moduleLoad; });
|
||||
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("textbox", { name: "Unsent draft", hidden: true })).toHaveValue("Keep this draft");
|
||||
await selectJob();
|
||||
expect(await screen.findByText("Check the project status")).toBeVisible();
|
||||
expect(loaded).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("contains a failed chunk in a closeable dialog without losing the chat draft", async () => {
|
||||
vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
await loadView(true);
|
||||
await selectJob();
|
||||
await act(async () => { release?.(); await moduleLoad?.catch(() => {}); });
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("Could not load automations.");
|
||||
expect(screen.getByRole("textbox", { name: "Unsent draft", hidden: true })).toHaveValue("Keep this draft");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Close" }));
|
||||
await waitFor(() => expect(screen.getByRole("button", { name: "Session details" })).toHaveFocus());
|
||||
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -77,6 +77,7 @@ describe("SessionInfoPopover", () => {
|
||||
expect(screen.queryByText("Check the project status")).not.toBeInTheDocument();
|
||||
|
||||
await user.click(row);
|
||||
await screen.findByText("Check the project status");
|
||||
const detail = screen.getByRole("dialog", { name: "Morning check" });
|
||||
expect(detail).toHaveClass("max-w-[520px]", "rounded-modal");
|
||||
expect(within(detail).queryByText("Task instructions")).not.toBeInTheDocument();
|
||||
@@ -131,6 +132,7 @@ describe("SessionInfoPopover", () => {
|
||||
|
||||
await user.click(screen.getByRole("button", { name: "Session details" }));
|
||||
await user.click(await screen.findByRole("button", { name: /Morning check/ }));
|
||||
await screen.findByText("Check the project status");
|
||||
const detail = screen.getByRole("dialog", { name: "Morning check" });
|
||||
await user.click(within(detail).getByRole("button", { name: "More actions" }));
|
||||
await user.click(screen.getByRole("menuitem", { name: "Disable" }));
|
||||
@@ -167,7 +169,7 @@ describe("SessionInfoPopover", () => {
|
||||
|
||||
await user.click(screen.getByRole("button", { name: "Session details" }));
|
||||
await user.click(await screen.findByRole("button", { name: /Morning check/ }));
|
||||
await user.click(screen.getByRole("button", { name: "Edit" }));
|
||||
await user.click(await screen.findByRole("button", { name: "Edit" }));
|
||||
const editor = await screen.findByRole("dialog", { name: "Edit task" });
|
||||
expect(screen.getAllByRole("dialog")).toHaveLength(1);
|
||||
await user.click(within(editor).getByRole("button", { name: "Cancel" }));
|
||||
@@ -260,6 +262,7 @@ describe("SessionInfoPopover", () => {
|
||||
const row = await screen.findByRole("button", { name: /PR monitor/ });
|
||||
expect(screen.queryByText("Review PR #4591")).not.toBeInTheDocument();
|
||||
await user.click(row);
|
||||
await screen.findByText("Command");
|
||||
const detail = screen.getByRole("dialog", { name: "PR monitor" });
|
||||
expect(within(detail).getByText("Command")).toBeInTheDocument();
|
||||
expect(within(detail).getByText('nanobot trigger trg_123 "message"')).toBeInTheDocument();
|
||||
|
||||
Reference in new issue
Block a user