Skip to content

Your lightweight open-source personal agent.

15.2 KB
Raw Blame
import { resolve } from "node:path";
import { cwd } from "node:process";
import { act, cleanup, render, screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, beforeAll, beforeEach, expect, it, vi } from "vitest";

import { Gallery, examples } from "@/dev/gallery/Gallery";
import { componentInventory } from "@/dev/gallery/inventory-plugin";
import { foundationPath } from "@/dev/gallery/inventory";
import { initializeGalleryI18n } from "@/dev/gallery/i18n";
import { registeredChannelUiContributions } from "@/channel-plugins/registry";

const inventory = componentInventory(resolve(cwd(), ".."));

beforeAll(initializeGalleryI18n);
beforeEach(() => {
  window.history.replaceState({}, "", "/gallery.html");
});

afterEach(() => {
  cleanup();
  vi.unstubAllGlobals();
});

it("indexes shared component exports and their application and channel consumers", () => {
  const toggle = inventory.find((item) => item.path === `${foundationPath}toggle-button.tsx`);
  expect(toggle?.exports).toContain("ToggleButton");
  expect(toggle?.usedBy).toEqual(expect.arrayContaining([
    "webui/src/components/thread/WorkspaceControls.tsx",
    "nanobot/channels/linear/webui/LinearMemberAccessView.tsx",
  ]));
  expect(inventory.find((item) => item.path === "nanobot/channels/linear/webui/LinearMemberAccess.tsx")?.group)
    .toBe("Channels / linear");
  expect(inventory.find((item) => item.path === "nanobot/channels/linear/webui/index.tsx")?.exports).toContain("default");
  expect(inventory.find((item) => item.path === "webui/src/components/MarkdownTextRenderer.tsx")?.exports).toContain("default");
});

it("provides a live example for every foundation source and resolves every documented example source", () => {
  const previewed = new Set(examples.flatMap((example) => example.files));
  for (const item of inventory.filter((source) => source.group === "Foundations")) {
    expect(previewed.has(item.path), `Missing foundation example: ${item.path}`).toBe(true);
  }
  const known = new Set(inventory.map((source) => source.path));
  for (const file of previewed) expect(known.has(file), `Unknown example source: ${file}`).toBe(true);
});

it("finds a shared component by its name and renders its working variants", async () => {
  vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ ok: true, json: async () => inventory }));
  render(<Gallery />);
  await screen.findByRole("heading", { name: "Buttons" });
  await userEvent.type(screen.getByRole("searchbox", { name: "Search components" }), "toggle-button");
  expect(screen.getByRole("link", { name: /toggle-button/ })).toHaveAttribute("href", expect.stringContaining("toggle-button"));
  await userEvent.click(screen.getByRole("button", { name: "destructive" }));
  expect(screen.getByText("Button clicks: 1")).toBeVisible();
  expect(screen.getByRole("button", { name: "Unavailable" })).toBeDisabled();
});

it("lets the developer retry a failed inventory request", async () => {
  vi.stubGlobal("fetch", vi.fn().mockResolvedValueOnce({ ok: false })
    .mockResolvedValueOnce({ ok: true, json: async () => inventory }));
  render(<Gallery />);
  expect(await screen.findByRole("alert")).toHaveTextContent("Could not load the inventory");
  await userEvent.click(screen.getByRole("button", { name: "Refresh inventory" }));
  expect(await screen.findByRole("heading", { name: "Buttons" })).toBeVisible();
});

it("covers every registered channel and its presentation components", () => {
  const previewed = new Set(examples.flatMap((example) => example.files));
  for (const { channel, webui } of registeredChannelUiContributions()) {
    const entry = `nanobot/channels/${channel}/${webui}`;
    expect(inventory.find((source) => source.path === entry)?.exports).toContain("default");
    expect(previewed.has(entry), `Missing channel entry preview: ${channel}`).toBe(true);
  }
  for (const source of inventory.filter((item) => item.path.startsWith("nanobot/channels/"))) {
    const hasView = inventory.some((view) => previewed.has(view.path) && view.usedBy.includes(source.path));
    expect(previewed.has(source.path) || hasView, `Missing channel component preview: ${source.path}`).toBe(true);
  }
});

it("starts with working previews and lets the developer inspect source-only modules", async () => {
  vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ ok: true, json: async () => inventory }));
  render(<Gallery />);
  await screen.findByRole("heading", { name: "Buttons" });
  expect(screen.queryByRole("link", { name: /SettingsPage/ })).not.toBeInTheDocument();

  await userEvent.click(screen.getByRole("button", { name: "All source" }));
  const sourceLink = screen.getByRole("link", { name: /SettingsPage Source only/ });
  // happy-dom does not follow anchor navigation or emit the browser's hashchange.
  act(() => {
    window.location.hash = sourceLink.getAttribute("href")!;
    window.dispatchEvent(new HashChangeEvent("hashchange"));
  });
  expect(await screen.findByRole("heading", { name: "Source only" })).toBeVisible();
  expect(screen.getByRole("link", { name: /Settings composition/ })).toBeVisible();

  await userEvent.click(screen.getByRole("button", { name: "Previews" }));
  expect(await screen.findByRole("region", { name: "Component preview" })).toBeVisible();
  expect(screen.queryByRole("heading", { name: "Source only" })).not.toBeInTheDocument();
});

it("opens bookmarked source entries and offers all source when a preview search has no match", async () => {
  const source = "webui/src/components/settings/SettingsView.tsx";
  window.history.replaceState({}, "", `/gallery.html#${new URLSearchParams({ component: source })}`);
  vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ ok: true, json: async () => inventory }));
  render(<Gallery />);
  expect(await screen.findByRole("heading", { name: "SettingsView" })).toBeVisible();
  expect(screen.getByRole("link", { name: /^SettingsView Source only/ })).toHaveAttribute("aria-current", "page");

  await userEvent.click(screen.getByRole("button", { name: "Previews" }));
  await userEvent.type(screen.getByRole("searchbox", { name: "Search components" }), source);
  expect(screen.getByText("No matching previews.")).toBeVisible();
  await userEvent.click(screen.getByRole("button", { name: "Search all source" }));
  expect(screen.getByRole("link", { name: /^SettingsView Source only/ })).toBeVisible();
});

it("submits a message through the actual composer using only local preview state", async () => {
  const source = "webui/src/components/thread/ThreadComposer.tsx";
  window.history.replaceState({}, "", `/gallery.html#${new URLSearchParams({ component: source })}`);
  const fetch = vi.fn().mockResolvedValue({ ok: true, json: async () => inventory });
  vi.stubGlobal("fetch", fetch);
  render(<Gallery />);
  const input = await screen.findByRole("textbox", { name: "Example message" });
  await userEvent.type(input, "Try the real composer{Enter}");
  expect(await screen.findByText("Submitted: Try the real composer")).toBeVisible();
  expect(input).toHaveValue("");
  expect(fetch).toHaveBeenCalledTimes(1);
  expect(fetch.mock.calls[0][0]).toBe("/__nanobot_components");
});

it("switches the chat list preview between ready, loading, empty and archived states", async () => {
  const source = "webui/src/components/SidebarSelectionHighlight.tsx";
  window.history.replaceState({}, "", `/gallery.html#${new URLSearchParams({ component: source })}`);
  vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ ok: true, json: async () => inventory }));
  render(<Gallery />);
  await screen.findByRole("heading", { name: "ChatList · Chat list" });
  const preview = within(screen.getByRole("region", { name: "Component preview" }));
  const setMode = async (mode: string) => {
    await userEvent.click(preview.getByRole("combobox", { name: "Chat list state" }));
    await userEvent.click(screen.getByRole("option", { name: mode }));
  };

  expect(preview.getByRole("button", { name: "@design 组件设计" })).toBeVisible();
  expect(preview.getByRole("button", { name: "@tests 验证交互" })).toBeVisible();
  expect(preview.getAllByRole("button", { name: /^@/ })).toHaveLength(2);

  await setMode("loading");
  expect(preview.getByText("Loading…")).toBeVisible();
  await setMode("empty");
  expect(preview.getByText("No sessions yet.")).toBeVisible();
  await setMode("archived");
  const archived = within(preview.getByRole("region", { name: "Archived" }));
  expect(archived.getByRole("button", { name: "@history 历史方案" })).toBeVisible();
  expect(preview.getAllByRole("button", { name: /^@/ })).toHaveLength(3);

  await setMode("ready");
  expect(preview.getByRole("button", { name: "@design 组件设计" })).toHaveAttribute("aria-current", "page");
  expect(preview.getAllByRole("button", { name: /^@/ })).toHaveLength(2);
});

it("edits a pairing route without mounting a client or making a gateway mutation", async () => {
  const source = "webui/src/components/remote/PairRouteSettingsView.tsx";
  window.history.replaceState({}, "", `/gallery.html#${new URLSearchParams({ component: source })}`);
  const fetch = vi.fn().mockResolvedValue({ ok: true, json: async () => inventory });
  vi.stubGlobal("fetch", fetch);
  render(<Gallery />);
  await screen.findByRole("heading", { name: "PairRouteSettingsView · Pairing route" });
  const preview = within(screen.getByRole("region", { name: "Component preview" }));
  expect(preview.getByRole("button", { name: "Save changes" })).toBeDisabled();
  await userEvent.click(preview.getByRole("combobox", { name: "Network route" }));
  await userEvent.click(screen.getByRole("option", { name: "VPN 路由" }));
  await userEvent.click(preview.getByRole("button", { name: "Save changes" }));
  expect(preview.getByRole("status")).toHaveTextContent("Saved");
  expect(preview.getByRole("button", { name: "Save changes" })).toBeDisabled();
  expect(fetch).toHaveBeenCalledTimes(1);
  expect(fetch.mock.calls[0][0]).toBe("/__nanobot_components");
});

it("uses the real provider manager and saves a new provider entirely in preview state", async () => {
  const source = "webui/src/components/settings/models/ProviderSettings.tsx";
  window.history.replaceState({}, "", `/gallery.html#${new URLSearchParams({ component: source })}`);
  const fetch = vi.fn().mockResolvedValue({ ok: true, json: async () => inventory });
  vi.stubGlobal("fetch", fetch);
  render(<Gallery />);
  await screen.findByRole("heading", { name: "Provider management" });
  const preview = within(screen.getByRole("region", { name: "Component preview" }));
  await userEvent.click(preview.getByRole("button", { name: "Manage providers" }));
  let dialog = within(screen.getByRole("dialog", { name: "Manage providers" }));
  expect(dialog.getByRole("button", { name: "Anthropic" })).toBeVisible();
  expect(dialog.getByTestId("provider-logo-anthropic")).toBeVisible();
  expect(dialog.queryByRole("button", { name: "OpenAI" })).not.toBeInTheDocument();

  await userEvent.click(dialog.getByRole("button", { name: "Add provider" }));
  await userEvent.click(screen.getByRole("option", { name: "OpenAI" }));
  dialog = within(screen.getByRole("dialog", { name: "OpenAI" }));
  await userEvent.type(dialog.getByLabelText("API key", { selector: "input" }), "gallery-example-key");
  const apiURL = dialog.getByLabelText("API URL");
  await userEvent.clear(apiURL);
  await userEvent.type(apiURL, "https://preview.example/v1");
  await userEvent.click(dialog.getByRole("button", { name: "Add provider" }));

  dialog = within(await screen.findByRole("dialog", { name: "Manage providers" }));
  await userEvent.click(dialog.getByRole("button", { name: "OpenAI" }));
  expect(screen.getByLabelText("API URL")).toHaveValue("https://preview.example/v1");
  await userEvent.keyboard("{Escape}{Escape}");
  expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
  expect(preview.getByRole("button", { name: "Manage providers" })).toHaveFocus();
  expect(fetch).toHaveBeenCalledTimes(1);
  expect(fetch.mock.calls[0][0]).toBe("/__nanobot_components");
});

it("renders a registered channel's real secret fields and enable action without a gateway", async () => {
  const source = "nanobot/channels/telegram/webui/index.ts";
  window.history.replaceState({}, "", `/gallery.html#${new URLSearchParams({ component: source })}`);
  const fetch = vi.fn().mockResolvedValue({ ok: true, json: async () => inventory });
  vi.stubGlobal("fetch", fetch);
  render(<Gallery />);
  await screen.findByRole("heading", { name: "Telegram · Channel setup" });
  const preview = within(screen.getByRole("region", { name: "Component preview" }));
  const token = preview.getByLabelText("Bot token", { selector: "input" });
  expect(token).toHaveAttribute("type", "password");
  await userEvent.click(preview.getByRole("switch", { name: "Enable channel" }));
  expect(token).toHaveAttribute("aria-invalid", "true");
  expect(preview.getByRole("switch", { name: "Enable channel" })).not.toBeChecked();
  await userEvent.type(token, "gallery-example-token");
  await userEvent.click(preview.getByRole("switch", { name: "Enable channel" }));
  expect(preview.getByRole("switch", { name: "Enable channel" })).toBeChecked();
  await userEvent.click(preview.getByRole("button", { name: "Advanced" }));
  expect(preview.getByRole("group", { name: "Connection mode" })).toBeVisible();
  expect(preview.getByRole("radio", { name: "Long polling" })).toBeChecked();
  expect(fetch).toHaveBeenCalledTimes(1);
  expect(fetch.mock.calls[0][0]).toBe("/__nanobot_components");
});

it("previews QQ QR states and retries without connecting to the portal", async () => {
  const source = "nanobot/channels/qq/webui/index.tsx";
  window.history.replaceState({}, "", `/gallery.html#${new URLSearchParams({ component: source })}`);
  const fetch = vi.fn().mockResolvedValue({ ok: true, json: async () => inventory });
  vi.stubGlobal("fetch", fetch);
  render(<Gallery />);
  await screen.findByRole("heading", { name: "QQConnectFlowView · QQ QR connection" });
  const preview = within(screen.getByRole("region", { name: "Component preview" }));
  expect(await preview.findByRole("img", { name: "QQ binding QR code" })).toBeVisible();
  await userEvent.click(preview.getByRole("button", { name: "Cancel" }));
  expect(preview.queryByRole("img", { name: "QQ binding QR code" })).not.toBeInTheDocument();
  await userEvent.click(preview.getByRole("button", { name: "Bind QQ bot" }));
  expect(await preview.findByRole("img", { name: "QQ binding QR code" })).toBeVisible();
  await userEvent.click(preview.getByRole("combobox", { name: "QQ connection state" }));
  await userEvent.click(screen.getByRole("option", { name: "succeeded" }));
  expect(preview.getByText("Configured")).toBeVisible();
  expect(preview.queryByText(/Rebinding may interrupt other apps/)).not.toBeInTheDocument();
  await userEvent.click(preview.getByRole("button", { name: "Rebind bot" }));
  const confirmation = screen.getByRole("alertdialog", { name: "Rebind bot" });
  expect(confirmation).toHaveTextContent("Rebinding may interrupt other apps using this QQ bot. If the App Secret is reset, the old secret becomes invalid and those apps need the new secret.");
  await userEvent.click(within(confirmation).getByRole("button", { name: "Cancel" }));
  expect(preview.getByText("Configured")).toBeVisible();
  expect(fetch).toHaveBeenCalledTimes(1);
  expect(fetch.mock.calls[0][0]).toBe("/__nanobot_components");
});