Move the smoke tests onto the shared harness

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

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

Result: 89 passed, 1 flaky, 2 known issues, 0 failed. Before, 45 of 78
passed.
This commit is contained in:
Knotty Wyvern
2026-10-27 20:58:55 -07:00
parent c66ea1ce83
commit 69f90df571
109 changed files with 5920 additions and 7915 deletions
+24 -41
View File
@@ -1,43 +1,26 @@
import { createRequire } from "node:module";
// Settings density: title bars and window controls match the main window, compact plugin rows, narrow layouts, Git dialog focus, many categories.
// @known-issue The settings window controls are 35px high and the main window's are 36px: the settings header draws its divider as a border inside the shared title bar height.
import assert from "node:assert/strict";
import { mkdir } from "node:fs/promises";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const origin = process.env.SMOKE_URL || "http://127.0.0.1:1420";
const errors = [];
await mkdir(".audit", { recursive: true });
try {
import path from "node:path";
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("settings/density", async ({ browser }) => {
const output = await outputDir("settings/density");
const context = await browser.newContext({ viewport: { width: 1152, height: 815 } });
await context.addInitScript(() => {
window.isTauri = true;
let sequence = 0;
const callbacks = new Map();
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 = {}) => {
if (command === "plugins_snapshot") return { root: "D:/RuneStone/plugins", plugins: Array.from({ length: 7 }, (_, index) => ({
manifest: { schemaVersion: 1, id: `org.example.plugin-${index}`, name: `Example plugin ${index + 1}`, author: "RuneStone Team", description: "A plugin description with enough text to check readable wrapping.", version: "0.1.1", apiVersion: 1, entry: "main.js", access: "full-app" },
enabled: false, hash: "test", installedAt: 1791390000000, path: `D:/RuneStone/plugins/plugin-${index}`, error: null, removal: false,
})) };
if (command === "workspace_last_path") return null;
if (command === "plugin:event|listen") return args.handler;
if (command === "plugin:window|is_maximized") return false;
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
await mockTauri(context, {
commands: () => ({
plugins_snapshot: () => ({ root: "D:/RuneStone/plugins", plugins: Array.from({ length: 7 }, (_, index) => ({
manifest: { schemaVersion: 1, id: `org.example.plugin-${index}`, name: `Example plugin ${index + 1}`, author: "RuneStone Team", description: "A plugin description with enough text to check readable wrapping.", version: "0.1.1", apiVersion: 1, entry: "main.js", access: "full-app" },
enabled: false, hash: "test", installedAt: 1791390000000, path: `D:/RuneStone/plugins/plugin-${index}`, error: null, removal: false,
})) }),
workspace_last_path: () => null,
"plugin:window|is_maximized": () => false,
}),
});
const main = await context.newPage();
const settings = await context.newPage();
for (const page of [main, settings]) {
page.setDefaultTimeout(7000);
page.on("pageerror", error => errors.push(error.message));
}
await main.goto(origin);
await settings.goto(`${origin}/?settingsWindow=true`);
const main = await openPage(context, { timeout: 7000 });
const settings = await openPage(context, { timeout: 7000 });
await main.goto(smokeUrl);
await settings.goto(`${smokeUrl}/?settingsWindow=true`);
await settings.getByRole("heading", { name: "General", exact: true }).waitFor();
const header = settings.locator("dialog > header");
const mainHeader = main.locator(".header");
@@ -54,7 +37,7 @@ try {
const pluginRows = content.locator(".row");
assert.equal(await pluginRows.count(), 7);
for (const theme of ["dark", "light"]) {
await settings.evaluate(value => document.documentElement.dataset.theme = value, theme);
await settings.evaluate(value => { document.documentElement.dataset.theme = value; }, theme);
for (const width of [1152, 540, 360]) {
await settings.setViewportSize({ width, height: width === 1152 ? 815 : 420 });
assert(await settings.evaluate(() => document.documentElement.scrollWidth <= innerWidth));
@@ -77,7 +60,7 @@ try {
assert(bounds.width >= 28 && bounds.height >= 28);
assert(await button.getAttribute("aria-label"));
}
await settings.screenshot({ path: `.audit/settings-density-${theme}-${width}.png` });
await settings.screenshot({ path: path.join(output, `${theme}-${width}.png`) });
}
}
await settings.setViewportSize({ width: 540, height: 420 });
@@ -104,6 +87,6 @@ try {
const navigation = await sidebar.boundingBox();
assert(category.y >= navigation.y && category.y + category.height <= navigation.y + navigation.height, "Every plugin category remains reachable");
assert(await settings.getByRole("spinbutton", { name: "Auto-save interval", exact: true }).isVisible());
assert.deepEqual(errors, []);
assert.deepEqual([...main.errors, ...settings.errors], []);
console.log("Settings density smoke passed: matching title bars and window controls, seven plugin rows, compact layout, readable text, accessible actions, both themes, narrow layouts, Git dialog focus, and many plugin categories.");
} finally { await browser.close(); }
});
+35 -54
View File
@@ -1,52 +1,35 @@
// Display language: four locales, persistence, cross-window updates, menu keyboard focus, translated editor menus, and transparency settings.
import assert from 'node:assert/strict';
import { mkdir } from 'node:fs/promises';
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
const origin = process.env.SMOKE_URL || 'http://127.0.0.1:1420';
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const errors = [];
await mkdir('.audit/appearance-language', { recursive: true });
try {
import path from 'node:path';
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
await runSmoke('settings/displayLanguage', async ({ browser }) => {
const output = await outputDir('settings/displayLanguage');
const context = await browser.newContext({ viewport: { width: 1100, height: 800 } });
await context.addInitScript(() => {
window.isTauri = true;
const root = "C:\\appearance-smoke";
const files = new Map(Array.from({ length: 12 }, (_, index) => [`theme-${index}.py`, `# Theme sample ${index}\ndef sample(parameter):\n return parameter\nname = "RuneStone"\nprint(name, 42)\n`]));
const callbacks = new Map();
let sequence = 0;
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 = {}) => {
if (command === "plugins_snapshot") return { root: "C:/appearance-smoke-plugins", plugins: [] };
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "appearance-smoke", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("File absent"); return files.get(args.rel); }
if (command === "workspace_write") { files.set(args.rel, args.contents); return; }
if (command === "workspace_list") return [...files.keys()].filter(path => !path.startsWith(".")).map(path => ({ name: path, rel_path: path, kind: "file" }));
if (command === "workspace_search") return [];
if (command === "plugin:event|listen") return args.handler;
if (command === "plugin:window|is_maximized") return false;
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
await mockTauri(context, {
commands: test => ({
...test.workspace({
root: 'C:\\appearance-smoke',
files: Object.fromEntries(Array.from({ length: 12 }, (_, index) => [`theme-${index}.py`, `# Theme sample ${index}\ndef sample(parameter):\n return parameter\nname = "RuneStone"\nprint(name, 42)\n`])),
}),
plugins_snapshot: () => ({ root: 'C:/appearance-smoke-plugins', plugins: [] }),
'plugin:window|is_maximized': () => false,
}),
});
const settings = await context.newPage();
const main = await context.newPage();
for (const page of [settings, main]) { page.on('pageerror', error => errors.push(error.message)); page.setDefaultTimeout(15000); }
await main.goto(origin);
await settings.goto(`${origin}/?settingsWindow=true`);
await settings.locator('#language-picker').waitFor();
const settings = await openPage(context, { timeout: 15000 });
const main = await openPage(context, { timeout: 15000 });
const languagePicker = settings.locator('#language-picker');
const surfaceOpacity = () => settings.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--rs-surface-opacity').trim());
await main.goto(smokeUrl);
await settings.goto(`${smokeUrl}/?settingsWindow=true`);
await languagePicker.waitFor();
for (const [language, name, heading, appearance, enabled, files] of [
['fr', 'Français', 'Paramètres', 'Apparence', 'Surfaces transparentes', 'Fichiers'],
['ja', '日本語', '設定', '外観', '背景を透過', 'ファイル'],
['zh-CN', '简体中文', '设置', '外观', '透明界面', '文件'],
['en', 'English', 'Settings', 'Appearance', 'Transparent surfaces', 'Files'],
]) {
await settings.locator('#language-picker').click();
await languagePicker.click();
await settings.getByRole('menuitemradio', { name, exact: true }).click();
await settings.getByRole('heading', { name: heading, exact: true }).waitFor();
await main.getByRole('button', { name: files, exact: true }).waitFor();
@@ -56,12 +39,12 @@ try {
await settings.reload();
await settings.getByRole('heading', { name: heading, exact: true }).waitFor();
// Arrow keys and Escape retain shared menu focus behavior.
await settings.locator('#language-picker').focus();
await languagePicker.focus();
await settings.keyboard.press('Enter');
await settings.keyboard.press('End');
await settings.keyboard.press('Home');
await settings.keyboard.press('Escape');
assert(await settings.locator('#language-picker').evaluate(node => node === document.activeElement));
assert(await languagePicker.evaluate(node => node === document.activeElement));
assert(await main.evaluate(async () => {
const { imageControls } = await import('/src/lib/editor/imageControls.ts');
const root = document.createElement('div'); root.innerHTML = '<img data-md-src="sample.png" alt="sample">'; document.body.append(root);
@@ -81,14 +64,14 @@ try {
wrapper.dispatchEvent(new KeyboardEvent('keydown', { key: 'Delete', bubbles: true }));
controls.destroy(); root.remove(); return !text.includes('one') && text.includes('two');
}), `${language}: Delete selected table cell keyboard action`);
await settings.screenshot({ path: `.audit/appearance-language/${language}-general.png` });
await settings.screenshot({ path: path.join(output, `${language}-general.png`) });
await main.locator('[data-tree-rel="theme-0.py"]').click();
await main.locator('.monaco-editor textarea').waitFor();
await main.locator('.view-lines').first().click({ button: 'right' });
await main.locator('.rs-menu').waitFor();
const copyLabels = { fr: 'Copier', ja: 'コピー', 'zh-CN': '复制', en: 'Copy' };
await main.locator('.rs-menu .action-label').filter({ hasText: new RegExp('^' + copyLabels[language] + '$') }).waitFor();
await main.screenshot({ path: `.audit/appearance-language/${language}-workbench-editor-menu.png` });
await main.screenshot({ path: path.join(output, `${language}-workbench-editor-menu.png`) });
await main.keyboard.press('Escape');
await settings.getByRole('button', { name: appearance, exact: true }).click();
for (const mode of ['dark', 'light']) {
@@ -101,25 +84,23 @@ try {
await toggle.uncheck();
assert.equal(await settings.locator('html').getAttribute('data-transparency'), 'off');
await main.waitForFunction(() => document.documentElement.dataset.transparency === 'off');
const opacity = await settings.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--rs-surface-opacity').trim());
assert.equal(opacity, '100%');
assert.equal(await surfaceOpacity(), '100%');
await settings.locator('.picker').first().click();
const menu = settings.getByRole('menu');
const bg = await menu.evaluate(node => getComputedStyle(node).backgroundColor);
const bg = await settings.getByRole('menu').evaluate(node => getComputedStyle(node).backgroundColor);
assert(!bg.endsWith('/ 0.82)') && !bg.startsWith('rgba'), `Opaque menu: ${bg}`);
await settings.screenshot({ path: `.audit/appearance-language/${language}-${mode}-opaque-menu.png` });
await settings.screenshot({ path: path.join(output, `${language}-${mode}-opaque-menu.png`) });
await settings.keyboard.press('Escape');
await toggle.check();
await settings.locator('#surface-transparency').fill('30');
assert.equal(await settings.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--rs-surface-opacity').trim()), '70%');
assert.equal(await surfaceOpacity(), '70%');
await settings.setViewportSize({ width: 360, height: 640 });
await settings.locator("#surface-transparency").scrollIntoViewIfNeeded();
await settings.locator('#surface-transparency').scrollIntoViewIfNeeded();
assert(await settings.locator('.content').evaluate(node => node.scrollWidth <= node.clientWidth), `${language} ${mode}: narrow overflow`);
await settings.screenshot({ path: `.audit/appearance-language/${language}-${mode}-narrow.png` });
await settings.screenshot({ path: path.join(output, `${language}-${mode}-narrow.png`) });
await settings.setViewportSize({ width: 1100, height: 800 });
}
await settings.reload();
}
assert.deepEqual(errors, []);
assert.deepEqual([...settings.errors, ...main.errors], []);
console.log('PASS: 4 locales, persistence, cross-window updates, keyboard menu focus, both themes, opaque menus, transparency levels, narrow layout.');
} finally { await browser.close(); }
});
+58 -69
View File
@@ -1,67 +1,56 @@
// Run against pnpm dev with PLAYWRIGHT_MODULE and CHROME_PATH if needed.
import { createRequire } from "node:module";
import { mkdirSync, readFileSync } from "node:fs";
// General settings: auto-save timers, manual saves, persistence, cross-window updates, validation, storage failure, help, search, focus, narrow layout.
import { readFileSync } from "node:fs";
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { version } = JSON.parse(readFileSync(new URL("../../../package.json", import.meta.url), "utf8"));
mkdirSync(".audit", { recursive: true });
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: 1100, height: 800 } });
const page = await context.newPage();
const settingsPage = await context.newPage();
const errors = [];
page.on("pageerror", error => errors.push(error.message));
settingsPage.on("pageerror", error => errors.push(error.message));
await context.addInitScript(() => {
window.isTauri = true;
const disk = { "note.txt": "Original note" };
const writes = [];
window.__TEST__ = { disk, writes };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: () => 1, unregisterCallback: () => {},
invoke: async (command, args = {}) => {
if (command === "plugins_snapshot") return { root: "D:\\AppData\\RuneStone\\plugins", plugins: [] };
if (command === "workspace_last_path") return "D:\\Notes";
if (command === "workspace_open") return { root: "D:\\Notes", name: "Notes", watch_mode: "native" };
if (command === "workspace_list") return args.rel ? [] : [{ name: "note.txt", rel_path: "note.txt", kind: "file" }];
if (command === "workspace_read") { if (args.rel in disk) return disk[args.rel]; throw "Missing file"; }
if (command === "workspace_write") { disk[args.rel] = args.contents; writes.push(args); return; }
return null;
import path from "node:path";
import { mockTauri, openPage, outputDir, repoRoot, runSmoke, smokeUrl } from "../_harness/index.mjs";
const { version } = JSON.parse(readFileSync(path.join(repoRoot, "package.json"), "utf8"));
await runSmoke("settings/general", async ({ browser }) => {
const output = await outputDir("settings/general");
const context = await browser.newContext({ viewport: { width: 1100, height: 800 } });
await mockTauri(context, {
state: { writes: [] },
commands: test => {
const workspace = test.workspace({ root: "D:\\Notes", files: { "note.txt": "Original note" } });
return {
...workspace,
workspace_write: args => { workspace.workspace_write(args); test.state.writes.push(args); },
plugins_snapshot: () => ({ root: "D:\\AppData\\RuneStone\\plugins", plugins: [] }),
settings_open_window: () => null,
};
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const url = process.env.SMOKE_URL || "http://127.0.0.1:1420";
const settings = settingsPage.getByRole("dialog", { name: "Settings", exact: true });
const trigger = page.getByRole("button", { name: "Settings (Ctrl+,)", exact: true });
async function showSettings(shortcut = false) {
if (shortcut) await page.keyboard.press("Control+,");
else await trigger.click();
await settingsPage.goto(`${url}/?settingsWindow=true`);
await settings.waitFor();
}
async function closeSettings() {
await settingsPage.goto("about:blank");
await page.bringToFront();
}
const interval = settings.getByRole("spinbutton", { name: "Auto-save interval" });
const enabled = settings.getByRole("switch", { name: "Auto-save", exact: true });
async function changeSeconds(value) {
await interval.fill(String(value));
await interval.press("Tab");
}
async function edit(value) {
await page.evaluate(async text => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected).setValue(text);
}, value);
}
const writes = () => page.evaluate(() => window.__TEST__.writes.length);
try {
});
const page = await openPage(context);
const settingsPage = await openPage(context);
const settings = settingsPage.getByRole("dialog", { name: "Settings", exact: true });
const trigger = page.getByRole("button", { name: "Settings (Ctrl+,)", exact: true });
async function showSettings(shortcut = false) {
if (shortcut) await page.keyboard.press("Control+,");
else await trigger.click();
await settingsPage.goto(`${smokeUrl}/?settingsWindow=true`);
await settings.waitFor();
}
async function closeSettings() {
await settingsPage.goto("about:blank");
await page.bringToFront();
}
const interval = settings.getByRole("spinbutton", { name: "Auto-save interval" });
const enabled = settings.getByRole("switch", { name: "Auto-save", exact: true });
async function changeSeconds(value) {
await interval.fill(String(value));
await interval.press("Tab");
}
async function edit(value) {
await page.evaluate(async text => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected).setValue(text);
}, value);
}
const writes = () => page.evaluate(() => window.__TEST__.state.writes.length);
await page.clock.install();
await page.goto(url);
await page.goto(smokeUrl);
await page.locator(".ws").filter({ hasText: "Notes" }).waitFor();
await showSettings();
assert.equal(await interval.inputValue(), "5");
@@ -82,7 +71,7 @@ try {
await settings.getByRole("textbox", { name: "Search settings" }).fill("no such setting");
await settings.getByText("No settings found", { exact: true }).waitFor();
await settings.getByRole("button", { name: "Clear search" }).click();
await settingsPage.screenshot({ path: ".audit/settings-general.png" });
await settingsPage.screenshot({ path: path.join(output, "general.png") });
await closeSettings();
await page.keyboard.press("Control+p");
@@ -109,7 +98,7 @@ try {
await page.clock.runFor(10000);
assert.equal(await writes(), before + 1);
await page.keyboard.press("Control+s");
await page.waitForFunction(count => window.__TEST__.writes.length === count, before + 2);
await page.waitForFunction(count => window.__TEST__.state.writes.length === count, before + 2);
await page.locator(".monaco-editor textarea").focus();
await showSettings(true);
await settings.waitFor();
@@ -119,8 +108,8 @@ try {
await page.getByRole("dialog", { name: "Help and about", exact: true }).waitFor();
await page.keyboard.press("Escape");
const other = await context.newPage();
await other.goto(`${url}/?settingsWindow=true`);
const other = await openPage(context);
await other.goto(`${smokeUrl}/?settingsWindow=true`);
assert.equal(await other.getByRole("spinbutton", { name: "Auto-save interval" }).inputValue(), "3");
assert.equal(await other.getByRole("switch", { name: "Auto-save", exact: true }).isChecked(), false);
await other.getByRole("button", { name: "Restore defaults" }).click();
@@ -152,7 +141,7 @@ try {
const help = page.getByRole("dialog", { name: "Help and about", exact: true });
await help.getByRole("heading", { name: "RuneStone", exact: true }).waitFor();
await help.getByText(`Version ${version}`, { exact: false }).waitFor();
await page.screenshot({ path: ".audit/settings-help.png" });
await page.screenshot({ path: path.join(output, "help.png") });
await page.keyboard.press("Escape");
await page.keyboard.press("Control+b");
await showSettings(true);
@@ -165,11 +154,11 @@ try {
await showSettings(true);
await settings.waitFor();
assert(await settings.evaluate(el => el.scrollWidth === el.clientWidth), "Narrow layout fits");
await settingsPage.screenshot({ path: ".audit/settings-narrow.png" });
await settingsPage.screenshot({ path: path.join(output, "narrow.png") });
for (let i = 0; i < 12; i++) {
await settingsPage.keyboard.press("Tab");
assert(await settings.evaluate(el => el.contains(document.activeElement)), "Focus stays in the modal");
}
assert.deepEqual(errors, []);
assert.deepEqual([...page.errors, ...settingsPage.errors], []);
console.log("Settings smoke passed: timer changes, disabled auto-save, manual saves, persistence, cross-window updates, validation, storage failure, help, search, focus, shortcuts, and narrow layout.");
} finally { await browser.close(); }
});
+51 -62
View File
@@ -1,68 +1,55 @@
// Run against pnpm dev with PLAYWRIGHT_MODULE and CHROME_PATH if needed.
import { createRequire } from "node:module";
import { mkdirSync, readFileSync } from "node:fs";
// Settings window title bar: scoped permissions, drag regions, minimize, maximize, restore, close, Escape, focus, errors, themes, and the browser fallback.
import { readFileSync } from "node:fs";
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 url = process.env.SMOKE_URL || "http://127.0.0.1:1420";
mkdirSync(".audit", { recursive: true });
const settingsCapability = JSON.parse(readFileSync(new URL("../../../src-tauri/capabilities/settings.json", import.meta.url), "utf8"));
assert.deepEqual(settingsCapability.windows, ["settings-main", "settings-workspace-*"]);
for (const action of ["close", "minimize", "toggle-maximize", "start-dragging"]) {
assert(settingsCapability.permissions.includes(`core:window:allow-${action}`));
}
const errors = [];
try {
import path from "node:path";
import { mockTauri, openPage, outputDir, repoRoot, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("settings/titlebar", async ({ browser }) => {
const settingsCapability = JSON.parse(readFileSync(path.join(repoRoot, "src-tauri/capabilities/settings.json"), "utf8"));
assert.deepEqual(settingsCapability.windows, ["settings-main", "settings-workspace-*"]);
for (const action of ["close", "minimize", "toggle-maximize", "start-dragging"]) {
assert(settingsCapability.permissions.includes(`core:window:allow-${action}`));
}
const output = await outputDir("settings/titlebar");
const context = await browser.newContext({ viewport: { width: 920, height: 650 } });
await context.addInitScript(() => {
window.isTauri = true;
const callbacks = new Map();
const listeners = new Map();
window.__TEST__ = { calls: [], maximized: false, fail: "", resize: () => callbacks.get(listeners.get("tauri://resize"))?.({ payload: {} }) };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "settings-main" }, currentWebview: { label: "settings-main" } },
transformCallback: callback => { const id = callbacks.size + 1; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
window.__TEST__.calls.push(command);
if (window.__TEST__.fail === command) throw new Error("Window action failed");
if (command === "plugins_snapshot") return { root: "D:\\SettingsTest\\plugins", plugins: [] };
if (command === "plugin:event|listen") { listeners.set(args.event, args.handler); return args.handler; }
if (command === "plugin:window|is_maximized") return window.__TEST__.maximized;
if (command === "plugin:window|toggle_maximize") window.__TEST__.maximized = !window.__TEST__.maximized;
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
await mockTauri(context, {
label: "settings-main",
state: { maximized: false, failMinimize: false },
commands: test => ({
plugins_snapshot: () => ({ root: "D:\\SettingsTest\\plugins", plugins: [] }),
"plugin:window|is_maximized": () => test.state.maximized,
"plugin:window|toggle_maximize": () => { test.state.maximized = !test.state.maximized; },
"plugin:window|minimize": () => { if (test.state.failMinimize) throw new Error("Window action failed"); },
"plugin:window|close": () => null,
}),
});
const page = await context.newPage();
page.on("pageerror", error => errors.push(error.message));
page.setDefaultTimeout(5000);
await page.goto(`${url}/?settingsWindow=true`);
const page = await openPage(context, { timeout: 5000 });
await page.goto(`${smokeUrl}/?settingsWindow=true`);
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
await dialog.waitFor();
assert.equal(await dialog.getByRole("button", { name: /^Close/ }).count(), 1);
assert(await dialog.locator("header[data-tauri-drag-region] h1[data-tauri-drag-region]").isVisible());
assert.equal(await dialog.locator(".window-controls [data-tauri-drag-region]").count(), 0);
const calls = () => page.evaluate(() => window.__TEST__.calls);
await page.getByRole("button", { name: "Minimize window", exact: true }).click();
const calls = () => page.evaluate(() => window.__TEST__.calls.map(call => call.command));
const closes = async () => (await calls()).filter(command => command === "plugin:window|close").length;
const button = name => page.getByRole("button", { name, exact: true });
await button("Minimize window").click();
assert((await calls()).includes("plugin:window|minimize"));
await page.getByRole("button", { name: "Maximize window", exact: true }).click();
await page.getByRole("button", { name: "Restore window", exact: true }).waitFor();
await page.getByRole("button", { name: "Restore window", exact: true }).focus();
await button("Maximize window").click();
await button("Restore window").waitFor();
await button("Restore window").focus();
await page.keyboard.press("Enter");
await page.getByRole("button", { name: "Maximize window", exact: true }).waitFor();
await page.evaluate(() => { window.__TEST__.maximized = true; window.__TEST__.resize(); });
await page.getByRole("button", { name: "Restore window", exact: true }).waitFor();
await page.getByRole("button", { name: "Close window", exact: true }).focus();
await button("Maximize window").waitFor();
await page.evaluate(() => { window.__TEST__.state.maximized = true; window.__TEST__.emit("tauri://resize", {}); });
await button("Restore window").waitFor();
await button("Close window").focus();
await page.getByRole("tooltip", { name: "Close window", exact: true }).waitFor();
await page.keyboard.press("Space");
const beforeEscape = (await calls()).filter(command => command === "plugin:window|close").length;
const beforeEscape = await closes();
assert.equal(beforeEscape, 1);
await page.getByRole("textbox", { name: "Search settings" }).focus();
await page.keyboard.press("Escape");
assert.equal((await calls()).filter(command => command === "plugin:window|close").length, beforeEscape + 1);
assert.equal(await closes(), beforeEscape + 1);
await page.mouse.move(400, 180);
for (const theme of ["dark", "light"]) {
await page.evaluate(value => document.documentElement.setAttribute("data-theme", value), theme);
@@ -70,27 +57,29 @@ try {
await page.setViewportSize(size);
assert(await dialog.evaluate(element => element.scrollWidth === element.clientWidth));
for (const label of ["Minimize window", "Restore window", "Close window"]) {
const button = dialog.getByRole("button", { name: label, exact: true });
const bounds = await button.boundingBox();
const control = dialog.getByRole("button", { name: label, exact: true });
const bounds = await control.boundingBox();
assert(bounds.x >= 0 && bounds.x + bounds.width <= size.width && bounds.height >= 28);
assert.notEqual(await button.evaluate(element => getComputedStyle(element).borderTopLeftRadius), "0px");
assert.notEqual(await control.evaluate(element => getComputedStyle(element).borderTopLeftRadius), "0px");
}
await page.screenshot({ path: `.audit/settings-window-${theme}-${size.width}.png` });
await page.screenshot({ path: path.join(output, `${theme}-${size.width}.png`) });
}
}
await page.evaluate(() => { window.__TEST__.fail = "plugin:window|minimize"; });
await page.getByRole("button", { name: "Minimize window", exact: true }).click();
await page.evaluate(() => { window.__TEST__.state.failMinimize = true; });
await button("Minimize window").click();
await dialog.getByRole("alert").filter({ hasText: "Window action failed" }).waitFor();
await page.evaluate(() => { window.__TEST__.fail = ""; });
await page.getByRole("button", { name: "Minimize window", exact: true }).focus();
await page.evaluate(() => { window.__TEST__.state.failMinimize = false; });
await button("Minimize window").focus();
await page.keyboard.press("Shift+Tab");
assert.equal(await page.evaluate(() => document.activeElement?.textContent), "Restore defaults");
await page.keyboard.press("Tab");
assert.equal(await page.evaluate(() => document.activeElement?.getAttribute("aria-label")), "Minimize window");
const web = await browser.newPage();
await web.goto(`${url}/?settingsWindow=true`);
// Without the Tauri mock, the page is a plain browser preview.
const web = await openPage(browser);
await web.goto(`${smokeUrl}/?settingsWindow=true`);
await web.getByRole("button", { name: "Close settings", exact: true }).waitFor();
assert.equal(await web.getByRole("group", { name: "Window controls" }).count(), 0);
assert.deepEqual(errors, []);
assert.deepEqual(page.errors, []);
console.log("Settings window smoke passed: scoped permissions, drag regions, minimize, maximize, restore, resize, close, Escape, keyboard focus, tooltips, errors, both themes, narrow layout, and browser fallback.");
} finally { await browser.close(); }
});
+41 -54
View File
@@ -1,21 +1,20 @@
// Run against pnpm dev. Native IPC is mocked; this does not test the operating system title bar.
import { createRequire } from "node:module";
// Settings window: browser preview fallback, standalone layout, two-way save sync, failed saves, native open requests, and close. The OS title bar is not tested.
import assert from "node:assert/strict";
import { mkdir } from "node:fs/promises";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const origin = process.env.SMOKE_URL || "http://127.0.0.1:1420";
const errors = [];
const context = await browser.newContext({ viewport: { width: 1100, height: 760 } });
const watch = page => page.on("pageerror", error => errors.push(error.message));
try {
const main = await context.newPage(); watch(main);
await main.goto(origin);
import path from "node:path";
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("settings/window", async ({ browser }) => {
const output = await outputDir("settings/window");
const context = await browser.newContext({ viewport: { width: 1100, height: 760 } });
const autosaveSeconds = page => page.evaluate(() => JSON.parse(localStorage.getItem("runestone.settings")).autosaveSeconds);
// The main window and settings run as browser previews, without the Tauri mock.
const main = await openPage(context);
await main.goto(smokeUrl);
await main.getByRole("button", { name: "Settings (Ctrl+,)", exact: true }).click();
assert.equal(await main.locator("dialog:modal").count(), 1, "Browser preview retains the settings dialog");
const settings = await context.newPage(); watch(settings);
await settings.goto(`${origin}/?settingsWindow=true`);
const settings = await openPage(context);
await settings.goto(`${smokeUrl}/?settingsWindow=true`);
await settings.getByRole("heading", { name: "General", exact: true }).waitFor();
assert.equal(await settings.locator(".workbench").count(), 0);
const interval = settings.getByRole("spinbutton", { name: "Auto-save interval" });
@@ -28,65 +27,53 @@ try {
await settings.waitForFunction(() => document.querySelector("#autosave-seconds")?.value === "29");
await interval.fill("301"); await interval.press("Tab");
await settings.getByRole("alert").filter({ hasText: "Choose a whole number" }).waitFor();
assert.equal(await settings.evaluate(() => JSON.parse(localStorage.getItem("runestone.settings")).autosaveSeconds), 29);
assert.equal(await autosaveSeconds(settings), 29);
await settings.evaluate(() => { Storage.prototype.setItem = () => { throw new Error("Storage full"); }; });
await interval.fill("40"); await interval.press("Tab");
await settings.getByRole("alert").filter({ hasText: "Could not save these settings" }).waitFor();
assert.equal(await settings.evaluate(() => JSON.parse(localStorage.getItem("runestone.settings")).autosaveSeconds), 29);
assert.equal(await autosaveSeconds(settings), 29);
await settings.reload();
await settings.getByRole("button", { name: "Plug-ins", exact: true }).click();
await settings.getByRole("heading", { name: "Plug-ins", exact: true }).waitFor();
await settings.getByRole("button", { name: "General", exact: true }).click();
await mkdir(".audit", { recursive: true });
await settings.screenshot({ path: ".audit/settings-window.png" });
await settings.screenshot({ path: path.join(output, "settings-window.png") });
await settings.setViewportSize({ width: 540, height: 420 });
assert.equal(await settings.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true);
await settings.keyboard.press("Escape");
await settings.waitForURL(`${origin}/`);
await settings.waitForURL(`${smokeUrl}/`);
const desktop = await context.newPage(); watch(desktop);
await desktop.addInitScript(() => {
window.isTauri = true;
const callbacks = new Map();
let sequence = 0;
window.settingsTest = { opens: 0, fail: false, closes: 0 };
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 = {}) => {
if (command === "settings_open_window") {
window.settingsTest.opens++;
if (window.settingsTest.fail) throw new Error("Native window creation failed");
await new Promise(resolve => setTimeout(resolve, 150));
return;
}
if (command === "plugins_snapshot") return { root: "C:/plugins", plugins: [] };
if (command === "workspace_last_path") return null;
if (command === "plugin:event|listen") return args.handler;
if (command === "plugin:event|unlisten") return;
if (command === "plugin:window|is_maximized") return false;
if (command === "plugin:window|close") { window.settingsTest.closes++; return; }
throw new Error(`Unexpected IPC: ${command}`);
// A desktop window with the Tauri mock opens settings in a native window.
const desktop = await openPage(context);
await mockTauri(desktop, {
state: { opens: 0, fail: false, closes: 0 },
commands: test => ({
settings_open_window: async () => {
test.state.opens++;
if (test.state.fail) throw new Error("Native window creation failed");
await new Promise(resolve => setTimeout(resolve, 150));
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
workspace_last_path: () => null,
"plugin:window|is_maximized": () => false,
"plugin:window|close": () => { test.state.closes++; },
}),
});
await desktop.goto(origin);
const desktopState = () => desktop.evaluate(() => window.__TEST__.state);
await desktop.goto(smokeUrl);
await desktop.getByRole("button", { name: "Settings (Ctrl+,)", exact: true }).dblclick();
assert.equal(await desktop.evaluate(() => window.settingsTest.opens), 1, "Rapid requests share the pending native open");
assert.equal((await desktopState()).opens, 1, "Rapid requests share the pending native open");
assert.equal(await desktop.locator("dialog:modal").count(), 0, "Native open does not block the workbench");
await desktop.waitForTimeout(180);
await desktop.keyboard.press("Control+,");
await desktop.waitForFunction(() => window.settingsTest.opens === 2);
await desktop.waitForFunction(() => window.__TEST__.state.opens === 2);
await desktop.waitForTimeout(180);
await desktop.evaluate(() => { window.settingsTest.fail = true; });
await desktop.evaluate(() => { window.__TEST__.state.fail = true; });
await desktop.keyboard.press("Control+,");
await desktop.getByText(/Could not open settings: .*Native window creation failed/).waitFor();
await desktop.goto(`${origin}/?settingsWindow=true`);
await desktop.goto(`${smokeUrl}/?settingsWindow=true`);
await desktop.getByRole("heading", { name: "General", exact: true }).waitFor();
await desktop.getByRole("button", { name: "Close window", exact: true }).click();
assert.equal(await desktop.evaluate(() => window.settingsTest.closes), 1);
assert.deepEqual(errors, []);
assert.equal((await desktopState()).closes, 1);
assert.deepEqual([main, settings, desktop].flatMap(page => page.errors), []);
console.log("Settings window smoke passed: preview fallback, standalone layout, two-way save sync, persistence, failed saves, native open requests, and close.");
} finally { await browser.close(); }
});