From c66ea1ce8310ea00542c0c4101fdc3ed35174330 Mon Sep 17 00:00:00 2001 From: Knotty Wyvern Date: Tue, 27 Oct 2026 19:55:49 -0700 Subject: [PATCH] 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. --- package.json | 2 + pnpm-lock.yaml | 19 ++ scripts/buildInstaller.mjs | 14 +- scripts/buildPlugins.mjs | 9 +- scripts/menuSurfaceAudit.mjs | 5 +- scripts/smoke.mjs | 199 ++++++++++++++++++ tests/smoke/_harness/index.mjs | 188 +++++++++++++++++ tests/smoke/browser/fields.smoke.mjs | 1 + tests/smoke/browser/interaction.smoke.mjs | 1 + tests/smoke/find/pluginViews.smoke.mjs | 1 + tests/smoke/layout/workbench.smoke.mjs | 1 + tests/smoke/plugins/choiceMenus.smoke.mjs | 3 +- tests/smoke/plugins/lifecycle.smoke.mjs | 1 + .../tooltipsAndBlankBrowser.smoke.mjs | 3 +- .../treeDragLinksAndGitToolbar.smoke.mjs | 1 + .../workspaceShortcutsAndTemplates.smoke.mjs | 2 +- tests/smoke/tables/formulas.smoke.mjs | 1 + tests/smoke/tables/navigation.smoke.mjs | 1 + tests/smoke/tabs/order.smoke.mjs | 95 ++++----- tests/smoke/tree/renameUndo.smoke.mjs | 1 + 20 files changed, 479 insertions(+), 69 deletions(-) create mode 100644 scripts/smoke.mjs create mode 100644 tests/smoke/_harness/index.mjs diff --git a/package.json b/package.json index e4c661f..669f7f7 100644 --- a/package.json +++ b/package.json @@ -14,6 +14,7 @@ "check:menus": "node scripts/menuSurfaceAudit.mjs", "tauri": "tauri", "test": "node --experimental-strip-types --test \"tests/unit/**/*.spec.ts\"", + "smoke": "node scripts/smoke.mjs", "build:plugins": "node scripts/buildPlugins.mjs", "browser:check": "npm --prefix browser-runtime run check", "browser:test": "npm --prefix browser-runtime test", @@ -56,6 +57,7 @@ "@sveltejs/vite-plugin-svelte": "^7.1.2", "@tauri-apps/cli": "^2", "@types/node": "24.19.2", + "playwright": "1.63.0", "svelte": "^5.56.3", "svelte-check": "^4.6.0", "typescript": "~6.0.3", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 13df774..7f2106b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -102,6 +102,9 @@ importers: '@types/node': specifier: 24.19.2 version: 24.19.2 + playwright: + specifier: 1.63.0 + version: 1.63.0 svelte: specifier: ^5.56.3 version: 5.57.1 @@ -1193,6 +1196,16 @@ packages: resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} engines: {node: '>=12'} + playwright-core@1.63.0: + resolution: {integrity: sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==} + engines: {node: '>=20'} + hasBin: true + + playwright@1.63.0: + resolution: {integrity: sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==} + engines: {node: '>=20'} + hasBin: true + points-on-curve@0.2.0: resolution: {integrity: sha512-0mYKnYYe9ZcqMCWhUjItv/oHjvgEsfKvnUTg8sAtnHr3GVy7rGkXCb6d5cSyqrWqL4k81b9CPg3urd+T7aop3A==} @@ -2461,6 +2474,12 @@ snapshots: picomatch@4.0.7: {} + playwright-core@1.63.0: {} + + playwright@1.63.0: + dependencies: + playwright-core: 1.63.0 + points-on-curve@0.2.0: {} points-on-path@0.2.1: diff --git a/scripts/buildInstaller.mjs b/scripts/buildInstaller.mjs index 40278b7..a97b721 100644 --- a/scripts/buildInstaller.mjs +++ b/scripts/buildInstaller.mjs @@ -23,6 +23,9 @@ if (config.bundle?.windows?.allowDowngrades === true) throw Error('Downgrade pro const platformConfig = JSON.parse(await fs.readFile(path.join(root, 'src-tauri/tauri.windows.conf.json'), 'utf8')); if (platformConfig.bundle.windows.allowDowngrades !== false) throw Error('Downgrade protection must remain enabled.'); if (process.platform !== 'win32') throw Error('Build the Windows installer on Windows.'); +if (!(await exists(path.join(root, 'src-tauri/browser-engine/RuneStone-Browser.exe')))) { + throw Error('The browser runtime is not staged. Run pnpm browser:stage first. See docs/development.md#built-in-browser-runtime.'); +} const artifactDir = path.join(root, 'src-tauri/target/release/bundle/nsis'); const artifact = path.join(artifactDir, `RuneStone_${next.version}_x64-setup.exe`); const internalArtifact = path.join(artifactDir, `RuneStone_${next.toolchain}_x64-setup.exe`); @@ -30,7 +33,8 @@ const releaseDir = path.join(root, 'releases', next.version); const releaseArtifact = path.join(releaseDir, path.basename(artifact)); const metadataPath = path.join(releaseDir, 'host.json'); for (const file of new Set([artifact, internalArtifact, releaseArtifact, metadataPath])) if (await exists(file)) throw Error('The release file already exists: ' + file); -const staging = path.join(root, 'output/installer-build', next.version); +// Each attempt keeps its own backups, so a later attempt cannot replace them. +const staging = path.join(root, 'output/installer-build', next.version, new Date().toISOString().replaceAll(':', '-')); await fs.mkdir(staging, { recursive: true }); for (let i = 0; i < files.length; i++) await fs.writeFile(path.join(staging, path.basename(files[i]) + '.before'), before[i]); let template = await fs.readFile(path.join(root, 'src-tauri/windows/installer.nsi'), 'utf8'); @@ -53,12 +57,17 @@ if (/\[package\.metadata\.runestone\]/.test(cargo)) { const lock = before[3].replace(/(name = "runestone"\r?\nversion = ")[^"]+"/, `$1${next.toolchain}"`); const updated = [JSON.stringify(packageJson, null, 2) + '\n', JSON.stringify(config, null, 2) + '\n', cargo, lock]; const env = { ...process.env, GIT_CONFIG_COUNT: '1', GIT_CONFIG_KEY_0: 'safe.directory', GIT_CONFIG_VALUE_0: root.replaceAll('\\', '/') }; +// Ctrl+C also stops the child build. Keep this process alive so that the version files are restored. +let interrupted = false; +for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(signal, () => { interrupted = true; process.exitCode = 130; }); async function run(command, parameters) { + if (interrupted) throw Error('The build was interrupted.'); console.log(command + ' ' + parameters.join(' ')); const code = await new Promise((resolve, reject) => { const child = spawn(command, parameters, { cwd: root, env, stdio: 'inherit', windowsHide: true }); child.on('error', reject); child.on('exit', resolve); }); + if (interrupted) throw Error('The build was interrupted.'); if (code !== 0) throw Error('The build command failed with exit code ' + code); } let complete = false; @@ -75,7 +84,7 @@ try { await fs.copyFile(artifact, releaseArtifact, 1); const bytes = await fs.readFile(releaseArtifact); const metadata = { version: next.version, toolchainVersion: next.toolchain, windowsVersion: next.windows, - source: releaseArtifact, path: releaseArtifact, bytes: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') }; + file: path.basename(releaseArtifact), bytes: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') }; await fs.writeFile(metadataPath, JSON.stringify(metadata, null, 2) + '\n', { flag: 'wx' }); await fs.unlink(artifact); complete = true; @@ -83,6 +92,7 @@ try { } finally { if (!complete) { for (let i = 0; i < files.length; i++) await fs.writeFile(files[i], before[i]); + console.error('The build did not complete. The version fields are restored. Backups: ' + staging); for (const file of new Set([artifact, internalArtifact, releaseArtifact, metadataPath])) { if (await exists(file)) await fs.rename(file, path.join(staging, path.basename(file) + '.failed-' + Date.now())); } diff --git a/scripts/buildPlugins.mjs b/scripts/buildPlugins.mjs index 0aa7c90..32d5af6 100644 --- a/scripts/buildPlugins.mjs +++ b/scripts/buildPlugins.mjs @@ -1,19 +1,22 @@ -import { mkdir, cp, access } from "node:fs/promises"; +import { mkdir, cp, access, rm } from "node:fs/promises"; import { execFileSync } from "node:child_process"; import { resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { packagePlugin } from "./packagePlugin.mjs"; const root = fileURLToPath(new URL("../", import.meta.url)); -const formulasRoot = resolve(process.env.RUNESTONE_TABLE_FORMULAS_ROOT || resolve(root, "../RuneStone_Table_Formulas")); +const pluginRepos = process.env.RUNESTONE_PLUGIN_REPOS || resolve(root, ".."); +const formulasRoot = resolve(process.env.RUNESTONE_TABLE_FORMULAS_ROOT || resolve(pluginRepos, "RuneStone_Table_Formulas")); const formulasBuild = resolve(formulasRoot, "scripts/build.mjs"); try { await access(formulasBuild); } catch { - throw new Error("Clone RuneStone_Table_Formulas beside RuneStone, or set RUNESTONE_TABLE_FORMULAS_ROOT. Install its dependencies before building plugins."); + throw new Error("Clone RuneStone_Table_Formulas beside RuneStone, or set RUNESTONE_PLUGIN_REPOS or RUNESTONE_TABLE_FORMULAS_ROOT. Install its dependencies before building plugins."); } execFileSync(process.execPath, [formulasBuild], { cwd: formulasRoot, stdio: "inherit" }); const formulasOutput = resolve(root, "plugin-packages/table-formulas"); +// Remove the previous build, so deleted plugin files do not stay in the package. +await rm(formulasOutput, { recursive: true, force: true }); await mkdir(formulasOutput, { recursive: true }); await cp(resolve(formulasRoot, "dist/plugin"), formulasOutput, { recursive: true }); console.log(await packagePlugin(formulasOutput, resolve(formulasRoot, "releases"))); diff --git a/scripts/menuSurfaceAudit.mjs b/scripts/menuSurfaceAudit.mjs index 458077b..2411a5b 100644 --- a/scripts/menuSurfaceAudit.mjs +++ b/scripts/menuSurfaceAudit.mjs @@ -3,6 +3,7 @@ import path from 'node:path'; import { fileURLToPath } from 'node:url'; const root = fileURLToPath(new URL('../', import.meta.url)); +const pluginRepos = process.env.RUNESTONE_PLUGIN_REPOS || path.resolve(root, '..'); export const projects = ['RuneStone', 'RuneStone_Project_Management', 'RuneStone_Terminal', 'RuneStone_Background_Slideshow', 'RuneStone_Local_Autocomplete', 'RuneStone_Git', 'RuneStone_PDF_Viewer', 'RuneStone_Table_Formulas', 'RuneStone_CSV_Viewer']; const patterns = { action: /\b(?:showActionMenu|actionMenu)\s*\(/g, @@ -20,7 +21,7 @@ async function files(dir) { export async function discover() { const surfaces = {}, missing = []; for (const project of projects) { - const base = project === 'RuneStone' ? root : path.resolve(root, '..', project); + const base = project === 'RuneStone' ? root : path.resolve(pluginRepos, project); let sources; try { sources = await files(path.join(base, 'src')); } catch (error) { if (error.code === 'ENOENT') { missing.push(project); continue; } throw error; } for (const file of sources) { @@ -45,7 +46,7 @@ export async function checkInventory() { for (const name of ['actionMenu.ts', 'managedActionMenu.ts', 'IconButton.svelte']) { try { const host = await readFile(path.join(root, 'src/lib/ui', name), 'utf8'); - const terminal = await readFile(path.resolve(root, '../RuneStone_Terminal/vendor/runestone/ui', name), 'utf8'); + const terminal = await readFile(path.resolve(pluginRepos, 'RuneStone_Terminal/vendor/runestone/ui', name), 'utf8'); if (host.replaceAll('\r\n', '\n') !== terminal.replaceAll('\r\n', '\n')) failures.push(`Terminal shared snapshot differs: ${name}`); } catch (error) { failures.push(`Cannot check Terminal snapshot ${name}: ${error.code}`); } } diff --git a/scripts/smoke.mjs b/scripts/smoke.mjs new file mode 100644 index 0000000..c97f26b --- /dev/null +++ b/scripts/smoke.mjs @@ -0,0 +1,199 @@ +// Run the browser smoke tests in tests/smoke/. See docs/development.md#browser-smoke-tests. +// +// pnpm smoke [filter...] [--list] [--jobs N] [--timeout seconds] [--no-serve] +// +// A filter selects the tests whose path contains it, for example `tabs` or `tables/drag`. +// A test declares what it needs on a line near the top: +// // @requires plugin:terminal plugin:table-formulas repo:RuneStone_Git/dist electron +// The runner skips a test, with the reason, when a requirement is missing. +import { spawn } from "node:child_process"; +import { createWriteStream, existsSync } from "node:fs"; +import { mkdir, readdir, readFile } from "node:fs/promises"; +import { createRequire } from "node:module"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const root = fileURLToPath(new URL("../", import.meta.url)); +const smokeRoot = path.join(root, "tests", "smoke"); +const logRoot = path.join(root, "output", "smoke", "logs"); + +const args = process.argv.slice(2); +const option = (name, fallback) => { + const index = args.indexOf(name); + if (index < 0) return fallback; + const [value] = args.splice(index, 2).slice(1); + return value; +}; +const flag = name => { + const index = args.indexOf(name); + if (index >= 0) args.splice(index, 1); + return index >= 0; +}; +const list = flag("--list"); +const serve = !flag("--no-serve"); +const jobs = Math.max(1, Number(option("--jobs", "4"))); +const timeoutMs = Math.max(10, Number(option("--timeout", "180"))) * 1000; +const filters = args; + +const env = { ...process.env, SMOKE_URL: process.env.SMOKE_URL || "http://127.0.0.1:1420" }; +const pluginRepos = env.RUNESTONE_PLUGIN_REPOS || path.join(root, ".."); + +async function findTests(dir) { + const result = []; + for (const entry of await readdir(dir, { withFileTypes: true })) { + const full = path.join(dir, entry.name); + if (entry.isDirectory() && !entry.name.startsWith("_")) result.push(...await findTests(full)); + else if (entry.isFile() && entry.name.endsWith(".smoke.mjs")) result.push(full); + } + return result.sort(); +} + +async function requirements(file) { + const head = (await readFile(file, "utf8")).split("\n").slice(0, 10).join("\n"); + return head.match(/@requires\s+([^\n]+)/)?.[1].trim().split(/\s+/) ?? []; +} + +function missing(requirement) { + const [kind, value = ""] = requirement.split(/:(.*)/s); + if (kind === "plugin" && value === "terminal") { + const dist = env.RUNESTONE_TERMINAL_DIST || path.join(pluginRepos, "RuneStone_Terminal", "dist"); + return existsSync(path.join(dist, "main.js")) ? null : `the Terminal plugin is not built at ${dist}`; + } + if (kind === "plugin") { + const entry = path.join(root, "plugin-packages", value, "main.js"); + return existsSync(entry) ? null : `plugin-packages/${value} is missing; run pnpm build:plugins`; + } + if (kind === "repo") { + const target = path.join(pluginRepos, value); + return existsSync(target) ? null : `${target} is missing; set RUNESTONE_PLUGIN_REPOS to the folder of the plugin checkouts`; + } + if (kind === "electron") { + return existsSync(path.join(root, "browser-runtime", "node_modules", "electron")) ? null : "Electron is missing; run npm ci --prefix browser-runtime"; + } + return `unknown requirement "${requirement}"`; +} + +function findChrome() { + if (env.CHROME_PATH || env.PLAYWRIGHT_MODULE) return; + try { + const bundled = createRequire(import.meta.url)("playwright").chromium.executablePath(); + if (existsSync(bundled)) return; + } catch { + return; + } + const candidates = { + win32: [ + path.join(env.PROGRAMFILES || "C:\\Program Files", "Google\\Chrome\\Application\\chrome.exe"), + path.join(env["PROGRAMFILES(X86)"] || "C:\\Program Files (x86)", "Microsoft\\Edge\\Application\\msedge.exe"), + path.join(env.PROGRAMFILES || "C:\\Program Files", "Microsoft\\Edge\\Application\\msedge.exe"), + ], + darwin: ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "/Applications/Chromium.app/Contents/MacOS/Chromium"], + linux: ["/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser"], + }[process.platform] ?? []; + const found = candidates.find(existsSync); + if (found) env.CHROME_PATH = found; + else console.warn("No Chromium found. Run `pnpm exec playwright install chromium`, or set CHROME_PATH."); +} + +async function reachable(url) { + try { + await fetch(url, { signal: AbortSignal.timeout(2000) }); + return true; + } catch { + return false; + } +} + +async function startServer() { + const vite = path.join(root, "node_modules", "vite", "bin", "vite.js"); + const server = spawn(process.execPath, [vite, "dev"], { cwd: root, stdio: "ignore", windowsHide: true }); + for (let waited = 0; waited < 60000; waited += 500) { + if (await reachable(env.SMOKE_URL)) return server; + await new Promise(resolve => setTimeout(resolve, 500)); + } + server.kill(); + throw new Error(`The dev server did not start at ${env.SMOKE_URL}.`); +} + +function run(file) { + const name = path.relative(smokeRoot, file).replace(/\\/g, "/").replace(/\.smoke\.mjs$/, ""); + const log = path.join(logRoot, name.replaceAll("/", "__") + ".log"); + const started = Date.now(); + return new Promise(resolve => { + const out = createWriteStream(log); + const child = spawn(process.execPath, [file], { cwd: root, env, stdio: ["ignore", "pipe", "pipe"], windowsHide: true }); + child.stdout.pipe(out, { end: false }); + child.stderr.pipe(out, { end: false }); + const timer = setTimeout(() => child.kill(), timeoutMs); + child.on("close", code => { + clearTimeout(timer); + out.end(); + const seconds = ((Date.now() - started) / 1000).toFixed(1); + const status = code === 0 ? "pass" : Date.now() - started >= timeoutMs ? "timeout" : "fail"; + resolve({ name, status, detail: `${seconds}s`, log }); + }); + }); +} + +const tests = (await findTests(smokeRoot)).filter(file => { + const rel = path.relative(smokeRoot, file).replace(/\\/g, "/"); + return !filters.length || filters.some(filter => rel.includes(filter)); +}); +if (!tests.length) { + console.error(`No smoke tests match: ${filters.join(" ")}`); + process.exit(1); +} + +const plan = []; +for (const file of tests) { + const needs = await requirements(file); + const reasons = needs.map(missing).filter(Boolean); + plan.push({ file, needs, reasons }); +} + +if (list) { + for (const { file, needs, reasons } of plan) { + const name = path.relative(smokeRoot, file).replace(/\\/g, "/"); + console.log(`${reasons.length ? "skip" : "run "} ${name}${needs.length ? ` [${needs.join(" ")}]` : ""}${reasons.length ? ` (${reasons.join("; ")})` : ""}`); + } + process.exit(0); +} + +findChrome(); +await mkdir(logRoot, { recursive: true }); +let server; +if (!(await reachable(env.SMOKE_URL))) { + if (!serve) { + console.error(`Nothing serves ${env.SMOKE_URL}. Start pnpm dev, or run without --no-serve.`); + process.exit(1); + } + console.log(`Starting the dev server at ${env.SMOKE_URL}...`); + server = await startServer(); +} + +const results = []; +const queue = plan.filter(item => !item.reasons.length); +for (const item of plan.filter(item => item.reasons.length)) { + results.push({ name: path.relative(smokeRoot, item.file).replace(/\\/g, "/").replace(/\.smoke\.mjs$/, ""), status: "skip", detail: item.reasons.join("; ") }); +} +async function worker() { + while (queue.length) { + const { file } = queue.shift(); + const result = await run(file); + results.push(result); + console.log(`${result.status.padEnd(7)} ${result.name} (${result.detail})`); + } +} +try { + await Promise.all(Array.from({ length: Math.min(jobs, queue.length || 1) }, worker)); +} finally { + server?.kill(); +} + +const count = status => results.filter(result => result.status === status).length; +console.log(""); +for (const result of results.filter(item => item.status !== "pass").sort((a, b) => a.name.localeCompare(b.name))) { + console.log(`${result.status.padEnd(7)} ${result.name}: ${result.status === "skip" ? result.detail : path.relative(root, result.log)}`); +} +console.log(`\n${count("pass")} passed, ${count("fail") + count("timeout")} failed, ${count("skip")} skipped. Logs: ${path.relative(root, logRoot)}`); +process.exitCode = count("fail") + count("timeout") ? 1 : 0; diff --git a/tests/smoke/_harness/index.mjs b/tests/smoke/_harness/index.mjs new file mode 100644 index 0000000..3133ad9 --- /dev/null +++ b/tests/smoke/_harness/index.mjs @@ -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 `, 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// 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(); + } +} diff --git a/tests/smoke/browser/fields.smoke.mjs b/tests/smoke/browser/fields.smoke.mjs index fda0134..dd7fc9e 100644 --- a/tests/smoke/browser/fields.smoke.mjs +++ b/tests/smoke/browser/fields.smoke.mjs @@ -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'; diff --git a/tests/smoke/browser/interaction.smoke.mjs b/tests/smoke/browser/interaction.smoke.mjs index 4165956..b6edabf 100644 --- a/tests/smoke/browser/interaction.smoke.mjs +++ b/tests/smoke/browser/interaction.smoke.mjs @@ -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'; diff --git a/tests/smoke/find/pluginViews.smoke.mjs b/tests/smoke/find/pluginViews.smoke.mjs index edd4b03..7220955 100644 --- a/tests/smoke/find/pluginViews.smoke.mjs +++ b/tests/smoke/find/pluginViews.smoke.mjs @@ -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'; diff --git a/tests/smoke/layout/workbench.smoke.mjs b/tests/smoke/layout/workbench.smoke.mjs index 4cf2383..5654975 100644 --- a/tests/smoke/layout/workbench.smoke.mjs +++ b/tests/smoke/layout/workbench.smoke.mjs @@ -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"; diff --git a/tests/smoke/plugins/choiceMenus.smoke.mjs b/tests/smoke/plugins/choiceMenus.smoke.mjs index 8ddc4c2..448ee58 100644 --- a/tests/smoke/plugins/choiceMenus.smoke.mjs +++ b/tests/smoke/plugins/choiceMenus.smoke.mjs @@ -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]) { diff --git a/tests/smoke/plugins/lifecycle.smoke.mjs b/tests/smoke/plugins/lifecycle.smoke.mjs index c2a12d3..6e6e059 100644 --- a/tests/smoke/plugins/lifecycle.smoke.mjs +++ b/tests/smoke/plugins/lifecycle.smoke.mjs @@ -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"; diff --git a/tests/smoke/regressions/tooltipsAndBlankBrowser.smoke.mjs b/tests/smoke/regressions/tooltipsAndBlankBrowser.smoke.mjs index 925b283..99fc3bf 100644 --- a/tests/smoke/regressions/tooltipsAndBlankBrowser.smoke.mjs +++ b/tests/smoke/regressions/tooltipsAndBlankBrowser.smoke.mjs @@ -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 }); diff --git a/tests/smoke/regressions/treeDragLinksAndGitToolbar.smoke.mjs b/tests/smoke/regressions/treeDragLinksAndGitToolbar.smoke.mjs index 3476875..65adfb9 100644 --- a/tests/smoke/regressions/treeDragLinksAndGitToolbar.smoke.mjs +++ b/tests/smoke/regressions/treeDragLinksAndGitToolbar.smoke.mjs @@ -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"; diff --git a/tests/smoke/regressions/workspaceShortcutsAndTemplates.smoke.mjs b/tests/smoke/regressions/workspaceShortcutsAndTemplates.smoke.mjs index beda113..cfee8f6 100644 --- a/tests/smoke/regressions/workspaceShortcutsAndTemplates.smoke.mjs +++ b/tests/smoke/regressions/workspaceShortcutsAndTemplates.smoke.mjs @@ -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(() => { diff --git a/tests/smoke/tables/formulas.smoke.mjs b/tests/smoke/tables/formulas.smoke.mjs index 46e53a6..ba899f2 100644 --- a/tests/smoke/tables/formulas.smoke.mjs +++ b/tests/smoke/tables/formulas.smoke.mjs @@ -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"; diff --git a/tests/smoke/tables/navigation.smoke.mjs b/tests/smoke/tables/navigation.smoke.mjs index 3d05f02..13f6d3c 100644 --- a/tests/smoke/tables/navigation.smoke.mjs +++ b/tests/smoke/tables/navigation.smoke.mjs @@ -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"; diff --git a/tests/smoke/tabs/order.smoke.mjs b/tests/smoke/tabs/order.smoke.mjs index 7448bb5..bf80afc 100644 --- a/tests/smoke/tabs/order.smoke.mjs +++ b/tests/smoke/tabs/order.smoke.mjs @@ -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(); -} +}); diff --git a/tests/smoke/tree/renameUndo.smoke.mjs b/tests/smoke/tree/renameUndo.smoke.mjs index 2669eed..1da6b51 100644 --- a/tests/smoke/tree/renameUndo.smoke.mjs +++ b/tests/smoke/tree/renameUndo.smoke.mjs @@ -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';