Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
test(webui): trim redundant browser coverage
chengyongru960bfa9a83be
diff --git a/webui/browser/answer-order.spec.ts b/webui/browser/answer-order.spec.tsindex 5998cd644..d84ecf2c5 100644--- a/webui/browser/answer-order.spec.ts+++ b/webui/browser/answer-order.spec.ts@@ -46,10 +46,11 @@ async function expectAnswerOrder(page: Page) {.toBeLessThan(texts.findIndex((text) => text.includes("Later answer")));}-for (const width of [1440, 390]) {+test.describe("answer order", () => {+ test.use({ viewport: { width: 1440, height: 1000 } });+for (const path of ["callback", "cached return"] as const) {- test(`keeps closed answer order through ${path} and textless streams at ${width}px`, async ({ page }, info) => {- await page.setViewportSize({ width, height: 1000 });+ test(`keeps closed answer order through ${path} and textless streams`, async ({ page }, info) => {const { emit, errors } = await openThread(page);emit({ event: "goal_status", ...base, status: "running", started_at: 100 },@@ -89,8 +90,7 @@ for (const width of [1440, 390]) {});}- test(`keeps hosted-tool answer segments after a cached return at ${width}px`, async ({ page }) => {- await page.setViewportSize({ width, height: 1000 });+ test("keeps hosted-tool answer segments after a cached return", async ({ page }) => {const { emit, errors } = await openThread(page);emit({ event: "goal_status", ...base, status: "running", started_at: 100 },@@ -117,36 +117,37 @@ for (const width of [1440, 390]) {expect(errors).toEqual([]);});- test(`replays legacy cumulative answers on both sides of a hosted tool at ${width}px`, async ({ page }) => {- await page.setViewportSize({ width, height: 1000 });- const { errors } = await openThread(page, [- { event: "stream_end", ...base, stream_id: "legacy", turn_seq: 2, text: "First ", resuming: true, merge_next: true },- { event: "message", ...base, turn_seq: 3, kind: "tool_hint", text: "web_search(query)" },- { event: "stream_end", ...base, stream_id: "legacy", turn_seq: 5, text: "First last" },- { event: "turn_end", ...base, turn_seq: 6 },- ]);- const first = page.getByText("First", { exact: true });- const last = page.getByText("last", { exact: true });- await expect(first).toHaveCount(1);- await expect(last).toHaveCount(1);- await expect(page.getByRole("button", { name: "Stop response" })).toHaveCount(0);- // Completed activity is folded into the answer block, not lost or still running.- const lastBlock = last.locator("xpath=ancestor::*[@data-thread-display-unit]");- await lastBlock.hover();- await lastBlock.getByRole("button", { name: "Message actions" }).click();- await page.locator("[data-message-block-activity-action]").click();- const tool = page.getByText(/Searched the web/).first();- await expect(tool).toBeVisible();- const [firstNode, lastNode] = await Promise.all([first.elementHandle(), last.elementHandle()]);- expect(await tool.evaluate((node, [before, after]) => (- !!(before.compareDocumentPosition(node) & Node.DOCUMENT_POSITION_FOLLOWING)- && !!(node.compareDocumentPosition(after) & Node.DOCUMENT_POSITION_FOLLOWING)- ), [firstNode!, lastNode!])).toBe(true);- expect(errors).toEqual([]);- });+ for (const width of [1440, 390]) {+ test(`replays legacy cumulative answers on both sides of a hosted tool at ${width}px`, async ({ page }) => {+ await page.setViewportSize({ width, height: 1000 });+ const { errors } = await openThread(page, [+ { event: "stream_end", ...base, stream_id: "legacy", turn_seq: 2, text: "First ", resuming: true, merge_next: true },+ { event: "message", ...base, turn_seq: 3, kind: "tool_hint", text: "web_search(query)" },+ { event: "stream_end", ...base, stream_id: "legacy", turn_seq: 5, text: "First last" },+ { event: "turn_end", ...base, turn_seq: 6 },+ ]);+ const first = page.getByText("First", { exact: true });+ const last = page.getByText("last", { exact: true });+ await expect(first).toHaveCount(1);+ await expect(last).toHaveCount(1);+ await expect(page.getByRole("button", { name: "Stop response" })).toHaveCount(0);+ // Completed activity is folded into the answer block, not lost or still running.+ const lastBlock = last.locator("xpath=ancestor::*[@data-thread-display-unit]");+ await lastBlock.hover();+ await lastBlock.getByRole("button", { name: "Message actions" }).click();+ await page.locator("[data-message-block-activity-action]").click();+ const tool = page.getByText(/Searched the web/).first();+ await expect(tool).toBeVisible();+ const [firstNode, lastNode] = await Promise.all([first.elementHandle(), last.elementHandle()]);+ expect(await tool.evaluate((node, [before, after]) => (+ !!(before.compareDocumentPosition(node) & Node.DOCUMENT_POSITION_FOLLOWING)+ && !!(node.compareDocumentPosition(after) & Node.DOCUMENT_POSITION_FOLLOWING)+ ), [firstNode!, lastNode!])).toBe(true);+ expect(errors).toEqual([]);+ });+ }- test(`keeps a rewritten image intact before a hosted tool at ${width}px`, async ({ page }, info) => {- await page.setViewportSize({ width, height: 1000 });+ test("keeps a rewritten image intact before a hosted tool", async ({ page }, info) => {const { emit, errors } = await openThread(page);await page.route("**/api/media/**", (route) => route.fulfill({ contentType: "image/png", body: Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+j5hUAAAAASUVORK5CYII=", "base64",@@ -177,8 +178,7 @@ for (const width of [1440, 390]) {expect(errors).toEqual([]);});- test(`resumes merge_next with cumulative HTTP snapshots at ${width}px`, async ({ page }) => {- await page.setViewportSize({ width, height: 1000 });+ test("resumes merge_next with cumulative HTTP snapshots", async ({ page }) => {const events: ThreadProjectionEvent[] = [{ event: "stream_end", ...base, stream_id: "answer", turn_seq: 2, text: "First ", resuming: true, merge_next: true, projection_id: "http-first" },{ event: "reasoning_end", ...base, stream_id: "answer", turn_seq: 3, text: "More reasoning", projection_id: "http-reasoning" },@@ -199,4 +199,4 @@ for (const width of [1440, 390]) {await expect(page.getByText("First last", { exact: true })).toHaveCount(0);expect(errors).toEqual([]);});-}+});diff --git a/webui/browser/compaction-reasons.spec.ts b/webui/browser/compaction-reasons.spec.tsindex 08662fecd..352828813 100644--- a/webui/browser/compaction-reasons.spec.ts+++ b/webui/browser/compaction-reasons.spec.ts@@ -6,10 +6,20 @@ import type { ThreadProjectionEvent } from "../src/lib/types";const reasons = ["idle", "context_pressure", "manual", "provider_native"] as const;const phases = ["started", "succeeded", "failed", "cancelled"] as const;-// Synthetic HTTP history and WebSocket delivery through the production client,-// projection, cache, and thread. No model/provider execution is involved.+const legacy: ThreadProjectionEvent = { event: "context_compaction", chat_id: "answer-order",+ compaction_id: "legacy", phase: "succeeded", created_at_ms: 100,+ projection_id: "legacy", turn_id: "legacy-turn", turn_seq: 1 };+const samples = reasons.map((reason, index) => {+ const start: ThreadProjectionEvent = { event: "context_compaction", chat_id: "answer-order",+ compaction_id: reason, phase: "started", reason,+ projection_id: `${reason}-start`, turn_id: `${reason}-turn`, turn_seq: 1 };+ const phase = phases[index === 3 ? 1 : index + 1]!;+ return { reason, start, finish: { ...start, phase, projection_id: `${reason}-finish`, turn_seq: 2 } };+});+for (const { code } of supportedLocales) {- test(`compaction reasons survive live updates and session reentry in ${code}`, async ({ page }, info) => {+ const lifecycle = code === "en";+ test(`${lifecycle ? "compaction reasons survive live updates and session reentry" : "localized compaction history fits the thread"} in ${code}`, async ({ page }, info) => {await page.setViewportSize({ width: 390, height: 900 });const messages: typeof import("../src/i18n/locales/en/common.json") = JSON.parse(readFileSync(new URL(`../src/i18n/locales/${code}/common.json`, import.meta.url), "utf8"),@@ -18,9 +28,8 @@ for (const { code } of supportedLocales) {await page.addInitScript((locale) => localStorage.setItem("nanobot.locale", locale), code);const errors: string[] = [];page.on("pageerror", (error) => errors.push(error.message));- let history: ThreadProjectionEvent[] = [{ event: "context_compaction", chat_id: "answer-order",- compaction_id: "legacy", phase: "succeeded", created_at_ms: 100,- projection_id: "legacy", turn_id: "legacy-turn", turn_seq: 1 }];+ const history: ThreadProjectionEvent[] = [legacy,+ ...(lifecycle ? [] : samples.flatMap(({ start, finish }) => [start, finish]))];await page.route("**/api/**", (route) => route.fulfill({ status: 404, json: {} }));await page.route("**/api/commands", (route) => route.fulfill({ json: { commands: [] } }));await page.route("**/api/sessions/*/webui-thread?*", (route) => route.fulfill({ json: {@@ -42,34 +51,33 @@ for (const { code } of supportedLocales) {await page.goto("/browser/fixture.html?case=answer-order");await expect.poll(() => attached.has("answer-order")).toBe(true);const notices = page.locator("[data-context-compaction]");- await expect(notices).toHaveCount(1);- await expect(notices.first()).toHaveText(copy.succeeded);- await expect(notices.first()).not.toHaveAttribute("role", "status");- for (const [index, reason] of reasons.entries()) {- const start: ThreadProjectionEvent = { event: "context_compaction", chat_id: "answer-order",- compaction_id: reason, phase: "started", reason,- projection_id: `${reason}-start`, turn_id: `${reason}-turn`, turn_seq: 1 };- socket.send(JSON.stringify(start));- const notice = notices.nth(index + 1);- await expect(notices).toHaveCount(index + 2);- await expect(notice).toHaveText(copy.reasons[reason].started);- await expect(notice).toHaveAttribute("aria-busy", "true");- const handle = await notice.elementHandle();- const phase = phases[index === 3 ? 1 : index + 1]!;- const finish = { ...start, phase, projection_id: `${reason}-finish`, turn_seq: 2 };- socket.send(JSON.stringify(finish));- await expect(notice).toHaveText(copy.reasons[reason][phase]);- await expect(notice).toHaveAttribute("aria-busy", "false");- expect(await notice.evaluate((node, original) => node === original, handle)).toBe(true);- await expect(notices).toHaveCount(index + 2);- history = [...history, start, finish];+ if (lifecycle) {+ await expect(notices).toHaveCount(1);+ await expect(notices.first()).toHaveText(copy.succeeded);+ await expect(notices.first()).not.toHaveAttribute("role", "status");+ for (const [index, { reason, start, finish }] of samples.entries()) {+ socket.send(JSON.stringify(start));+ const notice = notices.nth(index + 1);+ await expect(notices).toHaveCount(index + 2);+ await expect(notice).toHaveText(copy.reasons[reason].started);+ await expect(notice).toHaveAttribute("aria-busy", "true");+ const handle = await notice.elementHandle();+ socket.send(JSON.stringify(finish));+ await expect(notice).toHaveText(copy.reasons[reason][finish.phase]);+ await expect(notice).toHaveAttribute("aria-busy", "false");+ expect(await notice.evaluate((node, original) => node === original, handle)).toBe(true);+ await expect(notices).toHaveCount(index + 2);+ history.push(start, finish);+ }+ const text = await notices.allTextContents();+ await page.getByRole("button", { name: "Switch topic" }).click();+ await expect(notices).toHaveCount(0);+ await page.getByRole("button", { name: "Switch topic" }).click();+ await expect(notices).toHaveText(text);+ await page.reload();+ await expect(notices).toHaveText(text);}- const text = await notices.allTextContents();- await page.getByRole("button", { name: "Switch topic" }).click();- await expect(notices).toHaveCount(0);- await page.getByRole("button", { name: "Switch topic" }).click();- await expect(notices).toHaveText(text);- await page.reload();+ const text = [copy.succeeded, ...samples.map(({ reason, finish }) => copy.reasons[reason][finish.phase])];await expect(notices).toHaveText(text);await expect(page.locator('[data-context-compaction][role="status"]')).toHaveCount(0);for (const theme of ["light", "dark"]) {diff --git a/webui/browser/fixture.tsx b/webui/browser/fixture.tsxindex 34859f72f..b44e8e82b 100644--- a/webui/browser/fixture.tsx+++ b/webui/browser/fixture.tsx@@ -25,7 +25,6 @@ import "../src/globals.css";import { DiagramFixture } from "./diagram-fixture";import { TypographyFixture } from "./typography-fixture";import { InlineReferencesFixture } from "./inline-references-fixture";-import { MarkdownEmphasisFixture } from "./markdown-emphasis-fixture";import { HistoryBoundaryFixture } from "./history-boundary-fixture";import { ChatFailureFixture } from "./chat-failure-fixture";import { ThreadLoadingFixture } from "./thread-loading-fixture";@@ -252,8 +251,6 @@ createRoot(document.getElementById("root")!).render(<TooltipProvider>? <ChatFailureFixture parameters={parameters} />: parameters.get("case") === "display-math"? <DisplayMathFixture />- : parameters.get("case") === "markdown-emphasis"- ? <MarkdownEmphasisFixture />: parameters.get("case") === "typography"? <ClientProvider client={railClient} token="fixture"><TypographyFixture /></ClientProvider>: parameters.get("case") === "inline-references"diff --git a/webui/browser/loaded-session-search-fixture.tsx b/webui/browser/loaded-session-search-fixture.tsxindex 26a7e744c..fdbbb7ae1 100644--- a/webui/browser/loaded-session-search-fixture.tsx+++ b/webui/browser/loaded-session-search-fixture.tsx@@ -1,14 +1,13 @@-import { useEffect, useState } from "react";+import { useState } from "react";import { SessionSearchDialog } from "@/components/SessionSearchDialog";import { useAppViewport } from "@/hooks/useAppViewport";import { ThreadMessageCache } from "@/lib/thread-message-cache";import { ThreadTranscript } from "@/lib/thread-transcript";import type { ChatSummary } from "@/lib/types";-const sessions: ChatSummary[] = Array.from({ length: 1000 }, (_, index) => ({+const sessions: ChatSummary[] = Array.from({ length: 2 }, (_, index) => ({key: `websocket:topic-${index}`, chatId: `topic-${index}`, channel: "websocket",title: `Topic ${index}`, preview: `Preview ${index}`, createdAt: null, updatedAt: null,- ...(index === 1 ? { handle: { id: "handle_00000000000000000000000000000001", name: "betu" } } : {}),}));export function LoadedSessionSearchFixture() {@@ -19,23 +18,11 @@ export function LoadedSessionSearchFixture() {const value = new ThreadMessageCache(() => false);value.set("topic-1", new ThreadTranscript([{ id: "user", role: "user", content: "我们讨论权限与配对", createdAt: 1 },- { id: "answer", role: "assistant", content: `${"Earlier notes. ".repeat(500)}Use Full Access at 25% in session_history.py`, createdAt: 2 },]).save());return value;});- useEffect(() => {- const shortcut = (event: KeyboardEvent) => {- if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "k") {- event.preventDefault();- setOpen(true);- }- };- window.addEventListener("keydown", shortcut);- return () => window.removeEventListener("keydown", shortcut);- }, []);return <main className="h-[100dvh] bg-background p-6 text-foreground"><button onClick={() => setOpen(true)}>Search</button>- <textarea aria-label="Draft" defaultValue="Keep this unsent draft" className="block" /><output aria-label="Selected topic">{selected}</output><SessionSearchDialog open={open} onOpenChange={setOpen} sessions={sessions}activeKey={selected} loading={false} messageCache={cache} onSelect={setSelected} />diff --git a/webui/browser/loaded-session-search.spec.ts b/webui/browser/loaded-session-search.spec.tsindex 8f213ce88..2a018ee2d 100644--- a/webui/browser/loaded-session-search.spec.ts+++ b/webui/browser/loaded-session-search.spec.ts@@ -1,33 +1,18 @@import { expect, test } from "@playwright/test";for (const viewport of [{ width: 1280, height: 800 }, { width: 390, height: 844 }]) {- test(`searches only loaded body text without requests at ${viewport.width}px`, async ({ page }) => {+ test(`selects a loaded body match from the search dialog at ${viewport.width}px`, async ({ page }) => {await page.setViewportSize(viewport);- const apiRequests: string[] = [];const errors: string[] = [];- page.on("request", (request) => { if (new URL(request.url()).pathname.startsWith("/api/")) apiRequests.push(request.url()); });page.on("pageerror", (error) => errors.push(error.message));await page.goto("/browser/fixture.html?case=loaded-session-search");- await page.getByRole("button", { name: "Search", exact: true }).waitFor();- await page.keyboard.press("Control+k");+ await page.getByRole("button", { name: "Search", exact: true }).click();const dialog = page.getByRole("dialog", { name: "Search", exact: true });const input = dialog.getByRole("textbox", { name: "Search", exact: true });- await expect(dialog.getByRole("button")).toHaveCount(24);- for (const query of ["@betu", "betu", "@BETU", "@be"]) {- await input.fill(query);- await expect(dialog.getByRole("button")).toHaveCount(1);- await expect(dialog.getByText("Topic 1", { exact: true })).toBeVisible();- await expect(dialog.getByText("Preview 1", { exact: true })).toBeVisible();- }- for (const query of ["权限", "full access", "25%", "session_history.py"]) {- await input.fill(query);- await expect(dialog.getByRole("button")).toHaveCount(1);- await expect(dialog.getByText("Topic 1", { exact: true })).toBeVisible();- await expect(dialog.getByText(query === "权限" ? "我们讨论权限与配对" : /Use Full Access at 25%/)).toBeVisible();- }- await input.fill("unloaded server content");- await expect(dialog.getByText("No matching topics.")).toBeVisible();await input.fill("权限");+ await expect(dialog.getByRole("button")).toHaveCount(1);+ await expect(dialog.getByText("Topic 1", { exact: true })).toBeVisible();+ await expect(dialog.getByText("我们讨论权限与配对")).toBeVisible();const box = await dialog.boundingBox();expect(box).not.toBeNull();expect(box!.x).toBeGreaterThanOrEqual(0);@@ -36,8 +21,6 @@ for (const viewport of [{ width: 1280, height: 800 }, { width: 390, height: 844await input.press("Enter");await expect(dialog).not.toBeVisible();await expect(page.getByLabel("Selected topic")).toHaveText("websocket:topic-1");- await expect(page.getByRole("textbox", { name: "Draft" })).toHaveValue("Keep this unsent draft");- expect(apiRequests).toEqual([]);expect(errors).toEqual([]);});}diff --git a/webui/browser/markdown-emphasis-fixture.tsx b/webui/browser/markdown-emphasis-fixture.tsxdeleted file mode 100644index 9b9a75b46..000000000--- a/webui/browser/markdown-emphasis-fixture.tsx+++ /dev/null@@ -1,21 +0,0 @@-import { useState } from "react";--import { MarkdownText } from "@/components/MarkdownText";--const source = [- "**`ThreadTranscript` 已经朝这个方向走了一步:它把正文、来源覆盖和分页接纳集中起来,因此可以看作一个隐式的状态转换模型。**但“集中到一个类”不等于已经有清晰的状态机。",- "前文**「重点」**后文。**参考 [说明](https://example.com) 的结论。**继续阅读。",- "**日本語。**続き。**한국어(설명)**입니다。",- "**中文。** 继续。**English.** Next.",- "**边界说明: **issue",-].join("\n\n");--export function MarkdownEmphasisFixture() {- const [end, setEnd] = useState(0);- const [streaming, setStreaming] = useState(true);- return <main className="mx-auto max-w-3xl p-6">- <button onClick={() => setEnd((value) => Math.min(source.length, value + 1))}>Next character</button>- <button onClick={() => { setEnd(source.length); setStreaming(false); }}>Complete</button>- <div data-testid="reply"><MarkdownText streaming={streaming} preserveStreamingLayout>{source.slice(0, end)}</MarkdownText></div>- </main>;-}diff --git a/webui/browser/markdown-emphasis.spec.ts b/webui/browser/markdown-emphasis.spec.tsdeleted file mode 100644index dab0ccfb5..000000000--- a/webui/browser/markdown-emphasis.spec.ts+++ /dev/null@@ -1,23 +0,0 @@-import { expect, test } from "@playwright/test";--for (const width of [390, 1440]) {- test(`CJK emphasis retains inline semantics through completion at ${width}px`, async ({ page }) => {- await page.setViewportSize({ width, height: 900 });- await page.goto("/browser/fixture.html?case=markdown-emphasis");- // Reveal the inline code while its enclosing emphasis is still incomplete.- for (let index = 0; index < 24; index++) {- await page.getByRole("button", { name: "Next character", exact: true }).click();- }- const reply = page.getByTestId("reply");- await expect(reply.locator("code")).toHaveText("ThreadTranscript");- await page.getByRole("button", { name: "Complete", exact: true }).click();- await expect(reply.locator("strong code")).toHaveText("ThreadTranscript");- await expect(reply.locator("strong a")).toHaveText("说明");- await expect(reply.locator("strong a")).toHaveAttribute("href", "https://example.com");- await expect(reply.locator("strong")).toHaveCount(7);- await expect(reply.locator("p").last()).toHaveText("**边界说明: **issue");- await expect(reply.locator("p").first()).toContainText("但“集中到一个类”不等于已经有清晰的状态机。");- await expect(reply.locator("strong").first()).not.toContainText("但“集中到一个类”");- await expect(reply).toBeVisible();- });-}diff --git a/webui/browser/queued-guidance.spec.ts b/webui/browser/queued-guidance.spec.tsindex ff38ffe13..a3e0951cc 100644--- a/webui/browser/queued-guidance.spec.ts+++ b/webui/browser/queued-guidance.spec.ts@@ -10,41 +10,37 @@ async function queue(page: Page, text = "Confirm this instruction") {await expect(page.getByRole("group", { name: "Waiting to send" })).toContainText(text);}-for (const width of [1440, 390]) {- test(`a new page retains waiting content without executing it (${width}px)`, async ({ page }) => {- await page.setViewportSize({ width, height: 900 });+test("a new page retains waiting content without executing it", async ({ page }) => {+ await page.goto(fixture);+ await queue(page);+ await page.goto(`${fixture}&complete`);+ await expect(page.getByRole("group", { name: "Waiting to send" })).toContainText("Confirm this instruction");+ await expect(page.getByLabel("Submitted messages")).toHaveText("[]");+ await page.getByRole("textbox", { name: "Message input", exact: true }).press("Enter");+ await expect(page.getByLabel("Submitted messages")).toHaveText('[{"text":"Confirm this instruction"}]');+ await expect(page.getByRole("group", { name: "Waiting to send" })).toHaveCount(0);+});++for (const interaction of ["refocus", "clear edits"] as const) {+ test(`empty Enter sends waiting content after ${interaction}`, async ({ page }) => {await page.goto(fixture);await queue(page);- await page.goto(`${fixture}&complete`);- await expect(page.getByRole("group", { name: "Waiting to send" })).toContainText("Confirm this instruction");+ const input = page.getByRole("textbox", { name: "Message input", exact: true });+ if (interaction === "refocus") {+ await input.press("Shift+Tab");+ await expect(input).not.toBeFocused();+ await page.keyboard.press("Tab");+ } else {+ await input.press("x");+ await input.press("Backspace");+ }+ await expect(input).toBeFocused();+ await expect(input).toHaveValue("");await expect(page.getByLabel("Submitted messages")).toHaveText("[]");- await page.getByRole("textbox", { name: "Message input", exact: true }).press("Enter");- await expect(page.getByLabel("Submitted messages")).toHaveText('[{"text":"Confirm this instruction"}]');+ await input.press("Enter");+ await expect(page.getByLabel("Submitted messages")).toHaveText('[{"text":"Confirm this instruction","options":{"continueActiveTurn":true}}]');await expect(page.getByRole("group", { name: "Waiting to send" })).toHaveCount(0);});-- for (const interaction of ["refocus", "clear edits"] as const) {- test(`empty Enter sends waiting content after ${interaction} (${width}px)`, async ({ page }) => {- await page.setViewportSize({ width, height: 900 });- await page.goto(fixture);- await queue(page);- const input = page.getByRole("textbox", { name: "Message input", exact: true });- if (interaction === "refocus") {- await input.press("Shift+Tab");- await expect(input).not.toBeFocused();- await page.keyboard.press("Tab");- } else {- await input.press("x");- await input.press("Backspace");- }- await expect(input).toBeFocused();- await expect(input).toHaveValue("");- await expect(page.getByLabel("Submitted messages")).toHaveText("[]");- await input.press("Enter");- await expect(page.getByLabel("Submitted messages")).toHaveText('[{"text":"Confirm this instruction","options":{"continueActiveTurn":true}}]');- await expect(page.getByRole("group", { name: "Waiting to send" })).toHaveCount(0);- });- }}test("desktop Shift+Enter keeps waiting content until the editor is empty again", async ({ page }) => {diff --git a/webui/browser/typography.spec.ts b/webui/browser/typography.spec.tsindex e707720f3..2ddf65a6c 100644--- a/webui/browser/typography.spec.ts+++ b/webui/browser/typography.spec.ts@@ -22,69 +22,67 @@ async function metrics(element: Locator): Promise<Awaited<ReturnType<typeof read}for (const narrow of [false, true]) {- for (const dark of [false, true]) {- test(`reading hierarchy and stable controls: ${narrow ? "narrow" : "desktop"}, ${dark ? "dark" : "light"}`, async ({ page }, info) => {- await page.setViewportSize(narrow ? { width: 390, height: 844 } : { width: 1440, height: 1000 });- await page.addInitScript((theme) => {- localStorage.setItem("nanobot.locale", "zh-CN");- localStorage.setItem("nanobot-webui.theme", theme);- }, dark ? "dark" : "light");- await page.goto("/browser/fixture.html?case=typography");- const group = page.getByRole("radiogroup", { name: "阅读字号", exact: true });- await expect(group.getByRole("radio", { name: "阅读字号:标准", exact: true })).toBeChecked();- await expect(group.getByRole("radio")).toHaveCount(3);- const stable = await metrics(page.locator(".settings-row").first().locator(".text-control-label"));- const observations = [];- for (const [size, label, bodySize] of [- ["small", "阅读字号:小", narrow ? 15 : 16],- ["standard", "阅读字号:标准", narrow ? 16 : 18],- ["large", "阅读字号:大", narrow ? 18 : 20],- ] as const) {- await group.getByRole("radio", { name: label, exact: true }).click();- await expect(page.locator("html")).toHaveAttribute("data-reading-text-size", size);- const paragraph = page.locator('section[aria-label="Reading preview"] .markdown-content p').first();- await expect(paragraph).toHaveCSS("font-size", `${bodySize}px`);- const body = await metrics(paragraph);- expect(body.size).toBe(bodySize);- expect(body.line).toBeCloseTo(bodySize * 1.8);- expect(body.weight).toBe("400");- expect((await metrics(page.locator("[data-user-text-bubble] p"))).size).toBe(bodySize);- for (const selector of ["blockquote", "ol > li", ".task-list-item"]) {- expect((await metrics(page.locator(`.markdown-content ${selector}`).first())).size).toBe(bodySize);- }- for (const [selector, ratio] of [["h1", 1.5], ["h2", 1.25], ["h3", 1.125], ["h4", 1]] as const) {- const heading = await metrics(page.locator(`.markdown-content ${selector}`));- expect(heading.size).toBeCloseTo(bodySize * ratio);- expect(heading.weight).toBe("600");- }- for (const selector of ["table", "th", "td"]) {- expect((await metrics(page.locator(`.markdown-content ${selector}`).first())).size).toBeCloseTo(bodySize * 0.875);- }- expect((await metrics(page.locator(".code-content pre"))).size).toBeCloseTo(bodySize * 0.875);- expect((await metrics(page.locator(".markdown-inline-code"))).size).toBeCloseTo(bodySize * 0.875);- expect((await metrics(page.locator("textarea"))).size).toBe(Math.max(16, bodySize));- expect(await metrics(page.locator(".settings-row").first().locator(".text-control-label"))).toEqual(stable);- const targets = await group.getByRole("radio").evaluateAll((nodes) => nodes.map((node) => {- const { width, height } = node.getBoundingClientRect();- return { width, height };- }));- // Fine-pointer presets are circular; the separate touch test protects 44px hit targets.- for (const target of targets) {- expect(target.width).toBeGreaterThanOrEqual(36);- expect(target.width).toBe(target.height);- }- expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true);- observations.push({ size, body, targets });- await page.locator(".markdown-content h1").evaluate(node => node.scrollIntoView({ block: "start" }));- await page.screenshot({ path: info.outputPath(`${size}.png`) });- }- await info.attach("text-metrics", { body: JSON.stringify(observations, null, 2), contentType: "application/json" });- await page.getByRole("button", { name: "复制代码", exact: true }).click();- await expect(page.getByRole("button", { name: "已复制", exact: true })).toBeVisible();- await page.locator("summary").click();- await expect(page.getByText("这里的正文与折叠标题也应保持协调,不因字号变化发生裁切。")).toBeVisible();+ test(`reading hierarchy and stable controls: ${narrow ? "narrow" : "desktop"}`, async ({ page }, info) => {+ await page.setViewportSize(narrow ? { width: 390, height: 844 } : { width: 1440, height: 1000 });+ await page.addInitScript(() => {+ localStorage.setItem("nanobot.locale", "zh-CN");+ localStorage.setItem("nanobot-webui.theme", "light");});- }+ await page.goto("/browser/fixture.html?case=typography");+ const group = page.getByRole("radiogroup", { name: "阅读字号", exact: true });+ await expect(group.getByRole("radio", { name: "阅读字号:标准", exact: true })).toBeChecked();+ await expect(group.getByRole("radio")).toHaveCount(3);+ const stable = await metrics(page.locator(".settings-row").first().locator(".text-control-label"));+ const observations = [];+ for (const [size, label, bodySize] of [+ ["small", "阅读字号:小", narrow ? 15 : 16],+ ["standard", "阅读字号:标准", narrow ? 16 : 18],+ ["large", "阅读字号:大", narrow ? 18 : 20],+ ] as const) {+ await group.getByRole("radio", { name: label, exact: true }).click();+ await expect(page.locator("html")).toHaveAttribute("data-reading-text-size", size);+ const paragraph = page.locator('section[aria-label="Reading preview"] .markdown-content p').first();+ await expect(paragraph).toHaveCSS("font-size", `${bodySize}px`);+ const body = await metrics(paragraph);+ expect(body.size).toBe(bodySize);+ expect(body.line).toBeCloseTo(bodySize * 1.8);+ expect(body.weight).toBe("400");+ expect((await metrics(page.locator("[data-user-text-bubble] p"))).size).toBe(bodySize);+ for (const selector of ["blockquote", "ol > li", ".task-list-item"]) {+ expect((await metrics(page.locator(`.markdown-content ${selector}`).first())).size).toBe(bodySize);+ }+ for (const [selector, ratio] of [["h1", 1.5], ["h2", 1.25], ["h3", 1.125], ["h4", 1]] as const) {+ const heading = await metrics(page.locator(`.markdown-content ${selector}`));+ expect(heading.size).toBeCloseTo(bodySize * ratio);+ expect(heading.weight).toBe("600");+ }+ for (const selector of ["table", "th", "td"]) {+ expect((await metrics(page.locator(`.markdown-content ${selector}`).first())).size).toBeCloseTo(bodySize * 0.875);+ }+ expect((await metrics(page.locator(".code-content pre"))).size).toBeCloseTo(bodySize * 0.875);+ expect((await metrics(page.locator(".markdown-inline-code"))).size).toBeCloseTo(bodySize * 0.875);+ expect((await metrics(page.locator("textarea"))).size).toBe(Math.max(16, bodySize));+ expect(await metrics(page.locator(".settings-row").first().locator(".text-control-label"))).toEqual(stable);+ const targets = await group.getByRole("radio").evaluateAll((nodes) => nodes.map((node) => {+ const { width, height } = node.getBoundingClientRect();+ return { width, height };+ }));+ // Fine-pointer presets are circular; the separate touch test protects 44px hit targets.+ for (const target of targets) {+ expect(target.width).toBeGreaterThanOrEqual(36);+ expect(target.width).toBe(target.height);+ }+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true);+ observations.push({ size, body, targets });+ await page.locator(".markdown-content h1").evaluate(node => node.scrollIntoView({ block: "start" }));+ await page.screenshot({ path: info.outputPath(`${size}.png`) });+ }+ await info.attach("text-metrics", { body: JSON.stringify(observations, null, 2), contentType: "application/json" });+ await page.getByRole("button", { name: "复制代码", exact: true }).click();+ await expect(page.getByRole("button", { name: "已复制", exact: true })).toBeVisible();+ await page.locator("summary").click();+ await expect(page.getByText("这里的正文与折叠标题也应保持协调,不因字号变化发生裁切。")).toBeVisible();+ });}test("keyboard, tooltip, persistence and unchanged preferences", async ({ page }) => {diff --git a/webui/browser/workspace-alignment.spec.ts b/webui/browser/workspace-alignment.spec.tsindex 624e4a957..6697bd97a 100644--- a/webui/browser/workspace-alignment.spec.ts+++ b/webui/browser/workspace-alignment.spec.ts@@ -1,27 +1,28 @@-import { expect, test } from "@playwright/test";+import { expect, test, type Page } from "@playwright/test";const cases = [- { name: "desktop", width: 1280, touch: false, extra: "" },- { name: "tablet", width: 1280, touch: true, extra: "" },- { name: "small desktop", width: 600, touch: false, extra: "" },- { name: "phone", width: 390, touch: true, extra: "" },- { name: "narrow desktop pane", width: 1024, touch: false, extra: "&containerWidth=480" },+ { name: "tablet", width: 1280, touch: true },+ { name: "small desktop", width: 600, touch: false },];+async function expectAlignedWorkspaceGlyph(page: Page) {+ const attachment = page.getByRole("button", { name: "Attach files" }).locator("svg");+ const workspace = page.getByRole("button", { name: "Switch directory" }).locator('[data-product-icon="workspace"]');+ await expect(workspace).toBeVisible();+ await page.evaluate(() => document.fonts.ready);+ const attachmentBox = (await attachment.boundingBox())!;+ const workspaceBox = (await workspace.boundingBox())!;+ expect(workspaceBox.x).toBeCloseTo(attachmentBox.x, 1);+}+for (const variant of ["hero", "thread"]) for (const c of cases) {test.describe(`${variant} ${c.name}`, () => {test.use({ viewport: { width: c.width, height: 900 }, hasTouch: c.touch, reducedMotion: "reduce" });test("aligns the directory glyph with the attachment glyph", async ({ page }) => {await page.addInitScript(() => localStorage.setItem("nanobot.locale", "en"));await page.route("**/api/commands", route => route.fulfill({ json: { commands: [] } }));- await page.goto(`/browser/fixture.html?case=workspace-alignment&composerVariant=${variant}${c.extra}`);- const attachment = page.getByRole("button", { name: "Attach files" }).locator("svg");- const workspace = page.getByRole("button", { name: "Switch directory" }).locator('[data-product-icon="workspace"]');- await expect(workspace).toBeVisible();- await page.evaluate(() => document.fonts.ready);- const attachmentBox = (await attachment.boundingBox())!;- const workspaceBox = (await workspace.boundingBox())!;- expect(workspaceBox.x).toBeCloseTo(attachmentBox.x, 1);+ await page.goto(`/browser/fixture.html?case=workspace-alignment&composerVariant=${variant}`);+ await expectAlignedWorkspaceGlyph(page);expect(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth)).toBe(false);});});@@ -34,6 +35,7 @@ for (const variant of ["hero", "thread"]) for (const width of [280, 320, 390, 60await page.addInitScript(() => localStorage.setItem("nanobot.locale", "en"));await page.route("**/api/commands", route => route.fulfill({ json: { commands: [] } }));await page.goto(`/browser/fixture.html?case=workspace-alignment&composerVariant=${variant}${width === 1024 ? "&containerWidth=480" : ""}`);+ if ([390, 1024, 1280].includes(width)) await expectAlignedWorkspaceGlyph(page);const workspace = page.getByRole("button", { name: "Switch directory" });const access = page.getByRole("button", { name: "Workspace access mode: Full Access" });await expect(access).toBeVisible();