/** Markdown in agent replies, in the real conversation: browser defaults don't suit a narrow chat. */ import { expect, test, type Page } from "@playwright/test"; const TASK = { id: "t1", title: "Repro task", status: "ready" as const, isolation: "local" as const, provider: "codex", model: null, cwd: "/dev/acme-api", branch: null, base: null, baseCommit: null, error: null, createdMs: 0, updatedMs: 0, config: [], commands: [], usage: null, queue: [], capabilities: { fork: true, rollback: true, steer: true, images: true }, }; const PIXEL = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"; const REPLY = [ "# Heading one", "", "## Heading two", "", "##### Heading five", "", "> A quote", "", "- [x] done", "- [ ] open", "", "---", "", `![pixel](${PIXEL})`, "", "| Path | Owner | Status | Notes |", "| --- | --- | --- | --- |", "| src/features/agents/conversation/very/long/path/file.tsx | someone | modified | a fairly long note |", "", "```ts", "const a = 1;", "```", ].join("\n"); async function openReply(page: Page, text: string, imageData?: string, theme?: "dark" | "light") { await page.goto("/"); await page.getByRole("tree", { name: "Project" }).waitFor(); await page.evaluate( async ({ task, text, imageData, theme }) => { if (theme) document.documentElement.dataset.theme = theme; if (imageData) { const routePath = "/src/platform/tauriCore.ts"; const { setInvokeRoute } = await import(routePath); setInvokeRoute((cmd: string) => (cmd === "fs_read_image" ? Promise.resolve(imageData) : null)); } // Paths go through variables: knip can't resolve these browser-absolute URLs. const storePath = "/src/features/agents/store.ts"; const store = await import(storePath); store.useAgents.setState({ loaded: true, error: null, providers: [], tasks: new Map([[task.id, task]]), entries: new Map([ [ task.id, [ { type: "user", text: "Show Markdown", attachments: [], sentMs: 0, doneMs: 1, steered: false, }, { type: "agent", text }, ], ], ]), unread: new Set(), docked: null, }); store.dockTask(task.id); }, { task: TASK, text, imageData, theme }, ); const reply = page.locator("[class*='_markdown_']").first(); await reply.locator("h1, p").first().waitFor(); return reply; } const css = (reply: ReturnType, selector: string, property: string) => reply .locator(selector) .first() .evaluate((el, name) => getComputedStyle(el).getPropertyValue(name), property); const px = (value: string) => Number.parseFloat(value); test("opens Windows file links in the editor at their line and column", async ({ page }) => { const path = "E:/work/笔记 list.txt"; const reply = await openReply( page, "[Windows file](E:/work/笔记%20list.txt:3:5)\n\n[Backslash path](E:%5Cwork%5C笔记%20list.txt#L7)", ); await page.evaluate(async (path) => { const backendPath = "/src/editor/core/backend.ts"; const { docBackend } = await import(backendPath); docBackend().files.set(path, Array.from({ length: 12 }, (_, i) => `Line ${i + 1}: Windows file link`).join("\n")); }, path); await reply.getByRole("link", { name: "Windows file", exact: true }).click(); const cursor = () => page.evaluate(async () => { const servicePath = "/src/workbench/contributions.ts"; const { editorService } = await import(servicePath); return { path: editorService().activePath(), cursor: editorService().activeCursor() }; }); await expect.poll(cursor).toMatchObject({ path, cursor: { line: 2, col: 4 } }); await expect(page.locator(".cm-content").first()).toContainText("Line 3: Windows file link"); await reply.getByRole("link", { name: "Backslash path", exact: true }).click(); await expect.poll(cursor).toMatchObject({ path, cursor: { line: 6, col: 0 } }); }); test("opens slash-prefixed Windows Markdown links with preview content and hover targets", async ({ page }) => { const spec = "E:/work/feature/spec.md"; const skill = "E:/work/.agents/skills/work-spec/SKILL.md"; const reply = await openReply(page, `[Specification](/${spec})\n\n[Work skill](/${skill})`); await page.evaluate( async ({ spec, skill }) => { const backendPath = "/src/editor/core/backend.ts"; const modePath = "/src/features/viewers/markdown/modes.ts"; const { docBackend } = await import(backendPath); const { setMarkdownMode } = await import(modePath); docBackend().files.set(spec, "# Windows specification\n\nThe specification is not empty."); docBackend().files.set(skill, "# Work specification skill\n\nThe skill is not empty."); setMarkdownMode(spec, "preview"); setMarkdownMode(skill, "preview"); }, { spec, skill }, ); for (const [label, path, heading] of [ ["Specification", spec, "Windows specification"], ["Work skill", skill, "Work specification skill"], ] as const) { const link = reply.getByRole("link", { name: label, exact: true }); await link.hover(); await expect(link).toHaveAttribute("title", path); await link.click(); await expect(page.getByRole("heading", { name: heading, exact: true })).toBeVisible(); await expect .poll(() => page.evaluate(async () => { const servicePath = "/src/workbench/contributions.ts"; return (await import(servicePath)).editorService().activePath(); }), ) .toBe(path); } }); test("styles tables so a reply reads as a table", async ({ page }) => { const reply = await openReply(page, REPLY); expect(await css(reply, "td", "border-top-width")).toBe("1px"); expect(await css(reply, "td", "padding-left")).toBe("8px"); expect(await css(reply, "th", "border-top-width")).toBe("1px"); // A narrow chat must not squeeze a column to a few letters. const widths = await reply .locator("td") .evaluateAll((cells) => cells.map((cell) => cell.getBoundingClientRect().width)); for (const width of widths) expect(width).toBeGreaterThanOrEqual(70); }); test("scrolls a wide table inside the reply", async ({ page }) => { const reply = await openReply(page, REPLY); const sizes = await reply.evaluate((el) => { const table = el.querySelector("table")!; return { reply: el.clientWidth, table: table.clientWidth, content: table.scrollWidth, }; }); expect(sizes.table).toBeLessThanOrEqual(sizes.reply); expect(sizes.content).toBeGreaterThan(sizes.table); }); test("sizes headings for a chat and keeps small ones readable", async ({ page }) => { const reply = await openReply(page, REPLY); const body = px(await css(reply, "td", "font-size")); const h1 = px(await css(reply, "h1", "font-size")); expect(h1).toBeGreaterThan(body); expect(h1).toBeLessThanOrEqual(body * 1.2); expect(px(await css(reply, "h2", "font-size"))).toBeLessThan(h1); expect(px(await css(reply, "h5", "font-size"))).toBe(body); }); test("starts and ends a reply without stray margins", async ({ page }) => { const reply = await openReply(page, REPLY); expect(await css(reply, "> :first-child", "margin-top")).toBe("0px"); expect(await css(reply, "> :last-child", "margin-bottom")).toBe("0px"); }); test("styles quotes, rules, images and task lists", async ({ page }) => { const reply = await openReply(page, REPLY); expect(await css(reply, "blockquote", "margin-left")).toBe("0px"); expect(await css(reply, "blockquote", "border-left-width")).toBe("3px"); expect(await css(reply, "hr", "border-left-width")).toBe("0px"); expect(await css(reply, "hr", "border-top-width")).toBe("1px"); expect(await css(reply, "img", "max-width")).toBe("100%"); // A checkbox stands in for the bullet. expect(await css(reply, "li:has(> input)", "list-style-type")).toBe("none"); }); test("loads local reply images, and web ones when asked", async ({ page }) => { let fetched = 0; await page.route("https://images.example.com/code.gif", (route) => { fetched++; return route.fulfill({ contentType: "image/gif", body: Buffer.from(PIXEL.split(",")[1]!, "base64"), }); }); const reply = await openReply( page, "![Local QR](/tmp/code.png)\n\n![Web QR](https://images.example.com/code.gif)", PIXEL, ); const width = (name: string) => reply.getByRole("img", { name, includeHidden: true }).evaluate((img: HTMLImageElement) => img.naturalWidth); await expect.poll(() => width("Local QR")).toBe(1); const load = reply.getByRole("button", { name: "Load image from images.example.com", }); await expect(load).toBeVisible(); expect(fetched).toBe(0); await load.click(); await expect.poll(() => width("Web QR")).toBe(1); expect(fetched).toBe(1); }); test("copies reply Markdown with the keyboard and keeps code copying separate", async ({ page, context }) => { await context.grantPermissions(["clipboard-read", "clipboard-write"]); const reply = await openReply(page, REPLY); const copy = page.getByRole("button", { name: "Copy Markdown", exact: true }); const actions = copy.locator(".."); await page.mouse.move(0, 0); await expect(actions).toHaveCSS("opacity", "1"); await copy.focus(); await expect(actions).toHaveCSS("opacity", "1"); await page.keyboard.press("Enter"); await expect(page.getByRole("button", { name: "Copied", exact: true })).toBeVisible(); expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(REPLY); await reply.getByRole("button", { name: "Copy Code", exact: true }).click(); expect(await page.evaluate(() => navigator.clipboard.readText())).toBe("const a = 1;"); }); test("copies a reply link's address from its context menu and keeps Copy for the selected text", async ({ page, context, }) => { await context.grantPermissions(["clipboard-read", "clipboard-write"]); const url = "https://example.com/pull/42?tab=files#diff"; const reply = await openReply(page, `[**Review changes**](${url})\n\nOrdinary reply text`); const link = reply.getByRole("link", { name: "Review changes" }); await link.locator("strong").click({ button: "right" }); await page.getByRole("menuitem", { name: "Copy Link Address" }).click(); await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe(url); await link.evaluate((el) => { const range = document.createRange(); range.selectNodeContents(el); window.getSelection()!.removeAllRanges(); window.getSelection()!.addRange(range); }); await link.click({ button: "right" }); await page .getByRole("menuitem", { name: /^Copy\b/ }) .first() .click(); await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe("Review changes"); const paragraph = reply.getByText("Ordinary reply text", { exact: true }); await paragraph.click({ button: "right" }); await expect(page.getByRole("menuitem", { name: "Copy Link Address" })).toHaveCount(0); await page.keyboard.press("Escape"); }); test("keeps latest reply actions visible and quotes into the draft without shifting content", async ({ page }) => { const reply = await openReply(page, REPLY); const copy = page.getByRole("button", { name: "Copy Markdown", exact: true }); const actions = copy.locator(".."); await page.mouse.move(0, 0); await expect(actions).toHaveCSS("opacity", "1"); const before = await reply.boundingBox(); await reply.hover(); await expect(actions).toHaveCSS("opacity", "1"); expect(await reply.boundingBox()).toEqual(before); await expect(actions.getByRole("button")).toHaveCount(4); await page.mouse.move(0, 0); await expect(actions).toHaveCSS("opacity", "1"); const userCopy = page.getByRole("button", { name: "Copy", exact: true }); await expect(userCopy.locator("..")).toHaveCSS("opacity", "0"); await page.getByText("Show Markdown", { exact: true }).hover(); await expect(userCopy.locator("..")).toHaveCSS("opacity", "1"); await reply.hover(); await page.getByRole("button", { name: "Quote Reply", exact: true }).click(); const draft = page.getByRole("textbox", { name: "Message", exact: true }); await expect(draft).toBeFocused(); // Quoted as `> ` lines, drawn as a block without their markers, an empty line to type in after it. const quoted = REPLY.trimEnd().split("\n"); await expect(draft.locator(".cm-line")).toHaveText([...quoted, "", ""]); await expect(draft.locator(".cm-line[class*='_quoteLine_']")).toHaveCount(quoted.length); }); test("copies a mouse selection with Ctrl+C and pops up no Quote button", async ({ page, context }) => { await context.grantPermissions(["clipboard-read", "clipboard-write"]); const reply = await openReply(page, "Selectable answer"); const box = (await reply.locator("p").first().boundingBox())!; await page.mouse.move(box.x + 2, box.y + box.height / 2); await page.mouse.down(); await page.mouse.move(box.x + box.width - 2, box.y + box.height / 2); await page.mouse.up(); await page.keyboard.press("ControlOrMeta+c"); expect(await page.evaluate(() => navigator.clipboard.readText())).toBe("Selectable answer"); await expect(page.getByRole("button", { name: "Quote", exact: true })).toHaveCount(0); }); test("keeps chat history readable and selections free of timestamps and status labels", async ({ page, context }) => { await page.setViewportSize({ width: 1800, height: 1000 }); await context.grantPermissions(["clipboard-read", "clipboard-write"]); await openReply(page, "Hi! What would you like to work on?"); await page.evaluate(async (task) => { const path = "/src/features/agents/store.ts"; const store = await import(path); const user = (text: string) => ({ type: "user", text, attachments: [], sentMs: 1, doneMs: 5001, steered: false, }); store.useAgents.setState({ entries: new Map([ [ task.id, [ user("hi"), { type: "agent", text: "Hi! What would you like to work on?" }, user("im bob"), { type: "agent", text: "Hi Bob! What are we working on today?" }, user("yes"), { type: "thought", text: "**Requesting task context**" }, { type: "agent", text: "What would you like me to proceed with?" }, ], ], ]), }); store.openTaskInEditorLocation(task.id); }, TASK); const stream = page.locator("[class*='_stream_']:visible"); const replies = stream.locator("[class*='_reply_']"); await expect(replies).toHaveCount(3); const geometry = await stream.evaluate((root) => { const reply = root.querySelector("[class*='_reply_']")!; const bubble = root.querySelector("[class*='_user_']")!; const composer = root .closest("[class*='_conversation_']")! .querySelector("[class*='_composerArea_']")!; const rr = reply.getBoundingClientRect(); const br = bubble.getBoundingClientRect(); const cr = composer.getBoundingClientRect(); return { reply: rr.width, root: root.clientWidth, bubbleLeft: br.left, replyLeft: rr.left, bubbleRight: br.right, replyRight: rr.right, columnCenter: (() => { const column = reply.closest("[class*='_agentMessage_']")!.getBoundingClientRect(); return (column.left + column.right) / 2; })(), composerCenter: (cr.left + cr.right) / 2, }; }); expect(geometry.reply).toBeGreaterThan(0); expect(geometry.reply).toBeLessThan(geometry.root); expect(geometry.bubbleLeft).toBeGreaterThan(geometry.replyLeft); expect(geometry.bubbleRight).toBeGreaterThan(geometry.replyRight); expect(Math.abs(geometry.columnCenter - geometry.composerCenter)).toBeLessThan(1); await stream.getByText("hi", { exact: true }).hover(); await expect(stream.locator("[class*='_messageTime_']").first()).toBeVisible(); const selected = await stream.evaluate((root) => { const range = document.createRange(); range.selectNodeContents(root); const selection = window.getSelection()!; selection.removeAllRanges(); selection.addRange(range); return selection.toString(); }); expect(selected).toContain("hi"); expect(selected).toContain("Hi Bob!"); expect(selected).toContain("What would you like me to proceed with?"); expect(selected).not.toMatch(/AM|PM|5s|Reasoning|Requesting task context/); await page.keyboard.press("ControlOrMeta+c"); expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(selected); // The finished turn's reasoning is folded with its work. await stream.locator("[class*='_turnFold_'] > summary").click(); await stream.locator("[class*='_thought_'] > summary").click(); await expect(stream.locator("[class*='_thoughtPreview_']")).toHaveText("Requesting task context"); await expect(stream.locator("[class*='_thoughtBody_'] strong")).toHaveText("Requesting task context"); await page.evaluate(async (id) => { const path = "/src/features/agents/store.ts"; const store = await import(path); store.dockTask(id); }, TASK.id); await expect(stream).toBeVisible(); const narrow = await stream.evaluate((root) => ({ width: root.clientWidth, content: root.scrollWidth, reply: root.querySelector("[class*='_reply_']")!.getBoundingClientRect().width, padding: Number.parseFloat(getComputedStyle(root).paddingLeft) + Number.parseFloat(getComputedStyle(root).paddingRight), })); expect(narrow.width).toBeGreaterThan(0); expect(narrow.content).toBeLessThanOrEqual(narrow.width); expect(narrow.reply).toBeLessThanOrEqual((narrow.width - narrow.padding) * 0.96); }); test("fits conversation stream, composer, question card and off-screen rows live from Settings without restarting", async ({ page, }) => { await page.setViewportSize({ width: 1800, height: 900 }); await openReply(page, "Initial reply"); await page.evaluate(async (task) => { const storePath = "/src/features/agents/store.ts"; const store = await import(storePath); const filler = Array.from({ length: 8 }, (_, i) => ({ type: "agent" as const, text: `Earlier paragraph ${i + 1}: ` + "wrapped words across the column ".repeat(35), })); store.useAgents.setState({ tasks: new Map([[task.id, { ...task, status: "needsInput" as const }]]), entries: new Map([ [ task.id, [ ...filler, { type: "user", text: "Long prompt ".repeat(40), attachments: [], sentMs: 1, doneMs: 2, steered: false, }, { type: "agent", text: "Wide reply body." }, { type: "permission", id: 1, title: "Choose layout", options: [], chosen: null, questions: [ { header: "Width", question: "Use full window width?", multiSelect: false, options: [{ label: "Yes", description: "Fill the pane", preview: null }], }, ], }, ], ], ]), }); store.openTaskInEditorLocation(task.id); }, TASK); const stream = page.locator("[class*='_stream_']:visible"); await expect(page.getByRole("form", { name: "Choose layout" })).toBeVisible(); await expect(stream.locator("[data-measured]").first()).toBeAttached(); const measure = () => stream.evaluate((root) => { const conversation = root.closest("[class*='_conversation_']")!; const rows = [...root.querySelectorAll("[class*='_conversationRow_']")]; const column = [...root.querySelectorAll("[class*='_agentMessage_']")] .at(-1)! .getBoundingClientRect(); const bubble = root.querySelector("[class*='_user_']")!.getBoundingClientRect(); const composer = conversation.querySelector("[class*='_composerArea_']")!.getBoundingClientRect(); const question = conversation.querySelector("[class*='_questionCard_']")!.getBoundingClientRect(); const padding = Number.parseFloat(getComputedStyle(root).paddingLeft) + Number.parseFloat(getComputedStyle(root).paddingRight); return { conversationWidth: conversation.clientWidth, streamInnerWidth: root.clientWidth - padding, columnWidth: column.width, bubbleWidth: bubble.width, composerWidth: composer.width, questionWidth: question.width, offscreenRowHeight: rows[0]!.getBoundingClientRect().height, scrollHeight: root.scrollHeight, }; }); const capped = await measure(); expect(capped.conversationWidth).toBeGreaterThan(1000); expect(Math.abs(capped.columnWidth - 900)).toBeLessThan(1); expect(Math.abs(capped.bubbleWidth - 720)).toBeLessThan(1); expect(Math.abs(capped.composerWidth - 924)).toBeLessThan(1); expect(Math.abs(capped.questionWidth - 900)).toBeLessThan(1); // Toggle on through Settings › Agents › Chat › Apply and verify live re-layout including off-screen rows. await page.evaluate(async () => { const actionsPath = "/src/platform/actions.ts"; const { executeAction } = await import(actionsPath); await executeAction("file.settings", "agents.chat"); }); const dialog = page.getByRole("dialog", { name: "Settings" }); const toggle = dialog.getByRole("checkbox", { name: "Fit conversation to the window width" }); await expect(toggle).not.toBeChecked(); await toggle.click(); await dialog.getByRole("button", { name: "Apply", exact: true }).click(); await expect(stream.locator("[data-measured]").first()).toBeAttached(); const fitted = await measure(); expect(Math.abs(fitted.columnWidth - fitted.streamInnerWidth)).toBeLessThan(1); expect(fitted.bubbleWidth).toBeGreaterThan(720); expect(Math.abs(fitted.bubbleWidth - fitted.streamInnerWidth * 0.8)).toBeLessThan(1); expect(Math.abs(fitted.composerWidth - fitted.conversationWidth)).toBeLessThan(1); expect(Math.abs(fitted.questionWidth - fitted.streamInnerWidth)).toBeLessThan(1); expect(fitted.offscreenRowHeight).toBeLessThan(capped.offscreenRowHeight); expect(fitted.scrollHeight).toBeLessThan(capped.scrollHeight); // Toggle back off and click OK: dialog closes and conversation returns to the 900px column live. await toggle.click(); await dialog.getByRole("button", { name: "OK", exact: true }).click(); await expect(dialog).toBeHidden(); await expect(stream.locator("[data-measured]").first()).toBeAttached(); const restored = await measure(); expect(Math.abs(restored.columnWidth - 900)).toBeLessThan(1); expect(Math.abs(restored.offscreenRowHeight - capped.offscreenRowHeight)).toBeLessThan(1); }); test("keeps hover actions reachable when the pointer leaves the message body", async ({ page, context }) => { await context.grantPermissions(["clipboard-read", "clipboard-write"]); const reply = await openReply(page, "A short answer."); const copy = page.getByRole("button", { name: "Copy Markdown", exact: true }); await reply.hover(); const box = await copy.boundingBox(); await page.mouse.move(box!.x + box!.width / 2, box!.y + box!.height / 2, { steps: 20, }); await expect(copy.locator("..")).toHaveCSS("opacity", "1"); await copy.click(); expect(await page.evaluate(() => navigator.clipboard.readText())).toBe("A short answer."); }); test("selects through code blocks and tables while keeping copy controls outside the code", async ({ page, context, }) => { await context.grantPermissions(["clipboard-read", "clipboard-write"]); const tree = "rust/\n├── Cargo.toml\n└── src/\n └── main.rs"; const flow = "内置文本 SAMPLE\n ↓ parser::parse\nVec\n ↓ Inventory::add\n终端输出"; const text = `项目结构:\n\n\`\`\`text\n${tree}\n\`\`\`\n\n| 模块 | 职责 |\n| --- | --- |\n| main.rs | 程序入口 |\n\n数据流是:\n\n\`\`\`text\n${flow}\n\`\`\``; const reply = await openReply(page, text); await expect(reply.getByRole("button", { name: "Copy Code", exact: true })).toHaveCount(2); const selected = await reply.evaluate((root) => { const codes = [...root.querySelectorAll("pre > code")]; if (codes.some((code) => code.parentElement!.querySelector("button"))) throw new Error("Control in code selection"); const start = root.querySelector("p")!.firstChild!; const end = codes.at(-1)!.lastChild!; window.getSelection()!.setBaseAndExtent(start, 0, end, end.textContent!.length); return window.getSelection()!.toString(); }); expect(selected).toContain(tree); expect(selected).toContain("程序入口"); expect(selected).toContain(flow); await page.keyboard.press("ControlOrMeta+c"); expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(selected); await page.evaluate(() => window.getSelection()!.removeAllRanges()); const copies = reply.getByRole("button", { name: "Copy Code", exact: true }); await copies.first().click(); expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(tree); await copies.last().click(); expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(flow); }); test("keeps mermaid `