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
+198
View File
@@ -0,0 +1,198 @@
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 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");
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();
await selectFiles();
await row("a.md").click({ button: "right" });
assert.deepEqual(await selected(), ["a.md", "b.md"]);
assert.equal(await page.getByRole("menuitem", { name: "Rename", exact: true }).isDisabled(), true);
await page.keyboard.press("Escape");
await action("a.md", "Copy workspace paths");
assert.equal(await page.evaluate(() => window.__TEST__.clipboard), "a.md\nb.md");
await action("b.md", "Copy system paths");
assert.equal(await page.evaluate(() => window.__TEST__.clipboard), "C:\\tree-actions-test\\a.md\nC:\\tree-actions-test\\b.md");
await action("a.md", "Show in Explorer");
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"]);
await action("a.md", "Unpin");
await action("a.md", "Remove bookmarks");
await action("a.md", "Make copies (2)");
assert.deepEqual((await calls("workspace_copy")).map(args => args.rel), ["a.md", "b.md"]);
await row("c.md").click({ button: "right" });
assert.deepEqual(await selected(), ["c.md"]);
assert.equal(await page.getByRole("menuitem", { name: "Rename", exact: true }).isDisabled(), false);
await page.keyboard.press("Escape");
console.log("PASS: selection, clipboard paths, marks, copies, reveal, and single-item menus");
await reset();
await selectFiles();
await page.evaluate(() => { window.__TEST__.answer = "Cancel"; });
await action("a.md", "Delete (2)");
assert.equal((await calls("workspace_delete")).length, 0);
assert.deepEqual(await selected(), ["a.md", "b.md"]);
await page.evaluate(() => { window.__TEST__.answer = "Ok"; window.__TEST__.fail = "a.md"; });
await row("c.md").click({ modifiers: ["Control"] });
await action("a.md", "Delete (3)");
await row("c.md").waitFor({ state: "detached" });
assert.deepEqual((await calls("workspace_delete")).map(args => args.rel), ["a.md", "b.md", "c.md"]);
assert.match(await page.locator(".tree .error").textContent(), /a.md: Access denied/);
assert.deepEqual(await selected(), ["a.md"]);
console.log("PASS: cancellation, one confirmation per batch, partial failure, and selection after deletion");
await reset();
await row("notes").click();
await row("notes/nested").click();
await row("notes").click({ modifiers: ["Control"] });
await row("notes/a.md").click({ modifiers: ["Control"] });
await row("notes/nested/b.md").click({ modifiers: ["Control"] });
await row("c.md").click({ modifiers: ["Control"] });
await action("notes/a.md", "Make copies (5)");
assert.deepEqual((await calls("workspace_copy")).map(args => args.rel), ["notes", "c.md"]);
await action("notes/nested/b.md", "Delete (5)");
await row("notes").waitFor({ state: "detached" });
assert.deepEqual((await calls("workspace_delete")).map(args => args.rel), ["notes", "c.md"]);
assert.equal((await calls("plugin:dialog|message")).length, 1);
console.log("PASS: recursive copy and delete process selected folders and children once");
await reset();
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 selected(), ["target/a 2.md", "target/b.md"]);
console.log("PASS: group move into a collapsed folder preserves an existing same-name file");
await reset();
await row("notes").click();
await row("notes/a.md").click({ modifiers: ["Control"] });
await row("c.md").click({ modifiers: ["Control"] });
await drag("notes/a.md", "notes/nested");
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 selected(), ["target/notes", "target/c.md"]);
await row("target/notes").click();
await row("target/notes/a.md").waitFor();
console.log("PASS: mixed folder and file moves skip selected descendants and reject drops into the same folder");
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"]);
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, []);
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();
}
+137
View File
@@ -0,0 +1,137 @@
import { createRequire } from 'node:module';
import assert from 'node:assert/strict';
import { mkdir, writeFile } 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: 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;
},
};
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');
await row('Untitled').waitFor();
const welcome = page.locator('.welcome-actions');
await welcome.waitFor();
await welcome.getByRole('button', { name: 'Open browser', exact: true }).waitFor();
assert.deepEqual(await welcome.locator('button').allTextContents().then(values => values.map(value => value.replace(/Ctrl [NOP]/g, '').trim())), ['New file', 'New note', 'Find file', 'Open folder', 'Open browser']);
const firstRow = welcome.locator('.welcome-row').first();
assert.equal(await firstRow.locator('button').count(), 3);
const tops = await firstRow.locator('button').evaluateAll(nodes => nodes.map(node => node.getBoundingClientRect().top));
assert.ok(tops.every(top => top === tops[0]), 'Wide layout has three actions in the first row');
await welcome.getByRole('button', { name: /^New file/ }).focus();
for (const name of ['New note', 'Find file', 'Open folder', 'Open browser']) {
await page.keyboard.press('Tab');
assert.ok((await page.evaluate(() => document.activeElement.textContent)).includes(name), `Tab reaches ${name} in order`);
}
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 page.setViewportSize({ width: 850, height: 650 });
await page.screenshot({ path: `${output}/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 });
}
await page.getByRole('navigation', { name: 'Workspace files' }).click({ button: 'right', position: { x: 80, y: 320 } });
await folderAction().focus();
await page.keyboard.press('Enter');
await checkRename('untitled 2');
await input().fill('Created folder');
await input().press('Enter');
await row('Created folder').waitFor();
await row('Parent').click();
await row('Parent').click();
assert.equal(await row('Parent').getAttribute('aria-expanded'), 'false');
await row('Parent').click({ button: 'right' });
await folderAction().click();
await checkRename('untitled');
assert.equal(await row('Parent').getAttribute('aria-expanded'), 'true', 'Cached collapsed parent opens for rename');
await input().press('Escape');
await row('Parent/untitled').waitFor();
for (const mode of ['dark', 'light']) {
await setMode(mode);
await row('Parent').click({ button: 'right' });
await folderAction().click();
const expected = mode === 'dark' ? 'untitled 2' : 'untitled 3';
await checkRename(expected);
await page.screenshot({ path: `${output}/new-folder-${mode}.png` });
await page.setViewportSize({ width: 850, height: 650 });
await page.screenshot({ path: `${output}/new-folder-${mode}-narrow.png` });
await input().press('Escape');
await page.setViewportSize({ width: 1280, height: 850 });
}
await row('Empty').click({ button: 'right' });
await folderAction().click();
await checkRename('untitled');
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');
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.close();
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));
console.log(`Navigation checks passed. Evidence: ${output}`);
} finally { await browser.close(); }
+142
View File
@@ -0,0 +1,142 @@
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 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}`);
},
};
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");
await row("note.md").waitFor();
await page.getByRole("button", { name: "New file", exact: true }).click();
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 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);
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);
await row("hello.txt").dblclick();
await page.waitForFunction(() => !!document.querySelector(".monaco-editor .view-line"));
await row("hello.txt").click({ button: "right" });
await page.getByRole("menuitem", { name: "Rename", exact: true }).click();
assert.equal(await row("hello.txt").locator("input.rename").inputValue(), "hello.txt");
await row("hello.txt").locator("input.rename").fill("hello.py");
await page.keyboard.press("Enter");
await row("hello.py").waitFor();
await page.waitForFunction(async () => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
return monaco.editor.getEditors().some(editor => editor.getDomNode()?.isConnected && editor.getModel()?.getLanguageId() === "python");
});
const code = await modelDetails();
assert.equal(code.value, "print('hello')\n");
assert.equal(code.fontSize, 13);
await page.keyboard.press("Control+e");
assert.equal((await modelDetails()).fontSize, code.fontSize, "Code size stays the same in both layouts");
await row("note.md").dblclick();
await page.locator(".cm-content").waitFor();
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
window.writerTest = EditorView.findFromDOM(document.querySelector(".cm-content"));
});
for (const theme of ["dark", "light"]) {
await page.evaluate(async 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 } });
const line = document.querySelector(".cm-line"), rect = line.getBoundingClientRect();
const event = new MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: rect.left + 15, clientY: rect.top + 5 });
line.dispatchEvent(event);
return !event.defaultPrevented;
});
assert.equal(nativeAllowed, true, "The native spelling menu is available on plain text");
assert.equal(await page.getByRole("menu").count(), 0);
await page.evaluate(() => { window.writerTest.focus(); });
await page.keyboard.press("Shift+F10");
await page.getByRole("menu", { name: "Markdown text actions", exact: true }).waitFor();
await page.keyboard.press("Escape");
await page.evaluate(() => window.writerTest.dispatch({ selection: { anchor: 0, head: 9 } }));
await page.getByText("Mispelled text.", { exact: true }).click({ button: "right" });
await page.getByRole("menu", { name: "Markdown text actions", exact: true }).waitFor();
await page.keyboard.press("Escape");
await page.locator(".live-writer td").first().click({ button: "right" });
await page.getByRole("menu", { name: "Table actions", exact: true }).waitFor();
await page.keyboard.press("Escape");
await page.locator(".writer-cell-editor").click();
await page.keyboard.press("ArrowRight");
assert.equal(await page.locator(".writer-cell-editor p").evaluate(node => {
const event = new MouseEvent("contextmenu", { bubbles: true, cancelable: true });
node.dispatchEvent(event);
return !event.defaultPrevented;
}), 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(); }
+132
View File
@@ -0,0 +1,132 @@
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 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");
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');
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');
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');
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(errors,[]);
console.log('Rename selection passed: file, folder, editor dialog, dark/wide and light/narrow.');
} finally { await browser.close(); }
+158
View File
@@ -0,0 +1,158 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
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 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}`);
},
};
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(); }
+182
View File
@@ -0,0 +1,182 @@
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);
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'),
};
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;
},
};
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);
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);
await page.keyboard.press('Control+y'); await row('folder/nested/renamed.md').waitFor();
for (const path of ['folder', 'folder/nested', 'other']) await expanded(path);
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);
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);
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')), '');
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');
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 paneMenu(); await item('New note').focus(); await page.keyboard.press('ArrowRight');
await page.screenshot({ path: `output/host-navigation-pass3/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' });
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 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);
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.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();
const graph = page.getByRole('menuitem', { name: /Show Git graph/ });
await graph.waitFor();
assert.equal(await page.getByRole('menuitem', { name: /source control/i }).count(), 0);
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 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);
external.pluginNavigation.set([{ owner: 'pm-test', id: 'pm', title: 'Project Management', icon: 'kanban', placement: 'editor', toolbar: true }, { owner: 'git-test', id: 'source', title: 'Source control', icon: 'git', placement: 'sidebar', toolbar: true }]);
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; };
});
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.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);
await page.getByRole('button', { name: 'Plug-in views', exact: true }).click();
assert.equal(await page.getByRole('menuitem', { name: /Project Management/ }).count(), 1);
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 page.getByRole('button', { name: 'Plug-in views', exact: true }).click();
await page.screenshot({ path: `output/host-navigation-pass3/plugin-navigation-${mode}.png` });
await page.keyboard.press('Escape');
}
const token = '00000000-0000-4000-8000-000000000001';
const saved = await page.evaluate(token => {
const layout = JSON.stringify({ leftOpen: true, rightOpen: true, leftWidth: 280, rightWidth: 260, leftView: 'files' });
localStorage.setItem('runestone.workbenchLayout', layout);
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}`);
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);
assert.equal(await detached.getByRole('button', { name: 'Show outline', exact: true }).count(), 0);
assert.equal(await detached.evaluate(() => localStorage.getItem('runestone.workbenchLayout')), saved);
assert.equal(await detached.getByRole('button', { name: 'Files', exact: true }).count(), 0);
await detached.keyboard.press('Control+b');
await detached.keyboard.press('Control+Shift+f');
assert.equal(await detached.locator('aside.left,aside.right,.plugin-ribbon,.gutter-v').count(), 0);
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 detached.setViewportSize({ width: 650, height: 600 });
await detached.screenshot({ path: `output/host-navigation-pass3/detached-${mode}-narrow.png` });
}
assert.deepEqual(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(); }
+123
View File
@@ -0,0 +1,123 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
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 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 };
});
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'] });
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));
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(); }