Files
RuneStone/tests/smoke/layout/workbench.smoke.mjs
T
Knotty Wyvern 4d09da30d9 Support the migrated plugins in the host tests
- The pty_open mocks in layout/workbench and plugins/lifecycle send
  output through the channel that api.pty passes. Without a channel they
  keep the old events, so released Terminal versions still pass.
- plugins/gitToolbar resolves the Git plugin's "@runestone/plugin-sdk"
  imports to this repository's SDK build. The smoke runner builds the
  SDK when it is missing.
- The menu audit no longer compares the Terminal plugin's copies of the
  host menu files. The plugin now uses host menus through the SDK.

Checked with the released plugins and with the migrated Terminal, Git,
and Project Management branches.
2026-10-28 03:11:07 -07:00

791 lines
49 KiB
JavaScript

// 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 { 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);
// Choose a mode from a compact mode switcher, such as "Editor layout" or "Document view".
async function mode(group, value) {
await page.getByRole("group", { name: group, exact: true }).hover();
await page.getByRole("button", { name: value, exact: true }).click();
}
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 mode("Editor layout", "IDE");
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}});
}
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.__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 mode("Document view", "Split");
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: 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/LiveWriter.svelte:381, 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");
// The Read mode is a compact switcher button; its tooltip is a decorative child (src/lib/ui/ModeSwitcher.svelte:108).
const documentView = page.getByRole("group", { name: "Document view", exact: true });
const read = documentView.locator('button[aria-label="Read"]');
const readTip = read.locator(".tooltip");
assert.equal(await read.innerText(), "");
assert.equal(await read.locator("svg").count(), 1);
await documentView.hover();
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-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: 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") });
await page.setViewportSize({ width: 1000, 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 mode("Document view", "Split");
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: 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") });
await mode("Document view", "Edit");
assert.equal(await contents(), showcase);
assert.equal(await page.evaluate(() => window.__TEST__.files.get("reader-showcase.md")), showcase);
await documentView.hover();
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 mode("Editor layout", "Writer");
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 mode("Editor layout", "IDE");
await waitForText(editedSource);
await focusEditor();
await page.keyboard.press("Control+z");
await waitForText(writingSource);
await mode("Editor layout", "Writer");
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'));
// 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 mode("Editor layout", "Writer");
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.<br>Keep listings consistent.<br>Introduce automated investing.<br>Make the API usable and document common errors. |\n| CBOE.US | Cboe Global Markets Inc | BATS | Exchange | Operations;<br>- 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 mode("Editor layout", "Writer");
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('<br>'));
// Columns keep the 3rem minimum width (src/app.css:289; 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('<br>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 mode('Document view', '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 mode('Document view', 'Edit');
await mode('Editor layout', 'Writer');
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');
// clipboard.write resolves its items asynchronously.
await page.waitForFunction(expected => window.__TEST__.clipboard === expected, '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 mode('Document view', 'Edit');
await mode('Editor layout', 'Writer');
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: 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 = '<b>literal</b>\nnext'; });
await actionItem('Paste as plain text');
assert.ok((await saveActionSource()).includes('Interactive &lt;') || (await saveActionSource()).includes('Interactive \\<b\\>literal\\</b\\><br>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' ? '<em>Rich paste</em>' : '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)<br />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 mode('Document view', 'Edit');
await mode('Editor layout', 'Writer');
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](<missing.png>)'));
assert.ok(richSaved.includes('<br>Next edited'));
assert.ok(!/(?<!\r)\n/.test(richSaved));
await page.keyboard.press('Escape');
await richCell.click();
await page.keyboard.press('Control+End');
await page.keyboard.type(' again');
await page.keyboard.press('Control+s');
await page.waitForFunction(() => 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<br>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<br>Second note<br>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 mode('Editor layout', 'Writer');
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).");
});