Move the tests from scripts/ to tests/ by feature

Unit tests go to tests/unit/<area>/, browser smoke tests to
tests/smoke/<area>/, and tests against a running desktop app to
tests/native/. Files named after dates, work passes, or Kanban cards get
feature names, for example editorOctober12 -> editor/footnotes.

scripts/ keeps the build, release, and package tools. Plugin repositories
import scripts/packagePlugin.mjs, and the Terminal smoke test imports
scripts/pluginMocks.mjs, which now re-exports the harness copy.

The unit tests get their own type check (tests/tsconfig.json) with Node
types. pnpm check runs it after the app check. Add @types/node and fix
the three test mocks that it reported.
This commit is contained in:
Knotty Wyvern
2026-10-27 19:47:39 -07:00
parent 90d1940c73
commit e433bed28e
154 changed files with 269 additions and 227 deletions
+95
View File
@@ -0,0 +1,95 @@
// Run against pnpm dev with PLAYWRIGHT_MODULE and CHROME_PATH if needed.
import { createRequire } from "node:module";
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const context = await browser.newContext({ viewport: { width: 1280, height: 800 } });
await context.addInitScript(() => {
window.isTauri = true;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: () => 1, unregisterCallback: () => {},
invoke: async (command, args = {}) => {
if (command === "plugins_snapshot") return { root: "D:\\LayoutTest\\plugins", plugins: [] };
if (command === "workspace_last_path") return "D:\\LayoutTest";
if (command === "workspace_open") return { root: "D:\\LayoutTest", name: "LayoutTest", watch_mode: "native" };
if (command === "workspace_list") return args.rel ? [] : [{ name: "note.md", rel_path: "note.md", kind: "file" }];
if (command === "workspace_read") {
if (args.rel === "note.md") return "# Layout test\n\nA note.\n";
throw new Error("Missing file");
}
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const errors = [];
context.on("page", page => page.on("pageerror", error => errors.push(error.message)));
const url = process.env.SMOKE_URL || "http://127.0.0.1:1420";
let page = await context.newPage();
page.setDefaultTimeout(5000);
async function ready() { await page.getByRole("button", { name: /^(Hide|Show) outline$/ }).waitFor(); }
async function reopen() {
await page.close();
page = await context.newPage();
page.setDefaultTimeout(5000);
await page.goto(url);
await ready();
}
async function resize(index, x) {
const box = await page.locator(".gutter-v").nth(index).boundingBox();
await page.mouse.move(box.x + box.width / 2, box.y + 60);
await page.mouse.down();
await page.mouse.move(x, box.y + 60);
await page.mouse.up();
}
async function widths() {
return page.locator(".shell").evaluate(element => [element.style.getPropertyValue("--left"), element.style.getPropertyValue("--right")]);
}
try {
await page.goto(url);
await ready();
await page.getByText("LayoutTest", { exact: true }).waitFor();
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill("note.md");
await page.getByRole("dialog").getByRole("button").filter({ hasText: "note.md" }).click();
await page.locator(".cm-content").waitFor();
await page.getByRole("button", { name: "Hide outline", exact: true }).click();
await page.keyboard.press("Control+e");
await page.locator(".monaco-editor").waitFor();
assert.equal(await page.locator(".right").count(), 0);
await page.keyboard.press("Control+e");
await page.locator(".cm-content").waitFor();
assert.equal(await page.locator(".right").count(), 0);
console.log("PASS: hidden outline stays hidden across Writer and IDE changes");
await page.reload();
await page.getByRole("button", { name: "Show outline", exact: true }).waitFor();
assert.equal(await page.locator(".right").count(), 0);
await reopen();
await page.getByRole("button", { name: "Show outline", exact: true }).waitFor();
console.log("PASS: hidden outline survives reload and window reopen");
await page.getByRole("button", { name: "Show outline", exact: true }).click();
await resize(0, 330);
await resize(1, 970);
const resized = await widths();
assert.deepEqual(resized, ["330px", "310px"]);
await page.getByRole("button", { name: "Bookmarks", exact: true }).click();
await reopen();
assert.deepEqual(await widths(), resized);
assert.equal(await page.getByRole("button", { name: "Bookmarks", exact: true }).getAttribute("aria-pressed"), "true");
await page.getByRole("button", { name: "Hide outline", exact: true }).waitFor();
console.log("PASS: resized sidebars and chosen navigation view survive reopen");
await page.getByRole("button", { name: "Bookmarks", exact: true }).click();
await page.getByRole("button", { name: "Hide outline", exact: true }).click();
await reopen();
assert.equal(await page.locator(".left, .right").count(), 0);
await page.keyboard.press("Control+b");
assert.equal(await page.getByRole("button", { name: "Bookmarks", exact: true }).getAttribute("aria-pressed"), "true");
await page.getByRole("button", { name: "Show outline", exact: true }).click();
assert.deepEqual(await widths(), resized);
console.log("PASS: collapsed sidebars retain their sizes and navigation view");
assert.deepEqual(errors, []);
} finally { await browser.close(); }
+160
View File
@@ -0,0 +1,160 @@
import { createRequire } from "node:module";
import assert from "node:assert/strict";
import { mkdir } from "node:fs/promises";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(15000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
page.on("console", message => { if (message.text().includes("binding_property_non_reactive")) errors.push(message.text()); });
await mkdir(".audit", { recursive: true });
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\tab-menu-workspace";
const files = new Map(["a.md", "b.md", "c.md", "d.md"].map(name => [name, `# ${name}\n\nOriginal text.\n\n\`\`\`js\nconst answer = 42;\n\`\`\`\n\n| Name | Value |\n| --- | --- |\n| Alpha | One |\n`]));
files.set("a.md", "# Links\n\nSelected reading text.\n\n[Web label](https://example.com/path)\n\n[[b.md|Workspace note]]\n");
files.set("a.md", "# Alpha\n\nOrigin paragraph.\n\n[[notes/b.md|Right note]]\n");
files.set("notes/b.md", "# Bravo\n\nSecond paragraph.\n\n[Relative](c.md)\n\n[[/a.md|Original note]]\n");
files.set("notes/c.md", "# Charlie\n\nThird paragraph.\n");
files.set("sample.txt", "const answer = 42;\n");
window.tabMenuTest = { prompts: [], answer: "Cancel", revealed: null, clipboard: null, opened: null, app: null, windows: [] };
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { window.tabMenuTest.clipboard = text; } } });
window.tabMenuTest.files = files;
let sequence = 0;
const callbacks = new Map(), listeners = new Map();
window.tabMenuTest.change = (path, text) => { files.set(path, text); callbacks.get(listeners.get("workspace-event"))?.({ event: "workspace-event", id: 1, payload: { root, kind: "modify", paths: [path] } }); };
window.tabMenuTest.writes = [];
window.spellingTest = { commands: [], emit: payload => callbacks.get(listeners.get("spelling-menu"))?.({ event: "spelling-menu", id: 1, payload }) };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { callbacks.set(++sequence, callback); return sequence; }, unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === "plugin:event|listen") { listeners.set(args.event, args.handler); return ++sequence; }
if (command === "plugin:event|unlisten") return;
if (command.startsWith("spelling_menu_")) { window.spellingTest.commands.push({ method: command, ...args }); return; }
if (command === "spelling_suggestions") return { language: "en-US", words: ["Corrected"], misspelled: args.word === "Original" };
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "tab-menu-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_list") return [...(!args.rel ? [{ name: "notes", rel_path: "notes", kind: "folder" }] : []), ...[...files.keys()].filter(path => path.split("/").slice(0, -1).join("/") === (args.rel || "")).map(path => ({ name: path.split("/").at(-1), rel_path: path, kind: "file" }))];
if (command === "workspace_search") { window.tabMenuTest.searched = args.query; return []; }
if (command === "plugin:opener|open_url") { window.tabMenuTest.opened = args.url; return; }
if (command === "workspace_open_default") { window.tabMenuTest.app = args.rel; return; }
if (command === "workspace_open_window") { window.tabMenuTest.windows.push(args); return; }
if (command === "workspace_write") { if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("conflict"); files.set(args.rel, args.contents); window.tabMenuTest.writes.push(args.rel); return; }
if (command === "workspace_rename") { files.set(args.to, files.get(args.from)); files.delete(args.from); return; }
if (command === "workspace_abs_path") return `${root}\\${args.rel}`;
if (command === "workspace_reveal") { window.tabMenuTest.revealed = args.rel; return; }
if (command === "plugin:dialog|message") { window.tabMenuTest.prompts.push(args.message); return window.tabMenuTest.answer; }
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const output = '.audit/document-splits';
await mkdir(output, {recursive:true});
const pane = path => page.locator(`[data-document-path="${path}"]`);
const item = name => page.getByRole('menuitem',{name,exact:true});
async function openRight(path,label) {
const current = pane(path);
await current.locator('.cm-content').getByText(path === 'a.md' ? 'Origin paragraph.' : 'Second paragraph.',{exact:true}).click();
await current.locator('.cm-content').getByText(label,{exact:true}).click({button:'right'});
await item('Open to the right').click();
}
async function append(path, text) {
const target=pane(path).locator('.cm-content');
await target.click(); await page.keyboard.press('Control+End'); await page.keyboard.type(text);
}
async function text(path) { return pane(path).locator('.cm-content').evaluate(async node=> { const {EditorView}=await import('/node_modules/@codemirror/view/dist/index.js'); return EditorView.findFromDOM(node).state.doc.toString(); }); }
async function focus(path) { await pane(path).locator('.cm-content').click(); }
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await page.locator('[data-tree-rel="a.md"]').click(); await pane('a.md').locator('.cm-content').waitFor();
await append('a.md','\nLeft unsaved.');
await openRight('a.md','Right note'); await pane('notes/b.md').locator('.cm-content').waitFor();
assert.equal(await page.locator('.document-pane').count(),2);
assert.match(await text('a.md'),/Left unsaved/);
await append('notes/b.md','\nRight saved.'); await page.keyboard.press('Control+s');
await page.waitForFunction(()=>window.tabMenuTest.writes.includes('notes/b.md'));
assert.equal(await page.evaluate(()=>window.tabMenuTest.writes.includes('a.md')),false,'Save uses the focused right pane');
await focus('a.md'); await page.keyboard.press('Control+s'); await page.waitForFunction(()=>window.tabMenuTest.writes.includes('a.md'));
await pane('notes/b.md').getByRole('group',{name:'Editor layout',exact:true}).hover();
await pane('notes/b.md').getByRole('button',{name:'IDE',exact:true}).click(); await pane('notes/b.md').locator('.monaco-editor').waitFor();
assert.equal(await pane('a.md').locator('.cm-content').count(),1,'Changing the right mode keeps the left editor');
await openRight('a.md','Right note');
assert.equal(await page.locator('.document-pane').count(),2);
await page.waitForFunction(async()=>{const {monaco}=await import('/src/lib/editor/monacoEnv.ts');return monaco.editor.getEditors().some(editor=>editor.getModel()?.uri.path.endsWith('/b.md') && editor.hasTextFocus());}); await page.keyboard.press('Control+End'); await page.keyboard.type('\nIDE edit.'); await page.keyboard.press('Control+s');
await page.waitForFunction(()=>window.tabMenuTest.files.get('notes/b.md').includes('IDE edit.'));
await pane('notes/b.md').getByRole('group',{name:'Editor layout',exact:true}).hover();
await pane('notes/b.md').getByRole('button',{name:'Writer',exact:true}).click(); await pane('notes/b.md').locator('.cm-content').waitFor();
assert.match(await text('notes/b.md'),/IDE edit/);
await pane('notes/b.md').getByRole('group',{name:'Document view',exact:true}).hover();
await pane('notes/b.md').getByRole('button',{name:'Read',exact:true}).click(); await pane('notes/b.md').locator('.reading').waitFor();
assert.equal(await pane('a.md').locator('.reading').count(),0,'Reading mode belongs to its pane');
await focus('a.md'); assert.equal(await pane('notes/b.md').locator('.reading').count(),1);
await pane('notes/b.md').getByRole('group',{name:'Document view',exact:true}).hover();
await pane('notes/b.md').getByRole('button',{name:'Edit',exact:true}).click(); await pane('notes/b.md').locator('.cm-content').waitFor();
for(const path of ['a.md','notes/b.md']) await pane(path).locator('.cm-content').evaluate(async node=> {
const {EditorView}=await import('/node_modules/@codemirror/view/dist/index.js'); const v=EditorView.findFromDOM(node); const source=v.state.doc.toString(); const from=source.indexOf(source.includes('Alpha') ? 'Origin' : 'Second'); v.dispatch({selection:{anchor:from,head:from+6}});
});
const selections=await page.evaluate(async()=> { const {monaco}=await import('/src/lib/editor/monacoEnv.ts'); const resource=performance.getEntriesByType('resource').find(entry=>new URL(entry.name).pathname==='/src/lib/editor/selection.ts'); const {selectedEditorText}=await import(resource.name); return monaco.editor.getModels().map(model=>selectedEditorText(model.uri.path.split('/')[1])).filter(Boolean).sort(); });
assert.deepEqual(selections,['Origin','Second'],'Each pane retains its own selection');
await openRight('a.md','Right note'); assert.equal(await page.locator('.document-pane').count(),2);
await page.waitForFunction(()=>document.activeElement?.closest('[data-document-path]')?.dataset.documentPath==='notes/b.md');
await openRight('notes/b.md','Original note'); assert.equal(await page.locator('.document-pane').count(),2);
await page.waitForFunction(()=>document.activeElement?.closest('[data-document-path]')?.dataset.documentPath==='a.md');
await append('notes/b.md','\nRight still unsaved.');
for(const theme of ['light','dark']) {
await page.evaluate(async mode=> { const {saveAppearance}=await import('/src/lib/theme/appearance.ts'); saveAppearance({theme:'default',mode}); },theme);
await page.screenshot({path:`${output}/two-editors-${theme}.png`});
}
await pane('notes/b.md').getByRole('button',{name:'Close split',exact:true}).click();
assert.equal(await page.locator('.document-pane').count(),1); assert.equal(await pane('a.md').count(),1);
assert.match(await text('a.md'),/Left unsaved/);
assert.equal(await page.evaluate(async()=> { const {monaco}=await import('/src/lib/editor/monacoEnv.ts'); return monaco.editor.getModels().length; }),2,'Closing a split preserves both tab models');
await page.getByRole('tab',{name:/b.md/}).click(); await pane('notes/b.md').locator('.cm-content').waitFor();
assert.match(await text('notes/b.md'),/Right still unsaved/,'The closed split retains its unsaved buffer');
await page.getByRole('tab',{name:/a.md/}).click(); await openRight('a.md','Right note'); await pane('notes/b.md').locator('.cm-content').waitFor();
await openRight('notes/b.md','Relative'); await pane('notes/c.md').locator('.cm-content').waitFor();
assert.equal(await page.locator('.document-pane').count(),3);
assert.match(await text('notes/c.md'),/Charlie/,'Relative links use the pane document folder');
await pane('notes/c.md').getByRole('button',{name:'Close split',exact:true}).click();
assert.equal(await page.locator('.document-pane').count(),2);
await page.evaluate(()=>window.tabMenuTest.change('notes/b.md','# Bravo disk\n\nExternal update.\n'));
await pane('notes/b.md').getByRole('alert').waitFor();
assert.equal(await pane('a.md').getByRole('alert').count(),0);
assert.match(await text('notes/b.md'),/Right still unsaved/,'A disk conflict preserves the right pane edits');
await focus('a.md');
await pane('notes/b.md').getByRole('button',{name:'Use disk version',exact:true}).click();
await page.waitForFunction(()=>document.querySelector('[data-document-path="notes/b.md"] .cm-content')?.textContent.includes('External update.'));
assert.match(await text('a.md'),/Left unsaved/,'Resolving the other pane cannot replace the primary buffer');
await page.getByRole('button',{name:'Files',exact:true}).click(); await page.getByRole('button',{name:'Hide outline',exact:true}).click();
await page.setViewportSize({width:560,height:740});
for(const theme of ['light','dark']) {
await page.evaluate(async mode=> { const {saveAppearance}=await import('/src/lib/theme/appearance.ts'); saveAppearance({theme:'default',mode}); },theme);
const first=await pane('a.md').boundingBox(), second=await pane('notes/b.md').boundingBox();
assert.ok(first.width>500 && second.width>500 && second.y>=first.y+first.height-1,'Narrow panes stack with readable widths');
await page.screenshot({path:`${output}/stacked-${theme}.png`});
}
await append('notes/b.md','\nNarrow edit.'); await page.keyboard.press('Control+s');
await page.waitForFunction(()=>window.tabMenuTest.files.get('notes/b.md').includes('Narrow edit.'));
await pane('notes/b.md').getByRole('button',{name:'Close split',exact:true}).click();
await append('a.md','\nAfter closing split.'); await page.keyboard.press('Control+s');
await page.waitForFunction(()=>window.tabMenuTest.files.get('a.md').includes('After closing split.'));
await page.setViewportSize({width:1440,height:1000});
await openRight('a.md','Right note'); await pane('notes/b.md').locator('.cm-content').waitFor();
await append('notes/b.md','\nClose guard.');
await page.keyboard.press('Control+w');
await page.waitForFunction(()=>window.tabMenuTest.prompts.length>0);
assert.equal(await pane('notes/b.md').count(),1,'Cancel keeps the dirty split open');
await page.keyboard.press('Control+s'); await page.waitForFunction(()=>window.tabMenuTest.files.get('notes/b.md').includes('Close guard.'));
await page.keyboard.press('Control+w'); await pane('notes/b.md').waitFor({state:'detached'});
await focus('a.md'); await append('a.md','\nOther tab closed.'); await page.keyboard.press('Control+s');
await page.waitForFunction(()=>window.tabMenuTest.files.get('a.md').includes('Other tab closed.'));
assert.equal(await page.evaluate(async()=>{const {monaco}=await import('/src/lib/editor/monacoEnv.ts');return monaco.editor.getModels().some(model=>model.uri.path.endsWith('/b.md'));}),false,'Closing the tab releases only its model');
assert.deepEqual(errors,[]);
console.log(JSON.stringify({passed:['independent Writer/IDE/Reading modes','dirty close cancellation and model release','independent edits and saves','per-pane selections','focus existing duplicate target','closing split retains unsaved tabs and models','nested relative link origin','per-pane conflict resolution','narrow layout and save','light/dark screenshots'],nativeDesktop:'not tested'},null,2));
} catch(error) { await page.screenshot({path:`${output}/failure.png`}); console.log(await page.locator('.status,.rs-menu').allTextContents()); throw error; } finally { await browser.close(); }
@@ -0,0 +1,84 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1400, height: 900 } });
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const callbacks = new Map(), listeners = new Map();
let sequence = 0;
const state = { maximized: false, confirm: "Cancel", calls: [] };
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
state.calls.push(command);
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return null;
if (command === "plugin:window|is_maximized") return state.maximized;
if (command === "plugin:window|toggle_maximize") { state.maximized = !state.maximized; emit("tauri://resize", { width: 1400, height: 900 }); return; }
if (command === "plugin:window|minimize" || command === "plugin:window|destroy") return;
if (command === "plugin:window|close") { emit("tauri://close-requested"); return; }
if (command === "plugin:dialog|message") return state.confirm;
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { state, emit };
});
try {
const config = JSON.parse(await readFile(new URL("../../../src-tauri/tauri.conf.json", import.meta.url), "utf8"));
assert.equal(config.app.windows[0].decorations, false);
const capability = JSON.parse(await readFile(new URL("../../../src-tauri/capabilities/default.json", import.meta.url), "utf8"));
for (const permission of ["close", "minimize", "toggle-maximize", "start-dragging"]) {
assert.ok(capability.permissions.includes(`core:window:allow-${permission}`));
}
await page.goto(process.env.SMOKE_URL || "http://localhost:1420");
await page.getByRole("button", { name: "Maximize window", exact: true }).click();
await page.getByRole("button", { name: "Restore window", exact: true }).waitFor();
await page.getByRole("button", { name: "Restore window", exact: true }).click();
await page.getByRole("button", { name: "Maximize window", exact: true }).waitFor();
// Native maximize/restore (e.g. double-clicking the drag region) updates the button too.
await page.evaluate(() => { window.__TEST__.state.maximized = true; window.__TEST__.emit("tauri://resize", { width: 1920, height: 1080 }); });
await page.getByRole("button", { name: "Restore window", exact: true }).waitFor();
await page.getByRole("button", { name: "Minimize window", exact: true }).click();
assert.ok(await page.evaluate(() => window.__TEST__.state.calls.includes("plugin:window|minimize")));
await page.getByRole("button", { name: "Close window", exact: true }).focus();
await page.getByRole("tooltip", { name: "Close window", exact: true }).waitFor();
// Opening the terminal engages the existing close guard; cancellation must not destroy the window.
await page.getByRole("button", { name: "Terminal", exact: true }).click();
await page.getByRole("button", { name: "Close window", exact: true }).click();
await page.waitForFunction(() => window.__TEST__.state.calls.includes("plugin:dialog|message"));
assert.equal(await page.evaluate(() => window.__TEST__.state.calls.includes("plugin:window|destroy")), false);
await page.evaluate(() => window.__TEST__.state.confirm = "Ok");
await page.getByRole("button", { name: "Close window", exact: true }).click();
await page.waitForFunction(() => window.__TEST__.state.calls.includes("plugin:window|destroy"));
await page.getByRole("button", { name: "Terminal", exact: true }).click();
for (const width of [1400, 880]) {
await page.setViewportSize({ width, height: 900 });
const layout = await page.evaluate(() => {
const header = document.querySelector(".header").getBoundingClientRect();
const controls = [...document.querySelectorAll(".header button")].map(el => el.getBoundingClientRect());
return { height: header.height, top: header.top, fits: controls.every(rect => rect.x >= 0 && rect.right <= innerWidth && rect.y >= header.y && rect.bottom <= header.bottom), drag: document.querySelector(".window-drag-space").getBoundingClientRect().width };
});
assert.equal(layout.height, 36);
assert.equal(layout.top, 0);
assert.ok(layout.fits);
assert.ok(layout.drag >= 40);
await page.screenshot({ path: `.audit/window-controls-${width}.png` });
}
assert.deepEqual(errors, []);
console.log("Window controls smoke passed: actions, restore state, close guard, keyboard tooltip, and 1400/880px layouts.");
} finally { await browser.close(); }
+801
View File
@@ -0,0 +1,801 @@
import { mockFeaturePlugins } from "../_harness/pluginMocks.mjs";
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
const showcase = await readFile(new URL("../../../fixtures/reader-showcase.md", import.meta.url), "utf8");
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
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();
if (await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).count()) {
await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click();
}
await page.locator(".monaco-editor textarea").waitFor();
}
async function contents() {
return page.evaluate(async () => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
return monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected)?.getValue();
});
}
async function waitForText(text) {
await page.evaluate(async () => { window.__MONACO__ = (await import("/src/lib/editor/monacoEnv.ts")).monaco; });
await page.waitForFunction(expected => window.__MONACO__.editor.getEditors().some(editor => editor.getDomNode()?.isConnected && editor.getValue() === expected), text);
}
async function focusEditor() {
await page.locator(".monaco-host .view-lines").click({position:{x:120,y:12}});
}
try {
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
await page.getByText("smoke-workspace", { exact: true }).waitFor();
await quickOpen("welcome.md");
const original = await contents();
assert.ok(original.startsWith("---\ntitle:"));
await focusEditor();
await page.keyboard.press("Control+End");
await page.keyboard.type("Added in source.");
await waitForText(original + "Added in source.");
await quickOpen("hello.py");
await page.getByRole("tab", { name: /welcome\.md/ }).click();
await focusEditor();
await page.keyboard.press("Control+z");
await page.waitForFunction(expected => window.__MONACO__.editor.getEditors().some(editor => editor.getDomNode()?.isConnected && editor.getValue() !== expected), original + "Added in source.");
await page.keyboard.press("Control+y");
await waitForText(original + "Added in source.");
await page.keyboard.press("Control+s");
await page.waitForFunction(expected => window.__TEST__.files.get("notes/welcome.md") === expected, original + "Added in source.");
await page.getByRole("button", { name: "Split", exact: true }).click();
await page.locator(".md-page h1").first().waitFor();
assert.ok(await page.locator(".monaco-host").isVisible());
await page.evaluate(() => {
window.__TEST__.files.set("notes/welcome.md", "# Agent update\n");
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "modify", paths: ["notes/welcome.md"] });
});
await waitForText("# Agent update\n");
await focusEditor();
await page.keyboard.press("Control+End");
await page.keyboard.type("Local edit");
await page.evaluate(() => {
window.__TEST__.files.set("notes/welcome.md", "# Another agent edit\n");
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "modify", paths: ["notes/welcome.md"] });
});
await page.getByRole("button", { name: "Keep my edits" }).waitFor();
assert.equal(await contents(), "# Agent update\nLocal edit");
await page.getByRole("button", { name: "Keep my edits" }).click();
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md") === "# Agent update\nLocal edit");
await page.getByRole("button", { name: "Terminal", exact: true }).click();
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_open"));
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_write" && /\x1b\[\d+;\d+R/.test(c.args.data)));
await page.screenshot({ path: ".audit/core-rebuild-terminal.png" });
await page.getByRole("button", { name: "Hide terminal (sessions keep running)" }).click();
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_close").length), 0);
await page.getByRole("button", { name: "Terminal", exact: true }).click();
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_open").length), 1);
await page.getByRole("button", { name: "New terminal", exact: true }).click();
await page.waitForFunction(() => window.__TEST__.calls.filter(c => c.command === "pty_open").length === 2);
await page.getByRole("button", { name: "Kill terminal", exact: true }).first().click();
await page.waitForFunction(() => window.__TEST__.calls.filter(c => c.command === "pty_close").length === 1);
await page.getByRole("button", { name: "Hide terminal (sessions keep running)" }).click();
await page.keyboard.press("Control+n");
await page.getByLabel("New file path relative to the workspace").fill("notes/new-note.md");
await page.getByRole("button", { name: "Continue", exact: true }).click();
await page.getByRole("tab", { name: "new-note.md", exact: true }).waitFor();
await page.screenshot({ path: ".audit/core-rebuild.png" });
await page.evaluate(text => {
window.__TEST__.files.set("reader-showcase.md", text);
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "create", paths: ["reader-showcase.md"] });
}, showcase);
await quickOpen("reader-showcase.md");
const read = page.getByRole("button", { name: "Read", exact: true });
assert.equal(await read.innerText(), "");
assert.equal(await read.locator("svg").count(), 1);
await read.hover();
await page.getByRole("tooltip", { name: "Read", exact: true }).waitFor({ state: "visible" });
const tip = await page.getByRole("tooltip", { name: "Read", exact: true }).boundingBox();
assert.ok(tip.x >= 0 && tip.x + tip.width <= 1440);
await read.click();
assert.equal(await read.getAttribute("aria-pressed"), "true");
await page.locator(".reading h1:not(.document-title)").waitFor();
assert.equal(await page.locator(".monaco-host").isVisible(), false);
assert.equal(await page.locator(".reading h1:not(.document-title)").innerText(), "Project field notes");
assert.equal(await page.locator(".reading ol > li").count(), 3);
assert.equal(await page.locator(".reading ol ul > li").count(), 2);
assert.equal(await page.locator(".reading input:checked").count(), 2);
assert.equal(await page.locator(".md-properties").getAttribute("open"), null);
assert.ok((await page.locator(".reading > p").first().innerText()).includes("implementation notes"));
const surface = await page.locator(".reading").boundingBox();
assert.ok(surface.width <= 741);
await page.mouse.move(700, 980);
await page.screenshot({ path: ".audit/reader-mode.png" });
await page.locator(".md-table-scroll").scrollIntoViewIfNeeded();
await page.getByRole("button", { name: "Copy code", exact: true }).click();
await page.getByRole("button", { name: "Copied", exact: true }).waitFor();
await page.screenshot({ path: ".audit/reader-details.png" });
await page.setViewportSize({ width: 1000, height: 900 });
await page.locator(".md-page").evaluate(element => { element.scrollTop = 0; });
await page.screenshot({ path: ".audit/reader-narrow.png" });
assert.ok(await page.locator(".md-page").evaluate(element => element.scrollWidth <= element.clientWidth + 1));
await page.getByRole("button", { name: "Split", exact: true }).click();
await page.waitForFunction(() => {
const host = document.querySelector(".monaco-host");
const rendered = host?.querySelector(".monaco-editor");
return rendered && Math.abs(host.clientWidth - rendered.clientWidth) < 2;
});
assert.equal(await page.locator(".body.split").evaluate(element => getComputedStyle(element).flexDirection), "column");
await page.screenshot({ path: ".audit/reader-split.png" });
assert.ok(await page.locator(".md-page").evaluate(element => element.scrollWidth <= element.clientWidth + 1));
await page.setViewportSize({ width: 1440, height: 1000 });
await page.waitForFunction(() => getComputedStyle(document.querySelector(".body.split")).flexDirection === "row");
await page.screenshot({ path: ".audit/reader-split-wide.png" });
await page.getByRole("button", { name: "Edit", exact: true }).click();
assert.equal(await contents(), showcase);
assert.equal(await page.evaluate(() => window.__TEST__.files.get("reader-showcase.md")), showcase);
await page.getByRole("button", { name: "Read", exact: true }).focus();
await page.getByRole("tooltip", { name: "Read", exact: true }).waitFor({ state: "visible" });
await page.keyboard.press("Escape");
await page.getByRole("tooltip", { name: "Read", exact: true }).waitFor({ state: "hidden" });
// Continuous live Markdown: only active lines reveal source; checkboxes
// remain inline and update the original file without HTML serialization.
const writingSource = '---\ntitle: Preserved\n---\n\n# Writer preview\n\nA **formatted** paragraph.\n\n[Project link](https://example.com/old)\n\n- [ ] Ship draft\n- [x] Finished task\n\n```mermaid\nflowchart LR\n A[Draft] --> B[Publish]\n```\n\n```mermaid\nnot a valid diagram\n```\n\n- Parent\n - Child\n';
await page.evaluate(text => {
window.__TEST__.files.set("writing.md", text);
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "create", paths: ["writing.md"] });
}, writingSource);
await quickOpen("writing.md");
await page.getByRole("button", { name: "Switch to writing layout (Ctrl E)", exact: true }).click();
const writer = page.getByRole("textbox", { name: "Writing editor", exact: true });
await writer.waitFor();
assert.equal(await page.locator('.live-writer [contenteditable="true"]').count(), 1);
assert.equal(await page.getByRole("toolbar", { name: "Text formatting" }).count(), 0);
await page.locator(".live-writer .md-diagram svg").waitFor({ timeout: 30000 });
await page.getByRole("status").filter({ hasText: "Diagram could not render" }).waitFor();
const paragraph = page.locator(".live-writer .cm-line").filter({ hasText: "A formatted paragraph." });
await paragraph.click();
await page.locator(".live-writer .cm-line").filter({ hasText: "A **formatted** paragraph." }).waitFor();
await page.keyboard.press("Home");
await page.keyboard.type("New ");
await page.keyboard.press("Control+s");
const editedSource = writingSource.replace("A **formatted**", "New A **formatted**");
await page.waitForFunction(text => window.__TEST__.files.get("writing.md") === text, editedSource);
await page.keyboard.press("Control+z");
await page.keyboard.press("Control+s");
await page.waitForFunction(text => window.__TEST__.files.get("writing.md") === text, writingSource);
await page.keyboard.press("Control+y");
await page.keyboard.press("Control+s");
await page.waitForFunction(text => window.__TEST__.files.get("writing.md") === text, editedSource);
await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click();
await waitForText(editedSource);
await focusEditor();
await page.keyboard.press("Control+z");
await waitForText(writingSource);
await page.getByRole("button", { name: "Switch to writing layout (Ctrl E)", exact: true }).click();
await writer.waitFor();
await paragraph.click();
await page.keyboard.press("End");
await page.keyboard.press("Enter");
await page.keyboard.press("Enter");
await page.keyboard.type("First new paragraph.");
await page.keyboard.press("Enter");
await page.keyboard.press("Enter");
await page.keyboard.type("**Second new paragraph.**");
await page.keyboard.press("Enter");
await page.keyboard.press("Enter");
await page.keyboard.type("Third new paragraph.");
assert.equal(await page.locator(".live-writer .writer-strong").filter({ hasText: "Second new paragraph." }).count(), 1);
await page.keyboard.press("Home");
await page.keyboard.press("Shift+ArrowUp");
await page.keyboard.press("Shift+ArrowUp");
assert.ok((await page.evaluate(() => window.getSelection().toString())).includes("Second new paragraph."));
await page.keyboard.press("Backspace");
await page.keyboard.press("Control+z");
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("writing.md").includes("First new paragraph.\n\n**Second new paragraph.**\n\nThird new paragraph."));
assert.ok(await writer.evaluate(el => el.contains(document.activeElement)));
// Link syntax becomes editable on a normal click, without opening the link.
await page.locator('.live-writer .writer-link').filter({ hasText: "Project link" }).click();
await page.locator('.live-writer .cm-line').filter({ hasText: "[Project link](https://example.com/old)" }).waitFor();
await page.keyboard.press("End");
await page.keyboard.press("Home");
await page.keyboard.press("Shift+End");
await page.keyboard.type("[Project link](https://example.com/new)");
await page.keyboard.press("ArrowDown");
await page.locator('.live-writer [data-href="https://example.com/new"]').waitFor();
const task = page.locator('.live-writer .cm-line').filter({ hasText: "Ship draft" });
const checkbox = task.getByRole("checkbox");
assert.ok(await task.evaluate(line => {
const box = line.querySelector('input').getBoundingClientRect();
const text = [...line.childNodes].find(node => node.nodeType === Node.TEXT_NODE && node.textContent.includes('Ship draft'));
const range = document.createRange(); range.selectNode(text);
const label = range.getBoundingClientRect();
return Math.abs((box.top + box.bottom) / 2 - (label.top + label.bottom) / 2) < 8 && box.right <= label.left;
}));
await checkbox.click();
await task.locator('.writer-completed').waitFor();
assert.equal(await task.locator('.writer-completed').evaluate(el => getComputedStyle(el).textDecorationLine), 'line-through');
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("writing.md").includes('- [x] Ship draft'));
await task.locator('.writer-completed').click();
await page.locator('.live-writer .cm-line').filter({ hasText: '- [x] Ship draft' }).waitFor();
await page.keyboard.press("Home");
await page.keyboard.press("Shift+End");
await page.keyboard.type('- [ ] Revised task');
await page.keyboard.press("ArrowUp");
await page.locator('.live-writer .cm-line').filter({ hasText: 'Revised task' }).getByRole('checkbox', { checked: false }).waitFor();
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("writing.md").includes('- [ ] Revised task'));
await page.locator(".live-writer .md-diagram svg").waitFor();
await page.screenshot({ path: ".audit/writing-continuous.png" });
await page.setViewportSize({ width: 1000, height: 900 });
assert.ok(await page.locator(".cm-scroller").evaluate(el => el.scrollWidth <= el.clientWidth + 1));
await page.evaluate(() => {
window.__TEST__.files.set("crlf.md", "# Windows note\r\n\r\nA paragraph.\r\n\r\nTail stays intact.\r\n");
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "create", paths: ["crlf.md"] });
});
await quickOpen("crlf.md");
await page.getByRole("button", { name: "Switch to writing layout (Ctrl E)", exact: true }).click();
await page.locator(".live-writer .cm-line").filter({ hasText: "A paragraph." }).click();
await page.keyboard.press("Home");
await page.keyboard.type("Changed ");
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("crlf.md") === "# Windows note\r\n\r\nChanged A paragraph.\r\n\r\nTail stays intact.\r\n");
await page.keyboard.press("Control+n");
await page.getByLabel("New file path relative to the workspace").fill("blank.md");
await page.getByRole("button", { name: "Continue", exact: true }).click();
await writer.waitFor();
await page.keyboard.type("One");
await page.keyboard.press("Enter");
await page.keyboard.type("Two");
await page.keyboard.press("Enter");
await page.keyboard.type("Three");
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("blank.md").replace(/\r\n/g, "\n") === "One\nTwo\nThree");
await page.getByRole("tab", { name: "crlf.md", exact: true }).click();
await page.getByRole("tab", { name: "blank.md", exact: true }).click();
await writer.waitFor();
await page.keyboard.press("Control+z");
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("blank.md").replace(/\r\n/g, "\n") !== "One\nTwo\nThree");
await page.keyboard.press("Control+y");
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("blank.md").replace(/\r\n/g, "\n") === "One\nTwo\nThree");
await page.keyboard.press("Control+f");
await page.getByRole("textbox", { name: "Find", exact: true }).fill("Two");
await page.keyboard.press("Escape");
await page.keyboard.press("Control+a");
await page.keyboard.type("- [ ] First task");
await page.keyboard.press("Enter");
await page.keyboard.type("Second task");
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("blank.md").replace(/\r\n/g, "\n") === "- [ ] First task\n- [ ] Second task");
await page.evaluate(() => {
window.__TEST__.files.set("blank.md", "Fresh disk version\r\n");
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "modify", paths: ["blank.md"] });
});
await page.locator('.live-writer .cm-line').filter({ hasText: 'Fresh disk version' }).waitFor();
await page.keyboard.press("Control+z");
assert.ok((await writer.innerText()).includes("Fresh disk version"));
const tableSource = '# Table layout\n\n| Ticker | Name | Exchange | Products/Service | Notes |\n| :--- | --- | --- | --- | --- |\n| IBKR.US | Interactive Brokers Group Inc | NASDAQ | Broker | Rebuild the trading interface.<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 page.getByRole("button", { name: "Switch to writing layout (Ctrl E)", exact: true }).click();
const table = page.locator('.live-writer table');
await table.waitFor();
assert.equal(await page.locator('.live-writer .document-title').innerText(), 'tables');
const tableHeading = page.locator('.live-writer .writer-heading');
await tableHeading.click();
assert.equal(await tableHeading.innerText(), '# Table layout');
await table.locator('tbody tr').first().locator('td').first().click();
await page.waitForFunction(() => document.querySelector('.live-writer .writer-heading')?.textContent === 'Table layout');
await page.waitForFunction(() => [...document.querySelectorAll('.table-add')].every(button => getComputedStyle(button).opacity === '0'));
await page.keyboard.press('Control+s');
assert.equal(await page.evaluate(() => window.__TEST__.files.get('tables.md')), tableSource);
assert.equal(await table.locator('th').count(), 5);
assert.equal(await table.locator('tbody tr').count(), 2);
assert.equal(await table.locator('br').count(), 4);
assert.ok(!(await table.innerText()).includes('<br>'));
assert.ok(await table.locator('th').evaluateAll(cells => cells.every(cell => cell.getBoundingClientRect().width >= 100)));
assert.ok(await table.locator('td').evaluateAll(cells => cells.every(cell => getComputedStyle(cell).verticalAlign === 'top')));
assert.ok(await page.locator('.cm-scroller').evaluate(el => el.scrollWidth <= el.clientWidth + 1));
const addColumn = page.getByRole('button', { name: 'Add column to the right', exact: true });
const addRow = page.getByRole('button', { name: 'Add row below', exact: true });
await addColumn.hover();
await page.waitForFunction(() => getComputedStyle(document.querySelector('.table-add-column')).opacity === '1');
assert.equal(await addRow.evaluate(el => getComputedStyle(el).opacity), '0');
await table.locator('td').first().hover();
await page.waitForFunction(() => [...document.querySelectorAll('.table-add')].every(button => getComputedStyle(button).opacity === '0'));
await addColumn.hover();
await page.waitForFunction(() => getComputedStyle(document.querySelector('.table-add-column')).opacity === '1');
await page.screenshot({ path: '.audit/writing-table-column.png' });
await addColumn.click();
await page.waitForFunction(() => document.querySelectorAll('.live-writer th').length === 6);
await addRow.hover();
await page.waitForFunction(() => getComputedStyle(document.querySelector('.table-add-row')).opacity === '1');
await page.screenshot({ path: '.audit/writing-table-row.png' });
await addRow.click();
await page.waitForFunction(() => document.querySelectorAll('.live-writer tbody tr').length === 3);
await page.keyboard.press('Control+s');
await page.waitForFunction(() => window.__TEST__.files.get('tables.md').includes('| | | | | | |'));
assert.ok((await page.evaluate(() => window.__TEST__.files.get('tables.md'))).endsWith('\n\nAfter the table.\n'));
await page.keyboard.press('Control+z');
await page.waitForFunction(() => document.querySelectorAll('.live-writer tbody tr').length === 2);
await page.keyboard.press('Control+z');
await page.keyboard.press('Control+s');
await page.waitForFunction(expected => window.__TEST__.files.get('tables.md') === expected, tableSource);
await page.keyboard.press('Control+y');
await page.keyboard.press('Control+y');
await table.locator('th').last().click();
const cellEditor = page.locator('.writer-cell-editor');
await cellEditor.waitFor();
assert.equal(await table.locator('th').count(), 6);
assert.equal(await page.locator('.live-writer .cm-line').filter({ hasText: '| Ticker |' }).count(), 0);
await page.keyboard.type('New column');
await page.keyboard.press('Control+s');
await page.waitForFunction(() => window.__TEST__.files.get('tables.md').includes('New column'));
await page.keyboard.press('Tab');
assert.ok(await table.locator('tbody tr').first().locator('td').first().locator('.writer-cell-editor').count());
await page.keyboard.press('Shift+Tab');
assert.ok(await table.locator('th').last().locator('.writer-cell-editor').count());
await table.locator('tbody tr').first().locator('td').nth(4).click();
assert.equal(await cellEditor.locator('br:not(.ProseMirror-trailingBreak)').count(), 3);
await page.keyboard.press('Control+End');
await page.keyboard.press('Enter');
await page.keyboard.type('Plain | pipe and *stars*');
await page.keyboard.press('Control+s');
await page.waitForFunction(() => window.__TEST__.files.get('tables.md').includes('<br>Plain \\| pipe and \\*stars\\*'));
assert.equal(await table.locator('th').count(), 6);
await page.screenshot({ path: '.audit/writing-table-cell-edit.png' });
await page.keyboard.press('Control+z');
await page.keyboard.press('Control+s');
await page.waitForFunction(() => !window.__TEST__.files.get('tables.md').includes('Plain'));
await cellEditor.waitFor();
await page.keyboard.press('Control+y');
await page.keyboard.press('Control+s');
await page.waitForFunction(() => window.__TEST__.files.get('tables.md').includes('Plain'));
await page.keyboard.press('Escape');
await page.locator('.live-writer .cm-line').filter({ hasText: 'After the table.' }).click();
const beforeVisit = await page.evaluate(() => window.__TEST__.files.get('tables.md'));
await table.locator('tbody tr').first().locator('td').nth(4).click();
await page.keyboard.press('Escape');
await page.keyboard.press('Control+s');
assert.equal(await page.evaluate(() => window.__TEST__.files.get('tables.md')), beforeVisit);
await table.locator('tbody tr').last().locator('td').last().click();
await page.keyboard.press('Tab');
await page.waitForFunction(() => document.querySelectorAll('.live-writer tbody tr').length === 4);
await table.locator('tbody tr').last().locator('td').first().locator('.writer-cell-editor').waitFor();
await page.keyboard.press('Escape');
await page.setViewportSize({ width: 1000, height: 900 });
assert.ok(await page.locator('.cm-scroller').evaluate(el => el.scrollWidth <= el.clientWidth + 1));
await page.getByRole('button', { name: 'Read', exact: true }).click();
assert.equal(await page.locator('.md-page .document-title').innerText(), 'tables');
assert.equal(await page.locator('.md-page table br').count(), 5);
assert.ok(await page.locator('.md-page').evaluate(el => el.scrollWidth <= el.clientWidth + 1));
const selectionTable = '| A | B | C |\n| --- | --- | --- |\n| one | two | three |\n| four | five | six |\n\nAfter.\n';
await page.evaluate(text => {
window.__TEST__.files.set('selection-table.md', text);
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['selection-table.md'] });
window.__TEST__.clipboard = '';
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: {
writeText: async text => { window.__TEST__.clipboard = text; },
readText: async () => window.__TEST__.clipboard,
} });
}, selectionTable);
await quickOpen('selection-table.md');
await page.getByRole('button', { name: 'Edit', exact: true }).click();
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
const selectedTable = page.locator('.live-writer table');
const selectedCell = (r, c) => selectedTable.locator('tr').nth(r).locator('th, td').nth(c);
const fromCell = await selectedCell(1, 0).boundingBox(), toCell = await selectedCell(2, 1).boundingBox();
await page.mouse.move(fromCell.x + 15, fromCell.y + 15);
await page.mouse.down();
await page.mouse.move(toCell.x + 15, toCell.y + 15, { steps: 12 });
await page.mouse.up();
assert.equal(await selectedTable.locator('.is-cell-selected').count(), 4);
await selectedCell(1, 0).click({ button: 'right' });
await page.getByRole('menuitem', { name: 'Format', exact: true }).hover();
await page.getByRole('menuitem', { name: 'Bold', exact: true }).waitFor();
await page.screenshot({ path: '.audit/table-cell-selection-menu.png' });
await page.getByRole('menuitem', { name: 'Bold', exact: true }).click();
await page.waitForFunction(() => document.querySelectorAll('.live-writer table strong').length === 4);
await page.waitForFunction(() => document.querySelectorAll('.is-cell-selected').length === 4);
await page.keyboard.press('Control+i');
await page.waitForFunction(() => document.querySelectorAll('.live-writer table em').length === 4);
await page.keyboard.press('Control+z');
await page.waitForFunction(() => document.querySelectorAll('.live-writer table em').length === 0);
assert.equal(await selectedTable.locator('strong').count(), 4);
await selectedCell(1, 0).click();
await selectedCell(2, 1).click({ modifiers: ['Shift'] });
assert.equal(await selectedTable.locator('.is-cell-selected').count(), 4);
async function cellAction(name, formatted = false) {
await selectedTable.locator('.is-cell-selected').first().click({ button: 'right' });
if (formatted) await page.getByRole('menuitem', { name: 'Format', exact: true }).hover();
await page.getByRole('menuitem', { name, exact: true }).click();
}
await cellAction('Clear formatting', true);
await page.waitForFunction(() => document.querySelectorAll('.live-writer table strong').length === 0);
await cellAction('Copy');
assert.equal(await page.evaluate(() => window.__TEST__.clipboard), 'one\ttwo\nfour\tfive');
await cellAction('Cut');
await page.waitForFunction(() => [...document.querySelectorAll('.is-cell-selected')].every(cell => !cell.textContent.trim()));
await cellAction('Paste');
await page.waitForFunction(() => document.querySelector('.live-writer tbody td').textContent === 'one');
await cellAction('Align centre');
await page.waitForFunction(() => [...document.querySelectorAll('.is-cell-selected')].every(cell => cell.style.textAlign === 'center'));
for (const [name, selector] of [['Highlight', 'mark'], ['Math', '[data-cell-format="math"]'], ['Comment', '[data-cell-format="comment"]'], ['Code', 'code'], ['Strikethrough', 's']]) {
await cellAction(name, true);
await page.waitForFunction(selector => document.querySelectorAll(`.live-writer table ${selector}`).length === 4, selector);
await cellAction('Clear formatting', true);
}
// Native clipboard events must operate on the rectangle, including one-step undo.
await page.locator('.writer-table').evaluate(el => {
const data = new DataTransfer(); data.setData('text/plain', 'red\tblue\ngreen\tyellow');
el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: data, bubbles: true, cancelable: true }));
});
await page.waitForFunction(() => document.querySelector('.live-writer tbody td').textContent === 'red');
await page.keyboard.press('Control+z');
await page.waitForFunction(() => document.querySelector('.live-writer tbody td').textContent === 'one');
await selectedCell(1, 0).click();
await selectedCell(2, 1).click({ modifiers: ['Shift'] });
await cellAction('Delete cells');
await page.waitForFunction(() => document.querySelector('.live-writer tbody td').textContent === 'three');
assert.equal(await selectedTable.locator('th').count(), 3);
await page.keyboard.press('Control+z');
await page.waitForFunction(() => document.querySelector('.live-writer tbody td').textContent === 'one');
await selectedCell(1, 0).click();
await selectedCell(1, 0).click({ modifiers: ['Shift'] });
await page.keyboard.press('Control+a');
assert.equal(await selectedTable.locator('.is-cell-selected').count(), 9);
await cellAction('Delete cells');
await page.waitForFunction(() => document.querySelectorAll('.live-writer table').length === 0);
await page.keyboard.press('Control+z');
await selectedTable.waitFor();
for (const [name, selector] of [['Highlight', 'mark'], ['Math', '[data-cell-format="math"]'], ['Comment', '[data-cell-format="comment"]']]) {
await selectedCell(1, 0).click();
await selectedCell(1, 0).click({ modifiers: ['Shift'] });
await selectedCell(1, 0).click({ button: 'right' });
await page.getByRole('menuitem', { name: 'Format', exact: true }).hover();
await page.getByRole('menuitem', { name, exact: true }).click();
await selectedCell(1, 0).click();
await page.keyboard.press('Control+End');
await page.keyboard.type(' edited');
await page.keyboard.press('Escape');
assert.ok(await selectedCell(1, 0).locator(selector).count(), `${name} survives cell editing`);
await selectedCell(1, 0).click();
await selectedCell(1, 0).click({ modifiers: ['Shift'] });
await selectedCell(1, 0).click({ button: 'right' });
await cellAction('Clear formatting', true);
}
const actionsSource = '| Name | Value |\n| :--- | ---: |\n| Interactive Brokers Group | 20 |\n| Apple | 3 |\n| Pear | 10 |\n\nAfter.\n';
await page.evaluate(text => {
window.__TEST__.files.set('table-actions.md', text);
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['table-actions.md'] });
}, actionsSource);
await quickOpen('table-actions.md');
await page.getByRole('button', { name: 'Edit', exact: true }).click();
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
const actionTable = page.locator('.live-writer table');
const actionCell = (r, c) => actionTable.locator('tr').nth(r).locator('th, td').nth(c);
async function actionItem(label, group, r = 1, c = 0) {
await actionCell(r, c).click({ button: 'right' });
if (group) await page.getByRole('menuitem', { name: group, exact: true }).hover();
await page.getByRole('menuitem', { name: label, exact: true }).click();
}
async function saveActionSource() {
await page.keyboard.press('Control+s');
return page.evaluate(() => window.__TEST__.files.get('table-actions.md'));
}
async function undoAction() {
await page.keyboard.press('Control+z');
await page.keyboard.press('Control+s');
await page.waitForFunction(expected => window.__TEST__.files.get('table-actions.md') === expected, actionsSource);
}
for (const [label, group, r, c, rows, columns] of [
['Add row above', 'Row', 1, 0, 5, 2], ['Add row below', 'Row', 2, 0, 5, 2], ['Duplicate row', 'Row', 1, 0, 5, 2], ['Delete row', 'Row', 1, 0, 3, 2],
['Add column to the left', 'Column', 1, 0, 4, 3], ['Add column to the right', 'Column', 1, 1, 4, 3], ['Duplicate column', 'Column', 1, 1, 4, 3], ['Delete column', 'Column', 1, 1, 4, 1],
]) {
await actionItem(label, group, r, c);
assert.equal(await actionTable.locator('tr').count(), rows, label);
assert.equal(await actionTable.locator('th').count(), columns, label);
await undoAction();
}
await actionItem('Move row down', 'Row');
assert.equal(await actionCell(2, 0).innerText(), 'Interactive Brokers Group');
await undoAction();
await actionItem('Move row up', 'Row', 2);
assert.equal(await actionCell(1, 0).innerText(), 'Apple');
await undoAction();
await actionItem('Move column right', 'Column');
assert.equal(await actionCell(0, 0).innerText(), 'Value');
assert.equal(await actionCell(1, 0).evaluate(el => el.style.textAlign), 'right');
await undoAction();
await actionItem('Move column left', 'Column', 1, 1);
assert.equal(await actionCell(0, 0).innerText(), 'Value');
await undoAction();
await actionItem('Sort by column (A to Z)', undefined, 1, 1);
assert.deepEqual(await actionTable.locator('tbody tr td:last-child').allTextContents(), ['3', '10', '20']);
await undoAction();
await actionItem('Sort by column (Z to A)', undefined, 1, 1);
assert.deepEqual(await actionTable.locator('tbody tr td:last-child').allTextContents(), ['20', '10', '3']);
await undoAction();
await actionCell(0, 0).click({ button: 'right' });
await page.getByRole('menuitem', { name: 'Row', exact: true }).hover();
assert.ok(await page.getByRole('menuitem', { name: 'Add row above', exact: true }).isDisabled());
assert.ok(await page.getByRole('menuitem', { name: 'Move row down', exact: true }).isDisabled());
await page.keyboard.press('Escape');
async function selectBrokers() {
await actionCell(1, 0).click();
await page.keyboard.press('Control+Home');
for (let i = 0; i < 12; i++) await page.keyboard.press('ArrowRight');
for (let i = 0; i < 7; i++) await page.keyboard.press('Shift+ArrowRight');
assert.equal(await page.evaluate(() => getSelection().toString()), 'Brokers');
}
await selectBrokers();
await actionCell(1, 0).click({ button: 'right' });
assert.equal(await page.getByRole('menuitem', { name: 'Copy', exact: true }).isDisabled(), false);
assert.ok(await page.locator('.table-cell-menu button').evaluateAll(buttons => buttons.every(button => button.querySelector('svg[aria-hidden="true"]'))));
await page.getByRole('menuitem', { name: 'Row', exact: true }).hover();
await page.screenshot({ path: '.audit/table-text-row-menu.png' });
await page.getByRole('menuitem', { name: 'Column', exact: true }).hover();
await page.screenshot({ path: '.audit/table-text-column-menu.png' });
await page.getByRole('menuitem', { name: 'Column', exact: true }).focus();
await page.keyboard.press('ArrowRight');
assert.equal(await page.evaluate(() => document.activeElement.textContent), 'Add column to the left');
await page.keyboard.press('ArrowLeft');
assert.equal(await page.evaluate(() => document.activeElement.textContent), 'Column');
await page.keyboard.press('Escape');
await actionItem('Bold', 'Format');
assert.equal(await actionCell(1, 0).locator('strong').innerText(), 'Brokers');
assert.ok((await saveActionSource()).includes('Interactive **Brokers** Group'));
await actionItem('Add external link');
await page.getByRole('dialog').locator('input').fill('https://example.com/brokers?q=1');
await page.getByRole('button', { name: 'Continue', exact: true }).click();
await page.waitForFunction(() => document.querySelector('.live-writer td a')?.getAttribute('href') === 'https://example.com/brokers?q=1');
assert.equal(await actionCell(1, 0).locator('a').innerText(), 'Brokers');
await page.keyboard.press('Control+z');
await selectBrokers();
await actionItem('Add link');
await page.getByRole('dialog').locator('input').fill('notes/second');
await page.getByRole('button', { name: 'Continue', exact: true }).click();
await page.waitForFunction(() => document.querySelector('.live-writer td a')?.getAttribute('data-kind') === 'wiki');
await page.keyboard.press('Control+z');
await selectBrokers();
await actionItem('Search for “Brokers”');
await page.getByPlaceholder('Search files and notes').waitFor();
assert.equal(await page.getByPlaceholder('Search files and notes').inputValue(), 'Brokers');
await page.waitForFunction(() => window.__TEST__.calls.some(call => call.command === 'workspace_search' && call.args.query === 'Brokers'));
await selectBrokers();
await actionItem('Extract current selection…');
await page.getByRole('dialog').locator('input').fill('extracted-brokers.md');
await page.getByRole('button', { name: 'Continue', exact: true }).click();
await page.waitForFunction(() => window.__TEST__.files.get('extracted-brokers.md') === '**Brokers**\n');
await page.waitForFunction(() => document.querySelector('.live-writer td a')?.getAttribute('href') === '/extracted-brokers.md');
await page.keyboard.press('Control+z');
await selectBrokers();
await page.evaluate(() => { window.__TEST__.clipboard = '<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 page.getByRole('button', { name: 'Edit', exact: true }).click();
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
const richCell = page.locator('.live-writer tbody tr').first().locator('td').last();
assert.equal(await page.locator('.live-writer .document-title').innerText(), 'rich-table');
await richCell.click();
await page.keyboard.press('Control+s');
assert.equal(await page.evaluate(() => window.__TEST__.files.get('rich-table.md')), richTable);
await page.keyboard.press('Control+End');
await page.keyboard.type(' edited');
await page.keyboard.press('Control+s');
await page.waitForFunction(() => window.__TEST__.files.get('rich-table.md').includes('edited'));
const richSaved = await page.evaluate(() => window.__TEST__.files.get('rich-table.md'));
assert.ok(richSaved.includes('| Untouched |'));
assert.ok(richSaved.includes('~~Old~~'));
assert.ok(richSaved.includes('**bold**'));
assert.ok(richSaved.includes('https://example.com'));
assert.ok(richSaved.includes('![attachment](<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 page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
async function clickRenderedLine(locator, expected) {
await locator.scrollIntoViewIfNeeded();
const rect = await locator.boundingBox();
assert.ok(rect);
await page.mouse.click(rect.x + 45, rect.y + rect.height * .7);
const actual = await page.evaluate(() => window.getSelection()?.anchorNode?.parentElement?.closest('.cm-line')?.textContent);
assert.equal(actual, expected, `Mouse click on ${expected} landed on ${actual}`);
}
async function checkLinesAfterTables() {
await page.locator('.cm-scroller').evaluate(async el => {
el.scrollTop = 0;
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
});
for (const [heading, body] of [
['# Tier 1', 'Tier one body directly below heading.'],
['## Tier 2', 'Tier two body directly below heading.'],
]) {
const tables = page.locator('.live-writer .writer-table');
await (heading === '# Tier 1' ? tables.first() : tables.last()).locator('.table-add-row').scrollIntoViewIfNeeded();
await clickRenderedLine(page.locator('.live-writer .writer-heading').filter({ hasText: heading.replace(/^#+ /, '') }), heading);
await page.keyboard.press('End');
await page.keyboard.type(' edited');
await page.keyboard.press('Control+s');
await page.waitForFunction(text => window.__TEST__.files.get('table-hit-testing.md').includes(text + ' edited\n'), heading);
await page.keyboard.press('Control+z');
await clickRenderedLine(page.locator('.live-writer .cm-line').filter({ hasText: body }), body);
}
}
await page.setViewportSize({ width: 1440, height: 1000 });
await checkLinesAfterTables();
await page.locator('.cm-scroller').evaluate(async el => {
el.scrollTop = 0;
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
});
await page.locator('.live-writer table').first().locator('tbody tr').last().locator('td').last().click();
await page.keyboard.press('Control+End');
for (let line = 0; line < 4; line++) {
await page.keyboard.press('Enter');
await page.keyboard.type('A newly added line changes the table height.');
}
await checkLinesAfterTables();
await page.setViewportSize({ width: 1000, height: 900 });
await checkLinesAfterTables();
await page.screenshot({ path: '.audit/table-cursor-position.png' });
assert.deepEqual(errors, []);
console.log("PASS: continuous live Markdown, raw active lines, editable links and checklists, completed-task strikethrough, cross-line selection, preservation and history, search, table layout/line breaks/edge insertion/cell editing/undo, save, agent refresh, conflicts, persistent terminals, reader and Mermaid previews, narrow layouts (mocked desktop IPC).");
} catch (error) {
console.error("Browser errors:", errors);
console.error("Writing source:", await page.evaluate(() => window.__TEST__?.files.get("writing.md")));
console.error("Visible text:", (await page.locator("body").innerText()).slice(0, 5000));
await page.screenshot({ path: ".audit/core-rebuild-failure.png" });
throw error;
} finally { await browser.close(); }