Add a smoke test runner, a shared harness, and safer build scripts

- pnpm smoke runs tests/smoke/ in parallel. It starts Vite when nothing
  serves SMOKE_URL, finds an installed Chrome when Playwright has no
  Chromium, and skips a test with a reason when a requirement that the
  test declares with "// @requires" is missing. Logs go to
  output/smoke/logs/.
- tests/smoke/_harness/ holds the Playwright launch, page error
  collection, the Tauri IPC mock with an in-memory workspace, and output
  folders. tabs/order uses it as the first converted test.
- Pin Playwright 1.63.0, the version that browser-runtime uses.
- RUNESTONE_PLUGIN_REPOS names the folder of the sibling plugin
  checkouts for buildPlugins, the menu audit, and the smoke tests.
- buildInstaller restores the version fields after Ctrl+C, keeps the
  backups of each attempt, stops when the browser runtime is not staged,
  and writes the file name instead of absolute paths to host.json.
- buildPlugins clears the staged Table Formulas package before copying.
- plugins/choiceMenus used the wrong Local Autocomplete folder name.
This commit is contained in:
Knotty Wyvern
2026-10-27 19:55:49 -07:00
parent e433bed28e
commit c66ea1ce83
20 changed files with 479 additions and 69 deletions
+188
View File
@@ -0,0 +1,188 @@
// Shared setup for the browser smoke tests: Playwright, the Tauri IPC mock, and output folders.
// Run a test with `pnpm smoke <name>`, or run its file with Node while `pnpm dev` serves the app.
import { createRequire } from "node:module";
import { mkdir } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import path from "node:path";
export const repoRoot = fileURLToPath(new URL("../../../", import.meta.url));
export const smokeUrl = process.env.SMOKE_URL || "http://127.0.0.1:1420";
/** The path of a sibling plugin checkout, for example pluginRepo("RuneStone_Git"). */
export function pluginRepo(folder) {
return path.resolve(process.env.RUNESTONE_PLUGIN_REPOS || path.join(repoRoot, ".."), folder);
}
/** Playwright, from PLAYWRIGHT_MODULE or the project dependency. */
export function playwright() {
return createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || "playwright");
}
/** Start headless Chromium. CHROME_PATH selects an installed browser. */
export function launchBrowser(options = {}) {
const executablePath = process.env.CHROME_PATH;
return playwright().chromium.launch({ headless: true, ...(executablePath ? { executablePath } : {}), ...options });
}
/** Open a page that collects uncaught page errors in `page.errors`. */
export async function openPage(target, { viewport = { width: 1440, height: 1000 }, timeout = 10000, ...options } = {}) {
const page = await target.newPage({ viewport, ...options });
page.setDefaultTimeout(timeout);
page.errors = [];
page.on("pageerror", error => page.errors.push(error.message));
return page;
}
/** Create and return output/smoke/<name>/ for screenshots and reports. */
export async function outputDir(name) {
const dir = path.join(repoRoot, "output", "smoke", name);
await mkdir(dir, { recursive: true });
return dir;
}
/** Wait two animation frames, so layout and Svelte updates settle. */
export function settle(page) {
return page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
}
/**
* Mock the Tauri IPC layer before the app loads. The mock handles the event plugin.
*
* `commands(test)` runs in the page and returns a map from command name to handler `(args, test) => result`.
* It cannot use variables from the test file. Pass data through `state`, which must be JSON.
* `test` is also `window.__TEST__`: `{ state, calls, emit(event, payload), label, workspace(options) }`.
* A command without a handler throws "Unhandled IPC", or returns null when `strict` is false.
*/
export function mockTauri(target, { label = "main", state = {}, commands, strict = true } = {}) {
const options = JSON.stringify({ label, state, strict });
return target.addInitScript(`(${installMock})(${options}, ${commands ? commands.toString() : "undefined"});`);
}
// This function runs in the page. Keep it self-contained.
function installMock(options, commands) {
let sequence = 0;
const callbacks = new Map();
const listeners = new Map();
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
// An in-memory workspace: `files` maps workspace paths to text. Folders come from the paths and `folders`.
// Create, rename, and delete emit "workspace-event". Writes emit it only when `writeEvents` is true.
const workspace = ({ root = "C:\\workspace", name = root.split(/[\\/]/).pop(), files = {}, folders = [], watchMode = "native", recent = [], writeEvents = false } = {}) => {
const store = files instanceof Map ? files : new Map(Object.entries(files));
const dirs = new Set(folders);
const parentOf = rel => rel.includes("/") ? rel.slice(0, rel.lastIndexOf("/")) : "";
const allFolders = () => {
const result = new Set(dirs);
for (const rel of store.keys()) for (let dir = parentOf(rel); dir; dir = parentOf(dir)) result.add(dir);
return result;
};
const changed = (kind, paths) => emit("workspace-event", { root, kind, paths });
const handlers = {
workspace_last_path: () => root,
workspace_recent: () => recent,
workspace_open: () => ({ root, name, watch_mode: watchMode }),
workspace_list: ({ rel = "" }) => {
const children = [];
for (const dir of allFolders()) if (parentOf(dir) === rel) children.push({ name: dir.split("/").pop(), rel_path: dir, kind: "folder" });
for (const file of store.keys()) if (parentOf(file) === rel) children.push({ name: file.split("/").pop(), rel_path: file, kind: "file" });
return children;
},
workspace_list_markdown: () => [...store.keys()].filter(rel => /\.md$/i.test(rel)).sort(),
workspace_read: ({ rel }) => {
if (!store.has(rel)) throw new Error(`Missing file: ${rel}`);
return store.get(rel);
},
workspace_read_many: ({ paths }) => paths.map(rel => store.has(rel) ? { path: rel, source: store.get(rel) } : { path: rel, error: "Missing file" }),
workspace_write: ({ rel, contents }) => {
store.set(rel, contents);
if (writeEvents) changed("modify", [rel]);
return null;
},
workspace_create: ({ rel, kind }) => {
if (store.has(rel) || allFolders().has(rel)) throw new Error("Destination exists");
if (kind === "folder") dirs.add(rel); else store.set(rel, "");
changed("create", [rel]);
return null;
},
workspace_rename: ({ from, to }) => {
if (store.has(to) || allFolders().has(to)) throw new Error("Destination exists");
for (const [rel, text] of [...store]) {
if (rel === from || rel.startsWith(from + "/")) { store.delete(rel); store.set(to + rel.slice(from.length), text); }
}
for (const dir of [...dirs]) if (dir === from || dir.startsWith(from + "/")) { dirs.delete(dir); dirs.add(to + dir.slice(from.length)); }
changed("rename", [from, to]);
return null;
},
workspace_delete: ({ rel }) => {
for (const key of [...store.keys()]) if (key === rel || key.startsWith(rel + "/")) store.delete(key);
for (const dir of [...dirs]) if (dir === rel || dir.startsWith(rel + "/")) dirs.delete(dir);
changed("remove", [rel]);
return null;
},
workspace_search: ({ query }) => {
const hits = [];
for (const [rel, text] of store) text.split("\n").forEach((line, index) => {
if (query && line.toLowerCase().includes(query.toLowerCase())) hits.push({ rel_path: rel, line: index + 1, text: line });
});
return hits;
},
workspace_abs_path: ({ rel }) => `${root}\\${rel.replaceAll("/", "\\")}`,
};
return Object.assign(handlers, { files: store, folders: dirs, root, name });
};
const test = { state: options.state, calls: [], emit, label: options.label, workspace };
const table = commands ? commands(test) || {} : {};
window.isTauri = true;
window.__TEST__ = test;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: options.label }, currentWebview: { label: options.label } },
transformCallback: callback => {
const id = ++sequence;
callbacks.set(id, callback);
return id;
},
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
test.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 null; }
if (command === "plugin:event|emit" || command === "plugin:event|emit_to") { emit(args.event, args.payload); return null; }
const handler = table[command];
if (typeof handler === "function") {
const result = await handler(args, test);
return result === undefined ? null : result;
}
if (options.strict) throw new Error(`Unhandled IPC: ${command}`);
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
}
/**
* Run one smoke test: start the browser, run `body`, fail on page errors, and close the browser.
* `body({ browser, page })` returns nothing. Set `allowPageErrors` for tests that expect page errors.
*/
export async function runSmoke(name, body, { viewport, timeout, allowPageErrors = false } = {}) {
const browser = await launchBrowser();
try {
const page = await openPage(browser, { viewport, timeout });
await body({ browser, page });
if (!allowPageErrors && page.errors.length) throw new Error(`Page errors:\n${page.errors.join("\n")}`);
console.log(`PASS ${name}`);
} catch (error) {
console.error(`FAIL ${name}`);
console.error(error);
process.exitCode = 1;
} finally {
await browser.close();
}
}
+1
View File
@@ -1,3 +1,4 @@
// @requires electron
import { createRequire } from 'node:module';
import { spawn } from 'node:child_process';
import { mkdtemp, mkdir, writeFile } from 'node:fs/promises';
@@ -1,3 +1,4 @@
// @requires electron
import { createRequire } from 'node:module';
import { spawn } from 'node:child_process';
import { mkdtemp, mkdir, writeFile } from 'node:fs/promises';
+1
View File
@@ -1,3 +1,4 @@
// @requires repo:RuneStone_Project_Management/dist/plugin
// Run against the host development server with PLAYWRIGHT_MODULE set when needed.
import { createRequire } from 'node:module';
import assert from 'node:assert/strict';
+1
View File
@@ -1,3 +1,4 @@
// @requires plugin:terminal plugin:table-formulas
import { mockFeaturePlugins } from "../_harness/pluginMocks.mjs";
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
+2 -1
View File
@@ -1,3 +1,4 @@
// @requires repo:RuneStone_Local_Autocomplete/src
import assert from 'node:assert/strict';
import { readFile, mkdir } from 'node:fs/promises';
import { createRequire } from 'node:module';
@@ -13,7 +14,7 @@ await page.route('**/__choice-audit__', route => route.fulfill({ contentType: 't
await page.route('**/__autocomplete__/*.mjs', async route => {
const name = new URL(route.request().url()).pathname.split('/').pop();
assert.ok(['main.mjs', 'engine.mjs'].includes(name));
await route.fulfill({ contentType: 'application/javascript', body: await readFile(new URL(`../../../../RuneStone_LocalAutocomplete/src/${name}`, import.meta.url), 'utf8') });
await route.fulfill({ contentType: 'application/javascript', body: await readFile(new URL(`../../../../RuneStone_Local_Autocomplete/src/${name}`, import.meta.url), 'utf8') });
});
try {
for (const theme of ['light', 'dark']) for (const width of [1100, 390]) {
+1
View File
@@ -1,3 +1,4 @@
// @requires plugin:terminal plugin:table-formulas
import { mockFeaturePlugins } from "../_harness/pluginMocks.mjs";
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
@@ -1,7 +1,8 @@
// @requires electron
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { mkdir } from 'node:fs/promises';
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || '../browser-runtime/node_modules/playwright');
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || '../../../browser-runtime/node_modules/playwright');
const browser = await chromium.launch({ headless: true, executablePath: process.env.CHROME_PATH || 'C:/Program Files/Google/Chrome/Application/chrome.exe' });
const output = '.audit/todo-ui';
await mkdir(output, { recursive: true });
@@ -1,3 +1,4 @@
// @requires repo:RuneStone_Git/dist
// Run against the host dev server with PLAYWRIGHT_MODULE and CHROME_PATH when needed.
import { createRequire } from "node:module";
import { readFile, mkdir } from "node:fs/promises";
@@ -1,7 +1,7 @@
import { createRequire } from 'node:module';
import assert from 'node:assert/strict';
import { mkdir } from 'node:fs/promises';
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || '../node_modules/playwright');
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || '../../../node_modules/playwright');
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
await context.addInitScript(() => {
+1
View File
@@ -1,3 +1,4 @@
// @requires plugin:terminal plugin:table-formulas
import { mockFeaturePlugins } from "../_harness/pluginMocks.mjs";
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
+1
View File
@@ -1,3 +1,4 @@
// @requires plugin:terminal plugin:table-formulas
import { mockFeaturePlugins } from "../_harness/pluginMocks.mjs";
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
+36 -59
View File
@@ -1,60 +1,40 @@
// Run against pnpm dev with PLAYWRIGHT_MODULE set if Playwright is shared.
import { createRequire } from "node:module";
// Tab order: pointer drags, cancellation, keyboard moves, tab menus, empty tabs, and an overflowing tab bar.
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:\\tab-order-workspace";
const files = new Map(Array.from({ length: 16 }, (_, i) => [`note-${String(i).padStart(2, "0")}.md`, `# Note ${i}\n\nKeep this text.\n`]));
files.set("note-00.md", Array.from({ length: 200 }, (_, i) => `Paragraph ${i}.\n\n`).join(""));
let sequence = 0;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: () => ++sequence,
unregisterCallback: () => {},
invoke: async (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: "tab-order-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") { files.set(args.rel, args.contents); return; }
if (command === "workspace_list") return args.rel ? [] : [...files.keys()].map(name => ({ name, rel_path: name, kind: "file" }));
if (command === "workspace_search") return [];
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
import { mockTauri, runSmoke, settle as settleFrames, smokeUrl } from "../_harness/index.mjs";
await runSmoke("tabs/order", async ({ page }) => {
await mockTauri(page, {
commands: test => {
const files = new Map(Array.from({ length: 16 }, (_, i) => [`note-${String(i).padStart(2, "0")}.md`, `# Note ${i}\n\nKeep this text.\n`]));
files.set("note-00.md", Array.from({ length: 200 }, (_, i) => `Paragraph ${i}.\n\n`).join(""));
return {
...test.workspace({ root: "C:\\tab-order-workspace", files }),
workspace_search: () => [],
"plugin:dialog|message": () => "Cancel",
};
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const tab = name => page.getByRole("tab", { name, exact: true });
const order = () => page.getByRole("tablist", { name: "Working tabs" }).getByRole("tab").evaluateAll(nodes => nodes.map(node => node.dataset.path));
const settle = () => page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
async function open(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 tab(name).waitFor();
}
async function drag(from, to, side, cancel) {
const source = await tab(from).boundingBox();
const target = await tab(to).boundingBox();
await page.mouse.move(source.x + source.width / 2, source.y + source.height / 2);
await page.mouse.down();
await page.mouse.move(side === "before" ? target.x + 2 : target.x + target.width - 2, target.y + target.height / 2, { steps: 10 });
if (cancel === "escape") await page.keyboard.press("Escape");
if (cancel === "outside") await page.mouse.move(target.x, target.y + 100);
await page.mouse.up();
await settle();
}
try {
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
});
const settle = () => settleFrames(page);
const tab = name => page.getByRole("tab", { name, exact: true });
const order = () => page.getByRole("tablist", { name: "Working tabs" }).getByRole("tab").evaluateAll(nodes => nodes.map(node => node.dataset.path));
async function open(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 tab(name).waitFor();
}
async function drag(from, to, side, cancel) {
const source = await tab(from).boundingBox();
const target = await tab(to).boundingBox();
await page.mouse.move(source.x + source.width / 2, source.y + source.height / 2);
await page.mouse.down();
await page.mouse.move(side === "before" ? target.x + 2 : target.x + target.width - 2, target.y + target.height / 2, { steps: 10 });
if (cancel === "escape") await page.keyboard.press("Escape");
if (cancel === "outside") await page.mouse.move(target.x, target.y + 100);
await page.mouse.up();
await settle();
}
await page.goto(smokeUrl);
await page.getByText("tab-order-workspace", { exact: true }).waitFor();
for (const name of ["note-00.md", "note-01.md", "note-02.md"]) await open(name);
await drag("note-00.md", "note-02.md", "after");
@@ -120,9 +100,6 @@ try {
await page.mouse.up();
await settle();
assert.equal((await order()).at(-1), "note-15.md");
assert.deepEqual(errors, []);
console.log("PASS: automatic scrolling and drag to the end of an overflowing tab bar");
if (process.env.SCREENSHOT_PATH) await page.screenshot({ path: process.env.SCREENSHOT_PATH });
} finally {
await browser.close();
}
});
+1
View File
@@ -1,3 +1,4 @@
// @requires repo:RuneStone_Git/dist
import { createRequire } from 'node:module';
import assert from 'node:assert/strict';
import { mkdir, readFile } from 'node:fs/promises';