refactor(webui): separate presentation views and expand component gallery (#6179)

* refactor(webui): organize shared components with an internal gallery

* refactor(webui): decouple views and expand component gallery

* fix(docker): include channel sources in WebUI build

* refactor(webui): cover all channel interfaces in gallery

* docs(webui): remove manual paragraph wrapping
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-14 00:11:00 +08:00
1 parent db804ef94a
commit 30e43aec82
109 files changed
+7874 -3459

No files matched your search

@@ -210,6 +210,23 @@ it("keeps the current chat visible when discovery fails and permits a retry", as
expect(fetchAutomationChats).toHaveBeenCalledTimes(2);
});
it("aborts discovery for the previous task and ignores its delayed chat choices", async () => {
let first!: (value: AutomationChatsPayload) => void;
let second!: (value: AutomationChatsPayload) => void;
vi.mocked(fetchAutomationChats).mockImplementationOnce(() => new Promise(resolve => { first = resolve; }));
vi.mocked(fetchAutomationChats).mockImplementationOnce(() => new Promise(resolve => { second = resolve; }));
const { rerender } = render(<AutomationDetailDialog {...props} job={job} onChangeChat={vi.fn()} />);
const oldSignal = vi.mocked(fetchAutomationChats).mock.calls[0][2]!;
rerender(<AutomationDetailDialog {...props} job={{ ...job, id: "another-task", chat_binding_revision: "rev-next" }} onChangeChat={vi.fn()} />);
expect(oldSignal.aborted).toBe(true);
await act(async () => first({ ...choices, current: target }));
expect(screen.getByRole("combobox", { name: "Run in chat" })).toBeDisabled();
expect(screen.getByRole("combobox", { name: "Run in chat" })).not.toHaveTextContent("Product team");
await act(async () => second({ ...choices, current: target, revision: "rev-next" }));
expect(screen.getByRole("combobox", { name: "Run in chat" })).toHaveTextContent("Product team");
expect(screen.getByRole("combobox", { name: "Run in chat" })).toBeEnabled();
});
const webTarget = { ...target, channel: "websocket" };
const namedSessions: ChatSummary[] = [source, webTarget].map((chat) => ({
key: `websocket:${chat.id}`, channel: "websocket", chatId: chat.id,
@@ -3,6 +3,7 @@ import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { AutomationRunDialog } from "@/components/settings/system/AutomationRunDialog";
import { AutomationRunDialogView } from "@/components/settings/system/AutomationRunDialogView";
import { fetchAutomationRunResult } from "@/lib/api";
import i18n from "@/i18n";
import type { SessionAutomationJob } from "@/lib/types";
@@ -25,6 +26,21 @@ beforeEach(async () => {
afterEach(cleanup);
describe("Automation run response", () => {
it("renders caller-owned results and delegates retry without loading a run", async () => {
const retry = vi.fn();
const { rerender } = render(<AutomationRunDialogView job={job} run={run} locale="en" open
result={{ status: "error", response: null }} onRetry={retry}
onOpenChange={props.onOpenChange} onCloseAutoFocus={props.onCloseAutoFocus} />);
await userEvent.click(screen.getByRole("button", { name: "Retry" }));
expect(retry).toHaveBeenCalledTimes(1);
expect(fetchResult).not.toHaveBeenCalled();
rerender(<AutomationRunDialogView job={job} run={run} locale="en" open
result={{ status: "loaded", response: "A supplied result" }} onRetry={retry}
onOpenChange={props.onOpenChange} onCloseAutoFocus={props.onCloseAutoFocus} />);
expect(await screen.findByText("A supplied result")).toBeVisible();
expect(fetchResult).not.toHaveBeenCalled();
});
it("loads only the selected run and renders its Markdown response", async () => {
let complete!: (value: { response: string }) => void;
fetchResult.mockReturnValue(new Promise((resolve) => { complete = resolve; }));
+200
View File
@@ -0,0 +1,200 @@
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, 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 { registeredChannelUiContributions } from "@/channel-plugins/registry";
const inventory = componentInventory(resolve(cwd(), ".."));
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: "Button · 按钮" });
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", exact: true }));
expect(screen.getByText("Button clicks: 1")).toBeVisible();
expect(screen.getByRole("button", { name: "Unavailable", exact: true })).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: "Button · 按钮" })).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: "Button · 按钮" });
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: "示例消息" });
await userEvent.type(input, "Try the real composer{Enter}");
expect(await screen.findByText("提交内容:Try the real composer")).toBeVisible();
expect(input).toHaveValue("");
expect(fetch).toHaveBeenCalledTimes(1);
expect(fetch.mock.calls[0][0]).toBe("/__nanobot_components");
});
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 · 配对路由" });
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: "ProvidersSettings · 管理提供商" });
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", exact: true })).toBeVisible();
expect(dialog.getByTestId("provider-logo-anthropic")).toBeVisible();
expect(dialog.queryByRole("button", { name: "OpenAI", exact: true })).not.toBeInTheDocument();
await userEvent.click(dialog.getByRole("button", { name: "Add provider", exact: true }));
await userEvent.click(screen.getByRole("option", { name: "OpenAI", exact: true }));
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", exact: true }));
dialog = within(await screen.findByRole("dialog", { name: "Manage providers" }));
await userEvent.click(dialog.getByRole("button", { name: "OpenAI", exact: true }));
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 · 频道配置" });
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", exact: true }));
expect(token).toHaveAttribute("aria-invalid", "true");
expect(preview.getByRole("switch", { name: "Enable channel", exact: true })).not.toBeChecked();
await userEvent.type(token, "gallery-example-token");
await userEvent.click(preview.getByRole("switch", { name: "Enable channel", exact: true }));
expect(preview.getByRole("switch", { name: "Enable channel", exact: true })).toBeChecked();
await userEvent.click(preview.getByRole("button", { name: "Advanced", exact: true }));
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");
});
+28 -1
View File
@@ -1,10 +1,12 @@
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { expect, it, vi } from "vitest";
import { HostNavigationContext } from "@/components/remote/HostSwitcher";
import { AboutSettings } from "@/components/settings/overview/OverviewSettings";
import { AboutSettings, AppearanceSettings } from "@/components/settings/overview/OverviewSettings";
import { VersionCheckRowView } from "@/components/settings/overview/VersionCheckRowView";
import { NanobotClient } from "@/lib/nanobot-client";
import { ClientProvider } from "@/providers/ClientProvider";
import type { SettingsPayload } from "@/lib/types";
import { DEFAULT_LOCAL_PREFS } from "@/lib/local-preferences";
import { jsonResponse, settingsPayload, renderSettingsView, installSettingsViewTestHooks } from "@/tests/settings-test-utils";
const thirdPartyBrandNotice =
@@ -13,6 +15,31 @@ import { jsonResponse, settingsPayload, renderSettingsView, installSettingsViewT
describe("Settings overview and appearance", () => {
installSettingsViewTestHooks();
it("displays a caller-owned version result and delegates checking without a client provider", () => {
const check = vi.fn();
render(<VersionCheckRowView currentVersion="0.3.5" checking={false}
result={{ type: "update", latestVersion: "0.3.6", pypiUrl: "https://pypi.org/project/nanobot-ai/" }} onCheck={check} />);
expect(screen.getByText("Update available v0.3.6")).toBeVisible();
expect(screen.getByRole("link", { name: "PyPI" })).toHaveAttribute("href", "https://pypi.org/project/nanobot-ai/");
fireEvent.click(screen.getByRole("button", { name: "Check for updates" }));
expect(check).toHaveBeenCalledTimes(1);
});
it.each(["granted", "denied"])("updates task notifications only after browser permission is %s", async (permission) => {
const requestPermission = vi.fn().mockResolvedValue(permission);
vi.stubGlobal("Notification", { permission: "default", requestPermission });
const changePreferences = vi.fn();
render(<AppearanceSettings theme="light" onToggleTheme={vi.fn()} localPrefs={DEFAULT_LOCAL_PREFS} onChangeLocalPrefs={changePreferences} />);
fireEvent.click(screen.getByRole("switch", { name: "Task notifications" }));
expect(changePreferences).not.toHaveBeenCalled();
await waitFor(() => expect(requestPermission).toHaveBeenCalledTimes(1));
await act(async () => { await Promise.resolve(); });
if (permission === "granted") {
expect(changePreferences).toHaveBeenCalledTimes(1);
expect(changePreferences.mock.calls[0][0](DEFAULT_LOCAL_PREFS).browserNotifications).toBe(true);
} else expect(changePreferences).not.toHaveBeenCalled();
});
it("links the host's short commit beside its version", () => {
const commit = "abcdef12".repeat(5);
+13
View File
@@ -5,6 +5,7 @@ import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { StarLink, StarPrompt } from "@/components/StarPrompt";
import { StarPromptView } from "@/components/StarPromptView";
import { starPromptAction } from "@/lib/api";
import i18n from "@/i18n";
import { supportedLocales } from "@/i18n/config";
@@ -34,6 +35,18 @@ async function clickStarLink(link: HTMLElement) {
await act(async () => fireEvent.click(link));
}
it("renders an invitation from caller-owned state and delegates actions without claiming it", async () => {
const star = vi.fn();
const dismiss = vi.fn();
render(<StarPromptView open saving={false} error={false} onOpenChange={vi.fn()}
onStar={star} onDismissForever={dismiss} />);
await clickStarLink(screen.getByRole("link", { name: "Star on GitHub" }));
expect(star).toHaveBeenCalledTimes(1);
await userEvent.click(screen.getByRole("button", { name: "Don't ask again" }));
expect(dismiss).toHaveBeenCalledTimes(1);
expect(action).not.toHaveBeenCalled();
});
it("claims once on entry and lets users skip without permanently dismissing", async () => {
const view = render(<StarPrompt ready />);
await enter();
+1 -1
View File
@@ -2,7 +2,7 @@ import { fireEvent, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest";
import { ToggleButton } from "@/components/settings/ToggleButton";
import { ToggleButton } from "@/components/ui/toggle-button";
describe("ToggleButton", () => {
it("uses shared theme colors and compact dimensions in both states", () => {
+78
View File
@@ -0,0 +1,78 @@
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import QRCode from "qrcode";
import type { NanobotFeatureInfo } from "@/lib/types";
import { WeixinConnectFlow } from "../../../nanobot/channels/weixin/webui/WeixinConnectFlow";
import { WeixinConnectFlowView } from "../../../nanobot/channels/weixin/webui/WeixinConnectFlowView";
const { requestMutation, useClientMock } = vi.hoisted(() => ({
requestMutation: vi.fn(), useClientMock: vi.fn(),
}));
vi.mock("@/providers/ClientProvider", () => ({ useClient: useClientMock }));
const challenge = {
session_id: "weixin-verification", status: "pending" as const,
qr_url: "https://example.com/weixin", challenge: "verify_code" as const,
};
const feature: NanobotFeatureInfo = {
name: "weixin", display_name: "WeChat", type: "channel", webui: "webui/index.tsx",
enabled: false, configured: false, installed: true, ready: true, status: "not_enabled",
install_supported: true, requires_restart: false,
};
beforeEach(() => {
requestMutation.mockReset();
useClientMock.mockReset().mockReturnValue({ client: { requestMutation } });
vi.spyOn(QRCode, "toDataURL").mockResolvedValue("data:image/png;base64,preview");
});
afterEach(() => { cleanup(); vi.useRealTimers(); vi.restoreAllMocks(); });
describe("WeChat verification views", () => {
it("renders without a runtime client and retains the verification draft after a rejected code", async () => {
const onPoll = vi.fn().mockResolvedValue({ ...challenge, verification_failed: true });
const props = {
connect: challenge, busy: false, error: null, minimalPending: true,
onStart: vi.fn(), onCancel: vi.fn(), onPoll,
};
const view = render(<WeixinConnectFlowView {...props} />);
const code = screen.getByRole("textbox", { name: "Code" });
fireEvent.change(code, { target: { value: " 987654 " } });
fireEvent.click(screen.getByRole("button", { name: "Verify", exact: true }));
await waitFor(() => expect(onPoll).toHaveBeenCalledWith({ verify_code: "987654" }));
view.rerender(<WeixinConnectFlowView {...props} connect={{ ...challenge, verification_failed: true }} busy />);
expect(code).toHaveValue(" 987654 ");
expect(code).toHaveAttribute("aria-invalid", "true");
expect(code).toHaveAttribute("aria-describedby", screen.getByRole("alert").id);
expect(screen.getByRole("button", { name: "Verify", exact: true })).toBeDisabled();
expect(useClientMock).not.toHaveBeenCalled();
expect(requestMutation).not.toHaveBeenCalled();
});
it("pauses automatic polling for verification and submits the code through the real adapter", async () => {
requestMutation.mockResolvedValueOnce(challenge);
const onFeaturesUpdate = vi.fn();
render(<WeixinConnectFlow token="tok" feature={feature} onFeaturesUpdate={onFeaturesUpdate} />);
const code = await screen.findByRole("textbox", { name: "Code" });
vi.useFakeTimers();
await act(async () => { await vi.advanceTimersByTimeAsync(6000); });
expect(requestMutation).toHaveBeenCalledTimes(1);
expect(requestMutation).toHaveBeenCalledWith("settings.channel.connect.start", { channel: "weixin" }, 150_000);
requestMutation.mockResolvedValueOnce({ ...challenge, verification_failed: true });
fireEvent.change(code, { target: { value: "123456" } });
await act(async () => { fireEvent.click(screen.getByRole("button", { name: "Verify", exact: true })); });
expect(requestMutation).toHaveBeenLastCalledWith("settings.channel.connect.poll", {
channel: "weixin", session_id: "weixin-verification", verify_code: "123456",
}, 150_000);
expect(code).toHaveValue("123456");
expect(code).toHaveAttribute("aria-invalid", "true");
const features = { features: [{ ...feature, configured: true }], enabled_count: 0 };
requestMutation.mockResolvedValueOnce({ ...challenge, status: "succeeded", nanobot_features: features });
await act(async () => { fireEvent.click(screen.getByRole("button", { name: "Verify", exact: true })); });
expect(onFeaturesUpdate).toHaveBeenCalledWith(features);
expect(screen.getByText("WeChat is connected.")).toBeVisible();
expect(screen.queryByRole("textbox", { name: "Code" })).not.toBeInTheDocument();
});
});