// Core workbench: source edits and history, agent refresh and conflicts, persistent terminals, Reading and Mermaid previews, the live Writer, tables and their menus, and narrow layouts.
// @requires plugin:terminal
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import path from "node:path";
import { chooseView, mockTauri, outputDir, repoRoot, runSmoke, smokeUrl } from "../_harness/index.mjs";
import { mockFeaturePlugins } from "../_harness/pluginMocks.mjs";
await runSmoke("layout/workbench", async ({ page }) => {
const output = await outputDir("layout/workbench");
const showcase = await readFile(path.join(repoRoot, "fixtures/reader-showcase.md"), "utf8");
await mockTauri(page, {
commands: test => {
const workspace = test.workspace({
root: "C:\\smoke-workspace",
writeEvents: true,
files: {
"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",
},
});
Object.assign(test, { files: workspace.files, root: workspace.root });
// The terminal plug-in opens shells through these commands.
const pty = {};
for (const command of ["pty_write", "pty_resize", "pty_close"]) pty[command] = () => {};
return {
...workspace,
...pty,
workspace_write: args => {
if (args.expected !== undefined && workspace.files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
return workspace.workspace_write(args);
},
workspace_search: () => [],
pty_profiles: () => [{ id: "powershell", title: "PowerShell", kind: "powershell" }],
pty_open: async args => {
const data = new TextEncoder().encode("READY 🪨\r\n\x1b[6n");
// A Terminal plugin that uses api.pty passes a channel and gets raw bytes. Released versions listen for events.
if (args.channel) setTimeout(() => { args.channel.onmessage(data.slice(0, 8).buffer); args.channel.onmessage(data.slice(8).buffer); }, 0);
else {
test.emit("pty-data", { id: args.id, data: [...data.slice(0, 8)] });
test.emit("pty-data", { id: args.id, data: [...data.slice(8)] });
}
await new Promise(resolve => setTimeout(resolve, 50));
},
"plugin:dialog|message": () => "Cancel",
};
},
});
await mockFeaturePlugins(page);
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();
await chooseView(page, "Source");
await page.locator(".source-editor .cm-content").waitFor();
}
async function contents() {
return page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
return EditorView.findFromDOM(document.querySelector(".source-editor .cm-content"))?.state.doc.toString();
});
}
async function waitForText(text) {
await page.evaluate(async () => { window.__EditorView = (await import("/node_modules/@codemirror/view/dist/index.js")).EditorView; });
await page.waitForFunction(expected => window.__EditorView.findFromDOM(document.querySelector(".source-editor .cm-content"))?.state.doc.toString() === expected, text);
}
async function focusEditor() {
await page.locator(".source-editor .cm-content").click({position:{x:120,y:12}});
}
await page.goto(smokeUrl);
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.__EditorView.findFromDOM(document.querySelector(".source-editor .cm-content"))?.state.doc.toString() !== 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 chooseView(page, "Split");
await page.locator(".md-page h1").first().waitFor();
assert.ok(await page.locator(".source-editor").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: path.join(output, "core-rebuild-terminal.png") });
await page.getByRole("button", { name: "Terminal", exact: true }).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: "Terminal", exact: true }).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();
// A new note starts in its filename field, which keeps its own keys (src/lib/editor/DocumentEditor.svelte:386-392, src/lib/editor/noteTitle.ts:80).
await page.getByRole("textbox", { name: "Note filename", exact: true }).waitFor();
await page.screenshot({ path: path.join(output, "core-rebuild.png") });
await page.keyboard.press("Escape");
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");
// Each view choice shows an icon and its name. The tooltip adds the shortcut (src/lib/layout/ViewModes.svelte).
const read = page.getByRole("radiogroup", { name: "View", exact: true }).getByRole("radio", { name: "Read", exact: true });
const readTip = page.getByRole("tooltip").filter({ hasText: "Read (Ctrl+Shift+E)" });
assert.equal(await read.innerText(), "Read");
assert.equal(await read.locator("svg").count(), 1);
await read.hover();
await readTip.waitFor({ state: "visible" });
const tip = await readTip.boundingBox();
assert.ok(tip.x >= 0 && tip.x + tip.width <= 1440);
await read.click();
assert.equal(await read.getAttribute("aria-checked"), "true");
await page.locator(".reading h1:not(.document-title)").waitFor();
assert.equal(await page.locator(".source-editor").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: path.join(output, "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: path.join(output, "reader-details.png") });
// At the minimum window width of 880 pixels the outline gives way, and Split stacks in the remaining pane.
await page.setViewportSize({ width: 880, height: 900 });
await page.locator(".md-page").evaluate(element => { element.scrollTop = 0; });
await page.screenshot({ path: path.join(output, "reader-narrow.png") });
assert.ok(await page.locator(".md-page").evaluate(element => element.scrollWidth <= element.clientWidth + 1));
await chooseView(page, "Split");
await page.waitForFunction(() => {
const host = document.querySelector(".source-editor");
const rendered = host?.querySelector(".cm-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: path.join(output, "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: path.join(output, "reader-split-wide.png") });
// A second press ends the Split view.
await chooseView(page, "Split");
await page.locator(".md-page").waitFor({ state: "detached" });
// The editor stores one line break character. The saved file keeps its own line breaks.
assert.equal(await contents(), showcase.replace(/\r\n/g, "\n"));
assert.equal(await page.evaluate(() => window.__TEST__.files.get("reader-showcase.md")), showcase);
await read.focus();
await readTip.waitFor({ state: "visible" });
await page.keyboard.press("Escape");
await readTip.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 chooseView(page, "Write");
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 chooseView(page, "Source");
await waitForText(editedSource);
await focusEditor();
await page.keyboard.press("Control+z");
await waitForText(writingSource);
await chooseView(page, "Write");
await writer.waitFor();
// Write keeps the caret of the Source undo, so the paragraph can show its source.
await page.locator(".live-writer .cm-line").filter({ hasText: /A (\*\*)?formatted(\*\*)? 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'));
// Task markers stay rendered until the cursor reaches them (src/lib/editor/liveMarkdown.ts:262-268).
await task.locator('.writer-completed').click();
await page.keyboard.press("Home");
await page.locator('.live-writer .cm-line').filter({ hasText: '- [x] Ship draft' }).waitFor();
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: path.join(output, "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 chooseView(page, "Write");
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();
// Enter keeps the new note's filename and moves to its body (src/lib/editor/noteTitle.ts:57, 83).
await page.getByRole("textbox", { name: "Note filename", exact: true }).press("Enter");
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");
// The find field is labelled "Find in document" (src/lib/editor/FindPanel.svelte:60).
await page.getByRole("textbox", { name: "Find in document", 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 chooseView(page, "Write");
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('
'));
// Columns keep the 3rem minimum width (`.reading th, .reading td` in src/lib/layout/reading.css; reduced from 8rem in 909894b).
assert.ok(await table.locator('th').evaluateAll(cells => {
const minimum = 3 * parseFloat(getComputedStyle(document.documentElement).fontSize);
return cells.every(cell => cell.getBoundingClientRect().width >= minimum - 0.5);
}));
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: path.join(output, '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: path.join(output, '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');
// Shift+Enter adds a line break in a cell; Enter moves to the next row (src/lib/editor/tableControls.ts:278-286).
await page.keyboard.press('Shift+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: path.join(output, '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 chooseView(page, 'Read');
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 = '';
// Cell copies write plain text and HTML through clipboard.write (src/lib/editor/tableSelectionControls.ts:80-85).
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: {
write: async items => { window.__TEST__.clipboard = await (await items[0].getType('text/plain')).text(); },
writeText: async text => { window.__TEST__.clipboard = text; },
readText: async () => window.__TEST__.clipboard,
} });
}, selectionTable);
await quickOpen('selection-table.md');
await chooseView(page, 'Write');
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: path.join(output, '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 Ctrl+C');
// clipboard.write resolves its items asynchronously.
await page.waitForFunction(expected => window.__TEST__.clipboard === expected, 'one\ttwo\nfour\tfive');
await cellAction('Cut Ctrl+X');
await page.waitForFunction(() => [...document.querySelectorAll('.is-cell-selected')].every(cell => !cell.textContent.trim()));
await cellAction('Paste Ctrl+V');
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 chooseView(page, 'Write');
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 Ctrl+C', 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: path.join(output, 'table-text-row-menu.png') });
await page.getByRole('menuitem', { name: 'Column', exact: true }).hover();
await page.screenshot({ path: path.join(output, '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 Ctrl+V');
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 Ctrl+C');
assert.equal(await page.evaluate(() => window.__TEST__.clipboard), 'Brokers');
await actionItem('Cut Ctrl+X');
await page.waitForFunction(() => !document.querySelector('.live-writer td').textContent.includes('Brokers'));
await page.keyboard.press('Control+z');
await selectBrokers();
await actionItem('Select all Ctrl+A');
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:popover-open').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) 
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 chooseView(page, 'Write');
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 chooseView(page, 'Write');
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: path.join(output, 'table-cursor-position.png') });
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).");
});