Move the smoke tests onto the shared harness

Each smoke test now uses tests/smoke/_harness/ for Playwright, the Tauri
IPC mock, the in-memory workspace, and output folders, instead of its
own copy. The tests keep their interactions and assertions. Mock
handlers that the app never calls are gone.

- Split the four mixed regression scripts into 18 feature tests.
- Update tests that broke when the app changed on purpose. Each update
  cites the app source that shows the new behavior.
- Mark two real app defects with @known-issue: the settings window
  controls are 1px shorter than the main window controls, and plugin
  tabs cannot be reordered by dragging without a workspace.
- Merge three palette unit tests into one table-driven test.
- The native tests load Playwright through the harness and read
  NATIVE_CDP_URL, with their old variable names as fallbacks.
- A failed smoke test saves a screenshot and prints the console errors.
- The runner runs failed tests once more, alone, and reports a test
  that then passes as flaky.

Result: 89 passed, 1 flaky, 2 known issues, 0 failed. Before, 45 of 78
passed.
This commit is contained in:
Knotty Wyvern
2026-10-27 20:58:55 -07:00
parent c66ea1ce83
commit 69f90df571
109 changed files with 5920 additions and 7915 deletions
+77 -113
View File
@@ -1,105 +1,75 @@
import { createRequire } from "node:module";
// File tree actions on multiple selections: clipboard paths, marks, copies, deletion, group moves, and reordering.
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 page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\tree-actions-test";
const files = new Map([
["notes/a.md", "# A"], ["notes/nested/b.md", "# B"],
["target/a.md", "# Existing"], ["a.md", "# A"], ["b.md", "# B"], ["c.md", "# C"],
]);
const calls = [];
const state = { files, calls, answer: "Ok", fail: "", clipboard: "" };
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { state.clipboard = text; } } });
let sequence = 0;
const contains = (parent, path) => path === parent || path.startsWith(parent + "/");
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: () => ++sequence,
unregisterCallback: () => {},
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") return ++sequence;
if (command === "plugin:event|unlisten") return;
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "tree-actions-test", 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") { files.set(args.rel, args.contents); 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_delete") {
if (args.rel === state.fail) throw new Error("Access denied");
for (const path of [...files.keys()]) if (contains(args.rel, path)) files.delete(path);
return;
}
if (command === "workspace_copy") {
const to = args.rel + "-copy";
for (const [path, text] of [...files]) if (contains(args.rel, path)) files.set(to + path.slice(args.rel.length), text);
return { name: to.split("/").pop(), rel_path: to, kind: files.has(to) ? "file" : "folder" };
}
if (command === "workspace_rename") {
if ([...files.keys()].some(path => contains(args.to, path))) throw new Error("Destination exists");
for (const [path, text] of [...files]) if (contains(args.from, path)) {
files.delete(path);
files.set(args.to + path.slice(args.from.length), text);
}
return;
}
if (command === "workspace_abs_path") return root + "\\" + args.rel.replaceAll("/", "\\");
if (command === "workspace_reveal") return;
if (command === "workspace_search") return [];
if (command === "plugin:dialog|message") return state.answer;
throw new Error(`Unhandled IPC: ${command}`);
import { mockTauri, runSmoke, settle as settleFrames, smokeUrl } from "../_harness/index.mjs";
await runSmoke("tree/actions", async ({ page }) => {
await mockTauri(page, {
commands: test => {
const contains = (parent, path) => path === parent || path.startsWith(parent + "/");
const ws = test.workspace({
root: "C:\\tree-actions-test",
files: { "notes/a.md": "# A", "notes/nested/b.md": "# B", "target/a.md": "# Existing", "a.md": "# A", "b.md": "# B", "c.md": "# C" },
});
const files = ws.files;
Object.assign(test, { files, answer: "Ok", fail: "", clipboard: "" });
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { test.clipboard = text; } } });
return {
...ws,
workspace_list: args => ws.workspace_list(args).filter(entry => !entry.rel_path.startsWith(".runestone")),
workspace_delete: ({ rel }) => {
if (rel === test.fail) throw new Error("Access denied");
for (const path of [...files.keys()]) if (contains(rel, path)) files.delete(path);
},
workspace_copy: ({ rel }) => {
const to = rel + "-copy";
for (const [path, text] of [...files]) if (contains(rel, path)) files.set(to + path.slice(rel.length), text);
return { name: to.split("/").pop(), rel_path: to, kind: files.has(to) ? "file" : "folder" };
},
workspace_rename: ({ from, to }) => {
if ([...files.keys()].some(path => contains(to, path))) throw new Error("Destination exists");
for (const [path, text] of [...files]) if (contains(from, path)) {
files.delete(path);
files.set(to + path.slice(from.length), text);
}
},
workspace_reveal: () => null,
"plugin:dialog|message": () => test.answer,
};
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
window.__TEST__ = state;
});
const row = rel => page.locator(`[data-tree-rel="${rel}"]`);
const selected = () => page.locator('[role="treeitem"][aria-selected="true"]').evaluateAll(nodes => nodes.map(node => node.dataset.treeRel));
const calls = command => page.evaluate(command => window.__TEST__.calls.filter(call => call.command === command).map(call => call.args), command);
const settle = () => page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
async function reset() {
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
await row("notes").waitFor();
}
async function action(path, name) {
await row(path).click({ button: "right" });
await page.getByRole("menuitem", { name, exact: true }).click();
await settle();
}
async function selectFiles() {
await row("a.md").click();
await page.getByRole("tab", { name: "a.md", exact: true }).waitFor();
await settle();
await row("b.md").click({ modifiers: ["Control"] });
await settle();
}
async function drag(sourcePath, targetPath, place = "inside") {
const source = await row(sourcePath).boundingBox();
const target = await row(targetPath).boundingBox();
await page.mouse.move(source.x + source.width / 2, source.y + source.height / 2);
await page.mouse.down();
await page.mouse.move(target.x + target.width / 2, target.y + target.height * (place === "before" ? 0.1 : place === "after" ? 0.9 : 0.5), { steps: 10 });
await page.mouse.up();
await settle();
}
try {
});
const row = rel => page.locator(`[data-tree-rel="${rel}"]`);
const selected = () => page.locator('[role="treeitem"][aria-selected="true"]').evaluateAll(nodes => nodes.map(node => node.dataset.treeRel));
const calls = command => page.evaluate(command => window.__TEST__.calls.filter(call => call.command === command).map(call => call.args), command);
const settle = () => settleFrames(page);
const marks = () => page.evaluate(() => JSON.parse(window.__TEST__.files.get(".runestone/marks.json")));
// Mutations name the workspace root they expect (src/lib/workspace/api.ts:63).
const expectedRoot = "C:\\tree-actions-test";
async function reset() {
await page.goto(smokeUrl);
await row("notes").waitFor();
}
async function action(path, name) {
await row(path).click({ button: "right" });
await page.getByRole("menuitem", { name, exact: true }).click();
await settle();
}
async function selectFiles() {
await row("a.md").click();
await page.getByRole("tab", { name: "a.md", exact: true }).waitFor();
await settle();
await row("b.md").click({ modifiers: ["Control"] });
await settle();
}
async function drag(sourcePath, targetPath, place = "inside") {
const source = await row(sourcePath).boundingBox();
const target = await row(targetPath).boundingBox();
await page.mouse.move(source.x + source.width / 2, source.y + source.height / 2);
await page.mouse.down();
await page.mouse.move(target.x + target.width / 2, target.y + target.height * (place === "before" ? 0.1 : place === "after" ? 0.9 : 0.5), { steps: 10 });
await page.mouse.up();
await settle();
}
await reset();
await selectFiles();
await row("a.md").click({ button: "right" });
@@ -114,9 +84,8 @@ try {
assert.deepEqual((await calls("workspace_reveal")).map(args => args.rel), ["a.md", "b.md"]);
await action("a.md", "Bookmark");
await action("b.md", "Pin");
let marks = await page.evaluate(() => JSON.parse(window.__TEST__.files.get(".runestone/marks.json")));
assert.deepEqual(marks.bookmarks, ["a.md", "b.md"]);
assert.deepEqual(marks.pins, ["a.md", "b.md"]);
assert.deepEqual((await marks()).bookmarks, ["a.md", "b.md"]);
assert.deepEqual((await marks()).pins, ["a.md", "b.md"]);
await action("a.md", "Unpin");
await action("a.md", "Remove bookmarks");
await action("a.md", "Make copies (2)");
@@ -161,7 +130,7 @@ try {
await selectFiles();
await drag("a.md", "target");
await row("target/b.md").waitFor();
assert.deepEqual((await calls("workspace_rename")), [{ from: "a.md", to: "target/a 2.md" }, { from: "b.md", to: "target/b.md" }]);
assert.deepEqual(await calls("workspace_rename"), [{ from: "a.md", to: "target/a 2.md", expectedRoot }, { from: "b.md", to: "target/b.md", expectedRoot }]);
assert.deepEqual(await selected(), ["target/a 2.md", "target/b.md"]);
console.log("PASS: group move into a collapsed folder preserves an existing same-name file");
@@ -173,7 +142,7 @@ try {
assert.equal((await calls("workspace_rename")).length, 0);
await drag("notes/a.md", "target");
await row("target/notes").waitFor();
assert.deepEqual(await calls("workspace_rename"), [{ from: "notes", to: "target/notes" }, { from: "c.md", to: "target/c.md" }]);
assert.deepEqual(await calls("workspace_rename"), [{ from: "notes", to: "target/notes", expectedRoot }, { from: "c.md", to: "target/c.md", expectedRoot }]);
assert.deepEqual(await selected(), ["target/notes", "target/c.md"]);
await row("target/notes").click();
await row("target/notes/a.md").waitFor();
@@ -182,17 +151,12 @@ try {
await reset();
await selectFiles();
await drag("a.md", "c.md", "after");
marks = await page.evaluate(() => JSON.parse(window.__TEST__.files.get(".runestone/marks.json")));
assert.deepEqual(marks.order[""].filter(name => name.endsWith(".md")), ["c.md", "a.md", "b.md"]);
assert.deepEqual((await marks()).order[""].filter(name => name.endsWith(".md")), ["c.md", "a.md", "b.md"]);
await drag("b.md", "c.md", "before");
marks = await page.evaluate(() => JSON.parse(window.__TEST__.files.get(".runestone/marks.json")));
assert.deepEqual(marks.order[""].filter(name => name.endsWith(".md")), ["a.md", "b.md", "c.md"]);
assert.deepEqual(errors, []);
assert.deepEqual((await marks()).order[""].filter(name => name.endsWith(".md")), ["a.md", "b.md", "c.md"]);
if (process.env.SCREENSHOT_PATH) {
await row("a.md").click({ button: "right" });
await page.screenshot({ path: process.env.SCREENSHOT_PATH });
}
console.log("PASS: group reorder preserves selected row order in both directions");
} finally {
await browser.close();
}
});
+38
View File
@@ -0,0 +1,38 @@
// Folder actions in the tree: Open in terminal, and the Show .runestone folder setting from the settings window.
import assert from "node:assert/strict";
import { mockTauri, openPage, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("tree/folderActions", async ({ browser }) => {
// The settings window shares localStorage with the main window, so both pages need one context.
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
await mockTauri(context, {
commands: test => {
const workspace = test.workspace({ root: "C:\\folder-actions", files: { "a.md": "# Alpha\n", "folder/keep.md": "# Keep\n", ".runestone/config.json": "{}" } });
return {
...workspace,
workspace_list: args => workspace.workspace_list(args).filter(entry => args.rel || args.showInternal || entry.rel_path !== ".runestone"),
workspace_open_terminal: () => null,
settings_open_window: () => null,
plugins_snapshot: () => ({ plugins: [], issues: [] }),
spelling_menu_install: () => null,
};
},
});
const page = await openPage(context, { timeout: 15000 });
const row = path => page.locator(`[data-tree-rel="${path}"]`);
await page.goto(smokeUrl);
await row("folder").click({ button: "right" });
await page.getByRole("menuitem", { name: "Open in terminal", exact: true }).click();
assert.ok(await page.evaluate(() => window.__TEST__.calls.some(call => call.command === "workspace_open_terminal" && call.args.rel === "folder")));
console.log("PASS: Open in terminal");
await page.keyboard.press("Control+,");
const settings = await openPage(context, { timeout: 15000 });
await settings.goto(smokeUrl + "/?settingsWindow=true");
await settings.getByRole("switch", { name: "Show .runestone folder" }).check();
await settings.close();
await row(".runestone").waitFor();
const errors = [...page.errors, ...settings.errors];
assert.deepEqual(errors, []);
console.log("PASS: Show .runestone folder reveals the internal folder");
});
+45
View File
@@ -0,0 +1,45 @@
// File moves in the tree: cut and paste, Undo and Redo file move from the folder menu, Ctrl+Z, and drag into a folder.
import { mockTauri, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("tree/moveUndo", async ({ page }) => {
await mockTauri(page, {
commands: test => {
const workspace = test.workspace({ root: "C:\\move-undo", files: { "a.md": "# Alpha\n", "b.md": "# Beta\n", "folder/keep.md": "# Keep\n" } });
test.files = workspace.files;
return {
...workspace,
plugins_snapshot: () => ({ plugins: [], issues: [] }),
spelling_menu_install: () => null,
};
},
});
const row = path => page.locator(`[data-tree-rel="${path}"]`);
const menu = label => page.getByRole("menuitem", { name: label, exact: true });
const has = path => page.waitForFunction(path => window.__TEST__.files.has(path), path);
await page.goto(smokeUrl);
await row("b.md").click({ button: "right" });
await menu("Cut").click();
await row("folder").click({ button: "right" });
await menu("Paste").click();
await has("folder/b.md");
await row("folder").click({ button: "right" });
await menu("Undo file move").click();
await has("b.md");
await row("folder").click({ button: "right" });
await menu("Redo file move").click();
await has("folder/b.md");
await row("folder").focus();
await page.keyboard.press("Control+z");
await has("b.md");
console.log("PASS: cut and paste, menu undo and redo, and Ctrl+Z");
const sourceBox = await row("b.md").boundingBox(), folderBox = await row("folder").boundingBox();
await page.mouse.move(sourceBox.x + 50, sourceBox.y + sourceBox.height / 2);
await page.mouse.down();
await page.mouse.move(folderBox.x + 70, folderBox.y + folderBox.height / 2, { steps: 12 });
await page.mouse.up();
await has("folder/b.md");
await page.keyboard.press("Control+z");
await has("b.md");
console.log("PASS: drag into a folder, and Ctrl+Z");
}, { timeout: 15000 });
+51 -75
View File
@@ -1,70 +1,44 @@
import { createRequire } from 'node:module';
// Splash actions and order, and New folder with inline rename in the root, collapsed, and empty folders, with and without a workspace.
import assert from 'node:assert/strict';
import { mkdir, writeFile } from 'node:fs/promises';
import { writeFile } from 'node:fs/promises';
import path from 'node:path';
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
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: 850 } });
const page = await context.newPage();
page.setDefaultTimeout(10000);
const errors = [];
page.on('pageerror', error => errors.push(error.message));
await context.addInitScript(() => {
window.isTauri = true;
const root = 'C:\\navigation-check';
const folders = new Set(['Untitled', 'Parent', 'Empty']);
const files = new Map([['note.md', '# Note'], ['Parent/existing.md', '# Existing']]);
const state = { folders, files, calls: [] };
window.__NAVIGATION_CHECK__ = state;
let sequence = 0;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
transformCallback: () => ++sequence, unregisterCallback: () => {},
invoke: async (command, args = {}) => {
state.calls.push({ command, args });
if (command === 'plugins_snapshot') return { root: 'C:/plugins', plugins: [] };
if (command === 'workspace_last_path') return state.noWorkspace ? null : root;
if (command === 'workspace_open') return { root, name: 'navigation-check', watch_mode: 'native' };
if (command === 'workspace_read') { if (!files.has(args.rel)) throw new Error('Missing file'); return files.get(args.rel); }
if (command === 'workspace_write') { files.set(args.rel, args.contents); return; }
if (command === 'workspace_list') {
const prefix = args.rel ? args.rel + '/' : '';
return [...[...folders].filter(path => path.startsWith(prefix) && !path.slice(prefix.length).includes('/')).map(path => ({ name: path.slice(prefix.length), rel_path: path, kind: 'folder' })),
...[...files.keys()].filter(path => path.startsWith(prefix) && !path.slice(prefix.length).includes('/') && !path.startsWith('.runestone/')).map(path => ({ name: path.slice(prefix.length), rel_path: path, kind: 'file' }))];
}
if (command === 'workspace_create') { if (folders.has(args.rel) || files.has(args.rel)) throw new Error('Destination exists'); if (args.kind === 'folder') folders.add(args.rel); else files.set(args.rel, ''); return; }
if (command === 'workspace_rename') {
if (folders.has(args.to) || files.has(args.to)) throw new Error('Destination exists');
if (folders.delete(args.from)) folders.add(args.to);
else { files.set(args.to, files.get(args.from)); files.delete(args.from); }
return;
}
if (command === 'plugin:event|listen') return ++sequence;
if (command === 'plugin:window|is_maximized') return false;
if (command === 'workspace_recent' || command === 'workspace_search') return [];
return null;
await runSmoke('tree/navigation', async ({ browser }) => {
const context = await browser.newContext({ viewport: { width: 1280, height: 850 } });
await mockTauri(context, {
strict: false,
commands: test => {
const ws = test.workspace({ root: 'C:\\navigation-check', folders: ['Untitled', 'Parent', 'Empty'], files: { 'note.md': '# Note', 'Parent/existing.md': '# Existing' } });
test.folders = ws.folders;
return {
...ws,
workspace_last_path: () => test.noWorkspace ? null : ws.root,
workspace_list: args => ws.workspace_list(args).filter(entry => !entry.rel_path.startsWith('.runestone')),
workspace_search: () => [],
plugins_snapshot: () => ({ root: 'C:/plugins', plugins: [] }),
'plugin:window|is_maximized': () => false,
};
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const output = '.audit/todo-navigation';
await mkdir(output, { recursive: true });
const row = path => page.locator(`[data-tree-rel="${path}"]`);
const input = () => page.locator('.tree input');
const folderAction = () => page.getByRole('menuitem', { name: 'New folder', exact: true });
async function checkRename(name) {
await input().waitFor();
await page.waitForFunction(() => document.activeElement?.matches('.tree input'));
const state = await input().evaluate(node => ({ name: node.value, start: node.selectionStart, end: node.selectionEnd }));
assert.deepEqual(state, { name, start: 0, end: name.length });
assert.equal(await page.getByRole('dialog').count(), 0, 'New folder uses inline rename');
}
async function setMode(mode) {
await page.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); }, mode);
}
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:5194');
});
const page = await openPage(context);
const output = await outputDir('tree/navigation');
const shot = name => page.screenshot({ path: path.join(output, name) });
const row = rel => page.locator(`[data-tree-rel="${rel}"]`);
const input = () => page.locator('.tree input');
const folderAction = () => page.getByRole('menuitem', { name: 'New folder', exact: true });
async function checkRename(name) {
await input().waitFor();
await page.waitForFunction(() => document.activeElement?.matches('.tree input'));
const state = await input().evaluate(node => ({ name: node.value, start: node.selectionStart, end: node.selectionEnd }));
assert.deepEqual(state, { name, start: 0, end: name.length });
assert.equal(await page.getByRole('dialog').count(), 0, 'New folder uses inline rename');
}
async function setMode(mode) {
await page.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); }, mode);
}
await page.goto(smokeUrl);
await row('Untitled').waitFor();
const welcome = page.locator('.welcome-actions');
await welcome.waitFor();
@@ -82,9 +56,9 @@ try {
for (const mode of ['dark', 'light']) {
await setMode(mode);
await welcome.getByRole('button', { name: /^New file/ }).focus();
await page.screenshot({ path: `${output}/splash-${mode}.png` });
await shot(`splash-${mode}.png`);
await page.setViewportSize({ width: 850, height: 650 });
await page.screenshot({ path: `${output}/splash-${mode}-narrow.png` });
await shot(`splash-${mode}-narrow.png`);
assert.ok(await welcome.locator('button').evaluateAll(nodes => nodes.every(node => { const rect = node.getBoundingClientRect(); return rect.left >= 0 && rect.right <= innerWidth; })), 'Narrow splash controls fit');
await page.setViewportSize({ width: 1280, height: 850 });
}
@@ -110,9 +84,9 @@ try {
await folderAction().click();
const expected = mode === 'dark' ? 'untitled 2' : 'untitled 3';
await checkRename(expected);
await page.screenshot({ path: `${output}/new-folder-${mode}.png` });
await shot(`new-folder-${mode}.png`);
await page.setViewportSize({ width: 850, height: 650 });
await page.screenshot({ path: `${output}/new-folder-${mode}-narrow.png` });
await shot(`new-folder-${mode}-narrow.png`);
await input().press('Escape');
await page.setViewportSize({ width: 1280, height: 850 });
}
@@ -122,16 +96,18 @@ try {
await input().fill('First folder');
await input().press('Enter');
await row('Empty/First folder').waitFor();
assert.equal(await page.evaluate(() => window.__NAVIGATION_CHECK__.folders.has('Empty/First folder')), true);
const emptyPage = await context.newPage();
await emptyPage.addInitScript(() => { window.__NAVIGATION_CHECK__.noWorkspace = true; });
await emptyPage.goto(process.env.SMOKE_URL || 'http://127.0.0.1:5194');
assert.equal(await page.evaluate(() => window.__TEST__.folders.has('Empty/First folder')), true);
const emptyPage = await openPage(context);
await emptyPage.addInitScript(() => { window.__TEST__.noWorkspace = true; });
await emptyPage.goto(smokeUrl);
await emptyPage.locator('.welcome-actions').waitFor();
await emptyPage.locator('.welcome-actions').getByRole('button', { name: 'Open browser', exact: true }).waitFor();
assert.deepEqual(await emptyPage.locator('.welcome-actions button').allTextContents().then(values => values.map(value => value.replace(/Ctrl O/g, '').trim())), ['Open folder', 'Open browser']);
await emptyPage.screenshot({ path: `${output}/splash-no-workspace.png` });
await emptyPage.screenshot({ path: path.join(output, 'splash-no-workspace.png') });
await emptyPage.close();
const errors = [...page.errors, ...emptyPage.errors];
assert.deepEqual(errors, []);
await writeFile(`${output}/checks.json`, JSON.stringify({ passed: true, checks: ['Case-insensitive root name collision', 'Selected inline name and no dialog', 'Enter saves rename', 'Escape retains created folder', 'Collapsed cached parent opens', 'Empty parent', 'Repeated unique names', 'Splash order and three-column maximum', 'Keyboard tab order', 'No workspace actions', 'Dark/light wide/narrow screenshots'], errors }, null, 2));
await writeFile(path.join(output, 'checks.json'), JSON.stringify({ passed: true, checks: ['Case-insensitive root name collision', 'Selected inline name and no dialog', 'Enter saves rename', 'Escape retains created folder', 'Collapsed cached parent opens', 'Empty parent', 'Repeated unique names', 'Splash order and three-column maximum', 'Keyboard tab order', 'No workspace actions', 'Dark/light wide/narrow screenshots'], errors }, null, 2));
console.log(`Navigation checks passed. Evidence: ${output}`);
} finally { await browser.close(); }
});
+65 -76
View File
@@ -1,85 +1,71 @@
import { createRequire } from "node:module";
// New files keep exact names and extensions, renames change the code language, and Writer menus work in both themes.
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 page = await browser.newPage({ viewport: { width: 1280, height: 900 } });
page.setDefaultTimeout(15000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\editor-files-smoke";
const files = new Map([
["note.md", "Mispelled text.\n\n| Word | Value |\n| --- | --- |\n| Speling | Other |\n"],
["hello.txt", "print('hello')\n"],
["notes/existing.md", "Existing note"],
]);
window.editorFilesTest = { files, calls: [] };
let sequence = 0;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: () => ++sequence, unregisterCallback: () => {},
invoke: async (command, args = {}) => {
window.editorFilesTest.calls.push({ command, args });
if (command === "plugin:event|listen") return ++sequence;
if (command === "plugin:event|unlisten") return;
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "editor-files-smoke", 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") { files.set(args.rel, args.contents); return; }
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "", entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length), 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("path already exists");
files.set(args.rel, ""); return;
}
if (command === "workspace_rename") {
if (files.has(args.to)) throw new Error("destination already exists");
files.set(args.to, files.get(args.from)); files.delete(args.from); return;
}
if (command === "workspace_search") return [];
throw new Error(`Unhandled IPC: ${command}`);
import { mockTauri, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("tree/newFiles", async ({ page }) => {
await mockTauri(page, {
commands: test => {
const ws = test.workspace({
root: "C:\\editor-files-smoke",
files: {
"note.md": "Mispelled text.\n\n| Word | Value |\n| --- | --- |\n| Speling | Other |\n",
"hello.txt": "print('hello')\n",
"notes/existing.md": "Existing note",
},
});
const files = ws.files;
test.files = files;
return {
...ws,
workspace_list: args => ws.workspace_list(args).filter(entry => !entry.rel_path.startsWith(".runestone")),
workspace_create: ({ rel }) => {
if (files.has(rel)) throw new Error("path already exists");
files.set(rel, "");
},
workspace_rename: ({ from, to }) => {
if (files.has(to)) throw new Error("destination already exists");
files.set(to, files.get(from));
files.delete(from);
},
spelling_suggestions: ({ word }) => ({ language: "en-US", words: word === "Mispelled" ? ["Misspelled"] : [], misspelled: word === "Mispelled" }),
};
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const row = name => page.locator(`[data-tree-rel="${name}"]`);
async function enterName(name) {
await page.locator("#text-request").fill(name);
await page.getByRole("button", { name: "Continue", exact: true }).click();
}
async function modelDetails() {
return page.evaluate(async () => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
const editor = monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected);
return editor && { language: editor.getModel().getLanguageId(), value: editor.getValue(), fontSize: editor.getOption(monaco.editor.EditorOption.fontSize) };
});
}
try {
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
const row = name => page.locator(`[data-tree-rel="${name}"]`);
// The file pane header offers New note and New folder (src/lib/layout/FileTree.svelte:886-887);
// New file… is in the pane menu (src/lib/layout/FileTree.svelte:716-720).
async function newRootFile() {
await page.getByRole("navigation", { name: "Workspace files" }).click({ button: "right", position: { x: 80, y: 320 } });
await page.getByRole("menuitem", { name: "New file…", exact: true }).click();
}
async function enterName(name) {
await page.locator("#text-request").fill(name);
await page.getByRole("button", { name: "Continue", exact: true }).click();
}
async function modelDetails() {
return page.evaluate(async () => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
const editor = monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected);
return editor && { language: editor.getModel().getLanguageId(), value: editor.getValue(), fontSize: editor.getOption(monaco.editor.EditorOption.fontSize) };
});
}
await page.goto(smokeUrl);
await row("note.md").waitFor();
await page.getByRole("button", { name: "New file", exact: true }).click();
await newRootFile();
await enterName("LICENSE");
await row("LICENSE").waitFor();
await page.evaluate(() => window.editorFilesTest.files.set("LICENSE", "Keep this content"));
await page.getByRole("button", { name: "New file", exact: true }).click();
await page.evaluate(() => window.__TEST__.files.set("LICENSE", "Keep this content"));
await newRootFile();
await enterName("LICENSE");
await page.getByText("path already exists", { exact: true }).waitFor();
assert.equal(await page.evaluate(() => window.editorFilesTest.files.get("LICENSE")), "Keep this content");
assert.equal(await page.evaluate(() => window.editorFilesTest.files.has("LICENSE 2")), false);
assert.equal(await page.evaluate(() => window.__TEST__.files.get("LICENSE")), "Keep this content");
assert.equal(await page.evaluate(() => window.__TEST__.files.has("LICENSE 2")), false);
await row("notes").click({ button: "right" });
await page.getByRole("menuitem", { name: "New file…", exact: true }).click();
await enterName("hello_world.py");
await row("notes/hello_world.py").waitFor();
assert.equal(await page.evaluate(() => window.editorFilesTest.files.has("notes/hello_world.py.md")), false);
assert.equal(await page.evaluate(() => window.__TEST__.files.has("notes/hello_world.py.md")), false);
await row("hello.txt").dblclick();
await page.waitForFunction(() => !!document.querySelector(".monaco-editor .view-line"));
await row("hello.txt").click({ button: "right" });
@@ -105,8 +91,8 @@ try {
});
for (const theme of ["dark", "light"]) {
await page.evaluate(async mode => {
const { saveAppearance } = await import('/src/lib/theme/appearance.ts');
saveAppearance({ theme: 'default', mode });
const { saveAppearance } = await import("/src/lib/theme/appearance.ts");
saveAppearance({ theme: "default", mode });
}, theme);
const nativeAllowed = await page.evaluate(() => {
window.writerTest.dispatch({ selection: { anchor: 3 } });
@@ -115,7 +101,12 @@ try {
line.dispatchEvent(event);
return !event.defaultPrevented;
});
assert.equal(nativeAllowed, true, "The native spelling menu is available on plain text");
// Writer combines spelling suggestions with the Markdown actions (docs/design-decisions.md UI-027;
// src/lib/editor/LiveWriter.svelte:255-262 prevents the native menu and passes the spelling offset).
assert.equal(nativeAllowed, false, "Plain text opens the shared Markdown menu instead of the native one");
const textMenu = page.getByRole("menu", { name: "Markdown text actions", exact: true });
await textMenu.getByRole("menuitem", { name: "Misspelled", exact: true }).waitFor();
await page.keyboard.press("Escape");
assert.equal(await page.getByRole("menu").count(), 0);
await page.evaluate(() => { window.writerTest.focus(); });
await page.keyboard.press("Shift+F10");
@@ -137,6 +128,4 @@ try {
}), true, "Active table text permits the native spelling menu");
await page.locator(".cm-line").first().click();
}
assert.deepEqual(errors, []);
console.log("PASS: exact filenames, extensionless creation, extension rename and language, equal code font sizes, native spelling event, shared selection and table menus in both themes");
} finally { await browser.close(); }
}, { viewport: { width: 1280, height: 900 }, timeout: 15000 });
+42
View File
@@ -0,0 +1,42 @@
// Tree rename keeps pins and bookmarks: the file menu offers Copy system path, and Undo rename, Ctrl+Z, and Ctrl+Y restore the marks.
import assert from "node:assert/strict";
import { mockTauri, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("tree/renameMarks", async ({ page }) => {
await mockTauri(page, {
commands: test => {
const workspace = test.workspace({
root: "C:\\rename-marks",
files: { "a.md": "# Note\n\nOriginal text.", ".runestone/marks.json": JSON.stringify({ pins: ["a.md"], bookmarks: ["a.md"], order: { "": ["a.md"] } }) },
});
test.files = workspace.files;
return {
...workspace,
workspace_list: args => workspace.workspace_list(args).filter(entry => args.rel || entry.rel_path !== ".runestone"),
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
spelling_menu_install: () => null,
};
},
});
const row = path => page.locator(`[data-tree-rel="${path}"]`);
const item = name => page.getByRole("menuitem", { name, exact: true });
await page.goto(smokeUrl);
await row("a.md").click({ button: "right" });
assert.equal(await item("Copy path").count(), 0);
assert.equal(await item("Copy system path").count(), 1);
await item("Rename").click();
await page.locator(".tree input").fill("renamed.md");
await page.locator(".tree input").press("Enter");
await row("renamed.md").waitFor();
await row("renamed.md").click({ button: "right" });
assert.equal(await item("Undo rename").count(), 1);
await page.keyboard.press("Escape");
await row("renamed.md").focus();
await page.keyboard.press("Control+z");
await row("a.md").waitFor();
assert.deepEqual(await page.evaluate(() => JSON.parse(window.__TEST__.files.get(".runestone/marks.json")).pins), ["a.md"]);
await row("a.md").focus();
await page.keyboard.press("Control+y");
await row("renamed.md").waitFor();
console.log("PASS: Copy system path, rename, Undo rename, and Ctrl+Z and Ctrl+Y with marks");
}, { viewport: { width: 1200, height: 850 } });
+38 -126
View File
@@ -1,132 +1,44 @@
import { createRequire } from "node:module";
// Rename fields select the file stem, the folder name, or the tab dialog name, in dark/wide and light/narrow layouts.
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 page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\tree-actions-test";
const files = new Map([
["notes/a.md", "# A"], ["notes/nested/b.md", "# B"],
["target/a.md", "# Existing"], ["a.md", "# A"], ["b.md", "# B"], ["c.md", "# C"],
]);
const calls = [];
const state = { files, calls, answer: "Ok", fail: "", clipboard: "" };
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { state.clipboard = text; } } });
let sequence = 0;
const contains = (parent, path) => path === parent || path.startsWith(parent + "/");
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: () => ++sequence,
unregisterCallback: () => {},
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") return ++sequence;
if (command === "plugin:event|unlisten") return;
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "tree-actions-test", 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") { files.set(args.rel, args.contents); 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_delete") {
if (args.rel === state.fail) throw new Error("Access denied");
for (const path of [...files.keys()]) if (contains(args.rel, path)) files.delete(path);
return;
}
if (command === "workspace_copy") {
const to = args.rel + "-copy";
for (const [path, text] of [...files]) if (contains(args.rel, path)) files.set(to + path.slice(args.rel.length), text);
return { name: to.split("/").pop(), rel_path: to, kind: files.has(to) ? "file" : "folder" };
}
if (command === "workspace_rename") {
if ([...files.keys()].some(path => contains(args.to, path))) throw new Error("Destination exists");
for (const [path, text] of [...files]) if (contains(args.from, path)) {
files.delete(path);
files.set(args.to + path.slice(args.from.length), text);
}
return;
}
if (command === "workspace_abs_path") return root + "\\" + args.rel.replaceAll("/", "\\");
if (command === "workspace_reveal") return;
if (command === "workspace_search") return [];
if (command === "plugin:dialog|message") return state.answer;
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
window.__TEST__ = state;
});
const row = rel => page.locator(`[data-tree-rel="${rel}"]`);
const selected = () => page.locator('[role="treeitem"][aria-selected="true"]').evaluateAll(nodes => nodes.map(node => node.dataset.treeRel));
const calls = command => page.evaluate(command => window.__TEST__.calls.filter(call => call.command === command).map(call => call.args), command);
const settle = () => page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
async function reset() {
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("tree/renameSelection", async ({ page }) => {
await mockTauri(page, {
commands: test => test.workspace({
root: "C:\\tree-actions-test",
files: { "notes/a.md": "# A", "notes/nested/b.md": "# B", "target/a.md": "# Existing", "a.md": "# A", "b.md": "# B", "c.md": "# C" },
}),
});
const output = await outputDir("tree/renameSelection");
const row = rel => page.locator(`[data-tree-rel="${rel}"]`);
const selection = input => input.evaluate(node => [node.selectionStart, node.selectionEnd, node.value]);
await page.goto(smokeUrl);
await row("notes").waitFor();
}
async function action(path, name) {
await row(path).click({ button: "right" });
await page.getByRole("menuitem", { name, exact: true }).click();
await settle();
}
async function selectFiles() {
await row("a.md").click();
await page.getByRole("tab", { name: "a.md", exact: true }).waitFor();
await settle();
await row("b.md").click({ modifiers: ["Control"] });
await settle();
}
async function drag(sourcePath, targetPath, place = "inside") {
const source = await row(sourcePath).boundingBox();
const target = await row(targetPath).boundingBox();
await page.mouse.move(source.x + source.width / 2, source.y + source.height / 2);
await page.mouse.down();
await page.mouse.move(target.x + target.width / 2, target.y + target.height * (place === "before" ? 0.1 : place === "after" ? 0.9 : 0.5), { steps: 10 });
await page.mouse.up();
await settle();
}
try {
await reset();
for (const [theme, width] of [['dark',1440],['light',620]]) {
await page.setViewportSize({width,height:850});
await page.evaluate(theme => { document.documentElement.dataset.theme = theme; document.documentElement.dataset.palette = 'default'; },theme);
await row('a.md').click();
await row('a.md').focus();
await page.keyboard.press('F2');
const input=row('a.md').locator('input');
for (const [theme, width] of [["dark", 1440], ["light", 620]]) {
await page.setViewportSize({ width, height: 850 });
await page.evaluate(theme => { document.documentElement.dataset.theme = theme; document.documentElement.dataset.palette = "default"; }, theme);
await row("a.md").click();
await row("a.md").focus();
await page.keyboard.press("F2");
const input = row("a.md").locator("input");
await input.waitFor();
assert.deepEqual(await input.evaluate(node=>[node.selectionStart,node.selectionEnd,node.value]),[0,1,'a.md']);
await page.screenshot({path:'.audit/rename-selection-'+theme+'.png'});
await input.press('Escape');
await row('notes').click();
await row('notes').focus();
await page.keyboard.press('F2');
const folder=row('notes').locator('input');
assert.deepEqual(await selection(input), [0, 1, "a.md"]);
await page.screenshot({ path: path.join(output, `rename-selection-${theme}.png`) });
await input.press("Escape");
await row("notes").click();
await row("notes").focus();
await page.keyboard.press("F2");
const folder = row("notes").locator("input");
await folder.waitFor();
assert.deepEqual(await folder.evaluate(node=>[node.selectionStart,node.selectionEnd,node.value]),[0,5,'notes']);
await folder.press('Escape');
await page.getByRole('tab',{name:'a.md',exact:true}).click();
await page.getByRole('tab',{name:'a.md',exact:true}).click({button:'right'});
await page.getByRole('menuitem',{name:'Rename…',exact:true}).click();
const dialogInput=page.locator('#text-request');
assert.deepEqual(await selection(folder), [0, 5, "notes"]);
await folder.press("Escape");
await page.getByRole("tab", { name: "a.md", exact: true }).click();
await page.getByRole("tab", { name: "a.md", exact: true }).click({ button: "right" });
await page.getByRole("menuitem", { name: "Rename…", exact: true }).click();
const dialogInput = page.locator("#text-request");
await dialogInput.waitFor();
assert.deepEqual(await dialogInput.evaluate(node=>[node.selectionStart,node.selectionEnd,node.value]),[0,1,'a.md']);
await dialogInput.press('Escape');
assert.deepEqual(await selection(dialogInput), [0, 1, "a.md"]);
await dialogInput.press("Escape");
}
assert.deepEqual(errors,[]);
console.log('Rename selection passed: file, folder, editor dialog, dark/wide and light/narrow.');
} finally { await browser.close(); }
});
+118 -155
View File
@@ -1,158 +1,121 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
// Inline note title rename: tabs and tree, undo of contents, Enter/Tab/Escape, validation, collisions, tab switches mid-rename, and reload.
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 page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
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_rename") {
if (window.__TEST__.delayRename) await new Promise(resolve => { window.__TEST__.resumeRename = resolve; });
if (!files.has(args.from)) throw new Error("File is missing");
if (files.has(args.to)) throw new Error("A file with that name already exists");
files.set(args.to, files.get(args.from)); files.delete(args.from); 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}`);
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("tree/renameTitle", async ({ page }) => {
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
await mockTauri(page, {
commands: test => {
const ws = test.workspace({
root: "C:\\smoke-workspace",
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",
},
});
const files = ws.files;
Object.assign(test, { files, root: ws.root });
return {
...ws,
workspace_write: ({ rel, contents, expected }) => {
if (expected !== undefined && files.get(rel) !== expected) throw new Error("Save blocked: file changed on disk");
files.set(rel, contents);
test.emit("workspace-event", { root: ws.root, kind: "modify", paths: [rel] });
},
workspace_rename: async ({ from, to }) => {
if (test.delayRename) await new Promise(resolve => { test.resumeRename = resolve; });
if (!files.has(from)) throw new Error("File is missing");
if (files.has(to)) throw new Error("A file with that name already exists");
files.set(to, files.get(from));
files.delete(from);
},
};
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
async function openNote(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 page.getByRole("button", { name: "Rename note", exact: true }).waitFor();
}
const title = page.getByRole("button", { name: "Rename note", exact: true });
const input = page.getByRole("textbox", { name: "Note filename", exact: true });
const writer = page.getByRole("textbox", { name: "Writing editor", exact: true });
async function editTitle(value) { await title.click(); await input.fill(value); }
const renamed = name => page.waitForFunction(expected => document.querySelector(".breadcrumb")?.textContent === expected, name);
try {
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
await page.getByText("smoke-workspace", { exact: true }).waitFor();
await openNote("welcome.md");
const original = await page.evaluate(() => window.__TEST__.files.get("notes/welcome.md"));
await writer.click();
await page.keyboard.press("Control+End");
await page.keyboard.type("Unsaved text");
await editTitle("Release 1.2");
await input.press("Enter");
await renamed("notes/Release 1.2.md");
assert.equal(await page.evaluate(() => window.__TEST__.files.has("notes/welcome.md")), false);
await page.getByRole("tab", { name: /Release 1\.2\.md/ }).waitFor();
await page.locator('.tree').getByText("notes", { exact: true }).click();
await page.locator('.tree').getByText("Release 1.2", { exact: true }).waitFor();
await writer.click();
await page.keyboard.press("Control+z");
await page.keyboard.press("Control+s");
await page.waitForFunction(text => window.__TEST__.files.get("notes/Release 1.2.md") === text, original);
await page.keyboard.press("Control+y");
await page.keyboard.press("Control+s");
await page.waitForFunction(text => window.__TEST__.files.get("notes/Release 1.2.md") === text, original + "Unsaved text");
await editTitle("Cancelled");
await input.press("Escape");
await renamed("notes/Release 1.2.md");
assert.equal(await input.isVisible(), false);
// Keyboard activation and filename errors stay outside Markdown editing.
await title.focus(); await title.press("Enter");
await input.fill(" "); await input.press("Enter");
await page.getByRole("alert").filter({ hasText: "Name is empty" }).waitFor();
await input.fill("folder/note"); await input.press("Enter");
await page.getByRole("alert").filter({ hasText: "path separator" }).waitFor();
await input.fill("second"); await input.press("Enter");
await page.getByRole("alert").filter({ hasText: "already exists" }).waitFor();
assert.equal(await input.inputValue(), "second");
assert.equal(await page.evaluate(() => window.__TEST__.files.get("notes/second.md")), "# Second note\n");
await input.fill("Renamed.md"); await input.press("Tab");
await renamed("notes/Renamed.md");
await page.mouse.move(10, 10);
await page.screenshot({ path: ".audit/rename-title.png" });
// A pending rename belongs to its original document even if the tab changes.
await page.evaluate(() => { window.__TEST__.delayRename = true; });
await editTitle("Background"); await input.press("Enter");
await page.waitForFunction(() => !!window.__TEST__.resumeRename);
await page.locator('.tree').getByText("second", { exact: true }).click();
await renamed("notes/second.md");
await page.evaluate(() => { window.__TEST__.resumeRename(); window.__TEST__.delayRename = false; });
await page.getByRole("tab", { name: "Background.md", exact: true }).waitFor();
await renamed("notes/second.md");
await page.getByRole("tab", { name: "Background.md", exact: true }).click();
await renamed("notes/Background.md");
// Disk reload after rename must not restore the old displayed title.
await page.evaluate(() => {
window.__TEST__.files.set("notes/Background.md", "Reloaded\n");
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "modify", paths: ["notes/Background.md"] });
});
await page.waitForFunction(() => document.querySelector(".cm-line")?.textContent === "Reloaded");
assert.ok((await title.innerText()).startsWith("Background"));
assert.deepEqual(errors, []);
console.log("PASS: inline filename rename, folder/extension preservation, tabs/tree, contents and undo, Enter/blur/Escape, validation/collisions, tab switching during rename, and reload (mocked desktop IPC).");
} catch (error) {
console.error("Browser errors:", errors);
console.error("Visible text:", (await page.locator("body").innerText()).slice(0, 3000));
await page.screenshot({ path: ".audit/rename-title-failure.png" });
throw error;
} finally { await browser.close(); }
const output = await outputDir("tree/renameTitle");
const title = page.getByRole("button", { name: "Rename note", exact: true });
const input = page.getByRole("textbox", { name: "Note filename", exact: true });
const writer = page.getByRole("textbox", { name: "Writing editor", exact: true });
// Empty names and path separators share one message (src/lib/workspace/renamePath.ts:56-57, used by Workbench.svelte:958).
const invalidName = "Enter a document name without a leading dot or reserved filename characters.";
async function openNote(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 title.waitFor();
}
async function editTitle(value) { await title.click(); await input.fill(value); }
const renamed = name => page.waitForFunction(expected => document.querySelector(".breadcrumb")?.textContent === expected, name);
try {
await page.goto(smokeUrl);
await page.getByText("smoke-workspace", { exact: true }).waitFor();
await openNote("welcome.md");
const original = await page.evaluate(() => window.__TEST__.files.get("notes/welcome.md"));
await writer.click();
await page.keyboard.press("Control+End");
await page.keyboard.type("Unsaved text");
await editTitle("Release 1.2");
await input.press("Enter");
await renamed("notes/Release 1.2.md");
assert.equal(await page.evaluate(() => window.__TEST__.files.has("notes/welcome.md")), false);
await page.getByRole("tab", { name: /Release 1\.2\.md/ }).waitFor();
await page.locator(".tree").getByText("notes", { exact: true }).click();
await page.locator(".tree").getByText("Release 1.2", { exact: true }).waitFor();
await writer.click();
await page.keyboard.press("Control+z");
await page.keyboard.press("Control+s");
await page.waitForFunction(text => window.__TEST__.files.get("notes/Release 1.2.md") === text, original);
await page.keyboard.press("Control+y");
await page.keyboard.press("Control+s");
await page.waitForFunction(text => window.__TEST__.files.get("notes/Release 1.2.md") === text, original + "Unsaved text");
await editTitle("Cancelled");
await input.press("Escape");
await renamed("notes/Release 1.2.md");
assert.equal(await input.isVisible(), false);
// Keyboard activation and filename errors stay outside Markdown editing.
await title.focus(); await title.press("Enter");
await input.fill(" "); await input.press("Enter");
await page.getByRole("alert").filter({ hasText: invalidName }).waitFor();
await input.fill("folder/note"); await input.press("Enter");
await page.getByRole("alert").filter({ hasText: invalidName }).waitFor();
await page.waitForFunction(() => !document.querySelector(".note-title-input[aria-busy]"));
assert.equal(await page.evaluate(() => window.__TEST__.calls.some(call => call.command === "workspace_rename" && call.args.to.includes("folder"))), false);
await input.fill("second"); await input.press("Enter");
await page.getByRole("alert").filter({ hasText: "already exists" }).waitFor();
assert.equal(await input.inputValue(), "second");
assert.equal(await page.evaluate(() => window.__TEST__.files.get("notes/second.md")), "# Second note\n");
await input.fill("Renamed.md"); await input.press("Tab");
await renamed("notes/Renamed.md");
await page.mouse.move(10, 10);
await page.screenshot({ path: path.join(output, "rename-title.png") });
// A pending rename belongs to its original document even if the tab changes.
await page.evaluate(() => { window.__TEST__.delayRename = true; });
await editTitle("Background"); await input.press("Enter");
await page.waitForFunction(() => !!window.__TEST__.resumeRename);
// A plain tree click replaces the current tab (src/lib/layout/Workbench.svelte:1347), so open the other note in a new tab.
await page.locator('[data-tree-rel="notes/second.md"]').click({ button: "right" });
await page.getByRole("menuitem", { name: "Open in new tab", exact: true }).click();
await renamed("notes/second.md");
await page.evaluate(() => { window.__TEST__.resumeRename(); window.__TEST__.delayRename = false; });
await page.getByRole("tab", { name: "Background.md", exact: true }).waitFor();
await renamed("notes/second.md");
await page.getByRole("tab", { name: "Background.md", exact: true }).click();
await renamed("notes/Background.md");
// Disk reload after rename must not restore the old displayed title.
await page.evaluate(() => {
window.__TEST__.files.set("notes/Background.md", "Reloaded\n");
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "modify", paths: ["notes/Background.md"] });
});
await page.waitForFunction(() => document.querySelector(".cm-line")?.textContent === "Reloaded");
assert.ok((await title.innerText()).startsWith("Background"));
} catch (error) {
console.error("Visible text:", (await page.locator("body").innerText()).slice(0, 3000));
await page.screenshot({ path: path.join(output, "rename-title-failure.png") });
throw error;
}
});
+89 -98
View File
@@ -1,123 +1,115 @@
// Tree rename undo and redo keep folders expanded; New note templates, Git plug-in navigation, and detached tab layout isolation.
// @requires repo:RuneStone_Git/dist
import { createRequire } from 'node:module';
import assert from 'node:assert/strict';
import { mkdir, 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 context = await browser.newContext({ viewport: { width: 1200, height: 850 } });
const page = await context.newPage();
const errors = [];
page.on('pageerror', error => errors.push(error.message));
const gitRoot = new URL('../../../../RuneStone_Git/dist/', import.meta.url);
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { mockTauri, openPage, outputDir, pluginRepo, runSmoke, smokeUrl } from '../_harness/index.mjs';
const gitRoot = path.join(pluginRepo('RuneStone_Git'), 'dist');
const git = {
manifest: JSON.parse(await readFile(new URL('plugin.json', gitRoot), 'utf8')),
code: await readFile(new URL('main.js', gitRoot), 'utf8'),
css: (await readFile(new URL('style.css', gitRoot))).toString('base64'),
manifest: JSON.parse(await readFile(path.join(gitRoot, 'plugin.json'), 'utf8')),
code: await readFile(path.join(gitRoot, 'main.js'), 'utf8'),
css: (await readFile(path.join(gitRoot, 'style.css'))).toString('base64'),
};
await context.addInitScript(git => {
window.isTauri = true;
const root = 'C:\\host-todo-test';
const files = new Map([['a.md', '# Note\n\nOriginal text.'], ['folder/nested/note.md', '# Nested'], ['other/keep.md', '# Keep'], ['.runestone/templates/Daily.md', '# Daily\n\n## Tasks'], ['.runestone/marks.json', JSON.stringify({ pins: ['a.md'], bookmarks: ['a.md'], order: { '': ['a.md'] } })]]);
const state = { files, calls: [], exportResult: 'C:\\exports\\my-theme.json', exportError: '' };
window.__HOST_TEST__ = state;
let sequence = 0;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
transformCallback: () => ++sequence, unregisterCallback: () => {},
invoke: async (command, args = {}) => {
state.calls.push({ command, args });
if (command === 'plugins_snapshot') return { root: 'C:/plugins', plugins: [{ manifest: git.manifest, hash: 'navigation-git', enabled: true, installedAt: 1, path: 'C:/plugins/runestone.git', error: null, removal: false }] };
if (command === 'plugins_load') return git.code;
if (command === 'plugins_asset') return git.css;
if (command === 'plugins_data') return 'null';
if (command === 'workspace_last_path') return root;
if (command === 'workspace_open') return { root, name: 'host-todo-test', watch_mode: 'native' };
if (command === 'workspace_read') { if (!files.has(args.rel)) throw new Error('Missing file'); return files.get(args.rel); }
if (command === 'workspace_list') {
const prefix = args.rel ? args.rel + '/' : '';
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || (!args.rel && path.startsWith('.runestone/'))) continue;
const tail = path.slice(prefix.length), 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('Destination exists'); files.set(args.rel, ''); return; }
if (command === 'workspace_write') {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error('Changed on disk');
files.set(args.rel, args.contents); return;
}
if (command === 'workspace_rename') {
if (files.has(args.to)) throw new Error('Destination exists');
if (![...files.keys()].some(path => path === args.from || path.startsWith(args.from + '/'))) throw new Error('Missing file');
for (const [path, contents] of [...files]) { if (path === args.from || path.startsWith(args.from + '/')) { files.set(args.to + path.slice(args.from.length), contents); files.delete(path); } } return;
}
if (command === 'workspace_delete') { files.delete(args.rel); return; }
if (command === 'workspace_search') return [];
if (command === 'plugin:event|listen') return ++sequence;
if (command === 'plugin:window|is_maximized') return false;
if (command === 'plugin:dialog|message') return 'Ok';
if (command === 'theme_export') { if (state.exportError) throw new Error(state.exportError); return state.exportResult; }
return null;
await runSmoke('tree/renameUndo', async ({ browser }) => {
const context = await browser.newContext({ viewport: { width: 1200, height: 850 } });
await mockTauri(context, {
strict: false,
state: git,
commands: test => {
const git = test.state;
const ws = test.workspace({
root: 'C:\\host-todo-test',
files: {
'a.md': '# Note\n\nOriginal text.', 'folder/nested/note.md': '# Nested', 'other/keep.md': '# Keep', '.runestone/templates/Daily.md': '# Daily\n\n## Tasks',
'.runestone/marks.json': JSON.stringify({ pins: ['a.md'], bookmarks: ['a.md'], order: { '': ['a.md'] } }),
},
});
const files = ws.files;
const within = (from, path) => path === from || path.startsWith(from + '/');
test.files = files;
return {
workspace_last_path: ws.workspace_last_path,
workspace_open: ws.workspace_open,
workspace_read: ws.workspace_read,
workspace_list: args => ws.workspace_list(args).filter(entry => args.rel || !entry.rel_path.startsWith('.runestone')),
workspace_create: ({ rel }) => { if (files.has(rel)) throw new Error('Destination exists'); files.set(rel, ''); },
workspace_write: ({ rel, contents, expected }) => {
if (expected !== undefined && files.get(rel) !== expected) throw new Error('Changed on disk');
files.set(rel, contents);
},
workspace_rename: ({ from, to }) => {
if (files.has(to)) throw new Error('Destination exists');
if (![...files.keys()].some(path => within(from, path))) throw new Error('Missing file');
for (const [path, contents] of [...files]) if (within(from, path)) { files.set(to + path.slice(from.length), contents); files.delete(path); }
},
workspace_delete: ({ rel }) => { files.delete(rel); },
workspace_search: () => [],
plugins_snapshot: () => ({ root: 'C:/plugins', plugins: [{ manifest: git.manifest, hash: 'navigation-git', enabled: true, installedAt: 1, path: 'C:/plugins/runestone.git', error: null, removal: false }] }),
plugins_load: () => git.code,
plugins_asset: () => git.css,
plugins_data: () => 'null',
'plugin:window|is_maximized': () => false,
'plugin:dialog|message': () => 'Ok',
};
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
}, git);
const origin = process.env.SMOKE_URL || 'http://127.0.0.1:5186';
const row = path => page.locator(`[data-tree-rel="${path}"]`);
const item = name => page.getByRole('menuitem', { name, exact: true });
async function paneMenu() { await page.getByRole('navigation', { name: 'Workspace files' }).click({ button: 'right', position: { x: 90, y: 360 } }); }
async function rename(path, name) {
await row(path).click({ button: 'right' }); await item('Rename').click();
await page.locator('.tree input').fill(name); await page.locator('.tree input').press('Enter');
}
async function expanded(path) { assert.equal(await row(path).getAttribute('aria-expanded'), 'true', `${path} stays expanded`); }
await mkdir('output/host-navigation-pass3', { recursive: true });
try {
await page.goto(origin);
});
const page = await openPage(context, { timeout: 30000 });
const output = await outputDir('tree/renameUndo');
const shot = (target, name) => target.screenshot({ path: path.join(output, name) });
const row = rel => page.locator(`[data-tree-rel="${rel}"]`);
const item = name => page.getByRole('menuitem', { name, exact: true });
const setMode = (target, mode) => target.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); }, mode);
async function paneMenu() { await page.getByRole('navigation', { name: 'Workspace files' }).click({ button: 'right', position: { x: 90, y: 360 } }); }
async function rename(rel, name) {
await row(rel).click({ button: 'right' }); await item('Rename').click();
await page.locator('.tree input').fill(name); await page.locator('.tree input').press('Enter');
}
async function expanded(rel) { assert.equal(await row(rel).getAttribute('aria-expanded'), 'true', `${rel} stays expanded`); }
await page.goto(smokeUrl);
await row('folder').click(); await row('folder/nested').click(); await row('other').click();
await rename('folder/nested/note.md', 'renamed.md'); await row('folder/nested/renamed.md').waitFor();
await row('folder/nested/renamed.md').focus(); await page.keyboard.press('Control+z');
await row('folder/nested/note.md').waitFor();
for (const path of ['folder', 'folder/nested', 'other']) await expanded(path);
for (const rel of ['folder', 'folder/nested', 'other']) await expanded(rel);
await page.keyboard.press('Control+y'); await row('folder/nested/renamed.md').waitFor();
for (const path of ['folder', 'folder/nested', 'other']) await expanded(path);
for (const rel of ['folder', 'folder/nested', 'other']) await expanded(rel);
await rename('folder', 'renamed-folder'); await row('renamed-folder/nested/renamed.md').waitFor();
await row('renamed-folder').focus(); await page.keyboard.press('Control+z');
await row('folder/nested/renamed.md').waitFor();
for (const path of ['folder', 'folder/nested', 'other']) await expanded(path);
for (const rel of ['folder', 'folder/nested', 'other']) await expanded(rel);
await page.keyboard.press('Control+y'); await row('renamed-folder/nested/renamed.md').waitFor();
for (const path of ['renamed-folder', 'renamed-folder/nested', 'other']) await expanded(path);
for (const rel of ['renamed-folder', 'renamed-folder/nested', 'other']) await expanded(rel);
await paneMenu(); assert.equal(await item('Manage templates…').isVisible(), false);
await item('New note').click(); await row('untitled.md').waitFor();
assert.equal(await page.evaluate(() => window.__HOST_TEST__.files.get('untitled.md')), '');
assert.equal(await page.evaluate(() => window.__TEST__.files.get('untitled.md')), '');
await paneMenu(); await item('New note').focus(); await page.keyboard.press('ArrowRight');
await item('Daily').click(); await row('Daily.md').waitFor();
assert.equal(await page.evaluate(() => window.__HOST_TEST__.files.get('Daily.md')), '# Daily\n\n## Tasks');
assert.equal(await page.evaluate(() => window.__TEST__.files.get('Daily.md')), '# Daily\n\n## Tasks');
await paneMenu(); await item('New note').hover(); await item('Manage templates…').click();
await page.getByRole('button', { name: 'Close templates', exact: true }).click();
for (const mode of ['light', 'dark']) {
await page.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); }, mode);
await setMode(page, mode);
await paneMenu(); await item('New note').focus(); await page.keyboard.press('ArrowRight');
await page.screenshot({ path: `output/host-navigation-pass3/note-menu-${mode}.png` });
await shot(page, `note-menu-${mode}.png`);
await page.keyboard.press('Escape'); await page.keyboard.press('Escape');
}
await page.setViewportSize({ width: 600, height: 600 });
await paneMenu(); await item('New note').focus(); await page.keyboard.press('ArrowRight');
await page.screenshot({ path: 'output/host-navigation-pass3/note-menu-dark-narrow.png' });
await shot(page, 'note-menu-dark-narrow.png');
assert.ok(await item('Manage templates…').evaluate(node => node.getBoundingClientRect().right <= innerWidth));
await page.keyboard.press('Escape'); await page.keyboard.press('Escape');
await page.setViewportSize({ width: 1200, height: 850 });
await page.evaluate(() => { window.__HOST_TEST__.files.delete('.runestone/templates/Daily.md'); window.dispatchEvent(new Event('runestone-templates-changed')); });
await page.evaluate(() => { window.__TEST__.files.delete('.runestone/templates/Daily.md'); window.dispatchEvent(new Event('runestone-templates-changed')); });
await paneMenu(); await item('New note').focus(); await page.keyboard.press('ArrowRight');
assert.equal(await item('Daily').count(), 0);
await item('Manage templates…').click();
await page.getByRole('button', { name: 'Close templates', exact: true }).click();
const creations = await page.evaluate(() => window.__HOST_TEST__.calls.filter(call => call.command === 'workspace_create').length);
const creations = await page.evaluate(() => window.__TEST__.calls.filter(call => call.command === 'workspace_create').length);
await paneMenu(); await item('New note').focus(); await page.keyboard.press('Enter');
await page.waitForFunction(count => window.__HOST_TEST__.calls.filter(call => call.command === 'workspace_create').length === count + 1, creations);
await page.waitForFunction(count => window.__TEST__.calls.filter(call => call.command === 'workspace_create').length === count + 1, creations);
await page.getByRole('button', { name: 'Source control', exact: true }).waitFor();
assert.equal(await page.locator('.header-left').getByRole('button', { name: 'Source control', exact: true }).count(), 1);
await page.getByRole('button', { name: 'Plug-in views', exact: true }).click();
@@ -127,7 +119,7 @@ try {
const graphIcon = await graph.locator('.action-icon').innerHTML();
const expectedIcon = await page.evaluate(async () => (await import('/src/lib/ui/actionIcons.ts')).actionIcon('git').innerHTML);
assert.equal(graphIcon, expectedIcon, 'The real Git graph command uses the shared Git icon');
await page.screenshot({ path: 'output/host-navigation-pass3/real-git-command-dark.png' });
await shot(page, 'real-git-command-dark.png');
await page.keyboard.press('Escape');
await page.evaluate(async () => {
const external = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
@@ -135,10 +127,10 @@ try {
external.pluginTools.set([{ owner: 'pm-test', id: 'pm', title: 'Project Management', kind: 'view', surface: 'open' }, { owner: 'git-test', id: 'graph', title: 'Graph view', kind: 'command', surface: 'open', icon: 'git' }]);
external.pluginTools.update(items => [...items, { owner: 'runestone.browser', id: 'new-tab', title: 'New browser tab', kind: 'command', surface: 'open' }]);
const registry = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/registry.ts').name);
registry.pluginHost.get('browser').newTab = async () => { window.__HOST_TEST__.browserOpened = true; };
registry.pluginHost.get('browser').newTab = async () => { window.__TEST__.browserOpened = true; };
});
await page.locator('.header-right').getByRole('button', { name: 'New browser tab', exact: true }).click();
assert.equal(await page.evaluate(() => window.__HOST_TEST__.browserOpened), true);
assert.equal(await page.evaluate(() => window.__TEST__.browserOpened), true);
assert.equal(await page.locator('.header-right').getByRole('button', { name: 'Project Management', exact: true }).count(), 0);
assert.equal(await page.locator('.header-left').getByRole('button', { name: 'Source control', exact: true }).count(), 1);
assert.equal(await page.locator('.header-right').getByRole('button', { name: 'Source control', exact: true }).count(), 0);
@@ -147,9 +139,9 @@ try {
assert.equal(await page.getByRole('menuitem', { name: /New browser tab/ }).count(), 0);
await page.getByRole('menuitem', { name: /Graph view/ }).waitFor(); await page.keyboard.press('Escape');
for (const mode of ['light', 'dark']) {
await page.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); }, mode);
await setMode(page, mode);
await page.getByRole('button', { name: 'Plug-in views', exact: true }).click();
await page.screenshot({ path: `output/host-navigation-pass3/plugin-navigation-${mode}.png` });
await shot(page, `plugin-navigation-${mode}.png`);
await page.keyboard.press('Escape');
}
const token = '00000000-0000-4000-8000-000000000001';
@@ -159,9 +151,8 @@ try {
localStorage.setItem(`runestone.tab-transfer.${token}`, JSON.stringify({ root: 'C:\\host-todo-test', created: Date.now(), buffer: { id: 'moved', relPath: 'a.md', name: 'a.md', kind: 'text', contents: '# Transferred', saved: '# Note', chrome: 'Writing', pinned: true } }));
return layout;
}, token);
const detached = await context.newPage();
detached.on('pageerror', error => errors.push(error.message));
await detached.goto(`${origin}/?tabTransfer=${token}`);
const detached = await openPage(context, { timeout: 30000 });
await detached.goto(`${smokeUrl}/?tabTransfer=${token}`);
await detached.getByRole('tab', { name: /a.md/ }).waitFor();
await detached.getByText('# Transferred', { exact: true }).waitFor();
assert.equal(await detached.locator('.shell.left-open,.shell.right-open').count(), 0);
@@ -174,10 +165,10 @@ try {
await detached.keyboard.press('Escape');
assert.equal(await detached.evaluate(() => localStorage.getItem('runestone.workbenchLayout')), saved);
for (const mode of ['light', 'dark']) {
await detached.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); }, mode);
await setMode(detached, mode);
await detached.setViewportSize({ width: 650, height: 600 });
await detached.screenshot({ path: `output/host-navigation-pass3/detached-${mode}-narrow.png` });
await shot(detached, `detached-${mode}-narrow.png`);
}
assert.deepEqual(errors, []);
assert.deepEqual([...page.errors, ...detached.errors], []);
console.log('Host navigation passed: nested file/folder rename undo/redo, expanded folders, blank New note parent, template submenu, plugin navigation dedup, detached layout isolation.');
} finally { await browser.close(); }
});
+63 -119
View File
@@ -1,123 +1,67 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
// File tree selection: Ctrl and Shift ranges across expanded folders, F2 on multiple rows, and Collapse all.
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 page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
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 };
});
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
const row = rel => page.locator(`[data-tree-rel="${rel}"]`);
const selected = () => page.locator('[role="treeitem"][aria-selected="true"]').evaluateAll(rows => rows.map(row => row.dataset.treeRel));
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await row('notes').waitFor();
await row('notes').click();
await row('notes/second.md').waitFor();
assert.deepEqual(await selected(), ['notes']);
await row('notes/second.md').click({ modifiers: ['Control'] });
await row('src').click({ modifiers: ['Control'] });
assert.deepEqual(await selected(), ['notes', 'notes/second.md', 'src']);
assert.equal(await row('src').getAttribute('aria-expanded'), 'false');
assert.equal(await page.getByRole('tab').count(), 1);
assert.equal(await page.getByRole('tab', { name: 'New tab', exact: true }).count(), 1);
await row('notes').click({ modifiers: ['Control'] });
assert.deepEqual(await selected(), ['notes/second.md', 'src']);
assert.equal(await row('notes').getAttribute('aria-expanded'), 'true');
await row('notes/second.md').click({ modifiers: ['Shift'] });
assert.deepEqual(await selected(), ['notes', 'notes/second.md']);
await row('src').click({ modifiers: ['Shift'] });
assert.deepEqual(await selected(), ['notes', 'notes/second.md', 'notes/welcome.md', 'src']);
await page.keyboard.press('F2');
assert.equal(await page.locator('.tree .rename').count(), 0);
await row('notes/welcome.md').click({ modifiers: ['Shift'] });
assert.deepEqual(await selected(), ['notes', 'notes/second.md', 'notes/welcome.md']);
await row('notes/second.md').click();
assert.deepEqual(await selected(), ['notes/second.md']);
await page.getByRole('tab', { name: /second/ }).waitFor();
await row('notes/second.md').click({ modifiers: ['Control'] });
await runSmoke("tree/selection", async ({ page }) => {
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
await mockTauri(page, {
commands: test => test.workspace({
root: "C:\\smoke-workspace",
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",
},
writeEvents: true,
}),
});
const output = await outputDir("tree/selection");
const row = rel => page.locator(`[data-tree-rel="${rel}"]`);
const selected = () => page.locator('[role="treeitem"][aria-selected="true"]').evaluateAll(rows => rows.map(row => row.dataset.treeRel));
await page.goto(smokeUrl);
await row("notes").waitFor();
await row("notes").click();
await row("notes/second.md").waitFor();
assert.deepEqual(await selected(), ["notes"]);
await row("notes/second.md").click({ modifiers: ["Control"] });
await row("src").click({ modifiers: ["Control"] });
assert.deepEqual(await selected(), ["notes", "notes/second.md", "src"]);
assert.equal(await row("src").getAttribute("aria-expanded"), "false");
assert.equal(await page.getByRole("tab").count(), 1);
assert.equal(await page.getByRole("tab", { name: "New tab", exact: true }).count(), 1);
await row("notes").click({ modifiers: ["Control"] });
assert.deepEqual(await selected(), ["notes/second.md", "src"]);
assert.equal(await row("notes").getAttribute("aria-expanded"), "true");
await row("notes/second.md").click({ modifiers: ["Shift"] });
assert.deepEqual(await selected(), ["notes", "notes/second.md"]);
await row("src").click({ modifiers: ["Shift"] });
assert.deepEqual(await selected(), ["notes", "notes/second.md", "notes/welcome.md", "src"]);
await page.keyboard.press("F2");
assert.equal(await page.locator(".tree .rename").count(), 0);
await row("notes/welcome.md").click({ modifiers: ["Shift"] });
assert.deepEqual(await selected(), ["notes", "notes/second.md", "notes/welcome.md"]);
await row("notes/second.md").click();
assert.deepEqual(await selected(), ["notes/second.md"]);
await page.getByRole("tab", { name: /second/ }).waitFor();
await row("notes/second.md").click({ modifiers: ["Control"] });
assert.deepEqual(await selected(), []);
await row('src').click({ modifiers: ['Control'] });
await row('notes').click({ modifiers: ['Control'] });
await row('notes').click({ modifiers: ['Control'] });
await page.keyboard.press('F2');
assert.equal(await page.locator('.tree .rename').inputValue(), 'src');
await page.keyboard.press('Escape');
await row('notes/second.md').click({ modifiers: ['Shift'] });
assert.deepEqual(await selected(), ['notes/second.md', 'notes/welcome.md', 'src']);
const colors = await page.locator('.tree .row.selected').evaluateAll(rows => rows.map(row => getComputedStyle(row).backgroundColor));
await row("src").click({ modifiers: ["Control"] });
await row("notes").click({ modifiers: ["Control"] });
await row("notes").click({ modifiers: ["Control"] });
await page.keyboard.press("F2");
assert.equal(await page.locator(".tree .rename").inputValue(), "src");
await page.keyboard.press("Escape");
await row("notes/second.md").click({ modifiers: ["Shift"] });
assert.deepEqual(await selected(), ["notes/second.md", "notes/welcome.md", "src"]);
const colors = await page.locator(".tree .row.selected").evaluateAll(rows => rows.map(row => getComputedStyle(row).backgroundColor));
assert.equal(new Set(colors).size, 1);
await page.screenshot({ path: '.audit/tree-selection.png' });
await page.getByRole('button', { name: 'Collapse all', exact: true }).click();
assert.deepEqual(await selected(), ['src']);
await row('notes').click({ modifiers: ['Shift'] });
assert.deepEqual(await selected(), ['notes', 'src']);
await row('notes').click({ modifiers: ['Control'] });
await row('notes').click({ modifiers: ['Shift', 'Control'] });
assert.deepEqual(await selected(), ['notes', 'src']);
assert.deepEqual(errors, []);
console.log('Tree selection browser checks passed.');
} finally { await browser.close(); }
await page.screenshot({ path: path.join(output, "tree-selection.png") });
await page.getByRole("button", { name: "Collapse all", exact: true }).click();
assert.deepEqual(await selected(), ["src"]);
await row("notes").click({ modifiers: ["Shift"] });
assert.deepEqual(await selected(), ["notes", "src"]);
await row("notes").click({ modifiers: ["Control"] });
await row("notes").click({ modifiers: ["Shift", "Control"] });
assert.deepEqual(await selected(), ["notes", "src"]);
});