// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation. import { createRequire } from "node:module"; import assert from "node:assert/strict"; import { readFile } from "node:fs/promises"; const require = createRequire(import.meta.url); const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright"); const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) }); const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } }); page.setDefaultTimeout(10000); const errors = []; const showcase = await readFile(new URL("../fixtures/reader-showcase.md", import.meta.url), "utf8"); page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); }); page.on("pageerror", error => errors.push(error.message)); await page.addInitScript(() => { window.isTauri = true; const root = "C:\\smoke-workspace"; const files = new Map([ ["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"], ["notes/second.md", "# Second note\n"], ["src/hello.py", "print('hello')\n"], ]); const callbacks = new Map(); const listeners = new Map(); let sequence = 0; const calls = []; const emit = (event, payload) => { for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload }); }; window.__TAURI_INTERNALS__ = { metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } }, transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; }, unregisterCallback: id => callbacks.delete(id), invoke: async (command, args = {}) => { calls.push({ command, args }); if (command === "plugin:event|listen") { const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler; } if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; } if (command === "workspace_last_path") return root; if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" }; if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); } if (command === "workspace_write") { if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk"); files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return; } if (command === "workspace_list") { const prefix = args.rel ? args.rel + "/" : ""; const entries = new Map(); for (const path of files.keys()) { if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue; const tail = path.slice(prefix.length); const name = tail.split("/")[0]; entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" }); } return [...entries.values()]; } if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; } if (command === "workspace_search") return []; if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }]; if (command === "pty_open") { const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")]; emit("pty-data", { id: args.id, data: data.slice(0, 8) }); emit("pty-data", { id: args.id, data: data.slice(8) }); await new Promise(resolve => setTimeout(resolve, 50)); return; } if (command.startsWith("pty_")) return; if (command === "plugin:dialog|message") return "Cancel"; throw new Error(`Unhandled IPC: ${command}`); }, }; window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) }; window.__TEST__ = { files, calls, emit, root }; }); async function quickOpen(name) { await page.keyboard.press("Control+p"); await page.getByRole("textbox", { name: "Find a file" }).fill(name); await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click(); if (await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).count()) { await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click(); } await page.locator(".monaco-editor textarea").waitFor(); } async function contents() { return page.evaluate(async () => { const { monaco } = await import("/src/lib/editor/monacoEnv.ts"); return monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected)?.getValue(); }); } async function waitForText(text) { await page.evaluate(async () => { window.__MONACO__ = (await import("/src/lib/editor/monacoEnv.ts")).monaco; }); await page.waitForFunction(expected => window.__MONACO__.editor.getEditors().some(editor => editor.getDomNode()?.isConnected && editor.getValue() === expected), text); } async function focusEditor() { await page.locator(".monaco-host .view-lines").click({position:{x:120,y:12}}); } try { await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420"); await page.getByText("smoke-workspace", { exact: true }).waitFor(); await quickOpen("welcome.md"); const original = await contents(); assert.ok(original.startsWith("---\ntitle:")); await focusEditor(); await page.keyboard.press("Control+End"); await page.keyboard.type("Added in source."); await waitForText(original + "Added in source."); await quickOpen("hello.py"); await page.getByRole("tab", { name: /welcome\.md/ }).click(); await focusEditor(); await page.keyboard.press("Control+z"); await page.waitForFunction(expected => window.__MONACO__.editor.getEditors().some(editor => editor.getDomNode()?.isConnected && editor.getValue() !== expected), original + "Added in source."); await page.keyboard.press("Control+y"); await waitForText(original + "Added in source."); await page.keyboard.press("Control+s"); await page.waitForFunction(expected => window.__TEST__.files.get("notes/welcome.md") === expected, original + "Added in source."); await page.getByRole("button", { name: "Split", exact: true }).click(); await page.locator(".md-page h1").first().waitFor(); assert.ok(await page.locator(".monaco-host").isVisible()); await page.evaluate(() => { window.__TEST__.files.set("notes/welcome.md", "# Agent update\n"); window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "modify", paths: ["notes/welcome.md"] }); }); await waitForText("# Agent update\n"); await focusEditor(); await page.keyboard.press("Control+End"); await page.keyboard.type("Local edit"); await page.evaluate(() => { window.__TEST__.files.set("notes/welcome.md", "# Another agent edit\n"); window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "modify", paths: ["notes/welcome.md"] }); }); await page.getByRole("button", { name: "Keep my edits" }).waitFor(); assert.equal(await contents(), "# Agent update\nLocal edit"); await page.getByRole("button", { name: "Keep my edits" }).click(); await page.keyboard.press("Control+s"); await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md") === "# Agent update\nLocal edit"); await page.getByRole("button", { name: "Terminal", exact: true }).click(); await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_open")); await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_write" && /\x1b\[\d+;\d+R/.test(c.args.data))); await page.screenshot({ path: ".audit/core-rebuild-terminal.png" }); await page.getByRole("button", { name: "Hide terminal (sessions keep running)" }).click(); assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_close").length), 0); await page.getByRole("button", { name: "Terminal", exact: true }).click(); assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_open").length), 1); await page.getByRole("button", { name: "New terminal", exact: true }).click(); await page.waitForFunction(() => window.__TEST__.calls.filter(c => c.command === "pty_open").length === 2); await page.getByRole("button", { name: "Kill terminal", exact: true }).first().click(); await page.waitForFunction(() => window.__TEST__.calls.filter(c => c.command === "pty_close").length === 1); await page.getByRole("button", { name: "Hide terminal (sessions keep running)" }).click(); await page.keyboard.press("Control+n"); await page.getByLabel("New file path relative to the workspace").fill("notes/new-note.md"); await page.getByRole("button", { name: "Continue", exact: true }).click(); await page.getByRole("tab", { name: "new-note.md", exact: true }).waitFor(); await page.screenshot({ path: ".audit/core-rebuild.png" }); await page.evaluate(text => { window.__TEST__.files.set("reader-showcase.md", text); window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "create", paths: ["reader-showcase.md"] }); }, showcase); await quickOpen("reader-showcase.md"); const read = page.getByRole("button", { name: "Read", exact: true }); assert.equal(await read.innerText(), ""); assert.equal(await read.locator("svg").count(), 1); await read.hover(); await page.getByRole("tooltip", { name: "Read", exact: true }).waitFor({ state: "visible" }); const tip = await page.getByRole("tooltip", { name: "Read", exact: true }).boundingBox(); assert.ok(tip.x >= 0 && tip.x + tip.width <= 1440); await read.click(); assert.equal(await read.getAttribute("aria-pressed"), "true"); await page.locator(".reading h1:not(.document-title)").waitFor(); assert.equal(await page.locator(".monaco-host").isVisible(), false); assert.equal(await page.locator(".reading h1:not(.document-title)").innerText(), "Project field notes"); assert.equal(await page.locator(".reading ol > li").count(), 3); assert.equal(await page.locator(".reading ol ul > li").count(), 2); assert.equal(await page.locator(".reading input:checked").count(), 2); assert.equal(await page.locator(".md-properties").getAttribute("open"), null); assert.ok((await page.locator(".reading > p").first().innerText()).includes("implementation notes")); const surface = await page.locator(".reading").boundingBox(); assert.ok(surface.width <= 741); await page.mouse.move(700, 980); await page.screenshot({ path: ".audit/reader-mode.png" }); await page.locator(".md-table-scroll").scrollIntoViewIfNeeded(); await page.getByRole("button", { name: "Copy code", exact: true }).click(); await page.getByRole("button", { name: "Copied", exact: true }).waitFor(); await page.screenshot({ path: ".audit/reader-details.png" }); await page.setViewportSize({ width: 1000, height: 900 }); await page.locator(".md-page").evaluate(element => { element.scrollTop = 0; }); await page.screenshot({ path: ".audit/reader-narrow.png" }); assert.ok(await page.locator(".md-page").evaluate(element => element.scrollWidth <= element.clientWidth + 1)); await page.getByRole("button", { name: "Split", exact: true }).click(); await page.waitForFunction(() => { const host = document.querySelector(".monaco-host"); const rendered = host?.querySelector(".monaco-editor"); return rendered && Math.abs(host.clientWidth - rendered.clientWidth) < 2; }); assert.equal(await page.locator(".body.split").evaluate(element => getComputedStyle(element).flexDirection), "column"); await page.screenshot({ path: ".audit/reader-split.png" }); assert.ok(await page.locator(".md-page").evaluate(element => element.scrollWidth <= element.clientWidth + 1)); await page.setViewportSize({ width: 1440, height: 1000 }); await page.waitForFunction(() => getComputedStyle(document.querySelector(".body.split")).flexDirection === "row"); await page.screenshot({ path: ".audit/reader-split-wide.png" }); await page.getByRole("button", { name: "Edit", exact: true }).click(); assert.equal(await contents(), showcase); assert.equal(await page.evaluate(() => window.__TEST__.files.get("reader-showcase.md")), showcase); await page.getByRole("button", { name: "Read", exact: true }).focus(); await page.getByRole("tooltip", { name: "Read", exact: true }).waitFor({ state: "visible" }); await page.keyboard.press("Escape"); await page.getByRole("tooltip", { name: "Read", exact: true }).waitFor({ state: "hidden" }); // Continuous live Markdown: only active lines reveal source; checkboxes // remain inline and update the original file without HTML serialization. const writingSource = '---\ntitle: Preserved\n---\n\n# Writer preview\n\nA **formatted** paragraph.\n\n[Project link](https://example.com/old)\n\n- [ ] Ship draft\n- [x] Finished task\n\n```mermaid\nflowchart LR\n A[Draft] --> B[Publish]\n```\n\n```mermaid\nnot a valid diagram\n```\n\n- Parent\n - Child\n'; await page.evaluate(text => { window.__TEST__.files.set("writing.md", text); window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "create", paths: ["writing.md"] }); }, writingSource); await quickOpen("writing.md"); await page.getByRole("button", { name: "Switch to writing layout (Ctrl E)", exact: true }).click(); const writer = page.getByRole("textbox", { name: "Writing editor", exact: true }); await writer.waitFor(); assert.equal(await page.locator('.live-writer [contenteditable="true"]').count(), 1); assert.equal(await page.getByRole("toolbar", { name: "Text formatting" }).count(), 0); await page.locator(".live-writer .md-diagram svg").waitFor({ timeout: 30000 }); await page.getByRole("status").filter({ hasText: "Diagram could not render" }).waitFor(); const paragraph = page.locator(".live-writer .cm-line").filter({ hasText: "A formatted paragraph." }); await paragraph.click(); await page.locator(".live-writer .cm-line").filter({ hasText: "A **formatted** paragraph." }).waitFor(); await page.keyboard.press("Home"); await page.keyboard.type("New "); await page.keyboard.press("Control+s"); const editedSource = writingSource.replace("A **formatted**", "New A **formatted**"); await page.waitForFunction(text => window.__TEST__.files.get("writing.md") === text, editedSource); await page.keyboard.press("Control+z"); await page.keyboard.press("Control+s"); await page.waitForFunction(text => window.__TEST__.files.get("writing.md") === text, writingSource); await page.keyboard.press("Control+y"); await page.keyboard.press("Control+s"); await page.waitForFunction(text => window.__TEST__.files.get("writing.md") === text, editedSource); await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click(); await waitForText(editedSource); await focusEditor(); await page.keyboard.press("Control+z"); await waitForText(writingSource); await page.getByRole("button", { name: "Switch to writing layout (Ctrl E)", exact: true }).click(); await writer.waitFor(); await paragraph.click(); await page.keyboard.press("End"); await page.keyboard.press("Enter"); await page.keyboard.press("Enter"); await page.keyboard.type("First new paragraph."); await page.keyboard.press("Enter"); await page.keyboard.press("Enter"); await page.keyboard.type("**Second new paragraph.**"); await page.keyboard.press("Enter"); await page.keyboard.press("Enter"); await page.keyboard.type("Third new paragraph."); assert.equal(await page.locator(".live-writer .writer-strong").filter({ hasText: "Second new paragraph." }).count(), 1); await page.keyboard.press("Home"); await page.keyboard.press("Shift+ArrowUp"); await page.keyboard.press("Shift+ArrowUp"); assert.ok((await page.evaluate(() => window.getSelection().toString())).includes("Second new paragraph.")); await page.keyboard.press("Backspace"); await page.keyboard.press("Control+z"); await page.keyboard.press("Control+s"); await page.waitForFunction(() => window.__TEST__.files.get("writing.md").includes("First new paragraph.\n\n**Second new paragraph.**\n\nThird new paragraph.")); assert.ok(await writer.evaluate(el => el.contains(document.activeElement))); // Link syntax becomes editable on a normal click, without opening the link. await page.locator('.live-writer .writer-link').filter({ hasText: "Project link" }).click(); await page.locator('.live-writer .cm-line').filter({ hasText: "[Project link](https://example.com/old)" }).waitFor(); await page.keyboard.press("End"); await page.keyboard.press("Home"); await page.keyboard.press("Shift+End"); await page.keyboard.type("[Project link](https://example.com/new)"); await page.keyboard.press("ArrowDown"); await page.locator('.live-writer [data-href="https://example.com/new"]').waitFor(); const task = page.locator('.live-writer .cm-line').filter({ hasText: "Ship draft" }); const checkbox = task.getByRole("checkbox"); assert.ok(await task.evaluate(line => { const box = line.querySelector('input').getBoundingClientRect(); const text = [...line.childNodes].find(node => node.nodeType === Node.TEXT_NODE && node.textContent.includes('Ship draft')); const range = document.createRange(); range.selectNode(text); const label = range.getBoundingClientRect(); return Math.abs((box.top + box.bottom) / 2 - (label.top + label.bottom) / 2) < 8 && box.right <= label.left; })); await checkbox.click(); await task.locator('.writer-completed').waitFor(); assert.equal(await task.locator('.writer-completed').evaluate(el => getComputedStyle(el).textDecorationLine), 'line-through'); await page.keyboard.press("Control+s"); await page.waitForFunction(() => window.__TEST__.files.get("writing.md").includes('- [x] Ship draft')); await task.locator('.writer-completed').click(); await page.locator('.live-writer .cm-line').filter({ hasText: '- [x] Ship draft' }).waitFor(); await page.keyboard.press("Home"); await page.keyboard.press("Shift+End"); await page.keyboard.type('- [ ] Revised task'); await page.keyboard.press("ArrowUp"); await page.locator('.live-writer .cm-line').filter({ hasText: 'Revised task' }).getByRole('checkbox', { checked: false }).waitFor(); await page.keyboard.press("Control+s"); await page.waitForFunction(() => window.__TEST__.files.get("writing.md").includes('- [ ] Revised task')); await page.locator(".live-writer .md-diagram svg").waitFor(); await page.screenshot({ path: ".audit/writing-continuous.png" }); await page.setViewportSize({ width: 1000, height: 900 }); assert.ok(await page.locator(".cm-scroller").evaluate(el => el.scrollWidth <= el.clientWidth + 1)); await page.evaluate(() => { window.__TEST__.files.set("crlf.md", "# Windows note\r\n\r\nA paragraph.\r\n\r\nTail stays intact.\r\n"); window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "create", paths: ["crlf.md"] }); }); await quickOpen("crlf.md"); await page.getByRole("button", { name: "Switch to writing layout (Ctrl E)", exact: true }).click(); await page.locator(".live-writer .cm-line").filter({ hasText: "A paragraph." }).click(); await page.keyboard.press("Home"); await page.keyboard.type("Changed "); await page.keyboard.press("Control+s"); await page.waitForFunction(() => window.__TEST__.files.get("crlf.md") === "# Windows note\r\n\r\nChanged A paragraph.\r\n\r\nTail stays intact.\r\n"); await page.keyboard.press("Control+n"); await page.getByLabel("New file path relative to the workspace").fill("blank.md"); await page.getByRole("button", { name: "Continue", exact: true }).click(); await writer.waitFor(); await page.keyboard.type("One"); await page.keyboard.press("Enter"); await page.keyboard.type("Two"); await page.keyboard.press("Enter"); await page.keyboard.type("Three"); await page.keyboard.press("Control+s"); await page.waitForFunction(() => window.__TEST__.files.get("blank.md").replace(/\r\n/g, "\n") === "One\nTwo\nThree"); await page.getByRole("tab", { name: "crlf.md", exact: true }).click(); await page.getByRole("tab", { name: "blank.md", exact: true }).click(); await writer.waitFor(); await page.keyboard.press("Control+z"); await page.keyboard.press("Control+s"); await page.waitForFunction(() => window.__TEST__.files.get("blank.md").replace(/\r\n/g, "\n") !== "One\nTwo\nThree"); await page.keyboard.press("Control+y"); await page.keyboard.press("Control+s"); await page.waitForFunction(() => window.__TEST__.files.get("blank.md").replace(/\r\n/g, "\n") === "One\nTwo\nThree"); await page.keyboard.press("Control+f"); await page.getByRole("textbox", { name: "Find", exact: true }).fill("Two"); await page.keyboard.press("Escape"); await page.keyboard.press("Control+a"); await page.keyboard.type("- [ ] First task"); await page.keyboard.press("Enter"); await page.keyboard.type("Second task"); await page.keyboard.press("Control+s"); await page.waitForFunction(() => window.__TEST__.files.get("blank.md").replace(/\r\n/g, "\n") === "- [ ] First task\n- [ ] Second task"); await page.evaluate(() => { window.__TEST__.files.set("blank.md", "Fresh disk version\r\n"); window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "modify", paths: ["blank.md"] }); }); await page.locator('.live-writer .cm-line').filter({ hasText: 'Fresh disk version' }).waitFor(); await page.keyboard.press("Control+z"); assert.ok((await writer.innerText()).includes("Fresh disk version")); const tableSource = '# Table layout\n\n| Ticker | Name | Exchange | Products/Service | Notes |\n| :--- | --- | --- | --- | --- |\n| IBKR.US | Interactive Brokers Group Inc | NASDAQ | Broker | Rebuild the trading interface.
Keep listings consistent.
Introduce automated investing.
Make the API usable and document common errors. |\n| CBOE.US | Cboe Global Markets Inc | BATS | Exchange | Operations;
- Trading |\n\nAfter the table.\n'; await page.evaluate(text => { window.__TEST__.files.set("tables.md", text); window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "create", paths: ["tables.md"] }); }, tableSource); await page.setViewportSize({ width: 1440, height: 1000 }); await quickOpen("tables.md"); await page.getByRole("button", { name: "Switch to writing layout (Ctrl E)", exact: true }).click(); const table = page.locator('.live-writer table'); await table.waitFor(); assert.equal(await page.locator('.live-writer .document-title').innerText(), 'tables'); const tableHeading = page.locator('.live-writer .writer-heading'); await tableHeading.click(); assert.equal(await tableHeading.innerText(), '# Table layout'); await table.locator('tbody tr').first().locator('td').first().click(); await page.waitForFunction(() => document.querySelector('.live-writer .writer-heading')?.textContent === 'Table layout'); await page.waitForFunction(() => [...document.querySelectorAll('.table-add')].every(button => getComputedStyle(button).opacity === '0')); await page.keyboard.press('Control+s'); assert.equal(await page.evaluate(() => window.__TEST__.files.get('tables.md')), tableSource); assert.equal(await table.locator('th').count(), 5); assert.equal(await table.locator('tbody tr').count(), 2); assert.equal(await table.locator('br').count(), 4); assert.ok(!(await table.innerText()).includes('
')); assert.ok(await table.locator('th').evaluateAll(cells => cells.every(cell => cell.getBoundingClientRect().width >= 100))); assert.ok(await table.locator('td').evaluateAll(cells => cells.every(cell => getComputedStyle(cell).verticalAlign === 'top'))); assert.ok(await page.locator('.cm-scroller').evaluate(el => el.scrollWidth <= el.clientWidth + 1)); const addColumn = page.getByRole('button', { name: 'Add column to the right', exact: true }); const addRow = page.getByRole('button', { name: 'Add row below', exact: true }); await addColumn.hover(); await page.waitForFunction(() => getComputedStyle(document.querySelector('.table-add-column')).opacity === '1'); assert.equal(await addRow.evaluate(el => getComputedStyle(el).opacity), '0'); await table.locator('td').first().hover(); await page.waitForFunction(() => [...document.querySelectorAll('.table-add')].every(button => getComputedStyle(button).opacity === '0')); await addColumn.hover(); await page.waitForFunction(() => getComputedStyle(document.querySelector('.table-add-column')).opacity === '1'); await page.screenshot({ path: '.audit/writing-table-column.png' }); await addColumn.click(); await page.waitForFunction(() => document.querySelectorAll('.live-writer th').length === 6); await addRow.hover(); await page.waitForFunction(() => getComputedStyle(document.querySelector('.table-add-row')).opacity === '1'); await page.screenshot({ path: '.audit/writing-table-row.png' }); await addRow.click(); await page.waitForFunction(() => document.querySelectorAll('.live-writer tbody tr').length === 3); await page.keyboard.press('Control+s'); await page.waitForFunction(() => window.__TEST__.files.get('tables.md').includes('| | | | | | |')); assert.ok((await page.evaluate(() => window.__TEST__.files.get('tables.md'))).endsWith('\n\nAfter the table.\n')); await page.keyboard.press('Control+z'); await page.waitForFunction(() => document.querySelectorAll('.live-writer tbody tr').length === 2); await page.keyboard.press('Control+z'); await page.keyboard.press('Control+s'); await page.waitForFunction(expected => window.__TEST__.files.get('tables.md') === expected, tableSource); await page.keyboard.press('Control+y'); await page.keyboard.press('Control+y'); await table.locator('th').last().click(); const cellEditor = page.locator('.writer-cell-editor'); await cellEditor.waitFor(); assert.equal(await table.locator('th').count(), 6); assert.equal(await page.locator('.live-writer .cm-line').filter({ hasText: '| Ticker |' }).count(), 0); await page.keyboard.type('New column'); await page.keyboard.press('Control+s'); await page.waitForFunction(() => window.__TEST__.files.get('tables.md').includes('New column')); await page.keyboard.press('Tab'); assert.ok(await table.locator('tbody tr').first().locator('td').first().locator('.writer-cell-editor').count()); await page.keyboard.press('Shift+Tab'); assert.ok(await table.locator('th').last().locator('.writer-cell-editor').count()); await table.locator('tbody tr').first().locator('td').nth(4).click(); assert.equal(await cellEditor.locator('br:not(.ProseMirror-trailingBreak)').count(), 3); await page.keyboard.press('Control+End'); await page.keyboard.press('Enter'); await page.keyboard.type('Plain | pipe and *stars*'); await page.keyboard.press('Control+s'); await page.waitForFunction(() => window.__TEST__.files.get('tables.md').includes('
Plain \\| pipe and \\*stars\\*')); assert.equal(await table.locator('th').count(), 6); await page.screenshot({ path: '.audit/writing-table-cell-edit.png' }); await page.keyboard.press('Control+z'); await page.keyboard.press('Control+s'); await page.waitForFunction(() => !window.__TEST__.files.get('tables.md').includes('Plain')); await cellEditor.waitFor(); await page.keyboard.press('Control+y'); await page.keyboard.press('Control+s'); await page.waitForFunction(() => window.__TEST__.files.get('tables.md').includes('Plain')); await page.keyboard.press('Escape'); await page.locator('.live-writer .cm-line').filter({ hasText: 'After the table.' }).click(); const beforeVisit = await page.evaluate(() => window.__TEST__.files.get('tables.md')); await table.locator('tbody tr').first().locator('td').nth(4).click(); await page.keyboard.press('Escape'); await page.keyboard.press('Control+s'); assert.equal(await page.evaluate(() => window.__TEST__.files.get('tables.md')), beforeVisit); await table.locator('tbody tr').last().locator('td').last().click(); await page.keyboard.press('Tab'); await page.waitForFunction(() => document.querySelectorAll('.live-writer tbody tr').length === 4); await table.locator('tbody tr').last().locator('td').first().locator('.writer-cell-editor').waitFor(); await page.keyboard.press('Escape'); await page.setViewportSize({ width: 1000, height: 900 }); assert.ok(await page.locator('.cm-scroller').evaluate(el => el.scrollWidth <= el.clientWidth + 1)); await page.getByRole('button', { name: 'Read', exact: true }).click(); assert.equal(await page.locator('.md-page .document-title').innerText(), 'tables'); assert.equal(await page.locator('.md-page table br').count(), 5); assert.ok(await page.locator('.md-page').evaluate(el => el.scrollWidth <= el.clientWidth + 1)); const selectionTable = '| A | B | C |\n| --- | --- | --- |\n| one | two | three |\n| four | five | six |\n\nAfter.\n'; await page.evaluate(text => { window.__TEST__.files.set('selection-table.md', text); window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['selection-table.md'] }); window.__TEST__.clipboard = ''; Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText: async text => { window.__TEST__.clipboard = text; }, readText: async () => window.__TEST__.clipboard, } }); }, selectionTable); await quickOpen('selection-table.md'); await page.getByRole('button', { name: 'Edit', exact: true }).click(); await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click(); const selectedTable = page.locator('.live-writer table'); const selectedCell = (r, c) => selectedTable.locator('tr').nth(r).locator('th, td').nth(c); const fromCell = await selectedCell(1, 0).boundingBox(), toCell = await selectedCell(2, 1).boundingBox(); await page.mouse.move(fromCell.x + 15, fromCell.y + 15); await page.mouse.down(); await page.mouse.move(toCell.x + 15, toCell.y + 15, { steps: 12 }); await page.mouse.up(); assert.equal(await selectedTable.locator('.is-cell-selected').count(), 4); await selectedCell(1, 0).click({ button: 'right' }); await page.getByRole('menuitem', { name: 'Format', exact: true }).hover(); await page.getByRole('menuitem', { name: 'Bold', exact: true }).waitFor(); await page.screenshot({ path: '.audit/table-cell-selection-menu.png' }); await page.getByRole('menuitem', { name: 'Bold', exact: true }).click(); await page.waitForFunction(() => document.querySelectorAll('.live-writer table strong').length === 4); await page.waitForFunction(() => document.querySelectorAll('.is-cell-selected').length === 4); await page.keyboard.press('Control+i'); await page.waitForFunction(() => document.querySelectorAll('.live-writer table em').length === 4); await page.keyboard.press('Control+z'); await page.waitForFunction(() => document.querySelectorAll('.live-writer table em').length === 0); assert.equal(await selectedTable.locator('strong').count(), 4); await selectedCell(1, 0).click(); await selectedCell(2, 1).click({ modifiers: ['Shift'] }); assert.equal(await selectedTable.locator('.is-cell-selected').count(), 4); async function cellAction(name, formatted = false) { await selectedTable.locator('.is-cell-selected').first().click({ button: 'right' }); if (formatted) await page.getByRole('menuitem', { name: 'Format', exact: true }).hover(); await page.getByRole('menuitem', { name, exact: true }).click(); } await cellAction('Clear formatting', true); await page.waitForFunction(() => document.querySelectorAll('.live-writer table strong').length === 0); await cellAction('Copy'); assert.equal(await page.evaluate(() => window.__TEST__.clipboard), 'one\ttwo\nfour\tfive'); await cellAction('Cut'); await page.waitForFunction(() => [...document.querySelectorAll('.is-cell-selected')].every(cell => !cell.textContent.trim())); await cellAction('Paste'); await page.waitForFunction(() => document.querySelector('.live-writer tbody td').textContent === 'one'); await cellAction('Align centre'); await page.waitForFunction(() => [...document.querySelectorAll('.is-cell-selected')].every(cell => cell.style.textAlign === 'center')); for (const [name, selector] of [['Highlight', 'mark'], ['Math', '[data-cell-format="math"]'], ['Comment', '[data-cell-format="comment"]'], ['Code', 'code'], ['Strikethrough', 's']]) { await cellAction(name, true); await page.waitForFunction(selector => document.querySelectorAll(`.live-writer table ${selector}`).length === 4, selector); await cellAction('Clear formatting', true); } // Native clipboard events must operate on the rectangle, including one-step undo. await page.locator('.writer-table').evaluate(el => { const data = new DataTransfer(); data.setData('text/plain', 'red\tblue\ngreen\tyellow'); el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: data, bubbles: true, cancelable: true })); }); await page.waitForFunction(() => document.querySelector('.live-writer tbody td').textContent === 'red'); await page.keyboard.press('Control+z'); await page.waitForFunction(() => document.querySelector('.live-writer tbody td').textContent === 'one'); await selectedCell(1, 0).click(); await selectedCell(2, 1).click({ modifiers: ['Shift'] }); await cellAction('Delete cells'); await page.waitForFunction(() => document.querySelector('.live-writer tbody td').textContent === 'three'); assert.equal(await selectedTable.locator('th').count(), 3); await page.keyboard.press('Control+z'); await page.waitForFunction(() => document.querySelector('.live-writer tbody td').textContent === 'one'); await selectedCell(1, 0).click(); await selectedCell(1, 0).click({ modifiers: ['Shift'] }); await page.keyboard.press('Control+a'); assert.equal(await selectedTable.locator('.is-cell-selected').count(), 9); await cellAction('Delete cells'); await page.waitForFunction(() => document.querySelectorAll('.live-writer table').length === 0); await page.keyboard.press('Control+z'); await selectedTable.waitFor(); for (const [name, selector] of [['Highlight', 'mark'], ['Math', '[data-cell-format="math"]'], ['Comment', '[data-cell-format="comment"]']]) { await selectedCell(1, 0).click(); await selectedCell(1, 0).click({ modifiers: ['Shift'] }); await selectedCell(1, 0).click({ button: 'right' }); await page.getByRole('menuitem', { name: 'Format', exact: true }).hover(); await page.getByRole('menuitem', { name, exact: true }).click(); await selectedCell(1, 0).click(); await page.keyboard.press('Control+End'); await page.keyboard.type(' edited'); await page.keyboard.press('Escape'); assert.ok(await selectedCell(1, 0).locator(selector).count(), `${name} survives cell editing`); await selectedCell(1, 0).click(); await selectedCell(1, 0).click({ modifiers: ['Shift'] }); await selectedCell(1, 0).click({ button: 'right' }); await cellAction('Clear formatting', true); } const actionsSource = '| Name | Value |\n| :--- | ---: |\n| Interactive Brokers Group | 20 |\n| Apple | 3 |\n| Pear | 10 |\n\nAfter.\n'; await page.evaluate(text => { window.__TEST__.files.set('table-actions.md', text); window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['table-actions.md'] }); }, actionsSource); await quickOpen('table-actions.md'); await page.getByRole('button', { name: 'Edit', exact: true }).click(); await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click(); const actionTable = page.locator('.live-writer table'); const actionCell = (r, c) => actionTable.locator('tr').nth(r).locator('th, td').nth(c); async function actionItem(label, group, r = 1, c = 0) { await actionCell(r, c).click({ button: 'right' }); if (group) await page.getByRole('menuitem', { name: group, exact: true }).hover(); await page.getByRole('menuitem', { name: label, exact: true }).click(); } async function saveActionSource() { await page.keyboard.press('Control+s'); return page.evaluate(() => window.__TEST__.files.get('table-actions.md')); } async function undoAction() { await page.keyboard.press('Control+z'); await page.keyboard.press('Control+s'); await page.waitForFunction(expected => window.__TEST__.files.get('table-actions.md') === expected, actionsSource); } for (const [label, group, r, c, rows, columns] of [ ['Add row above', 'Row', 1, 0, 5, 2], ['Add row below', 'Row', 2, 0, 5, 2], ['Duplicate row', 'Row', 1, 0, 5, 2], ['Delete row', 'Row', 1, 0, 3, 2], ['Add column to the left', 'Column', 1, 0, 4, 3], ['Add column to the right', 'Column', 1, 1, 4, 3], ['Duplicate column', 'Column', 1, 1, 4, 3], ['Delete column', 'Column', 1, 1, 4, 1], ]) { await actionItem(label, group, r, c); assert.equal(await actionTable.locator('tr').count(), rows, label); assert.equal(await actionTable.locator('th').count(), columns, label); await undoAction(); } await actionItem('Move row down', 'Row'); assert.equal(await actionCell(2, 0).innerText(), 'Interactive Brokers Group'); await undoAction(); await actionItem('Move row up', 'Row', 2); assert.equal(await actionCell(1, 0).innerText(), 'Apple'); await undoAction(); await actionItem('Move column right', 'Column'); assert.equal(await actionCell(0, 0).innerText(), 'Value'); assert.equal(await actionCell(1, 0).evaluate(el => el.style.textAlign), 'right'); await undoAction(); await actionItem('Move column left', 'Column', 1, 1); assert.equal(await actionCell(0, 0).innerText(), 'Value'); await undoAction(); await actionItem('Sort by column (A to Z)', undefined, 1, 1); assert.deepEqual(await actionTable.locator('tbody tr td:last-child').allTextContents(), ['3', '10', '20']); await undoAction(); await actionItem('Sort by column (Z to A)', undefined, 1, 1); assert.deepEqual(await actionTable.locator('tbody tr td:last-child').allTextContents(), ['20', '10', '3']); await undoAction(); await actionCell(0, 0).click({ button: 'right' }); await page.getByRole('menuitem', { name: 'Row', exact: true }).hover(); assert.ok(await page.getByRole('menuitem', { name: 'Add row above', exact: true }).isDisabled()); assert.ok(await page.getByRole('menuitem', { name: 'Move row down', exact: true }).isDisabled()); await page.keyboard.press('Escape'); async function selectBrokers() { await actionCell(1, 0).click(); await page.keyboard.press('Control+Home'); for (let i = 0; i < 12; i++) await page.keyboard.press('ArrowRight'); for (let i = 0; i < 7; i++) await page.keyboard.press('Shift+ArrowRight'); assert.equal(await page.evaluate(() => getSelection().toString()), 'Brokers'); } await selectBrokers(); await actionCell(1, 0).click({ button: 'right' }); assert.equal(await page.getByRole('menuitem', { name: 'Copy', exact: true }).isDisabled(), false); assert.ok(await page.locator('.table-cell-menu button').evaluateAll(buttons => buttons.every(button => button.querySelector('svg[aria-hidden="true"]')))); await page.getByRole('menuitem', { name: 'Row', exact: true }).hover(); await page.screenshot({ path: '.audit/table-text-row-menu.png' }); await page.getByRole('menuitem', { name: 'Column', exact: true }).hover(); await page.screenshot({ path: '.audit/table-text-column-menu.png' }); await page.getByRole('menuitem', { name: 'Column', exact: true }).focus(); await page.keyboard.press('ArrowRight'); assert.equal(await page.evaluate(() => document.activeElement.textContent), 'Add column to the left'); await page.keyboard.press('ArrowLeft'); assert.equal(await page.evaluate(() => document.activeElement.textContent), 'Column'); await page.keyboard.press('Escape'); await actionItem('Bold', 'Format'); assert.equal(await actionCell(1, 0).locator('strong').innerText(), 'Brokers'); assert.ok((await saveActionSource()).includes('Interactive **Brokers** Group')); await actionItem('Add external link'); await page.getByRole('dialog').locator('input').fill('https://example.com/brokers?q=1'); await page.getByRole('button', { name: 'Continue', exact: true }).click(); await page.waitForFunction(() => document.querySelector('.live-writer td a')?.getAttribute('href') === 'https://example.com/brokers?q=1'); assert.equal(await actionCell(1, 0).locator('a').innerText(), 'Brokers'); await page.keyboard.press('Control+z'); await selectBrokers(); await actionItem('Add link'); await page.getByRole('dialog').locator('input').fill('notes/second'); await page.getByRole('button', { name: 'Continue', exact: true }).click(); await page.waitForFunction(() => document.querySelector('.live-writer td a')?.getAttribute('data-kind') === 'wiki'); await page.keyboard.press('Control+z'); await selectBrokers(); await actionItem('Search for “Brokers”'); await page.getByPlaceholder('Search files and notes').waitFor(); assert.equal(await page.getByPlaceholder('Search files and notes').inputValue(), 'Brokers'); await page.waitForFunction(() => window.__TEST__.calls.some(call => call.command === 'workspace_search' && call.args.query === 'Brokers')); await selectBrokers(); await actionItem('Extract current selection…'); await page.getByRole('dialog').locator('input').fill('extracted-brokers.md'); await page.getByRole('button', { name: 'Continue', exact: true }).click(); await page.waitForFunction(() => window.__TEST__.files.get('extracted-brokers.md') === '**Brokers**\n'); await page.waitForFunction(() => document.querySelector('.live-writer td a')?.getAttribute('href') === '/extracted-brokers.md'); await page.keyboard.press('Control+z'); await selectBrokers(); await page.evaluate(() => { window.__TEST__.clipboard = 'literal\nnext'; }); await actionItem('Paste as plain text'); assert.ok((await saveActionSource()).includes('Interactive <') || (await saveActionSource()).includes('Interactive \\literal\\
next')); assert.equal(await actionCell(1, 0).locator('b').count(), 0); await page.keyboard.press('Control+z'); await selectBrokers(); await page.evaluate(() => { navigator.clipboard.read = async () => [{ types: ['text/html', 'text/plain'], getType: async type => new Blob([type === 'text/html' ? 'Rich paste' : 'Rich paste'], { type }) }]; }); await actionItem('Paste'); await page.waitForFunction(() => document.querySelector('.live-writer td em')?.textContent === 'Rich paste'); await page.keyboard.press('Control+z'); await page.evaluate(() => { delete navigator.clipboard.read; }); await selectBrokers(); await actionItem('Copy'); assert.equal(await page.evaluate(() => window.__TEST__.clipboard), 'Brokers'); await actionItem('Cut'); await page.waitForFunction(() => !document.querySelector('.live-writer td').textContent.includes('Brokers')); await page.keyboard.press('Control+z'); await selectBrokers(); await actionItem('Select all'); assert.equal(await page.evaluate(() => getSelection().toString()), 'Interactive Brokers Group'); await page.setViewportSize({ width: 800, height: 600 }); await actionCell(1, 0).click({ button: 'right' }); await page.getByRole('menuitem', { name: 'Column', exact: true }).hover(); assert.ok(await page.locator('.table-cell-menu, .table-cell-submenu:not([hidden])').evaluateAll(panels => panels.every(panel => { const rect = panel.getBoundingClientRect(); return rect.left >= 0 && rect.top >= 0 && rect.right <= innerWidth && rect.bottom <= innerHeight; }))); await page.keyboard.press('Escape'); await page.setViewportSize({ width: 1000, height: 900 }); const richTable = '| Name | Notes |\r\n| :--- | ---: |\r\n| Untouched | ~~Old~~ **bold** [link](https://example.com) ![attachment](missing.png)
Next |\r\n| Short |\r\n'; await page.evaluate(text => { window.__TEST__.files.set('rich-table.md', text); window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['rich-table.md'] }); }, richTable); await quickOpen('rich-table.md'); await page.getByRole('button', { name: 'Edit', exact: true }).click(); await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click(); const richCell = page.locator('.live-writer tbody tr').first().locator('td').last(); assert.equal(await page.locator('.live-writer .document-title').innerText(), 'rich-table'); await richCell.click(); await page.keyboard.press('Control+s'); assert.equal(await page.evaluate(() => window.__TEST__.files.get('rich-table.md')), richTable); await page.keyboard.press('Control+End'); await page.keyboard.type(' edited'); await page.keyboard.press('Control+s'); await page.waitForFunction(() => window.__TEST__.files.get('rich-table.md').includes('edited')); const richSaved = await page.evaluate(() => window.__TEST__.files.get('rich-table.md')); assert.ok(richSaved.includes('| Untouched |')); assert.ok(richSaved.includes('~~Old~~')); assert.ok(richSaved.includes('**bold**')); assert.ok(richSaved.includes('https://example.com')); assert.ok(richSaved.includes('![attachment]()')); assert.ok(richSaved.includes('
Next edited')); assert.ok(!/(? window.__TEST__.files.get('rich-table.md').includes('Next edited again')); const shortCell = page.locator('.live-writer tbody tr').last().locator('td').last(); await shortCell.click(); await cellEditor.evaluate(el => { const data = new DataTransfer(); data.setData('text/plain', 'Pasted | text\nSecond line'); el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: data, bubbles: true, cancelable: true })); }); await page.keyboard.press('Control+s'); await page.waitForFunction(() => window.__TEST__.files.get('rich-table.md').includes('Pasted \\| text
Second line')); await page.keyboard.press('Control+a'); await page.keyboard.press('Control+b'); await page.keyboard.press('Control+s'); await page.waitForFunction(() => window.__TEST__.files.get('rich-table.md').includes('**Pasted \\| text**')); assert.equal(await page.locator('.live-writer th').count(), 2); // Physical mouse coordinates below tall block widgets must resolve to the // visible line, including immediately adjacent heading/body lines. const longTable = '| Ticker | Name | Notes |\n| --- | --- | --- |\n' + Array.from({ length: 14 }, (_, index) => `| STOCK${index} | Company ${index} | First note
Second note
Third note |`).join('\n'); const hitTestSource = `# Listed\n\n${longTable}\n\n# Tier 1\nTier one body directly below heading.\n\n${longTable}\n\n## Tier 2\nTier two body directly below heading.\n`; await page.evaluate(text => { window.__TEST__.files.set('table-hit-testing.md', text); window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['table-hit-testing.md'] }); }, hitTestSource); await quickOpen('table-hit-testing.md'); await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click(); async function clickRenderedLine(locator, expected) { await locator.scrollIntoViewIfNeeded(); const rect = await locator.boundingBox(); assert.ok(rect); await page.mouse.click(rect.x + 45, rect.y + rect.height * .7); const actual = await page.evaluate(() => window.getSelection()?.anchorNode?.parentElement?.closest('.cm-line')?.textContent); assert.equal(actual, expected, `Mouse click on ${expected} landed on ${actual}`); } async function checkLinesAfterTables() { await page.locator('.cm-scroller').evaluate(async el => { el.scrollTop = 0; await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))); }); for (const [heading, body] of [ ['# Tier 1', 'Tier one body directly below heading.'], ['## Tier 2', 'Tier two body directly below heading.'], ]) { const tables = page.locator('.live-writer .writer-table'); await (heading === '# Tier 1' ? tables.first() : tables.last()).locator('.table-add-row').scrollIntoViewIfNeeded(); await clickRenderedLine(page.locator('.live-writer .writer-heading').filter({ hasText: heading.replace(/^#+ /, '') }), heading); await page.keyboard.press('End'); await page.keyboard.type(' edited'); await page.keyboard.press('Control+s'); await page.waitForFunction(text => window.__TEST__.files.get('table-hit-testing.md').includes(text + ' edited\n'), heading); await page.keyboard.press('Control+z'); await clickRenderedLine(page.locator('.live-writer .cm-line').filter({ hasText: body }), body); } } await page.setViewportSize({ width: 1440, height: 1000 }); await checkLinesAfterTables(); await page.locator('.cm-scroller').evaluate(async el => { el.scrollTop = 0; await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))); }); await page.locator('.live-writer table').first().locator('tbody tr').last().locator('td').last().click(); await page.keyboard.press('Control+End'); for (let line = 0; line < 4; line++) { await page.keyboard.press('Enter'); await page.keyboard.type('A newly added line changes the table height.'); } await checkLinesAfterTables(); await page.setViewportSize({ width: 1000, height: 900 }); await checkLinesAfterTables(); await page.screenshot({ path: '.audit/table-cursor-position.png' }); assert.deepEqual(errors, []); console.log("PASS: continuous live Markdown, raw active lines, editable links and checklists, completed-task strikethrough, cross-line selection, preservation and history, search, table layout/line breaks/edge insertion/cell editing/undo, save, agent refresh, conflicts, persistent terminals, reader and Mermaid previews, narrow layouts (mocked desktop IPC)."); } catch (error) { console.error("Browser errors:", errors); console.error("Writing source:", await page.evaluate(() => window.__TEST__?.files.get("writing.md"))); console.error("Visible text:", (await page.locator("body").innerText()).slice(0, 5000)); await page.screenshot({ path: ".audit/core-rebuild-failure.png" }); throw error; } finally { await browser.close(); }