test: replace false-green checks with behavioral coverage (#6282)

* test: replace false-green checks with behavioral coverage

* test: complete behavior-focused audit coverage
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-18 03:16:25 +08:00
1 parent c7ab7aa6da
commit 74942bd190
91 files changed
+1891 -1391

No files matched your search

+2
View File
@@ -6,3 +6,5 @@ coverage/
.env
.env.*
!.env.example
test-results/
playwright-report/
+3 -1
View File
@@ -114,10 +114,12 @@ The gateway picks up the new bundle on the next restart.
cd webui
bun run lint
bun run test
bun x playwright install chromium
bun run test:browser
bun run build
```
`lint` runs ESLint; `test` runs Vitest, including channel-owned frontend tests; `build` runs TypeScript checking and produces the production bundle. Keep tests near the changed behavior and exercise settings save/reload in the browser. Browser-only preferences stay in the frontend; persistent configuration and security policy belong to the Python gateway. When changing that boundary, also run the relevant Python tests from [CONTRIBUTING.md](../CONTRIBUTING.md).
`lint` runs ESLint; `test` runs Vitest, including channel-owned frontend tests; `test:browser` uses Chromium with the real components and stylesheet to check tall-dialog reachability and completed-history motion without a gateway; `build` runs TypeScript checking and produces the production bundle. Keep tests near the changed behavior and exercise settings save/reload in the browser. Browser-only preferences stay in the frontend; persistent configuration and security policy belong to the Python gateway. When changing that boundary, also run the relevant Python tests from [CONTRIBUTING.md](../CONTRIBUTING.md).
## Acknowledgements
+5
View File
@@ -0,0 +1,5 @@
<!doctype html>
<html lang="en">
<head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><title>Browser regression fixtures</title></head>
<body><div id="root"></div><script type="module" src="/browser/fixture.tsx"></script></body>
</html>
+54
View File
@@ -0,0 +1,54 @@
import { useState } from "react";
import { createRoot } from "react-dom/client";
import { MessageBubble } from "@/components/MessageBubble";
import { ThreadMessages } from "@/components/thread/ThreadMessages";
import { Dialog, DialogClose, DialogContent, DialogDescription, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { TooltipProvider } from "@/components/ui/tooltip";
import { initializeI18n } from "@/i18n";
import type { UIMessage } from "@/lib/types";
import "../src/globals.css";
const history: UIMessage[] = [
{ id: "question", role: "user", content: "Earlier question", createdAt: 1_700_000_000_000 },
{ id: "answer", role: "assistant", content: "Earlier answer", createdAt: 1_700_000_001_000 },
];
const trace: UIMessage = {
id: "trace", role: "tool", kind: "trace", content: "Earlier tool call", createdAt: 1_700_000_002_000,
};
function HistoryFixture() {
const [open, setOpen] = useState(false);
return <main>
<button onClick={() => setOpen(!open)}>{open ? "Close history" : "Reopen history"}</button>
<section aria-label="Persisted history">
{open && <>
<ThreadMessages messages={history} isStreaming={false} />
<MessageBubble message={trace} />
</>}
</section>
</main>;
}
function TallDialogFixture({ placement }: { placement: "center" | "bottom" }) {
return <main aria-label="Background content" style={{ height: 240, overflowY: "auto" }}>
<div style={{ minHeight: 1800 }}><Dialog>
<DialogTrigger asChild><button>Open tall dialog</button></DialogTrigger>
<DialogContent placement={placement}>
<DialogTitle>Tall dialog</DialogTitle>
<DialogDescription>All controls must remain reachable in a short viewport.</DialogDescription>
{Array.from({ length: 30 }, (_, index) => <label key={index}>
Field {index + 1}<input aria-label={`Field ${index + 1}`} style={{ display: "block", height: 40 }} />
</label>)}
<DialogClose asChild><button>Save tall dialog</button></DialogClose>
</DialogContent>
</Dialog></div>
</main>;
}
const parameters = new URLSearchParams(location.search);
await initializeI18n();
createRoot(document.getElementById("root")!).render(<TooltipProvider>
{parameters.get("case") === "history"
? <HistoryFixture />
: <TallDialogFixture placement={parameters.get("placement") === "bottom" ? "bottom" : "center"} />}
</TooltipProvider>);
+77
View File
@@ -0,0 +1,77 @@
import { expect, test } from "@playwright/test";
for (const placement of ["center", "bottom"]) {
test(`oversized ${placement} dialog keeps both ends keyboard-reachable`, async ({ page }) => {
await page.setViewportSize({ width: 640, height: 320 });
await page.goto(`/browser/fixture.html?placement=${placement}`);
const background = page.getByRole("main", { name: "Background content", includeHidden: true });
const trigger = page.getByRole("button", { name: "Open tall dialog" });
await trigger.click();
const dialog = page.getByRole("dialog", { name: "Tall dialog" });
const close = dialog.getByRole("button", { name: "Close", exact: true });
const lastAction = dialog.getByRole("button", { name: "Save tall dialog" });
await expect(dialog.getByRole("heading", { name: "Tall dialog" })).toBeInViewport({ ratio: 1 });
await expect(close).toBeInViewport({ ratio: 1 });
expect(await dialog.evaluate((element) => element.scrollHeight)).toBeGreaterThan(320);
await expect(page.locator("body")).toHaveAttribute("data-scroll-locked", "1");
await close.focus();
await page.keyboard.press("Shift+Tab");
await expect(lastAction).toBeFocused();
await expect(lastAction).toBeInViewport({ ratio: 1 });
expect(await background.evaluate((element) => element.scrollTop)).toBe(0);
await lastAction.press("Enter");
await expect(dialog).not.toBeVisible();
await expect(trigger).toBeFocused();
await expect(page.locator("body")).not.toHaveAttribute("data-scroll-locked");
await background.hover({ position: { x: 300, y: 180 } });
await page.mouse.wheel(0, 400);
await expect.poll(() => background.evaluate((element) => element.scrollTop)).toBeGreaterThan(0);
});
}
test("reopened completed history is readable without subtree entrance motion", async ({ page }) => {
await page.goto("/browser/fixture.html?case=history");
const history = page.getByRole("region", { name: "Persisted history" });
for (let reopen = 0; reopen < 2; reopen++) {
const observation = await history.evaluateHandle((element) => {
const names = new Set<string>();
let frames = 0;
let frame = 0;
const onAnimation = (event: Event) => names.add((event as AnimationEvent).animationName);
element.addEventListener("animationstart", onAnimation);
const sample = () => {
for (const animation of element.getAnimations({ subtree: true })) {
names.add(animation.constructor.name);
}
frames++;
frame = requestAnimationFrame(sample);
};
frame = requestAnimationFrame(sample);
return {
get frames() { return frames; },
stop() {
cancelAnimationFrame(frame);
element.removeEventListener("animationstart", onAnimation);
return [...names];
},
};
});
try {
await page.getByRole("button", { name: "Reopen history" }).click();
await expect(history.getByText("Earlier question", { exact: true })).toBeVisible();
await expect(history.getByText("Earlier answer", { exact: true })).toBeVisible();
await expect(history.getByRole("button", { name: "Using a tool", exact: true })).toBeVisible();
await expect.poll(() => observation.evaluate((record) => record.frames)).toBeGreaterThan(12);
expect(await observation.evaluate((record) => record.stop())).toEqual([]);
} finally {
await observation.evaluate((record) => record.stop());
await observation.dispose();
}
const disclosure = history.getByRole("button", { name: "Using a tool", exact: true });
await disclosure.click();
await expect(history.getByText("Earlier tool call", { exact: true })).toBeVisible();
await page.getByRole("button", { name: "Close history" }).click();
await expect(history.getByText("Earlier question", { exact: true })).not.toBeVisible();
}
});
+7
View File
@@ -37,6 +37,7 @@
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"@playwright/test": "1.64.1",
"@tailwindcss/typography": "^0.5.19",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.1.0",
@@ -231,6 +232,8 @@
"@pkgjs/parseargs": ["@pkgjs/parseargs@0.11.0", "", {}, "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg=="],
"@playwright/test": ["@playwright/test@1.64.1", "https://registry.npmjs.org/@playwright/test/-/test-1.64.1.tgz", { "dependencies": { "playwright": "1.64.1" }, "bin": { "playwright": "cli.js" } }, "sha512-IaYGml/nSOiZWROfPtuIL7neuu9qDOZ3TNvNljUIrhDMxiGTgPjzj/g9p9RxpS2tSepPDRY+UwAaEeiKtUvIAg=="],
"@radix-ui/number": ["@radix-ui/number@1.1.1", "", {}, "sha512-MkKCwxlXTgz6CFoJx3pCwn07GKp36+aZyu/u2Ln2VrA5DcdyCZkASEDBTd8x5whTQQL5CiYf4prXKLcgQdv29g=="],
"@radix-ui/primitive": ["@radix-ui/primitive@1.1.3", "", {}, "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg=="],
@@ -1109,6 +1112,10 @@
"pirates": ["pirates@4.0.7", "", {}, "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA=="],
"playwright": ["playwright@1.64.1", "https://registry.npmjs.org/playwright/-/playwright-1.64.1.tgz", { "dependencies": { "playwright-core": "1.64.1" }, "bin": { "playwright": "cli.js" } }, "sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA=="],
"playwright-core": ["playwright-core@1.64.1", "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.1.tgz", { "bin": { "playwright-core": "cli.js" } }, "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ=="],
"pngjs": ["pngjs@5.0.0", "", {}, "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw=="],
"points-on-curve": ["points-on-curve@0.2.0", "", {}, "sha512-0mYKnYYe9ZcqMCWhUjItv/oHjvgEsfKvnUTg8sAtnHr3GVy7rGkXCb6d5cSyqrWqL4k81b9CPg3urd+T7aop3A=="],
+1
View File
@@ -21,6 +21,7 @@ export default tseslint.config(
{
files: [
"webui/src/**/*.{ts,tsx}",
"webui/browser/**/*.{ts,tsx}",
"nanobot/channels/*/webui/**/*.{ts,tsx}",
"nanobot/channels/*/tests/webui/**/*.{ts,tsx}",
],
+46
View File
@@ -40,6 +40,7 @@
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"@playwright/test": "1.64.1",
"@tailwindcss/typography": "^0.5.19",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.1.0",
@@ -1227,6 +1228,22 @@
"node": ">=14"
}
},
"node_modules/@playwright/test": {
"version": "1.64.1",
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.64.1.tgz",
"integrity": "sha512-IaYGml/nSOiZWROfPtuIL7neuu9qDOZ3TNvNljUIrhDMxiGTgPjzj/g9p9RxpS2tSepPDRY+UwAaEeiKtUvIAg==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright": "1.64.1"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/@radix-ui/number": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@radix-ui/number/-/number-1.1.1.tgz",
@@ -7284,6 +7301,35 @@
"node": ">= 6"
}
},
"node_modules/playwright": {
"version": "1.64.1",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.64.1.tgz",
"integrity": "sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.64.1"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/playwright-core": {
"version": "1.64.1",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.1.tgz",
"integrity": "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/pngjs": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz",
+3 -1
View File
@@ -11,9 +11,10 @@
"test": "vitest run",
"test:coverage": "vitest run --coverage",
"test:watch": "vitest",
"test:browser": "tsc -p tsconfig.browser.json && playwright test",
"check:imports": "bun ../scripts/check_client_import_boundaries.mjs --project webui",
"test:imports": "bun test ../scripts/check_client_import_boundaries.test.mjs",
"lint": "cd .. && eslint --config webui/eslint.config.js webui/src \"nanobot/channels/*/webui/**/*.{ts,tsx}\" \"nanobot/channels/*/tests/webui/**/*.{ts,tsx}\" \"scripts/check_client_import_boundaries*.mjs\" --max-warnings 0"
"lint": "cd .. && eslint --config webui/eslint.config.js webui/src webui/browser \"nanobot/channels/*/webui/**/*.{ts,tsx}\" \"nanobot/channels/*/tests/webui/**/*.{ts,tsx}\" \"scripts/check_client_import_boundaries*.mjs\" --max-warnings 0"
},
"dependencies": {
"@radix-ui/react-alert-dialog": "^1.1.4",
@@ -48,6 +49,7 @@
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"@playwright/test": "1.64.1",
"@tailwindcss/typography": "^0.5.19",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.1.0",
+27
View File
@@ -0,0 +1,27 @@
import { defineConfig, devices } from "@playwright/test";
const port = Number(process.env.NANOBOT_BROWSER_TEST_PORT ?? 4178);
export default defineConfig({
testDir: "./browser",
fullyParallel: false,
workers: 1,
retries: 0,
timeout: 30_000,
reporter: "list",
outputDir: "test-results/browser",
use: {
...devices["Desktop Chrome"],
baseURL: `http://127.0.0.1:${port}`,
reducedMotion: "no-preference",
launchOptions: {
executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
},
screenshot: "only-on-failure",
},
webServer: {
command: `node node_modules/vite/bin/vite.js --host 127.0.0.1 --port ${port} --strictPort`,
url: `http://127.0.0.1:${port}/browser/fixture.html`,
reuseExistingServer: false,
},
});
+3 -1
View File
@@ -55,7 +55,9 @@ describe("channel logos", () => {
expectFootprint(icon);
expect(fallback).toHaveClass("opacity-0");
expect(image).toHaveClass("opacity-100");
expect(image).not.toHaveClass("invert", "grayscale", "object-cover");
for (const className of ["invert", "grayscale", "object-cover"]) {
expect(image).not.toHaveClass(className);
}
expect(icon).toHaveClass(presentation.logoLayout === "tile" ? "bg-transparent" : "bg-white");
expect(image).toHaveClass(...(presentation.logoLayout === "tile" ? ["h-8", "w-8"] : ["h-6", "w-6"]));
});
+20 -5
View File
@@ -1,7 +1,9 @@
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { describe, expect, it } from "vitest";
import postcss from "postcss";
import tailwindcss from "tailwindcss";
import loadConfig from "tailwindcss/loadConfig";
import { describe, expect, it, vi } from "vitest";
import {
channelUiContribution,
@@ -34,9 +36,22 @@ describe("channel UI contributions", () => {
expect(channelUiOwner("wechat")).toBe("weixin");
});
it("includes channel-owned UI in Tailwind's production scan", () => {
const source = readFileSync(resolve(process.cwd(), "tailwind.config.js"), "utf8");
it("includes channel-owned UI in Tailwind's production scan", async () => {
vi.stubEnv("NODE_ENV", "production");
try {
const config = loadConfig(resolve(process.cwd(), "tailwind.config.js"));
const result = await postcss([tailwindcss(config)]).process("@tailwind utilities;", { from: undefined });
expect(source).toContain("../nanobot/channels/*/webui/**/*.{ts,tsx}");
// Linear's connecting indicator uses a channel-only arbitrary color.
let backgroundColor: string | undefined;
result.root.walkRules(".bg-\\[\\#5E6AD2\\]", (rule) => {
rule.walkDecls("background-color", (declaration) => {
backgroundColor = declaration.value;
});
});
expect(backgroundColor?.trim()).toBeTruthy();
} finally {
vi.unstubAllEnvs();
}
});
});
+4 -2
View File
@@ -17,10 +17,12 @@ describe("form control focus styles", () => {
"focus-visible:ring-inset",
"focus-visible:ring-ring/50",
);
expect(element).not.toHaveClass(
for (const className of [
"ring-offset-background",
"focus-visible:ring-ring",
"focus-visible:ring-offset-2",
);
]) {
expect(element).not.toHaveClass(className);
}
});
});
+22 -48
View File
@@ -1,6 +1,6 @@
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { runInNewContext } from "node:vm";
import { Window } from "happy-dom";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
@@ -339,43 +339,24 @@ const ACCIDENTALLY_SPANISH_SETTINGS_KEYS = [
"settings.oauth.signInHelp",
];
const INDEX_HTML = readFileSync(resolve(process.cwd(), "index.html"), "utf8");
const PREBOOT_SCRIPT = INDEX_HTML.match(
/<script>\s*(\(function \(\) \{\s*var localeKey = "nanobot\.locale";[\s\S]*?\}\)\(\);)\s*<\/script>/,
)?.[1];
const BOOT_COPY_MARKUP = '<span data-boot-copy>Loading nanobot…</span>';
function runPrebootLocale(storedLocale: string) {
if (!PREBOOT_SCRIPT) throw new Error("Could not find the preboot locale script in index.html");
const documentElement = { lang: "" };
const meta = {
content: "",
setAttribute(name: string, value: string) {
if (name === "content") this.content = value;
},
};
const boot = { textContent: "" };
runInNewContext(PREBOOT_SCRIPT, {
localStorage: {
getItem: (key: string) => key === LOCALE_STORAGE_KEY ? storedLocale : null,
},
navigator: { languages: [], language: "en" },
document: {
documentElement,
querySelector: (selector: string) => {
if (selector === '[data-i18n-meta="description"]') return meta;
if (selector === "[data-boot-copy]") return boot;
return null;
},
},
async function runPrebootLocale(storedLocale: string) {
const preboot = new Window({
url: "http://preboot.test",
settings: { disableJavaScriptFileLoading: true, disableCSSFileLoading: true },
});
return {
lang: documentElement.lang,
boot: boot.textContent,
description: meta.content,
};
try {
preboot.localStorage.setItem(LOCALE_STORAGE_KEY, storedLocale);
// Parse the shipped document and execute inline scripts in parser order.
// External/module loading stays disabled: React must not repair the splash.
preboot.document.write(INDEX_HTML);
return {
lang: preboot.document.documentElement.lang,
boot: preboot.document.querySelector('[role="status"]')?.textContent.trim(),
description: preboot.document.querySelector('meta[name="description"]')?.getAttribute("content"),
};
} finally {
await preboot.happyDOM.close();
}
}
function isRecord(value: unknown): value is Record<string, unknown> {
@@ -406,13 +387,6 @@ function interpolationKeys(value: unknown): string[] {
}
describe("webui i18n", () => {
it("runs preboot localization after the splash copy exists", () => {
expect(INDEX_HTML.indexOf(BOOT_COPY_MARKUP)).toBeGreaterThan(-1);
expect(INDEX_HTML.indexOf(PREBOOT_SCRIPT ?? "")).toBeGreaterThan(
INDEX_HTML.indexOf(BOOT_COPY_MARKUP),
);
});
it.each(supportedLocales)("localizes compaction states in $code", async ({ code }) => {
await setAppLanguage(code);
const copy = resources[code].common.thread.compaction;
@@ -437,9 +411,9 @@ describe("webui i18n", () => {
}
});
it("keeps preboot copy aligned with every registered locale", () => {
it("localizes the parsed splash in document order for every registered locale", async () => {
for (const { code } of supportedLocales) {
const result = runPrebootLocale(code);
const result = await runPrebootLocale(code);
const expected = resources[code].common.app;
expect({ code, ...result }).toEqual({
@@ -451,11 +425,11 @@ describe("webui i18n", () => {
}
});
it("normalizes Portuguese locales before the app bundle loads", () => {
it("normalizes Portuguese locales before the app bundle loads", async () => {
const expected = resources["pt-BR"].common.app;
for (const locale of ["pt", "pt-PT"]) {
expect(runPrebootLocale(locale)).toEqual({
expect(await runPrebootLocale(locale)).toEqual({
lang: "pt-BR",
boot: expected.loading.boot,
description: expected.meta.description,
+3 -1
View File
@@ -97,7 +97,9 @@ describe("file quick look", () => {
const quickLook = screen.getByTestId("file-image-quick-look");
expect(quickLook.textContent).toBe("");
expect(quickLook).toHaveClass("w-max");
expect(quickLook).not.toHaveClass("h-36", "w-full");
for (const className of ["h-36", "w-full"]) {
expect(quickLook).not.toHaveClass(className);
}
expect(quickLook.querySelector("img")).toHaveClass("rounded-mark", "object-contain");
expect(quickLook.querySelector("img")).toHaveClass("h-auto", "w-auto", "max-h-36");
expect(screen.getByRole("tooltip")).toHaveTextContent("File preview");
+3 -1
View File
@@ -12,7 +12,9 @@ describe("Linear workspace logo", () => {
expect(image).toHaveAttribute("height", "28");
expect(image).toHaveAttribute("referrerpolicy", "no-referrer");
expect(image.parentElement).toHaveClass("h-7", "w-7");
expect(image.parentElement).not.toHaveClass("overflow-hidden", "bg-muted");
for (const className of ["overflow-hidden", "bg-muted"]) {
expect(image.parentElement).not.toHaveClass(className);
}
expect(image).toHaveClass("object-contain");
expect(view.container.querySelector("svg")).toBeNull();
fireEvent.error(image);
@@ -1,3 +1,4 @@
import { waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const render = vi.fn();
@@ -12,28 +13,28 @@ vi.mock("@/App", () => ({
}));
describe("service worker registration when unsupported", () => {
const register = vi.fn(() => Promise.resolve());
beforeEach(() => {
vi.resetModules();
createRoot.mockClear();
render.mockClear();
register.mockClear();
document.body.innerHTML = '<div id="root"></div>';
// happy-dom's Navigator has no serviceWorker member, so this file runs
// without defining one — the entry's `"serviceWorker" in navigator` guard
// must keep registration from being attempted.
Reflect.deleteProperty(navigator, "serviceWorker");
});
afterEach(() => {
document.body.innerHTML = "";
delete (navigator as Navigator & { serviceWorker?: unknown }).serviceWorker;
Reflect.deleteProperty(navigator, "serviceWorker");
});
it("does not attempt registration when the service worker API is missing", async () => {
it("renders the app when the service worker API is missing", async () => {
expect("serviceWorker" in navigator).toBe(false);
await import("../main");
window.dispatchEvent(new Event("load"));
expect(register).not.toHaveBeenCalled();
await waitFor(() => {
expect(createRoot).toHaveBeenCalledWith(document.getElementById("root"));
expect(render).toHaveBeenCalledTimes(1);
});
});
});
-26
View File
@@ -142,30 +142,4 @@ describe("MarkdownText", () => {
"true",
);
});
it("defers syntax highlighting until the final render", async () => {
rendererSpy.mockClear();
const largeCode = `\`\`\`ts\n${"const value = 1;\n".repeat(1_100)}\`\`\``;
const { rerender } = render(
<MarkdownText streaming>{largeCode}</MarkdownText>,
);
await act(async () => {
await Promise.resolve();
await Promise.resolve();
});
expect(screen.getByTestId("markdown-renderer")).toHaveAttribute(
"data-highlight-code",
"false",
);
rerender(<MarkdownText>{largeCode}</MarkdownText>);
expect(screen.getByTestId("markdown-renderer")).toHaveAttribute(
"data-highlight-code",
"true",
);
});
});
+10 -4
View File
@@ -274,31 +274,37 @@ describe("MessageBubble", () => {
expect(bubble).toHaveClass("bg-secondary/70");
});
it("does not replay an entrance animation when persisted messages mount", () => {
it("renders completed message branches with static wrapper classes", async () => {
const messages: UIMessage[] = [
{
id: "u-persisted",
role: "user",
content: "Earlier question",
createdAt: Date.now(),
createdAt: 1_700_000_000_000,
},
{
id: "a-persisted",
role: "assistant",
content: "Earlier answer",
createdAt: Date.now(),
createdAt: 1_700_000_001_000,
},
{
id: "t-persisted",
role: "tool",
kind: "trace",
content: "Earlier tool call",
createdAt: Date.now(),
createdAt: 1_700_000_002_000,
},
];
for (const message of messages) {
const { container, unmount } = render(<MessageBubble message={message} />);
if (message.kind === "trace") {
const disclosure = screen.getByRole("button", { expanded: false });
fireEvent.click(disclosure);
expect(disclosure).toHaveAttribute("aria-expanded", "true");
}
expect(await screen.findByText(message.content)).toBeVisible();
for (const className of ["animate-in", "fade-in-0", "slide-in-from-bottom-1"]) {
expect(container.firstElementChild).not.toHaveClass(className);
}
+6 -2
View File
@@ -40,7 +40,9 @@ describe("settings provider icons", () => {
expect(icon).not.toHaveAttribute("style");
expect(fallback).toHaveClass("opacity-0");
expect(image).toHaveClass("opacity-100");
expect(image).not.toHaveClass("invert", "grayscale");
for (const className of ["invert", "grayscale"]) {
expect(image).not.toHaveClass(className);
}
},
);
@@ -60,7 +62,9 @@ describe("settings provider icons", () => {
fireEvent.load(image);
expect(image).toHaveClass("opacity-100");
expect(icon).toHaveClass("bg-transparent");
expect(icon).not.toHaveClass("bg-white", "bg-muted");
for (const className of ["bg-white", "bg-muted"]) {
expect(icon).not.toHaveClass(className);
}
fireEvent.error(image);
expect(image).toHaveAttribute("src", providerBrand(provider)!.logoUrls[1]);
@@ -2,6 +2,8 @@ import { fireEvent, render, screen, waitFor, within } from "@testing-library/rea
import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest";
import { RuntimeSettings } from "@/components/settings/system/RuntimeSettings";
import { RUNTIME_CONFIG_FIELDS, RUNTIME_CONFIG_GROUPS } from "@/components/settings/system/runtime-config-fields";
import runtimeConfigKeys from "../../../tests/webui/fixtures/runtime-config-keys.json";
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";
@@ -29,6 +31,15 @@ function runtimeSettings() {
describe("Runtime configuration settings", () => {
installSettingsViewTestHooks();
it("covers the shared runtime wire-key catalogue without duplicate editors", () => {
const paths = RUNTIME_CONFIG_FIELDS.map((field) => field.path);
expect(new Set(paths).size).toBe(paths.length);
// This key gates the CLI group rather than having a separate editor.
const visibilityOnly = "tools.cli_apps.enable";
expect(RUNTIME_CONFIG_GROUPS.find((group) => group.id === "cli")?.enabledBy).toBe(visibilityOnly);
expect([...paths, visibilityOnly].sort()).toEqual([...runtimeConfigKeys].sort());
});
it("keeps local service controls available when tool families are disabled", () => {
const payload = runtimeSettings();
renderSettingsView({ initialSection: "advanced", initialSettings: {
+6 -2
View File
@@ -203,7 +203,9 @@ describe("Settings system domains", () => {
expect(title.parentElement).toHaveClass("settings-section-heading");
expect(title.nextElementSibling).toHaveTextContent("1");
expect(title.nextElementSibling).toHaveClass("tabular-nums");
expect(title.nextElementSibling).not.toHaveClass("rounded-full", "bg-muted");
for (const className of ["rounded-full", "bg-muted"]) {
expect(title.nextElementSibling).not.toHaveClass(className);
}
fireEvent.click(screen.getByRole("button", { name: "MCP", exact: true }));
const mcpTitle = screen.getByRole("heading", { name: "MCP tools" });
@@ -267,7 +269,9 @@ describe("Settings system domains", () => {
for (const name of ["Custom", "Built-in", "Other"]) {
const title = screen.getByRole("heading", { name, exact: true });
expect(title).toHaveClass("text-[13px]", "font-medium", "leading-5");
expect(title).not.toHaveClass("uppercase", "tracking-[0.08em]");
for (const className of ["uppercase", "tracking-[0.08em]"]) {
expect(title).not.toHaveClass(className);
}
expect(title.nextElementSibling).toHaveTextContent("1");
expect(title.nextElementSibling).toHaveClass("leading-5");
}
+10 -12
View File
@@ -139,10 +139,10 @@ function indexHtml(assetPaths: string[]): Response {
return new Response(`<!doctype html><html><head>${refs}</head></html>`);
}
function fetchEvent(url: string) {
function fetchEvent(url: string, init?: RequestInit) {
const respondWith = vi.fn();
const event = {
request: new Request(url, { method: "GET" }),
request: new Request(url, init),
respondWith,
};
return { event, respondWith };
@@ -223,8 +223,8 @@ describe("service worker", () => {
];
for (const path of paths) {
const { respondWith } = fetchEvent(`${ORIGIN}${path}`);
await sw.fire("fetch", { request: new Request(`${ORIGIN}${path}`) });
const { event, respondWith } = fetchEvent(`${ORIGIN}${path}`);
await sw.fire("fetch", event);
expect(respondWith, path).not.toHaveBeenCalled();
}
expect(sw.fetchMock).not.toHaveBeenCalled();
@@ -233,16 +233,14 @@ describe("service worker", () => {
it("does not intercept non-GET or unrelated cross-origin requests", async () => {
const sw = loadSw();
const { respondWith: post } = fetchEvent(`${ORIGIN}/api/v1/models`);
await sw.fire("fetch", {
request: new Request(`${ORIGIN}/api/v1/models`, { method: "POST" }),
});
const { event: postEvent, respondWith: post } = fetchEvent(
`${ORIGIN}/assets/app.js`, { method: "POST" },
);
await sw.fire("fetch", postEvent);
expect(post).not.toHaveBeenCalled();
const { respondWith: cross } = fetchEvent("https://other.test/assets/app.js");
await sw.fire("fetch", {
request: new Request("https://other.test/assets/app.js"),
});
const { event: crossEvent, respondWith: cross } = fetchEvent("https://other.test/assets/app.js");
await sw.fire("fetch", crossEvent);
expect(cross).not.toHaveBeenCalled();
expect(sw.fetchMock).not.toHaveBeenCalled();
});
+3 -1
View File
@@ -816,7 +816,9 @@ describe("ThreadComposer", () => {
expect(modelPill).not.toHaveClass("font-semibold");
const providerLogo = screen.getByTestId("composer-model-logo-openai");
expect(providerLogo).toBeInTheDocument();
expect(providerLogo).not.toHaveClass("border", "bg-background");
for (const className of ["border", "bg-background"]) {
expect(providerLogo).not.toHaveClass(className);
}
const input = screen.getByPlaceholderText("Type your message...");
expect(input.className).toContain("min-h-[50px]");
expect(input.className).toContain("text-[16px]");
+6 -2
View File
@@ -731,7 +731,9 @@ describe("ThreadMessages", () => {
const rows = Array.from(container.firstElementChild?.children ?? []);
expect(rows).toHaveLength(2);
expect(rows[0]).not.toHaveClass("mt-2", "mt-4", "mt-5");
for (const className of ["mt-2", "mt-4", "mt-5"]) {
expect(rows[0]).not.toHaveClass(className);
}
expect(rows[1]).not.toHaveClass("mt-4");
const answerRow = screen.getByText("final answer")
.closest<HTMLElement>("[data-thread-display-unit]")!;
@@ -772,7 +774,9 @@ describe("ThreadMessages", () => {
expect(disclosure.compareDocumentPosition(timestamp) & Node.DOCUMENT_POSITION_FOLLOWING)
.toBeTruthy();
expect(menu).toHaveClass("w-max", "max-w-64", "bg-popover", "rounded-floating", "overflow-y-auto");
expect(menu).not.toHaveClass("min-w-[8.5rem]", "bg-popover/95", "rounded-xl");
for (const className of ["min-w-[8.5rem]", "bg-popover/95", "rounded-xl"]) {
expect(menu).not.toHaveClass(className);
}
const menuButtons = Array.from(menu.querySelectorAll("button"));
expect(menuButtons.length).toBeGreaterThan(1);
for (const button of menuButtons) {
+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.each(["center", "bottom"] as const)("keeps an oversized %s dialog scrollable from its start", (placement) => {
it.each(["center", "bottom"] as const)("declares a scroll owner inside the %s modal boundary", (placement) => {
render(<Dialog open><DialogContent placement={placement}>
<DialogTitle>Long dialog</DialogTitle>
<DialogDescription>Content that can outgrow a keyboard-fitted frame.</DialogDescription>
@@ -32,7 +32,7 @@ describe("UI shape system", () => {
const dialog = screen.getByRole("dialog");
expect(dialog.parentElement).toHaveClass("items-start", "overflow-y-auto");
// The scroll owner stays inside Radix's overlay/scroll-lock boundary.
expect(dialog.parentElement?.parentElement).toHaveClass("backdrop-blur-[8px]", "duration-200");
expect(dialog.parentElement?.parentElement).toHaveAttribute("data-state", "open");
expect(dialog).toHaveClass(placement === "bottom" ? "mt-auto" : "my-auto");
});
+27 -14
View File
@@ -1,14 +1,14 @@
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { gunzipSync } from "node:zlib";
import { describe, expect, it } from "vitest";
import { rollup } from "rollup";
import webuiConfig, {
entryLazyFeatureImports,
gzipWebuiAssets,
webuiManualChunk,
writeCompressedWebuiAssets,
} from "../../vite.config";
describe("development overlay dependencies", () => {
@@ -20,24 +20,37 @@ describe("development overlay dependencies", () => {
});
describe("gzipWebuiAssets", () => {
it("compresses finalized files after Rollup writes the bundle", () => {
it("compresses finalized files after Rollup writes the bundle", async () => {
const plugin = gzipWebuiAssets();
expect(plugin.generateBundle).toBeUndefined();
expect(plugin.writeBundle).toBeTypeOf("function");
const outputDir = mkdtempSync(path.join(tmpdir(), "nanobot-vite-gzip-"));
const assetPath = path.join(outputDir, "assets", "index-final.js");
const finalized = Buffer.from(
"const __vite__mapDeps = ['assets/lazy-feature.js'];\n".repeat(200),
);
const build = await rollup({
input: "virtual-entry",
plugins: [
{
name: "fixture-entry",
resolveId: (id) => id === "virtual-entry" ? id : null,
load: (id) => id === "virtual-entry" ? 'console.log("stale in-memory bytes");' : null,
},
{
name: "finalize-on-disk",
writeBundle: {
sequential: true,
handler() { writeFileSync(assetPath, finalized); },
},
},
plugin,
],
});
try {
const assetPath = path.join(outputDir, "assets", "index-final.js");
mkdirSync(path.dirname(assetPath), { recursive: true });
const finalized = Buffer.from(
"const __vite__mapDeps = ['assets/lazy-feature.js'];\n".repeat(200),
);
writeFileSync(assetPath, finalized);
writeCompressedWebuiAssets(outputDir, ["assets/index-final.js"]);
await build.write({ dir: outputDir, format: "es", entryFileNames: "assets/index-final.js" });
expect(gunzipSync(readFileSync(`${assetPath}.gz`))).toEqual(finalized);
} finally {
await build.close();
rmSync(outputDir, { recursive: true, force: true });
}
});
+2 -1
View File
@@ -7,7 +7,8 @@ function payload(id: string): WebuiThreadPersistedPayload {
return {
schemaVersion: 3,
revision: `rev-${id}`,
messages: [{ id, role: "assistant", content: id, createdAt: 1 }],
projection: "events",
events: [{ event: "message", chat_id: id, text: id }],
};
}
+5
View File
@@ -0,0 +1,5 @@
{
"extends": "./tsconfig.build.json",
"include": ["browser", "playwright.config.ts"],
"exclude": []
}
+1
View File
@@ -26,6 +26,7 @@
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"],
"vitest": ["./node_modules/vitest"],
"lucide-react": ["./node_modules/lucide-react"],
"react": ["./node_modules/@types/react/index.d.ts"],
"react/*": ["./node_modules/@types/react/*"],