feat(webui): expand and organize settings with autosave (#5704)

* feat(webui): expand settings with autosave and live configuration

* feat(memory): add long-term memory and idle compaction switches

* refactor(webui): clarify settings hierarchy and align compact controls

* refactor(webui): keep only memory consolidation in memory settings

* refactor(webui): defer runtime changes until explicit restart

* refactor(webui): remove default workspace setting

* fix(webui): align model lists and remove preset counters

* fix(i18n): use natural Chinese labels for chat platforms

* fix(i18n): shorten chat settings navigation label

* fix(webui): match settings navigation icons to text size

* refactor(webui): remove redundant settings sidebar heading

* refactor(webui): use icon-only back navigation in settings

* fix(webui): remove back arrow hover hint

* refactor(webui): remove redundant overview details

* refactor(webui): hide secondary descriptions in settings rows

* style(webui): replace settings dividers with rounded highlights

* refactor(webui): remove redundant model list subtitles and badges

* fix(i18n): restore chat translation namespace boundaries

* fix(i18n): complete settings translations for all locales

* fix(webui): reveal settings only for enabled capabilities

* fix(webui): consolidate capabilities and isolate settings feedback

* fix(webui): clear restart notices when settings are reverted

* fix(webui): anchor restart controls in settings sidebar

* fix(webui): shorten sidebar restart label

* fix(webui): align settings spacing and control sizes

* refactor(webui): unify settings dialogs and interaction feedback

* fix(webui): keep settings option groups on one line without scrolling

* refactor(webui): align settings spacing and sidebar icon proportions

* style(webui): match main sidebar typography to settings

* style(webui): use monospace for sidebar session handles

* refactor(webui): remove heartbeat configuration from automations

* feat(webui): expose configuration actions beside capability toggles

* style(webui): remove ellipsis from configuration actions

* refactor(webui): remove redundant app configuration controls

* feat(webui): add compact sidebar navigation and shortcut hints

* fix(webui): synchronize npm dependency lockfile

* test(webui): align input radius expectation with pill styling

* feat(webui): show daily token usage and cache breakdown

* feat(webui): add model usage details and cache hit rates

* feat(webui): chart daily token usage by model

* refactor(webui): simplify usage details and model labels

* fix(webui): hide usage dialog date range

* refactor(webui): consolidate model usage into chart legends

* fix(webui): enforce restart choices and correct settings test route

* fix(webui): polish settings localization and controls

* fix(webui): avoid repeated usage legend labels

* fix(webui): skip empty usage columns in keyboard navigation

* test(webui): assert settings behavior positively

* feat(webui): refine sidebar navigation and add drag resizing

* style(webui): soften sidebar scroll edges

* style(webui): harmonize sidebar typography and text colors

* feat(webui): move channels to the main sidebar

* style(webui): remove dotted underlines from settings hints

* fix(webui): unify tooltip hover delay

* fix(webui): support Seatbelt sandbox settings

* fix(webui): remove unused appearance density preference

* fix(webui): align settings input values consistently

* style(webui): group compact settings controls before inputs

* feat(webui): edit multiline settings in compact dialogs

* feat(webui): add continuous settings scrolling with gentle snapping

* Revert "feat(webui): add continuous settings scrolling with gentle snapping"

This reverts commit f0978c261a53c844185eeab4d0c3190fbd196fe6.
This commit is contained in:
chengyongru authored and GitHub committed 2026-09-10 11:10:51 +08:00
1 parent 20f115bf46
commit 8ea683679d
244 files changed
+6929 -3900

No files matched your search

+109 -457
View File
@@ -313,6 +313,7 @@ describe("App layout", () => {
Reflect.deleteProperty(window, "nanobotHost");
setNavigatorPlatform("Linux x86_64");
localStorage.removeItem("nanobot-webui.sidebar");
localStorage.removeItem("nanobot-webui.sidebar.width");
localStorage.removeItem("nanobot-webui.sidebar.completed-runs.v1");
localStorage.removeItem("nanobot-webui.sidebar.session-updates.v1");
localStorage.removeItem("nanobot-webui.collapsed-pane-groups.v1");
@@ -458,7 +459,7 @@ describe("App layout", () => {
expect(main).not.toHaveAttribute("style");
expect(screen.getByTestId("sidebar-brand-row")).toHaveClass("pt-3");
expect(screen.getByTestId("sidebar-brand-mark")).not.toHaveClass("mt-5");
expect(screen.getByRole("button", { name: "Collapse sidebar" })).toHaveClass("mt-1");
expect(screen.getByRole("separator", { name: "Resize sidebar" })).toHaveAttribute("aria-valuenow", "272");
const asideClassNames = Array.from(container.querySelectorAll("aside")).map(
(el) => el.className,
@@ -485,7 +486,7 @@ describe("App layout", () => {
expect(backButton.closest("aside")).toHaveClass("pt-4", "lg:pt-4");
expect(backButton).not.toHaveClass("-ml-1");
expect(container.querySelectorAll("main")).toHaveLength(1);
expect(screen.getByRole("heading", { level: 1, name: "Settings" })).toBeInTheDocument();
expect(screen.getByRole("navigation", { name: "Settings sections" })).toBeInTheDocument();
});
it("opens the full Models settings directly from the first-run prompt", async () => {
@@ -537,6 +538,29 @@ describe("App layout", () => {
).toBeTruthy();
});
it("opens Channels below Automations and supports its keyboard shortcut", async () => {
mockFetchRoutes({
"/api/settings": baseSettingsPayload(),
"/api/settings/nanobot-features": { features: [], enabled_count: 0 },
});
render(<App />);
await waitFor(() => expect(connectSpy).toHaveBeenCalled());
const sidebar = screen.getByRole("navigation", { name: "Sidebar navigation" });
const channels = within(sidebar).getByRole("button", { name: "Channels" });
expect(within(sidebar).getByRole("button", { name: "Automations" })
.compareDocumentPosition(channels) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
fireEvent.click(channels);
expect(await screen.findByRole("heading", { name: "Channels" })).toBeVisible();
expect(window.location.hash).toBe("#/channels");
expect(channels).toHaveAttribute("aria-current", "page");
expect(document.title).toBe("Channels · nanobot");
fireEvent.click(within(sidebar).getByRole("button", { name: "New topic" }));
await waitFor(() => expect(window.location.hash).toBe("#/new"));
fireEvent.keyDown(window, { key: "$", code: "Digit4", ctrlKey: true, shiftKey: true });
expect(await screen.findByRole("heading", { name: "Channels" })).toBeVisible();
expect(window.location.hash).toBe("#/channels");
});
it("highlights the blank new-topic destination immediately", async () => {
render(<App />);
@@ -545,12 +569,8 @@ describe("App layout", () => {
const newTopicButton = within(sidebar).getByRole("button", { name: "New topic" });
expect(newTopicButton).toHaveAttribute("aria-current", "page");
expect(newTopicButton).not.toHaveClass("bg-sidebar-accent");
expect(newTopicButton).toHaveClass("transition-[width,padding,color]");
expect(within(sidebar).getByTestId("actions-selection-highlight")).toHaveAttribute(
"data-active-id",
"new-chat",
);
expect(newTopicButton).toBeEnabled();
});
it("keeps a just-created topic route while the session list catches up", async () => {
@@ -899,7 +919,7 @@ describe("App layout", () => {
consoleError.mockRestore();
});
it("restores the Settings route after a restart fallback hash", async () => {
it("restores the standalone Channels page from a legacy restart route", async () => {
localStorage.setItem("nanobot-webui.restartStartedAt", String(Date.now()));
localStorage.setItem("nanobot-webui.restartRoute", "#/settings?section=channels");
window.history.replaceState(null, "", "/#/new");
@@ -925,9 +945,9 @@ describe("App layout", () => {
await waitFor(() => expect(connectSpy).toHaveBeenCalled());
expect(
await screen.findByRole("navigation", { name: "Settings sections" }),
await screen.findByRole("heading", { name: "Channels" }),
).toBeInTheDocument();
expect(screen.queryByRole("heading", { name: "Channels" })).not.toBeInTheDocument();
expect(within(screen.getByRole("navigation", { name: "Sidebar navigation" })).getByRole("button", { name: "Channels" })).toHaveAttribute("aria-current", "page");
expect(window.location.hash).toBe("#/settings?section=channels");
});
@@ -1656,6 +1676,35 @@ describe("App layout", () => {
expect(document.title).toBe("自动任务 · nanobot");
});
it("resizes the sidebar, collapses at the drag threshold and restores its saved width", async () => {
const view = render(<App />);
await waitFor(() => expect(connectSpy).toHaveBeenCalled());
const handle = screen.getByRole("separator", { name: "Resize sidebar" });
const sidebar = screen.getByTestId("host-sidebar-flow");
fireEvent.pointerDown(handle, { button: 0, pointerId: 1, clientX: 272 });
fireEvent.pointerMove(handle, { pointerId: 1, clientX: 360 });
fireEvent.pointerUp(handle, { pointerId: 1, clientX: 360 });
expect(sidebar).toHaveStyle({ width: "360px" });
expect(localStorage.getItem("nanobot-webui.sidebar.width")).toBe("360");
fireEvent.pointerDown(handle, { button: 0, pointerId: 2, clientX: 360 });
fireEvent.pointerMove(handle, { pointerId: 2, clientX: 150 });
expect(sidebar).toHaveStyle({ width: "56px" });
fireEvent.pointerMove(handle, { pointerId: 2, clientX: 180 });
expect(sidebar).toHaveStyle({ width: "56px" });
fireEvent.pointerMove(handle, { pointerId: 2, clientX: 240 });
fireEvent.pointerUp(handle, { pointerId: 2, clientX: 240 });
expect(sidebar).toHaveStyle({ width: "240px" });
fireEvent.keyDown(handle, { key: "Enter" });
expect(sidebar).toHaveStyle({ width: "56px" });
view.unmount();
render(<App />);
await waitFor(() => expect(screen.getByTestId("host-sidebar-flow")).toHaveStyle({ width: "56px" }));
fireEvent.click(within(screen.getByRole("navigation", { name: "Sidebar navigation" })).getByRole("button", { name: "Toggle sidebar" }));
expect(screen.getByTestId("host-sidebar-flow")).toHaveStyle({ width: "240px" });
fireEvent.keyDown(screen.getByRole("separator", { name: "Resize sidebar" }), { key: "ArrowRight" });
expect(screen.getByTestId("host-sidebar-flow")).toHaveStyle({ width: "272px" });
});
it("uses the shared sidebar controls and rail on the native host", async () => {
mockSessions = [
{
@@ -1682,13 +1731,13 @@ describe("App layout", () => {
expect(flowSidebar).toHaveStyle({ width: "272px" });
expect(screen.getByTestId("sidebar-brand-row")).toHaveClass("pt-3");
expect(screen.getByTestId("sidebar-brand-mark")).toHaveClass("mt-5");
expect(screen.getByRole("button", { name: "Collapse sidebar" })).toHaveClass("mt-1");
expect(screen.getByRole("separator", { name: "Resize sidebar" })).toHaveAttribute("aria-valuenow", "272");
expect(screen.queryByTestId("host-sidebar-toggle")).not.toBeInTheDocument();
expect(
screen.getByRole("navigation", { name: "Sidebar navigation" }),
).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Collapse sidebar" }));
fireEvent.keyDown(screen.getByRole("separator", { name: "Resize sidebar" }), { key: "Enter" });
await waitFor(() => expect(flowSidebar).toHaveStyle({ width: "56px" }));
expect(
screen.getByRole("navigation", { name: "Sidebar navigation" }),
@@ -2346,430 +2395,23 @@ describe("App layout", () => {
});
it("opens the settings view from the sidebar footer", async () => {
const user = userEvent.setup();
mockSessions = [
{
key: "websocket:chat-a",
channel: "websocket",
chatId: "chat-a",
createdAt: "2026-04-16T10:00:00Z",
updatedAt: "2026-04-16T10:00:00Z",
preview: "Existing chat",
},
];
vi.stubGlobal(
"fetch",
vi.fn(async (input: RequestInfo | URL) => {
const href = String(input);
if (href === "/api/settings/api-service") {
return jsonResponse({
installed: false,
running: false,
managed: false,
host: "127.0.0.1",
port: 8900,
timeout: 120,
endpoint: "http://127.0.0.1:8900/v1",
command: "nanobot serve",
});
}
if (href === "/api/settings/provider-models?provider=openai") {
return jsonResponse({
provider: "openai",
label: "OpenAI",
status: "available",
catalog_kind: "official",
models: [
{ id: "openai/gpt-4o", owned_by: "openai", context_window: 128000 },
{ id: "openai/gpt-4o-mini", owned_by: "openai", context_window: 128000 },
],
model_count: 2,
fetched_at: 1,
});
}
if (href.includes("/api/settings")) {
return {
ok: true,
status: 200,
json: async () => ({
agent: {
model: "openai/gpt-4o",
provider: "auto",
resolved_provider: "openai",
has_api_key: true,
model_preset: "primary",
max_tokens: 8192,
context_window_tokens: 65536,
temperature: 0.1,
reasoning_effort: null,
timezone: "UTC",
tool_hint_max_length: 40,
},
model_presets: [
{
name: "primary",
label: "Primary",
active: true,
is_default: false,
model: "openai/gpt-4o",
provider: "auto",
resolved_provider: "openai",
max_tokens: 8192,
context_window_tokens: 65536,
temperature: 0.1,
reasoning_effort: null,
},
{
name: "deep",
label: "deep",
active: false,
is_default: false,
model: "anthropic/claude-opus-4-5",
provider: "anthropic",
max_tokens: 8192,
context_window_tokens: 200000,
temperature: 0.1,
reasoning_effort: "high",
},
],
model_call_order: ["primary", "deep"],
model_call_order_editable: true,
providers: [
{
name: "openai",
label: "OpenAI",
configured: true,
api_key_hint: "open••••-key",
},
{
name: "openrouter",
label: "OpenRouter",
configured: false,
api_key_required: true,
default_api_base: "https://openrouter.ai/api/v1",
},
{
name: "ant_ling",
label: "Ant Ling",
configured: false,
api_key_required: true,
default_api_base: "https://api.ant-ling.com/v1",
},
{
name: "azure_openai",
label: "Azure OpenAI",
configured: false,
api_key_required: true,
},
{
name: "huggingface",
label: "Hugging Face",
configured: false,
api_key_required: true,
},
{
name: "siliconflow",
label: "SiliconFlow",
configured: false,
api_key_required: true,
},
{
name: "volcengine",
label: "VolcEngine",
configured: false,
api_key_required: true,
},
{
name: "byteplus",
label: "BytePlus",
configured: false,
api_key_required: true,
},
{
name: "qianfan",
label: "Qianfan",
configured: false,
api_key_required: true,
},
{
name: "atomic_chat",
label: "Atomic Chat",
configured: false,
api_key_required: false,
default_api_base: "http://localhost:1337/v1",
},
],
web_search: {
provider: "brave",
api_key_hint: "BSAo••••ew20",
base_url: null,
max_results: 5,
timeout: 30,
providers: [
{ name: "duckduckgo", label: "DuckDuckGo", credential: "none" },
{ name: "brave", label: "Brave Search", credential: "api_key" },
{ name: "tavily", label: "Tavily", credential: "api_key" },
],
},
web: {
enable: true,
proxy: null,
user_agent: null,
search: { max_results: 5, timeout: 30 },
fetch: { use_jina_reader: true },
},
image_generation: {
enabled: false,
provider: "openrouter",
provider_configured: true,
model: "openai/gpt-5.4-image-2",
default_aspect_ratio: "1:1",
default_image_size: "1K",
max_images_per_turn: 4,
save_dir: "generated",
providers: [
{
name: "openrouter",
label: "OpenRouter",
configured: true,
api_key_hint: "sk-o••••test",
api_base: "https://openrouter.ai/api/v1",
default_api_base: "https://openrouter.ai/api/v1",
},
{
name: "gemini",
label: "Gemini",
configured: false,
api_key_hint: null,
api_base: null,
default_api_base: "https://generativelanguage.googleapis.com/v1beta/openai/",
},
],
},
runtime: {
config_path: "/tmp/config.json",
workspace_path: "/tmp/workspace",
gateway_host: "127.0.0.1",
gateway_port: 18790,
heartbeat: {
enabled: true,
interval_s: 1800,
},
dream: {
schedule: "every 2h",
},
unified_session: false,
},
advanced: {
restrict_to_workspace: false,
webui_allow_local_service_access: true,
webui_default_access_mode: "default",
private_service_protection_enabled: true,
ssrf_whitelist_count: 0,
mcp_server_count: 0,
exec_enabled: true,
exec_sandbox: null,
exec_path_prepend_set: false,
exec_path_append_set: false,
},
requires_restart: false,
}),
};
}
return { ok: false, status: 404, json: async () => ({}) };
}),
);
localStorage.setItem(
"nanobot-webui.settings-preferences",
JSON.stringify({ brandLogos: true }),
);
mockFetchRoutes({ "/api/settings": baseSettingsPayload() });
render(<App />);
await waitFor(() => expect(connectSpy).toHaveBeenCalled());
const sidebar = screen.getByRole("navigation", { name: "Sidebar navigation" });
const searchButton = within(sidebar).getByRole("button", { name: "Search" });
const appsButton = within(sidebar).getByRole("button", { name: "Apps" });
expect(searchButton.compareDocumentPosition(appsButton) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
await user.click(within(sidebar).getByRole("button", { name: "Settings" }));
expect(
await screen.findByRole("navigation", { name: "Settings sections" }),
).toBeInTheDocument();
expect(screen.queryByRole("heading", { name: "Overview" })).not.toBeInTheDocument();
expect(document.title).toBe("Settings · nanobot");
expect(screen.getByTestId("overview-logo-openai")).toBeInTheDocument();
expect(screen.getByTestId("overview-logo-brave")).toBeInTheDocument();
expect(screen.getByTestId("overview-logo-openrouter")).toBeInTheDocument();
expect(screen.queryByTestId("overview-logo-nanobot-gateway")).not.toBeInTheDocument();
expect(screen.queryByTestId("overview-logo-nanobot-workspace")).not.toBeInTheDocument();
expect(screen.queryByRole("navigation", { name: "Sidebar navigation" })).not.toBeInTheDocument();
const settingsNav = screen.getByRole("navigation", { name: "Settings sections" });
expect(settingsNav.className).not.toContain("overflow-x-auto");
expect(within(settingsNav).getByRole("button", { name: "Settings: Overview" })).toBeInTheDocument();
expect(within(settingsNav).getByRole("button", { name: "Overview" })).toHaveAttribute(
"aria-current",
"page",
);
expect(within(settingsNav).getByRole("button", { name: "Models" })).toBeInTheDocument();
expect(within(settingsNav).queryByRole("button", { name: "Providers" })).not.toBeInTheDocument();
expect(within(settingsNav).getByRole("button", { name: "Image" })).toBeInTheDocument();
expect(within(settingsNav).queryByRole("button", { name: "Files" })).not.toBeInTheDocument();
expect(within(settingsNav).getByRole("button", { name: "Web" })).toBeInTheDocument();
expect(within(settingsNav).queryByRole("button", { name: "Apps" })).not.toBeInTheDocument();
expect(within(settingsNav).getByRole("button", { name: "Security" })).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Sign out" })).toBeInTheDocument();
fireEvent.pointerDown(within(settingsNav).getByRole("button", { name: "Settings: Overview" }));
fireEvent.click(await screen.findByRole("menuitem", { name: "Appearance" }));
expect(screen.getByText("Brand logos")).toBeInTheDocument();
expect(screen.getByRole("switch", { name: "Brand logos" })).toBeInTheDocument();
expect(
screen.queryByText("Switch between light and dark appearance."),
).not.toBeInTheDocument();
expect(screen.queryByText("Choose the language used by the WebUI.")).not.toBeInTheDocument();
expect(screen.queryByText("Stored only in this browser.")).not.toBeInTheDocument();
expect(within(settingsNav).getByRole("button", { name: "Settings: Appearance" })).toBeInTheDocument();
fireEvent.pointerDown(within(settingsNav).getByRole("button", { name: "Settings: Appearance" }));
fireEvent.click(await screen.findByRole("menuitem", { name: "Models" }));
expect(screen.queryByText("AI")).not.toBeInTheDocument();
expect(screen.getByText("Model presets")).toBeInTheDocument();
expect(screen.queryByText("Model call order")).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "New model preset" }));
expect(screen.queryByRole("dialog", { name: "New model preset" })).not.toBeInTheDocument();
fireEvent.change(screen.getByRole("textbox", { name: "Preset name" }), {
target: { value: "Fast writing" },
});
expect(
screen
.getAllByRole("button", { name: /OpenAI/ })
.some((button) => button.getAttribute("aria-haspopup") === "menu"),
).toBe(true);
await user.click(screen.getByRole("button", { name: "Select model" }));
await user.click(await screen.findByRole("option", { name: /openai\/gpt-4o-mini/ }));
expect(screen.getByRole("button", { name: "Save" })).toBeEnabled();
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
expect(screen.queryByText("Up to date.")).not.toBeInTheDocument();
fireEvent.click(
within(screen.getByTestId("model-call-order-row-primary")).getAllByRole("button")[0],
);
fireEvent.pointerDown(screen.getByRole("button", { name: /Auto/ }));
expect(screen.getAllByTestId("provider-picker-logo-openai").length).toBeGreaterThan(0);
fireEvent.click(screen.getByRole("menuitem", { name: /Auto/ }));
const openModelPicker = async () => {
const modelButtons = screen.getAllByRole("button", { name: /openai\/gpt-4o/ });
await user.click(modelButtons[modelButtons.length - 1]);
};
await openModelPicker();
await user.click(await screen.findByRole("option", { name: /openai\/gpt-4o-mini/ }));
expect(screen.queryByText("Unsaved changes.")).not.toBeInTheDocument();
expect(screen.getByText("Model providers")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Add your own model provider" })).toBeInTheDocument();
expect(screen.queryByText("OpenRouter")).not.toBeInTheDocument();
expect(screen.queryByText("Ant Ling")).not.toBeInTheDocument();
expect(
screen.queryByText(
"Bring your own provider keys. Nanobot reads these values from the current config and only configured providers can be used in model presets.",
),
).not.toBeInTheDocument();
expect(screen.queryByText("azure_openai")).not.toBeInTheDocument();
expect(screen.getByTestId("provider-logo-openai")).toBeInTheDocument();
expect(screen.queryByText(/Product names, logos, and brands/)).not.toBeInTheDocument();
expect(screen.queryByText("Not configured")).not.toBeInTheDocument();
const clickProviderRow = async (label: string) => {
const providerLabel = (await screen.findAllByText(label))
.find((element) => element.className.includes("font-semibold"));
expect(providerLabel).toBeTruthy();
fireEvent.click(providerLabel!);
};
const chooseProvider = async (label: string) => {
fireEvent.pointerDown(
screen.getByRole("button", { name: "Add your own model provider" }),
);
fireEvent.click(await screen.findByRole("menuitem", { name: label }));
};
await clickProviderRow("OpenAI");
fireEvent.click(screen.getByRole("button", { name: "Edit" }));
fireEvent.change(screen.getByPlaceholderText("Leave blank to keep the current key"), {
target: { value: "unsaved-openai-key" },
});
await clickProviderRow("OpenAI");
await chooseProvider("OpenRouter");
await clickProviderRow("OpenRouter");
await clickProviderRow("OpenAI");
expect(screen.getByText("open••••-key")).toBeInTheDocument();
expect(screen.queryByDisplayValue("unsaved-openai-key")).not.toBeInTheDocument();
await clickProviderRow("OpenAI");
await chooseProvider("Ant Ling");
expect(screen.getByDisplayValue("https://api.ant-ling.com/v1")).toBeInTheDocument();
await clickProviderRow("Ant Ling");
await chooseProvider("Atomic Chat");
expect(screen.getByDisplayValue("http://localhost:1337/v1")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Save provider" })).toBeEnabled();
fireEvent.click(within(settingsNav).getByRole("button", { name: "Image" }));
expect(screen.queryByRole("heading", { name: "Image" })).not.toBeInTheDocument();
fireEvent.click(within(screen.getByRole("navigation", { name: "Sidebar navigation" }))
.getByRole("button", { name: "Settings" }));
const nav = await screen.findByRole("navigation", { name: "Settings sections" });
for (const name of ["Overview", "Appearance", "Models", "Capabilities", "System", "Advanced", "About"]) {
expect(within(nav).getByRole("button", { name, exact: true })).toBeInTheDocument();
}
fireEvent.click(within(nav).getByRole("button", { name: "Appearance", exact: true }));
expect(await screen.findByRole("switch", { name: "Brand logos" })).toBeInTheDocument();
fireEvent.click(within(nav).getByRole("button", { name: "Models", exact: true }));
expect(await screen.findByText("Model presets")).toBeInTheDocument();
fireEvent.click(within(nav).getByRole("button", { name: "Capabilities", exact: true }));
expect(screen.getByRole("switch", { name: "Image generation" })).toBeInTheDocument();
expect(screen.getByText("Provider status")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "openai/gpt-5.4-image-2" })).toBeInTheDocument();
expect(screen.getByText("Save directory")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Save" })).toBeDisabled();
expect(
screen.queryByText(
"Expose generate_image in chats when a configured image provider is available.",
),
).not.toBeInTheDocument();
expect(
screen.queryByText("Choose a model supported by the selected image provider."),
).not.toBeInTheDocument();
fireEvent.click(within(settingsNav).getByRole("button", { name: "Web" }));
expect(screen.getByText("Search provider")).toBeInTheDocument();
expect(screen.getByRole("switch", { name: "Jina reader" })).toBeInTheDocument();
expect(screen.getByRole("button", { name: /Brave Search/ })).toBeInTheDocument();
expect(screen.getByTestId("provider-picker-logo-brave")).toBeInTheDocument();
expect(screen.getByText("BSAo••••ew20")).toBeInTheDocument();
expect(
screen.queryByText("Choose the backend used by the web search tool."),
).not.toBeInTheDocument();
expect(
screen.queryByText("Results returned by each web_search call."),
).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Edit" }));
fireEvent.change(screen.getByPlaceholderText("Leave blank to keep the current key"), {
target: { value: "unsaved-brave-key" },
});
fireEvent.pointerDown(screen.getByRole("button", { name: /Brave Search/ }));
fireEvent.click(screen.getByRole("menuitem", { name: "Tavily" }));
fireEvent.pointerDown(screen.getByRole("button", { name: /Tavily/ }));
fireEvent.click(screen.getByRole("menuitem", { name: "Brave Search" }));
expect(screen.getByText("BSAo••••ew20")).toBeInTheDocument();
expect(screen.queryByDisplayValue("unsaved-brave-key")).not.toBeInTheDocument();
fireEvent.click(within(settingsNav).getByRole("button", { name: "System" }));
expect(screen.queryByText("Regional")).not.toBeInTheDocument();
expect(screen.getByText("Timezone")).toBeInTheDocument();
expect(
screen.queryByText("Used for schedules and time-aware replies."),
).not.toBeInTheDocument();
expect(
screen.queryByText("Restart nanobot to apply runtime changes."),
).not.toBeInTheDocument();
expect(screen.queryByText("Bot name")).not.toBeInTheDocument();
expect(screen.queryByText("Bot icon")).not.toBeInTheDocument();
expect(screen.queryByText("Tool hint length")).not.toBeInTheDocument();
expect(screen.queryByText("Heartbeat")).not.toBeInTheDocument();
expect(screen.queryByText("Dream")).not.toBeInTheDocument();
expect(screen.queryByText("Unified session")).not.toBeInTheDocument();
expect(screen.getByText("Default workspace")).toBeInTheDocument();
expect(screen.getByText("UTC")).toBeInTheDocument();
expect(screen.queryByPlaceholderText("Search timezone")).not.toBeInTheDocument();
expect(screen.queryByRole("listbox", { name: "Select timezone" })).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "UTC" })).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Save" })).not.toBeInTheDocument();
expect(
screen.queryByText("Connect SDKs and agents through a local /v1 endpoint."),
).not.toBeInTheDocument();
expect(screen.queryByText("The API uses this local port.")).not.toBeInTheDocument();
fireEvent.click(within(nav).getByRole("button", { name: "About", exact: true }));
expect(await screen.findByRole("button", { name: "Check for updates" })).toBeInTheDocument();
});
it("restores the settings section from the URL hash after a page reload", async () => {
@@ -2779,7 +2421,7 @@ describe("App layout", () => {
render(<App />);
await waitFor(() => expect(connectSpy).toHaveBeenCalled());
expect(await screen.findByRole("heading", { name: "Voice input" })).toBeInTheDocument();
expect(await screen.findByRole("dialog", { name: "Transcription" })).toBeInTheDocument();
expect(window.location.hash).toBe("#/settings?section=voice");
});
@@ -2805,11 +2447,8 @@ describe("App layout", () => {
const systemSection = screen.getByRole("heading", { name: "System" }).closest("section");
expect(systemSection).not.toBeNull();
const system = within(systemSection as HTMLElement);
const timezoneLabel = system.getByText("Timezone");
const restartButton = system.getByRole("button", { name: "Restart nanobot" });
expect(
timezoneLabel.compareDocumentPosition(restartButton) & Node.DOCUMENT_POSITION_FOLLOWING,
).toBeTruthy();
expect(system.getByText("Timezone")).toBeInTheDocument();
expect(within(screen.getByRole("complementary")).getByRole("button", { name: "Restart", exact: true })).toBeInTheDocument();
expect(
system.queryByText("Restart nanobot to apply runtime changes."),
).not.toBeInTheDocument();
@@ -2868,15 +2507,15 @@ describe("App layout", () => {
expect(settingsHighlight).toHaveAttribute("data-active-id", "models");
const voiceButton = within(settingsNav).getByRole("button", {
name: "Voice",
name: "Capabilities",
exact: true,
});
fireEvent.click(voiceButton);
expect(await screen.findByRole("heading", { name: "Voice input" })).toBeInTheDocument();
expect(window.location.hash).toBe("#/settings?section=voice");
expect(await screen.findByRole("switch", { name: "Transcription" })).toBeInTheDocument();
expect(window.location.hash).toBe("#/settings?section=capabilities");
expect(voiceButton).toHaveAttribute("aria-current", "page");
expect(settingsHighlight).toHaveAttribute("data-active-id", "voice");
expect(settingsHighlight).toHaveAttribute("data-active-id", "capabilities");
});
it("transitions between Apps and Skills without replacing the sidebar", async () => {
@@ -2964,7 +2603,7 @@ describe("App layout", () => {
vi.stubGlobal(
"fetch",
vi.fn(async (input: RequestInfo | URL) => {
if (String(input).includes("/api/settings")) {
if (String(input) === "/api/settings") {
return {
ok: true,
status: 200,
@@ -3116,7 +2755,7 @@ describe("App layout", () => {
const newChatButton = within(sidebar).getByRole("button", { name: "New topic" });
const searchButton = within(sidebar).getByRole("button", { name: "Search" });
expect(
newChatButton.compareDocumentPosition(searchButton) &
searchButton.compareDocumentPosition(newChatButton) &
Node.DOCUMENT_POSITION_FOLLOWING,
).toBeTruthy();
@@ -3294,7 +2933,6 @@ describe("App layout", () => {
)).toEqual(["Alpha child"]));
expect(screen.queryByRole("button", { name: "Pane layout" })).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Add pane" })).not.toBeInTheDocument();
expect(screen.queryByRole("separator")).not.toBeInTheDocument();
const sidebar = screen.getByRole("navigation", { name: "Sidebar navigation" });
fireEvent.pointerDown(within(sidebar).getByRole("button", {
@@ -3675,6 +3313,19 @@ describe("App layout", () => {
expect(createChatSpy).not.toHaveBeenCalled();
});
it.each([
["apps", "1", "Digit1", true],
["skills", "2", "Digit2", true],
["automations", "3", "Digit3", true],
["settings", ",", "Comma", false],
])("opens %s using its sidebar shortcut", async (route, key, code, shiftKey) => {
mockFetchRoutes({ "/api/settings": baseSettingsPayload() });
render(<App />);
await waitFor(() => expect(connectSpy).toHaveBeenCalled());
fireEvent.keyDown(window, { key, code, shiftKey, ctrlKey: true });
await waitFor(() => expect(window.location.hash).toContain("#/" + route));
});
it.each([
["Command", { metaKey: true }],
["Control", { ctrlKey: true }],
@@ -3724,34 +3375,35 @@ describe("App layout", () => {
expect(window.location.hash).toBe("#/new");
});
it("exposes the new chat keyboard shortcut in the sidebar title", async () => {
it("exposes the new chat keyboard shortcut in the sidebar tooltip", async () => {
render(<App />);
await waitFor(() => expect(connectSpy).toHaveBeenCalled());
const sidebar = screen.getByRole("navigation", { name: "Sidebar navigation" });
const newChatButton = within(sidebar).getByRole("button", { name: "New topic" });
expect(newChatButton).toHaveAttribute(
"title",
"New topic (Ctrl+Shift+O)",
);
expect(newChatButton).toHaveTextContent("");
await userEvent.setup().hover(newChatButton);
const tooltip = await screen.findByRole("tooltip");
expect(tooltip).toHaveTextContent("New topic");
expect(tooltip.querySelector("kbd")).toHaveTextContent("Ctrl+Shift+O");
expect(newChatButton).toHaveAttribute(
"aria-keyshortcuts",
"Meta+Shift+O Control+Shift+O",
);
});
it("uses macOS shortcut glyphs in the sidebar title", async () => {
it("uses macOS shortcut glyphs in the sidebar tooltip", async () => {
setNavigatorPlatform("MacIntel");
render(<App />);
await waitFor(() => expect(connectSpy).toHaveBeenCalled());
const sidebar = screen.getByRole("navigation", { name: "Sidebar navigation" });
expect(within(sidebar).getByRole("button", { name: "New topic" })).toHaveAttribute(
"title",
"New topic (⌘⇧O)",
);
await userEvent.setup().hover(within(sidebar).getByRole("button", { name: "New topic" }));
const tooltip = await screen.findByRole("tooltip");
expect(tooltip).toHaveTextContent("New topic");
expect(tooltip.querySelector("kbd")).toHaveTextContent("⌘⇧O");
});
it("keeps large sidebars light while search still covers every chat", async () => {
@@ -3817,7 +3469,7 @@ describe("App layout", () => {
fireEvent.click(screen.getByRole("button", { name: "Toggle theme from header" }));
expect(toggleThemeSpy).toHaveBeenCalledTimes(1);
fireEvent.click(screen.getByRole("button", { name: "Collapse sidebar" }));
fireEvent.keyDown(screen.getByRole("separator", { name: "Resize sidebar" }), { key: "Enter" });
const sidebarAside = container.querySelector("aside.lg\\:block") as HTMLElement;
await waitFor(() => expect(sidebarAside.style.width).toBe("56px"));
+1 -1
View File
@@ -90,7 +90,7 @@ describe("ChatList", () => {
const handle = conversation.querySelector("[data-sidebar-session-handle]");
expect(handle).toHaveClass("max-w-20", "shrink-0");
const underline = handle?.querySelector("[data-sidebar-session-handle-underline]");
expect(underline).toHaveClass("border-b-2", "text-foreground");
expect(underline).toHaveClass("border-b-2", "text-sidebar-muted-foreground");
expect(underline?.getAttribute("style"))
.toContain(sessionHandleColor("handle_1234"));
@@ -0,0 +1,23 @@
import { createInstance } from "i18next";
import { describe, expect, it } from "vitest";
import en from "@/i18n/locales/en/common.json";
import zhCN from "@/i18n/locales/zh-CN/common.json";
describe("chat translation resources", () => {
it.each([
["en", en],
["zh-CN", zhCN],
] as const)("resolves sidebar labels from the chat namespace in %s", async (lng, common) => {
const i18n = createInstance();
await i18n.init({ lng, fallbackLng: false, resources: { [lng]: { translation: common } } });
for (const key of [
"chat.groups.all", "chat.groups.projects", "chat.newChat",
"chat.fallbackTitle", "chat.activity.running", "chat.rename", "chat.loading",
]) {
expect(i18n.exists(key), key).toBe(true);
expect(i18n.t(key), key).not.toBe(key);
}
});
});
+4 -8
View File
@@ -159,7 +159,6 @@ const LOCALIZED_SETTINGS_COPY_KEYS = [
"settings.sections.about",
"settings.rows.theme",
"settings.rows.language",
"settings.rows.density",
"settings.rows.activityMode",
"settings.rows.fileEditDisplay",
"settings.rows.codeWrap",
@@ -171,7 +170,6 @@ const LOCALIZED_SETTINGS_COPY_KEYS = [
"settings.rows.contextWindow",
"settings.help.theme",
"settings.help.language",
"settings.help.density",
"settings.help.activityMode",
"settings.help.fileEditDisplay",
"settings.help.codeWrap",
@@ -182,8 +180,6 @@ const LOCALIZED_SETTINGS_COPY_KEYS = [
"settings.help.webuiDefaultAccess",
"settings.values.light",
"settings.values.dark",
"settings.values.comfortable",
"settings.values.compact",
"settings.values.expanded",
"settings.values.enabled",
"settings.values.disabled",
@@ -483,10 +479,10 @@ describe("webui i18n", () => {
const user = userEvent.setup();
render(<LanguageSwitcher />);
await user.click(screen.getByRole("button", { name: "Change language" }));
await user.click(screen.getByRole("combobox", { name: "Change language" }));
for (const { nativeLabel } of supportedLocales) {
expect(screen.getByRole("menuitemradio", { name: nativeLabel })).toBeInTheDocument();
expect(screen.getByRole("option", { name: nativeLabel })).toBeInTheDocument();
}
});
@@ -505,8 +501,8 @@ describe("webui i18n", () => {
).toBeInTheDocument();
expect(document.documentElement.lang).toBe("en");
await user.click(screen.getByRole("button", { name: "Change language" }));
await user.click(screen.getByRole("menuitemradio", { name: /简体中文/i }));
await user.click(screen.getByRole("combobox", { name: "Change language" }));
await user.click(screen.getByRole("option", { name: /简体中文/i }));
await waitFor(() => {
expect(document.documentElement.lang).toBe("zh-CN");
+4 -22
View File
@@ -118,10 +118,8 @@ describe("SettingsView Apps catalog", () => {
"https://accounts.xmind.test/authorize?state=state-123",
));
expect(popup.opener).toBeNull();
expect(screen.queryByRole("textbox", { name: /authorization/i })).not.toBeInTheDocument();
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
expect(screen.getByRole("status")).toHaveTextContent(
"Finish signing in in the browser window.",
"Complete sign-in in the browser window.",
);
expect(screen.getByRole("button", { name: "Connecting Xmind" })).toHaveTextContent(
"Connecting…",
@@ -130,9 +128,6 @@ describe("SettingsView Apps catalog", () => {
expect(await screen.findByRole("button", { name: "Manage Xmind" }, { timeout: 2500 }))
.toHaveTextContent("Manage");
expect(screen.queryByRole("button", { name: "Cancel" })).not.toBeInTheDocument();
expect(screen.queryByText("Xmind connected.")).not.toBeInTheDocument();
expect(screen.queryByText(/some servers did not connect: notion/i)).not.toBeInTheDocument();
expect(popup.close).toHaveBeenCalledTimes(1);
expect(replace).toHaveBeenCalledTimes(1);
expect(fetchMock).toHaveBeenCalledWith(
@@ -169,7 +164,6 @@ describe("SettingsView Apps catalog", () => {
renderSettingsView({ initialSection: "apps" });
fireEvent.click(await screen.findByRole("button", { name: "Ready" }));
expect(await screen.findByText("No tools are ready yet.")).toBeInTheDocument();
expect(screen.queryByRole("heading", { name: "Xmind" })).not.toBeInTheDocument();
fireEvent.click(await screen.findByRole("button", { name: "MCP" }));
@@ -177,7 +171,6 @@ describe("SettingsView Apps catalog", () => {
const row = heading.closest("article");
expect(row).not.toBeNull();
expect(row?.parentElement).toHaveClass("xl:grid-cols-2");
expect(within(row as HTMLElement).queryByText("MCP")).not.toBeInTheDocument();
const failed = within(row as HTMLElement).getByText("Connection failed.");
expect(failed.closest("button")).toBeNull();
expect(failed.closest("p")?.querySelector(".lucide-triangle-alert")).not.toBeNull();
@@ -358,7 +351,6 @@ describe("SettingsView Apps catalog", () => {
fireEvent.click(await screen.findByRole("button", { name: "MCP" }));
fireEvent.click(await screen.findByRole("button", { name: "Custom" }));
expect(screen.queryByText("Authentication")).not.toBeInTheDocument();
fireEvent.change(screen.getByLabelText("Server name"), {
target: { value: "team-mcp" },
});
@@ -372,19 +364,18 @@ describe("SettingsView Apps catalog", () => {
expect(oauth).toHaveAttribute("aria-pressed", "false");
fireEvent.click(within(authentication).getByRole("button", { name: "Headers" }));
fireEvent.change(screen.getByLabelText("Headers JSON"), {
fireEvent.change(screen.getByLabelText("Headers (JSON)"), {
target: { value: '{"Authorization":"Bearer stale"}' },
});
expect(screen.getByText("Add the request headers used by this server.")).toBeInTheDocument();
fireEvent.click(oauth);
expect(oauth).toHaveAttribute("aria-pressed", "true");
expect(screen.queryByLabelText("Headers JSON")).not.toBeInTheDocument();
expect(
screen.getByText("Save the server, then select Connect to sign in."),
).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Save MCP" }));
fireEvent.click(screen.getByRole("button", { name: "Save MCP server" }));
await waitFor(() => {
const saveCall = requestMutationMock.mock.calls.find(
@@ -403,9 +394,6 @@ describe("SettingsView Apps catalog", () => {
});
expect(await screen.findByRole("button", { name: "Connect team-mcp" }))
.toBeInTheDocument();
expect(
screen.queryByText("MCP config reloaded, but some servers did not connect: team-mcp"),
).not.toBeInTheDocument();
});
it("offers a pasted callback flow when the remote WebUI uses HTTP", async () => {
@@ -491,7 +479,6 @@ describe("SettingsView Apps catalog", () => {
expect(screen.getByRole("status")).toHaveTextContent(
"Finish signing in, then paste the callback URL into nanobot.",
);
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
fireEvent.change(callbackInput, { target: { value: callbackUrl } });
fireEvent.click(screen.getByRole("button", { name: "Finish sign-in" }));
@@ -503,7 +490,6 @@ describe("SettingsView Apps catalog", () => {
));
expect(await screen.findByRole("button", { name: "Manage Xmind" }, { timeout: 2500 }))
.toHaveTextContent("Manage");
expect(screen.queryByRole("textbox", { name: "Full callback URL" })).not.toBeInTheDocument();
expect(popup.close).toHaveBeenCalledTimes(1);
});
@@ -566,8 +552,6 @@ describe("SettingsView Apps catalog", () => {
20_000,
));
expect(await screen.findByRole("button", { name: "Connect Xmind" })).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Connecting Xmind" })).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Cancel" })).not.toBeInTheDocument();
expect(popup.close).not.toHaveBeenCalled();
});
@@ -622,7 +606,6 @@ describe("SettingsView Apps catalog", () => {
20_000,
));
expect(await screen.findByRole("button", { name: "Connect Xmind" })).toBeInTheDocument();
expect(screen.queryByText(/Removed MCP preset|reloaded without restarting/)).not.toBeInTheDocument();
});
it("offers a one-click recovery when the OAuth popup is blocked", async () => {
@@ -736,9 +719,8 @@ describe("SettingsView Apps catalog", () => {
await waitFor(() => expect(statusCalls).toBe(1), { timeout: 2000 });
expect(screen.getByRole("status")).toHaveTextContent(
"Finish signing in in the browser window.",
"Complete sign-in in the browser window.",
);
expect(screen.queryByRole("button", { name: "Continue sign-in" })).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "Cancel" })).toBeInTheDocument();
});
+149 -20
View File
@@ -1,12 +1,151 @@
import { fireEvent, screen, waitFor } from "@testing-library/react";
import { act, fireEvent, screen, waitFor, within } from "@testing-library/react";
import { expect, it, vi } from "vitest";
import type { SettingsPayload } from "@/lib/types";
import { DEFAULT_TRANSCRIPTION_SETTINGS } from "@/components/settings/capabilities/TranscriptionSettings";
import { requestMutationMock, jsonResponse, settingsPayload, renderSettingsView, openPopover, installSettingsViewTestHooks } from "@/tests/settings-test-utils";
describe("Settings capabilities", () => {
installSettingsViewTestHooks();
it("opens configuration for disabled features without enabling them", () => {
const payload = settingsPayload();
payload.image_generation.enabled = false;
payload.transcription = { ...DEFAULT_TRANSCRIPTION_SETTINGS, enabled: false };
payload.runtime_config = { "tools.web.enable": false };
renderSettingsView({ initialSection: "capabilities", initialSettings: payload });
for (const name of ["Image generation", "Transcription", "Web access"]) {
expect(screen.getByRole("switch", { name })).not.toBeChecked();
fireEvent.click(within(screen.getByRole("region", { name })).getByRole("button", { name: "Configure" }));
const dialog = screen.getByRole("dialog", { name });
expect(within(dialog).getAllByRole("combobox").length).toBeGreaterThan(0);
fireEvent.click(within(dialog).getByRole("button", { name: "Close", exact: true }));
expect(screen.getByRole("switch", { name })).not.toBeChecked();
}
expect(requestMutationMock).not.toHaveBeenCalled();
});
it("keeps other capability switches stable while saving and queues their edits", async () => {
const payload = { ...settingsPayload(), runtime_config: {
"tools.web.enable": true, "agents.defaults.dream.enabled": true,
} };
const memorySaved = { ...payload, runtime_config: { ...payload.runtime_config, "agents.defaults.dream.enabled": false } };
let finishMemory!: (value: SettingsPayload) => void;
requestMutationMock.mockImplementationOnce(() => new Promise<SettingsPayload>((resolve) => { finishMemory = resolve; }))
.mockResolvedValueOnce({ ...memorySaved, runtime_config: { ...memorySaved.runtime_config, "tools.web.enable": false } });
renderSettingsView({ initialSection: "capabilities", initialSettings: payload });
const memory = screen.getByRole("switch", { name: "Memory consolidation" });
const web = screen.getByRole("switch", { name: "Web access" });
const webStyle = web.className;
fireEvent.click(memory);
await waitFor(() => expect(memory).toBeDisabled());
expect(web).toBeEnabled();
expect(web).toBeChecked();
expect(web.className).toBe(webStyle);
fireEvent.click(web);
expect(web).not.toBeChecked();
await act(async () => finishMemory(memorySaved));
await waitFor(() => expect(requestMutationMock).toHaveBeenLastCalledWith(
"settings.runtime_config.update", { values: { "tools.web.enable": false } }, 20_000,
));
await waitFor(() => expect(web).toBeEnabled());
expect(memory).not.toBeChecked();
expect(web).not.toBeChecked();
});
it("keeps missing image credentials local and does not submit an invalid draft", async () => {
renderSettingsView({ initialSection: "capabilities", initialSettings: settingsPayload() });
fireEvent.click(screen.getByRole("switch", { name: "Image generation" }));
const image = within(screen.getByRole("dialog", { name: "Image generation" }));
expect(image.getByRole("alert")).toHaveTextContent("Configure this provider before enabling image generation.");
await new Promise((resolve) => setTimeout(resolve, 700));
expect(requestMutationMock).not.toHaveBeenCalled();
expect(screen.getAllByRole("alert")).toHaveLength(1);
});
it("keeps a rejected image save attached to the feature when its editor is collapsed", async () => {
const payload = settingsPayload();
payload.image_generation.providers = [{ name: "openrouter", label: "OpenRouter", configured: true }];
requestMutationMock.mockRejectedValue(new Error("image generation provider is not configured"));
renderSettingsView({ initialSection: "capabilities", initialSettings: payload });
fireEvent.click(screen.getByRole("switch", { name: "Image generation" }));
const image = within(screen.getByRole("dialog", { name: "Image generation" }));
await waitFor(() => expect(image.getByRole("alert")).toHaveTextContent("Configure this provider before enabling image generation."));
fireEvent.click(image.getByRole("button", { name: "Close", exact: true }));
expect(screen.getByRole("region", { name: "Image generation" })).toContainElement(screen.getByRole("alert"));
expect(screen.getAllByRole("alert")).toHaveLength(1);
});
it("keeps capabilities together and separates expanding settings from enabling a feature", () => {
const payload = settingsPayload();
payload.image_generation.enabled = true;
payload.image_generation.providers = [{ name: "openrouter", label: "OpenRouter", configured: true }];
payload.runtime_config = { "tools.web.enable": true, "agents.defaults.dream.enabled": true };
renderSettingsView({ initialSection: "capabilities", initialSettings: payload });
expect(screen.getAllByRole("switch")).toHaveLength(4);
expect(screen.getByRole("button", { name: "Capabilities", exact: true })).toHaveAttribute("aria-current", "page");
const editor = screen.getByRole("button", { name: "Image generation", exact: true });
expect(editor).toHaveAttribute("aria-expanded", "false");
fireEvent.click(editor);
expect(editor).toHaveAttribute("aria-expanded", "true");
expect(screen.getByRole("combobox", { name: "OpenRouter", exact: true })).toBeVisible();
fireEvent.click(screen.getByRole("button", { name: "Close", exact: true }));
expect(screen.getByRole("switch", { name: "Image generation" })).toBeChecked();
expect(requestMutationMock).not.toHaveBeenCalled();
});
it("reveals image settings only after enabling and preserves them when disabled", async () => {
const payload = settingsPayload();
payload.image_generation.providers = [{ name: "openrouter", label: "OpenRouter", configured: true }];
requestMutationMock.mockImplementation(async (_method, update) => ({
...payload,
image_generation: { ...payload.image_generation, enabled: update.enabled },
requires_restart: true,
restart_required_sections: ["image"],
}));
renderSettingsView({ initialSection: "image", initialSettings: payload });
fireEvent.click(screen.getByRole("switch", { name: "Image generation" }));
expect(screen.getByRole("combobox", { name: "OpenRouter" })).toBeVisible();
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(
"settings.image_generation.update", expect.objectContaining({ enabled: true }), 20_000,
));
expect(await screen.findByText("Saved. Restart to apply changes.")).toBeVisible();
fireEvent.click(screen.getByRole("button", { name: "Close", exact: true }));
fireEvent.click(screen.getByRole("switch", { name: "Image generation" }));
await waitFor(() => expect(requestMutationMock).toHaveBeenLastCalledWith(
"settings.image_generation.update", expect.objectContaining({
enabled: false, provider: "openrouter", model: payload.image_generation.model,
}), 20_000,
));
expect(await screen.findByText("Saved. Restart to apply changes.")).toBeVisible();
});
it("reveals web search settings when web tools are enabled", async () => {
const payload = { ...settingsPayload(), runtime_config: { "tools.web.enable": false } };
requestMutationMock.mockResolvedValue({
...payload, runtime_config: { "tools.web.enable": true },
});
renderSettingsView({ initialSection: "browser", initialSettings: payload });
fireEvent.click(screen.getByRole("switch", { name: "Web access" }));
expect(screen.getByRole("combobox", { name: "DuckDuckGo" })).toBeVisible();
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(
"settings.runtime_config.update", { values: { "tools.web.enable": true } }, 20_000,
));
});
it("reveals the configured transcription provider and model when enabled", () => {
const payload: SettingsPayload = { ...settingsPayload(), transcription: {
enabled: false, provider: "groq", provider_configured: true, model: "whisper-large-v3",
language: null, max_duration_sec: 120, max_upload_mb: 25,
providers: [{ name: "groq", label: "Groq", configured: true }],
} };
renderSettingsView({ initialSection: "voice", initialSettings: payload });
fireEvent.click(screen.getByRole("switch", { name: "Transcription" }));
expect(screen.getByRole("combobox", { name: "Groq" })).toBeVisible();
expect(screen.getByDisplayValue("whisper-large-v3")).toBeVisible();
});
it("selects image models from provider-specific options", async () => {
const base = settingsPayload();
@@ -14,6 +153,7 @@ describe("Settings capabilities", () => {
...base,
image_generation: {
...base.image_generation,
enabled: true,
providers: [
{
name: "openrouter",
@@ -42,9 +182,8 @@ describe("Settings capabilities", () => {
renderSettingsView({ initialSection: "image", initialSettings: payload });
expect(screen.queryByDisplayValue("openai/gpt-5.4-image-2")).not.toBeInTheDocument();
fireEvent.pointerDown(screen.getByRole("button", { name: "OpenRouter" }));
fireEvent.click(await screen.findByRole("menuitem", { name: "Gemini" }));
fireEvent.keyDown(screen.getByRole("combobox", { name: "OpenRouter" }), { key: "ArrowDown" });
fireEvent.click(await screen.findByRole("option", { name: "Gemini" }));
expect(await screen.findByRole("button", { name: "gemini-2.5-flash-image" })).toBeInTheDocument();
await openPopover(screen.getByRole("button", { name: "gemini-2.5-flash-image" }));
@@ -59,8 +198,8 @@ describe("Settings capabilities", () => {
fireEvent.click(await screen.findByRole("option", { name: "Use “imagen-5-preview”" }));
expect(await screen.findByRole("button", { name: "imagen-5-preview" })).toBeInTheDocument();
fireEvent.pointerDown(screen.getByRole("button", { name: "Gemini" }));
fireEvent.click(await screen.findByRole("menuitem", { name: "Custom" }));
fireEvent.keyDown(screen.getByRole("combobox", { name: "Gemini" }), { key: "ArrowDown" });
fireEvent.click(await screen.findByRole("option", { name: "Custom" }));
expect(screen.getByRole("button", { name: "imagen-5-preview" })).toBeInTheDocument();
await openPopover(screen.getByRole("button", { name: "imagen-5-preview" }));
@@ -96,15 +235,11 @@ describe("Settings capabilities", () => {
renderSettingsView({ initialSection: "advanced" });
expect(await screen.findByText("Web safety")).toBeInTheDocument();
expect(screen.queryByText(/SSRF/i)).not.toBeInTheDocument();
expect(screen.queryByText("Private Service Protection")).not.toBeInTheDocument();
expect(screen.getByText("Default access")).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Restricted" })).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "Default Permission" })).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Full Access" })).toBeInTheDocument();
fireEvent.click(screen.getByRole("switch", { name: "Local services" }));
fireEvent.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() =>
expect(requestMutationMock).toHaveBeenCalledWith(
@@ -149,13 +284,8 @@ describe("Settings capabilities", () => {
renderSettingsView({ initialSection: "browser" });
fireEvent.pointerDown(await screen.findByRole("button", { name: /DuckDuckGo/ }));
fireEvent.click(await screen.findByRole("menuitem", { name: "Keenable" }));
const saveButton = screen
.getAllByRole("button", { name: "Save" })
.find((button) => !(button as HTMLButtonElement).disabled);
if (!saveButton) throw new Error("enabled Save button was not found");
fireEvent.click(saveButton);
fireEvent.keyDown(await screen.findByRole("combobox", { name: /DuckDuckGo/ }), { key: "ArrowDown" });
fireEvent.click(await screen.findByRole("option", { name: "Keenable" }));
await waitFor(() =>
expect(requestMutationMock).toHaveBeenCalledWith(
@@ -191,8 +321,8 @@ describe("Settings capabilities", () => {
renderSettingsView({ initialSection: "advanced" });
expect(await screen.findByText("App safety")).toBeInTheDocument();
expect(screen.queryByText("Web safety")).not.toBeInTheDocument();
expect(screen.getByText("Allow Full Access shell commands to reach services on this Mac.")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Local services" }));
expect(await screen.findByRole("tooltip")).toHaveTextContent("Allow Full Access shell commands to reach services on this Mac.");
});
it("refreshes settings with a fresh token after native engine restart", async () => {
@@ -240,7 +370,6 @@ describe("Settings capabilities", () => {
expect(await screen.findByText("App safety")).toBeInTheDocument();
fireEvent.click(screen.getByRole("switch", { name: "Local services" }));
fireEvent.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(restartEngine).toHaveBeenCalledTimes(1));
await waitFor(() =>
+39 -52
View File
@@ -166,12 +166,10 @@ describe("Settings channels", () => {
renderSettingsView({ initialSection: "channels" });
expect(await screen.findByRole("button", { name: "View Matrix settings" })).toBeInTheDocument();
expect(screen.queryByText("0 running · 1 channels")).not.toBeInTheDocument();
fireEvent.click(await screen.findByRole("button", { name: "View Matrix settings" }));
expect(screen.getAllByText("Failed").length).toBeGreaterThan(0);
expect(screen.queryByText("Enabled, support needs install")).not.toBeInTheDocument();
expect(screen.getByRole("switch", { name: "Matrix channel" })).toHaveAttribute("aria-checked", "false");
expect(screen.getByLabelText("Matrix channel")).toHaveAttribute("aria-checked", "false");
fireEvent.click(screen.getByRole("button", { name: "Install support" }));
fireEvent.click(screen.getByRole("button", { name: "Install and enable" }));
@@ -219,11 +217,10 @@ describe("Settings channels", () => {
renderSettingsView({ initialSection: "channels" });
expect(await screen.findByRole("button", { name: "View Matrix settings" })).toBeInTheDocument();
expect(screen.queryByText("0 running · 1 channels")).not.toBeInTheDocument();
fireEvent.click(await screen.findByRole("button", { name: "View Matrix settings" }));
expect(screen.getAllByText("Failed").length).toBeGreaterThan(0);
expect(screen.getByText(runtimeError)).toBeInTheDocument();
expect(screen.getByRole("switch", { name: "Matrix channel" })).toHaveAttribute(
expect(screen.getByLabelText("Matrix channel")).toHaveAttribute(
"aria-checked",
"false",
);
@@ -268,8 +265,7 @@ describe("Settings channels", () => {
renderSettingsView({ initialSection: "channels" });
expect(await screen.findByRole("button", { name: "View Feishu settings" })).toBeInTheDocument();
expect(screen.queryByText("nanobot channels login feishu")).not.toBeInTheDocument();
fireEvent.click(await screen.findByRole("button", { name: "View Feishu settings" }));
fireEvent.click(await screen.findByRole(
"button",
{ name: "nanobot" },
@@ -327,7 +323,7 @@ describe("Settings channels", () => {
renderSettingsView({ initialSection: "channels" });
expect(await screen.findByRole("button", { name: "View Feishu settings" })).toBeInTheDocument();
fireEvent.click(await screen.findByRole("button", { name: "View Feishu settings" }));
fireEvent.click(await screen.findByRole(
"button",
{ name: "nanobot" },
@@ -416,6 +412,7 @@ describe("Settings channels", () => {
renderSettingsView({ initialSection: "channels" });
fireEvent.click((await screen.findAllByRole("button", { name: /^View .+ settings$/ }))[0]);
fireEvent.click(await screen.findByRole("button", { name: "nanobot" }));
fireEvent.click(await screen.findByRole("switch", { name: "nanobot assistant" }));
@@ -505,6 +502,7 @@ describe("Settings channels", () => {
renderSettingsView({ initialSection: "channels" });
fireEvent.click((await screen.findAllByRole("button", { name: /^View .+ settings$/ }))[0]);
expect(await screen.findByText("Product Helper")).toBeInTheDocument();
expect(screen.getAllByText("Support Bot")).toHaveLength(1);
expect(document.querySelector('img[src="https://example.com/support.png"]')).toBeTruthy();
@@ -518,14 +516,13 @@ describe("Settings channels", () => {
"false",
);
expect(screen.queryByText("cli_def...ault")).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: /Support Bot/ }));
expect(screen.getByRole("button", { name: /Support Bot/ })).toHaveAttribute(
"aria-expanded",
"true",
);
expect(screen.getAllByText("cli_def...ault").length).toBeGreaterThan(0);
expect(screen.getByText("Advanced")).toBeInTheDocument();
expect(screen.getByText("Advanced", { selector: "summary span" })).toBeInTheDocument();
expect(screen.getByText("Topic isolation")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: /Product Helper/ }));
@@ -601,8 +598,8 @@ describe("Settings channels", () => {
renderSettingsView({ initialSection: "channels" });
fireEvent.click((await screen.findAllByRole("button", { name: /^View .+ settings$/ }))[0]);
expect(await screen.findByText("Default worker")).toBeInTheDocument();
expect(screen.queryByRole("switch", { name: "Multi Plugin channel" })).not.toBeInTheDocument();
expect(screen.getByRole("switch", { name: "Default worker instance" })).toHaveAttribute(
"aria-checked",
"true",
@@ -665,6 +662,7 @@ describe("Settings channels", () => {
renderSettingsView({ initialSection: "channels" });
fireEvent.click((await screen.findAllByRole("button", { name: /^View .+ settings$/ }))[0]);
await screen.findByText("Support Bot");
expect(screen.getAllByText("Support Bot")).toHaveLength(1);
expect(screen.getByText("1 assistant connected")).toBeInTheDocument();
@@ -672,10 +670,8 @@ describe("Settings channels", () => {
"aria-checked",
"true",
);
expect(screen.queryByText("cli_sup...port")).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Support Bot" }));
expect(screen.getByText("cli_sup...port")).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Replace assistant" })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Reconnect" }));
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(
"settings.feature.enable",
@@ -735,15 +731,14 @@ describe("Settings channels", () => {
renderSettingsView({ initialSection: "channels" });
fireEvent.click((await screen.findAllByRole("button", { name: /^View .+ settings$/ }))[0]);
await screen.findByText("No assistant connected");
expect(screen.queryByText("0 running · 1 channels")).not.toBeInTheDocument();
expect(screen.getAllByText("Failed").length).toBeGreaterThan(0);
expect(screen.getByText(runtimeError)).toBeInTheDocument();
expect(screen.getByRole("switch", { name: "test assistant" })).toHaveAttribute(
"aria-checked",
"false",
);
expect(screen.queryByText("Connected")).not.toBeInTheDocument();
});
it("shows group behavior fields as options", async () => {
@@ -778,8 +773,8 @@ describe("Settings channels", () => {
renderSettingsView({ initialSection: "channels" });
expect(await screen.findByRole("button", { name: "View Discord settings" })).toBeInTheDocument();
fireEvent.click(screen.getByText("Advanced"));
fireEvent.click(await screen.findByRole("button", { name: "View Discord settings" }));
fireEvent.click(screen.getByText("Advanced", { selector: "summary span" }));
const behavior = screen.getByRole("radiogroup", { name: "Group behavior" });
expect(within(behavior).getByRole("radio", { name: "Mention only" })).toHaveAttribute(
@@ -787,7 +782,6 @@ describe("Settings channels", () => {
"true",
);
expect(within(behavior).getByRole("radio", { name: "All messages" })).toBeInTheDocument();
expect(screen.queryByPlaceholderText("mention")).not.toBeInTheDocument();
fireEvent.click(within(behavior).getByRole("radio", { name: "All messages" }));
@@ -841,22 +835,15 @@ describe("Settings channels", () => {
renderSettingsView({ initialSection: "channels" });
const emailRow = await screen.findByRole("button", { name: "View Email settings" });
expect(screen.getByPlaceholderText("Search channels")).toHaveClass(
"focus-visible:ring-2",
"focus-visible:ring-inset",
"focus-visible:ring-ring/50",
);
expect(screen.queryByRole("switch", { name: "Email channel" })).not.toBeInTheDocument();
expect(emailRow).toBeVisible();
expect(screen.getByRole("switch", { name: "Email channel" })).toBeInTheDocument();
fireEvent.click(emailRow);
expect(screen.getByRole("button", { name: "All channels" })).toBeInTheDocument();
expect(screen.getByRole("switch", { name: "Email channel" })).toBeInTheDocument();
expect(screen.queryByPlaceholderText("Search channels")).not.toBeInTheDocument();
expect(screen.getByRole("dialog")).toHaveFocus();
fireEvent.click(screen.getByRole("button", { name: "All channels" }));
fireEvent.click(screen.getByRole("button", { name: "Close", exact: true }));
expect(screen.getByPlaceholderText("Search channels")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "View Email settings" })).toBeInTheDocument();
});
@@ -929,16 +916,16 @@ describe("Settings channels", () => {
renderSettingsView({ initialSection: "channels" });
expect(await screen.findByRole("button", { name: "View Discord settings" })).toBeInTheDocument();
fireEvent.click(await screen.findByRole("button", { name: "View Discord settings" }));
expect(screen.getByRole("link", { name: "Open Discord setup" })).toHaveAttribute(
"href",
"https://nanobot.wiki/docs/0.2.2/getting-started/chat-apps#discord",
);
expect(screen.getByRole("switch", { name: "Discord channel" })).toBeDisabled();
expect(screen.getByLabelText("Discord channel")).toBeEnabled();
fireEvent.change(screen.getByPlaceholderText("Discord bot token"), {
target: { value: "discord-token" },
});
fireEvent.click(screen.getByText("Advanced"));
fireEvent.click(screen.getByText("Advanced", { selector: "summary span" }));
fireEvent.change(screen.getByLabelText("Allowed channels"), {
target: { value: "123, 456" },
});
@@ -969,7 +956,7 @@ describe("Settings channels", () => {
150_000,
);
expect(await screen.findByText("Checked and enabled.")).toBeInTheDocument();
expect(screen.getByRole("switch", { name: "Discord channel" })).toHaveAttribute(
expect(screen.getByLabelText("Discord channel")).toHaveAttribute(
"aria-checked",
"true",
);
@@ -1033,12 +1020,12 @@ describe("Settings channels", () => {
renderSettingsView({ initialSection: "channels" });
expect(await screen.findByRole("button", { name: "View Discord settings" })).toBeInTheDocument();
expect(screen.getByRole("switch", { name: "Discord channel" })).toHaveAttribute(
fireEvent.click(await screen.findByRole("button", { name: "View Discord settings" }));
expect(screen.getByLabelText("Discord channel")).toHaveAttribute(
"aria-checked",
"false",
);
expect(screen.getByRole("switch", { name: "Discord channel" })).toBeEnabled();
expect(screen.getByLabelText("Discord channel")).toBeEnabled();
expect(screen.getByText("Configured manually")).toBeInTheDocument();
expect(screen.getByText("Saved")).toBeInTheDocument();
const savedSecret = screen.getByPlaceholderText("Saved secret");
@@ -1047,13 +1034,14 @@ describe("Settings channels", () => {
expect(savedSecret.closest("form")).not.toBeNull();
expect(screen.queryByDisplayValue("discord-secret-token")).not.toBeInTheDocument();
fireEvent.click(screen.getByText("Advanced"));
fireEvent.click(screen.getByText("Advanced", { selector: "summary span" }));
expect(screen.getByLabelText("Allowed channels")).toHaveValue("123, 456");
expect(within(screen.getByRole("radiogroup", { name: "Group behavior" })).getByRole(
"radio",
{ name: "All messages" },
)).toHaveAttribute("aria-checked", "true");
fireEvent.click(screen.getByRole("button", { name: "Close", exact: true }));
fireEvent.click(screen.getByRole("switch", { name: "Discord channel" }));
await waitFor(() =>
expect(requestMutationMock).toHaveBeenCalledWith(
@@ -1095,7 +1083,7 @@ describe("Settings channels", () => {
renderSettingsView({ initialSection: "channels" });
expect(await screen.findByRole("button", { name: "View Telegram settings" })).toBeInTheDocument();
fireEvent.click(await screen.findByRole("button", { name: "View Telegram settings" }));
expect(screen.getByRole("link", { name: "Open Telegram setup" })).toHaveAttribute(
"href",
"https://nanobot.wiki/docs/0.2.2/getting-started/chat-apps#telegram",
@@ -1175,8 +1163,8 @@ describe("Settings channels", () => {
const guide = await screen.findByRole("link", { name: guideLabel });
expect(guide).toHaveAttribute("href", expect.stringMatching(/^https:\/\//));
expect(guide.querySelector("span[aria-hidden] img, span[aria-hidden] svg")).not.toBeNull();
fireEvent.click(screen.getByRole("button", { name: "Close", exact: true }));
}
expect(screen.queryByRole("button", { name: "View MoChat settings" })).not.toBeInTheDocument();
});
it("uses choices for channel enum and boolean fields", async () => {
@@ -1212,17 +1200,17 @@ describe("Settings channels", () => {
renderSettingsView({ initialSection: "channels" });
fireEvent.click(await screen.findByRole("button", { name: "View Email settings" }));
const consent = screen.getByRole("radiogroup", { name: "Consent granted" });
const consent = screen.getByRole("radiogroup", { name: "Allow nanobot to read and send email" });
expect(within(consent).getByRole("radio", { name: "Not granted" })).toHaveAttribute(
"aria-checked",
"true",
);
expect(within(consent).getByRole("radio", { name: "Granted" })).toBeInTheDocument();
expect(screen.queryByPlaceholderText("true")).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Close", exact: true }));
fireEvent.click(screen.getByRole("button", { name: "View Feishu settings" }));
fireEvent.click(screen.getByRole("button", { name: "nanobot" }));
fireEvent.click(screen.getByText("Advanced"));
fireEvent.click(screen.getByText("Advanced", { selector: "summary span" }));
const region = screen.getByRole("radiogroup", { name: "Region" });
expect(within(region).getByRole("radio", { name: "Feishu" })).toHaveAttribute(
"aria-checked",
@@ -1230,8 +1218,9 @@ describe("Settings channels", () => {
);
expect(within(region).getByRole("radio", { name: "Lark" })).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Close", exact: true }));
fireEvent.click(screen.getByRole("button", { name: "View Matrix settings" }));
fireEvent.click(screen.getByText("Advanced"));
fireEvent.click(screen.getByText("Advanced", { selector: "summary span" }));
const matrixBehavior = screen.getByRole("radiogroup", { name: "Group behavior" });
expect(within(matrixBehavior).getByRole("radio", { name: "All messages" })).toHaveAttribute(
"aria-checked",
@@ -1239,8 +1228,9 @@ describe("Settings channels", () => {
);
expect(within(matrixBehavior).getByRole("radio", { name: "Allowlist" })).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Close", exact: true }));
fireEvent.click(screen.getByRole("button", { name: "View QQ settings" }));
fireEvent.click(screen.getByText("Advanced"));
fireEvent.click(screen.getByText("Advanced", { selector: "summary span" }));
const format = screen.getByRole("radiogroup", { name: "Message format" });
expect(within(format).getByRole("radio", { name: "Plain text" })).toHaveAttribute(
"aria-checked",
@@ -1279,13 +1269,10 @@ describe("Settings channels", () => {
renderSettingsView({ initialSection: "channels" });
expect(await screen.findByRole("button", { name: "View WebSocket settings" })).toBeInTheDocument();
expect(screen.getAllByText("WebSocket")).toHaveLength(2);
expect(screen.queryByText("Required for WebUI")).not.toBeInTheDocument();
expect(screen.getAllByText("On").length).toBeGreaterThanOrEqual(1);
fireEvent.click(await screen.findByRole("button", { name: "View WebSocket settings" }));
expect(screen.getByRole("heading", { name: "WebSocket", exact: true })).toBeVisible();
expect(screen.getByText("Managed by WebUI")).toBeInTheDocument();
expect(screen.queryByText("Configured manually")).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Disable channel" })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Close", exact: true }));
const websocketSwitch = screen.getByRole("switch", { name: "WebSocket channel" });
expect(websocketSwitch).toBeDisabled();
expect(websocketSwitch).toHaveAttribute("aria-checked", "true");
+39 -104
View File
@@ -109,7 +109,6 @@ describe("Settings models", () => {
expect(within(editor).getByRole("textbox", { name: "Preset name" })).toHaveValue(
"openai",
);
expect(within(editor).queryByText("minimax")).not.toBeInTheDocument();
});
it("edits a legacy case-conflicting preset without treating its own name as a rename", async () => {
@@ -150,7 +149,6 @@ describe("Settings models", () => {
20_000,
);
});
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
});
it("renames an existing preset without losing the editor selection", async () => {
@@ -223,12 +221,8 @@ describe("Settings models", () => {
renderSettingsView({ initialSection: "models" });
expect(screen.queryByText("Edit preset")).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: /Advanced options/ })).not.toBeInTheDocument();
await togglePresetEditor();
const advanced = await screen.findByRole("button", { name: /Advanced options/ });
expect(screen.queryByText("Context window")).not.toBeInTheDocument();
expect(screen.queryByText("Temperature")).not.toBeInTheDocument();
fireEvent.click(advanced);
@@ -245,7 +239,7 @@ describe("Settings models", () => {
expect(reasoningEffort).toHaveValue("provider-native-mode");
});
it("expands the model preset editor directly below the selected row", async () => {
it("opens the preset editor in a dialog and protects the primary preset", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async (input: RequestInfo | URL) => {
@@ -265,23 +259,15 @@ describe("Settings models", () => {
const row = await screen.findByTestId("model-call-order-row-primary");
const trigger = within(row).getAllByRole("button")[0];
expect(screen.queryByTestId("model-preset-editor")).not.toBeInTheDocument();
expect(trigger).toHaveAttribute("aria-expanded", "false");
expect(trigger).toHaveAttribute("aria-haspopup", "dialog");
fireEvent.click(trigger);
const editor = screen.getByTestId("model-preset-editor");
expect(trigger).toHaveAttribute("aria-pressed", "true");
expect(trigger).toHaveAttribute("aria-expanded", "true");
expect(trigger).toHaveAttribute("aria-controls", "model-preset-editor");
expect(row.parentElement).toHaveAttribute("role", "listitem");
expect(row.parentElement?.parentElement).toHaveAttribute("role", "list");
expect(row.nextElementSibling).toBe(editor);
expect(editor).toHaveClass(
"slide-in-from-top-1",
"lg:max-w-6xl",
"rounded-floating",
);
expect(row.closest('[role="listitem"]')).toBeInTheDocument();
expect(row.closest('[role="list"]')).toBeInTheDocument();
expect(screen.getByRole("dialog", { name: "primary" })).toContainElement(editor);
expect(within(editor).getByRole("textbox", { name: "Preset name" })).toHaveValue(
"primary",
);
@@ -289,13 +275,10 @@ describe("Settings models", () => {
expect(deleteButton).toBeDisabled();
expect(deleteButton).toHaveAttribute("aria-describedby", "model-preset-delete-hint");
expect(
within(editor).getByText("Remove this preset from the call order before deleting it."),
within(editor).getByText("Choose another primary preset before deleting this one."),
).toBeInTheDocument();
fireEvent.click(trigger);
expect(trigger).toHaveAttribute("aria-expanded", "false");
expect(screen.queryByTestId("model-preset-editor")).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Close", exact: true }));
});
it("drags model presets to reorder and saves the model call order immediately", async () => {
@@ -344,19 +327,12 @@ describe("Settings models", () => {
fireEvent.change(screen.getByLabelText("Temperature"), {
target: { value: "0.4" },
});
const primaryRow = screen.getByTestId("model-call-order-row-primary");
fireEvent.click(screen.getByRole("button", { name: "Close", exact: true }));
const backupRow = screen.getByTestId("model-call-order-row-backup");
expect(backupRow).toHaveAttribute("draggable", "true");
expect(screen.queryByRole("button", { name: "Move up" })).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Move down" })).not.toBeInTheDocument();
const dataTransfer = {
dropEffect: "move",
effectAllowed: "move",
setData: vi.fn(),
};
fireEvent.dragStart(backupRow, { dataTransfer });
fireEvent.dragEnter(primaryRow, { dataTransfer });
fireEvent.drop(primaryRow, { dataTransfer });
fireEvent.pointerDown(backupRow, { button: 0, clientY: 100, pointerId: 1 });
fireEvent.pointerMove(backupRow, { clientY: 40, pointerId: 1, buttons: 1 });
fireEvent.pointerUp(backupRow, { pointerId: 1 });
fireEvent.click(backupRow);
await waitFor(() => {
expect(requestMutationMock).toHaveBeenCalledWith(
@@ -366,7 +342,8 @@ describe("Settings models", () => {
);
});
expect(screen.queryByRole("button", { name: "Save order" })).not.toBeInTheDocument();
fireEvent.click(within(screen.getByTestId("model-call-order-row-primary")).getByRole("button"));
fireEvent.click(screen.getByRole("button", { name: /Advanced options/ }));
expect(screen.getByLabelText("Temperature")).toHaveValue(0.4);
expect(screen.getByRole("button", { name: "Save" })).toBeEnabled();
});
@@ -418,24 +395,17 @@ describe("Settings models", () => {
const primaryRow = screen.getByTestId("model-call-order-row-primary");
const backupRows = screen.getAllByTestId("model-call-order-row-backup");
const firstBackupRow = backupRows[0];
const secondBackupRow = backupRows[1];
const secondBackupTrigger = within(secondBackupRow).getAllByRole("button")[0];
fireEvent.click(secondBackupTrigger);
expect(screen.getAllByTestId("model-preset-editor")).toHaveLength(1);
expect(secondBackupRow.nextElementSibling).toBe(
screen.getByTestId("model-preset-editor"),
);
fireEvent.click(secondBackupTrigger);
expect(screen.getByRole("dialog", { name: "backup" })).toContainElement(screen.getByTestId("model-preset-editor"));
expect(screen.getByRole("button", { name: "Delete", exact: true })).toBeDisabled();
fireEvent.click(screen.getByRole("button", { name: "Close", exact: true }));
const dataTransfer = {
dropEffect: "move",
effectAllowed: "move",
setData: vi.fn(),
};
fireEvent.dragStart(primaryRow, { dataTransfer });
fireEvent.dragEnter(firstBackupRow, { dataTransfer });
fireEvent.drop(firstBackupRow, { dataTransfer });
fireEvent.pointerDown(primaryRow, { button: 0, clientY: 100, pointerId: 1 });
fireEvent.pointerMove(primaryRow, { clientY: 40, pointerId: 1, buttons: 1 });
fireEvent.pointerUp(primaryRow, { pointerId: 1 });
await waitFor(() =>
expect(
@@ -528,11 +498,7 @@ describe("Settings models", () => {
const codexRow = await screen.findByTestId("model-call-order-row-codex");
expect(codexRow).toHaveTextContent("codex");
expect(codexRow).not.toHaveTextContent("Codex");
expect(codexRow).toHaveTextContent("openai-codex/gpt-5.5");
expect(codexRow).toHaveTextContent("Disabled");
expect(codexRow).toHaveAttribute("draggable", "false");
expect(screen.queryByRole("button", { name: "Add preset" })).not.toBeInTheDocument();
expect(codexRow).toHaveAttribute("tabindex", "-1");
const enableSwitch = within(codexRow).getByRole("switch", { name: "Enable preset" });
expect(enableSwitch).not.toBeChecked();
@@ -546,13 +512,10 @@ describe("Settings models", () => {
);
});
const enabledCodexRow = await screen.findByTestId("model-call-order-row-codex");
expect(enabledCodexRow).not.toHaveTextContent("Disabled");
expect(enabledCodexRow).not.toHaveTextContent(/Fallback/);
expect(enabledCodexRow).toHaveAttribute("draggable", "true");
expect(enabledCodexRow).toHaveAttribute("tabindex", "0");
expect(
within(enabledCodexRow).getByRole("switch", { name: "Disable preset" }),
).toBeChecked();
expect(screen.queryByText("Up to date.")).not.toBeInTheDocument();
});
it("appends a new model preset to the call order immediately", async () => {
@@ -603,11 +566,8 @@ describe("Settings models", () => {
),
);
fireEvent.click(screen.getByRole("button", { name: "New model preset" }));
expect(screen.queryByRole("dialog", { name: "New model preset" })).not.toBeInTheDocument();
expect(screen.getByRole("dialog", { name: "New model preset" })).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Save" })).toBeDisabled();
expect(
screen.queryByText("Complete the preset before saving."),
).not.toBeInTheDocument();
fireEvent.change(screen.getByRole("textbox", { name: "Preset name" }), {
target: { value: "Writer" },
});
@@ -631,11 +591,9 @@ describe("Settings models", () => {
);
});
const writerRow = await screen.findByTestId("model-call-order-row-Writer");
expect(writerRow).not.toHaveTextContent("Disabled");
expect(writerRow).not.toHaveTextContent(/Fallback/);
fireEvent.click(screen.getByRole("button", { name: "Close", exact: true }));
expect(within(writerRow).getByRole("switch", { name: "Disable preset" })).toBeChecked();
expect(screen.getAllByText("Writer").length).toBeGreaterThan(0);
expect(screen.queryByRole("button", { name: "Save order" })).not.toBeInTheDocument();
});
it("shows an inline error when a new preset name already exists", async () => {
@@ -670,7 +628,6 @@ describe("Settings models", () => {
fireEvent.change(nameInput, { target: { value: "Writer" } });
expect(nameInput).toHaveAttribute("aria-invalid", "false");
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
});
it("converts legacy model settings into presets before editing call order", async () => {
@@ -719,11 +676,6 @@ describe("Settings models", () => {
20_000,
),
);
expect(
screen.queryByRole("button", { name: "Convert to presets" }),
).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Save order" })).not.toBeInTheDocument();
expect(screen.queryByText("Default")).not.toBeInTheDocument();
});
it("starts fresh users with an empty preset list instead of legacy conversion", async () => {
@@ -762,10 +714,6 @@ describe("Settings models", () => {
expect(
await screen.findByRole("button", { name: "New model preset" }),
).toBeInTheDocument();
expect(
screen.queryByRole("button", { name: "Convert to presets" }),
).not.toBeInTheDocument();
expect(screen.queryByText("claude-opus-4-5")).not.toBeInTheDocument();
});
it("does not expose the synthetic default configuration as a WebUI preset", async () => {
@@ -832,10 +780,7 @@ describe("Settings models", () => {
renderSettingsView({ initialSection: "models", initialSettings: payload });
expect((await screen.findAllByText("MiniMax-M3")).length).toBeGreaterThan(0);
expect(screen.getAllByText("fast").length).toBeGreaterThan(0);
expect(screen.queryByText("Default")).not.toBeInTheDocument();
expect(screen.queryByText("openai-codex/gpt-5.5")).not.toBeInTheDocument();
});
it("does not expose the synthetic default preset in the overview summary", async () => {
@@ -862,7 +807,6 @@ describe("Settings models", () => {
renderSettingsView({ initialSection: "overview", initialSettings: payload });
expect(await screen.findByText("openai/gpt-4o")).toBeInTheDocument();
expect(screen.queryByText("openai · default")).not.toBeInTheDocument();
expect(screen.getByText("openai")).toBeInTheDocument();
});
@@ -879,9 +823,7 @@ describe("Settings models", () => {
}),
});
expect((await screen.findAllByText("companyProxy/gpt-4o")).length).toBeGreaterThan(0);
expect(screen.getAllByText("Company Proxy").length).toBeGreaterThan(0);
expect(screen.queryByText("Provider setup required")).not.toBeInTheDocument();
});
it("does not treat auto dynamic provider api keys as configured without apiBase", async () => {
@@ -897,11 +839,7 @@ describe("Settings models", () => {
}),
});
expect((await screen.findAllByText("companyProxy/gpt-4o")).length).toBeGreaterThan(0);
expect(screen.getByText("Provider setup required")).toBeInTheDocument();
expect(
screen.queryByText("Configure this provider before saving the preset."),
).not.toBeInTheDocument();
});
it("marks the current model as unconfigured when its provider needs setup", async () => {
@@ -956,7 +894,8 @@ describe("Settings models", () => {
expect(await screen.findByText("Provider setup required")).toBeInTheDocument();
await togglePresetEditor();
expect(screen.getAllByText(/Sign in before saving/).length).toBeGreaterThan(0);
fireEvent.click(screen.getByRole("button", { name: "Sign in required" }));
expect(await screen.findByRole("tooltip")).toHaveTextContent(/Sign in before saving/);
expect(await screen.findByRole("button", { name: "Sign in" })).toBeInTheDocument();
});
@@ -1033,16 +972,10 @@ describe("Settings models", () => {
renderSettingsView({ initialSection: "models" });
await togglePresetEditor();
const deepseekButtons = await screen.findAllByRole("button", { name: /DeepSeek/ });
const providerPicker = deepseekButtons.find(
(button) => button.getAttribute("aria-haspopup") === "menu",
);
if (!providerPicker) throw new Error("provider picker was not found");
fireEvent.pointerDown(providerPicker);
const providerPicker = await screen.findByRole("combobox", { name: /DeepSeek/ });
fireEvent.keyDown(providerPicker, { key: "ArrowDown" });
expect(await screen.findByRole("menuitem", { name: /DeepSeek/ })).toBeInTheDocument();
expect(screen.queryByRole("menuitem", { name: /OpenAI Codex/ })).not.toBeInTheDocument();
expect(screen.queryByRole("menuitem", { name: /GitHub Copilot/ })).not.toBeInTheDocument();
expect(await screen.findByRole("option", { name: /DeepSeek/ })).toBeInTheDocument();
});
it("does not fetch model lists for unsigned OAuth providers", async () => {
@@ -1243,7 +1176,7 @@ describe("Settings models", () => {
await togglePresetEditor();
const modelButtons = await screen.findAllByRole("button", { name: /orcarouter\/auto/i });
await openPopover(modelButtons[modelButtons.length - 1]);
expect(await screen.findByText("Search provider catalog to choose a model.")).toBeInTheDocument();
expect(await screen.findByText("Search this provider’s model catalog.")).toBeInTheDocument();
expect(
fetchMock.mock.calls.some(([input]) =>
String(input).startsWith("/api/settings/provider-models"),
@@ -1418,9 +1351,13 @@ describe("Settings models", () => {
"/api/settings/provider-models?provider=xai_grok",
expect.objectContaining({ headers: { Authorization: "Bearer tok" } }),
);
fireEvent.keyDown(document.activeElement!, { key: "Escape" });
await waitFor(() => expect(modelButtons[modelButtons.length - 1]).toHaveFocus());
fireEvent.click(screen.getByRole("button", { name: "Close", exact: true }));
await waitFor(() => expect(within(screen.getByTestId("model-call-order-row-primary")).getAllByRole("button")[0]).toBeVisible());
});
it("creates presets in the inline editor and can cancel without opening a dialog", async () => {
it("creates presets in a dialog and can cancel", async () => {
const payload = settingsPayload();
payload.providers = [{ name: "openai", label: "OpenAI", configured: true }];
vi.stubGlobal(
@@ -1441,20 +1378,18 @@ describe("Settings models", () => {
renderSettingsView({ initialSection: "models" });
const createButton = await screen.findByRole("button", { name: "New model preset" });
const previousPointerEvents = document.body.style.pointerEvents;
expect(createButton).toHaveClass("w-full");
fireEvent.click(createButton);
expect(screen.queryByRole("dialog", { name: "New model preset" })).not.toBeInTheDocument();
expect(screen.getByTestId("model-preset-editor")).toHaveClass("mt-3", "mb-3");
expect(screen.getByRole("dialog", { name: "New model preset" })).toBeInTheDocument();
expect(screen.getByRole("dialog")).toContainElement(screen.getByTestId("model-preset-editor"));
expect(screen.getByRole("textbox", { name: "Preset name" })).toHaveValue("");
expect(screen.queryByText("Temperature")).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: /Advanced options/ }));
expect(screen.getByText("Temperature")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
expect(screen.queryByDisplayValue("Primary")).not.toBeInTheDocument();
expect(screen.queryByText("Edit preset")).not.toBeInTheDocument();
expect(document.body.style.pointerEvents).not.toBe("none");
await waitFor(() => expect(document.body.style.pointerEvents).toBe(previousPointerEvents));
fireEvent.click(screen.getByRole("button", { name: "New model preset" }));
const nameInput = await screen.findByRole("textbox", { name: "Preset name" });
+8 -26
View File
@@ -1,4 +1,4 @@
import { act, fireEvent, screen, waitFor, within } from "@testing-library/react";
import { act, fireEvent, screen, waitFor } from "@testing-library/react";
import { expect, it, vi } from "vitest";
import type { SettingsPayload } from "@/lib/types";
import { jsonResponse, settingsPayload, renderSettingsView, installSettingsViewTestHooks } from "@/tests/settings-test-utils";
@@ -26,31 +26,17 @@ describe("Settings overview and appearance", () => {
});
});
it("shows the third-party brand notice only with the brand logo preference", () => {
it("shows the brand logo explanation in a tooltip when requested", async () => {
renderSettingsView({
initialSection: "appearance",
initialSettings: settingsPayload(),
showSidebar: true,
});
const brandLogosTitle = screen.getByText("Brand logos");
const brandLogosRow = brandLogosTitle.parentElement?.parentElement;
expect(brandLogosRow).not.toBeNull();
expect(
within(brandLogosRow as HTMLElement).getByText(thirdPartyBrandNotice),
).toBeInTheDocument();
expect(screen.getAllByText(thirdPartyBrandNotice)).toHaveLength(1);
fireEvent.click(screen.getByRole("button", { name: "Brand logos" }));
expect(await screen.findByRole("tooltip")).toHaveTextContent(thirdPartyBrandNotice);
});
it.each(["apps", "channels"] as const)(
"does not repeat the third-party brand notice in %s",
(initialSection) => {
renderSettingsView({ initialSection, initialSettings: settingsPayload() });
expect(screen.queryByText(thirdPartyBrandNotice)).not.toBeInTheDocument();
},
);
it("publishes the latest settings payload to the shell", async () => {
const payload = settingsPayload();
@@ -99,7 +85,6 @@ describe("Settings overview and appearance", () => {
renderSettingsView();
expect(await screen.findByText("No apps available.")).toBeInTheDocument();
expect(screen.queryByText("Loading Apps...")).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Browse MCP tools" }));
expect(await screen.findByText("Add MCP server")).toBeInTheDocument();
});
@@ -110,7 +95,7 @@ describe("Settings overview and appearance", () => {
usage: {
days: [
{
date: "2026-06-03",
date: new Date().toISOString().slice(0, 10),
input_tokens: 1200,
output_tokens: 300,
cache_read_tokens: 500,
@@ -149,11 +134,8 @@ describe("Settings overview and appearance", () => {
renderSettingsView({ initialSection: "overview" });
expect(await screen.findByLabelText("Token activity")).toBeInTheDocument();
expect(screen.getByText("Token Usage")).toBeInTheDocument();
expect(screen.queryByText("Token activity")).not.toBeInTheDocument();
expect(screen.queryByText("Total tokens")).not.toBeInTheDocument();
expect(screen.queryByText("Peak tokens")).not.toBeInTheDocument();
expect(await screen.findByLabelText("1,500 tokens")).toBeInTheDocument();
expect(screen.getByText("Token usage")).toBeInTheDocument();
});
it("coalesces focus refreshes while usage is already loading", async () => {
@@ -242,6 +224,6 @@ describe("Settings overview and appearance", () => {
renderSettingsView({ initialSection: "overview", initialSettings: payload });
expect(screen.getByLabelText("2026-06-03: 1.5K tokens, 2 requests")).toBeInTheDocument();
expect(screen.getByLabelText(/2026-06-03: 1,500 tokens, 2 requests/)).toBeInTheDocument();
});
});
+26 -37
View File
@@ -83,7 +83,7 @@ describe("Settings providers", () => {
expect(
screen.getByText(
"Complete sign-in in your browser. Nanobot usually finishes automatically; if it does not, paste the authorization code below.",
"Complete sign-in in your browser. If nanobot does not connect automatically, paste the authorization code below.",
),
).toBeInTheDocument();
const callbackInput = await screen.findByRole("textbox", {
@@ -170,7 +170,7 @@ describe("Settings providers", () => {
).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Sign in" }));
const dialog = await screen.findByRole("dialog");
const dialog = (await screen.findByText("Select Sign in to open xAI on your computer. After signing in, paste the authorization code shown by xAI below.")).closest('[role="dialog"]') as HTMLElement;
expect(openMock).not.toHaveBeenCalled();
expect(
@@ -178,12 +178,6 @@ describe("Settings providers", () => {
"Select Sign in to open xAI on your computer. After signing in, paste the authorization code shown by xAI below.",
),
).toBeInTheDocument();
expect(
within(dialog).queryByRole("textbox", { name: "xAI sign-in URL" }),
).not.toBeInTheDocument();
expect(
within(dialog).queryByRole("button", { name: "Copy" }),
).not.toBeInTheDocument();
expect(
within(dialog).getByRole("textbox", { name: "Authorization code" }),
).toBeInTheDocument();
@@ -251,7 +245,7 @@ describe("Settings providers", () => {
await chooseProviderToConfigure("OpenAI Codex");
fireEvent.click(screen.getByRole("button", { name: "Sign in" }));
const dialog = await screen.findByRole("dialog");
const dialog = (await screen.findByText("Complete sign-in in your browser. If nanobot does not connect automatically, copy the full localhost callback URL from the address bar and paste it below.")).closest('[role="dialog"]') as HTMLElement;
expect(requestMutationMock).toHaveBeenCalledWith(
"settings.provider.oauth_login",
@@ -261,13 +255,10 @@ describe("Settings providers", () => {
expect(openMock).not.toHaveBeenCalled();
expect(
within(dialog).getByText(
"Complete sign-in in your browser. Nanobot usually finishes automatically; if it does not, copy the full localhost callback URL from the address bar and paste it below.",
"Complete sign-in in your browser. If nanobot does not connect automatically, copy the full localhost callback URL from the address bar and paste it below.",
),
).toBeInTheDocument();
expect(within(dialog).getByText("Waiting for the browser callback…")).toBeInTheDocument();
expect(
within(dialog).queryByText("Paste the callback URL to continue."),
).not.toBeInTheDocument();
expect(
await screen.findByText("Signed in as acct-codex", {}, { timeout: 2500 }),
@@ -354,7 +345,7 @@ describe("Settings providers", () => {
).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Sign in" }));
const dialog = await screen.findByRole("dialog");
const dialog = (await screen.findByText("Open ChatGPT in this browser and finish signing in. When the localhost page fails to load, copy the full URL from the address bar and paste it below.")).closest('[role="dialog"]') as HTMLElement;
expect(openMock).not.toHaveBeenCalled();
expect(
@@ -496,7 +487,7 @@ describe("Settings providers", () => {
);
await waitFor(() => expect(screen.getByRole("button", { name: "Sign in" })).toBeEnabled());
fireEvent.click(screen.getByRole("button", { name: "xAI Grok" }));
fireEvent.click(screen.getByRole("button", { name: "Close", exact: true }));
await chooseProviderToConfigure("OpenAI Codex");
fireEvent.click(screen.getByRole("button", { name: "Advanced options" }));
const codexProxy = screen.getByLabelText("Network proxy");
@@ -595,7 +586,7 @@ describe("Settings providers", () => {
screen.getByRole("button", { name: "Save provider" }),
).toBeEnabled());
fireEvent.click(screen.getByRole("button", { name: "xAI Grok" }));
fireEvent.click(screen.getByRole("button", { name: "Close", exact: true }));
fireEvent.click(screen.getByRole("button", { name: "OpenAI Codex" }));
fireEvent.click(screen.getByRole("switch", { name: "Fast mode" }));
fireEvent.click(screen.getByRole("button", { name: "Save provider" }));
@@ -608,7 +599,7 @@ describe("Settings providers", () => {
screen.getByRole("button", { name: "Save provider" }),
).toBeEnabled());
fireEvent.click(screen.getByRole("button", { name: "OpenAI Codex" }));
fireEvent.click(screen.getByRole("button", { name: "Close", exact: true }));
fireEvent.click(screen.getByRole("button", { name: /^DeepSeek/ }));
expect(screen.getByText(/DeepSeek V4 Flash/)).toBeInTheDocument();
const deepSeekSearch = screen.getByRole("switch", { name: "DeepSeek web search" });
@@ -616,15 +607,15 @@ describe("Settings providers", () => {
fireEvent.click(deepSeekSearch);
fireEvent.click(screen.getByRole("button", { name: "Save provider" }));
await waitFor(() => expect(
screen.queryByRole("switch", { name: "DeepSeek web search" }),
).not.toBeInTheDocument());
screen.getByRole("button", { name: "DeepSeek", exact: true }),
).toBeVisible());
fireEvent.click(screen.getByRole("button", { name: /^OpenAI https:/ }));
fireEvent.click(screen.getByRole("button", { name: "OpenAI", exact: true }));
fireEvent.click(screen.getByRole("switch", { name: "OpenAI web search" }));
fireEvent.click(screen.getByRole("button", { name: "Save provider" }));
await waitFor(() => expect(
screen.queryByRole("switch", { name: "OpenAI web search" }),
).not.toBeInTheDocument());
screen.getByRole("button", { name: "OpenAI", exact: true }),
).toBeVisible());
await waitFor(() => {
const requestUpdates = requestMutationMock.mock.calls
@@ -690,7 +681,7 @@ describe("Settings providers", () => {
renderSettingsView({ initialSection: "models", initialSettings: payload });
fireEvent.click(await screen.findByRole("button", { name: /^OpenAI https:/ }));
fireEvent.click(await screen.findByRole("button", { name: "OpenAI", exact: true }));
const searchSwitch = screen.getByRole("switch", { name: "OpenAI web search" });
expect(searchSwitch).toHaveAttribute("aria-checked", "true");
fireEvent.click(searchSwitch);
@@ -792,10 +783,6 @@ describe("Settings providers", () => {
expect(openRouterOption.querySelector("svg, img")).not.toBeNull();
fireEvent.click(customOption);
expect(
screen.queryByRole("button", { name: "Add your own model provider" }),
).not.toBeInTheDocument();
expect(screen.queryByLabelText("Extra headers")).not.toBeInTheDocument();
fireEvent.change(screen.getByPlaceholderText("My model provider"), {
target: { value: "Company Gateway" },
});
@@ -807,19 +794,21 @@ describe("Settings providers", () => {
});
fireEvent.click(screen.getByRole("button", { name: "Advanced options" }));
fireEvent.change(screen.getByLabelText("Extra headers"), {
target: { value: '{"X-Tenant":"engineering"}' },
});
fireEvent.change(screen.getByLabelText("Extra body"), {
target: { value: '{"service_tier":"priority"}' },
});
fireEvent.change(screen.getByLabelText("Extra query"), {
target: { value: '{"api-version":"2026-01-01"}' },
});
for (const [title, value] of [
["Extra headers", '{"X-Tenant":"engineering"}'],
["Additional body parameters", '{"service_tier":"priority"}'],
["Additional query parameters", '{"api-version":"2026-01-01"}'],
]) {
fireEvent.click(screen.getByRole("button", { name: title }));
const editor = screen.getByRole("dialog", { name: title });
fireEvent.change(within(editor).getByRole("textbox", { name: title }), { target: { value } });
fireEvent.click(within(editor).getByRole("button", { name: "Save", exact: true }));
await waitFor(() => expect(screen.queryByRole("dialog", { name: title })).not.toBeInTheDocument());
}
fireEvent.change(screen.getByLabelText("Network proxy"), {
target: { value: "http://127.0.0.1:7890" },
});
fireEvent.pointerDown(screen.getByRole("button", { name: "Thinking style" }));
fireEvent.pointerDown(screen.getByRole("button", { name: "Reasoning parameter format" }));
fireEvent.click(await screen.findByRole("menuitem", { name: "enable_thinking" }));
fireEvent.click(screen.getByRole("button", { name: "Save provider" }));
@@ -0,0 +1,209 @@
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { RuntimeSettings } from "@/components/settings/system/RuntimeSettings";
import { TimezonePicker } from "@/components/settings/shared/TimezonePicker";
import { DEFAULT_AGENT_SETTINGS_DRAFT } from "@/components/settings/models/ModelsSettings";
import { installSettingsViewTestHooks, jsonResponse, renderSettingsView, requestMutationMock, settingsPayload } from "@/tests/settings-test-utils";
function runtimeSettings() {
return { ...settingsPayload(), runtime_config: {
"agents.defaults.bot_name": "nanobot",
"agents.defaults.bot_icon": "🐈",
"agents.defaults.timezone_mode": "auto",
"agents.defaults.timezone": "UTC",
"agents.defaults.dream.enabled": true,
"gateway.heartbeat.enabled": true,
"tools.exec.timeout": 60,
"tools.exec.allowed_env_keys": ["TERM"],
"tools.exec.allow_patterns": [],
"tools.exec.deny_patterns": [],
"tools.exec.sandbox_ro_binds": [],
"tools.exec.sandbox_rw_binds": [],
"agents.defaults.max_tool_iterations": 200,
"tools.web.proxy": "http://localhost:8080",
} };
}
describe("Runtime configuration settings", () => {
installSettingsViewTestHooks();
it("keeps local service controls available when tool families are disabled", () => {
const payload = runtimeSettings();
renderSettingsView({ initialSection: "advanced", initialSettings: {
...payload, runtime_config: {
...payload.runtime_config, "tools.exec.enable": false,
"tools.web.enable": false, "tools.cli_apps.enable": false,
},
} });
expect(screen.getByRole("switch", { name: "Local services" })).toBeVisible();
});
it("keeps chat permission settings discoverable within the advanced page", () => {
renderSettingsView({ initialSection: "advanced", initialSettings: runtimeSettings() });
expect(screen.getByRole("switch", { name: "Local services" })).toBeInTheDocument();
});
it("places common settings in their feature pages and reserves advanced for low-frequency controls", () => {
renderSettingsView({ initialSection: "runtime", initialSettings: runtimeSettings() });
expect(document.getElementById("runtime-tools.exec.enable")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Advanced" }));
expect(document.getElementById("runtime-tools.exec.sandbox")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Capabilities" }));
fireEvent.click(screen.getByRole("switch", { name: "Image generation" }));
expect(document.getElementById("runtime-tools.image_generation.save_dir")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Close", exact: true }));
expect(screen.getByRole("switch", { name: "Web access" })).toBeInTheDocument();
});
it("offers only the memory consolidation switch and saves only dream.enabled", async () => {
const payload = runtimeSettings();
requestMutationMock.mockResolvedValue({ ...payload, runtime_config: { ...payload.runtime_config, "agents.defaults.dream.enabled": false } });
renderSettingsView({ initialSection: "memory", initialSettings: payload });
const memory = within(screen.getByRole("region", { name: "Memory consolidation" }));
expect(memory.getAllByRole("switch")).toHaveLength(1);
fireEvent.click(screen.getByRole("switch", { name: "Memory consolidation" }));
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith("settings.runtime_config.update", { values: { "agents.defaults.dream.enabled": false } }, 20_000));
await waitFor(() => expect(screen.getByRole("switch", { name: "Memory consolidation" })).not.toBeChecked());
});
it("explains unavailable memory settings instead of rendering a blank page", () => {
renderSettingsView({ initialSection: "memory", initialSettings: settingsPayload() });
expect(screen.getByText("Update the gateway to edit these settings.")).toBeVisible();
});
it.each(["bwrap", "seatbelt", ""])("saves the %s sandbox and reveals its path settings", async (backend) => {
const payload = runtimeSettings();
payload.runtime_config!["tools.exec.sandbox"] = backend ? "" : "seatbelt";
requestMutationMock.mockResolvedValue({ ...payload, runtime_config: { ...payload.runtime_config, "tools.exec.sandbox": backend } });
renderSettingsView({ initialSection: "advanced", initialSettings: payload });
fireEvent.click(screen.getByRole("combobox", { name: "Command sandbox" }));
fireEvent.click(screen.getByRole("option", { name: backend || "None", exact: true }));
if (backend) expect(document.getElementById("runtime-tools.exec.sandbox_ro_binds")).toBeVisible();
else expect(document.getElementById("runtime-tools.exec.sandbox_ro_binds")).not.toBeInTheDocument();
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith("settings.runtime_config.update", { values: { "tools.exec.sandbox": backend } }, 20_000));
});
it("edits lists in a dialog, cancels drafts, and retains failed saves for retry", async () => {
const payload = runtimeSettings();
renderSettingsView({ initialSection: "advanced", initialSettings: payload });
const trigger = screen.getByRole("button", { name: "Allowed environment variables", expanded: false });
expect(screen.queryByRole("textbox", { name: "Allowed environment variables" })).not.toBeInTheDocument();
fireEvent.click(trigger);
let dialog = screen.getByRole("dialog", { name: "Allowed environment variables" });
let editor = within(dialog).getByRole("textbox");
expect(editor).toHaveValue("TERM");
await waitFor(() => expect(editor).toHaveFocus());
fireEvent.change(editor, { target: { value: "discarded" } });
fireEvent.click(within(dialog).getByRole("button", { name: "Cancel" }));
await waitFor(() => expect(trigger).toHaveFocus());
expect(requestMutationMock).not.toHaveBeenCalled();
fireEvent.click(trigger);
dialog = screen.getByRole("dialog", { name: "Allowed environment variables" });
editor = within(dialog).getByRole("textbox");
expect(editor).toHaveValue("TERM");
fireEvent.change(editor, { target: { value: " TERM \n\n COLORTERM " } });
requestMutationMock.mockRejectedValueOnce(new Error("Could not save list"));
fireEvent.click(within(dialog).getByRole("button", { name: "Save", exact: true }));
expect(await within(dialog).findByRole("alert")).toHaveTextContent("Could not save list");
expect(editor).toHaveValue(" TERM \n\n COLORTERM ");
expect(requestMutationMock).toHaveBeenLastCalledWith("settings.runtime_config.update", {
values: { "tools.exec.allowed_env_keys": ["TERM", "COLORTERM"] },
}, 20_000);
requestMutationMock.mockResolvedValueOnce({ ...payload, requires_restart: true,
runtime_config: { ...payload.runtime_config, "tools.exec.allowed_env_keys": ["TERM", "COLORTERM"] } });
fireEvent.click(within(dialog).getByRole("button", { name: "Save", exact: true }));
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
expect(await screen.findByText("Saved. Restart to apply changes.")).toBeVisible();
fireEvent.click(trigger);
expect(within(screen.getByRole("dialog")).getByRole("textbox")).toHaveValue("TERM\nCOLORTERM");
});
it("starts the API with newly saved advanced settings", async () => {
const payload = runtimeSettings();
payload.api = { ...payload.api, host: "192.168.1.7", timeout: 77.5, api_key_hint: "set" };
const action = vi.fn();
render(<RuntimeSettings form={DEFAULT_AGENT_SETTINGS_DRAFT} settings={payload}
requiresRestartPending={false} apiService={{
installed: true, running: false, managed: false, host: "127.0.0.1", port: 8900,
timeout: 120, endpoint: "http://127.0.0.1:8900/v1", command: "nanobot serve",
api_key_hint: "set",
}} apiServiceLoading={false} apiServiceAction={null} apiServiceError={null}
capabilitiesLoading={false} capabilityAction={null} capabilityError={null}
onApiServiceAction={action} onInstallCapability={() => {}} />);
fireEvent.click(screen.getByRole("button", { name: "Start API server" }));
expect(action).toHaveBeenCalledWith("start", {
host: "192.168.1.7", port: 8900, timeout: 77.5, apiKey: undefined,
});
});
it("saves only edited fields using the existing settings footer", async () => {
const payload = runtimeSettings();
requestMutationMock.mockResolvedValue({ ...payload, requires_restart: true,
runtime_config: { ...payload.runtime_config, "tools.exec.timeout": 90 } });
renderSettingsView({ initialSection: "advanced", initialSettings: payload });
fireEvent.change(screen.getByRole("spinbutton", { name: "Command timeout (seconds)" }), { target: { value: "90" } });
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(
"settings.runtime_config.update", { values: { "tools.exec.timeout": 90 } }, 20_000,
));
expect(await screen.findByText("Saved. Restart to apply changes.")).toBeInTheDocument();
});
it("validates numbers and keeps a failed draft editable", async () => {
requestMutationMock.mockRejectedValue(new Error("Could not save settings"));
renderSettingsView({ initialSection: "advanced", initialSettings: runtimeSettings() });
const field = screen.getByRole("spinbutton", { name: "Command timeout (seconds)" });
fireEvent.change(field, { target: { value: "-1" } });
await waitFor(() => expect(field).toHaveFocus());
expect(field).toHaveAttribute("aria-invalid", "true");
expect(requestMutationMock).not.toHaveBeenCalled();
fireEvent.change(field, { target: { value: "17" } });
expect(await screen.findByRole("alert")).toHaveTextContent("Could not save settings");
expect(field).toHaveValue(17);
});
it("preserves drafts when navigating away and supports explicit clearing", async () => {
renderSettingsView({ initialSection: "advanced", initialSettings: runtimeSettings() });
const proxy = screen.getByRole("textbox", { name: "Web proxy" });
fireEvent.change(proxy, { target: { value: "" } });
fireEvent.click(screen.getByRole("button", { name: "System" }));
fireEvent.click(screen.getByRole("button", { name: "Advanced" }));
expect(screen.getByRole("textbox", { name: "Web proxy" })).toHaveValue("");
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(
"settings.runtime_config.update", { values: { "tools.web.proxy": null } }, 20_000,
));
});
it("keeps an existing timezone alias selectable and accepts only listed search results", () => {
const onChange = vi.fn();
render(<TimezonePicker value="Asia/Calcutta" aria-label="Timezone" onChange={onChange} />);
fireEvent.click(screen.getByRole("button", { name: "Timezone" }));
const search = screen.getByRole("combobox", { name: "Search" });
fireEvent.change(search, { target: { value: "invalid timezone" } });
expect(screen.getByRole("status")).toHaveTextContent("No matching timezones.");
fireEvent.keyDown(search, { key: "Enter" });
expect(onChange).not.toHaveBeenCalled();
fireEvent.change(search, { target: { value: "Asia/Calcutta" } });
fireEvent.keyDown(search, { key: "Enter" });
expect(onChange).toHaveBeenCalledWith("Asia/Calcutta");
});
it("selects a manual timezone from search results and persists both fields", async () => {
const payload = runtimeSettings();
vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) =>
jsonResponse(String(input) === "/api/settings" ? payload : {})));
requestMutationMock.mockResolvedValue(payload);
renderSettingsView({ initialSection: "runtime", initialSettings: payload });
fireEvent.click(screen.getByRole("switch", { name: "Use system timezone" }));
const field = screen.getByRole("button", { name: "Timezone", expanded: false });
expect(field).toBeEnabled();
fireEvent.click(field);
fireEvent.change(screen.getByRole("combobox", { name: "Search" }), { target: { value: "Shanghai" } });
fireEvent.click(screen.getByRole("option", { name: /Asia\/Shanghai/ }));
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(
"settings.runtime_config.update", { values: {
"agents.defaults.timezone_mode": "manual", "agents.defaults.timezone": "Asia/Shanghai",
} }, 20_000,
));
});
});
+62 -21
View File
@@ -1,4 +1,4 @@
import { act, fireEvent, screen, waitFor } from "@testing-library/react";
import { act, fireEvent, screen, waitFor, within } from "@testing-library/react";
import { expect, it, vi } from "vitest";
import { installedMcpPresetsFromPayload } from "@/lib/mcp-preset-events";
import { requestMutationMock, jsonResponse, settingsPayload, renderSettingsView, installSettingsViewTestHooks } from "@/tests/settings-test-utils";
@@ -41,6 +41,61 @@ const agentPlugin = {
describe("Settings system domains", () => {
installSettingsViewTestHooks();
it("asks before leaving with pending changes and lets the user restart later", () => {
const leave = vi.fn();
renderSettingsView({ initialSection: "runtime", initialSettings: {
...settingsPayload(), requires_restart: true, restart_required_sections: ["runtime"],
}, onBackToChat: leave });
fireEvent.click(screen.getByRole("button", { name: "Back to chat" }));
const dialog = screen.getByRole("dialog", { name: "Restart before leaving?" });
expect(leave).not.toHaveBeenCalled();
expect(within(dialog).getByText("Your changes are saved. Restart to apply them.")).toBeVisible();
expect(within(dialog).getAllByRole("button").map((button) => button.textContent)).toEqual([
"Restart later", "Restart",
]);
fireEvent.click(within(dialog).getByRole("button", { name: "Restart later" }));
expect(leave).toHaveBeenCalledTimes(1);
expect(requestMutationMock).not.toHaveBeenCalled();
});
it("restarts from the exit prompt", () => {
const restart = vi.fn();
renderSettingsView({ initialSection: "runtime", initialSettings: {
...settingsPayload(), requires_restart: true,
}, onRestart: restart });
fireEvent.click(screen.getByRole("button", { name: "Back to chat" }));
fireEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Restart", exact: true }));
expect(restart).toHaveBeenCalledTimes(1);
});
it("leaves directly when no restart is pending", () => {
const leave = vi.fn();
renderSettingsView({ initialSection: "runtime", initialSettings: settingsPayload(), onBackToChat: leave });
fireEvent.click(screen.getByRole("button", { name: "Back to chat" }));
expect(leave).toHaveBeenCalledTimes(1);
});
it("keeps one restart action and pending notice in the sidebar across settings pages", async () => {
renderSettingsView({
initialSection: "runtime",
initialSettings: {
...settingsPayload(),
requires_restart: true,
restart_required_sections: ["runtime", "image"],
},
});
const sidebar = screen.getByRole("complementary");
const restart = within(sidebar).getByRole("button", { name: "Restart", exact: true });
for (const section of ["Capabilities", "Models", "Advanced", "System"]) {
fireEvent.click(within(sidebar).getByRole("button", { name: section, exact: true }));
await waitFor(() => {
expect(screen.getAllByRole("button", { name: "Restart", exact: true })).toEqual([restart]);
expect(screen.getAllByText("Saved. Restart to apply changes.")).toHaveLength(1);
expect(within(sidebar).getByText("Saved. Restart to apply changes.")).toBeVisible();
});
}
});
it("keeps enabled Agent Plugins out of MCP composer attachments", () => {
const enabled = { ...agentPlugin, enabled: true, available: true, status: "enabled" };
expect(installedMcpPresetsFromPayload({ presets: [enabled], installed_count: 1 })).toEqual([]);
@@ -109,10 +164,6 @@ describe("Settings system domains", () => {
expect(screen.getByRole("heading", { name: "Automations" })).toBeInTheDocument();
expect(await screen.findByText("No automations yet.")).toBeInTheDocument();
expect(screen.queryByText("Settings")).not.toBeInTheDocument();
expect(
screen.queryByPlaceholderText("Search task, message, linked chat, or schedule"),
).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Open a chat" }));
expect(onBackToChat).toHaveBeenCalledTimes(1);
});
@@ -262,7 +313,6 @@ describe("Settings system domains", () => {
renderSettingsView();
expect(screen.queryByRole("heading", { name: "Apps" })).not.toBeInTheDocument();
expect(await screen.findByText("AnyGen")).toBeInTheDocument();
const uninstall = screen.getByRole("button", { name: "Uninstall app" });
@@ -279,7 +329,6 @@ describe("Settings system domains", () => {
fireEvent.click(screen.getByRole("button", { name: "Dismiss" }));
expect(screen.queryByText("Uninstalled CLI for AnyGen.")).not.toBeInTheDocument();
});
it("keeps runtime dependencies out of Apps and explains chat mentions", async () => {
@@ -319,15 +368,9 @@ describe("Settings system domains", () => {
renderSettingsView({ initialSection: "apps" });
expect(await screen.findByText("AnyGen")).toBeInTheDocument();
expect(
screen.queryByText("Add tools to nanobot, then @ them in chat."),
).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "Ready" })).toHaveAttribute("aria-pressed", "false");
expect(screen.getByRole("button", { name: "Apps" })).toHaveAttribute("aria-pressed", "true");
expect(screen.getByRole("button", { name: "MCP" })).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Plugins" })).not.toBeInTheDocument();
expect(screen.queryByText("Api")).not.toBeInTheDocument();
expect(screen.queryByText("0 ready")).not.toBeInTheDocument();
});
it("shows nanobot optional features and enables one", async () => {
@@ -402,10 +445,10 @@ describe("Settings system domains", () => {
renderSettingsView({ initialSection: "channels" });
const matrixRow = await screen.findByRole("button", { name: "View Matrix settings" });
expect(matrixRow).toHaveAttribute("aria-pressed", "true");
expect(screen.getAllByText("Matrix")).toHaveLength(2);
expect(screen.getAllByText("Use nanobot from Matrix rooms.")).toHaveLength(2);
expect(screen.queryByText(/Enabling Nanobot features may install Python packages/)).not.toBeInTheDocument();
expect(matrixRow).toHaveAttribute("aria-haspopup", "dialog");
fireEvent.click(matrixRow);
expect(screen.getByRole("heading", { name: "Matrix", exact: true })).toBeVisible();
fireEvent.click(screen.getByRole("button", { name: "Close", exact: true }));
fireEvent.click(screen.getByRole("switch", { name: "Matrix channel" }));
expect(screen.getByRole("dialog", { name: "Install support for Matrix?" })).toBeInTheDocument();
expect(screen.getByText("nanobot will add what Matrix needs, then turn it on. Continue?")).toBeInTheDocument();
@@ -422,15 +465,14 @@ describe("Settings system domains", () => {
await waitFor(() =>
expect(screen.getByRole("switch", { name: "Matrix channel" })).toHaveAttribute("aria-checked", "true"),
);
expect(screen.queryByText("Enabled channel 'matrix'")).not.toBeInTheDocument();
expect(screen.queryByText("Restart nanobot to apply updated channel support.")).not.toBeInTheDocument();
expect(screen.getAllByText("On").length).toBeGreaterThan(0);
fireEvent.click(screen.getByRole("button", { name: "View Matrix settings" }));
expect(screen.getByLabelText("Homeserver")).toBeInTheDocument();
expect(screen.getByLabelText("User ID")).toBeInTheDocument();
expect(screen.getByLabelText("Device ID")).toBeInTheDocument();
expect(screen.queryByText("channels.matrix.homeserver")).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Close", exact: true }));
fireEvent.click(screen.getByRole("switch", { name: "Matrix channel" }));
await waitFor(() =>
@@ -443,6 +485,5 @@ describe("Settings system domains", () => {
await waitFor(() =>
expect(screen.getByRole("switch", { name: "Matrix channel" })).toHaveAttribute("aria-checked", "false"),
);
expect(screen.queryByText("Disabled channel 'matrix'")).not.toBeInTheDocument();
});
});
+2
View File
@@ -140,6 +140,7 @@ export function renderSettingsView(
onBackToChat?: () => void;
onSettingsChange?: (payload: SettingsPayload) => void;
onNativeEngineRestart?: () => Promise<string>;
onRestart?: () => void;
} = {},
) {
render(
@@ -154,6 +155,7 @@ export function renderSettingsView(
onModelNameChange={() => {}}
onSettingsChange={options.onSettingsChange}
onNativeEngineRestart={options.onNativeEngineRestart}
onRestart={options.onRestart}
/>
</ClientProvider>,
);
+10
View File
@@ -3,6 +3,16 @@ import { beforeAll, beforeEach } from "vitest";
import i18n, { initializeI18n, loadAllLocaleResources } from "@/i18n";
// The DOM test environment does not implement pointer capture used by Radix Select.
if (!HTMLElement.prototype.hasPointerCapture) {
HTMLElement.prototype.hasPointerCapture = () => false;
HTMLElement.prototype.setPointerCapture = () => {};
HTMLElement.prototype.releasePointerCapture = () => {};
}
if (!HTMLElement.prototype.scrollIntoView) {
HTMLElement.prototype.scrollIntoView = () => {};
}
function createTestStorage(): Storage {
const store = new Map<string, string>();
return {
+93
View File
@@ -0,0 +1,93 @@
import { fireEvent, render, screen, within } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { TokenUsageCard } from "@/components/settings/TokenUsageCard";
import { TokenUsageModelTrend } from "@/components/settings/TokenUsageModelTrend";
import type { SettingsPayload } from "@/lib/types";
type Usage = NonNullable<SettingsPayload["usage"]>;
function day(date: string, tokens: number): Usage["days"][number] {
return { date, total_tokens: tokens, input_tokens: tokens, output_tokens: 0,
cache_read_tokens: 0, cache_write_tokens: 0, cache_read_observed_input_tokens: 0,
cache_write_observed_input_tokens: 0, requests: 1 };
}
function usage(days: Usage["days"]): Usage {
return { days, total_tokens: 999999, total_tokens_30d: 999999, total_tokens_365d: 999999,
peak_day_tokens: 999999, current_streak_days: 0, longest_streak_days: 0,
active_days_30d: 0, requests_30d: 0, updated_at: "2026-09-09T00:00:00Z" };
}
describe("Token usage card", () => {
beforeEach(() => {
vi.useFakeTimers({ toFake: ["Date"] });
vi.setSystemTime(new Date("2026-09-09T12:00:00Z"));
});
afterEach(() => vi.useRealTimers());
it("uses one 30-day window for the total, chart and source percentages", () => {
const today = { ...day("2026-09-09", 300), input_tokens: 240, output_tokens: 60, cache_read_tokens: 120, cache_read_observed_input_tokens: 180, estimated_tokens: 100,
sources: { user: day("2026-09-09", 200) } };
render(<TokenUsageCard timeZone="UTC" usage={usage([
day("2026-08-10", 9000), day("2026-08-11", 100), today, day("2026-09-10", 9000),
])} />);
expect(screen.getByLabelText("400 tokens")).toBeInTheDocument();
const bars = within(screen.getByRole("group", { name: "Daily token usage" })).getAllByRole("img");
expect(bars).toHaveLength(30);
expect(bars.filter((bar) => bar.tabIndex === 0)).toEqual([bars[0], bars[29]]);
expect(bars[0]).toHaveAccessibleName(/2026-08-11: 100 tokens, 1 requests/);
expect(bars[29]).toHaveAccessibleName(/Cached input: 120, Cache miss: 60, Cache status unknown: 60, Output: 60/);
const segments = bars[29].firstElementChild?.children;
expect(segments).toHaveLength(4);
expect(segments?.[0]).toHaveStyle({ height: "40%" });
expect(segments?.[1]).toHaveStyle({ height: "20%" });
expect(segments?.[2]).toHaveStyle({ height: "20%" });
expect(segments?.[3]).toHaveStyle({ height: "20%" });
expect(bars[0]).toHaveAccessibleName(/Cache miss: 0, Cache status unknown: 100/);
expect(screen.getAllByText("50%")).toHaveLength(2);
expect(screen.getByText("Unclassified")).toBeInTheDocument();
});
it("shows an empty state for zero usage", () => {
render(<TokenUsageCard usage={usage([])} />);
expect(screen.getByRole("status")).toHaveTextContent("No token usage in the last 30 days.");
});
it("opens details and computes the weighted cache rate from observed input only", () => {
render(<TokenUsageCard usage={usage([
{ ...day("2026-09-08", 100), cache_read_tokens: 80, cache_read_observed_input_tokens: 100 },
{ ...day("2026-09-09", 900), cache_read_tokens: 20, cache_read_observed_input_tokens: 300 },
])} />);
fireEvent.click(screen.getByRole("button", { name: "View details" }));
const details = screen.getByRole("dialog", { name: "Token usage" });
expect(within(details).getByText("25%")).toBeInTheDocument();
expect(within(details).getByTitle("Cache hit rate excludes input with unknown cache status.")).toBeInTheDocument();
});
it("does not misrepresent unavailable usage as zero", () => {
render(<TokenUsageCard />);
expect(screen.getByRole("status")).toHaveTextContent("Usage data is unavailable.");
expect(screen.getByText("—")).toBeInTheDocument();
});
it("keeps the five leading model series and reconciles the rest to the daily total", () => {
const days = Array.from({ length: 30 }, (_, index) => {
const date = new Date("2026-09-09T00:00:00Z");
date.setUTCDate(date.getUTCDate() - 29 + index);
const key = date.toISOString().slice(0, 10);
return { date: key, usage: day(key, index === 29 ? 2200 : 0) };
});
render(<TokenUsageModelTrend days={days}
models={[{ ...day("2026-09-09", 600), provider: "provider", model: "model-5",
cache_read_tokens: 120, cache_read_observed_input_tokens: 150,
reported_tokens: 600, estimated_tokens: 0, successful_requests: 1, failed_requests: 0,
reported_requests: 1, estimated_requests: 0, generation_ms: 0, measured_output_tokens: 0,
ttft_ms: 0, timed_requests: 0, duration_ms: 0 }]}
modelDays={Array.from({ length: 6 }, (_, index) => ({ date: "2026-09-09", provider: "provider", model: `model-${index}`, total_tokens: (index + 1) * 100 }))} />);
const column = screen.getAllByRole("img")[29];
expect(screen.getAllByRole("img").filter((bar) => bar.tabIndex === 0)).toEqual([column]);
expect(column).toHaveAccessibleName(/2026-09-09: 2,200 tokens/);
expect(column).toHaveAccessibleName(/model-5: 600/);
expect(column).toHaveAccessibleName(/Other \/ unattributed: 200/);
const legend = screen.getByLabelText("model-5: Total tokens: 600 · 27.3%, Cache hit rate: 80%");
expect(legend).toHaveAttribute("tabindex", "0");
});
});
+36
View File
@@ -0,0 +1,36 @@
import { act, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, expect, it, vi } from "vitest";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
function Hints() {
return <TooltipProvider>{["First", "Second"].map(label => (
<Tooltip key={label}>
<TooltipTrigger asChild><button>{label}</button></TooltipTrigger>
<TooltipContent>{label} help</TooltipContent>
</Tooltip>
))}</TooltipProvider>;
}
afterEach(() => vi.useRealTimers());
it("waits 500ms for each hover, including after a recently opened hint", () => {
vi.useFakeTimers();
render(<Hints />);
for (const label of ["First", "Second"]) {
const trigger = screen.getByRole("button", { name: label });
fireEvent.pointerMove(trigger, { pointerType: "mouse" });
act(() => vi.advanceTimersByTime(499));
expect(screen.queryByRole("tooltip")).not.toBeInTheDocument();
act(() => vi.advanceTimersByTime(1));
expect(screen.getByRole("tooltip")).toHaveTextContent(`${label} help`);
fireEvent.pointerLeave(trigger, { pointerType: "mouse" });
fireEvent.pointerMove(document.body, { pointerType: "mouse", clientX: 1000, clientY: 1000 });
act(() => vi.advanceTimersByTime(1));
}
});
it("shows keyboard focus help immediately", () => {
render(<Hints />);
fireEvent.focus(screen.getByRole("button", { name: "First" }));
expect(screen.getByRole("tooltip")).toHaveTextContent("First help");
});
+2 -2
View File
@@ -24,7 +24,7 @@ import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
describe("UI shape system", () => {
it("gives standard controls one shared radius", () => {
it("uses pill-shaped inputs and the shared radius for other controls", () => {
render(
<>
<Button>Continue</Button>
@@ -34,7 +34,7 @@ describe("UI shape system", () => {
);
expect(screen.getByRole("button", { name: "Continue" })).toHaveClass("rounded-control");
expect(screen.getByRole("textbox", { name: "Name" })).toHaveClass("rounded-control");
expect(screen.getByRole("textbox", { name: "Name" })).toHaveClass("rounded-full");
expect(screen.getByRole("textbox", { name: "Description" })).toHaveClass(
"rounded-control",
);