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
+4 -4
View File
@@ -20,11 +20,11 @@ The [development guide](docs/development.md#architecture) maps the source folder
| --- | --- |
| `pnpm install --frozen-lockfile` | Install dependencies |
| `pnpm tauri dev` | Run the desktop app with hot reload |
| `pnpm check` | Type checks |
| `pnpm test` | Unit tests (`scripts/*.spec.ts`) |
| `pnpm check` | Type checks of the app and the unit tests |
| `pnpm test` | Unit tests (`tests/unit/`) |
| `cargo test --manifest-path src-tauri/Cargo.toml --lib` | Rust tests |
| `pnpm check:menus` | Menu surface inventory |
| `node scripts/<name>.smoke.mjs` | One browser smoke test. See [Browser smoke tests](docs/development.md#browser-smoke-tests). |
| `pnpm smoke [filter...]` | Browser smoke tests (`tests/smoke/`). See [Browser smoke tests](docs/development.md#browser-smoke-tests). |
| `pnpm build:installer --version <version>` | Windows installer. See [Builds](docs/builds.md). |
| `pnpm package:plugin <compiled-folder> [output-folder]` | Plugin ZIP |
@@ -107,7 +107,7 @@ Rules from the owner:
- A selection gets one outline around each group of adjacent selected items, with no borders on shared internal edges.
- Colors follow the `ui-functional-color` skill and `docs/ui-color.md`: vivid by default, informative text opaque.
- Before Review, check both themes, narrow windows, long lists, keyboard focus, and viewport edges.
For menu work, run `pnpm check:menus` and `tests/smoke/menus/consistency.smoke.mjs`.
For menu work, run `pnpm check:menus` and `pnpm smoke menus`.
Keep screenshots of the exact control that the card names.
- Record a rule change, a recurring problem, or an exception in `docs/design-decisions.md`. An isolated fix needs no entry.
+6 -9
View File
@@ -31,7 +31,7 @@ Output:
| File | Contents |
| --- | --- |
| `releases/<version>/RuneStone_<version>_x64-setup.exe` | The setup file to distribute |
| `releases/<version>/host.json` | The release version, the encoded toolchain and Windows versions, the path, the size in bytes, and the SHA-256 hash |
| `releases/<version>/host.json` | The release version, the encoded toolchain and Windows versions, the file name, the size in bytes, and the SHA-256 hash |
The script prints `Installer available: <path>` when it completes.
After a successful build, the version fields keep the new version.
@@ -43,9 +43,9 @@ Example, from the 0.1.44 download link in the README: version `0.1.44` gives `re
Source: `scripts/buildInstaller.mjs`.
1. Reads the version and makes sure that all version fields match the current version.
2. Makes sure that downgrade protection stays on in `tauri.conf.json` and `tauri.windows.conf.json`.
2. Makes sure that downgrade protection stays on in `tauri.conf.json` and `tauri.windows.conf.json`, and that the browser runtime is staged.
3. Stops if the setup file or `host.json` exists in the bundle folder or in `releases/<version>/`.
4. Saves copies of the four version files as `*.before` in `output/installer-build/<version>/`.
4. Saves copies of the four version files as `*.before` in `output/installer-build/<version>/<time>/`, a new folder for each attempt.
It also writes the NSIS template and a configuration override to that folder.
5. Writes the new version to `package.json`, `tauri.conf.json`, `Cargo.toml`, and `Cargo.lock`.
6. Runs `tauri build --no-bundle -- --locked`. This runs `pnpm build` and compiles the release app.
@@ -55,12 +55,9 @@ Source: `scripts/buildInstaller.mjs`.
### Failure and rollback
If a step fails, the script restores the four version files.
It moves partial setup files and `host.json` into `output/installer-build/<version>/` with a `.failed-<timestamp>` suffix.
Ctrl+C stops the script before this cleanup. The version files then keep the new version.
Before you run the script again, copy the `*.before` files from `output/installer-build/<version>/` back to their original names.
A new run with the same version replaces those copies.
If a step fails, or you press Ctrl+C, the script restores the four version files.
It moves partial setup files and `host.json` into the folder of that attempt with a `.failed-<timestamp>` suffix.
If the process is killed before this cleanup, copy the `*.before` files of the attempt back to their original names.
## Installer requirements
+43 -25
View File
@@ -91,8 +91,12 @@ A new command needs an entry in `generate_handler!` in `lib.rs`, in the command
| Folder | Content |
| --- | --- |
| `browser-runtime/` | The browser engine, its tests, filter lists, and third-party notices |
| `scripts/` | Unit tests (`*.spec.ts`), browser smoke tests (`*.smoke.mjs`), and build and package tools |
| `fixtures/` | Sample documents, a sample plugin, and a completion test page |
| `tests/unit/<area>/` | Unit tests (`*.spec.ts`) that run in Node |
| `tests/smoke/<area>/` | Browser smoke tests (`*.smoke.mjs`) and their shared harness in `_harness/` |
| `tests/native/` | Tests that attach to a running desktop app |
| `scripts/` | Build, release, package, and audit tools, and the smoke test runner |
| `fixtures/` | A sample workspace (`fixtures/sample/`), a sample plugin, and a completion test page |
| `design/` | Icon drafts |
| `docs/` | User and developer documentation |
### Where data lives
@@ -127,18 +131,19 @@ Run these commands from the repository folder. They do not need an installer.
| Command | Checks |
| --- | --- |
| `pnpm check` | Svelte and TypeScript types |
| `pnpm test` | Unit tests in `scripts/*.spec.ts` |
| `pnpm check` | Svelte and TypeScript types of the app, then of the unit tests (`tests/tsconfig.json`) |
| `pnpm test` | Unit tests in `tests/unit/` |
| `cargo test --manifest-path src-tauri/Cargo.toml --lib` | Rust unit tests |
| `pnpm smoke` | Browser smoke tests. See [Browser smoke tests](#browser-smoke-tests). |
| `pnpm build` | The production frontend build |
| `pnpm check:menus` | The inventory of menu surfaces. See [Interface design](ui-design.md). |
To run one test file, use `node --experimental-strip-types --test tests/unit/tables/selection.spec.ts`.
For type errors while you edit, run `pnpm check:watch`.
Some tests need files from outside this repository:
Some tests need files from outside this repository. Without those files, the tests skip and state the reason:
- `tests/unit/plugins/plugins.spec.ts` and `tests/unit/tables/formulas.spec.ts` import the compiled Table Formulas package. Run `pnpm build:plugins` first. See [Build examples](plugin-development.md#build-examples).
- `tests/unit/plugins/plugins.spec.ts` and `tests/unit/tables/formulas.spec.ts` import the compiled Table Formulas package. To run them, run `pnpm build:plugins` first. See [Build examples](plugin-development.md#build-examples).
- `tests/unit/release/installerVersion.spec.ts` needs the NSIS compiler that the Tauri CLI downloads on Windows.
- The Rust terminal tests start the real shells on the computer.
@@ -147,32 +152,45 @@ Some tests need files from outside this repository:
Smoke tests run the real interface in headless Chromium with a mock of the desktop host.
They do not replace tests in the native app. Real folder access, file writes, and terminals need `pnpm tauri dev`.
1. Make Playwright available. It is not a project dependency.
Set `PLAYWRIGHT_MODULE` to the folder of an installed `playwright` package.
If that package has no Chromium, set `CHROME_PATH` to an installed browser.
2. Start the frontend with `pnpm dev`, or use the server of a running `pnpm tauri dev` session.
3. In a second terminal, run one script, for example `node tests/smoke/layout/workbench.smoke.mjs`.
| Command | Runs |
| --- | --- |
| `pnpm smoke` | All smoke tests, four at a time |
| `pnpm smoke tabs tables/drag` | The tests whose path contains one of the filters |
| `pnpm smoke --list` | Nothing. It lists each test, its requirements, and why a test would skip. |
Example for PowerShell. Replace the paths with your own:
The runner starts the Vite server when nothing serves `SMOKE_URL`, and stops it at the end.
Use `--no-serve` to require a running server, `--jobs <n>` to change the number of parallel tests, and `--timeout <seconds>` to change the limit for each test (default 180).
After the parallel run, the runner runs each failed test one more time, alone. A test that passes then is reported as `flaky`. It does not fail the run, but the summary lists it. Use `--retries 0` to turn this off.
Each test writes its output to `output/smoke/logs/<area>__<name>.log`. Screenshots go to `output/smoke/<area>/<name>/`.
```powershell
$env:PLAYWRIGHT_MODULE = "C:\tools\browser-tests\node_modules\playwright"
$env:CHROME_PATH = "C:\Program Files\Google\Chrome\Application\chrome.exe"
node tests/smoke/layout/workbench.smoke.mjs
```
Playwright is a development dependency. When its own Chromium is not installed, the runner uses an installed Chrome or Edge.
To use the Playwright browser, run `pnpm exec playwright install chromium`.
A test states what it needs near its top. The runner skips the test, with the reason, when a requirement is missing:
| Line | Requirement |
| --- | --- |
| `// @requires plugin:table-formulas` | `plugin-packages/table-formulas/`. Run `pnpm build:plugins`. |
| `// @requires plugin:terminal` | The compiled Terminal plugin |
| `// @requires repo:RuneStone_Git/dist` | A file or folder in a sibling plugin checkout |
| `// @requires electron` | The browser engine dependencies. Run `npm ci --prefix browser-runtime`. |
| `// @known-issue <defect>` | The test fails because of a known app defect. The run reports it as `known`. If the test passes, the run fails, so that someone removes the line. |
| Variable | Use |
| --- | --- |
| `SMOKE_URL` | The frontend address. The default is `http://127.0.0.1:1420`. |
| `RUNESTONE_TERMINAL_DIST` | The compiled Terminal plugin. The default is `../RuneStone_Terminal/dist`. |
| `RUNESTONE_TABLE_FORMULAS_ROOT`, `RUNESTONE_GIT_ROOT` | Sibling plugin checkouts in other folders |
| `RUNESTONE_PLUGIN_REPOS` | The folder of the sibling plugin checkouts. The default is the parent folder of this repository. |
| `RUNESTONE_TERMINAL_DIST` | The compiled Terminal plugin. The default is `RuneStone_Terminal/dist` in that folder. |
| `CHROME_PATH` | A Chromium browser for Playwright |
| `PLAYWRIGHT_MODULE` | A different Playwright package |
Smoke tests for plugins load compiled packages through the real module loader. Build those plugins first.
`browserInteraction.smoke.mjs` and `browserFields.smoke.mjs` also start the browser engine from `browser-runtime`.
To write a smoke test, start from an existing test in the same area. The harness in `tests/smoke/_harness/index.mjs` starts the browser, mocks the Tauri commands, and gives an in-memory workspace.
A failed test saves `failure.png` in its output folder and prints the page console errors and warnings.
You can also run one test file directly while `pnpm dev` runs, for example `node tests/smoke/tabs/order.smoke.mjs`.
A few scripts attach to a running desktop app instead, through the WebView2 remote-debugging port.
Examples: `spellingNative.smoke.mjs`, `kanbanNative.smoke.mjs`, and `browserNativeAcceptance.mjs`.
Before you start the app, set `WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=<port>`. Each script states its port and variables at the top.
The tests in `tests/native/` attach to a running desktop app through the WebView2 remote-debugging port, and `pnpm smoke` does not run them.
Set `NATIVE_CDP_URL` to the debugging address, for example `http://127.0.0.1:9224`.
Before you start the app, set `WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=<port>`. Each file states its port and variables at the top.
## Built-in browser runtime
@@ -195,5 +213,5 @@ Each browser window gets a session token at startup. Native requests check that
| The window shows the old interface | Look for compile errors in the terminal. Restart `pnpm tauri dev` if necessary. |
| A page says that desktop features need `pnpm tauri dev` | You opened the Vite server in a browser. Use the native window. |
| Windows cannot find `link.exe` | Install the C++ build tools and the Windows SDK from the Tauri prerequisites. Open a new terminal. |
| A smoke test cannot find Playwright or Chromium | Set `PLAYWRIGHT_MODULE`. Install its Chromium, or set `CHROME_PATH`. |
| A smoke test cannot find Chromium | Run `pnpm exec playwright install chromium`, or set `CHROME_PATH` to an installed browser. |
| `cargo test --offline` reports missing crates | Run the command without `--offline` one time while you are online. |
+33 -14
View File
@@ -1,11 +1,16 @@
// 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]
// pnpm smoke [filter...] [--list] [--jobs N] [--timeout seconds] [--retries N] [--no-serve]
//
// A filter selects the tests whose path contains it, for example `tabs` or `tables/drag`.
// After the parallel run, the runner runs each failed test again, one at a time (--retries, default 1).
// A test that passes on a retry counts as "flaky". The summary lists it, but the run does not fail.
// 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.
// A test that fails because of a known app defect states it near the top:
// // @known-issue <the defect>
// It still runs. A failure counts as "known". A pass counts as a failure, so remove the stale line.
import { spawn } from "node:child_process";
import { createWriteStream, existsSync } from "node:fs";
import { mkdir, readdir, readFile } from "node:fs/promises";
@@ -33,6 +38,7 @@ 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 retries = Math.max(0, Number(option("--retries", "1")));
const filters = args;
const env = { ...process.env, SMOKE_URL: process.env.SMOKE_URL || "http://127.0.0.1:1420" };
@@ -48,9 +54,12 @@ async function findTests(dir) {
return result.sort();
}
async function requirements(file) {
async function header(file) {
const head = (await readFile(file, "utf8")).split("\n").slice(0, 10).join("\n");
return head.match(/@requires\s+([^\n]+)/)?.[1].trim().split(/\s+/) ?? [];
return {
needs: head.match(/@requires\s+([^\r\n]+)/)?.[1].trim().split(/\s+/) ?? [],
knownIssue: head.match(/@known-issue\s+([^\r\n]+)/)?.[1].trim(),
};
}
function missing(requirement) {
@@ -115,9 +124,9 @@ async function startServer() {
throw new Error(`The dev server did not start at ${env.SMOKE_URL}.`);
}
function run(file) {
function run(file, knownIssue, logSuffix = "") {
const name = path.relative(smokeRoot, file).replace(/\\/g, "/").replace(/\.smoke\.mjs$/, "");
const log = path.join(logRoot, name.replaceAll("/", "__") + ".log");
const log = path.join(logRoot, name.replaceAll("/", "__") + logSuffix + ".log");
const started = Date.now();
return new Promise(resolve => {
const out = createWriteStream(log);
@@ -129,8 +138,9 @@ function run(file) {
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 });
let status = code === 0 ? "pass" : Date.now() - started >= timeoutMs ? "timeout" : "fail";
if (knownIssue) status = status === "pass" ? "unexpected-pass" : "known";
resolve({ name, status, detail: status === "known" ? knownIssue : `${seconds}s`, log });
});
});
}
@@ -146,9 +156,9 @@ if (!tests.length) {
const plan = [];
for (const file of tests) {
const needs = await requirements(file);
const { needs, knownIssue } = await header(file);
const reasons = needs.map(missing).filter(Boolean);
plan.push({ file, needs, reasons });
plan.push({ file, needs, reasons, knownIssue });
}
if (list) {
@@ -178,14 +188,21 @@ for (const item of plan.filter(item => item.reasons.length)) {
}
async function worker() {
while (queue.length) {
const { file } = queue.shift();
const result = await run(file);
const { file, knownIssue } = queue.shift();
const result = { ...await run(file, knownIssue), 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));
for (let attempt = 1; attempt <= retries; attempt++) {
for (const result of results.filter(item => ["fail", "timeout"].includes(item.status))) {
const retry = await run(result.file, undefined, `.retry${attempt}`);
console.log(`retry ${retry.name}: ${retry.status} (${retry.detail})`);
if (retry.status === "pass") result.status = "flaky";
}
}
} finally {
server?.kill();
}
@@ -193,7 +210,9 @@ try {
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)}`);
const detail = ["skip", "known"].includes(result.status) ? result.detail : path.relative(root, result.log);
console.log(`${result.status.padEnd(7)} ${result.name}: ${detail}`);
}
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;
const failed = count("fail") + count("timeout") + count("unexpected-pass");
console.log(`\n${count("pass")} passed, ${count("flaky")} flaky, ${failed} failed, ${count("known")} known issues, ${count("skip")} skipped. Logs: ${path.relative(root, logRoot)}`);
process.exitCode = failed ? 1 : 0;
+12 -6
View File
@@ -1,10 +1,16 @@
import { createRequire } from 'node:module';
// Native built-in browser: page rendering at device pixel ratio, the page context menu, editing commands, and session checks.
// Start a debug app with an isolated identifier (com.runestone.browser-test or com.runestone.spelling-test) and remote debugging on port 9224:
// set WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=9224
// pnpm tauri dev --config "{\"identifier\":\"com.runestone.browser-test\"}"
// The browser runtime needs `npm ci --prefix browser-runtime`. The test loads https://example.com/.
// Run `node tests/native/browser.native.mjs`. NATIVE_CDP_URL (or the older BROWSER_NATIVE_CDP) overrides http://127.0.0.1:9224.
import path from 'node:path';
import assert from 'node:assert/strict';
import { writeFile } from 'node:fs/promises';
const require = createRequire(path.resolve('browser-runtime/package.json'));
const { chromium } = require('playwright');
const browser = await chromium.connectOverCDP(process.env.BROWSER_NATIVE_CDP || 'http://127.0.0.1:9224');
import { outputDir, playwright } from '../smoke/_harness/index.mjs';
const { chromium } = playwright();
const browser = await chromium.connectOverCDP(process.env.NATIVE_CDP_URL || process.env.BROWSER_NATIVE_CDP || 'http://127.0.0.1:9224');
const output = await outputDir('native/browser');
const page = browser.contexts()[0].pages()[0];
const raw = (command, args = {}) => page.evaluate(({ command, args }) => window.__TAURI_INTERNALS__.invoke(command, args), { command, args });
const profile = await raw('plugins_snapshot');
@@ -46,8 +52,8 @@ try {
await address.fill('https://example.com/');
await assert.rejects(raw('browser_request', { command: 'edit', args: { tabId, action: 'copy' }, session: 'invalid-session' }), /session/i);
await assert.rejects(request('contextAction', { tabId, token: 'stale-menu', action: 'saveImage' }), /no longer available/);
await page.screenshot({ path: 'output/browser-native-acceptance.png' });
await writeFile('output/browser-native-acceptance.json', JSON.stringify({ dimensions, passed: [
await page.screenshot({ path: path.join(output, 'acceptance.png') });
await writeFile(path.join(output, 'acceptance.json'), JSON.stringify({ dimensions, passed: [
'Native Tauri-to-Electron page rendering and high-DPI frame delivery', 'Native page context event opens the shared host menu',
'Native editing commands copy real webpage text', 'Session and stale-menu checks reject invalid requests',
] }, null, 2));
+15 -9
View File
@@ -1,9 +1,14 @@
// Use only an isolated com.runestone.spelling-test debug window.
import { createRequire } from 'node:module';
import { mkdir, writeFile } from 'node:fs/promises';
// Native editing menus in inputs, textareas, and dialogs: unsupported WebView2 commands stay hidden, Undo and spelling work, and focus returns, in both themes.
// Start a debug app with the isolated identifier com.runestone.spelling-test and remote debugging on port 9237:
// set WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=9237
// pnpm tauri dev --config "{\"identifier\":\"com.runestone.spelling-test\"}"
// Run `node tests/native/menuScope.native.mjs`. NATIVE_CDP_URL (or the older SPELLING_CDP_URL) overrides http://127.0.0.1:9237.
import { writeFile } from 'node:fs/promises';
import path from 'node:path';
import assert from 'node:assert/strict';
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || 'playwright');
const browser = await chromium.connectOverCDP(process.env.SPELLING_CDP_URL || 'http://127.0.0.1:9237');
import { outputDir, playwright } from '../smoke/_harness/index.mjs';
const { chromium } = playwright();
const browser = await chromium.connectOverCDP(process.env.NATIVE_CDP_URL || process.env.SPELLING_CDP_URL || 'http://127.0.0.1:9237');
const page = browser.contexts()[0].pages()[0];
page.setDefaultTimeout(15000);
const captures = [];
@@ -18,7 +23,8 @@ try {
await listen('spelling-menu', ({ payload }) => window.nativeMenuPayload = payload);
await (await import('/node_modules/@tauri-apps/api/core.js')).invoke('spelling_menu_install');
});
await mkdir('output/todo-menus', { recursive: true });
const output = await outputDir('native/menuScope');
const capturesFile = path.join(output, 'native-filtered-items.json');
const menu = page.getByRole('menu', { name: 'Spelling actions', exact: true });
for (const mode of ['dark', 'light']) {
await page.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); }, mode);
@@ -39,7 +45,7 @@ try {
await menu.waitFor();
const payload = await page.evaluate(() => window.nativeMenuPayload);
captures.push({ mode, kind, value: await field.inputValue(), payload });
await writeFile('output/todo-menus/native-filtered-items.json', JSON.stringify(captures, null, 2));
await writeFile(capturesFile, JSON.stringify(captures, null, 2));
const flatten = items => items.flatMap(item => [item, ...flatten(item.children)]);
const entries = flatten(payload.items);
assert.ok(entries.every(item => item.kind === 3 || !['share', 'writingDirection', 'voiceTyping', 'other'].includes(item.name)));
@@ -48,7 +54,7 @@ try {
assert.ok(entries.some(item => item.name === 'copy'));
assert.equal(await menu.getByRole('menuitem', { name: /More tools|Writing direction|Voice typing|Share/ }).count(), 0);
assert.equal(await menu.evaluate(node => getComputedStyle(node).borderColor), 'rgba(0, 0, 0, 0)');
if (kind === 'textarea') await page.screenshot({ path: `output/todo-menus/native-${mode}.png` });
if (kind === 'textarea') await page.screenshot({ path: path.join(output, `native-${mode}.png`) });
await menu.getByRole('menuitem', { name: 'Undo Ctrl+Z', exact: true }).click();
await page.waitForFunction(() => document.getElementById('native-menu-field').value === 'I recieved a letter.').catch(async error => { console.error('Undo result', await field.inputValue()); throw error; });
await field.click({ button: 'right', position: { x: 48, y: kind === 'input' ? 50 : 22 } });
@@ -62,7 +68,7 @@ try {
assert.equal(await field.evaluate(node => document.activeElement === node), true);
}
}
await writeFile('output/todo-menus/native-filtered-items.json', JSON.stringify(captures, null, 2));
await writeFile(capturesFile, JSON.stringify(captures, null, 2));
console.log('PASS: real WebView2 menus omit unsupported commands, retain editing and spelling, execute native Undo, correct spelling with undo, and restore focus in fields and dialogs in both themes.');
} finally {
await page.evaluate(() => { document.getElementById('native-menu-field')?.remove(); document.getElementById('native-menu-dialog')?.remove(); }).catch(() => {});
+15 -12
View File
@@ -1,15 +1,18 @@
// Use a debug app with TAURI_CONFIG identifier com.runestone.spelling-test,
// a hidden window, and a separate WEBVIEW2_USER_DATA_FOLDER outside Vite's watch paths.
// Set WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=9224 before launch.
// Native spelling menu in Writer, inputs, textareas, and dialogs: WebView2 Undo, spelling corrections, and editor undo.
// Start a debug app with the isolated identifier com.runestone.spelling-test, a hidden window, a separate
// WEBVIEW2_USER_DATA_FOLDER outside Vite's watch paths, and remote debugging on port 9224:
// set WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=9224
// pnpm tauri dev --config "{\"identifier\":\"com.runestone.spelling-test\"}"
// Run `node tests/native/spelling.native.mjs`. NATIVE_CDP_URL (or the older SPELLING_CDP_URL) overrides http://127.0.0.1:9224.
// SPELLING_APP_URL overrides http://localhost:1420. SPELLING_WORKSPACE overrides the workspace folder in output/smoke/native/spelling/.
// The normal app identifier is rejected before this test writes any workspace files.
import { createRequire } from "node:module";
import { mkdir, writeFile } from "node:fs/promises";
import { resolve } from "node:path";
import path from "node:path";
import assert from "node:assert/strict";
import { outputDir, playwright } from "../smoke/_harness/index.mjs";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.connectOverCDP(process.env.SPELLING_CDP_URL || "http://127.0.0.1:9224");
const { chromium } = playwright();
const browser = await chromium.connectOverCDP(process.env.NATIVE_CDP_URL || process.env.SPELLING_CDP_URL || "http://127.0.0.1:9224");
const page = browser.contexts()[0].pages()[0];
page.setDefaultTimeout(15000);
try {
@@ -19,9 +22,10 @@ try {
return appDataDir();
});
assert.match(data, /[\\/]com\.runestone\.spelling-test[\\/]?$/, "Use the isolated spelling-test app identifier");
const workspace = resolve(process.env.SPELLING_WORKSPACE || ".audit/spelling-workspace");
const output = await outputDir("native/spelling");
const workspace = path.resolve(process.env.SPELLING_WORKSPACE || path.join(output, "workspace"));
await mkdir(workspace, { recursive: true });
await writeFile(resolve(workspace, "Spelling.md"), "# Spelling\n\nI recieved a letter.\n");
await writeFile(path.join(workspace, "Spelling.md"), "# Spelling\n\nI recieved a letter.\n");
await page.evaluate(async path => {
const { invoke } = await import("/node_modules/@tauri-apps/api/core.js");
await invoke("workspace_open", { path });
@@ -41,8 +45,7 @@ try {
await page.mouse.click(rect.x + 42, rect.y + rect.height / 2, { button: "right" });
const menu = page.getByRole("menu", { name: "Spelling actions", exact: true });
await menu.waitFor();
await mkdir(".audit", { recursive: true });
await page.screenshot({ path: ".audit/spelling-native.png" });
await page.screenshot({ path: path.join(output, "spelling-menu.png") });
const undo = menu.getByRole("menuitem", { name: "Undo Ctrl+Z", exact: true });
assert.equal(await undo.isEnabled(), true, "The native Undo command is enabled after typing");
await undo.click();
@@ -1,7 +1,12 @@
import {createRequire} from 'node:module';
// Native windows: an empty-tab transfer opens a window that acknowledges the saved tab, and the settings window's theme export rejects invalid JSON.
// Start a debug app with the isolated identifier com.runestone.spelling-test, a workspace open, and remote debugging on port 9224:
// set WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=9224
// pnpm tauri dev --config "{\"identifier\":\"com.runestone.spelling-test\"}"
// Run `node tests/native/tabTransferAndThemeExport.native.mjs`. NATIVE_CDP_URL (or the older SPELLING_CDP_URL) overrides http://127.0.0.1:9224.
import assert from 'node:assert/strict';
const {chromium}=createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || 'playwright');
const browser=await chromium.connectOverCDP(process.env.SPELLING_CDP_URL || 'http://127.0.0.1:9224');
import { playwright } from '../smoke/_harness/index.mjs';
const {chromium}=playwright();
const browser=await chromium.connectOverCDP(process.env.NATIVE_CDP_URL || process.env.SPELLING_CDP_URL || 'http://127.0.0.1:9224');
const context=browser.contexts()[0];
const page=context.pages().find(page => new URL(page.url()).pathname === '/' && !new URL(page.url()).search);
assert.ok(page, 'The isolated main window must be open.');
+19 -10
View File
@@ -1,16 +1,25 @@
import { createRequire } from 'node:module';
// Native tree and windows: rename undo keeps folders expanded, Open in new window moves a tab without changing the saved layout,
// 50 MiB of JSON passes through workspace IPC, and a large background image survives a reload.
// Start a debug app with the isolated identifier com.runestone.pass3-test and remote debugging on port 9236:
// set WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=9236
// pnpm tauri dev --config "{\"identifier\":\"com.runestone.pass3-test\"}"
// Run `node tests/native/treeRename.native.mjs`. NATIVE_CDP_URL (or the older NAVIGATION_NATIVE_CDP) overrides http://127.0.0.1:9236.
// The test opens a workspace in the system temporary folder.
import assert from 'node:assert/strict';
import { mkdir, writeFile } from 'node:fs/promises';
import { resolve, join } from 'node:path';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { outputDir, playwright } from '../smoke/_harness/index.mjs';
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || 'playwright');
const browser = await chromium.connectOverCDP(process.env.NAVIGATION_NATIVE_CDP || 'http://127.0.0.1:9236');
const { chromium } = playwright();
const browser = await chromium.connectOverCDP(process.env.NATIVE_CDP_URL || process.env.NAVIGATION_NATIVE_CDP || 'http://127.0.0.1:9236');
const context = browser.contexts()[0];
const page = context.pages().find(page => new URL(page.url()).pathname === '/' && !new URL(page.url()).search);
assert.ok(page, 'The isolated main window must be open.');
page.setDefaultTimeout(20000);
const output = resolve('output/host-navigation-pass3-native');
const output = await outputDir('native/treeRename');
// Settings and reload pages use the app's own dev server, not a fixed port.
const origin = new URL(page.url()).origin;
const workspace = join(tmpdir(), 'runestone-pass3-native-workspace');
const results = {};
let detached;
@@ -18,7 +27,6 @@ try {
const identity = await page.evaluate(async () => (await import('/node_modules/@tauri-apps/api/path.js')).appDataDir());
assert.match(identity, /[\\/]com\.runestone\.pass3-test[\\/]?$/);
results.identity = identity;
await mkdir(output, { recursive: true });
await mkdir(join(workspace, 'folder', 'nested'), { recursive: true });
await mkdir(join(workspace, 'other'), { recursive: true });
await writeFile(join(workspace, 'folder', 'nested', 'note.md'), '# Native note\n\nText for transfer.\n');
@@ -75,17 +83,18 @@ try {
return { bytes, jsonLength: contents.length, matches: read === contents, writeMs: Math.round(written - start), readMs: Math.round(performance.now() - written) };
});
assert.equal(results.imageJsonIpc.matches, true);
await page.goto('http://127.0.0.1:5186/?settingsWindow=true');
await page.goto(`${origin}/?settingsWindow=true`);
await page.getByRole('button', { name: 'Appearance', exact: true }).click();
const pixel = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=', 'base64');
const largeImage = Buffer.concat([pixel, Buffer.alloc(1_900_000 - pixel.length)]);
await page.getByLabel('Background image file', { exact: true }).setInputFiles({ name: 'native-large.png', mimeType: 'image/png', buffer: largeImage });
await page.waitForFunction(() => !!JSON.parse(localStorage.getItem('runestone.appearance'))?.newTabBackground?.imageId);
await page.goto('http://127.0.0.1:5186/');
await page.goto(`${origin}/`);
// The image is on the work area layer behind the empty tab (src/lib/layout/Workbench.svelte:1258, :1543-1549).
await page.locator('.empty').waitFor();
await page.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('blob:'));
await page.waitForFunction(() => getComputedStyle(document.querySelector('.workarea-background')).backgroundImage.includes('blob:'));
await page.reload(); await page.locator('.empty').waitFor();
await page.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('blob:'));
await page.waitForFunction(() => getComputedStyle(document.querySelector('.workarea-background')).backgroundImage.includes('blob:'));
results.largeBackground = { bytes: largeImage.length, renderedAfterReload: true };
await page.screenshot({ path: join(output, 'large-background.png') });
await writeFile(join(output, 'results.json'), JSON.stringify(results, null, 2));
+20 -4
View File
@@ -24,12 +24,21 @@ export function launchBrowser(options = {}) {
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 });
/**
* Open a page that collects uncaught page errors in `page.errors`, and console errors and warnings in `page.console`.
* `target` is a browser or a browser context. A context page keeps the context viewport unless `viewport` is given.
*/
export async function openPage(target, { viewport, timeout = 10000, ...options } = {}) {
const isContext = typeof target.browser === "function";
const page = isContext ? await target.newPage() : await target.newPage({ viewport: viewport ?? { width: 1440, height: 1000 }, ...options });
if (isContext && viewport) await page.setViewportSize(viewport);
page.setDefaultTimeout(timeout);
page.errors = [];
page.console = [];
page.on("pageerror", error => page.errors.push(error.message));
page.on("console", message => {
if (["error", "warning"].includes(message.type())) page.console.push(`${message.type()}: ${message.text()}`);
});
return page;
}
@@ -170,17 +179,24 @@ function installMock(options, commands) {
/**
* 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.
* On failure, the test saves `failure.png` in its output folder and prints the console errors and warnings.
*/
export async function runSmoke(name, body, { viewport, timeout, allowPageErrors = false } = {}) {
const browser = await launchBrowser();
let page;
try {
const page = await openPage(browser, { viewport, timeout });
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);
if (page) {
if (page.console.length) console.error(`Console:\n${page.console.join("\n")}`);
const file = path.join(await outputDir(name), "failure.png");
if (await page.screenshot({ path: file }).then(() => true, () => false)) console.error(`Screenshot: ${file}`);
}
process.exitCode = 1;
} finally {
await browser.close();
@@ -1,38 +1,28 @@
// Workarea backgrounds in both themes: splash, writer, reader, split, IDE, narrow layouts, fades, reduced motion, and removal.
import assert from 'node:assert/strict';
import { mkdir, writeFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || 'playwright');
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const output = '.audit/background-frames';
const report = [];
await mkdir(output, { recursive: true });
try {
import { writeFile } from 'node:fs/promises';
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
const viewport = { width: 1280, height: 820 };
await runSmoke('appearance/backgroundFrames', async ({ browser }) => {
const output = await outputDir('appearance/backgroundFrames');
const report = [];
for (const theme of ['light', 'dark']) {
const page = await browser.newPage({ viewport: { width: 1280, height: 820 } });
const errors = [];
page.on('pageerror', error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = 'C:/background-test';
const files = new Map([
['welcome.md', '# Working notes\n\nKeep the image quiet behind readable text.\n\n## Next steps\n\n- Write a note\n- Review the code\n\n' + 'A paragraph with **bold text** and a [link](https://example.com).\n\n'.repeat(24)],
['hello.ts', '// A focused code view\nexport function greet(name: string) {\n const message = `Hello ${name}`;\n return message;\n}\n'],
]);
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } }, transformCallback: () => 1, unregisterCallback() {},
invoke: async (command, args = {}) => {
if (command === 'workspace_last_path') return root;
if (command === 'workspace_open') return { root, name: 'background-test', watch_mode: 'native' };
if (command === 'workspace_list') return [...files.keys()].map(name => ({ name, rel_path: name, kind: 'file' }));
if (command === 'workspace_read') { if (!files.has(args.rel)) throw new Error('missing'); return files.get(args.rel); }
if (command === 'workspace_search') return [];
if (command === 'plugins_snapshot') return { root, plugins: [] };
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener() {} };
const page = await openPage(browser, { viewport });
await mockTauri(page, {
commands: test => ({
...test.workspace({
root: 'C:/background-test',
files: {
'welcome.md': '# Working notes\n\nKeep the image quiet behind readable text.\n\n## Next steps\n\n- Write a note\n- Review the code\n\n' + 'A paragraph with **bold text** and a [link](https://example.com).\n\n'.repeat(24),
'hello.ts': '// A focused code view\nexport function greet(name: string) {\n const message = `Hello ${name}`;\n return message;\n}\n',
},
}),
plugins_snapshot: () => ({ root: 'C:/background-test', plugins: [] }),
}),
});
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await page.goto(smokeUrl);
await page.locator('.welcome-actions button').first().waitFor();
await page.getByText('background-test', { exact: true }).waitFor();
await page.evaluate(async theme => {
@@ -52,47 +42,55 @@ try {
window.backgroundTest = { hub: backgroundHub, owner: Symbol(), urls, saved, theme };
}, theme);
const background = page.locator('.workarea-background');
const style = (locator, property, pseudo) => locator.evaluate((node, [property, pseudo]) => getComputedStyle(node, pseudo)[property], [property, pseudo]);
async function openWelcome() {
await page.keyboard.press('Control+p');
await page.getByRole('textbox', { name: 'Find a file' }).fill('welcome');
await page.getByRole('dialog').getByRole('button').filter({ hasText: 'welcome.md' }).first().click();
}
assert.equal(await background.count(), 1);
assert.equal(await page.locator('.empty h1, .empty > p').count(), 0);
assert.equal(await page.locator('.empty').evaluate(node => getComputedStyle(node).backgroundImage), 'none');
assert.equal(await style(page.locator('.empty'), 'backgroundImage'), 'none');
const bounds = await background.boundingBox();
assert.equal(bounds.x, 0); assert.equal(bounds.y, 36); assert.equal(bounds.width, 1280); assert.equal(bounds.height, 762);
assert.match(await background.evaluate(node => getComputedStyle(node).backgroundImage), /blob:/);
assert.match(await page.locator('.left').evaluate(node => getComputedStyle(node).backgroundColor), /(?:0\.82|82%)/);
assert.match(await page.locator('.right').evaluate(node => getComputedStyle(node).backgroundColor), /(?:0\.82|82%)/);
assert.match(await page.locator('.welcome-actions button').first().evaluate(node => getComputedStyle(node).backgroundColor), /(?:0\.82|82%)/);
assert.doesNotMatch(await page.locator('header.header').evaluate(node => getComputedStyle(node).backgroundColor), /(?:0\.82|82%)/);
assert.match(await style(background, 'backgroundImage'), /blob:/);
assert.match(await style(page.locator('.left'), 'backgroundColor'), /(?:0\.82|82%)/);
assert.match(await style(page.locator('.right'), 'backgroundColor'), /(?:0\.82|82%)/);
assert.match(await style(page.locator('.welcome-actions button').first(), 'backgroundColor'), /(?:0\.82|82%)/);
assert.doesNotMatch(await style(page.locator('header.header'), 'backgroundColor'), /(?:0\.82|82%)/);
await page.locator('.welcome-actions button').first().focus();
await page.keyboard.press('Tab');
assert(await page.locator('.welcome-actions').evaluate(node => node.contains(document.activeElement)));
await page.screenshot({ path: `${output}/${theme}-splash.png` });
await page.evaluate(() => {
const { hub, owner, urls } = window.backgroundTest;
hub.set(owner, 'app', { url: urls[0], blurredUrl: urls[1], overlay: 0.15, position: 'top', size: 'contain' });
});
assert.equal(await background.evaluate(node => getComputedStyle(node).backgroundSize), '100% 100%, contain, cover');
assert.equal(await background.evaluate(node => getComputedStyle(node).backgroundPosition), '50% 50%, 50% 0%, 50% 50%');
assert.equal(await style(background, 'backgroundSize'), '100% 100%, contain, cover');
assert.equal(await style(background, 'backgroundPosition'), '50% 50%, 50% 0%, 50% 50%');
await page.screenshot({ path: `${output}/${theme}-portrait-layers.png` });
await page.setViewportSize({ width: 390, height: 700 });
assert.equal(await background.evaluate(node => getComputedStyle(node).backgroundSize), '100% 100%, contain, cover');
assert.equal(await style(background, 'backgroundSize'), '100% 100%, contain, cover');
await page.screenshot({ path: `${output}/${theme}-portrait-layers-narrow.png` });
await page.setViewportSize({ width: 1280, height: 820 });
await page.setViewportSize(viewport);
await page.evaluate(() => {
const { hub, owner, urls } = window.backgroundTest;
hub.set(owner, 'app', { url: urls[1], overlay: 0.2, position: 'center', size: 'cover', previous: { url: urls[0], overlay: 0.15, position: 'center', size: 'cover' }, transitionMs: 2000 });
});
await page.waitForTimeout(180);
const opacity = await background.evaluate(node => Number(getComputedStyle(node, '::after').opacity));
const opacity = Number(await style(background, 'opacity', '::after'));
assert(opacity > 0 && opacity < 1, `Fade has an intermediate opacity: ${opacity}`);
await page.waitForTimeout(900);
assert.ok(await background.evaluate(node => Number(getComputedStyle(node, '::after').opacity) < 1), 'The fade remains active after one second');
assert.ok(Number(await style(background, 'opacity', '::after')) < 1, 'The fade remains active after one second');
await page.waitForTimeout(1100);
assert.equal(await background.evaluate(node => getComputedStyle(node, '::after').opacity), '1');
await page.keyboard.press('Control+p');
await page.getByRole('textbox', { name: 'Find a file' }).fill('welcome');
await page.getByRole('dialog').getByRole('button').filter({ hasText: 'welcome.md' }).first().click();
assert.equal(await style(background, 'opacity', '::after'), '1');
await openWelcome();
await page.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
assert.match(await page.locator('.editor > .body').evaluate(node => getComputedStyle(node).backgroundColor), /(?:0\.9|90%)/);
assert.match(await style(page.locator('.editor > .body'), 'backgroundColor'), /(?:0\.9|90%)/);
await page.screenshot({ path: `${output}/${theme}-writer.png` });
await page.getByRole('group', { name: 'Document view', exact: true }).hover();
await page.getByRole('button', { name: 'Read', exact: true }).click();
@@ -103,7 +101,7 @@ try {
await page.screenshot({ path: `${output}/${theme}-reader.png` });
await page.getByRole('button', { name: 'Split', exact: true }).click();
await page.locator('.monaco-editor').waitFor();
assert.equal(await page.locator('.monaco-editor-background').first().evaluate(node => getComputedStyle(node).backgroundColor), 'rgba(0, 0, 0, 0)');
assert.equal(await style(page.locator('.monaco-editor-background').first(), 'backgroundColor'), 'rgba(0, 0, 0, 0)');
await page.screenshot({ path: `${output}/${theme}-split.png` });
await page.getByRole('button', { name: 'Edit', exact: true }).click();
await page.getByRole('group', { name: 'Editor layout', exact: true }).hover();
@@ -114,6 +112,7 @@ try {
await page.getByRole('button', { name: 'Files', exact: true }).click();
await page.getByRole('button', { name: 'Hide outline', exact: true }).click();
await page.screenshot({ path: `${output}/${theme}-ide-narrow.png` });
await page.keyboard.press('Control+t');
await page.locator('.welcome-actions').waitFor();
await page.setViewportSize({ width: 480, height: 640 });
@@ -124,19 +123,17 @@ try {
assert.equal(await background.evaluate(node => node.getAnimations().length), 0);
await page.evaluate(() => { const { hub, owner, urls } = window.backgroundTest; hub.removeOwner(owner); urls.forEach(URL.revokeObjectURL); });
assert.equal(await page.evaluate(() => document.body.style.getPropertyValue('--rs-background-previous-image')), '');
assert.match(await background.evaluate(node => getComputedStyle(node).backgroundImage), /blob:/);
assert.match(await style(background, 'backgroundImage'), /blob:/);
await page.evaluate(async () => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode: window.backgroundTest.theme }); });
assert.equal(await background.evaluate(node => getComputedStyle(node).backgroundImage), 'none');
await page.keyboard.press('Control+p');
await page.getByRole('textbox', { name: 'Find a file' }).fill('welcome');
await page.getByRole('dialog').getByRole('button').filter({ hasText: 'welcome.md' }).first().click();
assert.equal(await style(background, 'backgroundImage'), 'none');
await openWelcome();
await page.locator('.editor > .body').waitFor();
assert.equal(await page.locator('.editor > .body').evaluate(node => getComputedStyle(node).backgroundColor), await page.locator('.shell').evaluate(node => getComputedStyle(node).backgroundColor));
await page.screenshot({ path: output + '/' + theme + '-removed.png' });
assert.deepEqual(errors, []);
assert.equal(await style(page.locator('.editor > .body'), 'backgroundColor'), await style(page.locator('.shell'), 'backgroundColor'));
await page.screenshot({ path: `${output}/${theme}-removed.png` });
assert.deepEqual(page.errors, []);
report.push({ theme, passed: ['saved image', 'continuous workarea', 'sidebar transparency', 'button-only splash', 'keyboard focus', 'writer', 'reader scrolling', 'split', 'IDE transparency', 'narrow layout', 'fade', 'reduced motion', 'slideshow removal', 'saved image removal'], screenshots: `${output}/${theme}-*.png`, nativeDesktop: 'not tested' });
await page.close();
console.log(`PASS: ${theme} workarea backgrounds, editors, keyboard, narrow layout, fade, and restoration`);
}
await writeFile(`${output}/report.json`, JSON.stringify(report, null, 2));
} finally { await browser.close(); }
});
@@ -1,69 +1,41 @@
// New-tab background images: large uploads, cross-window sync, reload, theme reuse, removal, picker menus, and narrow settings.
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { mkdir, writeFile } from 'node:fs/promises';
import { resolve } from 'node:path';
const { chromium } = createRequire(import.meta.url)(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: 780 } });
await context.addInitScript(() => {
window.isTauri = true;
const root = 'C:\\host-todo-test';
const files = new Map([['a.md', '# Note\n\nOriginal text.'], ['.runestone/templates/Daily.md', '# Daily\n\n## Tasks'], ['.runestone/marks.json', JSON.stringify({ pins: ['a.md'], bookmarks: ['a.md'], order: { '': ['a.md'] } })]]);
const state = { files, calls: [], exportResult: 'C:\\exports\\my-theme.json', exportError: '' };
window.__HOST_TEST__ = state;
let sequence = 0;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
transformCallback: () => ++sequence, unregisterCallback: () => {},
invoke: async (command, args = {}) => {
state.calls.push({ command, args });
if (command === 'plugins_snapshot') return { root: 'C:/plugins', plugins: [] };
if (command === 'workspace_last_path') return root;
if (command === 'workspace_open') return { root, name: 'host-todo-test', watch_mode: 'native' };
if (command === 'workspace_read') { if (!files.has(args.rel)) throw new Error('Missing file'); return files.get(args.rel); }
if (command === 'workspace_list') {
const prefix = args.rel ? args.rel + '/' : '';
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || (!args.rel && path.startsWith('.runestone/'))) continue;
const tail = path.slice(prefix.length), name = tail.split('/')[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes('/') ? 'folder' : 'file' });
}
return [...entries.values()];
}
if (command === 'workspace_create') { if (files.has(args.rel)) throw new Error('Destination exists'); files.set(args.rel, ''); return; }
if (command === 'workspace_write') {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error('Changed on disk');
files.set(args.rel, args.contents); return;
}
if (command === 'workspace_rename') {
if (files.has(args.to)) throw new Error('Destination exists');
if (!files.has(args.from)) throw new Error('Missing file');
files.set(args.to, files.get(args.from)); files.delete(args.from); return;
}
if (command === 'workspace_delete') { files.delete(args.rel); return; }
if (command === 'workspace_search') return [];
if (command === 'plugin:event|listen') return ++sequence;
if (command === 'plugin:window|is_maximized') return false;
if (command === 'plugin:dialog|message') return 'Ok';
if (command === 'theme_export') { if (state.exportError) throw new Error(state.exportError); return state.exportResult; }
return null;
import { writeFile } from 'node:fs/promises';
import path from 'node:path';
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
// The image is painted on .workarea-background, not on the empty tab (src/lib/layout/Workbench.svelte:1258, 1543).
await runSmoke('appearance/backgroundImages', async ({ browser }) => {
const output = await outputDir('appearance/backgroundImages');
const context = await browser.newContext({ viewport: { width: 1100, height: 780 } });
await mockTauri(context, {
commands: test => {
const workspace = test.workspace({
root: 'C:\\host-todo-test',
files: {
'a.md': '# Note\n\nOriginal text.',
'.runestone/templates/Daily.md': '# Daily\n\n## Tasks',
'.runestone/marks.json': JSON.stringify({ pins: ['a.md'], bookmarks: ['a.md'], order: { '': ['a.md'] } }),
},
});
return {
...workspace,
workspace_list: args => workspace.workspace_list(args).filter(entry => entry.rel_path !== '.runestone'),
plugins_snapshot: () => ({ root: 'C:/plugins', plugins: [] }),
'plugin:window|is_maximized': () => false,
};
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const main = await context.newPage(), settings = await context.newPage();
const errors = [];
for (const page of [main, settings]) page.on('pageerror', error => errors.push(error.message));
const origin = process.env.SMOKE_URL || 'http://127.0.0.1:5187';
await mkdir('output/appearance-pass3', { recursive: true });
async function background() { return main.locator('.empty').evaluate(node => /url\("(blob:[^"]+)"\)/.exec(getComputedStyle(node).backgroundImage)?.[1]); }
async function decoded(page, url) {
return page.evaluate(async url => { const image = new Image(); image.src = url; await image.decode(); return image.naturalWidth; }, url);
}
try {
await main.goto(origin); await main.locator('.empty').waitFor();
await settings.goto(origin + '/?settingsWindow=true');
});
const main = await openPage(context), settings = await openPage(context);
const imageInput = () => settings.getByLabel('Background image file', { exact: true });
const background = () => main.locator('.workarea-background').evaluate(node => /url\("(blob:[^"]+)"\)/.exec(getComputedStyle(node).backgroundImage)?.[1]);
const decoded = (page, url) => page.evaluate(async url => { const image = new Image(); image.src = url; await image.decode(); return image.naturalWidth; }, url);
const savedImageId = () => settings.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance')).newTabBackground.imageId);
const picker = name => settings.locator('.picker').and(settings.getByRole('button', { name, exact: true }));
await main.goto(smokeUrl); await main.locator('.empty').waitFor();
await settings.goto(smokeUrl + '/?settingsWindow=true');
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
const image = await main.evaluate(() => {
const canvas = document.createElement('canvas'); canvas.width = canvas.height = 700;
@@ -74,61 +46,69 @@ try {
});
const bytes = Buffer.from(image.split(',')[1], 'base64');
assert.ok(image.length > 2 ** 21 && bytes.length < 2_000_000, 'Fixture crosses the CSS limit but fits the upload limit');
await settings.getByLabel('Background image file', { exact: true }).setInputFiles({ name: 'large.png', mimeType: 'image/png', buffer: bytes });
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('blob:'));
await imageInput().setInputFiles({ name: 'large.png', mimeType: 'image/png', buffer: bytes });
await main.waitForFunction(() => getComputedStyle(document.querySelector('.workarea-background')).backgroundImage.includes('blob:'));
let url = await background();
assert.equal(await decoded(main, url), 700, 'The actual new-tab image decodes');
await main.reload(); await main.locator('.empty').waitFor();
url = await background(); assert.equal(await decoded(main, url), 700, 'The saved image survives reload');
const pixel = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=', 'base64');
const large = Buffer.concat([pixel, Buffer.alloc(50 * 1024 * 1024 - pixel.length)]);
await writeFile('output/appearance-pass3/50MiB.png', large);
await settings.getByLabel('Background image file', { exact: true }).setInputFiles(resolve('output/appearance-pass3/50MiB.png'));
await main.waitForFunction(old => /url\("(blob:[^"]+)"\)/.exec(getComputedStyle(document.querySelector('.empty')).backgroundImage)?.[1] !== old, url);
const largeFile = path.join(output, '50MiB.png');
await writeFile(largeFile, Buffer.concat([pixel, Buffer.alloc(50 * 1024 * 1024 - pixel.length)]));
await imageInput().setInputFiles(largeFile);
await main.waitForFunction(old => /url\("(blob:[^"]+)"\)/.exec(getComputedStyle(document.querySelector('.workarea-background')).backgroundImage)?.[1] !== old, url);
url = await background(); assert.equal(await decoded(main, url), 1, '50 MiB image decodes');
assert.ok(await settings.evaluate(() => localStorage.getItem('runestone.appearance').length < 500), 'Image bytes stay outside localStorage');
await main.reload(); await main.locator('.empty').waitFor();
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('blob:'));
await main.waitForFunction(() => getComputedStyle(document.querySelector('.workarea-background')).backgroundImage.includes('blob:'));
url = await background(); assert.equal(await decoded(main, url), 1, '50 MiB image survives reload');
const acceptedId = await settings.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance')).newTabBackground.imageId);
await writeFile('output/appearance-pass3/too-large.png', Buffer.alloc(50 * 1024 * 1024 + 1));
await settings.getByLabel('Background image file', { exact: true }).setInputFiles(resolve('output/appearance-pass3/too-large.png'));
const acceptedId = await savedImageId();
const tooLargeFile = path.join(output, 'too-large.png');
await writeFile(tooLargeFile, Buffer.alloc(50 * 1024 * 1024 + 1));
await imageInput().setInputFiles(tooLargeFile);
await settings.getByRole('alert').filter({ hasText: '50 MiB' }).waitFor();
assert.equal(await settings.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance')).newTabBackground.imageId), acceptedId);
assert.equal(await savedImageId(), acceptedId);
assert.equal(await settings.locator('input[type=color]').count(), 0);
await settings.getByLabel('Image overlay', { exact: true }).fill('55');
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('0.55'));
await main.waitForFunction(() => getComputedStyle(document.querySelector('.workarea-background')).backgroundImage.includes('0.55'));
await settings.getByLabel('Image overlay', { exact: true }).fill('-40');
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('255, 255, 255, 0.4'));
await main.waitForFunction(() => getComputedStyle(document.querySelector('.workarea-background')).backgroundImage.includes('255, 255, 255, 0.4'));
// The Color theme picker now chooses the theme and its light or dark mode together (src/lib/theme/AppearanceSettings.svelte:20, 113).
for (const mode of ['dark', 'light']) {
await settings.locator('.picker').and(settings.getByRole('button', { name: 'Appearance', exact: true })).click();
await settings.getByRole('menuitemradio', { name: mode === 'dark' ? 'Dark' : 'Light', exact: true }).click();
await picker('Color theme').click();
await settings.getByRole('menuitemradio', { name: mode === 'dark' ? 'RuneStone Dark' : 'RuneStone Light', exact: true }).click();
await main.waitForFunction(mode => document.documentElement.dataset.theme === mode, mode);
assert.equal(await background(), url, 'Theme changes reuse the current image URL');
await main.screenshot({ path: `output/appearance-pass3/background-${mode}.png` });
for (const name of ['Color theme', 'Appearance']) {
await settings.locator('.picker').and(settings.getByRole('button', { name, exact: true })).click();
await main.screenshot({ path: `${output}/background-${mode}.png` });
for (const name of ['Color theme']) {
await picker(name).click();
const menu = settings.getByRole('menu', { name, exact: true });
assert.equal(await menu.evaluate(node => getComputedStyle(node).fontSize), '13px');
assert.equal(await menu.locator(':scope > button').first().evaluate(node => getComputedStyle(node).minHeight), '30px');
// Shared menu rows are 24px high (src/lib/theme/tokens.css:31, --rs-menu-row-height).
assert.equal(await menu.locator(':scope > button').first().evaluate(node => getComputedStyle(node).minHeight), '24px');
assert.equal(await menu.locator('[aria-checked="true"] svg').count(), 0);
assert.equal(await menu.evaluate(node => { const reference = document.createElement('span'); reference.style.color = 'var(--rs-menu-border)'; node.append(reference); const matches = getComputedStyle(node).borderColor === getComputedStyle(reference).color; reference.remove(); return matches; }), true, 'Menu uses the shared border token');
assert.equal(await menu.evaluate(node => getComputedStyle(node).borderColor), 'rgba(0, 0, 0, 0)', 'Menus have no visible border');
await settings.screenshot({ path: `output/appearance-pass3/${name.replaceAll(' ', '-')}-${mode}.png` });
await settings.screenshot({ path: `${output}/${name.replaceAll(' ', '-')}-${mode}.png` });
await settings.keyboard.press('Escape');
assert.equal(await settings.locator('.picker').and(settings.getByRole('button', { name, exact: true })).evaluate(node => node === document.activeElement), true);
assert.equal(await picker(name).evaluate(node => node === document.activeElement), true);
}
}
await settings.setViewportSize({ width: 360, height: 480 });
await settings.getByRole('button', { name: 'Color theme', exact: true }).click();
const box = await settings.getByRole('menu', { name: 'Color theme', exact: true }).boundingBox();
assert.ok(box.x >= 0 && box.x + box.width <= 360 && box.y + box.height <= 480);
await settings.screenshot({ path: 'output/appearance-pass3/menu-narrow.png' });
await settings.screenshot({ path: `${output}/menu-narrow.png` });
await settings.keyboard.press('Escape');
await settings.getByRole('button', { name: 'Remove image', exact: true }).click();
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage === 'none');
await main.waitForFunction(() => getComputedStyle(document.querySelector('.workarea-background')).backgroundImage === 'none');
assert.equal(await main.evaluate(async url => { try { await fetch(url); return false; } catch { return true; } }, url), true, 'Removing an image releases its URL');
assert.equal(await settings.evaluate(async id => (await import('/src/lib/theme/backgroundImages.ts')).readBackgroundImage(id).then(Boolean), acceptedId), false, 'Removal deletes stored image bytes');
await settings.evaluate(async () => {
const external = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
external.pluginTools.update(items => [...items, ...Array.from({ length: 30 }, (_, index) => ({ owner: `test.plugin${index}`, id: 'settings', title: `Plugin settings ${index}`, kind: 'view', surface: 'settings' }))]);
@@ -138,7 +118,7 @@ try {
await settings.setViewportSize({ width: 360, height: 600 });
assert.equal(await settings.getByRole('navigation', { name: 'Settings categories' }).getByRole('button').count() >= 34, true);
assert.equal(await settings.locator('.content').evaluate(node => node.clientHeight > 240 && node.clientWidth > 300), true, 'Long navigation leaves room for settings');
await settings.screenshot({ path: `output/appearance-pass3/long-plugin-list-${theme}-narrow.png` });
await settings.screenshot({ path: `${output}/long-plugin-list-${theme}-narrow.png` });
await main.setViewportSize({ width: 600, height: 700 });
await main.keyboard.press('F1');
await main.getByRole('dialog', { name: 'Help and about' }).waitFor();
@@ -146,9 +126,9 @@ try {
await main.locator('.help-card summary').first().focus(); await main.keyboard.press('Enter');
assert.equal(await main.locator('.help-card details[open]').count(), 1);
await main.keyboard.press('Enter');
await main.screenshot({ path: `output/appearance-pass3/help-${theme}-narrow.png` });
await main.screenshot({ path: `${output}/help-${theme}-narrow.png` });
await main.getByRole('button', { name: 'Close help', exact: true }).click();
}
assert.deepEqual(errors, []);
assert.deepEqual([...main.errors, ...settings.errors], []);
console.log('PASS: large image upload, decoding, cross-window sync, reload, theme reuse, removal, shared menu dimensions, keyboard dismissal, and narrow viewport.');
} finally { await browser.close(); }
});
@@ -1,43 +1,36 @@
// Background image position and size: menu choices, a stable surface under overflow, persistence, keyboard choice, both themes, narrow settings.
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { mkdir, writeFile } from 'node:fs/promises';
const { chromium } = createRequire(import.meta.url)(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: 780 } });
await context.addInitScript(() => {
window.isTauri = true;
let sequence = 0;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
transformCallback: () => ++sequence, unregisterCallback: () => {},
invoke: async (command) => {
if (command === 'plugins_snapshot') return { root: 'C:/plugins', plugins: [] };
if (command === 'plugin:window|is_maximized') return false;
if (command === 'plugin:event|listen') return ++sequence;
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const main = await context.newPage(), settings = await context.newPage();
const origin = process.env.SMOKE_URL || 'http://127.0.0.1:5187';
const screenshots = [];
await mkdir('output/todo-background', { recursive: true });
try {
await main.goto(origin);
await settings.goto(origin + '/?settingsWindow=true');
import { writeFile } from 'node:fs/promises';
import path from 'node:path';
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
// The image is painted on .workarea-background, not on the empty tab (src/lib/layout/Workbench.svelte:1258, 1543).
await runSmoke('appearance/backgroundLayout', async ({ browser }) => {
const output = await outputDir('appearance/backgroundLayout');
const context = await browser.newContext({ viewport: { width: 1100, height: 780 } });
await mockTauri(context, {
commands: () => ({
plugins_snapshot: () => ({ root: 'C:/plugins', plugins: [] }),
'plugin:window|is_maximized': () => false,
}),
});
const main = await openPage(context), settings = await openPage(context);
const screenshots = [];
await main.goto(smokeUrl);
await main.locator('.empty').waitFor();
await settings.goto(smokeUrl + '/?settingsWindow=true');
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=', 'base64');
await settings.getByLabel('Background image file', { exact: true }).setInputFiles({ name: 'image.png', mimeType: 'image/png', buffer: png });
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('blob:'));
await main.waitForFunction(() => getComputedStyle(document.querySelector('.workarea-background')).backgroundImage.includes('blob:'));
for (const [control, choice] of [['Image position', 'Top left'], ['Image size', 'Actual size']]) {
const button = settings.getByRole('button', { name: control, exact: true });
await button.click();
await settings.getByRole('menuitemradio', { name: choice, exact: true }).click();
assert.equal(await button.evaluate(node => node === document.activeElement), true);
}
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundPosition.endsWith('0% 0%'));
const layout = () => main.locator('.empty').evaluate(node => {
await main.waitForFunction(() => getComputedStyle(document.querySelector('.workarea-background')).backgroundPosition.endsWith('0% 0%'));
const layout = () => main.locator('.workarea-background').evaluate(node => {
const style = getComputedStyle(node), box = node.getBoundingClientRect();
return { position: style.backgroundPosition, size: style.backgroundSize, width: box.width, height: box.height };
});
@@ -49,13 +42,13 @@ try {
assert.deepEqual(await layout(), before, 'Overflowing content does not resize or reposition the image surface');
await main.reload();
await main.locator('.empty').waitFor();
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('blob:'));
await main.waitForFunction(() => getComputedStyle(document.querySelector('.workarea-background')).backgroundImage.includes('blob:'));
assert.equal((await layout()).position, before.position);
assert.equal((await layout()).size, before.size);
await settings.getByRole('button', { name: 'Image position', exact: true }).click();
await settings.keyboard.press('End');
await settings.keyboard.press('Enter');
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundPosition.endsWith('100% 100%'));
await main.waitForFunction(() => getComputedStyle(document.querySelector('.workarea-background')).backgroundPosition.endsWith('100% 100%'));
for (const mode of ['light', 'dark']) {
await settings.evaluate(async mode => {
const appearance = await import('/src/lib/theme/appearance.ts');
@@ -65,12 +58,12 @@ try {
await main.waitForFunction(mode => document.documentElement.dataset.theme === mode, mode);
for (const width of [1100, 360]) {
await settings.setViewportSize({ width, height: 700 });
const file = `output/todo-background/settings-${mode}-${width}.png`;
const file = path.join(output, `settings-${mode}-${width}.png`);
await settings.screenshot({ path: file }); screenshots.push(file);
const pane = settings.locator('.content');
assert.equal(await pane.evaluate(node => node.scrollWidth <= node.clientWidth + 1), true);
assert.equal(await settings.locator('.content').evaluate(node => node.scrollWidth <= node.clientWidth + 1), true);
}
}
await writeFile('output/todo-background-report.json', JSON.stringify({ card: 'ab7b1a06-fd5a-4b74-aaa1-da64eafdf71c', checks: ['Alignment and sizing choices persist across reload and windows', 'Overflow does not resize the background surface', 'Keyboard choice and focus return', 'Both themes and narrow settings'], screenshots, native: 'Desktop visual acceptance remains pending.' }, null, 2));
await writeFile(path.join(output, 'report.json'), JSON.stringify({ card: 'ab7b1a06-fd5a-4b74-aaa1-da64eafdf71c', checks: ['Alignment and sizing choices persist across reload and windows', 'Overflow does not resize the background surface', 'Keyboard choice and focus return', 'Both themes and narrow settings'], screenshots, native: 'Desktop visual acceptance remains pending.' }, null, 2));
assert.deepEqual([...main.errors, ...settings.errors], []);
console.log('PASS: background alignment, size, stable surface, persistence, keyboard, both themes, narrow settings.');
} finally { await browser.close(); }
});
@@ -1,31 +1,19 @@
// Background image overlay: signed numeric entry, slider sync, persistence, clamping, both themes, narrow settings, keyboard focus.
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { mkdir, writeFile } from 'node:fs/promises';
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || 'playwright');
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : { channel: 'chrome' }) });
const context = await browser.newContext({ viewport: { width: 1100, height: 780 } });
await context.addInitScript(() => {
window.isTauri = true;
let sequence = 0;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
transformCallback: () => ++sequence, unregisterCallback: () => {},
invoke: async command => {
if (command === 'plugins_snapshot') return { root: 'C:/plugins', plugins: [] };
if (command === 'plugin:window|is_maximized') return false;
if (command === 'plugin:event|listen') return ++sequence;
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const origin = process.env.SMOKE_URL || 'http://127.0.0.1:5187';
const settings = await context.newPage();
const errors = [];
settings.on('pageerror', error => errors.push(error.message));
await mkdir('output/round4-overlay', { recursive: true });
try {
await settings.goto(origin + '/?settingsWindow=true');
import { writeFile } from 'node:fs/promises';
import path from 'node:path';
import { mockTauri, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
await runSmoke('appearance/backgroundOverlay', async ({ page: settings }) => {
const output = await outputDir('appearance/backgroundOverlay');
await settings.setViewportSize({ width: 1100, height: 780 });
await mockTauri(settings, {
commands: () => ({
plugins_snapshot: () => ({ root: 'C:/plugins', plugins: [] }),
'plugin:window|is_maximized': () => false,
}),
});
await settings.goto(smokeUrl + '/?settingsWindow=true');
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
await settings.getByLabel('Background image file', { exact: true }).setInputFiles({
name: 'image.png', mimeType: 'image/png',
@@ -62,16 +50,15 @@ try {
await input.focus();
assert.equal(await input.evaluate(node => node === document.activeElement), true);
assert.equal(await settings.locator('.content').evaluate(node => node.scrollWidth <= node.clientWidth + 1), true);
await settings.screenshot({ path: `output/round4-overlay/${mode}-${width}.png` });
await settings.screenshot({ path: path.join(output, `${mode}-${width}.png`) });
}
}
assert.deepEqual(errors, []);
await writeFile('output/round4-overlay-report.json', JSON.stringify({
await writeFile(path.join(output, 'report.json'), JSON.stringify({
card: '2d1ae11e-8142-4840-bf0a-70f682e90e53',
hostChecks: ['Signed numeric entry and slider synchronization', 'Persistence after reload', 'Empty input retains saved value', 'Values clamp to -100 through 100', 'Both themes, keyboard focus, 360px and 1100px settings'],
shared: ['--rs-settings-control-height', '--rs-settings-gap', '--rs-control-radius'],
screenshotFolder: 'output/round4-overlay',
screenshotFolder: output,
native: 'Native desktop acceptance remains pending.',
}, null, 2));
console.log('PASS: numeric overlay, slider, persistence, bounds, themes, narrow settings, keyboard focus.');
} finally { await browser.close(); }
});
+129 -136
View File
@@ -1,98 +1,95 @@
// Character themes: colors, fonts, IDE syntax, export, window sync, narrow menus, selection fills, and legacy or removed theme IDs.
import assert from 'node:assert/strict';
import { mkdir } from 'node:fs/promises';
import { createRequire } from 'node:module';
import path from 'node:path';
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
const { chromium } = createRequire(import.meta.url)(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 output = '.audit/character-themes';
const errors = [];
await mkdir(output, { recursive: true });
try {
await runSmoke('appearance/characterThemes', async ({ browser }) => {
const output = await outputDir('appearance/characterThemes');
const context = await browser.newContext({ viewport: { width: 1100, height: 780 } });
await context.addInitScript(() => {
window.isTauri = true;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
transformCallback: () => 1, unregisterCallback: () => {},
invoke: async (command, args = {}) => {
if (command === 'plugins_snapshot') return { root: 'C:/theme-smoke-plugins', plugins: [] };
if (command === 'workspace_last_path') return 'C:\\theme-smoke';
if (command === 'workspace_open') return { root: 'C:\\theme-smoke', name: 'theme-smoke', watch_mode: 'native' };
if (command === 'workspace_list') return [{ name: 'Theme.md', rel_path: 'Theme.md', kind: 'file' }, { name: 'Theme.py', rel_path: 'Theme.py', kind: 'file' }];
if (command === 'workspace_read' && args.rel === 'Theme.py') return '# Character colors\ndef sample(parameter):\n return parameter\nname = "RuneStone"\nprint(name, 42)\n';
if (command === 'workspace_read') return '# Theme sample\n\nA calm surface with readable text.\n\n[Link](https://example.com)\n';
if (command === 'workspace_search') return [];
if (command === 'theme_export') { window.exportedTheme = JSON.parse(args.contents); return 'C:\\theme-smoke\\my-theme.json'; }
if (command === 'plugin:event|listen') return args.handler;
return null;
},
await mockTauri(context, {
commands: test => ({
...test.workspace({
root: 'C:\\theme-smoke',
files: {
'Theme.md': '# Theme sample\n\nA calm surface with readable text.\n\n[Link](https://example.com)\n',
'Theme.py': '# Character colors\ndef sample(parameter):\n return parameter\nname = "RuneStone"\nprint(name, 42)\n',
},
}),
plugins_snapshot: () => ({ root: 'C:/theme-smoke-plugins', plugins: [] }),
theme_export: args => { window.exportedTheme = JSON.parse(args.contents); return 'C:\\theme-smoke\\my-theme.json'; },
}),
});
const main = await openPage(context);
const settings = await openPage(context);
const ide = await openPage(context);
const pages = [main, settings, ide];
try {
const fontSession = await context.newCDPSession(settings);
await fontSession.send('DOM.enable');
await fontSession.send('CSS.enable');
async function openFile(page, name) {
await page.goto(smokeUrl);
await page.getByText('theme-smoke', { exact: true }).waitFor();
await page.keyboard.press('Control+p');
await page.getByRole('textbox', { name: 'Find a file' }).fill(name);
await page.getByRole('textbox', { name: 'Find a file' }).press('Enter');
}
await openFile(main, 'Theme.md');
await main.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
await openFile(ide, 'Theme.py');
await ide.locator('.monaco-editor textarea').waitFor();
const editorIds = () => ide.evaluate(async () => {
const { monaco } = await import('/src/lib/editor/monacoEnv.ts');
return monaco.editor.getEditors().filter(editor => editor.getDomNode()?.isConnected).map(editor => editor.getId());
});
const initialEditors = await editorIds();
const openSettings = async () => {
await settings.goto(`${smokeUrl}/?settingsWindow=true`);
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
await settings.getByRole('img', { name: 'Color theme preview' }).waitFor();
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const main = await context.newPage();
const settings = await context.newPage();
const ide = await context.newPage();
const fontSession = await context.newCDPSession(settings);
await fontSession.send('DOM.enable');
await fontSession.send('CSS.enable');
for (const page of [main, settings, ide]) page.on('pageerror', error => errors.push(error.message));
await main.goto(origin);
await main.getByText('theme-smoke', { exact: true }).waitFor();
await main.keyboard.press('Control+p');
await main.getByRole('textbox', { name: 'Find a file' }).fill('Theme.md');
await main.getByRole('textbox', { name: 'Find a file' }).press('Enter');
await main.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
await ide.goto(origin);
await ide.getByText('theme-smoke', { exact: true }).waitFor();
await ide.keyboard.press('Control+p');
await ide.getByRole('textbox', { name: 'Find a file' }).fill('Theme.py');
await ide.getByRole('textbox', { name: 'Find a file' }).press('Enter');
await ide.locator('.monaco-editor textarea').waitFor();
const editorIds = () => ide.evaluate(async () => {
const { monaco } = await import('/src/lib/editor/monacoEnv.ts');
return monaco.editor.getEditors().filter(editor => editor.getDomNode()?.isConnected).map(editor => editor.getId());
});
const initialEditors = await editorIds();
const openSettings = async () => {
await settings.goto(`${origin}/?settingsWindow=true`);
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
await settings.getByRole('img', { name: 'Color theme preview' }).waitFor();
};
const picker = name => settings.locator('.picker').and(settings.getByRole('button', { name, exact: true }));
const choose = async (name, value) => {
await picker(name).click();
await settings.getByRole('menuitemradio', { name: value, exact: true }).click();
};
await openSettings();
await picker('Color theme').click();
assert.equal(await settings.getByRole('menuitemradio', { name: 'Renamon', exact: true }).count(), 0);
assert.equal(await settings.getByRole('menuitemradio', { name: 'Asuka School Uniform', exact: true }).count(), 0);
for (const label of ['Holo', 'Asuka Langley Soryu', 'Malfoid']) {
assert.equal(await settings.getByRole('menuitemradio', { name: label, exact: true }).count(), 0);
}
await settings.keyboard.press('Escape');
const cases = [
['harvest-moon', 'Harvest Moon', 'dark', { ui: 'Candara', prose: 'Constantia', heading: 'Constantia' }],
['crimson-pilot', 'Crimson Pilot', 'dark', { ui: 'Bahnschrift', prose: 'Segoe UI', heading: 'Bahnschrift' }],
['silver-serpent', 'Silver Serpent', 'dark', { ui: 'Corbel', prose: 'Palatino Linotype', heading: 'Palatino Linotype' }],
];
for (const [theme, label, mode, expectedFonts] of cases) {
const picker = name => settings.locator('.picker').and(settings.getByRole('button', { name, exact: true }));
const choose = async (name, value) => {
await picker(name).click();
await settings.getByRole('menuitemradio', { name: value, exact: true }).click();
};
const waitForAppearance = (theme, mode) => Promise.all(pages.map(page => page.waitForFunction(({ theme, mode }) => document.documentElement.dataset.palette === theme && document.documentElement.dataset.theme === mode, { theme, mode })));
// Settings and the app import external.ts with a version query, so reuse the loaded module URL.
const setPluginTools = count => settings.evaluate(async count => {
const { pluginTools } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
pluginTools.set(Array.from({ length: count }, (_, index) => ({ owner: 'org.example.theme-check', id: `settings-${index}`, title: `Plugin settings ${index + 1}`, surface: 'settings' })));
}, count);
await openSettings();
await picker('Color theme').click();
assert.equal(await settings.getByRole('menuitemradio', { name: 'Renamon', exact: true }).count(), 0);
assert.equal(await settings.getByRole('menuitemradio', { name: 'Asuka School Uniform', exact: true }).count(), 0);
for (const label of ['Holo', 'Asuka Langley Soryu', 'Malfoid']) {
assert.equal(await settings.getByRole('menuitemradio', { name: label, exact: true }).count(), 0);
}
await settings.keyboard.press('Escape');
const cases = [
['harvest-moon', 'Harvest Moon', 'dark', { ui: 'Candara', prose: 'Constantia', heading: 'Constantia' }],
['crimson-pilot', 'Crimson Pilot', 'dark', { ui: 'Bahnschrift', prose: 'Segoe UI', heading: 'Bahnschrift' }],
['silver-serpent', 'Silver Serpent', 'dark', { ui: 'Corbel', prose: 'Palatino Linotype', heading: 'Palatino Linotype' }],
];
for (const [theme, label, mode, expectedFonts] of cases) {
await settings.setViewportSize({ width: 1100, height: 780 });
const variant = label;
await choose('Color theme', variant);
for (const page of [main, settings, ide]) {
await page.waitForFunction(({ theme, mode }) => document.documentElement.dataset.palette === theme && document.documentElement.dataset.theme === mode, { theme, mode });
}
const colors = await settings.evaluate(async theme => {
await choose('Color theme', label);
await waitForAppearance(theme, mode);
// The export is now one theme template, { schema, id, name, colors, fonts }, for the theme's own mode (src/lib/theme/appearance.ts:76-91).
const template = await settings.evaluate(async theme => {
const { exportAppearanceTheme } = await import('/src/lib/theme/appearance.ts');
return exportAppearanceTheme(theme);
}, theme);
const colors = template.colors;
// The applied selection color caps its alpha at a6 so text backgrounds show through (src/lib/theme/appearance.ts:197-203).
const applied = { ...colors, selection: `${colors.selection.slice(0, 7)}a6` };
const actual = await settings.evaluate(keys => {
const css = getComputedStyle(document.documentElement);
return Object.fromEntries(keys.map(key => [key, css.getPropertyValue(`--rs-${key}`).trim()]));
}, Object.keys(colors[mode]));
assert.deepEqual(actual, colors[mode]);
}, Object.keys(applied));
assert.deepEqual(actual, applied);
const fonts = await settings.evaluate(() => {
const css = getComputedStyle(document.documentElement);
return { ui: css.getPropertyValue('--rs-font-ui'), prose: getComputedStyle(document.querySelector('.preview-prose')).fontFamily,
@@ -106,8 +103,10 @@ try {
const rendered = await fontSession.send('CSS.getPlatformFontsForNode', { nodeId });
assert(rendered.fonts.some(item => item.glyphCount > 0), 'The font renders visible glyphs');
console.log(`${theme} rendered fonts: ${rendered.fonts.map(item => item.familyName).join(', ')}`);
await settings.evaluate(() => { window.exportedTheme = undefined; });
await settings.getByRole('button', { name: 'Export theme template' }).click();
assert.deepEqual(await settings.evaluate(() => window.exportedTheme), colors);
await settings.waitForFunction(() => window.exportedTheme);
assert.deepEqual(await settings.evaluate(() => window.exportedTheme), template);
await ide.waitForFunction(expected => {
const spans = [...document.querySelectorAll('.view-line span')].filter(node => !node.children.length);
return Object.entries(expected).every(([text, color]) => {
@@ -117,7 +116,7 @@ try {
const target = getComputedStyle(probe).color; probe.remove();
return node && getComputedStyle(node).color === target;
});
}, { return: colors[mode]['syntax-keyword'], RuneStone: colors[mode]['syntax-string'], 42: colors[mode]['syntax-number'], print: colors[mode]['syntax-keyword'], '# Character colors': colors[mode]['syntax-comment'] });
}, { return: colors['syntax-keyword'], RuneStone: colors['syntax-string'], 42: colors['syntax-number'], print: colors['syntax-keyword'], '# Character colors': colors['syntax-comment'] });
assert.deepEqual(await editorIds(), initialEditors, 'Theme changes preserve the editor');
if (theme === 'harvest-moon') {
const normalized = await settings.evaluate(async () => {
@@ -132,9 +131,11 @@ try {
selection: getComputedStyle(document.documentElement).getPropertyValue('--rs-item-selection-bg').trim() };
});
assert.equal(selectedRow.selected, 'true');
assert.equal(selectedRow.selection, colors[mode].selection, 'File selection uses the same warm selection color');
assert.equal(selectedRow.fill, 'rgb(72, 39, 20)', 'The selected file paints the warm fill');
await main.screenshot({ path: `${output}/${theme}-${mode}-file-selection.png` });
assert.equal(selectedRow.selection, applied.selection, 'File selection uses the same warm selection color');
// Selection fills use the capped a6 (0.65) alpha (src/lib/theme/appearance.ts:197-203).
const warmFill = 'rgba(72, 39, 20, 0.65)';
assert.equal(selectedRow.fill, warmFill, 'The selected file paints the warm fill');
await main.screenshot({ path: path.join(output, `${theme}-${mode}-file-selection.png`) });
await main.getByRole('textbox', { name: 'Writing editor', exact: true }).evaluate(node => {
node.focus();
const walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT);
@@ -144,7 +145,7 @@ try {
const selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(range);
});
assert.equal(await main.evaluate(() => window.getSelection().toString()), 'A calm surface with readable text.');
await main.screenshot({ path: `${output}/${theme}-${mode}-writer-selection.png` });
await main.screenshot({ path: path.join(output, `${theme}-${mode}-writer-selection.png`) });
await ide.evaluate(async () => {
const { monaco } = await import('/src/lib/editor/monacoEnv.ts');
const editor = monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected);
@@ -152,80 +153,72 @@ try {
});
await ide.locator('.selected-text').first().waitFor();
assert.equal(await ide.locator('.selected-text').first().evaluate(node => getComputedStyle(node).backgroundColor),
'rgb(72, 39, 20)', 'IDE selection uses the same warm fill');
await ide.screenshot({ path: `${output}/${theme}-${mode}-ide-selection.png` });
warmFill, 'IDE selection uses the same warm fill');
await ide.screenshot({ path: path.join(output, `${theme}-${mode}-ide-selection.png`) });
await ide.evaluate(async () => {
const { monaco } = await import('/src/lib/editor/monacoEnv.ts');
monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected).setPosition({ lineNumber: 1, column: 1 });
});
}
await ide.screenshot({ path: `${output}/${theme}-${mode}-ide.png` });
await settings.screenshot({ path: `${output}/${theme}-${mode}-settings.png` });
await main.screenshot({ path: `${output}/${theme}-${mode}-document.png` });
await ide.screenshot({ path: path.join(output, `${theme}-${mode}-ide.png`) });
await settings.screenshot({ path: path.join(output, `${theme}-${mode}-settings.png`) });
await main.screenshot({ path: path.join(output, `${theme}-${mode}-document.png`) });
await settings.reload();
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
assert.equal((await picker('Color theme').textContent()).trim(), variant);
assert.equal((await picker('Color theme').textContent()).trim(), label);
await settings.setViewportSize({ width: 360, height: 480 });
const content = settings.locator('dialog .content');
assert(await content.evaluate(node => node.scrollWidth <= node.clientWidth), 'Narrow settings fit the content area');
await picker('Color theme').scrollIntoViewIfNeeded();
await picker('Color theme').focus();
await settings.keyboard.press('Enter');
const current = settings.getByRole('menuitemradio', { name: variant, exact: true });
const current = settings.getByRole('menuitemradio', { name: label, exact: true });
await current.waitFor();
assert.equal(await current.getAttribute('aria-checked'), 'true');
assert(await current.evaluate(node => document.activeElement === node), 'The menu focuses the current theme');
const bounds = await settings.getByRole('menu', { name: 'Color theme', exact: true }).boundingBox();
assert(bounds.x >= 0 && bounds.x + bounds.width <= 360 && bounds.y >= 0 && bounds.y + bounds.height <= 480, 'The menu stays within the viewport');
await settings.screenshot({ path: `${output}/${theme}-${mode}-360-menu.png` });
await settings.screenshot({ path: path.join(output, `${theme}-${mode}-360-menu.png`) });
await settings.keyboard.press('ArrowDown');
await settings.keyboard.press('ArrowUp');
assert(await current.evaluate(node => document.activeElement === node));
await settings.keyboard.press('Escape');
assert(await picker('Color theme').evaluate(node => document.activeElement === node), 'Dismissal returns focus');
await settings.screenshot({ path: `${output}/${theme}-${mode}-360-focus.png` });
await settings.evaluate(async () => {
const { pluginTools } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
pluginTools.set(Array.from({ length: 16 }, (_, index) => ({ owner: 'org.example.theme-check', id: `settings-${index}`, title: `Plugin settings ${index + 1}`, surface: 'settings' })));
});
await settings.screenshot({ path: path.join(output, `${theme}-${mode}-360-focus.png`) });
await setPluginTools(16);
const navigation = settings.locator('dialog aside');
const bodyBounds = await settings.locator('dialog .body').boundingBox();
assert((await navigation.boundingBox()).height <= bodyBounds.height * 0.4 + 1, 'Long plugin navigation leaves room for settings');
assert(await content.evaluate(node => node.scrollWidth <= node.clientWidth));
await settings.getByRole('button', { name: 'Plugin settings 16', exact: true }).scrollIntoViewIfNeeded();
await settings.screenshot({ path: `${output}/${theme}-${mode}-360-long-navigation.png` });
await settings.evaluate(async () => { const { pluginTools } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name); pluginTools.set([]); });
await settings.screenshot({ path: path.join(output, `${theme}-${mode}-360-long-navigation.png`) });
await setPluginTools(0);
console.log(`PASS: ${theme} ${mode}, colors, fonts, IDE syntax, export, saved state, window sync, narrow menu, keyboard and focus`);
}
for (const [previous, theme, label] of [['holo', 'harvest-moon', 'Harvest Moon'], ['asuka', 'crimson-pilot', 'Crimson Pilot'], ['malfoid', 'silver-serpent', 'Silver Serpent']]) {
await settings.evaluate(theme => localStorage.setItem('runestone.appearance', JSON.stringify({ theme, mode: 'dark' })), previous);
await openSettings();
assert.equal((await picker('Color theme').textContent()).trim(), label);
assert.equal(await settings.evaluate(() => document.documentElement.dataset.palette), theme);
await choose('Color theme', label);
assert.equal(await settings.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance')).theme), theme);
}
for (const [removed, mode] of [['renamon', 'light'], ['asuka-school', 'dark']]) {
await settings.evaluate(({ theme, mode }) => localStorage.setItem('runestone.appearance', JSON.stringify({ theme, mode })), { theme: removed, mode });
await settings.setViewportSize({ width: 1100, height: 780 });
await openSettings();
for (const page of [main, settings, ide]) {
await page.waitForFunction(mode => document.documentElement.dataset.palette === 'default' && document.documentElement.dataset.theme === mode, mode);
}
assert.equal((await picker('Color theme').textContent()).trim(), `RuneStone ${mode === 'light' ? 'Light' : 'Dark'}`);
assert((await settings.evaluate(() => getComputedStyle(document.body).fontFamily)).includes('Segoe UI'), 'The default font returns after a palette change');
await settings.screenshot({ path: `${output}/${removed}-fallback-${mode}-settings.png` });
await settings.setViewportSize({ width: 360, height: 480 });
assert(await settings.locator('dialog .content').evaluate(node => node.scrollWidth <= node.clientWidth));
await settings.screenshot({ path: `${output}/default-${mode}-360-settings.png` });
console.log(`PASS: ${removed} saved appearance restores RuneStone ${mode}`);
for (const [previous, theme, label] of [['holo', 'harvest-moon', 'Harvest Moon'], ['asuka', 'crimson-pilot', 'Crimson Pilot'], ['malfoid', 'silver-serpent', 'Silver Serpent']]) {
await settings.evaluate(theme => localStorage.setItem('runestone.appearance', JSON.stringify({ theme, mode: 'dark' })), previous);
await openSettings();
assert.equal((await picker('Color theme').textContent()).trim(), label);
assert.equal(await settings.evaluate(() => document.documentElement.dataset.palette), theme);
await choose('Color theme', label);
assert.equal(await settings.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance')).theme), theme);
}
for (const [removed, mode] of [['renamon', 'light'], ['asuka-school', 'dark']]) {
await settings.evaluate(({ theme, mode }) => localStorage.setItem('runestone.appearance', JSON.stringify({ theme, mode })), { theme: removed, mode });
await settings.setViewportSize({ width: 1100, height: 780 });
await openSettings();
await waitForAppearance('default', mode);
assert.equal((await picker('Color theme').textContent()).trim(), `RuneStone ${mode === 'light' ? 'Light' : 'Dark'}`);
assert((await settings.evaluate(() => getComputedStyle(document.body).fontFamily)).includes('Segoe UI'), 'The default font returns after a palette change');
await settings.screenshot({ path: path.join(output, `${removed}-fallback-${mode}-settings.png`) });
await settings.setViewportSize({ width: 360, height: 480 });
assert(await settings.locator('dialog .content').evaluate(node => node.scrollWidth <= node.clientWidth));
await settings.screenshot({ path: path.join(output, `default-${mode}-360-settings.png`) });
console.log(`PASS: ${removed} saved appearance restores RuneStone ${mode}`);
}
assert.deepEqual(pages.flatMap(page => page.errors), []);
} catch (error) {
for (const [index, page] of pages.entries()) await page.screenshot({ path: path.join(output, `failure-${index}.png`) }).catch(() => {});
throw error;
}
assert.deepEqual(errors, []);
console.log('Character theme smoke passed.');
} catch (error) {
console.error('Page errors:', errors);
for (const context of browser.contexts()) {
for (const [index, page] of context.pages().entries()) await page.screenshot({ path: `${output}/failure-${index}.png` }).catch(() => {});
}
throw error;
} finally { await browser.close(); }
});
@@ -0,0 +1,43 @@
// The Color theme menu in Settings works from the keyboard, has no color inputs, and the main window's empty tab uses the new theme background.
import assert from "node:assert/strict";
import { mockTauri, openPage, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("appearance/colorThemeMenu", async ({ browser }) => {
// The settings window changes the main window through shared localStorage, so both pages need one context.
const context = await browser.newContext({ viewport: { width: 1200, height: 850 } });
await mockTauri(context, {
commands: test => ({
...test.workspace({ root: "C:\\color-theme-menu", files: { "a.md": "# Note\n\nOriginal text." } }),
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
spelling_menu_install: () => null,
}),
});
const page = await openPage(context);
await page.goto(smokeUrl);
await page.locator('[data-tree-rel="a.md"]').waitFor();
const settings = await openPage(context);
await settings.goto(smokeUrl + "/?settingsWindow=true");
await settings.getByRole("button", { name: "Appearance", exact: true }).click();
await settings.getByRole("button", { name: "Color theme", exact: true }).click();
// Menu entries now name the mode ("RuneStone Dark" is the default; src/lib/theme/AppearanceSettings.svelte:20-22). The next entry is Claude Light.
await settings.getByRole("menuitemradio", { name: "RuneStone Dark", exact: true }).focus();
await settings.keyboard.press("ArrowDown");
await settings.keyboard.press("Enter");
assert.equal(await settings.evaluate(() => document.documentElement.dataset.palette), "claude");
assert.equal(await settings.locator("input[type=color]").count(), 0);
await page.getByRole("button", { name: "New tab (Ctrl T)", exact: true }).click();
await page.locator(".empty").waitFor();
await page.waitForFunction(() => document.documentElement.dataset.palette === "claude");
// The empty tab is transparent over the work area layer, which paints the theme background (src/lib/layout/Workbench.svelte:1258, :1548).
assert.equal(await page.locator(".empty").evaluate(node => getComputedStyle(node).backgroundColor), "rgba(0, 0, 0, 0)");
assert.equal(await page.locator(".workarea-background").evaluate(node => {
const reference = document.createElement("span");
reference.style.color = "var(--rs-bg)";
node.append(reference);
const matches = getComputedStyle(node).backgroundColor === getComputedStyle(reference).color;
reference.remove();
return matches;
}), true);
assert.deepEqual([...page.errors, ...settings.errors], []);
console.log("PASS: keyboard theme selection, no color inputs, and the empty tab uses the theme background");
});
+78 -89
View File
@@ -1,104 +1,93 @@
// Run against pnpm dev with PLAYWRIGHT_MODULE and CHROME_PATH if needed.
import { createRequire } from "node:module";
// Compact layout: pane-aligned ribbon, square tables, focus-only tree outline, joined tabs, line hover marker, Git line history, narrow width.
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 context = await browser.newContext({ viewport: { width: 1280, height: 800 } });
await context.addInitScript(() => {
window.isTauri = true;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: () => 1, unregisterCallback: () => {},
invoke: async (command, args = {}) => {
if (command === "plugins_snapshot") return { root: "D:\\LayoutTest\\plugins", plugins: [] };
if (command === "workspace_last_path") return "D:\\LayoutTest";
if (command === "workspace_open") return { root: "D:\\LayoutTest", name: "LayoutTest", watch_mode: "native" };
if (command === "workspace_list") return args.rel ? [] : [{ name: "note.md", rel_path: "note.md", kind: "file" }];
if (command === "workspace_read") {
if (args.rel === "note.md") return "# Layout test\n\nA note with a short paragraph.\n\nA second paragraph.\n\n| Name | Value |\n| --- | --- |\n| Alpha | 12 |\n| Beta | 24 |\n";
throw new Error("Missing file");
}
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
const page = await context.newPage();
page.setDefaultTimeout(30000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
const url = process.env.SMOKE_URL || "http://127.0.0.1:5174";
const row = page.locator('[data-tree-rel="note.md"]');
try {
await page.goto(url);
await runSmoke("appearance/density", async ({ page }) => {
const output = await outputDir("appearance/density");
await page.setViewportSize({ width: 1280, height: 800 });
await mockTauri(page, {
commands: test => ({
...test.workspace({
root: "D:\\LayoutTest",
files: { "note.md": "# Layout test\n\nA note with a short paragraph.\n\nA second paragraph.\n\n| Name | Value |\n| --- | --- |\n| Alpha | 12 |\n| Beta | 24 |\n" },
}),
plugins_snapshot: () => ({ root: "D:\\LayoutTest\\plugins", plugins: [] }),
}),
});
const row = page.locator('[data-tree-rel="note.md"]');
const documentView = () => page.getByRole("group", { name: "Document view" }).locator("button.current");
const editorLayout = () => page.getByRole("group", { name: "Editor layout" }).locator("button.current");
const setTheme = theme => page.evaluate(theme => { document.documentElement.dataset.theme = theme; }, theme);
await page.goto(smokeUrl);
await row.waitFor();
await row.click();
await page.locator('.writer-table table').waitFor();
const alignment = await page.evaluate(() => ({header:document.querySelector('.header-left').getBoundingClientRect().right, content:document.querySelector('.center').getBoundingClientRect().left}));
await page.locator(".writer-table table").waitFor();
const alignment = await page.evaluate(() => ({ header: document.querySelector(".header-left").getBoundingClientRect().right, content: document.querySelector(".center").getBoundingClientRect().left }));
assert.ok(Math.abs(alignment.header - alignment.content) <= 1, JSON.stringify(alignment));
const table = await page.locator('.writer-table table').evaluate(el => ({width:el.getBoundingClientRect().width, heights:[...el.rows].map(row=>row.getBoundingClientRect().height), radius:getComputedStyle(el.parentElement).borderRadius}));
const table = await page.locator(".writer-table table").evaluate(el => ({ width: el.getBoundingClientRect().width, heights: [...el.rows].map(row => row.getBoundingClientRect().height), radius: getComputedStyle(el.parentElement).borderRadius }));
assert.ok(table.width < 400, JSON.stringify(table));
assert.ok(table.heights.every(height => height <= 36), JSON.stringify(table));
assert.equal(table.radius, '0px');
assert.equal(table.radius, "0px");
await row.focus();
assert.equal(await row.locator('.selection-outline').evaluate(el=>getComputedStyle(el).visibility), 'visible');
await page.locator('.cm-content').click({position:{x:80,y:100}});
assert.equal(await row.locator('.selection-outline').evaluate(el=>getComputedStyle(el).visibility), 'hidden');
assert.equal(await row.getAttribute('aria-selected'), 'true');
const line = page.locator('.cm-line').filter({hasText:'A second paragraph.'});
assert.equal(await row.locator(".selection-outline").evaluate(el => getComputedStyle(el).visibility), "visible");
await page.locator(".cm-content").click({ position: { x: 80, y: 100 } });
assert.equal(await row.locator(".selection-outline").evaluate(el => getComputedStyle(el).visibility), "hidden");
assert.equal(await row.getAttribute("aria-selected"), "true");
const line = page.locator(".cm-line").filter({ hasText: "A second paragraph." });
await line.hover();
assert.equal(await line.evaluate(el=>getComputedStyle(el,'::before').width), '3px');
assert.equal(await page.locator('.line-history').count(),0);
await page.evaluate(async()=>{
const {pluginHost}=await import('/src/lib/plugins/registry.ts');
window.blameCalls=[];
window.removeGit=pluginHost.register('ui-test','git',{blame:async(path,line)=>{
window.blameCalls.push({path,line});
return {commit:'123456789abcdef',author:'UI test',date:'2026-10-07T12:34:00Z',summary:`Changed line ${line}`};
}});
assert.equal(await line.evaluate(el => getComputedStyle(el, "::before").width), "3px");
assert.equal(await page.locator(".line-history").count(), 0);
await page.evaluate(async () => {
const { pluginHost } = await import("/src/lib/plugins/registry.ts");
window.blameCalls = [];
window.removeGit = pluginHost.register("ui-test", "git", { blame: async (path, line) => {
window.blameCalls.push({ path, line });
return { commit: "123456789abcdef", author: "UI test", date: "2026-10-07T12:34:00Z", summary: `Changed line ${line}` };
} });
});
await line.click();
await page.locator('.line-history').waitFor();
assert.match(await page.locator('.line-history').getAttribute('title'), /Line 5 · UI test/);
await page.keyboard.type('x');
await page.locator('.line-history').waitFor({state:'hidden'});
await page.keyboard.press('Control+z');
await page.locator('.line-history').waitFor();
for(const theme of ['dark','light']) {
await page.evaluate(theme=>document.documentElement.dataset.theme=theme,theme);
const tab = await page.locator('.tab.active').evaluate(el=>({background:getComputedStyle(el).backgroundColor,border:getComputedStyle(el).borderBottomColor,shadow:getComputedStyle(el).boxShadow}));
const pane = await page.locator('.chrome-bar').evaluate(el=>getComputedStyle(el).backgroundColor);
assert.equal(tab.background,pane);
assert.equal(tab.border,'rgba(0, 0, 0, 0)');
assert.equal(tab.shadow,'none');
await page.locator(".line-history").waitFor();
assert.match(await page.locator(".line-history").getAttribute("title"), /Line 5 · UI test/);
await page.keyboard.type("x");
await page.locator(".line-history").waitFor({ state: "hidden" });
await page.keyboard.press("Control+z");
await page.locator(".line-history").waitFor();
for (const theme of ["dark", "light"]) {
await setTheme(theme);
const tab = await page.locator(".tab.active").evaluate(el => ({ background: getComputedStyle(el).backgroundColor, border: getComputedStyle(el).borderBottomColor, shadow: getComputedStyle(el).boxShadow }));
const pane = await page.locator(".chrome-bar").evaluate(el => getComputedStyle(el).backgroundColor);
assert.equal(tab.background, pane);
assert.equal(tab.border, "rgba(0, 0, 0, 0)");
assert.equal(tab.shadow, "none");
await line.hover();
await page.screenshot({path:`.audit/ui-cards/writer-${theme}.png`});
await page.getByRole('group',{name:'Document view'}).locator('button.current').press('ArrowRight');
await page.locator('.md-page .reading').waitFor();
const paragraph=page.locator('.md-page p').filter({hasText:'A second paragraph.'});
await page.screenshot({ path: path.join(output, `writer-${theme}.png`) });
await documentView().press("ArrowRight");
await page.locator(".md-page .reading").waitFor();
const paragraph = page.locator(".md-page p").filter({ hasText: "A second paragraph." });
await paragraph.hover();
assert.equal(await paragraph.evaluate(el=>getComputedStyle(el,'::before').width),'3px');
assert.ok((await page.locator('.md-page table').boundingBox()).width<400);
await page.screenshot({path:`.audit/ui-cards/read-${theme}.png`});
await page.getByRole('group',{name:'Document view'}).locator('button.current').press('Home');
assert.equal(await paragraph.evaluate(el => getComputedStyle(el, "::before").width), "3px");
assert.ok((await page.locator(".md-page table").boundingBox()).width < 400);
await page.screenshot({ path: path.join(output, `read-${theme}.png`) });
await documentView().press("Home");
}
await page.getByRole('group',{name:'Editor layout'}).locator('button.current').press('Home');
await page.locator('.monaco-editor').waitFor();
await page.locator('.line-history').waitFor();
await page.evaluate(()=>window.removeGit());
await page.locator('.line-history').waitFor({state:'hidden'});
await page.getByRole('group',{name:'Editor layout'}).locator('button.current').press('End');
await page.getByRole('button',{name:'Hide outline',exact:true}).click();
await page.setViewportSize({width:760,height:640});
for(const theme of ['dark','light']) {
await page.evaluate(theme=>document.documentElement.dataset.theme=theme,theme);
const dimensions=await page.locator('.header-left .icon-btn').evaluateAll(els=>els.map(el=>({width:el.getBoundingClientRect().width,svg:el.querySelector('svg').getBoundingClientRect().width})));
assert.ok(dimensions.every(size=>size.width>=28 && size.svg>=16),JSON.stringify(dimensions));
assert.ok(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));
await page.screenshot({path:`.audit/ui-cards/narrow-${theme}.png`});
await editorLayout().press("Home");
await page.locator(".monaco-editor").waitFor();
await page.locator(".line-history").waitFor();
await page.evaluate(() => window.removeGit());
await page.locator(".line-history").waitFor({ state: "hidden" });
await editorLayout().press("End");
await page.getByRole("button", { name: "Hide outline", exact: true }).click();
await page.setViewportSize({ width: 760, height: 640 });
for (const theme of ["dark", "light"]) {
await setTheme(theme);
const dimensions = await page.locator(".header-left .icon-btn").evaluateAll(els => els.map(el => ({ width: el.getBoundingClientRect().width, svg: el.querySelector("svg").getBoundingClientRect().width })));
assert.ok(dimensions.every(size => size.width >= 28 && size.svg >= 16), JSON.stringify(dimensions));
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth));
await page.screenshot({ path: path.join(output, `narrow-${theme}.png`) });
}
assert.deepEqual(errors,[]);
console.log('PASS: pane-aligned ribbon, compact square tables, focus-only tree border, joined tabs, Writer/Read hover marker, Git line slot lifecycle, both themes and narrow width');
} finally {await browser.close();}
console.log("PASS: pane-aligned ribbon, compact square tables, focus-only tree border, joined tabs, Writer/Read hover marker, Git line slot lifecycle, both themes and narrow width");
}, { timeout: 30000 });
@@ -0,0 +1,49 @@
// The empty tab background image: set it in Settings, keep it after a reload, remove it, and leave Reset background disabled.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
const name = "appearance/newTabBackground";
await runSmoke(name, async ({ browser }) => {
const output = await outputDir(name);
// The settings window changes the main window through shared localStorage and IndexedDB, so both pages need one context.
const context = await browser.newContext({ viewport: { width: 1200, height: 850 } });
await mockTauri(context, {
commands: test => ({
...test.workspace({ root: "C:\\new-tab-background", files: { "a.md": "# Note\n\nOriginal text." } }),
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
spelling_menu_install: () => null,
}),
});
const page = await openPage(context);
await page.goto(smokeUrl);
await page.locator('[data-tree-rel="a.md"]').waitFor();
await page.getByRole("button", { name: "New tab (Ctrl T)", exact: true }).click();
await page.locator(".empty").waitFor();
const settings = await openPage(context);
await settings.goto(smokeUrl + "/?settingsWindow=true");
await settings.getByRole("button", { name: "Appearance", exact: true }).click();
const png = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=", "base64");
// The image now lives on the work area layer behind the empty tab (src/lib/layout/Workbench.svelte:1258, :1543-1549).
const layer = ".workarea-background";
await settings.getByLabel("Background image file", { exact: true }).setInputFiles({ name: "test.png", mimeType: "image/png", buffer: png });
await page.waitForFunction(layer => getComputedStyle(document.querySelector(layer)).backgroundImage.includes("blob:"), layer);
await page.reload();
await page.locator(".empty").waitFor();
assert.ok(await page.locator(layer).evaluate(node => getComputedStyle(node).backgroundImage.includes("blob:")), "Background survives restart");
await settings.getByRole("button", { name: "Remove image", exact: true }).click();
await page.waitForFunction(layer => getComputedStyle(document.querySelector(layer)).backgroundImage === "none", layer);
for (const mode of ["light", "dark"]) {
await settings.evaluate(async mode => {
const { saveAppearance, parseAppearance, APPEARANCE_KEY } = await import("/src/lib/theme/appearance.ts");
saveAppearance({ ...parseAppearance(localStorage.getItem(APPEARANCE_KEY)), theme: "default", mode });
window.dispatchEvent(new Event("focus"));
}, mode);
await settings.setViewportSize({ width: 650, height: 760 });
await settings.screenshot({ path: path.join(output, `appearance-${mode}-narrow.png`) });
}
assert.equal(await settings.getByRole("button", { name: "Reset background", exact: true }).isDisabled(), true);
await page.waitForFunction(() => !JSON.parse(localStorage.getItem("runestone.appearance")).newTabBackground);
assert.deepEqual([...page.errors, ...settings.errors], []);
console.log("PASS: background image applies, survives a reload, and is removed; Reset background is disabled");
});
+157 -195
View File
@@ -1,206 +1,168 @@
// Run against the development server with an isolated browser storage context.
// Built-in palettes: modes, light-only Sakura, migration, persistence, typography, cross-window sync, Monaco updates, and narrow settings.
import assert from "node:assert/strict";
import { mkdir } from "node:fs/promises";
import { createRequire } from "node:module";
import path from "node:path";
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const 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 = [];
const findings = [];
const output = ".audit";
await mkdir(output, { recursive: true });
try {
await runSmoke("appearance/palettes", async ({ browser }) => {
const output = await outputDir("appearance/palettes");
const context = await browser.newContext({ viewport: { width: 1100, height: 780 } });
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 main = await context.newPage();
const settings = await context.newPage();
const secondSettings = await context.newPage();
for (const page of [main, settings, secondSettings]) {
page.setDefaultTimeout(10000);
page.on("pageerror", error => errors.push(error.message));
}
await main.goto(origin);
await main.getByText("appearance-smoke", { exact: true }).waitFor();
async function openCode(index) {
await main.keyboard.press("Control+p");
await main.getByRole("textbox", { name: "Find a file" }).fill(`theme-${index}.py`);
await main.getByRole("dialog").getByRole("button").filter({ hasText: `theme-${index}.py` }).first().waitFor();
await main.getByRole("textbox", { name: "Find a file" }).press("Enter");
await main.locator(".monaco-editor textarea").waitFor();
await main.waitForFunction(async file => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
return monaco.editor.getEditors().some(editor => editor.getDomNode()?.isConnected && editor.getModel()?.uri.path.endsWith(file));
}, `theme-${index}.py`);
await main.locator(".view-line").filter({ hasText: `Theme sample ${index}` }).waitFor();
}
async function editorIds() {
return main.evaluate(async () => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
return monaco.editor.getEditors().filter(editor => editor.getDomNode()?.isConnected).map(editor => editor.getId());
});
}
async function syntaxColors() {
return main.locator(".view-line span").evaluateAll(spans => Object.fromEntries(["RuneStone", "print", "42"].map(text => {
const span = spans.find(node => !node.children.length && node.textContent.includes(text));
return [text, span ? getComputedStyle(span).color : null];
})));
}
async function waitForSyntax(expected = null) {
await main.waitForFunction(expected => {
const spans = [...document.querySelectorAll(".view-line span")];
const colors = Object.fromEntries(["RuneStone", "print", "42"].map(text => {
const span = spans.find(node => !node.children.length && node.textContent.includes(text));
return [text, span ? getComputedStyle(span).color : null];
}));
return expected ? JSON.stringify(colors) === JSON.stringify(expected) : Object.values(colors).every(Boolean) && new Set(Object.values(colors)).size === 3;
}, expected);
}
const themeName = (theme, mode) => theme === 'sakura' ? 'Sakura' : `${({ default: 'RuneStone', claude: 'Claude' })[theme]} ${mode === 'light' ? 'Light' : 'Dark'}`;
const picker = (page, name) => page.locator('.picker').filter({ has: page.locator('svg') }).and(page.getByRole('button', { name, exact: true }));
async function choose(page, theme, mode) {
await picker(page, 'Color theme').click();
await page.getByRole('menuitemradio', { name: themeName(theme, mode), exact: true }).click();
}
async function openAppearance(page) {
await page.goto(`${origin}/?settingsWindow=true`);
await page.getByRole("button", { name: "Appearance", exact: true }).click();
await picker(page, "Color theme").waitFor();
}
await openCode(0);
await openAppearance(settings);
await openAppearance(secondSettings);
async function expectAppearance(theme, mode) {
for (const page of [settings, secondSettings, main]) {
await page.waitForFunction(({ theme, mode }) => document.documentElement.dataset.palette === theme && document.documentElement.dataset.theme === mode, { theme, mode });
assert.equal(await page.evaluate(() => getComputedStyle(document.documentElement).colorScheme), mode);
const main = await openPage(context);
const settings = await openPage(context);
const secondSettings = await openPage(context);
const pages = [main, settings, secondSettings];
try {
await main.goto(smokeUrl);
await main.getByText("appearance-smoke", { exact: true }).waitFor();
async function openCode(index) {
await main.keyboard.press("Control+p");
await main.getByRole("textbox", { name: "Find a file" }).fill(`theme-${index}.py`);
await main.getByRole("dialog").getByRole("button").filter({ hasText: `theme-${index}.py` }).first().waitFor();
await main.getByRole("textbox", { name: "Find a file" }).press("Enter");
await main.locator(".monaco-editor textarea").waitFor();
await main.waitForFunction(async file => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
return monaco.editor.getEditors().some(editor => editor.getDomNode()?.isConnected && editor.getModel()?.uri.path.endsWith(file));
}, `theme-${index}.py`);
await main.locator(".view-line").filter({ hasText: `Theme sample ${index}` }).waitFor();
}
assert.equal((await picker(secondSettings, "Color theme").textContent()).trim(), themeName(theme, mode));
await main.waitForFunction(() => {
const root = document.documentElement;
const probe = document.createElement("i");
probe.style.backgroundColor = getComputedStyle(root).getPropertyValue("--rs-workarea-editor-bg");
document.body.append(probe);
const expected = getComputedStyle(probe).backgroundColor;
probe.remove();
const surfaces = [...document.querySelectorAll(".monaco-editor .monaco-editor-background")];
const workarea = document.querySelector('.editor > .body');
return surfaces.length > 0 && surfaces.every(element => getComputedStyle(element).backgroundColor === 'rgba(0, 0, 0, 0)')
&& workarea && getComputedStyle(workarea).backgroundColor === expected;
});
return settings.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue("--rs-bg").trim());
}
let nextCode = 1;
const backgrounds = new Set();
for (const theme of ["default", "claude", "sakura"]) {
for (const mode of theme === "sakura" ? ["light"] : ["light", "dark"]) {
const before = await editorIds();
await choose(settings, theme, mode);
backgrounds.add(await expectAppearance(theme, mode));
assert.deepEqual(await editorIds(), before, "Existing Monaco editors keep their identity when a theme changes");
await openCode(nextCode++);
assert.notDeepEqual(await editorIds(), before, "A new file creates a new Monaco editor");
await expectAppearance(theme, mode);
await waitForSyntax();
assert.deepEqual(await settings.evaluate(() => JSON.parse(localStorage.getItem("runestone.appearance"))), { theme, mode });
await settings.screenshot({ path: `${output}/appearance-${theme}-${mode}.png` });
await main.screenshot({ path: `${output}/appearance-editor-${theme}-${mode}.png` });
if (theme === 'sakura') {
const keywordColor = await main.locator('.view-line span').evaluateAll(spans => {
const keyword = spans.find(span => !span.children.length && span.textContent.trim() === 'def');
return keyword ? getComputedStyle(keyword).color : null;
async function editorIds() {
return main.evaluate(async () => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
return monaco.editor.getEditors().filter(editor => editor.getDomNode()?.isConnected).map(editor => editor.getId());
});
}
// Wait until "RuneStone", "print", and "42" have three distinct syntax colors.
async function waitForSyntax() {
await main.waitForFunction(() => {
const spans = [...document.querySelectorAll(".view-line span")];
const colors = ["RuneStone", "print", "42"].map(text => {
const span = spans.find(node => !node.children.length && node.textContent.includes(text));
return span ? getComputedStyle(span).color : null;
});
assert.equal(keywordColor, 'rgb(152, 85, 108)', 'Sakura keywords use Plum Wine');
}
const typography = await settings.evaluate(() => ({
body: getComputedStyle(document.body).fontFamily,
heading: getComputedStyle(document.querySelector('h2')).fontFamily,
prose: getComputedStyle(document.documentElement).getPropertyValue('--rs-font-prose').trim(),
}));
if (theme === 'claude') {
assert.match(typography.body, /Lora.*Georgia/);
assert.match(typography.prose, /Lora.*Georgia/);
assert.match(typography.heading, /Poppins.*Arial/);
assert.equal(await settings.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--rs-accent').trim()), '#d97757');
} else assert.doesNotMatch(typography.body, /Lora|Georgia/);
console.log(`PASS: ${theme} ${mode}, saved state, cross-window selection, existing and new Monaco editors`);
return colors.every(Boolean) && new Set(colors).size === 3;
});
}
}
assert.equal(backgrounds.size, 5, "All supported combinations have distinct backgrounds");
await picker(settings, 'Color theme').click();
assert.deepEqual(await settings.getByRole('menuitemradio').allTextContents(), ['RuneStone Light', 'RuneStone Dark', 'Claude Light', 'Claude Dark', 'Sakura', 'Harvest Moon', 'Crimson Pilot', 'Silver Serpent']);
await settings.keyboard.press('Escape');
assert.equal(await picker(settings, 'Appearance').count(), 0);
assert.equal(await picker(secondSettings, 'Appearance').count(), 0);
const sakura = await settings.evaluate(() => {
const css = getComputedStyle(document.documentElement);
return Object.fromEntries(['bg', 'border', 'selection', 'bg-active', 'syntax-parameter', 'syntax-keyword', 'syntax-local', 'syntax-static', 'syntax-instance', 'syntax-global'].map(key => [key, css.getPropertyValue(`--rs-${key}`).trim()]));
});
assert.deepEqual(sakura, { bg: '#fefcfc', border: '#f8dbe6', selection: '#ffc9dc', 'bg-active': '#dbeacb', 'syntax-parameter': '#cb6b91', 'syntax-keyword': '#98556c', 'syntax-local': '#618c71', 'syntax-static': '#69a2bd', 'syntax-instance': '#607fa9', 'syntax-global': '#687788' });
for (const [theme, savedMode, expectedTheme, mode] of [
['gpt', 'light', 'default', 'light'],
['terminal', 'dark', 'default', 'dark'],
['sakura', 'dark', 'sakura', 'light'],
]) {
await settings.evaluate(value => localStorage.setItem('runestone.appearance', JSON.stringify(value)), { theme, mode: savedMode });
await settings.reload();
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
await expectAppearance(expectedTheme, mode);
assert.deepEqual(await settings.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance'))), { theme: expectedTheme, mode });
console.log(`PASS: saved ${theme} ${savedMode} migrates to ${expectedTheme} ${mode}`);
}
for (const [theme, mode] of [['default', 'dark'], ['claude', 'light'], ['claude', 'dark'], ['sakura', 'light']]) {
await settings.setViewportSize({ width: 1100, height: 780 });
await choose(settings, theme, mode);
await expectAppearance(theme, mode);
await settings.setViewportSize({ width: 360, height: 480 });
assert(await settings.evaluate(() => document.documentElement.scrollWidth <= innerWidth), 'Narrow settings do not overflow the viewport');
const content = settings.locator('dialog .content');
assert(await content.evaluate(node => node.scrollWidth <= node.clientWidth), 'Appearance controls do not overflow the content area');
for (const name of ['Color theme']) {
const control = picker(settings, name);
const themeName = (theme, mode) => theme === "sakura" ? "Sakura" : `${({ default: "RuneStone", claude: "Claude" })[theme]} ${mode === "light" ? "Light" : "Dark"}`;
const picker = (page, name) => page.locator(".picker").filter({ has: page.locator("svg") }).and(page.getByRole("button", { name, exact: true }));
async function choose(page, theme, mode) {
await picker(page, "Color theme").click();
await page.getByRole("menuitemradio", { name: themeName(theme, mode), exact: true }).click();
}
async function openAppearance(page) {
await page.goto(`${smokeUrl}/?settingsWindow=true`);
await page.getByRole("button", { name: "Appearance", exact: true }).click();
await picker(page, "Color theme").waitFor();
}
await openCode(0);
await openAppearance(settings);
await openAppearance(secondSettings);
async function expectAppearance(theme, mode) {
for (const page of [settings, secondSettings, main]) {
await page.waitForFunction(({ theme, mode }) => document.documentElement.dataset.palette === theme && document.documentElement.dataset.theme === mode, { theme, mode });
assert.equal(await page.evaluate(() => getComputedStyle(document.documentElement).colorScheme), mode);
}
assert.equal((await picker(secondSettings, "Color theme").textContent()).trim(), themeName(theme, mode));
await main.waitForFunction(() => {
const root = document.documentElement;
const probe = document.createElement("i");
probe.style.backgroundColor = getComputedStyle(root).getPropertyValue("--rs-workarea-editor-bg");
document.body.append(probe);
const expected = getComputedStyle(probe).backgroundColor;
probe.remove();
const surfaces = [...document.querySelectorAll(".monaco-editor .monaco-editor-background")];
const workarea = document.querySelector(".editor > .body");
return surfaces.length > 0 && surfaces.every(element => getComputedStyle(element).backgroundColor === "rgba(0, 0, 0, 0)")
&& workarea && getComputedStyle(workarea).backgroundColor === expected;
});
return settings.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue("--rs-bg").trim());
}
let nextCode = 1;
const backgrounds = new Set();
for (const theme of ["default", "claude", "sakura"]) {
for (const mode of theme === "sakura" ? ["light"] : ["light", "dark"]) {
const before = await editorIds();
await choose(settings, theme, mode);
backgrounds.add(await expectAppearance(theme, mode));
assert.deepEqual(await editorIds(), before, "Existing Monaco editors keep their identity when a theme changes");
await openCode(nextCode++);
assert.notDeepEqual(await editorIds(), before, "A new file creates a new Monaco editor");
await expectAppearance(theme, mode);
await waitForSyntax();
assert.deepEqual(await settings.evaluate(() => JSON.parse(localStorage.getItem("runestone.appearance"))), { theme, mode });
await settings.screenshot({ path: path.join(output, `appearance-${theme}-${mode}.png`) });
await main.screenshot({ path: path.join(output, `appearance-editor-${theme}-${mode}.png`) });
if (theme === "sakura") {
const keywordColor = await main.locator(".view-line span").evaluateAll(spans => {
const keyword = spans.find(span => !span.children.length && span.textContent.trim() === "def");
return keyword ? getComputedStyle(keyword).color : null;
});
assert.equal(keywordColor, "rgb(152, 85, 108)", "Sakura keywords use Plum Wine");
}
const typography = await settings.evaluate(() => ({
body: getComputedStyle(document.body).fontFamily,
heading: getComputedStyle(document.querySelector("h2")).fontFamily,
prose: getComputedStyle(document.documentElement).getPropertyValue("--rs-font-prose").trim(),
}));
if (theme === "claude") {
assert.match(typography.body, /Lora.*Georgia/);
assert.match(typography.prose, /Lora.*Georgia/);
assert.match(typography.heading, /Poppins.*Arial/);
assert.equal(await settings.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue("--rs-accent").trim()), "#d97757");
} else assert.doesNotMatch(typography.body, /Lora|Georgia/);
console.log(`PASS: ${theme} ${mode}, saved state, cross-window selection, existing and new Monaco editors`);
}
}
assert.equal(backgrounds.size, 5, "All supported combinations have distinct backgrounds");
await picker(settings, "Color theme").click();
assert.deepEqual(await settings.getByRole("menuitemradio").allTextContents(), ["RuneStone Light", "RuneStone Dark", "Claude Light", "Claude Dark", "Sakura", "Harvest Moon", "Crimson Pilot", "Silver Serpent"]);
await settings.keyboard.press("Escape");
assert.equal(await picker(settings, "Appearance").count(), 0);
assert.equal(await picker(secondSettings, "Appearance").count(), 0);
const sakura = await settings.evaluate(() => {
const css = getComputedStyle(document.documentElement);
return Object.fromEntries(["bg", "border", "selection", "bg-active", "syntax-parameter", "syntax-keyword", "syntax-local", "syntax-static", "syntax-instance", "syntax-global"].map(key => [key, css.getPropertyValue(`--rs-${key}`).trim()]));
});
// The applied selection color caps its alpha at a6 so text backgrounds show through (src/lib/theme/appearance.ts:197-203).
assert.deepEqual(sakura, { bg: "#fefcfc", border: "#f8dbe6", selection: "#ffc9dca6", "bg-active": "#dbeacb", "syntax-parameter": "#cb6b91", "syntax-keyword": "#98556c", "syntax-local": "#618c71", "syntax-static": "#69a2bd", "syntax-instance": "#607fa9", "syntax-global": "#687788" });
for (const [theme, savedMode, expectedTheme, mode] of [
["gpt", "light", "default", "light"],
["terminal", "dark", "default", "dark"],
["sakura", "dark", "sakura", "light"],
]) {
await settings.evaluate(value => localStorage.setItem("runestone.appearance", JSON.stringify(value)), { theme, mode: savedMode });
await settings.reload();
await settings.getByRole("button", { name: "Appearance", exact: true }).click();
await expectAppearance(expectedTheme, mode);
assert.deepEqual(await settings.evaluate(() => JSON.parse(localStorage.getItem("runestone.appearance"))), { theme: expectedTheme, mode });
console.log(`PASS: saved ${theme} ${savedMode} migrates to ${expectedTheme} ${mode}`);
}
for (const [theme, mode] of [["default", "dark"], ["claude", "light"], ["claude", "dark"], ["sakura", "light"]]) {
await settings.setViewportSize({ width: 1100, height: 780 });
await choose(settings, theme, mode);
await expectAppearance(theme, mode);
await settings.setViewportSize({ width: 360, height: 480 });
assert(await settings.evaluate(() => document.documentElement.scrollWidth <= innerWidth), "Narrow settings do not overflow the viewport");
assert(await settings.locator("dialog .content").evaluate(node => node.scrollWidth <= node.clientWidth), "Appearance controls do not overflow the content area");
const control = picker(settings, "Color theme");
await control.scrollIntoViewIfNeeded();
const bounds = await control.boundingBox();
assert(bounds.x >= 0 && bounds.x + bounds.width <= 360 && bounds.height >= 28, `${name} remains reachable at 360px`);
assert(bounds.x >= 0 && bounds.x + bounds.width <= 360 && bounds.height >= 28, "Color theme remains reachable at 360px");
await settings.screenshot({ path: path.join(output, `appearance-${theme}-${mode}-360.png`) });
}
await settings.screenshot({ path: `${output}/appearance-${theme}-${mode}-360.png` });
assert.deepEqual(pages.flatMap(page => page.errors), []);
} catch (error) {
for (const [index, page] of pages.entries()) await page.screenshot({ path: path.join(output, `appearance-failure-${index}.png`) }).catch(() => {});
throw error;
}
assert.deepEqual(errors, []);
assert.deepEqual(findings, [], 'Appearance findings');
await context.close();
console.log('Appearance smoke passed: supported palettes, modes, light-only Sakura, migration, persistence, typography, cross-window sync, Monaco updates, and narrow settings.');
} catch (error) {
console.error('Browser errors:', errors);
for (const [index, page] of browser.contexts().flatMap(context => context.pages()).entries()) {
await page.screenshot({ path: `${output}/appearance-failure-${index}.png` }).catch(() => {});
}
throw error;
} finally { await browser.close(); }
});
@@ -0,0 +1,31 @@
// Export theme template in Settings > Appearance: success, cancel, and an export error.
import assert from "node:assert/strict";
import { mockTauri, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("appearance/themeExport", async ({ page }) => {
await mockTauri(page, {
state: { exportResult: "C:\\exports\\my-theme.json", exportError: "" },
commands: test => ({
...test.workspace({ root: "C:\\theme-export" }),
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
theme_export: () => {
if (test.state.exportError) throw new Error(test.state.exportError);
return test.state.exportResult;
},
}),
});
const exportButton = page.getByRole("button", { name: "Export theme template" });
await page.goto(smokeUrl + "/?settingsWindow=true");
await page.getByRole("button", { name: "Appearance", exact: true }).click();
await exportButton.click();
await page.getByRole("status").filter({ hasText: "Theme saved to" }).waitFor();
// Exported templates use theme schema 2 (src/lib/theme/appearance.ts:90).
assert.equal(await page.evaluate(() => JSON.parse(window.__TEST__.calls.find(call => call.command === "theme_export").args.contents).schema), 2);
await page.evaluate(() => { window.__TEST__.state.exportResult = null; });
await exportButton.click();
await page.getByText("Export canceled.", { exact: true }).waitFor();
await page.evaluate(() => { window.__TEST__.state.exportError = "Disk is full"; });
await exportButton.click();
await page.getByRole("alert").filter({ hasText: "Disk is full" }).waitFor();
console.log("PASS: theme export success, cancel, and error");
}, { viewport: { width: 1200, height: 850 } });
@@ -0,0 +1,33 @@
// Import a custom theme JSON in Settings > Appearance; its dark and light backgrounds apply.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
const name = "appearance/themeImport";
await runSmoke(name, async ({ page }) => {
const output = await outputDir(name);
await mockTauri(page, {
commands: test => ({
...test.workspace({ root: "C:\\theme-import", files: { "a.md": "# Alpha\n" } }),
plugins_snapshot: () => ({ plugins: [], issues: [] }),
}),
});
await page.goto(smokeUrl + "/?settingsWindow=true");
await page.getByRole("button", { name: "Appearance", exact: true }).click();
const theme = { schema: 1, id: "smoke", name: "Smoke theme", light: { bg: "#fefefe", text: "#222222", accent: "#334499" }, dark: { bg: "#181820", text: "#eeeeee", accent: "#aabbff" } };
const importTheme = () => page.locator('input[type=file][aria-label="Theme JSON file"]').setInputFiles({ name: "smoke.json", mimeType: "application/json", buffer: Buffer.from(JSON.stringify(theme)) });
const background = () => page.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue("--rs-bg").trim());
await importTheme();
await page.waitForFunction(() => document.documentElement.dataset.palette === "custom:smoke");
assert.equal(await background(), "#181820");
// A custom theme now keeps one palette. A schema 1 file converts with the current mode (src/lib/theme/customThemes.ts:38,
// src/lib/theme/AppearanceSettings.svelte:70), and the light/dark select became the Color theme menu (AppearanceSettings.svelte:20-31, :113).
await page.getByRole("button", { name: "Color theme", exact: true }).click();
await page.getByRole("menuitemradio", { name: "RuneStone Light", exact: true }).click();
await page.waitForFunction(() => document.documentElement.dataset.palette !== "custom:smoke");
await importTheme();
await page.waitForFunction(() => document.documentElement.dataset.palette === "custom:smoke");
assert.equal(await background(), "#fefefe");
await page.screenshot({ path: path.join(output, "custom-theme-light.png") });
console.log("PASS: custom theme import applies its dark and light backgrounds");
}, { timeout: 15000 });
+58 -74
View File
@@ -1,100 +1,84 @@
// Theme variants: transparency slider in eight variants, custom theme fonts, a single tooltip, and slideshow command icons.
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/host-ui', { recursive: true });
try {
import path from 'node:path';
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
await runSmoke('appearance/themeVariants', async ({ browser }) => {
const output = await outputDir('appearance/themeVariants');
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 page = await context.newPage();
page.on('pageerror', error => errors.push(error.message));
await page.goto(`${origin}/?settingsWindow=true`);
const page = await openPage(context);
await page.goto(`${smokeUrl}/?settingsWindow=true`);
await page.getByRole('button', { name: 'Appearance', exact: true }).click();
for (const [theme, mode] of [['default','dark'],['default','light'],['claude','dark'],['claude','light'],['sakura','light'],['harvest-moon','dark'],['crimson-pilot','dark'],['silver-serpent','dark']]) {
await page.evaluate(async ({theme,mode}) => {
(await import('/src/lib/theme/appearance.ts')).saveAppearance({theme,mode,transparency:{enabled:true,amount:18}});
const transparent = page.getByRole('switch', { name: 'Transparent surfaces', exact: true });
for (const [theme, mode] of [['default', 'dark'], ['default', 'light'], ['claude', 'dark'], ['claude', 'light'], ['sakura', 'light'], ['harvest-moon', 'dark'], ['crimson-pilot', 'dark'], ['silver-serpent', 'dark']]) {
await page.evaluate(async ({ theme, mode }) => {
(await import('/src/lib/theme/appearance.ts')).saveAppearance({ theme, mode, transparency: { enabled: true, amount: 18 } });
window.dispatchEvent(new Event('focus'));
},{theme,mode});
}, { theme, mode });
const slider = page.locator('#surface-transparency');
await slider.fill('100');
assert.equal(await page.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance')).transparency.amount),100);
await slider.focus(); await page.keyboard.press('Home'); assert.equal(await slider.inputValue(),'0');
await page.keyboard.press('End'); assert.equal(await slider.inputValue(),'100');
await page.screenshot({path:`.audit/host-ui/${theme}-${mode}-slider-focus.png`});
await page.getByRole('switch',{name:'Transparent surfaces',exact:true}).uncheck();
assert.equal(await page.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance')).transparency.amount), 100);
await slider.focus(); await page.keyboard.press('Home'); assert.equal(await slider.inputValue(), '0');
await page.keyboard.press('End'); assert.equal(await slider.inputValue(), '100');
await page.screenshot({ path: path.join(output, `${theme}-${mode}-slider-focus.png`) });
await transparent.uncheck();
assert(await slider.isDisabled());
await page.screenshot({path:`.audit/host-ui/${theme}-${mode}-slider-disabled.png`});
await page.getByRole('switch',{name:'Transparent surfaces',exact:true}).check();
await page.setViewportSize({width:360,height:740}); await slider.scrollIntoViewIfNeeded();
await page.screenshot({ path: path.join(output, `${theme}-${mode}-slider-disabled.png`) });
await transparent.check();
await page.setViewportSize({ width: 360, height: 740 }); await slider.scrollIntoViewIfNeeded();
assert(await page.locator('.content').evaluate(node => node.scrollWidth <= node.clientWidth));
await page.screenshot({path:`.audit/host-ui/${theme}-${mode}-narrow.png`});
await page.setViewportSize({width:1100,height:800});
await page.screenshot({ path: path.join(output, `${theme}-${mode}-narrow.png`) });
await page.setViewportSize({ width: 1100, height: 800 });
}
await page.evaluate(async () => {
const {installTheme} = await import('/src/lib/theme/customThemes.ts');
const {saveAppearance,exportAppearanceTheme} = await import('/src/lib/theme/appearance.ts');
const theme = exportAppearanceTheme('default'); theme.fonts = {ui:'Arial, sans-serif',prose:'Georgia, serif',heading:'Georgia, serif',mono:'Consolas, monospace'};
installTheme(theme); saveAppearance({theme:'custom:my-theme',mode:'dark'}); window.dispatchEvent(new Event('focus'));
const { installTheme } = await import('/src/lib/theme/customThemes.ts');
const { saveAppearance, exportAppearanceTheme } = await import('/src/lib/theme/appearance.ts');
const theme = exportAppearanceTheme('default'); theme.fonts = { ui: 'Arial, sans-serif', prose: 'Georgia, serif', heading: 'Georgia, serif', mono: 'Consolas, monospace' };
installTheme(theme); saveAppearance({ theme: 'custom:my-theme', mode: 'dark' }); window.dispatchEvent(new Event('focus'));
});
assert.match(await page.locator('.preview-prose').evaluate(node => getComputedStyle(node).fontFamily),/Georgia/);
assert.match(await page.evaluate(async () => (await import('/src/lib/theme/appearance.ts')).exportAppearanceTheme('custom:my-theme').fonts.ui),/Arial/);
await page.screenshot({path:'.audit/host-ui/custom-fonts.png'});
const main = await context.newPage(); await main.goto(origin);
assert.match(await page.locator('.preview-prose').evaluate(node => getComputedStyle(node).fontFamily), /Georgia/);
assert.match(await page.evaluate(async () => (await import('/src/lib/theme/appearance.ts')).exportAppearanceTheme('custom:my-theme').fonts.ui), /Arial/);
await page.screenshot({ path: path.join(output, 'custom-fonts.png') });
const main = await openPage(context); await main.goto(smokeUrl);
await main.bringToFront();
await main.getByRole('button',{name:'Files',exact:true}).waitFor();
await main.getByRole('button', { name: 'Files', exact: true }).waitFor();
await main.evaluate(async () => {
const loaded = performance.getEntriesByType('resource').map(entry => entry.name).find(name => new URL(name).pathname === '/src/lib/plugins/external.ts');
const {pluginTools,refreshPlugins} = await import(loaded || '/src/lib/plugins/external.ts');
const { pluginTools, refreshPlugins } = await import(loaded || '/src/lib/plugins/external.ts');
await refreshPlugins();
const invoke = window.__TAURI_INTERNALS__.invoke;
window.__TAURI_INTERNALS__.invoke = (command,args) => command === 'plugins_snapshot' ? Promise.resolve(null) : invoke(command,args);
const commands = [{owner:'runestone.background-slideshow',id:'next-image',title:'Next background image',kind:'command',surface:'commands',icon:'skip-forward'},{owner:'runestone.background-slideshow',id:'pause-resume',title:'Pause or resume background slideshow',kind:'command',surface:'commands',icon:'pause'}];
window.__TAURI_INTERNALS__.invoke = (command, args) => command === 'plugins_snapshot' ? Promise.resolve(null) : invoke(command, args);
const commands = [{ owner: 'runestone.background-slideshow', id: 'next-image', title: 'Next background image', kind: 'command', surface: 'commands', icon: 'skip-forward' }, { owner: 'runestone.background-slideshow', id: 'pause-resume', title: 'Pause or resume background slideshow', kind: 'command', surface: 'commands', icon: 'pause' }];
pluginTools.set(commands);
});
for (const mode of ['dark','light']) {
await main.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({theme:'default',mode}),mode);
const button = main.getByRole('button',{name:'Commands',exact:true});
assert.equal(await button.getAttribute('title'),null);
const visibleTooltips = () => main.locator('[role=tooltip]:visible').count();
for (const mode of ['dark', 'light']) {
await main.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({ theme: 'default', mode }), mode);
const button = main.getByRole('button', { name: 'Commands', exact: true });
assert.equal(await button.getAttribute('title'), null);
await button.hover(); await main.waitForTimeout(1100);
assert.equal(await main.locator('[role=tooltip]:visible').count(),1);
await main.screenshot({path:`.audit/host-ui/${mode}-single-tooltip.png`});
await main.keyboard.press('Escape'); assert.equal(await main.locator('[role=tooltip]:visible').count(),0);
await main.mouse.move(400,400);
assert.equal(await visibleTooltips(), 1);
await main.screenshot({ path: path.join(output, `${mode}-single-tooltip.png`) });
await main.keyboard.press('Escape'); assert.equal(await visibleTooltips(), 0);
await main.mouse.move(400, 400);
await button.evaluate(node => node.blur());
await button.focus(); await main.waitForTimeout(600); assert.equal(await main.locator('[role=tooltip]:visible').count(),1);
await button.focus(); await main.waitForTimeout(600); assert.equal(await visibleTooltips(), 1);
await button.click(); await main.getByRole('menu').waitFor();
const paths = await main.locator('.rs-menu svg').evaluateAll(nodes => nodes.map(node => node.innerHTML));
assert(paths.some(path => path.includes('M7 4v16'))); assert(paths.some(path => path.includes('m4 4 12 8')));
await main.screenshot({path:`.audit/host-ui/${mode}-slideshow-command-icons.png`}); await main.keyboard.press('Escape');
await main.screenshot({ path: path.join(output, `${mode}-slideshow-command-icons.png`) }); await main.keyboard.press('Escape');
}
assert.deepEqual(errors,[]);
assert.deepEqual([...page.errors, ...main.errors], []);
console.log('PASS: eight theme variants, slider endpoints, persistence, disabled states, narrow layout, font import/export, single tooltip, and command icons.');
} finally { await browser.close(); }
});
@@ -0,0 +1,53 @@
// Shared tooltips (attachTooltip) in both themes: no title attribute, rounded corners, Escape and focus, and placement inside a narrow window.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
const name = "appearance/tooltipPlacement";
await runSmoke(name, async ({ browser }) => {
const output = await outputDir(name);
for (const theme of ["light", "dark"]) {
const page = await openPage(browser, { viewport: { width: 1100, height: 780 } });
await mockTauri(page, {
commands: test => ({
...test.workspace({ root: "C:\\tooltip-placement", files: { "sample.md": "# Tooltip sample\n" } }),
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
}),
});
await page.goto(smokeUrl);
await page.getByText("tooltip-placement", { exact: true }).waitFor();
await page.evaluate(async theme => {
const { saveAppearance } = await import("/src/lib/theme/appearance.ts");
saveAppearance({ theme: "default", mode: theme });
const { attachTooltip } = await import("/src/lib/ui/tooltip.ts");
const cell = document.createElement("button");
cell.id = "tooltip-test";
cell.textContent = "Formula cell";
Object.assign(cell.style, { position: "fixed", left: "20px", top: "100px", zIndex: "2000" });
document.body.append(cell);
window.disposeTip = attachTooltip(cell, () => "B6 · Click to edit · Type = for a formula");
}, theme);
const target = page.locator("#tooltip-test");
const tooltip = page.locator(".rs-tooltip:popover-open");
await target.hover();
await tooltip.waitFor();
assert.equal(await target.getAttribute("title"), null);
assert.equal(await tooltip.evaluate(node => getComputedStyle(node).borderRadius), "5px");
await page.screenshot({ path: path.join(output, `${theme}-tooltip.png`) });
await page.keyboard.press("Escape");
assert.equal(await page.locator(".rs-tooltip:popover-open").count(), 0);
await target.focus();
await tooltip.waitFor();
await page.setViewportSize({ width: 390, height: 620 });
await page.locator("header").first().hover();
await target.hover();
await tooltip.waitFor();
const bounds = await tooltip.boundingBox();
assert(bounds.x >= 8 && bounds.x + bounds.width <= 382);
await page.screenshot({ path: path.join(output, `${theme}-narrow-tooltip.png`) });
await page.evaluate(() => { window.disposeTip(); document.getElementById("tooltip-test").remove(); });
assert.deepEqual(page.errors, []);
await page.close();
console.log(`PASS: ${theme} tooltip`);
}
});
@@ -1,166 +1,116 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
// Tab tooltips, translucent text selection, zero-transparency backgrounds, a stable transparency slider, and the themed install checkbox.
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 page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
await mkdir(".audit", { recursive: true });
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === 'plugin:window|is_maximized') return false;
if (command === 'plugins_snapshot') return { root: 'C:/theme-test-plugins', plugins: [] };
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "spelling_menu_install") return;
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
try {
await mkdir('output/october15-appearance', { recursive: true });
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await page.getByText('smoke-workspace', { exact: true }).waitFor();
await page.keyboard.press('Control+p');
await page.getByRole('textbox', { name: 'Find a file' }).fill('welcome.md');
await page.getByRole('dialog').getByRole('button').filter({ hasText: 'welcome.md' }).first().click();
await page.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
for (const mode of ['dark', 'light']) {
await page.evaluate(async mode => {
const { saveAppearance } = await import('/src/lib/theme/appearance.ts');
saveAppearance({ theme: 'default', mode, transparency: { enabled: true, amount: 0 }, newTabBackground: { image: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=' } });
}, mode);
const tab = page.getByRole('tab', { name: /welcome\.md/ });
assert.equal(await tab.getAttribute('title'), null);
await page.mouse.move(600, 600);
await tab.hover();
await page.locator('.rs-tooltip:popover-open').waitFor();
assert.match(await page.locator('.rs-tooltip:popover-open').innerText(), /welcome\.md/);
await page.screenshot({ path: `output/october15-appearance/${mode}-tab-tooltip.png` });
await page.keyboard.press('Escape');
assert.equal(await page.locator('.rs-tooltip:popover-open').count(), 0);
await tab.focus();
await page.locator('.rs-tooltip:popover-open').waitFor();
await page.keyboard.press('Escape');
const writer = page.getByRole('textbox', { name: 'Writing editor', exact: true });
await writer.click(); await page.keyboard.press('Control+a');
const colors = await writer.evaluate(node => {
const root = getComputedStyle(document.documentElement);
return { selection: root.getPropertyValue('--rs-selection'), bg: getComputedStyle(node, '::selection').backgroundColor,
text: getComputedStyle(node).color, image: root.getPropertyValue('--rs-new-tab-image'), pluginBg: root.getPropertyValue('--rs-workarea-plugin-bg') };
});
assert.match(colors.selection.trim(), /^#[0-9a-f]{6}a6$/i);
assert.match(colors.bg, /0\.65/);
assert.notEqual(colors.image.trim(), 'none');
assert.equal(colors.pluginBg.trim(), 'transparent');
console.log(mode, colors);
await page.screenshot({ path: `output/october15-appearance/${mode}-selection.png` });
await page.getByRole('button', { name: 'New tab (Ctrl T)', exact: true }).click();
await page.locator('.empty').waitFor();
await page.screenshot({ path: `output/october15-appearance/${mode}-zero-background.png` });
await page.getByRole('tab', { name: /welcome\.md/ }).click();
}
await page.goto((process.env.SMOKE_URL || 'http://127.0.0.1:1420') + '/?settingsWindow=true');
await page.getByRole('button', { name: 'Appearance', exact: true }).click();
for (const mode of ['dark', 'light']) {
await page.evaluate(async mode => {
(await import('/src/lib/theme/appearance.ts')).saveAppearance({ theme: 'default', mode });
window.dispatchEvent(new Event('focus'));
}, mode);
const slider = page.locator('#surface-transparency');
for (const width of [1100, 390]) {
await page.setViewportSize({ width, height: 800 });
await slider.fill('0'); const zero = await slider.boundingBox();
for (const amount of ['1', '9', '11', '18', '99', '100']) {
await slider.fill(amount); const current = await slider.boundingBox();
assert.equal(current.x, zero.x); assert.equal(current.width, zero.width);
}
await page.screenshot({ path: `output/october15-appearance/${mode}-${width}-slider.png` });
}
}
await page.evaluate(() => {
const invoke = window.__TAURI_INTERNALS__.invoke;
window.__TAURI_INTERNALS__.invoke = (command, args) => command === 'plugins_choose'
? Promise.resolve([{ token: 'theme-test', source: 'C:/Downloads/example.zip', error: null,
manifest: { id: 'example', name: 'Theme example', version: '0.1.0', description: 'Theme control test', author: 'RuneStone', entry: 'main.js' } }])
: invoke(command, args);
await runSmoke("appearance/tooltipsAndSelection", async ({ page }) => {
const output = await outputDir("appearance/tooltipsAndSelection");
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
await mockTauri(page, {
commands: test => ({
...test.workspace({
root: "C:\\smoke-workspace",
writeEvents: true,
files: {
"notes/welcome.md": "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n",
"notes/second.md": "# Second note\n",
"src/hello.py": "print('hello')\n",
},
}),
plugins_snapshot: () => ({ root: "C:/theme-test-plugins", plugins: [] }),
"plugin:window|is_maximized": () => false,
spelling_menu_install: () => null,
}),
});
await page.getByRole('button', { name: 'Plug-ins', exact: true }).click();
for (const [theme, mode] of [['harvest-moon', 'dark'], ['default', 'light']]) {
await page.evaluate(async ({ theme, mode }) => {
(await import('/src/lib/theme/appearance.ts')).saveAppearance({ theme, mode }); window.dispatchEvent(new Event('focus'));
}, { theme, mode });
await page.getByRole('button', { name: 'Install plugin ZIP', exact: true }).click();
const checkbox = page.getByRole('checkbox', { name: 'Theme example', exact: true });
await checkbox.waitFor();
assert.equal(await checkbox.evaluate(node => getComputedStyle(node).accentColor), await page.evaluate(() => {
const probe = document.createElement('span'); probe.style.color = 'var(--rs-accent)'; document.body.append(probe);
const color = getComputedStyle(probe).color; probe.remove(); return color;
}));
await checkbox.focus();
await page.screenshot({ path: `output/october15-appearance/${theme}-${mode}-install-checkbox.png` });
await page.getByRole('button', { name: 'Cancel', exact: true }).click();
const tooltip = page.locator(".rs-tooltip:popover-open");
try {
await page.goto(smokeUrl);
await page.getByText("smoke-workspace", { exact: true }).waitFor();
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill("welcome.md");
await page.getByRole("dialog").getByRole("button").filter({ hasText: "welcome.md" }).first().click();
await page.getByRole("textbox", { name: "Writing editor", exact: true }).waitFor();
for (const mode of ["dark", "light"]) {
await page.evaluate(async mode => {
const { saveAppearance } = await import("/src/lib/theme/appearance.ts");
saveAppearance({ theme: "default", mode, transparency: { enabled: true, amount: 0 }, newTabBackground: { image: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=" } });
}, mode);
const tab = page.getByRole("tab", { name: /welcome\.md/ });
assert.equal(await tab.getAttribute("title"), null);
await page.mouse.move(600, 600);
await tab.hover();
await tooltip.waitFor();
assert.match(await tooltip.innerText(), /welcome\.md/);
await page.screenshot({ path: path.join(output, `${mode}-tab-tooltip.png`) });
await page.keyboard.press("Escape");
assert.equal(await tooltip.count(), 0);
await tab.focus();
await tooltip.waitFor();
await page.keyboard.press("Escape");
const writer = page.getByRole("textbox", { name: "Writing editor", exact: true });
await writer.click(); await page.keyboard.press("Control+a");
const colors = await writer.evaluate(node => {
const root = getComputedStyle(document.documentElement);
return { selection: root.getPropertyValue("--rs-selection"), bg: getComputedStyle(node, "::selection").backgroundColor,
text: getComputedStyle(node).color, image: root.getPropertyValue("--rs-new-tab-image"), pluginBg: root.getPropertyValue("--rs-workarea-plugin-bg") };
});
assert.match(colors.selection.trim(), /^#[0-9a-f]{6}a6$/i);
assert.match(colors.bg, /0\.65/);
assert.notEqual(colors.image.trim(), "none");
assert.equal(colors.pluginBg.trim(), "transparent");
console.log(mode, colors);
await page.screenshot({ path: path.join(output, `${mode}-selection.png`) });
await page.getByRole("button", { name: "New tab (Ctrl T)", exact: true }).click();
await page.locator(".empty").waitFor();
await page.screenshot({ path: path.join(output, `${mode}-zero-background.png`) });
await page.getByRole("tab", { name: /welcome\.md/ }).click();
}
await page.goto(`${smokeUrl}/?settingsWindow=true`);
await page.getByRole("button", { name: "Appearance", exact: true }).click();
for (const mode of ["dark", "light"]) {
await page.evaluate(async mode => {
(await import("/src/lib/theme/appearance.ts")).saveAppearance({ theme: "default", mode });
window.dispatchEvent(new Event("focus"));
}, mode);
const slider = page.locator("#surface-transparency");
for (const width of [1100, 390]) {
await page.setViewportSize({ width, height: 800 });
await slider.fill("0"); const zero = await slider.boundingBox();
for (const amount of ["1", "9", "11", "18", "99", "100"]) {
await slider.fill(amount); const current = await slider.boundingBox();
assert.equal(current.x, zero.x); assert.equal(current.width, zero.width);
}
await page.screenshot({ path: path.join(output, `${mode}-${width}-slider.png`) });
}
}
await page.evaluate(() => {
const invoke = window.__TAURI_INTERNALS__.invoke;
window.__TAURI_INTERNALS__.invoke = (command, args) => command === "plugins_choose"
? Promise.resolve([{ token: "theme-test", source: "C:/Downloads/example.zip", error: null,
manifest: { id: "example", name: "Theme example", version: "0.1.0", description: "Theme control test", author: "RuneStone", entry: "main.js" } }])
: invoke(command, args);
});
await page.getByRole("button", { name: "Plug-ins", exact: true }).click();
for (const [theme, mode] of [["harvest-moon", "dark"], ["default", "light"]]) {
await page.evaluate(async ({ theme, mode }) => {
(await import("/src/lib/theme/appearance.ts")).saveAppearance({ theme, mode }); window.dispatchEvent(new Event("focus"));
}, { theme, mode });
await page.getByRole("button", { name: "Install plugin ZIP", exact: true }).click();
const checkbox = page.getByRole("checkbox", { name: "Theme example", exact: true });
await checkbox.waitFor();
assert.equal(await checkbox.evaluate(node => getComputedStyle(node).accentColor), await page.evaluate(() => {
const probe = document.createElement("span"); probe.style.color = "var(--rs-accent)"; document.body.append(probe);
const color = getComputedStyle(probe).color; probe.remove(); return color;
}));
await checkbox.focus();
await page.screenshot({ path: path.join(output, `${theme}-${mode}-install-checkbox.png`) });
await page.getByRole("button", { name: "Cancel", exact: true }).click();
}
console.log("PASS: exact tab tooltips, translucent text selection, retained zero-transparency background, stable slider, themed installation checkbox.");
} catch (error) {
await page.screenshot({ path: path.join(output, "failure.png") });
throw error;
}
assert.deepEqual(errors, []);
console.log('PASS: exact tab tooltips, translucent text selection, retained zero-transparency background, stable slider, themed installation checkbox.');
} catch (error) {
await page.screenshot({ path: 'output/october15-appearance/failure.png' });
throw error;
} finally { await browser.close(); }
});
+44 -54
View File
@@ -1,48 +1,37 @@
// Character theme typography: CSS families and the fonts Chromium renders for UI, prose, headings, and code, plus narrow settings.
import assert from 'node:assert/strict';
import { mkdir, writeFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
import { writeFile } from 'node:fs/promises';
import path from 'node:path';
import { mockTauri, openPage, outputDir, runSmoke, settle, smokeUrl } from '../_harness/index.mjs';
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || 'playwright');
const origin = process.env.SMOKE_URL || 'http://127.0.0.1:1420';
const output = '.audit/theme-typography';
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const errors = [];
const report = [];
await mkdir(output, { recursive: true });
try {
await runSmoke('appearance/typography', async ({ browser }) => {
const output = await outputDir('appearance/typography');
const report = [];
const context = await browser.newContext({ viewport: { width: 1100, height: 780 } });
await context.addInitScript(() => {
window.isTauri = true;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
transformCallback: () => 1, unregisterCallback: () => {},
invoke: async (command, args = {}) => {
if (command === 'plugins_snapshot') return { root: 'C:/font-smoke-plugins', plugins: [] };
if (command === 'workspace_last_path') return 'C:\\font-smoke';
if (command === 'workspace_open') return { root: 'C:\\font-smoke', name: 'font-smoke', watch_mode: 'native' };
if (command === 'workspace_list') return [{ name: 'Typography.md', rel_path: 'Typography.md', kind: 'file' }];
if (command === 'workspace_read') return '# A place for your ideas\n\nRead the next chapter, collect clear notes, and keep your work close. Small letters, open spaces, and steady lines help each sentence stay readable.\n\n## Details worth keeping\n\nThe quick brown fox jumps over the lazy dog. Il1 O0 rn m, 0123456789.\n\n`const name = "RuneStone";`\n';
if (command === 'workspace_search') return [];
if (command === 'plugin:event|listen') return args.handler;
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
await mockTauri(context, {
commands: test => ({
...test.workspace({
root: 'C:\\font-smoke',
files: { 'Typography.md': '# A place for your ideas\n\nRead the next chapter, collect clear notes, and keep your work close. Small letters, open spaces, and steady lines help each sentence stay readable.\n\n## Details worth keeping\n\nThe quick brown fox jumps over the lazy dog. Il1 O0 rn m, 0123456789.\n\n`const name = "RuneStone";`\n' },
}),
plugins_snapshot: () => ({ root: 'C:/font-smoke-plugins', plugins: [] }),
}),
});
const main = await context.newPage();
const settings = await context.newPage();
for (const page of [main, settings]) page.on('pageerror', error => errors.push(error.message));
await main.goto(origin);
const main = await openPage(context);
const settings = await openPage(context);
await main.goto(smokeUrl);
await main.getByText('font-smoke', { exact: true }).waitFor();
await main.keyboard.press('Control+p');
await main.getByRole('textbox', { name: 'Find a file' }).fill('Typography.md');
await main.getByRole('textbox', { name: 'Find a file' }).press('Enter');
await main.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
await settings.goto(`${origin}/?settingsWindow=true`);
await settings.goto(`${smokeUrl}/?settingsWindow=true`);
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
const sessions = new Map();
// The CSS font of `selector` and the platform fonts Chromium used to draw its glyphs.
async function rendered(page, selector) {
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
await settle(page);
let session = sessions.get(page);
if (!session) {
session = await context.newCDPSession(page);
@@ -58,6 +47,11 @@ try {
});
return { ...style, rendered: fonts.filter(font => font.glyphCount).map(({ familyName, postScriptName, glyphCount, isCustomFont }) => ({ familyName, postScriptName, glyphCount, isCustomFont })) };
}
const setPluginTools = count => settings.evaluate(async count => {
const { pluginTools } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
pluginTools.set(Array.from({ length: count }, (_, index) => ({ owner: 'org.example.font-check', id: `settings-${index}`, title: `Plugin settings ${index + 1}`, surface: 'settings' })));
}, count);
const selectors = { ui: '.picker[aria-label="Color theme"]', prose: '.cm-line:not(.writer-heading):not(.writer-blank)', heading: '.writer-h1' };
const cases = [
['harvest-moon', 'Harvest Moon', 'Constantia', 'Candara', 'Constantia', 'Constantia'],
['crimson-pilot', 'Crimson Pilot', 'Bahnschrift', 'Bahnschrift', 'Segoe UI', 'Bahnschrift'],
@@ -75,15 +69,15 @@ try {
await page.evaluate(font => {
for (const role of ['ui', 'prose', 'heading']) document.documentElement.style.setProperty(`--rs-font-${role}`, `"${font}"`);
}, oldFont);
await page.screenshot({ path: `${output}/${theme}-before-${page === main ? 'document' : 'settings'}.png` });
await page.screenshot({ path: path.join(output, `${theme}-before-${page === main ? 'document' : 'settings'}.png`) });
await page.evaluate(() => {
for (const role of ['ui', 'prose', 'heading']) document.documentElement.style.removeProperty(`--rs-font-${role}`);
});
}
const roles = {
ui: await rendered(settings, '.picker[aria-label="Color theme"]'),
prose: await rendered(main, '.cm-line:not(.writer-heading):not(.writer-blank)'),
heading: await rendered(main, '.writer-h1'),
ui: await rendered(settings, selectors.ui),
prose: await rendered(main, selectors.prose),
heading: await rendered(main, selectors.heading),
mono: await rendered(settings, '.preview-code'),
};
for (const [role, family] of Object.entries({ ui, prose, heading })) {
@@ -94,8 +88,8 @@ try {
assert.equal(roles.prose.size, '15px');
assert(roles.mono.family.includes('Cascadia Mono'));
assert(roles.mono.rendered.some(font => font.familyName === 'Cascadia Mono'));
await settings.screenshot({ path: `${output}/${theme}-after-settings.png` });
await main.screenshot({ path: `${output}/${theme}-after-document.png` });
await settings.screenshot({ path: path.join(output, `${theme}-after-settings.png`) });
await main.screenshot({ path: path.join(output, `${theme}-after-document.png`) });
await main.getByRole('textbox', { name: 'Writing editor', exact: true }).evaluate(node => {
node.focus();
const paragraph = [...node.querySelectorAll('.cm-line')].find(line => line.textContent.includes('Read the next chapter'));
@@ -103,7 +97,7 @@ try {
const selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(range);
});
assert((await main.evaluate(() => getSelection().toString())).includes('Read the next chapter'));
await main.screenshot({ path: `${output}/${theme}-selected-prose.png` });
await main.screenshot({ path: path.join(output, `${theme}-selected-prose.png`) });
await settings.setViewportSize({ width: 360, height: 480 });
const content = settings.locator('dialog .content');
assert(await content.evaluate(node => node.scrollWidth <= node.clientWidth), `${theme}: narrow overflow`);
@@ -111,35 +105,31 @@ try {
const current = settings.getByRole('menuitemradio', { name: label, exact: true });
await current.waitFor();
assert(await current.evaluate(node => node === document.activeElement));
await settings.screenshot({ path: `${output}/${theme}-narrow-menu.png` });
await settings.screenshot({ path: path.join(output, `${theme}-narrow-menu.png`) });
await settings.keyboard.press('Escape');
assert(await picker.evaluate(node => node === document.activeElement));
await settings.evaluate(async () => {
const { pluginTools } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
pluginTools.set(Array.from({ length: 16 }, (_, index) => ({ owner: 'org.example.font-check', id: `settings-${index}`, title: `Plugin settings ${index + 1}`, surface: 'settings' })));
});
await setPluginTools(16);
const bodyBounds = await settings.locator('dialog .body').boundingBox();
assert((await settings.locator('dialog aside').boundingBox()).height <= bodyBounds.height * .4 + 1);
await settings.getByRole('button', { name: 'Plugin settings 16', exact: true }).scrollIntoViewIfNeeded();
assert(await content.evaluate(node => node.scrollWidth <= node.clientWidth));
await settings.screenshot({ path: `${output}/${theme}-narrow-long-plugins.png` });
await settings.evaluate(async () => {
const { pluginTools } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name); pluginTools.set([]);
});
await settings.screenshot({ path: path.join(output, `${theme}-narrow-long-plugins.png`) });
await setPluginTools(0);
// Drop the first family from each stack and check that the fallback still renders glyphs.
const fallback = {};
for (const [role, page, selector] of [['ui', settings, '.picker[aria-label="Color theme"]'], ['prose', main, '.cm-line:not(.writer-heading):not(.writer-blank)'], ['heading', main, '.writer-h1']]) {
for (const [role, page] of [['ui', settings], ['prose', main], ['heading', main]]) {
await page.evaluate(role => {
const css = getComputedStyle(document.documentElement);
const stack = css.getPropertyValue(`--rs-font-${role}`);
document.documentElement.style.setProperty(`--rs-font-${role}`, stack.slice(stack.indexOf(',') + 1));
}, role);
fallback[role] = await rendered(page, selector);
fallback[role] = await rendered(page, selectors[role]);
assert(fallback[role].rendered.length > 0);
await page.evaluate(role => document.documentElement.style.removeProperty(`--rs-font-${role}`), role);
}
report.push({ theme, oldFont, roles, fallback });
console.log(`PASS ${theme}: real UI and prose sizes, rendered fonts, shared monospace, selection, narrow settings, keyboard focus, long plugin navigation`);
}
assert.deepEqual(errors, []);
await writeFile(`${output}/rendered-fonts.json`, JSON.stringify(report, null, 2));
} finally { await browser.close(); }
assert.deepEqual([...main.errors, ...settings.errors], []);
await writeFile(path.join(output, 'rendered-fonts.json'), JSON.stringify(report, null, 2));
});
+61
View File
@@ -0,0 +1,61 @@
// The built-in browser shows about:blank as a transparent surface with no frame image, and paints real pages, in both themes.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
const name = "browser/blankPage";
await runSmoke(name, async ({ browser }) => {
const output = await outputDir(name);
for (const theme of ["light", "dark"]) {
const page = await openPage(browser, { viewport: { width: 1100, height: 780 } });
await mockTauri(page, {
commands: test => ({
...test.workspace({ root: "C:\\blank-page", files: { "sample.md": "# Sample\n" } }),
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
browser_request: args => {
if (args.command === "frameAck") window.blankAcks = (window.blankAcks || 0) + 1;
return window.browserSnapshot;
},
}),
});
await page.goto(smokeUrl);
await page.getByText("blank-page", { exact: true }).waitFor();
await page.evaluate(async theme => {
(await import("/src/lib/theme/appearance.ts")).saveAppearance({ theme: "default", mode: theme });
const { mount } = await import("/node_modules/svelte/src/index-client.js");
const { default: Browser } = await import("/src/lib/browser/Browser.svelte");
const client = await import("/src/lib/browser/client.ts");
const container = document.createElement("div");
container.id = "browser-test";
Object.assign(container.style, { position: "fixed", inset: "50px 10px 20px", zIndex: "2000", background: "linear-gradient(120deg,#945975,#395c72)" });
document.body.append(container);
window.browserSnapshot = { profiles: [{ id: "user", name: "User" }], tabs: [{ id: "blank", profileId: "user", url: "about:blank", title: "", loading: false }], bookmarks: [], settings: {} };
client.state.set(window.browserSnapshot);
mount(Browser, { target: container, props: { initial: { tabId: "blank" }, onSessionChange() {}, async newTab() {} } });
window.browserClient = client;
}, theme);
const surface = page.locator("#browser-test .surface");
await page.locator('#browser-test [data-browser-state="ready"]').waitFor();
await page.evaluate(() => window.browserClient.frames.get("blank")({ tabId: "blank", frameId: 1, width: 10, height: 10, mime: "image/png", data: "AA==" }));
assert.equal(await surface.evaluate(node => getComputedStyle(node).backgroundColor), "rgba(0, 0, 0, 0)");
assert.equal(await surface.locator("img").count(), 0);
assert.equal(await page.evaluate(() => window.blankAcks), 1);
await page.screenshot({ path: path.join(output, `${theme}-blank-browser.png`) });
await page.evaluate(() => {
window.browserSnapshot.tabs[0].url = "https://example.com/minimal";
window.browserClient.state.set({ ...window.browserSnapshot });
const canvas = document.createElement("canvas");
canvas.width = 10;
canvas.height = 10;
const context = canvas.getContext("2d");
context.fillStyle = "white";
context.fillRect(0, 0, 10, 10);
window.browserClient.frames.get("blank")({ tabId: "blank", frameId: 2, width: 10, height: 10, mime: "image/png", data: canvas.toDataURL().split(",")[1] });
});
await surface.locator("img").waitFor();
assert.notEqual(await surface.evaluate(node => getComputedStyle(node).backgroundColor), "rgba(0, 0, 0, 0)");
assert.deepEqual(page.errors, []);
await page.close();
console.log(`PASS: ${theme} blank and painted browser pages`);
}
});
+96 -105
View File
@@ -1,109 +1,100 @@
import { createRequire } from 'node:module';
// The built-in browser: navigation, profiles, independence from the legacy package, same-tab view replacement, a plug-in sidebar, and settings.
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 context = await browser.newContext({ viewport: { width: 1280, height: 800 } });
const page = await context.newPage();
page.setDefaultTimeout(10000);
const errors = [];
page.on('pageerror', error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const callbacks = new Map(); let next = 0;
const snapshot = { profiles: [{ id: 'user', name: 'Existing user' }], tabs: [], bookmarks: [{ id: 'saved', profileId: 'user', title: 'Existing bookmark', url: 'https://example.com' }], settings: { search: 'duckduckgo', adblock: true, linkDestination: 'internal', personalRules: '', homepage: '', filterLists: [] } };
window.builtinCheck = { loads: [], commands: [], legacy: false, removed: false, mounts: [], cleanups: [] };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
transformCallback: fn => { const id = ++next; callbacks.set(id, fn); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === 'plugin:event|listen') return args.handler;
if (command === 'plugin:event|unlisten') return;
if (command === 'browser_connect') return 'window-session';
if (command === 'browser_stop' || command === 'plugins_release') return;
if (command === 'workspace_last_path') return null;
if (command === 'workspace_recent') return [];
if (command === 'plugins_snapshot') return { root: 'test', plugins: [
{ manifest: { schemaVersion: 1, id: 'org.test.boards', name: 'Boards', author: 'Test', description: '', version: '0.1.0', apiVersion: 1, entry: 'main.js', access: 'full-app' }, hash: 'fixture', enabled: true, installedAt: 1, path: '', error: null, removal: false },
...(window.builtinCheck.legacy && !window.builtinCheck.removed ? [{ manifest: { schemaVersion: 1, id: 'runestone.browser', name: 'Browser', author: 'Test', description: '', version: '0.1.6', apiVersion: 1, entry: 'main.js', access: 'full-app' }, hash: 'old', enabled: true, installedAt: 1, path: '', error: null, removal: false }] : [])
] };
if (command === 'plugins_load') {
window.builtinCheck.loads.push(args.id);
if (args.id === 'runestone.browser') throw Error('The old browser package must not load');
return `export function activate(api) {
for (const id of ['board-a', 'board-b']) api.registerView({ id, title: id, placement: 'editor', mount(el) {
window.builtinCheck.mounts.push(id); el.textContent = id;
if (id === 'board-a') { const b = document.createElement('button'); b.textContent = 'Select board B'; b.onclick = () => api.replaceView('board-a', 'board-b'); el.append(b); }
return () => { window.builtinCheck.cleanups.push(id); };
}});
api.registerView({ id:'source-control', title:'Source control', placement:'sidebar', navigation:true, icon:'git', mount(el) { el.textContent='Git sidebar fixture'; }});
}`;
}
if (command === 'browser_request') {
if (args.session !== 'window-session') throw Error('Missing browser session');
window.builtinCheck.commands.push(args.command);
if (args.command === 'newTab') { const tabId = 'native-' + (++next); snapshot.tabs.push({ id: tabId, profileId: args.args.profileId || 'user', url: 'about:blank', title: 'Browser', loading: false, blocked: 0, canBack: false, canForward: false }); return { tabId }; }
if (args.command === 'closeTab') snapshot.tabs = snapshot.tabs.filter(tab => tab.id !== args.args.tabId);
if (args.command === 'navigate') { const tab = snapshot.tabs.find(tab => tab.id === args.args.tabId); tab.url = args.args.input; tab.title = 'Example'; }
if (args.command === 'settings') Object.assign(snapshot.settings, args.args);
return structuredClone(snapshot);
}
if (command.startsWith('plugin:window|')) return false;
throw Error('Unhandled IPC: ' + command);
import path from 'node:path';
import { mockTauri, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
await runSmoke('browser/builtin', async ({ page }) => {
await mockTauri(page, {
commands: test => {
const snapshot = { profiles: [{ id: 'user', name: 'Existing user' }], tabs: [], bookmarks: [{ id: 'saved', profileId: 'user', title: 'Existing bookmark', url: 'https://example.com' }], settings: { search: 'duckduckgo', adblock: true, linkDestination: 'internal', personalRules: '', homepage: '', filterLists: [] } };
const check = Object.assign(test, { loads: [], commands: [], legacy: false, removed: false, mounts: [], cleanups: [] });
let next = 0;
const plugin = (id, name, version, hash) => ({ manifest: { schemaVersion: 1, id, name, author: 'Test', description: '', version, apiVersion: 1, entry: 'main.js', access: 'full-app' }, hash, enabled: true, installedAt: 1, path: '', error: null, removal: false });
return {
browser_connect: () => 'window-session',
workspace_last_path: () => null,
'plugin:window|is_maximized': () => false,
plugins_snapshot: () => ({ root: 'test', plugins: [
plugin('org.test.boards', 'Boards', '0.1.0', 'fixture'),
...(check.legacy && !check.removed ? [plugin('runestone.browser', 'Browser', '0.1.6', 'old')] : []),
] }),
plugins_load: ({ id }) => {
check.loads.push(id);
if (id === 'runestone.browser') throw Error('The old browser package must not load');
return `export function activate(api) {
for (const id of ['board-a', 'board-b']) api.registerView({ id, title: id, placement: 'editor', mount(el) {
window.__TEST__.mounts.push(id); el.textContent = id;
if (id === 'board-a') { const b = document.createElement('button'); b.textContent = 'Select board B'; b.onclick = () => api.replaceView('board-a', 'board-b'); el.append(b); }
return () => { window.__TEST__.cleanups.push(id); };
}});
api.registerView({ id:'source-control', title:'Source control', placement:'sidebar', navigation:true, icon:'git', mount(el) { el.textContent='Git sidebar fixture'; }});
}`;
},
browser_request: ({ session, command, args }) => {
if (session !== 'window-session') throw Error('Missing browser session');
check.commands.push(command);
if (command === 'newTab') { const tabId = 'native-' + (++next); snapshot.tabs.push({ id: tabId, profileId: args.profileId || 'user', url: 'about:blank', title: 'Browser', loading: false, blocked: 0, canBack: false, canForward: false }); return { tabId }; }
if (command === 'closeTab') snapshot.tabs = snapshot.tabs.filter(tab => tab.id !== args.tabId);
if (command === 'navigate') { const tab = snapshot.tabs.find(tab => tab.id === args.tabId); tab.url = args.input; tab.title = 'Example'; }
if (command === 'settings') Object.assign(snapshot.settings, args);
return structuredClone(snapshot);
},
};
},
});
const output = await outputDir('browser/builtin');
const external = () => page.evaluate(() => performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
const editorKeys = module => page.evaluate(async module => {
const { get } = await import('/node_modules/.vite/deps/svelte_store.js');
return get((await import(module)).pluginEditors).map(view => view.key);
}, module);
try {
await page.goto(smokeUrl);
await page.waitForFunction(async () => { const { pluginHost } = await import('/src/lib/plugins/registry.ts'); return !!pluginHost.get('browser'); });
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
await page.locator('[data-browser-state="ready"]').waitFor();
await page.getByRole('textbox', { name: 'Address or search' }).fill('https://example.com');
await page.getByRole('textbox', { name: 'Address or search' }).press('Enter');
await page.waitForFunction(() => window.__TEST__.commands.includes('navigate'));
await page.getByRole('button', { name: 'Browser profile' }).click();
assert.equal(await page.getByRole('menuitemradio', { checked: true }).count(), 1);
await page.keyboard.press('Escape');
const module = await external();
await page.evaluate(async module => { window.__TEST__.legacy = true; await (await import(module)).refreshPlugins(); }, module);
assert.equal(await page.evaluate(() => window.__TEST__.loads.includes('runestone.browser')), false);
await page.evaluate(async module => { window.__TEST__.removed = true; await (await import(module)).refreshPlugins(); }, module);
assert.equal(await page.locator('[data-browser-state="ready"]').count(), 1);
await page.evaluate(async module => { (await import(module)).openPluginView('org.test.boards', 'board-a'); }, module);
const before = await editorKeys(module);
await page.getByRole('button', { name: 'Select board B' }).click();
await page.getByRole('tabpanel', { name: 'board-b', exact: true }).waitFor();
await page.waitForFunction(() => window.__TEST__.mounts.includes('board-b') && window.__TEST__.cleanups.includes('board-a'));
assert.deepEqual(await editorKeys(module), before);
await page.getByRole('button', { name: 'Source control', exact: true }).click();
await page.getByText('Git sidebar fixture', { exact: true }).waitFor();
assert.equal(await page.getByRole('tabpanel', { name: 'board-b', exact: true }).count(), 1);
for (const theme of ['dark', 'light']) {
await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
await page.screenshot({ path: path.join(output, `builtin-browser-${theme}.png`) });
}
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
});
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:5174');
await page.waitForFunction(async () => { const { pluginHost } = await import('/src/lib/plugins/registry.ts'); return !!pluginHost.get('browser'); });
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
await page.locator('[data-browser-state="ready"]').waitFor();
await page.getByRole('textbox', { name: 'Address or search' }).fill('https://example.com');
await page.getByRole('textbox', { name: 'Address or search' }).press('Enter');
await page.waitForFunction(() => window.builtinCheck.commands.includes('navigate'));
await page.getByRole('button', { name: 'Browser profile' }).click();
assert.equal(await page.getByRole('menuitemradio', { checked: true }).count(), 1);
await page.keyboard.press('Escape');
await page.evaluate(async () => { window.builtinCheck.legacy = true; const { refreshPlugins } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name); await refreshPlugins(); });
assert.equal(await page.evaluate(() => window.builtinCheck.loads.includes('runestone.browser')), false);
await page.evaluate(async () => { window.builtinCheck.removed = true; const { refreshPlugins } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name); await refreshPlugins(); });
assert.equal(await page.locator('[data-browser-state="ready"]').count(), 1);
await page.evaluate(async () => { const { openPluginView } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name); openPluginView('org.test.boards', 'board-a'); });
const before = await page.evaluate(async () => { const { get } = await import('/node_modules/.vite/deps/svelte_store.js'); const { pluginEditors } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name); return get(pluginEditors).map(view => view.key); });
await page.getByRole('button', { name: 'Select board B' }).click();
await page.getByRole('tabpanel', { name: 'board-b', exact: true }).waitFor();
await page.waitForFunction(() => window.builtinCheck.mounts.includes('board-b') && window.builtinCheck.cleanups.includes('board-a'));
const after = await page.evaluate(async () => { const { get } = await import('/node_modules/.vite/deps/svelte_store.js'); const { pluginEditors } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name); return get(pluginEditors).map(view => view.key); });
assert.deepEqual(after, before);
await page.getByRole('button', { name: 'Source control', exact: true }).click();
await page.getByText('Git sidebar fixture', { exact: true }).waitFor();
assert.equal(await page.getByRole('tabpanel', { name: 'board-b', exact: true }).count(), 1);
await mkdir('.audit/cards-2026-10-08-next', { recursive: true });
for (const theme of ['dark', 'light']) {
await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
await page.screenshot({ path: `.audit/cards-2026-10-08-next/builtin-browser-${theme}.png` });
await page.goto(smokeUrl + '/?settingsWindow=true');
await page.getByRole('button', { name: 'Browser', exact: true }).click();
await page.getByRole('button', { name: 'Save browser settings' }).waitFor({ state: 'visible' });
assert.match(await page.getByRole('button', { name: 'Profile', exact: true }).innerText(), /Existing user/);
await page.setViewportSize({ width: 360, height: 800 });
for (const theme of ['dark', 'light']) {
await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
await page.screenshot({ path: path.join(output, `browser-settings-${theme}.png`) });
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
}
} catch (error) {
console.error(await page.evaluate(async () => {
const m = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
const read = store => { let value; store.subscribe(x => value = x)(); return value; };
const { calls, emit, workspace, ...state } = window.__TEST__;
return { state, text: document.body.innerText, errors: read(m.externalErrors), views: read(m.pluginEditors), tools: read(m.pluginTools) };
}).catch(reason => ({ diagnosticError: String(reason) })), page.errors);
throw error;
}
await page.goto((process.env.SMOKE_URL || 'http://127.0.0.1:5174') + '/?settingsWindow=true');
await page.getByRole('button', { name: 'Browser', exact: true }).click();
await page.getByRole('button', { name: 'Save browser settings' }).waitFor({ state: 'visible' });
assert.match(await page.getByRole('button', { name: 'Profile', exact: true }).innerText(), /Existing user/);
await page.setViewportSize({ width: 360, height: 800 });
for (const theme of ['dark', 'light']) {
await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
await page.screenshot({ path: `.audit/cards-2026-10-08-next/browser-settings-${theme}.png` });
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
}
assert.deepEqual(errors, []);
console.log('Built-in browser, legacy package independence, same-tab replacement and plugin sidebar checks passed.');
} catch (error) {
console.error(error);
console.error(await page.evaluate(async () => {
const m = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
const read = store => { let value; store.subscribe(x => value = x)(); return value; };
return { state: window.builtinCheck, text: document.body.innerText, errors: read(m.externalErrors), views: read(m.pluginEditors), tools: read(m.pluginTools) };
}).catch(reason => ({ diagnosticError: String(reason) })), errors);
throw error;
} finally { await browser.close(); }
}, { viewport: { width: 1280, height: 800 } });
+152 -144
View File
@@ -1,154 +1,162 @@
// Embedded browser fields with the real Electron engine: visible caret, page focus, toolbar blur, inputs, rich text, iframes, and navigation.
// @requires electron
import { createRequire } from 'node:module';
import { spawn } from 'node:child_process';
import { mkdtemp, mkdir, writeFile } from 'node:fs/promises';
import { createServer } from 'node:http';
import { mkdtemp } from 'node:fs/promises';
import path from 'node:path';
import os from 'node:os';
import assert from 'node:assert/strict';
const runtime = path.resolve('browser-runtime');
const require = createRequire(path.join(runtime, 'package.json'));
const { chromium } = require('playwright');
const electron = require('electron');
const root = await mkdtemp(path.join(os.tmpdir(), 'runestone-browser-ui-'));
const child = spawn(electron, [path.join(runtime, 'test/interaction-engine.mjs')], {
windowsHide: true, stdio: ['ignore', 'inherit', 'inherit', 'ipc'], env: { ...process.env, RS_INTERACTION_ROOT: root },
});
let sequence = 0, page, pendingFrame, painting = false;
const pending = new Map();
const commands = [];
const rpc = (command, args = {}) => new Promise((resolve, reject) => {
const id = ++sequence;
const timeout = setTimeout(() => { pending.delete(id); reject(Error(`Runtime timeout: ${command}`)); }, 15000);
pending.set(id, { resolve: value => { clearTimeout(timeout); resolve(value); }, reject: error => { clearTimeout(timeout); reject(error); } });
child.send({ id, command, args });
});
async function paint() {
if (painting || !page || !pendingFrame) return;
painting = true;
const frame = pendingFrame; pendingFrame = undefined;
await page.evaluate(value => window.browserEmit?.('browser-frame', value), frame).catch(() => {});
painting = false;
if (pendingFrame) void paint();
}
const ready = new Promise((resolve, reject) => {
child.on('error', reject);
child.on('message', message => {
if (message.ready) resolve();
if (message.id) {
const callback = pending.get(message.id); pending.delete(message.id);
if (message.error) callback?.reject(Error(message.error)); else callback?.resolve(message.result);
}
if (message.event?.event === 'frame') { pendingFrame = message.event; void paint(); }
else if (message.event && page) void page.evaluate(value => window.browserEmit?.('browser-state', value), message.event).catch(() => {});
import { mockTauri, openPage, outputDir, repoRoot, runSmoke, smokeUrl } from '../_harness/index.mjs';
const runtime = path.join(repoRoot, 'browser-runtime');
const electron = createRequire(path.join(runtime, 'package.json'))('electron');
const scale = Number(process.env.BROWSER_TEST_SCALE || 1);
/** Start the Electron browser engine and relay its frames and state events to `page` once it is set. */
async function startEngine() {
const root = await mkdtemp(path.join(os.tmpdir(), 'runestone-browser-ui-'));
const child = spawn(electron, [path.join(runtime, 'test/interaction-engine.mjs')], {
windowsHide: true, stdio: ['ignore', 'inherit', 'inherit', 'ipc'], env: { ...process.env, RS_INTERACTION_ROOT: root },
});
});
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : { channel: 'chrome' }) });
const errors = [];
try {
await ready;
page = await browser.newPage({ viewport: { width: 1280, height: 800 }, deviceScaleFactor: Number(process.env.BROWSER_TEST_SCALE || 1) });
page.on('pageerror', error => errors.push(error.message));
await page.exposeFunction('browserRpc', async (command, args) => { const entry = { command, args, start: Date.now() }; commands.push(entry); const result = await rpc(command, args); entry.elapsed = Date.now() - entry.start; return result; });
await page.addInitScript(() => {
window.isTauri = true;
const callbacks = new Map(), listeners = new Map(); let next = 0;
window.browserEmit = (event, payload) => { for (const [id, entry] of listeners) if (entry.event === event) callbacks.get(entry.handler)?.({ event, id, payload }); };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
transformCallback: fn => { const id = ++next; callbacks.set(id, fn); return id; }, unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === 'plugin:event|listen') { const id = ++next; listeners.set(id, args); return id; }
if (command === 'plugin:event|unlisten') { listeners.delete(args.eventId); return; }
if (command === 'browser_connect') return 'test-session';
if (command === 'browser_stop' || command === 'plugins_release') return;
if (command === 'browser_request') return window.browserRpc(args.command, args.args);
if (command === 'workspace_last_path') return null;
if (command === 'workspace_recent') return [];
if (command === 'plugins_snapshot') return { root: 'test', plugins: [] };
if (command.startsWith('plugin:window|')) return false;
throw Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => listeners.delete(id) };
const engine = { page: undefined, commands: [], child };
let sequence = 0, pendingFrame, painting = false;
const pending = new Map();
engine.rpc = (command, args = {}) => new Promise((resolve, reject) => {
const id = ++sequence;
const timeout = setTimeout(() => { pending.delete(id); reject(Error(`Runtime timeout: ${command}`)); }, 15000);
pending.set(id, { resolve: value => { clearTimeout(timeout); resolve(value); }, reject: error => { clearTimeout(timeout); reject(error); } });
child.send({ id, command, args });
});
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1451');
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
const surface = page.getByRole('application', { name: 'Web page', exact: true });
await page.locator('[data-browser-state="ready"]').waitFor();
const tabId = await page.locator('[data-browser-state="ready"]').getAttribute('data-browser-tab');
const evaluate = code => rpc('testEvaluate', { tabId, code });
async function expectRemote(code, expected) {
for (let attempt = 0; attempt < 100; attempt++) {
if (await evaluate(code) === expected) return;
await page.waitForTimeout(50);
}
assert.equal(await evaluate(code), expected);
async function paint() {
if (painting || !engine.page || !pendingFrame) return;
painting = true;
const frame = pendingFrame; pendingFrame = undefined;
await engine.page.evaluate(value => window.__TEST__?.emit('browser-frame', value), frame).catch(() => {});
painting = false;
if (pendingFrame) void paint();
}
await evaluate(`document.body.innerHTML='<input id="typing" style="position:absolute;left:40px;top:40px;width:300px;height:40px"><textarea id="other" style="position:absolute;left:40px;top:140px;width:300px;height:80px"></textarea><div id="rich" contenteditable="true" style="position:absolute;left:40px;top:280px;width:300px;height:80px;border:1px solid">Rich text</div>'; true;`);
await page.locator('.surface img').waitFor();
await page.waitForTimeout(300);
const box = await surface.boundingBox();
await page.mouse.click(box.x + 100, box.y + 60);
await page.waitForTimeout(150);
assert.deepEqual(await evaluate('({active:document.activeElement.id,focused:document.hasFocus()})'), { active: 'typing', focused: true });
await mkdir('.audit/browser-fields', { recursive: true });
await page.waitForFunction(() => {
const image = document.querySelector('.surface img');
if (!image?.complete || !image.naturalWidth) return false;
const surface = document.querySelector('.surface');
const ratio = image.naturalWidth / surface.clientWidth;
const canvas = document.createElement('canvas'); canvas.width = 12; canvas.height = 28;
const context = canvas.getContext('2d');
context.drawImage(image, 42 * ratio, 46 * ratio, 12 * ratio, 28 * ratio, 0, 0, 12, 28);
const pixels = context.getImageData(0, 0, 12, 28).data;
let dark = 0;
for (let offset = 0; offset < pixels.length; offset += 4) if (pixels[offset] < 100 && pixels[offset + 1] < 100 && pixels[offset + 2] < 100) dark++;
return dark >= 8;
}, null, { timeout: 5000, polling: 50 });
await page.screenshot({ path: `.audit/browser-fields/caret-${process.env.BROWSER_TEST_SCALE || 1}x.png` });
await page.getByRole('textbox', { name: 'Address or search' }).focus();
await page.waitForTimeout(100);
assert.equal(await evaluate('document.hasFocus()'), false, 'The toolbar removes focus from the page');
await page.mouse.click(box.x + 100, box.y + 60);
await page.waitForTimeout(100);
assert.equal(await evaluate('document.hasFocus()'), true, 'A page click restores focus');
await page.keyboard.type('Hello World!');
await expectRemote('document.querySelector("#typing").value', 'Hello World!');
await page.mouse.move(box.x + 50, box.y + 60);
await page.mouse.down();
await page.mouse.move(box.x + 100, box.y + 60, { steps: 8 });
await page.mouse.up();
await page.waitForTimeout(200);
assert(await evaluate('document.querySelector("#typing").selectionEnd > document.querySelector("#typing").selectionStart'), 'Dragging selects text in the embedded field');
await page.mouse.click(box.x + 100, box.y + 170);
await page.keyboard.type('Second field');
await expectRemote('document.querySelector("#other").value', 'Second field');
await page.mouse.click(box.x + 100, box.y + 310);
await page.keyboard.press('Control+a');
await page.keyboard.type('Edited rich text');
await expectRemote('document.querySelector("#rich").textContent', 'Edited rich text');
await evaluate(`document.body.insertAdjacentHTML('beforeend', '<iframe id="frame" style="position:absolute;left:40px;top:390px;width:300px;height:100px" srcdoc="<input id=framed style=width:200px;height:40px>"></iframe>'); true;`);
await page.waitForTimeout(200);
await page.mouse.click(box.x + 100, box.y + 415);
await page.keyboard.type('Frame input');
await expectRemote('document.querySelector("#frame").contentDocument.querySelector("#framed").value', 'Frame input');
assert.equal(await evaluate('document.querySelector("#frame").contentDocument.hasFocus()'), true);
await page.getByRole('textbox', { name: 'Address or search' }).focus();
await page.waitForTimeout(100);
assert.equal(await evaluate('document.querySelector("#frame").contentDocument.hasFocus()'), false);
await rpc('navigate', { tabId, input: 'about:blank' });
await page.waitForTimeout(100);
await evaluate(`document.body.innerHTML='<input id="after-navigation" style="position:absolute;left:40px;top:40px;width:300px;height:40px">'; true;`);
await page.waitForTimeout(400);
await page.mouse.click(box.x + 100, box.y + 60);
await page.keyboard.type('After navigation');
await page.waitForTimeout(500);
assert.equal(await evaluate('devicePixelRatio'), Number(process.env.BROWSER_TEST_SCALE || 1), 'Navigation preserves the host pixel ratio');
await expectRemote('document.querySelector("#after-navigation").value', 'After navigation');
assert.equal(await evaluate('document.hasFocus()'), true);
assert.deepEqual(errors, []);
console.log('PASS: visible caret, page focus, toolbar blur, input, textarea, contenteditable, iframe and navigation');
} finally {
await browser.close();
await rpc('shutdown').catch(() => {}); child.kill();
await new Promise((resolve, reject) => {
child.on('error', reject);
child.on('message', message => {
if (message.ready) resolve();
if (message.id) {
const callback = pending.get(message.id); pending.delete(message.id);
if (message.error) callback?.reject(Error(message.error)); else callback?.resolve(message.result);
}
if (message.event?.event === 'frame') { pendingFrame = message.event; void paint(); }
else if (message.event && engine.page) void engine.page.evaluate(value => window.__TEST__?.emit('browser-state', value), message.event).catch(() => {});
});
});
engine.stop = async () => { await engine.rpc('shutdown').catch(() => {}); child.kill(); };
return engine;
}
/** Serve an empty page. A tab on about:blank shows the host background instead of frames (docs/ui-design.md:218). */
async function startFixture() {
const server = createServer((_request, response) => { response.writeHead(200, { 'content-type': 'text/html' }); response.end('<!doctype html><title>Fixture</title><body></body>'); });
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
return { url: `http://127.0.0.1:${server.address().port}/`, close: () => new Promise(resolve => server.close(resolve)) };
}
await runSmoke('browser/fields', async ({ browser }) => {
const engine = await startEngine();
const fixture = await startFixture();
const { rpc, commands } = engine;
try {
const page = engine.page = await openPage(browser, { viewport: { width: 1280, height: 800 }, deviceScaleFactor: scale, timeout: 30000 });
await page.exposeFunction('browserRpc', async (command, args) => { const entry = { command, args, start: Date.now() }; commands.push(entry); const result = await rpc(command, args); entry.elapsed = Date.now() - entry.start; return result; });
await mockTauri(page, {
commands: () => ({
browser_connect: () => 'test-session',
browser_request: ({ command, args }) => window.browserRpc(command, args),
workspace_last_path: () => null,
plugins_snapshot: () => ({ root: 'test', plugins: [] }),
'plugin:window|is_maximized': () => false,
}),
});
const output = await outputDir('browser/fields');
await page.goto(smokeUrl);
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
const surface = page.getByRole('application', { name: 'Web page', exact: true });
await page.locator('[data-browser-state="ready"]').waitFor();
const tabId = await page.locator('[data-browser-state="ready"]').getAttribute('data-browser-tab');
const evaluate = code => rpc('testEvaluate', { tabId, code });
// Load an empty page first: the host shows frames only for loaded pages (src/lib/browser/Browser.svelte:18,264).
await rpc('navigate', { tabId, input: fixture.url });
await page.locator('.browser:not(.blank)[data-browser-state="ready"]').waitFor();
async function expectRemote(code, expected) {
for (let attempt = 0; attempt < 100; attempt++) {
if (await evaluate(code) === expected) return;
await page.waitForTimeout(50);
}
assert.equal(await evaluate(code), expected);
}
await evaluate(`document.body.innerHTML='<input id="typing" style="position:absolute;left:40px;top:40px;width:300px;height:40px"><textarea id="other" style="position:absolute;left:40px;top:140px;width:300px;height:80px"></textarea><div id="rich" contenteditable="true" style="position:absolute;left:40px;top:280px;width:300px;height:80px;border:1px solid">Rich text</div>'; true;`);
await page.locator('.surface img').waitFor();
await page.waitForTimeout(300);
const box = await surface.boundingBox();
await page.mouse.click(box.x + 100, box.y + 60);
await page.waitForTimeout(150);
assert.deepEqual(await evaluate('({active:document.activeElement.id,focused:document.hasFocus()})'), { active: 'typing', focused: true });
await page.waitForFunction(() => {
const image = document.querySelector('.surface img');
if (!image?.complete || !image.naturalWidth) return false;
const surface = document.querySelector('.surface');
const ratio = image.naturalWidth / surface.clientWidth;
const canvas = document.createElement('canvas'); canvas.width = 12; canvas.height = 28;
const context = canvas.getContext('2d');
context.drawImage(image, 42 * ratio, 46 * ratio, 12 * ratio, 28 * ratio, 0, 0, 12, 28);
const pixels = context.getImageData(0, 0, 12, 28).data;
let dark = 0;
for (let offset = 0; offset < pixels.length; offset += 4) if (pixels[offset] < 100 && pixels[offset + 1] < 100 && pixels[offset + 2] < 100) dark++;
return dark >= 8;
}, null, { timeout: 5000, polling: 50 });
await page.screenshot({ path: path.join(output, `caret-${scale}x.png`) });
await page.getByRole('textbox', { name: 'Address or search' }).focus();
await page.waitForTimeout(100);
assert.equal(await evaluate('document.hasFocus()'), false, 'The toolbar removes focus from the page');
await page.mouse.click(box.x + 100, box.y + 60);
await page.waitForTimeout(100);
assert.equal(await evaluate('document.hasFocus()'), true, 'A page click restores focus');
await page.keyboard.type('Hello World!');
await expectRemote('document.querySelector("#typing").value', 'Hello World!');
await page.mouse.move(box.x + 50, box.y + 60);
await page.mouse.down();
await page.mouse.move(box.x + 100, box.y + 60, { steps: 8 });
await page.mouse.up();
await page.waitForTimeout(200);
assert(await evaluate('document.querySelector("#typing").selectionEnd > document.querySelector("#typing").selectionStart'), 'Dragging selects text in the embedded field');
await page.mouse.click(box.x + 100, box.y + 170);
await page.keyboard.type('Second field');
await expectRemote('document.querySelector("#other").value', 'Second field');
await page.mouse.click(box.x + 100, box.y + 310);
await page.keyboard.press('Control+a');
await page.keyboard.type('Edited rich text');
await expectRemote('document.querySelector("#rich").textContent', 'Edited rich text');
await evaluate(`document.body.insertAdjacentHTML('beforeend', '<iframe id="frame" style="position:absolute;left:40px;top:390px;width:300px;height:100px" srcdoc="<input id=framed style=width:200px;height:40px>"></iframe>'); true;`);
await page.waitForTimeout(200);
await page.mouse.click(box.x + 100, box.y + 415);
await page.keyboard.type('Frame input');
await expectRemote('document.querySelector("#frame").contentDocument.querySelector("#framed").value', 'Frame input');
assert.equal(await evaluate('document.querySelector("#frame").contentDocument.hasFocus()'), true);
await page.getByRole('textbox', { name: 'Address or search' }).focus();
await page.waitForTimeout(100);
assert.equal(await evaluate('document.querySelector("#frame").contentDocument.hasFocus()'), false);
await rpc('navigate', { tabId, input: 'about:blank' });
await page.waitForTimeout(100);
await evaluate(`document.body.innerHTML='<input id="after-navigation" style="position:absolute;left:40px;top:40px;width:300px;height:40px">'; true;`);
await page.waitForTimeout(400);
await page.mouse.click(box.x + 100, box.y + 60);
await page.keyboard.type('After navigation');
await page.waitForTimeout(500);
assert.equal(await evaluate('devicePixelRatio'), scale, 'Navigation preserves the host pixel ratio');
await expectRemote('document.querySelector("#after-navigation").value', 'After navigation');
assert.equal(await evaluate('document.hasFocus()'), true);
assert.deepEqual(page.errors, []);
console.log('PASS: visible caret, page focus, toolbar blur, input, textarea, contenteditable, iframe and navigation');
} finally {
await engine.stop();
await fixture.close();
}
});
+184 -171
View File
@@ -1,181 +1,194 @@
// Embedded browser input with the real Electron engine: typing, clipboard, composition, page menus, autoscroll, input coalescing, and new tabs.
// @requires electron
import { createRequire } from 'node:module';
import { spawn } from 'node:child_process';
import { mkdtemp, mkdir, writeFile } from 'node:fs/promises';
import { createServer } from 'node:http';
import { mkdtemp, writeFile } from 'node:fs/promises';
import path from 'node:path';
import os from 'node:os';
import assert from 'node:assert/strict';
const runtime = path.resolve('browser-runtime');
const require = createRequire(path.join(runtime, 'package.json'));
const { chromium } = require('playwright');
const electron = require('electron');
const root = await mkdtemp(path.join(os.tmpdir(), 'runestone-browser-ui-'));
const child = spawn(electron, [path.join(runtime, 'test/interaction-engine.mjs')], {
windowsHide: true, stdio: ['ignore', 'inherit', 'inherit', 'ipc'], env: { ...process.env, RS_INTERACTION_ROOT: root },
});
let sequence = 0, page, pendingFrame, painting = false;
const pending = new Map();
const commands = [];
const rpc = (command, args = {}) => new Promise((resolve, reject) => {
const id = ++sequence;
const timeout = setTimeout(() => { pending.delete(id); reject(Error(`Runtime timeout: ${command}`)); }, 15000);
pending.set(id, { resolve: value => { clearTimeout(timeout); resolve(value); }, reject: error => { clearTimeout(timeout); reject(error); } });
child.send({ id, command, args });
});
async function paint() {
if (painting || !page || !pendingFrame) return;
painting = true;
const frame = pendingFrame; pendingFrame = undefined;
await page.evaluate(value => window.browserEmit?.('browser-frame', value), frame).catch(() => {});
painting = false;
if (pendingFrame) void paint();
}
const ready = new Promise((resolve, reject) => {
child.on('error', reject);
child.on('message', message => {
if (message.ready) resolve();
if (message.id) {
const callback = pending.get(message.id); pending.delete(message.id);
if (message.error) callback?.reject(Error(message.error)); else callback?.resolve(message.result);
}
if (message.event?.event === 'frame') { pendingFrame = message.event; void paint(); }
else if (message.event && page) void page.evaluate(value => window.browserEmit?.('browser-state', value), message.event).catch(() => {});
import { mockTauri, openPage, outputDir, repoRoot, runSmoke, smokeUrl } from '../_harness/index.mjs';
const runtime = path.join(repoRoot, 'browser-runtime');
const electron = createRequire(path.join(runtime, 'package.json'))('electron');
const scale = Number(process.env.BROWSER_TEST_SCALE || 1);
/** Start the Electron browser engine and relay its frames and state events to `page` once it is set. */
async function startEngine() {
const root = await mkdtemp(path.join(os.tmpdir(), 'runestone-browser-ui-'));
const child = spawn(electron, [path.join(runtime, 'test/interaction-engine.mjs')], {
windowsHide: true, stdio: ['ignore', 'inherit', 'inherit', 'ipc'], env: { ...process.env, RS_INTERACTION_ROOT: root },
});
});
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : { channel: 'chrome' }) });
const errors = [];
try {
await ready;
page = await browser.newPage({ viewport: { width: 1280, height: 800 }, deviceScaleFactor: Number(process.env.BROWSER_TEST_SCALE || 1) });
page.on('pageerror', error => errors.push(error.message));
await page.exposeFunction('browserRpc', async (command, args) => { const entry = { command, args, start: Date.now() }; commands.push(entry); const result = await rpc(command, args); entry.elapsed = Date.now() - entry.start; return result; });
await page.addInitScript(() => {
window.isTauri = true;
const callbacks = new Map(), listeners = new Map(); let next = 0;
window.browserEmit = (event, payload) => { for (const [id, entry] of listeners) if (entry.event === event) callbacks.get(entry.handler)?.({ event, id, payload }); };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
transformCallback: fn => { const id = ++next; callbacks.set(id, fn); return id; }, unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === 'plugin:event|listen') { const id = ++next; listeners.set(id, args); return id; }
if (command === 'plugin:event|unlisten') { listeners.delete(args.eventId); return; }
if (command === 'browser_connect') return 'test-session';
if (command === 'browser_stop' || command === 'plugins_release') return;
if (command === 'browser_request') return window.browserRpc(args.command, args.args);
if (command === 'workspace_last_path') return null;
if (command === 'workspace_recent') return [];
if (command === 'plugins_snapshot') return { root: 'test', plugins: [] };
if (command.startsWith('plugin:window|')) return false;
throw Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => listeners.delete(id) };
const engine = { page: undefined, commands: [], child };
let sequence = 0, pendingFrame, painting = false;
const pending = new Map();
engine.rpc = (command, args = {}) => new Promise((resolve, reject) => {
const id = ++sequence;
const timeout = setTimeout(() => { pending.delete(id); reject(Error(`Runtime timeout: ${command}`)); }, 15000);
pending.set(id, { resolve: value => { clearTimeout(timeout); resolve(value); }, reject: error => { clearTimeout(timeout); reject(error); } });
child.send({ id, command, args });
});
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1451');
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
const surface = page.getByRole('application', { name: 'Web page', exact: true });
await page.locator('[data-browser-state="ready"]').waitFor();
assert.equal(await page.getByRole('button', { name: 'New browser tab', exact: true }).count(), 0);
const tabId = await page.locator('[data-browser-state="ready"]').getAttribute('data-browser-tab');
const evaluate = code => rpc('testEvaluate', { tabId, code });
await evaluate(`document.body.innerHTML='<input id="typing" style="position:absolute;left:40px;top:40px;width:300px;height:40px"><a href="https://example.com/" style="position:absolute;left:40px;top:130px">Example link</a><p style="position:absolute;left:40px;top:200px">Page text</p>';true;`);
const initialBox = await surface.boundingBox();
await page.mouse.click(initialBox.x + 100, initialBox.y + 60);
await page.keyboard.type('Hello World!');
await page.waitForTimeout(200);
assert.equal(await evaluate('document.querySelector("#typing").value'), 'Hello World!');
await page.keyboard.press('Control+a'); await page.keyboard.press('Control+c');
await page.keyboard.press('End'); await page.keyboard.press('Control+v');
await page.waitForTimeout(200);
assert.equal(await evaluate('document.querySelector("#typing").value'), 'Hello World!Hello World!');
await page.getByRole('textbox', { name: 'Web page text input' }).evaluate(node => {
node.dispatchEvent(new CompositionEvent('compositionstart', { bubbles: true }));
node.dispatchEvent(new CompositionEvent('compositionend', { bubbles: true, data: '日本語' }));
});
await page.waitForTimeout(100);
assert.ok((await evaluate('document.querySelector("#typing").value')).endsWith('日本語'));
await page.mouse.click(initialBox.x + 100, initialBox.y + 60, { button: 'right' });
await page.getByRole('menu', { name: 'Browser page actions' }).waitFor();
await page.getByRole('menuitem', { name: 'Select all Ctrl+A', exact: true }).click();
await page.waitForTimeout(100);
assert.equal(await evaluate('document.querySelector("#typing").selectionEnd - document.querySelector("#typing").selectionStart'), 27);
await page.mouse.click(initialBox.x + 70, initialBox.y + 138, { button: 'right' });
await page.getByRole('menuitem', { name: 'Copy link address', exact: true }).waitFor();
await page.keyboard.press('Escape');
assert.equal(await page.getByRole('menu', { name: 'Browser page actions' }).count(), 0);
await page.mouse.click(initialBox.x + 70, initialBox.y + 138, { button: 'right' });
await page.getByRole('menuitem', { name: 'Copy link address', exact: true }).click();
await page.mouse.click(initialBox.x + 100, initialBox.y + 60);
await page.keyboard.press('Control+a'); await page.keyboard.press('Control+v');
await page.waitForTimeout(100);
assert.equal(await evaluate('document.querySelector("#typing").value'), 'https://example.com/');
await evaluate(`document.body.innerHTML='<canvas width="1000" height="700"></canvas>'; const c=document.querySelector('canvas').getContext('2d'); let n=0; window.testAnimate=true; function draw(){ c.fillStyle='#fff';c.fillRect(0,0,1000,700);c.fillStyle='#5482ff';c.fillRect(n++*5%900,200,80,80);if(window.testAnimate)requestAnimationFrame(draw); } draw();true;`);
await page.locator('.surface img').waitFor();
await page.evaluate(() => { window.decodedFrames = 0; document.querySelector('.surface img').addEventListener('load', () => window.decodedFrames++); });
await page.waitForTimeout(3000);
const decodedFps = await page.evaluate(() => window.decodedFrames / 3);
assert.ok(decodedFps >= 24, `The host image surface must decode at least 24 FPS: ${decodedFps}`);
const beforeWheels = commands.filter(call => call.command === 'input' && call.args.input.type === 'mouseWheel').length;
await surface.evaluate(node => {
const bounds = node.getBoundingClientRect();
for (let index = 0; index < 500; index++) node.dispatchEvent(new WheelEvent('wheel', {
bubbles: true, cancelable: true, clientX: bounds.x + 100, clientY: bounds.y + 100, deltaY: index < 250 ? 80 : -80,
}));
});
await page.waitForTimeout(200);
const wheelBurstCalls = commands.filter(call => call.command === 'input' && call.args.input.type === 'mouseWheel').length - beforeWheels;
assert.ok(wheelBurstCalls <= 3, `Animated pages must not accumulate wheel input: ${wheelBurstCalls}`);
await evaluate('window.testAnimate=false;true;');
await evaluate(`document.body.innerHTML='<div style="width:4000px;height:6000px;background:linear-gradient(45deg,white,steelblue)"><h1>Native scroll fixture</h1></div>'; true;`);
await page.locator('.surface img').waitFor();
const box = await surface.boundingBox();
const x = box.x + 220, y = box.y + 180;
await page.mouse.click(x, y, { button: 'middle' });
await page.mouse.move(x + 90, y + 120);
await page.waitForTimeout(1500);
const scrolled = await evaluate('({x:scrollX,y:scrollY})');
assert.ok(scrolled.x > 50 && scrolled.y > 100, `Middle-button motion must scroll real Chromium: ${JSON.stringify({ scrolled, anchor: await page.locator('.scroll-anchor').count(), wheels: commands.filter(c => c.command === 'input' && c.args.input.type === 'mouseWheel'), errors })}`);
await page.keyboard.press('Escape');
await page.waitForTimeout(350);
const stopped = await evaluate('scrollY');
await page.waitForTimeout(200);
assert.equal(await evaluate('scrollY'), stopped);
assert.equal(await page.locator('.scroll-anchor').count(), 0);
await page.mouse.move(x, y); await page.mouse.down({ button: 'middle' }); await page.mouse.move(x, y - 90);
await page.waitForTimeout(300); await page.mouse.up({ button: 'middle' });
await page.waitForTimeout(100);
assert.equal(await page.locator('.scroll-anchor').count(), 0, 'Release after a middle-button drag stops scrolling.');
assert.ok(await evaluate('scrollY') < stopped, 'Moving above the anchor scrolls upward.');
await page.mouse.click(x, y, { button: 'middle' });
await page.mouse.click(x, y, { button: 'left' });
assert.equal(await page.locator('.scroll-anchor').count(), 0, 'A click stops latched scrolling.');
await page.mouse.click(x, y, { button: 'middle' });
await page.getByRole('textbox', { name: 'Address or search' }).focus();
assert.equal(await page.locator('.scroll-anchor').count(), 0, 'Focus loss stops scrolling.');
const beforeMotion = commands.filter(c => c.command === 'input' && c.args.input.type === 'mouseMove').length;
await surface.dispatchEvent('mousemove', { clientX: x, clientY: y });
await page.evaluate(({ x, y }) => { const node = document.querySelector('.surface'); for (let i=0;i<500;i++) node.dispatchEvent(new MouseEvent('mousemove', { clientX:x+i%20, clientY:y, bubbles:true })); }, { x,y });
await page.waitForTimeout(100);
const motionCount = commands.filter(c => c.command === 'input' && c.args.input.type === 'mouseMove').length - beforeMotion;
assert.ok(motionCount < 10, `Pointer bursts must not queue hundreds of native calls: ${motionCount}`);
await mkdir('output', { recursive: true });
for (const theme of ['dark', 'light']) {
await page.evaluate(async mode => { const { applyAppearance } = await import('/src/lib/theme/appearance.ts'); applyAppearance({ theme: 'default', mode }); }, theme);
await page.mouse.click(x, y, { button: 'middle' });
await page.screenshot({ path: `output/browser-interaction-${theme}.png` });
await page.keyboard.press('Escape');
async function paint() {
if (painting || !engine.page || !pendingFrame) return;
painting = true;
const frame = pendingFrame; pendingFrame = undefined;
await engine.page.evaluate(value => window.__TEST__?.emit('browser-frame', value), frame).catch(() => {});
painting = false;
if (pendingFrame) void paint();
}
await page.setViewportSize({ width: 420, height: 650 });
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
await page.setViewportSize({ width: 1280, height: 800 });
await page.keyboard.press('Control+t');
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
await page.waitForFunction(() => document.querySelectorAll('[data-browser-state="ready"]').length >= 2);
assert.equal((await rpc('state')).tabs.length, 2, 'The center new-tab path must still open a browser tab.');
assert.deepEqual(errors, []);
await writeFile(`output/browser-interaction-${process.env.BROWSER_TEST_SCALE || 1}x.json`, JSON.stringify({ decodedFps, scrolled, pointerBurstCalls: motionCount, wheelBurstCalls, passed: ['Native text entry, clipboard, composition and context menus', 'Native middle-button scrolling on both axes', 'Escape, click, drag release and focus loss stop scrolling', 'Pointer and wheel bursts coalesce during animation', 'Both themes and narrow layout', 'Toolbar plus removed and center new-tab retained'] }, null, 2));
console.log('PASS browser UI with real Electron typing, clipboard, composition, page menus, autoscroll, pointer coalescing and center new-tab action');
} finally {
await browser.close();
await rpc('shutdown').catch(() => {}); child.kill();
await new Promise((resolve, reject) => {
child.on('error', reject);
child.on('message', message => {
if (message.ready) resolve();
if (message.id) {
const callback = pending.get(message.id); pending.delete(message.id);
if (message.error) callback?.reject(Error(message.error)); else callback?.resolve(message.result);
}
if (message.event?.event === 'frame') { pendingFrame = message.event; void paint(); }
else if (message.event && engine.page) void engine.page.evaluate(value => window.__TEST__?.emit('browser-state', value), message.event).catch(() => {});
});
});
engine.stop = async () => { await engine.rpc('shutdown').catch(() => {}); child.kill(); };
return engine;
}
/** Serve an empty page. A tab on about:blank shows the host background instead of frames (docs/ui-design.md:218). */
async function startFixture() {
const server = createServer((_request, response) => { response.writeHead(200, { 'content-type': 'text/html' }); response.end('<!doctype html><title>Fixture</title><body></body>'); });
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
return { url: `http://127.0.0.1:${server.address().port}/`, close: () => new Promise(resolve => server.close(resolve)) };
}
await runSmoke('browser/interaction', async ({ browser }) => {
const engine = await startEngine();
const fixture = await startFixture();
const { rpc, commands } = engine;
try {
const page = engine.page = await openPage(browser, { viewport: { width: 1280, height: 800 }, deviceScaleFactor: scale, timeout: 30000 });
await page.exposeFunction('browserRpc', async (command, args) => { const entry = { command, args, start: Date.now() }; commands.push(entry); const result = await rpc(command, args); entry.elapsed = Date.now() - entry.start; return result; });
await mockTauri(page, {
commands: () => ({
browser_connect: () => 'test-session',
browser_request: ({ command, args }) => window.browserRpc(command, args),
workspace_last_path: () => null,
plugins_snapshot: () => ({ root: 'test', plugins: [] }),
'plugin:window|is_maximized': () => false,
}),
});
const output = await outputDir('browser/interaction');
await page.goto(smokeUrl);
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
const surface = page.getByRole('application', { name: 'Web page', exact: true });
const ready = page.locator('[data-browser-state="ready"]');
await ready.waitFor();
// The browser toolbar has no new-tab button. The header globe button opens browser tabs
// (src/lib/layout/Workbench.svelte:1300; docs/user-guide.md:177).
assert.equal(await ready.getByRole('button', { name: /New browser tab/ }).count(), 0);
const tabId = await ready.getAttribute('data-browser-tab');
const evaluate = code => rpc('testEvaluate', { tabId, code });
// Load an empty page first: the host shows frames only for loaded pages (src/lib/browser/Browser.svelte:18,264).
await rpc('navigate', { tabId, input: fixture.url });
await page.locator('.browser:not(.blank)[data-browser-state="ready"]').waitFor();
// Input reaches the engine asynchronously, so poll the page for up to five seconds before asserting.
async function expectRemote(code, expected) {
for (let attempt = 0; attempt < 100 && await evaluate(code) !== expected; attempt++) await page.waitForTimeout(50);
assert.equal(await evaluate(code), expected);
}
await evaluate(`document.body.innerHTML='<input id="typing" style="position:absolute;left:40px;top:40px;width:300px;height:40px"><a href="https://example.com/" style="position:absolute;left:40px;top:130px">Example link</a><p style="position:absolute;left:40px;top:200px">Page text</p>';true;`);
const initialBox = await surface.boundingBox();
await page.mouse.click(initialBox.x + 100, initialBox.y + 60);
await page.keyboard.type('Hello World!');
await expectRemote('document.querySelector("#typing").value', 'Hello World!');
await page.keyboard.press('Control+a'); await page.keyboard.press('Control+c');
await page.keyboard.press('End'); await page.keyboard.press('Control+v');
await expectRemote('document.querySelector("#typing").value', 'Hello World!Hello World!');
await page.getByRole('textbox', { name: 'Web page text input' }).evaluate(node => {
node.dispatchEvent(new CompositionEvent('compositionstart', { bubbles: true }));
node.dispatchEvent(new CompositionEvent('compositionend', { bubbles: true, data: '日本語' }));
});
await expectRemote('document.querySelector("#typing").value.endsWith("日本語")', true);
await page.mouse.click(initialBox.x + 100, initialBox.y + 60, { button: 'right' });
await page.getByRole('menu', { name: 'Browser page actions' }).waitFor();
await page.getByRole('menuitem', { name: 'Select all Ctrl+A', exact: true }).click();
await expectRemote('document.querySelector("#typing").selectionEnd - document.querySelector("#typing").selectionStart', 27);
await page.mouse.click(initialBox.x + 70, initialBox.y + 138, { button: 'right' });
await page.getByRole('menuitem', { name: 'Copy link address', exact: true }).waitFor();
await page.keyboard.press('Escape');
assert.equal(await page.getByRole('menu', { name: 'Browser page actions' }).count(), 0);
await page.mouse.click(initialBox.x + 70, initialBox.y + 138, { button: 'right' });
await page.getByRole('menuitem', { name: 'Copy link address', exact: true }).click();
await page.mouse.click(initialBox.x + 100, initialBox.y + 60);
await page.keyboard.press('Control+a'); await page.keyboard.press('Control+v');
await expectRemote('document.querySelector("#typing").value', 'https://example.com/');
await evaluate(`document.body.innerHTML='<canvas width="1000" height="700"></canvas>'; const c=document.querySelector('canvas').getContext('2d'); let n=0; window.testAnimate=true; function draw(){ c.fillStyle='#fff';c.fillRect(0,0,1000,700);c.fillStyle='#5482ff';c.fillRect(n++*5%900,200,80,80);if(window.testAnimate)requestAnimationFrame(draw); } draw();true;`);
await page.locator('.surface img').waitFor();
await page.evaluate(() => { window.decodedFrames = 0; document.querySelector('.surface img').addEventListener('load', () => window.decodedFrames++); });
await page.waitForTimeout(3000);
const decodedFps = await page.evaluate(() => window.decodedFrames / 3);
assert.ok(decodedFps >= 24, `The host image surface must decode at least 24 FPS: ${decodedFps}`);
const wheelCount = () => commands.filter(call => call.command === 'input' && call.args.input.type === 'mouseWheel').length;
const beforeWheels = wheelCount();
await surface.evaluate(node => {
const bounds = node.getBoundingClientRect();
for (let index = 0; index < 500; index++) node.dispatchEvent(new WheelEvent('wheel', {
bubbles: true, cancelable: true, clientX: bounds.x + 100, clientY: bounds.y + 100, deltaY: index < 250 ? 80 : -80,
}));
});
await page.waitForTimeout(200);
const wheelBurstCalls = wheelCount() - beforeWheels;
assert.ok(wheelBurstCalls <= 3, `Animated pages must not accumulate wheel input: ${wheelBurstCalls}`);
await evaluate('window.testAnimate=false;true;');
await evaluate(`document.body.innerHTML='<div style="width:4000px;height:6000px;background:linear-gradient(45deg,white,steelblue)"><h1>Native scroll fixture</h1></div>'; true;`);
await page.locator('.surface img').waitFor();
const box = await surface.boundingBox();
const x = box.x + 220, y = box.y + 180;
await page.mouse.click(x, y, { button: 'middle' });
await page.mouse.move(x + 90, y + 120);
await page.waitForTimeout(1500);
const scrolled = await evaluate('({x:scrollX,y:scrollY})');
assert.ok(scrolled.x > 50 && scrolled.y > 100, `Middle-button motion must scroll real Chromium: ${JSON.stringify({ scrolled, anchor: await page.locator('.scroll-anchor').count(), wheels: commands.filter(c => c.command === 'input' && c.args.input.type === 'mouseWheel'), errors: page.errors })}`);
await page.keyboard.press('Escape');
await page.waitForTimeout(350);
const stopped = await evaluate('scrollY');
await page.waitForTimeout(200);
assert.equal(await evaluate('scrollY'), stopped);
assert.equal(await page.locator('.scroll-anchor').count(), 0);
await page.mouse.move(x, y); await page.mouse.down({ button: 'middle' }); await page.mouse.move(x, y - 90);
await page.waitForTimeout(300); await page.mouse.up({ button: 'middle' });
await page.waitForTimeout(100);
assert.equal(await page.locator('.scroll-anchor').count(), 0, 'Release after a middle-button drag stops scrolling.');
assert.ok(await evaluate('scrollY') < stopped, 'Moving above the anchor scrolls upward.');
await page.mouse.click(x, y, { button: 'middle' });
await page.mouse.click(x, y, { button: 'left' });
assert.equal(await page.locator('.scroll-anchor').count(), 0, 'A click stops latched scrolling.');
await page.mouse.click(x, y, { button: 'middle' });
await page.getByRole('textbox', { name: 'Address or search' }).focus();
assert.equal(await page.locator('.scroll-anchor').count(), 0, 'Focus loss stops scrolling.');
const motionCount = () => commands.filter(c => c.command === 'input' && c.args.input.type === 'mouseMove').length;
const beforeMotion = motionCount();
await surface.dispatchEvent('mousemove', { clientX: x, clientY: y });
await page.evaluate(({ x, y }) => { const node = document.querySelector('.surface'); for (let i = 0; i < 500; i++) node.dispatchEvent(new MouseEvent('mousemove', { clientX: x + i % 20, clientY: y, bubbles: true })); }, { x, y });
await page.waitForTimeout(100);
const pointerBurstCalls = motionCount() - beforeMotion;
assert.ok(pointerBurstCalls < 10, `Pointer bursts must not queue hundreds of native calls: ${pointerBurstCalls}`);
for (const theme of ['dark', 'light']) {
await page.evaluate(async mode => { const { applyAppearance } = await import('/src/lib/theme/appearance.ts'); applyAppearance({ theme: 'default', mode }); }, theme);
await page.mouse.click(x, y, { button: 'middle' });
await page.screenshot({ path: path.join(output, `browser-interaction-${theme}.png`) });
await page.keyboard.press('Escape');
}
await page.setViewportSize({ width: 420, height: 650 });
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
await page.setViewportSize({ width: 1280, height: 800 });
await page.keyboard.press('Control+t');
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
await page.waitForFunction(() => document.querySelectorAll('[data-browser-state="ready"]').length >= 2);
assert.equal((await rpc('state')).tabs.length, 2, 'The center new-tab path must still open a browser tab.');
assert.deepEqual(page.errors, []);
await writeFile(path.join(output, `browser-interaction-${scale}x.json`), JSON.stringify({ decodedFps, scrolled, pointerBurstCalls, wheelBurstCalls, passed: ['Native text entry, clipboard, composition and context menus', 'Native middle-button scrolling on both axes', 'Escape, click, drag release and focus loss stop scrolling', 'Pointer and wheel bursts coalesce during animation', 'Both themes and narrow layout', 'Toolbar plus removed and center new-tab retained'] }, null, 2));
console.log('PASS browser UI with real Electron typing, clipboard, composition, page menus, autoscroll, pointer coalescing and center new-tab action');
} finally {
await engine.stop();
await fixture.close();
}
});
+40 -49
View File
@@ -1,44 +1,36 @@
import { createRequire } from 'node:module';
import { mkdir } from 'node:fs/promises';
// Browser settings choice menus: keyboard selection and dismissal, saving, long profile lists, both themes, narrow layout, and cleanup.
import assert from 'node:assert/strict';
const { chromium } = createRequire(import.meta.url)(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: 1100, height: 850 } });
const errors = [];
page.on('pageerror', error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const snapshot = {
profiles: [{ id: 'user', name: 'Personal' }, { id: 'work', name: 'Work' }], tabs: [], bookmarks: [],
settings: { search: 'duckduckgo', adblock: true, linkDestination: 'internal', personalRules: '', homepage: '', filterLists: [] },
};
window.browserMenuTest = { snapshot, calls: [] };
let sequence = 0;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'settings-main' }, currentWebview: { label: 'settings-main' } },
transformCallback: () => ++sequence, unregisterCallback: () => {},
invoke: async (command, args = {}) => {
if (command === 'plugin:event|listen') return args.handler;
if (command === 'plugin:event|unlisten') return;
if (command === 'browser_connect') return 'menu-session';
if (command === 'browser_stop' || command === 'plugins_release') return;
if (command === 'plugins_snapshot') return { root: 'test', plugins: [] };
if (command.startsWith('plugin:window|')) return false;
if (command !== 'browser_request') throw Error('Unhandled IPC: ' + command);
const details = args.args || {};
window.browserMenuTest.calls.push({ command: args.command, ...details });
if (args.command === 'webData') return { profileId: details.profileId, cookies: [], history: [] };
if (args.command === 'settings') Object.assign(snapshot.settings, details);
return structuredClone(snapshot);
import path from 'node:path';
import { mockTauri, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
await runSmoke('browser/settingsMenus', async ({ page }) => {
await mockTauri(page, {
label: 'settings-main',
commands: test => {
const snapshot = {
profiles: [{ id: 'user', name: 'Personal' }, { id: 'work', name: 'Work' }], tabs: [], bookmarks: [],
settings: { search: 'duckduckgo', adblock: true, linkDestination: 'internal', personalRules: '', homepage: '', filterLists: [] },
};
// `requests` records browser requests; `calls` records every IPC command.
Object.assign(test, { snapshot, requests: [] });
return {
browser_connect: () => 'menu-session',
plugins_snapshot: () => ({ root: 'test', plugins: [] }),
'plugin:window|is_maximized': () => false,
browser_request: ({ command, args = {} }) => {
test.requests.push({ command, ...args });
if (command === 'webData') return { profileId: args.profileId, cookies: [], history: [] };
if (command === 'settings') Object.assign(snapshot.settings, args);
return structuredClone(snapshot);
},
};
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const menu = name => page.getByRole('menu', { name, exact: true });
const trigger = name => page.getByRole('button', { name, exact: true });
try {
await mkdir('output/todo-menus', { recursive: true });
await page.goto((process.env.SMOKE_URL || 'http://127.0.0.1:1420') + '/?settingsWindow=true');
});
const output = await outputDir('browser/settingsMenus');
const shot = name => page.screenshot({ path: path.join(output, name) });
const menu = name => page.getByRole('menu', { name, exact: true });
const trigger = name => page.getByRole('button', { name, exact: true });
await page.goto(smokeUrl + '/?settingsWindow=true');
await trigger('Browser').click();
await trigger('Search engine').waitFor();
for (const mode of ['dark', 'light']) {
@@ -49,7 +41,7 @@ try {
await engines.waitFor();
assert.equal(await engines.getByRole('menuitemradio', { name: 'DuckDuckGo' }).getAttribute('aria-checked'), 'true');
assert.equal(await engines.evaluate(node => getComputedStyle(node).borderColor), 'rgba(0, 0, 0, 0)');
await page.screenshot({ path: `output/todo-menus/search-${mode}.png` });
await shot(`search-${mode}.png`);
await page.keyboard.press('End');
await page.keyboard.press('Space');
assert.equal(await trigger('Search engine').innerText(), 'Bing');
@@ -60,11 +52,11 @@ try {
await trigger('Profile').focus();
await page.keyboard.press('Space');
await menu('Profile').waitFor();
await page.screenshot({ path: `output/todo-menus/profile-${mode}.png` });
await shot(`profile-${mode}.png`);
await page.keyboard.press('ArrowDown');
await page.keyboard.press('Enter');
await page.waitForFunction(() => document.querySelector('button[aria-label="Profile"]')?.textContent === 'Work');
await page.waitForFunction(() => window.browserMenuTest.calls.some(call => call.command === 'webData' && call.profileId === 'work'));
await page.waitForFunction(() => window.__TEST__.requests.some(request => request.command === 'webData' && request.profileId === 'work'));
await trigger('Profile').click();
await page.keyboard.press('Home');
await page.keyboard.press('Enter');
@@ -72,24 +64,24 @@ try {
await trigger('Search engine').click();
const bounds = await engines.boundingBox();
assert.ok(bounds.x >= 8 && bounds.x + bounds.width <= 512);
await page.screenshot({ path: `output/todo-menus/narrow-${mode}.png` });
await shot(`narrow-${mode}.png`);
await page.keyboard.press('Escape');
assert.equal(await trigger('Search engine').evaluate(node => node === document.activeElement), true);
await page.setViewportSize({ width: 1100, height: 850 });
}
await trigger('Search engine').click();
await menu('Search engine').getByRole('menuitemradio', { name: 'Google', exact: true }).click();
assert.equal(await page.evaluate(() => window.browserMenuTest.calls.filter(call => call.command === 'settings').length), 0, 'A choice does not submit the form');
assert.equal(await page.evaluate(() => window.__TEST__.requests.filter(request => request.command === 'settings').length), 0, 'A choice does not submit the form');
await trigger('Save browser settings').click();
await page.waitForFunction(() => window.browserMenuTest.snapshot.settings.search === 'google');
await page.evaluate(async () => { const { state } = await import('/src/lib/browser/client.ts'); const snapshot = window.browserMenuTest.snapshot; snapshot.profiles.push(...Array.from({ length: 60 }, (_, i) => ({ id: 'p' + i, name: 'Profile ' + i }))); state.set(structuredClone(snapshot)); });
await page.waitForFunction(() => window.__TEST__.snapshot.settings.search === 'google');
await page.evaluate(async () => { const { state } = await import('/src/lib/browser/client.ts'); const snapshot = window.__TEST__.snapshot; snapshot.profiles.push(...Array.from({ length: 60 }, (_, i) => ({ id: 'p' + i, name: 'Profile ' + i }))); state.set(structuredClone(snapshot)); });
await page.setViewportSize({ width: 520, height: 700 });
await trigger('Profile').click();
const profiles = menu('Profile');
assert.equal(await profiles.evaluate(node => node.scrollHeight > node.clientHeight), true, 'Long profile lists scroll');
await page.keyboard.press('End');
assert.equal(await profiles.getByRole('menuitemradio', { name: 'Profile 59', exact: true }).evaluate(node => node === document.activeElement), true);
await page.screenshot({ path: 'output/todo-menus/profile-long-narrow.png' });
await shot('profile-long-narrow.png');
await page.keyboard.press('Escape');
assert.equal(await trigger('Profile').evaluate(node => node === document.activeElement), true);
await trigger('Profile').click();
@@ -103,6 +95,5 @@ try {
await trigger('Search engine').click();
await trigger('General').click();
assert.equal(await page.locator('.rs-menu').count(), 0, 'Leaving Browser closes the menu');
assert.deepEqual(errors, []);
console.log('PASS: browser choices, persistence, keyboard selection and dismissal, long profiles, both themes, narrow layout, and cleanup.');
} finally { await browser.close(); }
}, { viewport: { width: 1100, height: 850 }, timeout: 30000 });
+195 -208
View File
@@ -1,218 +1,205 @@
// Run against pnpm dev with PLAYWRIGHT_MODULE and CHROME_PATH if needed.
import { createRequire } from 'node:module';
import { mkdir } from 'node:fs/promises';
// Browser web data settings: cookie and history lists, filters, removal, profile isolation, stale-response guards, and narrow layouts.
import assert from 'node:assert/strict';
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1100, height: 850 } });
page.setDefaultTimeout(10000);
const errors = [];
page.on('pageerror', error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const snapshot = {
profiles: [{ id: 'user', name: 'Personal' }, { id: 'work', name: 'Work' }],
tabs: [{ id: 'open-tab', profileId: 'user', url: 'https://example.com', title: 'Keep open', loading: false, blocked: 0, canBack: false, canForward: false }],
bookmarks: [],
settings: { search: 'duckduckgo', adblock: true, linkDestination: 'internal', personalRules: '', homepage: '', filterLists: [] },
};
const longUrl = 'https://very-long-domain.example/' + 'long-path-segment-'.repeat(30);
const data = {
user: {
profileId: 'user',
cookies: [
{ id: 'shared-cookie', name: 'session', domain: 'personal.example', path: '/account' },
{ id: 'second-cookie', name: '', domain: 'another.example', path: '/settings' },
{ id: 'long-cookie', name: 'Long cookie ' + 'value'.repeat(30), domain: 'long.example', path: '/' + 'path'.repeat(30) },
],
history: [
{ id: 'shared-visit', title: 'Personal guide', url: 'https://personal.example/guide', at: 1700000000000 },
{ id: 'second-visit', title: '', url: 'https://another.example/document', at: 1700000001000 },
{ id: 'long-visit', title: 'Long visit ' + 'title'.repeat(30), url: longUrl, at: 1700000002000 },
],
import path from 'node:path';
import { mockTauri, outputDir, runSmoke, settle as settleFrames, smokeUrl } from '../_harness/index.mjs';
await runSmoke('browser/webData', async ({ page }) => {
await mockTauri(page, {
label: 'settings-main',
commands: test => {
const snapshot = {
profiles: [{ id: 'user', name: 'Personal' }, { id: 'work', name: 'Work' }],
tabs: [{ id: 'open-tab', profileId: 'user', url: 'https://example.com', title: 'Keep open', loading: false, blocked: 0, canBack: false, canForward: false }],
bookmarks: [],
settings: { search: 'duckduckgo', adblock: true, linkDestination: 'internal', personalRules: '', homepage: '', filterLists: [] },
};
const longUrl = 'https://very-long-domain.example/' + 'long-path-segment-'.repeat(30);
const data = {
user: {
profileId: 'user',
cookies: [
{ id: 'shared-cookie', name: 'session', domain: 'personal.example', path: '/account' },
{ id: 'second-cookie', name: '', domain: 'another.example', path: '/settings' },
{ id: 'long-cookie', name: 'Long cookie ' + 'value'.repeat(30), domain: 'long.example', path: '/' + 'path'.repeat(30) },
],
history: [
{ id: 'shared-visit', title: 'Personal guide', url: 'https://personal.example/guide', at: 1700000000000 },
{ id: 'second-visit', title: '', url: 'https://another.example/document', at: 1700000001000 },
{ id: 'long-visit', title: 'Long visit ' + 'title'.repeat(30), url: longUrl, at: 1700000002000 },
],
},
work: {
profileId: 'work',
cookies: [{ id: 'shared-cookie', name: 'session', domain: 'work.example', path: '/account' }],
history: [{ id: 'shared-visit', title: 'Work guide', url: 'https://work.example/guide', at: 1700000000000 }],
},
};
// `requests` records browser requests; `hold` keys delay a request until the test releases it.
const check = Object.assign(test, { data, snapshot, requests: [], hold: [], pending: [], failNext: {} });
return {
browser_connect: () => 'web-data-session',
plugins_snapshot: () => ({ root: 'test', plugins: [] }),
'plugin:window|is_maximized': () => false,
browser_request: async ({ session, command: operation, args: details = {} }) => {
if (session !== 'web-data-session') throw Error('Missing browser session');
const key = `${operation}:${details.profileId}`;
check.requests.push({ operation, ...details });
if (check.failNext[key]) { const message = check.failNext[key]; delete check.failNext[key]; throw Error(message); }
const nextData = operation === 'webData' ? structuredClone(data[details.profileId]) : null;
if (check.hold.includes(key)) await new Promise((resolve, reject) => check.pending.push({ key, resolve, reject }));
if (operation === 'webData') return nextData;
if (operation === 'removeCookie') data[details.profileId].cookies = data[details.profileId].cookies.filter(item => item.id !== details.id);
else if (operation === 'removeHistory') data[details.profileId].history = data[details.profileId].history.filter(item => item.id !== details.id);
else if (!['state', 'settings'].includes(operation)) throw Error('Unhandled browser operation: ' + operation);
return structuredClone(snapshot);
},
};
},
work: {
profileId: 'work',
cookies: [{ id: 'shared-cookie', name: 'session', domain: 'work.example', path: '/account' }],
history: [{ id: 'shared-visit', title: 'Work guide', url: 'https://work.example/guide', at: 1700000000000 }],
},
};
const check = window.webDataTest = { data, snapshot, calls: [], hold: [], pending: [], failNext: {} };
let sequence = 0;
const callbacks = new Map();
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'settings-main' }, currentWebview: { label: 'settings-main' } },
transformCallback: fn => { const id = ++sequence; callbacks.set(id, fn); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === 'plugin:event|listen') return args.handler;
if (command === 'plugin:event|unlisten') return;
if (command === 'browser_connect') return 'web-data-session';
if (command === 'browser_stop' || command === 'plugins_release') return;
if (command === 'plugins_snapshot') return { root: 'test', plugins: [] };
if (command.startsWith('plugin:window|')) return false;
if (command !== 'browser_request') throw Error('Unhandled IPC: ' + command);
if (args.session !== 'web-data-session') throw Error('Missing browser session');
const operation = args.command, details = args.args || {}, key = `${operation}:${details.profileId}`;
check.calls.push({ operation, ...details });
if (check.failNext[key]) { const message = check.failNext[key]; delete check.failNext[key]; throw Error(message); }
const nextData = operation === 'webData' ? structuredClone(data[details.profileId]) : null;
if (check.hold.includes(key)) await new Promise((resolve, reject) => check.pending.push({ key, resolve, reject }));
if (operation === 'webData') return nextData;
if (operation === 'removeCookie') data[details.profileId].cookies = data[details.profileId].cookies.filter(item => item.id !== details.id);
else if (operation === 'removeHistory') data[details.profileId].history = data[details.profileId].history.filter(item => item.id !== details.id);
else if (!['state', 'settings'].includes(operation)) throw Error('Unhandled browser operation: ' + operation);
return structuredClone(snapshot);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
});
const section = page.getByRole('region', { name: 'Individual web data', exact: true });
const profile = page.getByRole('button', { name: 'Profile', exact: true });
async function selectProfile(id) {
await profile.click();
await page.getByRole('menuitemradio', { name: id === 'work' ? 'Work' : 'Personal', exact: true }).click();
}
const kind = section.getByRole('button', { name: 'Web data type', exact: true });
async function selectKind(value) { await kind.click(); await page.getByRole('menuitemradio', { name: value === 'cookies' ? 'Cookies' : 'History', exact: true }).click(); }
const filter = section.getByRole('searchbox', { name: 'Filter web data', exact: true });
const refresh = section.getByRole('button', { name: 'Refresh', exact: true });
const personalCookie = () => section.getByRole('button', { name: 'Remove cookie session from personal.example at /account', exact: true });
const workCookie = () => section.getByRole('button', { name: 'Remove cookie session from work.example at /account', exact: true });
const settle = () => section.locator('.entries[aria-busy="false"]').waitFor();
async function hold(key) { await page.evaluate(key => { window.webDataTest.hold.push(key); }, key); }
async function pending(key) { await page.waitForFunction(key => window.webDataTest.pending.some(item => item.key === key), key); }
async function release(key, error) {
await page.evaluate(({ key, error }) => {
const check = window.webDataTest;
check.hold = check.hold.filter(item => item !== key);
const index = check.pending.findIndex(item => item.key === key), item = check.pending.splice(index, 1)[0];
if (!item) throw Error('No pending request for ' + key);
if (error) item.reject(Error(error)); else item.resolve();
}, { key, error });
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
}
try {
await page.goto((process.env.SMOKE_URL || 'http://127.0.0.1:1420') + '/?settingsWindow=true');
await page.getByRole('button', { name: 'Browser', exact: true }).click();
await personalCookie().waitFor();
assert.equal(await section.locator('.entry').count(), 3);
assert.equal(await section.getByText('(unnamed cookie)', { exact: true }).count(), 1);
await filter.fill('PERSONAL.EXAMPLE');
assert.equal(await section.locator('.entry').count(), 1);
await filter.fill('/settings');
assert.equal(await section.locator('.entry').count(), 1);
await filter.fill('no matches');
await section.getByText('No matching cookies.', { exact: true }).waitFor();
await filter.fill('session');
await personalCookie().click();
await settle();
await section.getByText('No matching cookies.', { exact: true }).waitFor();
assert.equal(await page.evaluate(() => window.webDataTest.data.work.cookies.length), 1, 'Removing a cookie preserves another profile with the same ID');
await selectKind('history');
await filter.fill('GUIDE');
await section.getByRole('button', { name: 'Remove history entry Personal guide', exact: true }).click();
await settle();
await section.getByText('No matching history.', { exact: true }).waitFor();
assert.equal(await page.evaluate(() => window.webDataTest.data.work.history.length), 1);
await filter.fill('another.example/document');
await section.getByRole('button', { name: 'Remove history entry https://another.example/document', exact: true }).waitFor();
assert.equal(await section.locator('.entry').count(), 1);
await selectProfile('work');
await settle();
assert.equal(await filter.inputValue(), '', 'Profile changes clear the prior filter');
await section.getByText('Work guide', { exact: true }).waitFor();
await selectKind('cookies');
await workCookie().waitFor();
});
const output = await outputDir('browser/webData');
const section = page.getByRole('region', { name: 'Individual web data', exact: true });
const profile = page.getByRole('button', { name: 'Profile', exact: true });
async function selectProfile(id) {
await profile.click();
await page.getByRole('menuitemradio', { name: id === 'work' ? 'Work' : 'Personal', exact: true }).click();
}
const kind = section.getByRole('button', { name: 'Web data type', exact: true });
async function selectKind(value) { await kind.click(); await page.getByRole('menuitemradio', { name: value === 'cookies' ? 'Cookies' : 'History', exact: true }).click(); }
const filter = section.getByRole('searchbox', { name: 'Filter web data', exact: true });
const refresh = section.getByRole('button', { name: 'Refresh', exact: true });
const personalCookie = () => section.getByRole('button', { name: 'Remove cookie session from personal.example at /account', exact: true });
const workCookie = () => section.getByRole('button', { name: 'Remove cookie session from work.example at /account', exact: true });
const settle = () => section.locator('.entries[aria-busy="false"]').waitFor();
async function hold(key) { await page.evaluate(key => { window.__TEST__.hold.push(key); }, key); }
async function pending(key) { await page.waitForFunction(key => window.__TEST__.pending.some(item => item.key === key), key); }
async function release(key, error) {
await page.evaluate(({ key, error }) => {
const check = window.__TEST__;
check.hold = check.hold.filter(item => item !== key);
const index = check.pending.findIndex(item => item.key === key), item = check.pending.splice(index, 1)[0];
if (!item) throw Error('No pending request for ' + key);
if (error) item.reject(Error(error)); else item.resolve();
}, { key, error });
await settleFrames(page);
}
try {
await page.goto(smokeUrl + '/?settingsWindow=true');
await page.getByRole('button', { name: 'Browser', exact: true }).click();
await personalCookie().waitFor();
assert.equal(await section.locator('.entry').count(), 3);
assert.equal(await section.getByText('(unnamed cookie)', { exact: true }).count(), 1);
await filter.fill('PERSONAL.EXAMPLE');
assert.equal(await section.locator('.entry').count(), 1);
await filter.fill('/settings');
assert.equal(await section.locator('.entry').count(), 1);
await filter.fill('no matches');
await section.getByText('No matching cookies.', { exact: true }).waitFor();
await filter.fill('session');
await personalCookie().click();
await settle();
await section.getByText('No matching cookies.', { exact: true }).waitFor();
assert.equal(await page.evaluate(() => window.__TEST__.data.work.cookies.length), 1, 'Removing a cookie preserves another profile with the same ID');
await selectKind('history');
await filter.fill('GUIDE');
await section.getByRole('button', { name: 'Remove history entry Personal guide', exact: true }).click();
await settle();
await section.getByText('No matching history.', { exact: true }).waitFor();
assert.equal(await page.evaluate(() => window.__TEST__.data.work.history.length), 1);
await filter.fill('another.example/document');
await section.getByRole('button', { name: 'Remove history entry https://another.example/document', exact: true }).waitFor();
assert.equal(await section.locator('.entry').count(), 1);
await selectProfile('work');
await settle();
assert.equal(await filter.inputValue(), '', 'Profile changes clear the prior filter');
await section.getByText('Work guide', { exact: true }).waitFor();
await selectKind('cookies');
await workCookie().waitFor();
// A delayed successful response from the previous profile must not replace the current rows.
await hold('webData:work');
await refresh.click();
await pending('webData:work');
assert.equal(await workCookie().isDisabled(), true);
await selectProfile('user');
await settle();
await release('webData:work');
assert.equal(await workCookie().count(), 0);
assert.equal(await section.locator('.entry').count(), 2);
// A delayed successful response from the previous profile must not replace the current rows.
await hold('webData:work');
await refresh.click();
await pending('webData:work');
assert.equal(await workCookie().isDisabled(), true);
await selectProfile('user');
await settle();
await release('webData:work');
assert.equal(await workCookie().count(), 0);
assert.equal(await section.locator('.entry').count(), 2);
// The same guard must ignore an old request error.
await hold('webData:user');
await refresh.click();
await pending('webData:user');
await selectProfile('work');
await workCookie().waitFor();
await settle();
await release('webData:user', 'Stale personal error');
assert.equal(await section.getByRole('alert').count(), 0);
assert.equal(await refresh.isEnabled(), true);
// The same guard must ignore an old request error.
await hold('webData:user');
await refresh.click();
await pending('webData:user');
await selectProfile('work');
await workCookie().waitFor();
await settle();
await release('webData:user', 'Stale personal error');
assert.equal(await section.getByRole('alert').count(), 0);
assert.equal(await refresh.isEnabled(), true);
// Removal finishes for its original profile without refreshing the selected profile.
await hold('removeCookie:work');
await workCookie().click();
await pending('removeCookie:work');
await selectProfile('user');
await settle();
const readsBefore = await page.evaluate(() => window.webDataTest.calls.filter(item => item.operation === 'webData').length);
await release('removeCookie:work');
assert.equal(await profile.innerText(), 'Personal');
assert.equal(await section.locator('.entry').count(), 2);
assert.equal(await page.evaluate(() => window.webDataTest.calls.filter(item => item.operation === 'webData').length), readsBefore);
assert.equal(await page.evaluate(() => window.webDataTest.data.work.cookies.length), 0);
// Removal finishes for its original profile without refreshing the selected profile.
await hold('removeCookie:work');
await workCookie().click();
await pending('removeCookie:work');
await selectProfile('user');
await settle();
const readsBefore = await page.evaluate(() => window.__TEST__.requests.filter(item => item.operation === 'webData').length);
await release('removeCookie:work');
assert.equal(await profile.innerText(), 'Personal');
assert.equal(await section.locator('.entry').count(), 2);
assert.equal(await page.evaluate(() => window.__TEST__.requests.filter(item => item.operation === 'webData').length), readsBefore);
assert.equal(await page.evaluate(() => window.__TEST__.data.work.cookies.length), 0);
await page.evaluate(() => { window.webDataTest.failNext['webData:user'] = 'Cannot read personal data'; });
await refresh.click();
await section.getByRole('alert').filter({ hasText: 'Cannot read personal data' }).waitFor();
assert.equal(await refresh.isEnabled(), true);
await refresh.click();
await settle();
assert.equal(await section.getByRole('alert').count(), 0);
await page.evaluate(() => { window.webDataTest.failNext['removeCookie:user'] = 'Cannot remove this cookie'; });
const unnamed = section.getByRole('button', { name: 'Remove cookie from another.example at /settings', exact: true });
await unnamed.click();
await section.getByRole('alert').filter({ hasText: 'Cannot remove this cookie' }).waitFor();
assert.equal(await unnamed.isEnabled(), true);
await unnamed.click();
await settle();
assert.equal(await unnamed.count(), 0);
assert.equal(await section.getByRole('alert').count(), 0);
assert.deepEqual(await page.evaluate(() => window.webDataTest.snapshot.tabs.map(tab => tab.id)), ['open-tab']);
assert.equal(await page.evaluate(() => window.webDataTest.calls.some(item => ['closeTab', 'clearData'].includes(item.operation))), false);
await page.evaluate(() => { window.__TEST__.failNext['webData:user'] = 'Cannot read personal data'; });
await refresh.click();
await section.getByRole('alert').filter({ hasText: 'Cannot read personal data' }).waitFor();
assert.equal(await refresh.isEnabled(), true);
await refresh.click();
await settle();
assert.equal(await section.getByRole('alert').count(), 0);
await page.evaluate(() => { window.__TEST__.failNext['removeCookie:user'] = 'Cannot remove this cookie'; });
const unnamed = section.getByRole('button', { name: 'Remove cookie from another.example at /settings', exact: true });
await unnamed.click();
await section.getByRole('alert').filter({ hasText: 'Cannot remove this cookie' }).waitFor();
assert.equal(await unnamed.isEnabled(), true);
await unnamed.click();
await settle();
assert.equal(await unnamed.count(), 0);
assert.equal(await section.getByRole('alert').count(), 0);
assert.deepEqual(await page.evaluate(() => window.__TEST__.snapshot.tabs.map(tab => tab.id)), ['open-tab']);
assert.equal(await page.evaluate(() => window.__TEST__.requests.some(item => ['closeTab', 'clearData'].includes(item.operation))), false);
await mkdir('.audit/cards-2026-10-08-next', { recursive: true });
await page.setViewportSize({ width: 360, height: 800 });
for (const theme of ['dark', 'light']) {
await page.evaluate(async mode => {
const { saveAppearance } = await import('/src/lib/theme/appearance.ts');
saveAppearance({ theme: 'default', mode });
}, theme);
assert.equal(await page.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--rs-bg').trim()), theme === 'light' ? '#f3f3f3' : '#141414');
for (const dataType of ['cookies', 'history']) {
await selectKind(dataType);
await section.scrollIntoViewIfNeeded();
await page.screenshot({ path: `.audit/cards-2026-10-08-next/browser-web-data-${dataType}-${theme}.png` });
const overflow = await section.evaluate(node => {
const elements = [node, node.querySelector('.entries'), ...node.querySelectorAll('input, select, button')];
return elements.filter(element => element.scrollWidth > element.clientWidth + 1).map(element => ({ tag: element.tagName, className: element.className, width: element.clientWidth, scrollWidth: element.scrollWidth }));
});
assert.deepEqual(overflow, [], `${dataType} fits the narrow ${theme} settings view`);
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
const controls = await section.locator('input,select,button').evaluateAll(nodes => nodes.map(node => {
const rect = node.getBoundingClientRect(), style = getComputedStyle(node);
return { width: rect.width, height: rect.height, radius: parseFloat(style.borderRadius) };
}));
assert.ok(controls.every(control => control.height >= 28 && control.radius > 0));
await filter.focus();
await page.keyboard.press('Tab');
assert.equal(await refresh.evaluate(node => node === document.activeElement), true);
assert.notEqual(await refresh.evaluate(node => getComputedStyle(node).outlineStyle), 'none');
await page.setViewportSize({ width: 360, height: 800 });
for (const theme of ['dark', 'light']) {
await page.evaluate(async mode => {
const { saveAppearance } = await import('/src/lib/theme/appearance.ts');
saveAppearance({ theme: 'default', mode });
}, theme);
assert.equal(await page.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--rs-bg').trim()), theme === 'light' ? '#f3f3f3' : '#141414');
for (const dataType of ['cookies', 'history']) {
await selectKind(dataType);
await section.scrollIntoViewIfNeeded();
await page.screenshot({ path: path.join(output, `browser-web-data-${dataType}-${theme}.png`) });
const overflow = await section.evaluate(node => {
const elements = [node, node.querySelector('.entries'), ...node.querySelectorAll('input, select, button')];
return elements.filter(element => element.scrollWidth > element.clientWidth + 1).map(element => ({ tag: element.tagName, className: element.className, width: element.clientWidth, scrollWidth: element.scrollWidth }));
});
assert.deepEqual(overflow, [], `${dataType} fits the narrow ${theme} settings view`);
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
const controls = await section.locator('input,select,button').evaluateAll(nodes => nodes.map(node => {
const rect = node.getBoundingClientRect(), style = getComputedStyle(node);
return { width: rect.width, height: rect.height, radius: parseFloat(style.borderRadius) };
}));
assert.ok(controls.every(control => control.height >= 28 && control.radius > 0));
await filter.focus();
await page.keyboard.press('Tab');
assert.equal(await refresh.evaluate(node => node === document.activeElement), true);
assert.notEqual(await refresh.evaluate(node => getComputedStyle(node).outlineStyle), 'none');
}
}
} catch (error) {
console.error(await page.locator('body').innerText());
throw error;
}
assert.deepEqual(errors, []);
console.log('PASS: cookie/history lists and removal, filters, profile isolation, stale success/error/removal guards, recovery, open-tab preservation, and 360px controls in both themes.');
} catch (error) {
console.error(await page.locator('body').innerText());
console.error('Page errors:', errors);
throw error;
} finally { await browser.close(); }
}, { viewport: { width: 1100, height: 850 } });
+22 -84
View File
@@ -1,80 +1,23 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
// Checklist entry: keyboard marker editing, checkbox toggles, and pasted HTML tables in both themes and a narrow layout.
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 page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
await mkdir(".audit", { recursive: true });
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "spelling_menu_install") return;
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
try {
await mkdir('output/editor-clipboard-checklist', { recursive: true });
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await runSmoke("editor/checklistEntry", async ({ page }) => {
await mockTauri(page, {
commands: test => ({
...test.workspace({
root: "C:\\smoke-workspace",
files: {
"notes/welcome.md": "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n",
"notes/second.md": "# Second note\n",
"src/hello.py": "print('hello')\n",
},
}),
spelling_menu_install: () => null,
}),
});
const output = await outputDir("editor/checklistEntry");
await page.goto(smokeUrl);
await page.getByText('smoke-workspace', { exact: true }).waitFor();
await page.keyboard.press('Control+p');
await page.getByRole('textbox', { name: 'Find a file' }).fill('welcome.md');
@@ -101,10 +44,10 @@ try {
await page.setViewportSize({ width, height: width === 600 ? 760 : 1000 });
await reset();
assert.equal(await count(), 2, 'Caret at task text keeps both checkboxes');
await page.screenshot({ path: `output/editor-clipboard-checklist/${mode}-${width}-task-text.png` });
await page.screenshot({ path: `${output}/${mode}-${width}-task-text.png` });
await page.keyboard.press('ArrowLeft');
assert.equal(await count(), 1, 'ArrowLeft from text reveals the marker');
await page.screenshot({ path: `output/editor-clipboard-checklist/${mode}-${width}-task-marker.png` });
await page.screenshot({ path: `${output}/${mode}-${width}-task-marker.png` });
await page.keyboard.press('Home');
assert.equal(await count(), 1, 'Home keeps the marker editable');
await page.keyboard.press('ArrowRight');
@@ -133,7 +76,7 @@ try {
assert.doesNotMatch(pasted, /Fragment|<!--|-->/);
assert.match(pasted, /\| Ticker \| Name \|/);
assert.equal(await page.locator('.live-writer table tr').count(), 3);
await page.screenshot({ path: `output/editor-clipboard-checklist/${mode}-${width}-table-paste.png` });
await page.screenshot({ path: `${output}/${mode}-${width}-table-paste.png` });
if (width === 600) {
await page.setViewportSize({ width: 1440, height: 1000 });
await page.getByRole('button', { name: 'Files', exact: true }).click();
@@ -141,9 +84,4 @@ try {
}
}
}
assert.deepEqual(errors, []);
console.log('PASS: keyboard marker entry, task text, checkbox toggle, Windows HTML clipboard fragments, both themes and narrow layouts.');
} catch (error) {
await page.screenshot({ path: 'output/editor-clipboard-checklist/failure.png' });
throw error;
} finally { await browser.close(); }
});
+27 -79
View File
@@ -1,78 +1,31 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
// Code blocks: editing fenced and indented code in the Writer, with undo, cursor movement, preview, and save.
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 page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
await mkdir(".audit", { recursive: true });
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
import { mockTauri, runSmoke, smokeUrl } from "../_harness/index.mjs";
try {
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
await runSmoke("editor/codeBlocks", async ({ page }) => {
await mockTauri(page, {
commands: test => {
const workspace = test.workspace({
root: "C:\\smoke-workspace",
files: {
"notes/welcome.md": "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n",
"notes/second.md": "# Second note\n",
"src/hello.py": "print('hello')\n",
},
writeEvents: true,
});
test.files = workspace.files;
return {
...workspace,
// Saves send the last saved text. Reject a save when the file changed, as the backend does.
workspace_write: args => {
if (args.expected !== undefined && workspace.files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
return workspace.workspace_write(args);
},
};
},
});
await page.goto(smokeUrl);
await page.getByText("smoke-workspace", { exact: true }).waitFor();
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill("welcome.md");
@@ -126,10 +79,5 @@ try {
await page.keyboard.press("Control+s");
await page.waitForFunction(value => window.__TEST__.files.get("notes/welcome.md") === value, edited);
}
assert.deepEqual(errors, []);
console.log("PASS: Fenced and indented code editing, character deletion, selection deletion, cursor movement, undo, preview and save.");
} catch (error) {
console.error("Browser errors:", errors);
await page.screenshot({ path: ".audit/code-blocks-failure.png" });
throw error;
} finally { await browser.close(); }
});
+29 -80
View File
@@ -1,78 +1,32 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
// Dividers: thematic break syntax, width, source editing, keyboard navigation, selection, undo, and save.
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 page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
await mkdir(".audit", { recursive: true });
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
try {
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
await runSmoke("editor/dividers", async ({ page }) => {
await mockTauri(page, {
commands: test => {
const workspace = test.workspace({
root: "C:\\smoke-workspace",
files: {
"notes/welcome.md": "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n",
"notes/second.md": "# Second note\n",
"src/hello.py": "print('hello')\n",
},
writeEvents: true,
});
test.files = workspace.files;
return {
...workspace,
// Saves send the last saved text. Reject a save when the file changed, as the backend does.
workspace_write: args => {
if (args.expected !== undefined && workspace.files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
return workspace.workspace_write(args);
},
};
},
});
const output = await outputDir("editor/dividers");
await page.goto(smokeUrl);
await page.getByText("smoke-workspace", { exact: true }).waitFor();
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill("welcome.md");
@@ -97,7 +51,7 @@ try {
assert.equal(dividerStyle.border, "1px");
assert.notEqual(dividerStyle.color, "rgba(0, 0, 0, 0)");
await page.setViewportSize({ width: 1100, height: 900 });
await page.screenshot({ path: ".audit/markdown-dividers.png" });
await page.screenshot({ path: `${output}/markdown-dividers.png` });
await page.locator(".writer-divider").first().click();
assert.equal(await page.locator(".writer-divider").count(), 5);
@@ -129,10 +83,5 @@ try {
assert.ok(await divider.evaluate(node => node.getBoundingClientRect().right <= node.parentElement.getBoundingClientRect().right + 1));
}
assert.deepEqual(errors, []);
console.log("PASS: Divider syntax, width, source editing, keyboard navigation, selection, undo and save.");
} catch (error) {
console.error("Browser errors:", errors);
await page.screenshot({ path: ".audit/markdown-dividers-failure.png" });
throw error;
} finally { await browser.close(); }
});
+22 -87
View File
@@ -1,81 +1,20 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
// Writer text menu on empty and whitespace lines: submenus, disabled actions, links, the file picker, keyboard focus, both themes, a narrow window, and the IDE.
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 page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
await mkdir(".audit", { recursive: true });
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "spelling_menu_install") return;
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
try {
await mkdir('output/round4-editor-menu', { recursive: true });
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:5187');
await runSmoke("editor/emptyMenu", async ({ page }) => {
await mockTauri(page, {
commands: test => test.workspace({
root: "C:\\smoke-workspace",
files: {
"notes/welcome.md": "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n",
"notes/second.md": "# Second note\n",
"src/hello.py": "print('hello')\n",
},
}),
});
const output = await outputDir("editor/emptyMenu");
await page.goto(smokeUrl);
await page.getByText('smoke-workspace', { exact: true }).waitFor();
await page.keyboard.press('Control+p');
await page.getByRole('textbox', { name: 'Find a file' }).fill('welcome.md');
@@ -99,14 +38,14 @@ try {
for (const label of ['Add link','Add external link','Format','Paragraph','Insert','Paste','Paste as plain text','Select all']) assert.equal(await menu().getByRole('menuitem', {name:label,exact:true}).count(),1,label);
assert.equal(await menu().getByRole('menuitem',{name:'Cut',exact:true}).isDisabled(),true);
assert.equal(await menu().getByRole('menuitem',{name:'Copy',exact:true}).isDisabled(),true);
await page.screenshot({path:`output/round4-editor-menu/empty-${theme}.png`});
await page.screenshot({path:`${output}/empty-${theme}.png`});
await menu().getByRole('menuitem',{name:'Format',exact:true}).focus();
await page.keyboard.press('ArrowRight');
const format = page.getByRole('menu',{name:'Format',exact:true});
for (const label of ['Bold','Italic','Strikethrough','Highlight','Code','Math','Comment','Clear formatting']) assert.equal(await format.getByRole('menuitem',{name:label,exact:true}).count(),1);
await page.keyboard.press('End');
assert.equal(await page.getByRole('menuitem',{name:'Comment',exact:true}).evaluate(el=>el===document.activeElement),true);
await page.screenshot({path:`output/round4-editor-menu/format-${theme}.png`});
await page.screenshot({path:`${output}/format-${theme}.png`});
await page.keyboard.press('ArrowLeft');
await page.keyboard.press('Escape');
assert.equal(await page.locator('.cm-content').evaluate(el=>el===document.activeElement),true);
@@ -116,7 +55,7 @@ try {
assert.equal(await source(),'###### ');
await setSource(''); await openKeyboard();
await menu().getByRole('menuitem',{name:'Insert',exact:true}).click();
await page.screenshot({path:`output/round4-editor-menu/insert-${theme}.png`});
await page.screenshot({path:`${output}/insert-${theme}.png`});
await page.getByRole('menu',{name:'Insert',exact:true}).getByRole('menuitem',{name:'Code block',exact:true}).click();
assert.match(await source(),/^```\nCode\n```/);
await setSource(''); await openKeyboard();
@@ -131,7 +70,7 @@ try {
await setSource(''); await openKeyboard();
await menu().getByRole('menuitem',{name:'Add link',exact:true}).click();
await page.getByRole('textbox',{name:'Find a file'}).fill('second');
await page.screenshot({path:`output/round4-editor-menu/workspace-picker-${theme}.png`});
await page.screenshot({path:`${output}/workspace-picker-${theme}.png`});
await page.keyboard.press('Enter');
await page.getByRole('dialog').waitFor({state:'detached'});
assert.equal(await source(),'[[/notes/second.md]]');
@@ -151,7 +90,7 @@ try {
await page.locator('.cm-scroller').click({button:'right',position:{x:60,y:180}});
await menu().waitFor();
const box = await menu().boundingBox(); assert.ok(box.x>=8 && box.y>=8 && box.x+box.width<=552 && box.y+box.height<=412);
await page.screenshot({path:`output/round4-editor-menu/narrow-${theme}.png`});
await page.screenshot({path:`${output}/narrow-${theme}.png`});
await page.keyboard.press('Escape');
await page.setViewportSize({width:1440,height:1000});
await page.getByRole('button',{name:'Show outline',exact:true}).click();
@@ -172,10 +111,6 @@ try {
await page.getByRole('textbox',{name:'Find a file'}).fill('second');
await page.keyboard.press('Enter');
await page.getByRole('dialog').waitFor({state:'detached'});
await page.screenshot({path:'output/round4-editor-menu/ide-links.png'});
assert.deepEqual(errors,[]);
await page.screenshot({path:`${output}/ide-links.png`});
console.log('PASS: empty and whitespace Writer menus, full submenus, disabled actions, links, picker, selection, keyboard focus, two themes, narrow viewport and IDE.');
} catch(error) {
await page.screenshot({path:'output/round4-editor-menu/failure.png'});
console.error('Browser errors:',errors); throw error;
} finally { await browser.close(); }
});
+30 -84
View File
@@ -1,80 +1,32 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
// Footnotes and heading folds: the footnote menu, Reader numbering and backlinks, nested folding, keyboard toggles, and source preservation.
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 page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
await mkdir(".audit", { recursive: true });
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "spelling_menu_install") return;
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
try {
await mkdir("output/editor-october12", { recursive: true });
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
await runSmoke("editor/footnotes", async ({ page }) => {
await mockTauri(page, {
commands: test => {
const workspace = test.workspace({
root: "C:\\smoke-workspace",
files: {
"notes/welcome.md": "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n",
"notes/second.md": "# Second note\n",
"src/hello.py": "print('hello')\n",
},
writeEvents: true,
});
test.files = workspace.files;
return {
...workspace,
// Saves send the last saved text. Reject a save when the file changed, as the backend does.
workspace_write: args => {
if (args.expected !== undefined && workspace.files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
return workspace.workspace_write(args);
},
};
},
});
const output = await outputDir("editor/footnotes");
await page.goto(smokeUrl);
await page.getByText("smoke-workspace", { exact: true }).waitFor();
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill("welcome.md");
@@ -138,7 +90,7 @@ try {
const pane = button.closest('.cm-scroller').getBoundingClientRect();
return bounds.left >= pane.left && bounds.right <= pane.right;
}));
await page.screenshot({ path: `output/editor-october12/writer-${theme}-narrow.png` });
await page.screenshot({ path: `${output}/writer-${theme}-narrow.png` });
await page.keyboard.press("Space");
const borders = await page.locator(".writer-heading").evaluateAll(headings => headings.map(heading => getComputedStyle(heading).borderBottomWidth));
assert.ok(borders.every(border => border === "0px"));
@@ -157,7 +109,7 @@ try {
return bounds.left >= pane.left && bounds.right <= pane.right;
}));
assert.equal(await page.getByText("Child content.", { exact: true }).isVisible(), false);
await page.screenshot({ path: `output/editor-october12/reader-${theme}-narrow.png` });
await page.screenshot({ path: `${output}/reader-${theme}-narrow.png` });
await page.keyboard.press("Space");
assert.equal(await page.getByText("Child content.", { exact: true }).isVisible(), true);
await page.getByRole("button", { name: "Collapse Last section", exact: true }).click();
@@ -172,11 +124,5 @@ try {
}
await page.keyboard.press("Control+s");
await page.waitForFunction(value => window.__TEST__.files.get("notes/welcome.md") === value, source);
assert.deepEqual(errors, []);
console.log("PASS: footnote menu, Writer edits, Reader numbering and backlinks, nested folding, keyboard toggles, source preservation, light/dark narrow screenshots.");
} catch (error) {
console.error("Browser errors:", errors);
await page.screenshot({ path: "output/editor-october12/failure.png" });
throw error;
} finally { await browser.close(); }
␍
});
+63 -117
View File
@@ -1,117 +1,65 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
// Images dragged from the file tree: hidden source, selection, image menu actions, cancel, and source mode.
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="640" height="360"><rect width="640" height="360" fill="#486077"/><circle cx="320" cy="180" r="110" fill="#93cab5"/></svg>';
files.set("images/picture (#1).svg", btoa(svg));
files.set("images/replacement.svg", btoa(svg));
files.set("notes/welcome.md", "Above.\n\nBelow.\n");
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_write_bytes") {
if (window.__TEST__.delay) await new Promise(resolve => { window.__TEST__.resume = resolve; });
if (window.__TEST__.failWrite) throw new Error("Image write failed");
files.set(args.rel, args.base64); return;
}
if (command === "workspace_read_data_url") {
if (!files.has(args.rel)) throw new Error("missing image");
return "data:image/svg+xml;base64," + files.get(args.rel);
}
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_reveal") return;
if (command === "workspace_search") return [];
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("editor/imageNavigation", async ({ page }) => {
await mockTauri(page, {
commands: test => {
// Image files hold base64 SVG.
const svg = btoa('<svg xmlns="http://www.w3.org/2000/svg" width="640" height="360"><rect width="640" height="360" fill="#486077"/><circle cx="320" cy="180" r="110" fill="#93cab5"/></svg>');
const workspace = test.workspace({
root: "C:\\smoke-workspace",
files: {
"notes/welcome.md": "Above.\n\nBelow.\n",
"notes/second.md": "# Second note\n",
"src/hello.py": "print('hello')\n",
"images/picture (#1).svg": svg,
"images/replacement.svg": svg,
},
writeEvents: true,
});
test.files = workspace.files;
return {
...workspace,
// Saves send the last saved text. Reject a save when the file changed, as the backend does.
workspace_write: args => {
if (args.expected !== undefined && workspace.files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
return workspace.workspace_write(args);
},
workspace_read_data_url: ({ rel }) => {
if (!workspace.files.has(rel)) throw new Error("missing image");
return "data:image/svg+xml;base64," + workspace.files.get(rel);
},
workspace_reveal: () => null,
};
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
async function writer() {
await page.locator(".cm-content").waitFor();
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content"));
});
}
async function source() { return page.evaluate(() => window.__CM__.state.doc.toString()); }
async function dragFromTree(selector = ".cm-content", cancel = false) {
const row = page.locator('[data-tree-rel="images/picture (#1).svg"]');
const from = await row.boundingBox(), to = await page.locator(selector).boundingBox();
await page.mouse.move(from.x + 60, from.y + from.height / 2);
await page.mouse.down();
await page.mouse.move(to.x + 40, to.y + 10, { steps: 12 });
await page.getByText("Insert image", { exact: true }).waitFor();
assert.equal(await page.locator(".image-drop-target").count(), 1);
if (cancel) await page.keyboard.press("Escape");
await page.mouse.up();
}
async function imageMenu() {
await page.locator(".md-image-frame").first().click({ button: "right" });
await page.getByRole("menu", { name: "Image actions" }).waitFor();
}
try {
const output = await outputDir("editor/imageNavigation");
async function writer() {
await page.locator(".cm-content").waitFor();
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content"));
});
}
async function source() { return page.evaluate(() => window.__CM__.state.doc.toString()); }
async function dragFromTree(selector = ".cm-content", cancel = false) {
const row = page.locator('[data-tree-rel="images/picture (#1).svg"]');
const from = await row.boundingBox(), to = await page.locator(selector).boundingBox();
await page.mouse.move(from.x + 60, from.y + from.height / 2);
await page.mouse.down();
await page.mouse.move(to.x + 40, to.y + 10, { steps: 12 });
await page.getByText("Insert image", { exact: true }).waitFor();
assert.equal(await page.locator(".image-drop-target").count(), 1);
if (cancel) await page.keyboard.press("Escape");
await page.mouse.up();
}
async function imageMenu() {
await page.locator(".md-image-frame").first().click({ button: "right" });
await page.getByRole("menu", { name: "Image actions" }).waitFor();
}
await page.context().grantPermissions(["clipboard-read", "clipboard-write"]);
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
await page.goto(smokeUrl);
await page.getByText("smoke-workspace", { exact: true }).waitFor();
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill("welcome.md");
@@ -132,7 +80,7 @@ try {
await page.keyboard.press("Shift+F10");
await page.getByRole("menu", { name: "Image actions" }).waitFor();
assert.equal(await page.locator(".md-image-frame.is-selected").count(), 1);
await page.screenshot({ path: ".audit/image-context-menu.png" });
await page.screenshot({ path: `${output}/image-context-menu.png` });
await page.getByRole("menuitem", { name: "Copy Markdown", exact: true }).click();
assert.equal(await page.evaluate(() => navigator.clipboard.readText()), "![](../images/picture%20%28%231%29.svg)");
await imageMenu();
@@ -195,15 +143,13 @@ try {
await page.keyboard.press("Escape");
assert.equal(await page.locator(".cm-line").filter({ hasText: "![Reference]" }).count(), 0);
// The same navigator drag works in the source editor.
await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click();
// The layout switcher names its buttons by mode (src/lib/layout/EditorPane.svelte:200-208, src/lib/ui/ModeSwitcher.svelte:96).
await page.getByRole("group", { name: "Editor layout", exact: true }).hover();
await page.getByRole("button", { name: "IDE", exact: true }).click();
await page.locator(".monaco-editor textarea").waitFor();
await dragFromTree(".monaco-editor .view-lines");
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md").includes("picture%20"));
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "workspace_write_bytes").length), 0);
assert.deepEqual(errors, []);
console.log("Navigator image drag, hidden source, selection, copy, swap, remove, open, reveal, cancel and source mode passed.");
} catch (error) {
await page.screenshot({ path: ".audit/image-navigation-failure.png" });
console.error(errors); throw error;
} finally { await browser.close(); }
});
+63 -113
View File
@@ -1,110 +1,65 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
// Image drops and pastes: unique attachments, live source, zoom, delayed writes, source mode, and undo.
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_write_bytes") {
if (window.__TEST__.delay) await new Promise(resolve => { window.__TEST__.resume = resolve; });
if (window.__TEST__.failWrite) throw new Error("Image write failed");
files.set(args.rel, args.base64); return;
}
if (command === "workspace_read_data_url") {
if (!files.has(args.rel)) throw new Error("missing image");
return "data:image/svg+xml;base64," + files.get(args.rel);
}
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("editor/images", async ({ page }) => {
await mockTauri(page, {
commands: test => {
const workspace = test.workspace({
root: "C:\\smoke-workspace",
files: {
"notes/welcome.md": "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n",
"notes/second.md": "# Second note\n",
"src/hello.py": "print('hello')\n",
},
writeEvents: true,
});
test.files = workspace.files;
return {
...workspace,
// Saves send the last saved text. Reject a save when the file changed, as the backend does.
workspace_write: args => {
if (args.expected !== undefined && workspace.files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
return workspace.workspace_write(args);
},
// Image files hold base64 SVG. Tests set `delay` to hold a write until `resume()`, or `failWrite` to reject it.
workspace_write_bytes: async args => {
if (test.delay) await new Promise(resolve => { test.resume = resolve; });
if (test.failWrite) throw new Error("Image write failed");
workspace.files.set(args.rel, args.base64);
},
workspace_read_data_url: ({ rel }) => {
if (!workspace.files.has(rel)) throw new Error("missing image");
return "data:image/svg+xml;base64," + workspace.files.get(rel);
},
};
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
async function openNote(name = "welcome.md") {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
await page.locator(".cm-content").waitFor();
}
async function source() {
return page.evaluate(() => window.__CM__.state.doc.toString());
}
async function save() {
await page.keyboard.press("Control+s");
await page.waitForTimeout(100);
return page.evaluate(() => window.__TEST__.files.get("notes/welcome.md"));
}
async function drop(count = 1, selector = ".cm-content") {
await page.locator(selector).evaluate((element, count) => {
const data = new DataTransfer();
const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="900" height="600"><rect width="900" height="600" fill="#536174"/><circle cx="450" cy="260" r="140" fill="#99c9b5"/><text x="450" y="480" text-anchor="middle" font-size="40" fill="white">Image drop test</text></svg>';
for (let i = 0; i < count; i++) data.items.add(new File([svg], "picture.svg", { type: "" }));
const rect = element.getBoundingClientRect();
element.dispatchEvent(new DragEvent("drop", { bubbles: true, cancelable: true, dataTransfer: data, clientX: rect.left + 20, clientY: rect.top + 8 }));
}, count);
}
try {
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
});
const output = await outputDir("editor/images");
async function openNote(name = "welcome.md") {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
await page.locator(".cm-content").waitFor();
}
async function source() {
return page.evaluate(() => window.__CM__.state.doc.toString());
}
async function save() {
await page.keyboard.press("Control+s");
await page.waitForTimeout(100);
return page.evaluate(() => window.__TEST__.files.get("notes/welcome.md"));
}
async function drop(count = 1, selector = ".cm-content") {
await page.locator(selector).evaluate((element, count) => {
const data = new DataTransfer();
const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="900" height="600"><rect width="900" height="600" fill="#536174"/><circle cx="450" cy="260" r="140" fill="#99c9b5"/><text x="450" y="480" text-anchor="middle" font-size="40" fill="white">Image drop test</text></svg>';
for (let i = 0; i < count; i++) data.items.add(new File([svg], "picture.svg", { type: "" }));
const rect = element.getBoundingClientRect();
element.dispatchEvent(new DragEvent("drop", { bubbles: true, cancelable: true, dataTransfer: data, clientX: rect.left + 20, clientY: rect.top + 8 }));
}, count);
}
await page.goto(smokeUrl);
await page.getByText("smoke-workspace", { exact: true }).waitFor();
await openNote();
await page.evaluate(async () => {
@@ -140,7 +95,7 @@ try {
view.dispatch({ changes: { from, insert: "Edited alt" }, selection: { anchor: from + 10 } });
});
await page.locator('img[alt="Edited alt"]').waitFor();
await page.screenshot({ path: ".audit/images-editing.png" });
await page.screenshot({ path: `${output}/images-editing.png` });
await page.locator(".md-image-frame").first().hover();
await page.getByRole("button", { name: "Zoom in", exact: true }).first().click();
const zoom = page.getByRole("dialog", { name: "Image zoom" });
@@ -149,7 +104,7 @@ try {
assert.equal(await zoom.locator(".image-lightbox-scale").textContent(), "100%");
await zoom.getByRole("button", { name: "Zoom in", exact: true }).click();
assert.equal(await zoom.locator(".image-lightbox-scale").textContent(), "200%");
await page.screenshot({ path: ".audit/images-zoom.png" });
await page.screenshot({ path: `${output}/images-zoom.png` });
await zoom.getByRole("button", { name: "Fit image", exact: true }).click();
await page.keyboard.press("Escape");
assert.equal(await page.getByRole("dialog").count(), 0);
@@ -241,10 +196,5 @@ try {
await page.waitForFunction(() => document.querySelector(".md-image-frame img"));
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("notes/second.md").includes("pasted.svg"));
assert.deepEqual(errors, []);
console.log("Image drops, unique attachments, live source, zoom, async insertion, source mode and undo passed.");
} catch (error) {
await page.screenshot({ path: ".audit/images-failure.png" });
console.error(errors);
throw error;
} finally { await browser.close(); }
});
+38 -59
View File
@@ -1,57 +1,34 @@
import { createRequire } from "node:module";
import { mkdir } from "node:fs/promises";
// Writer interactions: code selection and copy, caret and scroll restore, Ctrl+click links, shared heading typography, and spelling targets.
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1280, height: 900 }, permissions: ["clipboard-read", "clipboard-write"] });
page.setDefaultTimeout(15000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\editor-interactions-smoke";
const files = new Map([
["note.md", "# Stack\n\nHardware can be reused.\nAssume speeds of 1 Gb/s.\n\n## Hardware\n\n### Router\n\n- [ ] First task\n- [ ] Second task\n\n[Local](other.md) and [Web](https://example.com) and [[other|Wiki]]\n\n```sh\npnpm install --frozen-lockfile\npnpm check\npnpm test\n```\n\n" + Array.from({ length: 80 }, (_, i) => `Paragraph ${i}.\n\n`).join("") + "```js\nconst preserve = 42;\nconsole.log(preserve);\n```\n"],
["other.md", "# Other document\n\nKeep the original tab.\n"],
]);
const callbacks = new Map(), listeners = new Map();
let sequence = 0;
const emit = (event, payload) => { for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload }); };
window.editorTest = { files, calls: [], emit };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { callbacks.set(++sequence, callback); return sequence; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
window.editorTest.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") return;
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "editor-interactions-smoke", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") { files.set(args.rel, args.contents); return; }
if (command === "workspace_list") return [...files.keys()].filter(path => !path.startsWith(".runestone/")).map(path => ({ name: path, rel_path: path, kind: "file" }));
if (command === "workspace_search") return [];
if (command === "plugin:opener|open_url" || command.startsWith("spelling_menu_")) return;
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
async function writer() {
await page.locator(".cm-content").waitFor();
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
window.writerView = EditorView.findFromDOM(document.querySelector(".cm-content"));
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("editor/interactions", async ({ page }) => {
await page.context().grantPermissions(["clipboard-read", "clipboard-write"]);
await mockTauri(page, {
commands: test => ({
...test.workspace({
root: "C:\\editor-interactions-smoke",
files: {
"note.md": "# Stack\n\nHardware can be reused.\nAssume speeds of 1 Gb/s.\n\n## Hardware\n\n### Router\n\n- [ ] First task\n- [ ] Second task\n\n[Local](other.md) and [Web](https://example.com) and [[other|Wiki]]\n\n```sh\npnpm install --frozen-lockfile\npnpm check\npnpm test\n```\n\n" + Array.from({ length: 80 }, (_, i) => `Paragraph ${i}.\n\n`).join("") + "```js\nconst preserve = 42;\nconsole.log(preserve);\n```\n",
"other.md": "# Other document\n\nKeep the original tab.\n",
},
}),
"plugin:opener|open_url": () => null,
spelling_menu_install: () => null,
}),
});
}
async function top() {
await writer();
await page.evaluate(() => { window.writerView.dispatch({ selection: { anchor: 0 } }); window.writerView.scrollDOM.scrollTop = 0; });
}
try {
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
async function writer() {
await page.locator(".cm-content").waitFor();
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
window.writerView = EditorView.findFromDOM(document.querySelector(".cm-content"));
});
}
async function top() {
await writer();
await page.evaluate(() => { window.writerView.dispatch({ selection: { anchor: 0 } }); window.writerView.scrollDOM.scrollTop = 0; });
}
await page.goto(smokeUrl);
await page.locator('[data-tree-rel="note.md"]').dblclick();
await writer();
const code = page.locator(".writer-code-line").filter({ hasText: "pnpm install" });
@@ -65,6 +42,9 @@ try {
await page.mouse.move(points.to.left, (points.to.top + points.to.bottom) / 2, { steps: 8 });
await page.mouse.up();
assert.match(await page.evaluate(() => { const view = window.writerView; return view.state.sliceDoc(view.state.selection.main.from, view.state.selection.main.to); }), /pnpm install/);
// A selection inside a code block shows its source and hides the copy button (src/lib/editor/liveMarkdown.ts:246-247).
// Move the caret out of the block, as a reader would before copying.
await page.evaluate(() => { window.writerView.dispatch({ selection: { anchor: 0 } }); });
await page.getByRole("button", { name: "Copy code", exact: true }).first().click();
assert.equal((await page.evaluate(() => navigator.clipboard.readText())).replace(/\r\n/g, "\n"), "pnpm install --frozen-lockfile\npnpm check\npnpm test\n");
console.log("PASS: first drag selects code and the copy button copies only the code body");
@@ -95,7 +75,7 @@ try {
await page.getByRole("tab", { name: "note.md", exact: true }).click();
await top();
await page.locator('.writer-link[data-href="https://example.com"]').click({ modifiers: ["Control"] });
await page.waitForFunction(() => window.editorTest.calls.some(call => call.command === "plugin:opener|open_url" && call.args.url === "https://example.com"));
await page.waitForFunction(() => window.__TEST__.calls.some(call => call.command === "plugin:opener|open_url" && call.args.url === "https://example.com"));
await page.keyboard.press("Control+e");
await page.locator(".monaco-editor").waitFor();
const linkPoint = await page.evaluate(async () => {
@@ -119,26 +99,26 @@ try {
await page.getByRole("tab", { name: "note.md", exact: true }).click();
await page.keyboard.press("Control+e");
await top();
await mkdir(".audit", { recursive: true });
const output = await outputDir("editor/interactions");
for (const theme of ["dark", "light"]) {
await page.evaluate(async mode => {
const { applyAppearance, parseAppearance } = await import("/src/lib/theme/appearance.ts");
applyAppearance({ ...parseAppearance(null), mode });
}, theme);
const writing = await page.locator(".writer-h1").first().evaluate(node => { const style = getComputedStyle(node); return { size: style.fontSize, line: style.lineHeight, family: style.fontFamily, weight: style.fontWeight }; });
await page.screenshot({ path: `.audit/editor-typography-${theme}.png` });
await page.screenshot({ path: `${output}/editor-typography-${theme}.png` });
await page.getByRole("group", { name: "Document view", exact: true }).hover();
await page.getByRole("button", { name: "Read", exact: true }).click();
const reading = await page.locator(".reading h1:not(.document-title)").first().evaluate(node => { const style = getComputedStyle(node); return { size: style.fontSize, line: style.lineHeight, family: style.fontFamily, weight: style.fontWeight }; });
assert.deepEqual(writing, reading);
await page.screenshot({ path: `.audit/reader-typography-${theme}.png` });
await page.screenshot({ path: `${output}/reader-typography-${theme}.png` });
await page.getByRole("group", { name: "Document view", exact: true }).hover();
await page.getByRole("button", { name: "Edit", exact: true }).click();
await top();
}
await page.setViewportSize({ width: 640, height: 750 });
await page.getByRole("button", { name: "Hide outline", exact: true }).click();
await page.screenshot({ path: ".audit/editor-typography-narrow.png" });
await page.screenshot({ path: `${output}/editor-typography-narrow.png` });
assert.ok(await page.locator(".cm-content").evaluate(node => node.getBoundingClientRect().width <= node.closest(".cm-scroller").getBoundingClientRect().width + 1));
const spelling = await page.evaluate(async () => {
const { isSpellingTarget } = await import("/src/lib/editor/spellingMenu.ts");
@@ -147,6 +127,5 @@ try {
return { active, readOnly };
});
assert.deepEqual(spelling, { active: true, readOnly: false });
assert.deepEqual(errors, []);
console.log("PASS: shared heading typography in both themes, narrow Writer, and textarea spelling target");
} finally { await browser.close(); }
}, { viewport: { width: 1280, height: 900 }, timeout: 15000 });
+52 -106
View File
@@ -1,100 +1,44 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
// Markdown text menu in source and writing modes: formatting, paragraphs, tables, links, extraction, clipboard, and stale selections.
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
const showcase = await readFile(new URL("../../../fixtures/reader-showcase.md", import.meta.url), "utf8");
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("editor/markdownMenu", async ({ page }) => {
await mockTauri(page, {
commands: test => {
const workspace = test.workspace({
root: "C:\\smoke-workspace",
files: {
"notes/welcome.md": "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n",
"notes/second.md": "# Second note\n",
"src/hello.py": "print('hello')\n",
},
writeEvents: true,
});
test.files = workspace.files;
return {
...workspace,
// Saves send the last saved text. Reject a save when the file changed, as the backend does.
workspace_write: args => {
if (args.expected !== undefined && workspace.files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
return workspace.workspace_write(args);
},
};
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
async function quickOpen(name) {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
await page.getByRole("tab", { selected: true }).click({ button: "right" });
await page.getByRole("menuitem", { name: "Source mode", exact: true }).click();
await page.locator(".monaco-editor textarea").waitFor();
}
async function contents() {
return page.evaluate(async () => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
return monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected)?.getValue();
});
}
async function waitForText(text) {
await page.evaluate(async () => { window.__MONACO__ = (await import("/src/lib/editor/monacoEnv.ts")).monaco; });
await page.waitForFunction(expected => window.__MONACO__.editor.getEditors().some(editor => editor.getDomNode()?.isConnected && editor.getValue() === expected), text);
}
async function focusEditor() {
await page.locator(".monaco-host .view-lines").click({position:{x:120,y:12}});
}
try {
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
const output = await outputDir("editor/markdownMenu");
async function quickOpen(name) {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
await page.getByRole("tab", { selected: true }).click({ button: "right" });
await page.getByRole("menuitem", { name: "Source mode", exact: true }).click();
await page.locator(".monaco-editor textarea").waitFor();
}
async function waitForText(text) {
await page.evaluate(async () => { window.__MONACO__ = (await import("/src/lib/editor/monacoEnv.ts")).monaco; });
await page.waitForFunction(expected => window.__MONACO__.editor.getEditors().some(editor => editor.getDomNode()?.isConnected && editor.getValue() === expected), text);
}
await page.goto(smokeUrl);
await page.getByText("smoke-workspace", { exact: true }).waitFor();
await quickOpen("welcome.md");
const source = "First paragraph.\n\nSecond paragraph.\n";
@@ -151,7 +95,7 @@ try {
await page.keyboard.press("Control+End");
await page.keyboard.press("Shift+F10");
await menu.getByRole("menuitem", { name: "Insert", exact: true }).hover();
await page.screenshot({ path: ".audit/markdown-insert-menu.png" });
await page.screenshot({ path: `${output}/markdown-insert-menu.png` });
await page.keyboard.press("Escape");
await page.setViewportSize({ width: 760, height: 600 });
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
@@ -162,7 +106,7 @@ try {
assert.equal(await page.evaluate(() => document.activeElement.textContent), "Bullet list");
const rect = await menu.getByRole("menu", { name: "Paragraph", exact: true }).boundingBox();
assert.ok(rect.x >= 0 && rect.y >= 0 && rect.x + rect.width <= 760 && rect.y + rect.height <= 600);
await page.screenshot({ path: ".audit/markdown-paragraph-menu.png" });
await page.screenshot({ path: `${output}/markdown-paragraph-menu.png` });
await page.keyboard.press("ArrowLeft");
assert.equal(await page.evaluate(() => document.activeElement.textContent), "Paragraph");
await page.keyboard.press("Escape");
@@ -170,11 +114,19 @@ try {
await page.keyboard.press("Control+Shift+ArrowRight");
await page.keyboard.press("Shift+F10");
await menu.getByRole("menuitem", { name: "Add external link", exact: true }).click();
await page.getByRole("textbox", { name: "External link URL" }).fill("https://example.com/a(b)");
await page.getByRole("button", { name: "Continue", exact: true }).click();
// External links insert `[label]()` with the caret in the URL, without a dialog (src/lib/editor/markdownMenu.ts:57, src/lib/editor/linkCommands.ts:3-8).
assert.equal(await page.getByRole("dialog").count(), 0);
await page.keyboard.type("https://example.com/a");
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md").startsWith("[First](https://example.com/a%28b%29) paragraph."));
await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md").startsWith("[First](https://example.com/a) paragraph."));
// Undo the typed URL, then the link, which restores the selected label.
await page.keyboard.press("Control+z");
await page.keyboard.press("Control+z");
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content"));
});
await page.waitForFunction(() => window.__CM__.state.sliceDoc().startsWith("First paragraph."));
await page.keyboard.press("Shift+F10");
await menu.getByRole("menuitem", { name: "Extract current selection…", exact: true }).click();
await page.getByRole("textbox", { name: "Extract selection to a new note (workspace relative path)" }).fill("notes/extracted.md");
@@ -197,11 +149,5 @@ try {
await page.evaluate(async () => { window.__finishPaste("STALE"); await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))); });
assert.ok(!(await writer.textContent()).includes("STALE"));
assert.ok((await writer.textContent()).includes("kept"));
assert.deepEqual(errors, []);
console.log("PASS: Markdown menus in source/writing modes, selection retention, formatting, paragraph conversion, table insertion, undo, keyboard navigation, narrow viewport, links, extraction, clipboard and stale-selection guards.");
} catch (error) {
console.error("Browser errors:", errors);
console.error("Visible text:", (await page.locator("body").innerText()).slice(0, 5000));
await page.screenshot({ path: ".audit/markdown-menu-failure.png" });
throw error;
} finally { await browser.close(); }
});
+15 -75
View File
@@ -1,78 +1,19 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
// Pasting large Markdown keeps the source exact and renders every bold span.
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 page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
await mkdir(".audit", { recursive: true });
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
import { mockTauri, runSmoke, smokeUrl } from "../_harness/index.mjs";
try {
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
await runSmoke("editor/markdownPaste", async ({ page }) => {
await mockTauri(page, {
commands: test => test.workspace({
root: "C:\\smoke-workspace",
files: {
"notes/welcome.md": "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n",
"notes/second.md": "# Second note\n",
"src/hello.py": "print('hello')\n",
},
}),
});
await page.goto(smokeUrl);
await page.getByText("smoke-workspace", { exact: true }).waitFor();
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill("welcome.md");
@@ -108,5 +49,4 @@ try {
assert.equal(result.nodes, count);
assert.equal(result.marks, count);
}
assert.deepEqual(errors, []);
} finally { await browser.close(); }
});
@@ -0,0 +1,19 @@
// The document mode switcher expands within 500 ms when the pointer hovers it.
import { mockTauri, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("editor/modeSwitcherHover", async ({ page }) => {
await mockTauri(page, {
commands: test => ({
...test.workspace({ root: "C:\\mode-switcher", files: { "a.md": "# Alpha\n\nTemplate body.\n" } }),
plugins_snapshot: () => ({ plugins: [], issues: [] }),
spelling_menu_install: () => null,
}),
});
await page.goto(smokeUrl);
await page.locator('[data-tree-rel="a.md"]').click();
await page.locator(".cm-content").waitFor();
await page.locator(".mode-switcher").first().hover();
await page.waitForFunction(() => document.querySelector(".mode-switcher")?.classList.contains("expanded"), null, { timeout: 500 });
await page.mouse.move(500, 400);
console.log("PASS: the mode switcher expands on hover");
}, { timeout: 15000 });
+43 -90
View File
@@ -1,94 +1,48 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
// Repeated copy and paste of formatted Markdown stays exact across saves, tab switches, IDE switches, and line endings.
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
import { mockTauri, runSmoke, smokeUrl } from "../_harness/index.mjs";
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();
}
async function writer() {
await page.locator('.cm-content').waitFor();
return page.evaluate(async () => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
window.__WRITER__ = EditorView.findFromDOM(document.querySelector('.cm-content'));
return window.__WRITER__.state.sliceDoc();
await runSmoke("editor/pasteRepeat", async ({ page }) => {
await mockTauri(page, {
commands: test => {
const workspace = test.workspace({
root: "C:\\smoke-workspace",
files: {
"notes/welcome.md": "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n",
"notes/second.md": "# Second note\n",
"src/hello.py": "print('hello')\n",
},
writeEvents: true,
});
test.files = workspace.files;
return {
...workspace,
// Saves send the last saved text. Reject a save when the file changed, as the backend does.
workspace_write: args => {
if (args.expected !== undefined && workspace.files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
return workspace.workspace_write(args);
},
};
},
});
}
async function expectWriter(expected) {
await writer();
try { await page.waitForFunction(text => window.__WRITER__.state.sliceDoc() === text, expected); } catch (error) { console.log({ expectedLength: expected.length, actualLength: (await writer()).length, errors }); throw error; }
}
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:5173');
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();
}
async function writer() {
await page.locator('.cm-content').waitFor();
return page.evaluate(async () => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
window.__WRITER__ = EditorView.findFromDOM(document.querySelector('.cm-content'));
return window.__WRITER__.state.sliceDoc();
});
}
async function expectWriter(expected) {
await writer();
try { await page.waitForFunction(text => window.__WRITER__.state.sliceDoc() === text, expected); } catch (error) { console.log({ expectedLength: expected.length, actualLength: (await writer()).length, errors: page.errors }); throw error; }
}
await page.goto(smokeUrl);
await page.getByText('smoke-workspace', { exact: true }).waitFor();
const formatted = '# Copied heading\n\n## Links\n\n[Reference](https://example.com) and [[second|Another note]]\n\n**Bold**, *italic*, and `code`.\n\n- A list item\n';
await page.evaluate(text => { window.__TEST__.files.set('notes/source.md', text); window.__TEST__.files.set('notes/pasted.md', ''); }, formatted);
@@ -140,6 +94,5 @@ try {
});
assert.equal(synchronized, true, 'Writer, model, and saved source agree');
}
assert.deepEqual(errors, []);
console.log('PASS: formatted Markdown copied across notes stays exact through 12 paste/delete cycles, saves, tab reopen, IDE reopen, and LF/CRLF/CR clipboard replacement');
} finally { await browser.close(); }
});
+17 -80
View File
@@ -1,80 +1,20 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
// Front matter properties: first open, editing, undo, the saved selection, and both themes.
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 page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
await mkdir(".audit", { recursive: true });
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "spelling_menu_install") return;
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
try {
await mkdir("output/editor-october12", { recursive: true });
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
await runSmoke("editor/properties", async ({ page }) => {
await mockTauri(page, {
commands: test => test.workspace({
root: "C:\\smoke-workspace",
files: {
"notes/welcome.md": "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n",
"notes/second.md": "# Second note\n",
"src/hello.py": "print('hello')\n",
},
}),
});
const output = await outputDir("editor/properties");
await page.goto(smokeUrl);
await page.getByText("smoke-workspace", { exact: true }).waitFor();
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill("welcome.md");
@@ -96,7 +36,7 @@ try {
applyAppearance({ theme: 'default', mode });
}, mode);
await page.setViewportSize({ width: 760, height: 900 });
await page.screenshot({ path: `output/editor-october12/properties-${mode}-narrow.png` });
await page.screenshot({ path: `${output}/properties-${mode}-narrow.png` });
}
await page.evaluate(() => { window.__CM__.dispatch({ selection: { anchor: 11 } }); window.__CM__.focus(); });
assert.equal(await page.locator('.md-properties').count(), 0);
@@ -114,8 +54,5 @@ try {
await page.getByRole('button', { name: 'Edit', exact: true }).click();
await page.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
assert.equal(await page.locator('.writer-preview .md-properties').count(), 0);
assert.equal(errors.length, 0, errors.join('\n'));
console.log('Properties first-open, editing, undo, saved selection, and both themes passed.');
} finally {
await browser.close();
}
});
@@ -0,0 +1,48 @@
// Text selection uses --rs-selection in Writer (native and CodeMirror layers) and in Read view, in both themes.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
const name = "editor/selectionColor";
await runSmoke(name, async ({ browser }) => {
const output = await outputDir(name);
for (const theme of ["light", "dark"]) {
const page = await openPage(browser, { viewport: { width: 1100, height: 780 } });
await mockTauri(page, {
commands: test => ({
...test.workspace({ root: "C:\\selection-color", files: { "sample.md": "# Selection sample\n\nThe same text color applies to each editor.\n" } }),
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
}),
});
await page.goto(smokeUrl);
await page.getByText("selection-color", { exact: true }).waitFor();
await page.evaluate(async theme => (await import("/src/lib/theme/appearance.ts")).saveAppearance({ theme: "default", mode: theme }), theme);
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill("sample.md");
await page.getByRole("textbox", { name: "Find a file" }).press("Enter");
const writer = page.getByRole("textbox", { name: "Writing editor", exact: true });
await writer.waitFor();
await writer.click();
await page.keyboard.press("Control+a");
const colors = await writer.evaluate(node => {
const probe = document.createElement("span");
probe.style.backgroundColor = "var(--rs-selection)";
node.append(probe);
const expected = getComputedStyle(probe).backgroundColor;
probe.remove();
return { expected, native: getComputedStyle(node, "::selection").backgroundColor,
layer: getComputedStyle(document.querySelector(".cm-selectionBackground")).backgroundColor };
});
assert.equal(colors.native, colors.expected);
assert.equal(colors.layer, colors.expected);
await page.screenshot({ path: path.join(output, `${theme}-writer-selection.png`) });
await page.getByRole("group", { name: "Document view", exact: true }).hover();
await page.getByRole("button", { name: "Read", exact: true }).click();
const reader = page.locator(".reading");
await reader.waitFor();
assert.equal(await reader.evaluate(node => getComputedStyle(node, "::selection").backgroundColor), colors.expected);
assert.deepEqual(page.errors, []);
await page.close();
console.log(`PASS: ${theme} Writer and Read view selection`);
}
});
+29 -59
View File
@@ -1,62 +1,33 @@
import { createRequire } from "node:module";
// Editor menu surfaces: Writer, spelling, IDE, and code menus share the file menu styles; code tint and the command palette match in both themes.
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 page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(15000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await mkdir(".audit", { recursive: true });
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\tab-menu-workspace";
const files = new Map(["a.md", "b.md", "c.md", "d.md"].map(name => [name, `# ${name}\n\nOriginal text.\n\n\`\`\`js\nconst answer = 42;\n\`\`\`\n\n| Name | Value |\n| --- | --- |\n| Alpha | One |\n`]));
files.set("sample.txt", "const answer = 42;\n");
window.tabMenuTest = { prompts: [], answer: "Cancel", revealed: null, clipboard: null };
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { window.tabMenuTest.clipboard = text; } } });
let sequence = 0;
const callbacks = new Map(), listeners = new Map();
window.spellingTest = { commands: [], emit: payload => callbacks.get(listeners.get("spelling-menu"))?.({ event: "spelling-menu", id: 1, payload }) };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { callbacks.set(++sequence, callback); return sequence; }, unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === "plugin:event|listen") { listeners.set(args.event, args.handler); return ++sequence; }
if (command === "plugin:event|unlisten") return;
if (command.startsWith("spelling_menu_")) { window.spellingTest.commands.push({ method: command, ...args }); return; }
if (command === "spelling_suggestions") return { language: "en-US", words: ["Corrected"], misspelled: args.word === "Original" };
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "tab-menu-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_list") return args.rel ? [] : [{ name: "notes", rel_path: "notes", kind: "folder" }, ...[...files.keys()].map(name => ({ name, rel_path: name, kind: "file" }))];
if (command === "workspace_search") return [];
if (command === "workspace_write") throw new Error("Keep unsaved edits for the close test");
if (command === "workspace_rename") { files.set(args.to, files.get(args.from)); files.delete(args.from); return; }
if (command === "workspace_abs_path") return `${root}\\${args.rel}`;
if (command === "workspace_reveal") { window.tabMenuTest.revealed = args.rel; return; }
if (command === "plugin:dialog|message") { window.tabMenuTest.prompts.push(args.message); return window.tabMenuTest.answer; }
throw new Error(`Unhandled IPC: ${command}`);
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("editor/surfaces", async ({ page }) => {
await mockTauri(page, {
commands: test => {
const note = name => `# ${name}\n\nOriginal text.\n\n\`\`\`js\nconst answer = 42;\n\`\`\`\n\n| Name | Value |\n| --- | --- |\n| Alpha | One |\n`;
return {
...test.workspace({
root: "C:\\tab-menu-workspace",
files: { ...Object.fromEntries(["a.md", "b.md", "c.md", "d.md"].map(name => [name, note(name)])), "sample.txt": "const answer = 42;\n" },
folders: ["notes"],
}),
spelling_menu_install: () => null,
spelling_suggestions: ({ word }) => ({ language: "en-US", words: ["Corrected"], misspelled: word === "Original" }),
};
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const menu = name => page.getByRole('menu', { name, exact: true });
const item = name => page.getByRole('menuitem', { name, exact: true });
const output = '.audit/editor-surfaces';
await mkdir(output, { recursive: true });
const report = [];
const dismiss = async () => { await page.keyboard.press('Escape'); await page.locator('.rs-menu').waitFor({ state: 'detached' }); };
const styles = panel => panel.evaluate(node => {
const row = node.querySelector(':scope > button');
const a = getComputedStyle(node), b = getComputedStyle(row);
return [a.backgroundColor, a.borderRadius, a.padding, b.minHeight, b.padding, b.font];
});
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
});
const menu = name => page.getByRole('menu', { name, exact: true });
const item = name => page.getByRole('menuitem', { name, exact: true });
const output = await outputDir("editor/surfaces");
const report = [];
const dismiss = async () => { await page.keyboard.press('Escape'); await page.locator('.rs-menu').waitFor({ state: 'detached' }); };
const styles = panel => panel.evaluate(node => {
const row = node.querySelector(':scope > button');
const a = getComputedStyle(node), b = getComputedStyle(row);
return [a.backgroundColor, a.borderRadius, a.padding, b.minHeight, b.padding, b.font];
});
await page.goto(smokeUrl);
await page.locator('[data-tree-rel="a.md"]').click();
await page.locator('.cm-content').waitFor();
for (const theme of ['dark', 'light']) {
@@ -176,6 +147,5 @@ try {
await page.getByRole('button', { name: 'Writer', exact: true }).click();
report.push({ theme, passed: ['word and blank menu parity', 'spelling correction and undo', 'Writer/IDE parity', 'undo menu action', 'code menu host styles', 'transparent code in Writer/Reader', 'palette selection/focus', 'narrow keyboard menu/palette'], nativeDesktop: 'not tested' });
}
assert.deepEqual(errors, []);
console.log(JSON.stringify(report, null, 2));
} catch (error) { await page.screenshot({path: `${output}/failure.png`}); console.log(await page.locator(".rs-menu").allTextContents()); throw error; } finally { await browser.close(); }
}, { timeout: 15000 });
+33 -83
View File
@@ -1,80 +1,34 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
// Note templates and task lines: template creation, filename focus, task entry, checkbox toggles, lone hyphens, and Setext headings.
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 page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
await mkdir(".audit", { recursive: true });
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || (!prefix && path.startsWith(".runestone/"))) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "spelling_menu_install") return;
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
try {
await mkdir('output/editor-template-hyphen', { recursive: true });
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await runSmoke("editor/templatesAndTasks", async ({ page }) => {
await mockTauri(page, {
commands: test => {
const workspace = test.workspace({
root: "C:\\smoke-workspace",
files: {
"notes/welcome.md": "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n",
"notes/second.md": "# Second note\n",
"src/hello.py": "print('hello')\n",
},
writeEvents: true,
});
test.files = workspace.files;
return {
...workspace,
// Saves send the last saved text. Reject a save when the file changed, as the backend does.
workspace_write: args => {
if (args.expected !== undefined && workspace.files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
return workspace.workspace_write(args);
},
// The tree hides the root .runestone folder; its templates folder stays listable.
workspace_list: args => workspace.workspace_list(args).filter(entry => args.rel || entry.rel_path !== ".runestone"),
};
},
});
const output = await outputDir("editor/templatesAndTasks");
await page.goto(smokeUrl);
await page.getByText('smoke-workspace', { exact: true }).waitFor();
// Save the empty task lines from the reported template, then create through
// the normal note action so the filename receives the initial focus.
@@ -113,7 +67,7 @@ try {
if (!(await title.isVisible())) await page.getByRole('button', { name: 'Rename note', exact: true }).click();
await title.focus();
await expectCount(10);
await page.screenshot({ path: `output/editor-template-hyphen/${mode}-${width}-template-title.png` });
await page.screenshot({ path: `${output}/${mode}-${width}-template-title.png` });
await page.keyboard.press('Escape');
await page.evaluate(() => {
const view = window.__CM__;
@@ -125,11 +79,11 @@ try {
await expectCount(10);
await page.locator('.writer-checkbox').first().click();
assert.match(await page.evaluate(() => window.__CM__.state.sliceDoc()), /^- \[x\] First task/);
await page.screenshot({ path: `output/editor-template-hyphen/${mode}-${width}-template-edit.png` });
await page.screenshot({ path: `${output}/${mode}-${width}-template-edit.png` });
await setSource(plain);
assert.equal(await page.locator('.writer-h2').count(), 0, 'A lone hyphen must not enlarge preceding prose');
await page.screenshot({ path: `output/editor-template-hyphen/${mode}-${width}-single-hyphen.png` });
await page.screenshot({ path: `${output}/${mode}-${width}-single-hyphen.png` });
await page.keyboard.type(' Item');
assert.equal(await page.locator('.writer-h2').count(), 0, 'The hyphen continues into a list');
assert.equal(await page.evaluate(() => window.__CM__.state.sliceDoc()), plain + ' Item');
@@ -147,9 +101,5 @@ try {
}
}
}
assert.deepEqual(errors, []);
console.log('PASS: template creation, filename focus, keyboard task entry, checkbox toggle, lone hyphen, list continuation, and Setext headings in both themes and narrow layouts.');
} catch (error) {
await page.screenshot({ path: 'output/editor-template-hyphen/failure.png' });
throw error;
} finally { await browser.close(); }
});
+43 -90
View File
@@ -1,94 +1,48 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
// Undo history survives tab switches, window focus, IDE edits, and table cell edits.
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
import { mockTauri, runSmoke, smokeUrl } from "../_harness/index.mjs";
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();
}
async function writer() {
await page.locator('.cm-content').waitFor();
return page.evaluate(async () => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
window.__WRITER__ = EditorView.findFromDOM(document.querySelector('.cm-content'));
return window.__WRITER__.state.sliceDoc();
await runSmoke("editor/undoHistory", async ({ page }) => {
await mockTauri(page, {
commands: test => {
const workspace = test.workspace({
root: "C:\\smoke-workspace",
files: {
"notes/welcome.md": "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n",
"notes/second.md": "# Second note\n",
"src/hello.py": "print('hello')\n",
},
writeEvents: true,
});
test.files = workspace.files;
return {
...workspace,
// Saves send the last saved text. Reject a save when the file changed, as the backend does.
workspace_write: args => {
if (args.expected !== undefined && workspace.files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
return workspace.workspace_write(args);
},
};
},
});
}
async function expectWriter(expected) {
await writer();
try { await page.waitForFunction(text => window.__WRITER__.state.sliceDoc() === text, expected); } catch (error) { console.log({ expected, actual: await writer(), errors }); throw error; }
}
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
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();
}
async function writer() {
await page.locator('.cm-content').waitFor();
return page.evaluate(async () => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
window.__WRITER__ = EditorView.findFromDOM(document.querySelector('.cm-content'));
return window.__WRITER__.state.sliceDoc();
});
}
async function expectWriter(expected) {
await writer();
try { await page.waitForFunction(text => window.__WRITER__.state.sliceDoc() === text, expected); } catch (error) { console.log({ expected, actual: await writer(), errors: page.errors }); throw error; }
}
await page.goto(smokeUrl);
await page.getByText('smoke-workspace', { exact: true }).waitFor();
await open('welcome.md');
const original = await writer();
@@ -171,5 +125,4 @@ try {
await page.keyboard.press('Control+y');
await expectWriter(editedTable);
console.log('PASS: table cell typing stays grouped per cell across tab switches');
assert.deepEqual(errors, []);
} finally { await browser.close(); }
});
+50 -101
View File
@@ -1,101 +1,55 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
// One full-width document Find in Writer, table cells, IDE source, and Reading: replacement, regex, CRLF, focus return, both themes, and narrow controls.
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 page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
const output = ".audit/todo-2026-10-14/unified-find";
await mkdir(output, { recursive: true });
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
const sample = "# Alpha\n\nAlpha alpha alphabet\n\n| Name | Value |\n| --- | --- |\n| Alpha | One |\n| Beta | Two |\n\nLast Alpha paragraph.\n";
const find = page.getByRole("textbox", { name: "Find in document", exact: true });
const replace = page.getByRole("textbox", { name: "Replace with", exact: true });
async function mode(group, value) {
await page.getByRole("group", { name: group, exact: true }).hover();
await page.getByRole("button", { name: value, exact: true }).click();
}
async function onePanel() {
assert.equal(await page.locator('.rs-find-bar:visible').count(), 1);
assert.equal(await page.locator('.find-widget.visible').count(), 0, 'No Monaco floating find widget');
const bar = await page.locator('.rs-find-bar:visible').boundingBox();
const pane = await page.locator('.editor.pane-active').boundingBox();
assert.ok(Math.abs(bar.width - pane.width) < 3, 'Find spans the document pane');
}
async function sourceEditor() {
await page.waitForFunction(() => !!document.querySelector('.monaco-editor'));
return page.evaluate(async () => {
const { monaco } = await import('/src/lib/editor/monacoEnv.ts');
window.__MONACO__ = monaco.editor.getEditors().find(view => view.getDomNode()?.isConnected && view.getDomNode().getBoundingClientRect().width > 0);
window.__MONACO__.focus();
await runSmoke("find/documentFind", async ({ page }) => {
const output = await outputDir("find/documentFind");
await mockTauri(page, {
commands: test => {
const workspace = test.workspace({
root: "C:\\smoke-workspace",
writeEvents: true,
files: {
"notes/welcome.md": "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n",
"notes/second.md": "# Second note\n",
"src/hello.py": "print('hello')\n",
},
});
return {
...workspace,
workspace_write: args => {
if (args.expected !== undefined && workspace.files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
return workspace.workspace_write(args);
},
workspace_search: () => [],
"plugin:dialog|message": () => "Cancel",
};
},
});
}
try {
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
const sample = "# Alpha\n\nAlpha alpha alphabet\n\n| Name | Value |\n| --- | --- |\n| Alpha | One |\n| Beta | Two |\n\nLast Alpha paragraph.\n";
const find = page.getByRole("textbox", { name: "Find in document", exact: true });
const replace = page.getByRole("textbox", { name: "Replace with", exact: true });
async function mode(group, value) {
await page.getByRole("group", { name: group, exact: true }).hover();
await page.getByRole("button", { name: value, exact: true }).click();
}
async function onePanel() {
assert.equal(await page.locator('.rs-find-bar:visible').count(), 1);
assert.equal(await page.locator('.find-widget.visible').count(), 0, 'No Monaco floating find widget');
const bar = await page.locator('.rs-find-bar:visible').boundingBox();
const pane = await page.locator('.editor.pane-active').boundingBox();
assert.ok(Math.abs(bar.width - pane.width) < 3, 'Find spans the document pane');
}
async function sourceEditor() {
await page.waitForFunction(() => !!document.querySelector('.monaco-editor'));
return page.evaluate(async () => {
const { monaco } = await import('/src/lib/editor/monacoEnv.ts');
window.__MONACO__ = monaco.editor.getEditors().find(view => view.getDomNode()?.isConnected && view.getDomNode().getBoundingClientRect().width > 0);
window.__MONACO__.focus();
});
}
await page.goto(smokeUrl);
await page.getByText("smoke-workspace", { exact: true }).waitFor();
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill("welcome.md");
@@ -191,10 +145,5 @@ try {
await mode('Document view', 'Edit');
await mode('Editor layout', 'Writer');
}
assert.deepEqual(errors, []);
console.log('PASS: one full-width document Find in Writer, nested table focus, IDE/source, and Reading, with replacement, regex, CRLF, focus return, both themes, and narrow controls.');
} catch (error) {
console.error('Browser errors:', errors);
await page.screenshot({ path: `${output}/failure.png` });
throw error;
} finally { await browser.close(); }
});
+53 -65
View File
@@ -1,70 +1,62 @@
// Find in plug-in views: privacy attributes, Project Management views, plug-in documents, custom find handlers, focus, both themes, and narrow layouts.
// @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';
import { mkdir, readFile } from 'node:fs/promises';
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
page.on('pageerror', error => errors.push(error.message));
const output = '.audit/host-privacy-find';
await mkdir(output, { recursive: true });
const pm = {
manifest: JSON.parse(await readFile(new URL('../../../../RuneStone_Project_Management/dist/plugin/plugin.json', import.meta.url), 'utf8')),
code: await readFile(new URL('../../../../RuneStone_Project_Management/dist/plugin/main.js', import.meta.url), 'utf8'),
};
await page.addInitScript(({ pm }) => {
window.isTauri = true;
const files = new Map([['untitled.md', '# Existing note\n'], ['sample.finddoc', 'Alpha alpha alphabet']]);
files.set('Board.md', '---\nrunestone_pm:\n schema: 1\n kind: board\n id: host-find-board\n lists:\n - {id: todo, name: To do, status: todo, collapsed: false}\n - {id: doing, name: In progress, status: doing, collapsed: false}\n - {id: done, name: Done, status: done, collapsed: false}\n defaults: {todo: todo, doing: doing, done: done}\n---\n');
const callbacks = new Map(), listeners = new Map();
let sequence = 0;
const manifest = { schemaVersion: 1, id: 'test.find', name: 'Find test', author: 'Test', description: 'Search checks', version: '1.0.0', apiVersion: 1, entry: 'main.js', access: 'full-app' };
const code = `export function activate(api) {
api.registerDocumentType({ id: 'document', title: 'Test document', extensions: ['finddoc'], identify: path => ({ id: path }), mount(root) {
root.innerHTML = '<section><h2>Test document</h2><p>Alpha alpha alphabet</p><button>Alpha card</button><p hidden>Hidden Alpha</p><button class="focus-return">Details</button></section>';
}});
for (const name of ['Board', 'Changes']) api.registerView({ id: name.toLowerCase(), title: name, placement: 'editor', navigation: true, icon: 'list', mount(root) {
root.innerHTML = '<section><h2>' + name + '</h2><p>Alpha alpha alphabet</p><button>Alpha card</button><p hidden>Hidden Alpha</p><button class="focus-return">Details</button></section>';
}});
api.registerView({ id: 'native', title: 'Custom find', placement: 'editor', navigation: true, find() { window.customFindCalls = (window.customFindCalls || 0) + 1; }, mount(root) { root.innerHTML = '<p>Native content</p>'; } });
}`;
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 === 'plugin:event|listen') { const ids = listeners.get(args.event) || []; ids.push(args.handler); listeners.set(args.event, ids); return args.handler; }
if (command === 'plugin:event|unlisten') return;
if (command === 'workspace_last_path') return 'C:/find-test';
if (command === 'workspace_open') return { root: 'C:/find-test', name: 'find-test', watch_mode: 'native' };
if (command === 'workspace_list') return args.rel ? [] : [...files.keys()].map(name => ({ name, rel_path: name, kind: 'file' }));
if (command === 'workspace_read') { if (!files.has(args.rel) && args.missingOk) return null; if (!files.has(args.rel)) throw Error('Missing file'); return files.get(args.rel); }
if (command === 'workspace_list_markdown') return [...files.keys()].filter(path => !path.startsWith('.') && path.endsWith('.md'));
if (command === 'workspace_read_many') return args.paths.map(path => ({ path, source: files.get(path) }));
if (command === 'workspace_create') { if (files.has(args.rel)) throw Error('File exists'); files.set(args.rel, ''); return; }
if (command === 'workspace_write') { files.set(args.rel, args.contents); return; }
if (command === 'plugins_snapshot') return { root: 'C:/test/plugins', plugins: [manifest, pm.manifest].map(item => ({ manifest: item, hash: item.id, enabled: true, path: 'C:/test/plugins/' + item.id, error: null, removal: false })) };
if (command === 'plugins_load') return args.id === pm.manifest.id ? pm.code : code;
if (command === 'plugins_data') return 'null';
if (command === 'browser_connect') return 'test';
return null;
},
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { mockTauri, outputDir, pluginRepo, runSmoke, smokeUrl } from '../_harness/index.mjs';
await runSmoke('find/pluginViews', async ({ page }) => {
const output = await outputDir('find/pluginViews');
const pmDist = pluginRepo('RuneStone_Project_Management/dist/plugin');
const pm = {
manifest: JSON.parse(await readFile(path.join(pmDist, 'plugin.json'), 'utf8')),
code: await readFile(path.join(pmDist, 'main.js'), 'utf8'),
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener() {} };
window.__FILES__ = files;
}, { pm });
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
// Unknown commands return null, as the original mock did.
await mockTauri(page, {
strict: false,
state: { pm },
commands: test => {
const workspace = test.workspace({
root: 'C:/find-test',
files: {
'untitled.md': '# Existing note\n',
'sample.finddoc': 'Alpha alpha alphabet',
'Board.md': '---\nrunestone_pm:\n schema: 1\n kind: board\n id: host-find-board\n lists:\n - {id: todo, name: To do, status: todo, collapsed: false}\n - {id: doing, name: In progress, status: doing, collapsed: false}\n - {id: done, name: Done, status: done, collapsed: false}\n defaults: {todo: todo, doing: doing, done: done}\n---\n',
},
});
test.files = workspace.files;
const { pm } = test.state;
const manifest = { schemaVersion: 1, id: 'test.find', name: 'Find test', author: 'Test', description: 'Search checks', version: '1.0.0', apiVersion: 1, entry: 'main.js', access: 'full-app' };
const code = `export function activate(api) {
api.registerDocumentType({ id: 'document', title: 'Test document', extensions: ['finddoc'], identify: path => ({ id: path }), mount(root) {
root.innerHTML = '<section><h2>Test document</h2><p>Alpha alpha alphabet</p><button>Alpha card</button><p hidden>Hidden Alpha</p><button class="focus-return">Details</button></section>';
}});
for (const name of ['Board', 'Changes']) api.registerView({ id: name.toLowerCase(), title: name, placement: 'editor', navigation: true, icon: 'list', mount(root) {
root.innerHTML = '<section><h2>' + name + '</h2><p>Alpha alpha alphabet</p><button>Alpha card</button><p hidden>Hidden Alpha</p><button class="focus-return">Details</button></section>';
}});
api.registerView({ id: 'native', title: 'Custom find', placement: 'editor', navigation: true, find() { window.customFindCalls = (window.customFindCalls || 0) + 1; }, mount(root) { root.innerHTML = '<p>Native content</p>'; } });
}`;
return {
...workspace,
workspace_read: args => {
if (!workspace.files.has(args.rel) && args.missingOk) return null;
return workspace.workspace_read(args);
},
plugins_snapshot: () => ({ root: 'C:/test/plugins', plugins: [manifest, pm.manifest].map(item => ({ manifest: item, hash: item.id, enabled: true, path: 'C:/test/plugins/' + item.id, error: null, removal: false })) }),
plugins_load: args => args.id === pm.manifest.id ? pm.code : code,
plugins_data: () => 'null',
browser_connect: () => 'test',
};
},
});
await page.goto(smokeUrl);
await page.locator('.ws').getByText('find-test', { exact: true }).waitFor();
await page.getByRole('button', { name: 'Plug-in views', exact: true }).waitFor();
const note = page.locator('.tree-tools').getByRole('button', { name: 'New note', exact: true });
assert.equal(await page.locator('.tree-tools').getByRole('button', { name: 'New file', exact: true }).count(), 0);
await note.click();
await page.waitForFunction(() => window.__FILES__.has('untitled 2.md'));
await page.waitForFunction(() => window.__TEST__.files.has('untitled 2.md'));
await page.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
await page.getByRole('textbox', { name: 'Writing editor', exact: true }).click();
await page.keyboard.press('Control+f');
@@ -75,7 +67,7 @@ try {
await page.screenshot({ path: `${output}/new-note-dark.png` });
assert.equal(await page.getByRole('dialog').count(), 0, 'The note opens without a filename dialog');
await note.click();
await page.waitForFunction(() => window.__FILES__.has('untitled 3.md'));
await page.waitForFunction(() => window.__TEST__.files.has('untitled 3.md'));
for (const theme of ['dark', 'light']) {
await page.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); }, theme);
await page.getByRole('tab', { name: 'untitled 3.md', exact: true }).click();
@@ -169,9 +161,5 @@ try {
await page.keyboard.press('Control+f');
assert.equal(await page.evaluate(() => window.customFindCalls), 1, 'Plugin find handlers retain ownership');
assert.equal(await page.locator('.rs-find-bar:visible').count(), 0);
assert.deepEqual(errors, []);
console.log('PASS: Find privacy attributes, actual PM All Tasks and board scope, plugin document Find, custom handlers, focus, both themes, and narrow layouts');
} catch (error) {
await page.screenshot({ path: `${output}/failure.png` });
throw error;
} finally { await browser.close(); }
});
+31 -81
View File
@@ -1,78 +1,33 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
// Writer find bar in the top editor panel: shortcuts, replacement, query sync, invalid regex, tooltip, outline filtering, focus return, and narrow layout.
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 page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
await mkdir(".audit", { recursive: true });
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
try {
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
await runSmoke("find/searchPanel", async ({ page }) => {
const output = await outputDir("find/searchPanel");
await mockTauri(page, {
commands: test => {
const workspace = test.workspace({
root: "C:\\smoke-workspace",
writeEvents: true,
files: {
"notes/welcome.md": "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n",
"notes/second.md": "# Second note\n",
"src/hello.py": "print('hello')\n",
},
});
return {
...workspace,
workspace_write: args => {
if (args.expected !== undefined && workspace.files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
return workspace.workspace_write(args);
},
workspace_search: () => [],
"plugin:dialog|message": () => "Cancel",
};
},
});
await page.goto(smokeUrl);
await page.getByText("smoke-workspace", { exact: true }).waitFor();
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill("welcome.md");
@@ -141,7 +96,7 @@ try {
await outlineFind.fill("missing");
await outline.getByText("No matching headings or symbols.").waitFor();
await outlineFind.fill("Gamma");
await page.screenshot({ path: ".audit/find-bars.png" });
await page.screenshot({ path: path.join(output, "find-bars.png") });
await page.keyboard.press("Escape");
assert.equal(await outlineFind.count(), 0);
assert.equal(await outline.locator("li").count(), 2);
@@ -154,14 +109,9 @@ try {
await page.setViewportSize({ width: 880, height: 760 });
await find.focus();
await page.screenshot({ path: ".audit/find-bars-narrow.png" });
await page.screenshot({ path: path.join(output, "find-bars-narrow.png") });
for (const selector of [".rs-writer-search", ".outline-search"]) {
assert.equal(await page.locator(selector).evaluate(el => el.scrollWidth <= el.clientWidth), true, selector);
}
assert.deepEqual(errors, []);
console.log("PASS: Top search panel, shortcuts, replacement, query sync, invalid regex, focus tooltip, outline filtering, focus return and narrow layout.");
} catch (error) {
console.error("Browser errors:", errors);
await page.screenshot({ path: ".audit/find-failure.png" });
throw error;
} finally { await browser.close(); }
});
+36 -52
View File
@@ -1,55 +1,38 @@
// Run against pnpm dev with PLAYWRIGHT_MODULE and CHROME_PATH if needed.
import { createRequire } from "node:module";
// Sidebar layout persistence: the hidden outline, resized sidebars, and the navigation view survive layout changes, reloads, and reopened windows.
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 context = await browser.newContext({ viewport: { width: 1280, height: 800 } });
await context.addInitScript(() => {
window.isTauri = true;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: () => 1, unregisterCallback: () => {},
invoke: async (command, args = {}) => {
if (command === "plugins_snapshot") return { root: "D:\\LayoutTest\\plugins", plugins: [] };
if (command === "workspace_last_path") return "D:\\LayoutTest";
if (command === "workspace_open") return { root: "D:\\LayoutTest", name: "LayoutTest", watch_mode: "native" };
if (command === "workspace_list") return args.rel ? [] : [{ name: "note.md", rel_path: "note.md", kind: "file" }];
if (command === "workspace_read") {
if (args.rel === "note.md") return "# Layout test\n\nA note.\n";
throw new Error("Missing file");
}
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const errors = [];
context.on("page", page => page.on("pageerror", error => errors.push(error.message)));
const url = process.env.SMOKE_URL || "http://127.0.0.1:1420";
let page = await context.newPage();
page.setDefaultTimeout(5000);
async function ready() { await page.getByRole("button", { name: /^(Hide|Show) outline$/ }).waitFor(); }
async function reopen() {
await page.close();
page = await context.newPage();
page.setDefaultTimeout(5000);
await page.goto(url);
await ready();
}
async function resize(index, x) {
const box = await page.locator(".gutter-v").nth(index).boundingBox();
await page.mouse.move(box.x + box.width / 2, box.y + 60);
await page.mouse.down();
await page.mouse.move(x, box.y + 60);
await page.mouse.up();
}
async function widths() {
return page.locator(".shell").evaluate(element => [element.style.getPropertyValue("--left"), element.style.getPropertyValue("--right")]);
}
try {
await page.goto(url);
await ready();
import { mockTauri, openPage, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("layout/outline", async ({ browser }) => {
// Pages share one context, so a reopened window keeps the saved layout.
const context = await browser.newContext({ viewport: { width: 1280, height: 800 } });
// Unknown commands return null, as the original mock did.
await mockTauri(context, {
strict: false,
commands: test => ({
...test.workspace({ root: "D:\\LayoutTest", files: { "note.md": "# Layout test\n\nA note.\n" } }),
plugins_snapshot: () => ({ root: "D:\\LayoutTest\\plugins", plugins: [] }),
}),
});
const errors = [];
let page;
async function ready() { await page.getByRole("button", { name: /^(Hide|Show) outline$/ }).waitFor(); }
async function reopen() {
if (page) { errors.push(...page.errors); await page.close(); }
page = await openPage(context, { timeout: 5000 });
await page.goto(smokeUrl);
await ready();
}
async function resize(index, x) {
const box = await page.locator(".gutter-v").nth(index).boundingBox();
await page.mouse.move(box.x + box.width / 2, box.y + 60);
await page.mouse.down();
await page.mouse.move(x, box.y + 60);
await page.mouse.up();
}
async function widths() {
return page.locator(".shell").evaluate(element => [element.style.getPropertyValue("--left"), element.style.getPropertyValue("--right")]);
}
await reopen();
await page.getByText("LayoutTest", { exact: true }).waitFor();
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill("note.md");
@@ -91,5 +74,6 @@ try {
await page.getByRole("button", { name: "Show outline", exact: true }).click();
assert.deepEqual(await widths(), resized);
console.log("PASS: collapsed sidebars retain their sizes and navigation view");
errors.push(...page.errors);
assert.deepEqual(errors, []);
} finally { await browser.close(); }
});
+68 -84
View File
@@ -1,93 +1,78 @@
import { createRequire } from "node:module";
// Document splits: independent modes, edits, saves, selections, and conflicts per pane; nested relative links; narrow stacking; and the close guard.
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 page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(15000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
page.on("console", message => { if (message.text().includes("binding_property_non_reactive")) errors.push(message.text()); });
await mkdir(".audit", { recursive: true });
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\tab-menu-workspace";
const files = new Map(["a.md", "b.md", "c.md", "d.md"].map(name => [name, `# ${name}\n\nOriginal text.\n\n\`\`\`js\nconst answer = 42;\n\`\`\`\n\n| Name | Value |\n| --- | --- |\n| Alpha | One |\n`]));
files.set("a.md", "# Links\n\nSelected reading text.\n\n[Web label](https://example.com/path)\n\n[[b.md|Workspace note]]\n");
files.set("a.md", "# Alpha\n\nOrigin paragraph.\n\n[[notes/b.md|Right note]]\n");
files.set("notes/b.md", "# Bravo\n\nSecond paragraph.\n\n[Relative](c.md)\n\n[[/a.md|Original note]]\n");
files.set("notes/c.md", "# Charlie\n\nThird paragraph.\n");
files.set("sample.txt", "const answer = 42;\n");
window.tabMenuTest = { prompts: [], answer: "Cancel", revealed: null, clipboard: null, opened: null, app: null, windows: [] };
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { window.tabMenuTest.clipboard = text; } } });
window.tabMenuTest.files = files;
let sequence = 0;
const callbacks = new Map(), listeners = new Map();
window.tabMenuTest.change = (path, text) => { files.set(path, text); callbacks.get(listeners.get("workspace-event"))?.({ event: "workspace-event", id: 1, payload: { root, kind: "modify", paths: [path] } }); };
window.tabMenuTest.writes = [];
window.spellingTest = { commands: [], emit: payload => callbacks.get(listeners.get("spelling-menu"))?.({ event: "spelling-menu", id: 1, payload }) };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { callbacks.set(++sequence, callback); return sequence; }, unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === "plugin:event|listen") { listeners.set(args.event, args.handler); return ++sequence; }
if (command === "plugin:event|unlisten") return;
if (command.startsWith("spelling_menu_")) { window.spellingTest.commands.push({ method: command, ...args }); return; }
if (command === "spelling_suggestions") return { language: "en-US", words: ["Corrected"], misspelled: args.word === "Original" };
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "tab-menu-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_list") return [...(!args.rel ? [{ name: "notes", rel_path: "notes", kind: "folder" }] : []), ...[...files.keys()].filter(path => path.split("/").slice(0, -1).join("/") === (args.rel || "")).map(path => ({ name: path.split("/").at(-1), rel_path: path, kind: "file" }))];
if (command === "workspace_search") { window.tabMenuTest.searched = args.query; return []; }
if (command === "plugin:opener|open_url") { window.tabMenuTest.opened = args.url; return; }
if (command === "workspace_open_default") { window.tabMenuTest.app = args.rel; return; }
if (command === "workspace_open_window") { window.tabMenuTest.windows.push(args); return; }
if (command === "workspace_write") { if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("conflict"); files.set(args.rel, args.contents); window.tabMenuTest.writes.push(args.rel); return; }
if (command === "workspace_rename") { files.set(args.to, files.get(args.from)); files.delete(args.from); return; }
if (command === "workspace_abs_path") return `${root}\\${args.rel}`;
if (command === "workspace_reveal") { window.tabMenuTest.revealed = args.rel; return; }
if (command === "plugin:dialog|message") { window.tabMenuTest.prompts.push(args.message); return window.tabMenuTest.answer; }
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
const output = '.audit/document-splits';
await mkdir(output, {recursive:true});
const pane = path => page.locator(`[data-document-path="${path}"]`);
const item = name => page.getByRole('menuitem',{name,exact:true});
async function openRight(path,label) {
const current = pane(path);
await current.locator('.cm-content').getByText(path === 'a.md' ? 'Origin paragraph.' : 'Second paragraph.',{exact:true}).click();
await current.locator('.cm-content').getByText(label,{exact:true}).click({button:'right'});
await item('Open to the right').click();
}
async function append(path, text) {
const target=pane(path).locator('.cm-content');
await target.click(); await page.keyboard.press('Control+End'); await page.keyboard.type(text);
}
async function text(path) { return pane(path).locator('.cm-content').evaluate(async node=> { const {EditorView}=await import('/node_modules/@codemirror/view/dist/index.js'); return EditorView.findFromDOM(node).state.doc.toString(); }); }
async function focus(path) { await pane(path).locator('.cm-content').click(); }
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await runSmoke("layout/splits", async ({ page }) => {
const output = await outputDir("layout/splits");
page.on("console", message => { if (message.text().includes("binding_property_non_reactive")) page.errors.push(message.text()); });
// The checks need edits to stay unsaved; autosave runs every 5 s by default (src/lib/workspace/settings.ts:12, src/lib/layout/Workbench.svelte:1165).
await page.addInitScript(() => localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false })));
await mockTauri(page, {
state: { answer: "Cancel" },
commands: test => {
const workspace = test.workspace({
root: "C:\\tab-menu-workspace",
files: {
"a.md": "# Alpha\n\nOrigin paragraph.\n\n[[notes/b.md|Right note]]\n",
"b.md": "# b.md\n\nOriginal text.\n\n```js\nconst answer = 42;\n```\n\n| Name | Value |\n| --- | --- |\n| Alpha | One |\n",
"c.md": "# c.md\n\nOriginal text.\n\n```js\nconst answer = 42;\n```\n\n| Name | Value |\n| --- | --- |\n| Alpha | One |\n",
"d.md": "# d.md\n\nOriginal text.\n\n```js\nconst answer = 42;\n```\n\n| Name | Value |\n| --- | --- |\n| Alpha | One |\n",
"notes/b.md": "# Bravo\n\nSecond paragraph.\n\n[Relative](c.md)\n\n[[/a.md|Original note]]\n",
"notes/c.md": "# Charlie\n\nThird paragraph.\n",
"sample.txt": "const answer = 42;\n",
},
});
Object.assign(test, { files: workspace.files, writes: [], prompts: [] });
return {
...workspace,
workspace_write: args => {
if (args.expected !== undefined && workspace.files.get(args.rel) !== args.expected) throw new Error("conflict");
workspace.files.set(args.rel, args.contents);
test.writes.push(args.rel);
},
spelling_menu_install: () => {},
"plugin:dialog|message": args => { test.prompts.push(args.message); return test.state.answer; },
};
},
});
const pane = path => page.locator(`[data-document-path="${path}"]`);
const item = name => page.getByRole('menuitem',{name,exact:true});
async function openRight(path,label) {
const current = pane(path);
await current.locator('.cm-content').getByText(path === 'a.md' ? 'Origin paragraph.' : 'Second paragraph.',{exact:true}).click();
await current.locator('.cm-content').getByText(label,{exact:true}).click({button:'right'});
await item('Open to the right').click();
}
async function append(path, text) {
const target=pane(path).locator('.cm-content');
await target.click(); await page.keyboard.press('Control+End'); await page.keyboard.type(text);
}
async function text(path) { return pane(path).locator('.cm-content').evaluate(async node=> { const {EditorView}=await import('/node_modules/@codemirror/view/dist/index.js'); return EditorView.findFromDOM(node).state.doc.toString(); }); }
async function focus(path) { await pane(path).locator('.cm-content').click(); }
async function changeOnDisk(path, text) {
await page.evaluate(([path, text]) => {
window.__TEST__.files.set(path, text);
window.__TEST__.emit("workspace-event", { root: "C:\\tab-menu-workspace", kind: "modify", paths: [path] });
}, [path, text]);
}
await page.goto(smokeUrl);
await page.locator('[data-tree-rel="a.md"]').click(); await pane('a.md').locator('.cm-content').waitFor();
await append('a.md','\nLeft unsaved.');
await openRight('a.md','Right note'); await pane('notes/b.md').locator('.cm-content').waitFor();
assert.equal(await page.locator('.document-pane').count(),2);
assert.match(await text('a.md'),/Left unsaved/);
await append('notes/b.md','\nRight saved.'); await page.keyboard.press('Control+s');
await page.waitForFunction(()=>window.tabMenuTest.writes.includes('notes/b.md'));
assert.equal(await page.evaluate(()=>window.tabMenuTest.writes.includes('a.md')),false,'Save uses the focused right pane');
await focus('a.md'); await page.keyboard.press('Control+s'); await page.waitForFunction(()=>window.tabMenuTest.writes.includes('a.md'));
await page.waitForFunction(()=>window.__TEST__.writes.includes('notes/b.md'));
assert.equal(await page.evaluate(()=>window.__TEST__.writes.includes('a.md')),false,'Save uses the focused right pane');
await focus('a.md'); await page.keyboard.press('Control+s'); await page.waitForFunction(()=>window.__TEST__.writes.includes('a.md'));
await pane('notes/b.md').getByRole('group',{name:'Editor layout',exact:true}).hover();
await pane('notes/b.md').getByRole('button',{name:'IDE',exact:true}).click(); await pane('notes/b.md').locator('.monaco-editor').waitFor();
assert.equal(await pane('a.md').locator('.cm-content').count(),1,'Changing the right mode keeps the left editor');
await openRight('a.md','Right note');
assert.equal(await page.locator('.document-pane').count(),2);
await page.waitForFunction(async()=>{const {monaco}=await import('/src/lib/editor/monacoEnv.ts');return monaco.editor.getEditors().some(editor=>editor.getModel()?.uri.path.endsWith('/b.md') && editor.hasTextFocus());}); await page.keyboard.press('Control+End'); await page.keyboard.type('\nIDE edit.'); await page.keyboard.press('Control+s');
await page.waitForFunction(()=>window.tabMenuTest.files.get('notes/b.md').includes('IDE edit.'));
await page.waitForFunction(()=>window.__TEST__.files.get('notes/b.md').includes('IDE edit.'));
await pane('notes/b.md').getByRole('group',{name:'Editor layout',exact:true}).hover();
await pane('notes/b.md').getByRole('button',{name:'Writer',exact:true}).click(); await pane('notes/b.md').locator('.cm-content').waitFor();
assert.match(await text('notes/b.md'),/IDE edit/);
@@ -123,7 +108,7 @@ try {
assert.match(await text('notes/c.md'),/Charlie/,'Relative links use the pane document folder');
await pane('notes/c.md').getByRole('button',{name:'Close split',exact:true}).click();
assert.equal(await page.locator('.document-pane').count(),2);
await page.evaluate(()=>window.tabMenuTest.change('notes/b.md','# Bravo disk\n\nExternal update.\n'));
await changeOnDisk('notes/b.md','# Bravo disk\n\nExternal update.\n');
await pane('notes/b.md').getByRole('alert').waitFor();
assert.equal(await pane('a.md').getByRole('alert').count(),0);
assert.match(await text('notes/b.md'),/Right still unsaved/,'A disk conflict preserves the right pane edits');
@@ -140,21 +125,20 @@ try {
await page.screenshot({path:`${output}/stacked-${theme}.png`});
}
await append('notes/b.md','\nNarrow edit.'); await page.keyboard.press('Control+s');
await page.waitForFunction(()=>window.tabMenuTest.files.get('notes/b.md').includes('Narrow edit.'));
await page.waitForFunction(()=>window.__TEST__.files.get('notes/b.md').includes('Narrow edit.'));
await pane('notes/b.md').getByRole('button',{name:'Close split',exact:true}).click();
await append('a.md','\nAfter closing split.'); await page.keyboard.press('Control+s');
await page.waitForFunction(()=>window.tabMenuTest.files.get('a.md').includes('After closing split.'));
await page.waitForFunction(()=>window.__TEST__.files.get('a.md').includes('After closing split.'));
await page.setViewportSize({width:1440,height:1000});
await openRight('a.md','Right note'); await pane('notes/b.md').locator('.cm-content').waitFor();
await append('notes/b.md','\nClose guard.');
await page.keyboard.press('Control+w');
await page.waitForFunction(()=>window.tabMenuTest.prompts.length>0);
await page.waitForFunction(()=>window.__TEST__.prompts.length>0);
assert.equal(await pane('notes/b.md').count(),1,'Cancel keeps the dirty split open');
await page.keyboard.press('Control+s'); await page.waitForFunction(()=>window.tabMenuTest.files.get('notes/b.md').includes('Close guard.'));
await page.keyboard.press('Control+s'); await page.waitForFunction(()=>window.__TEST__.files.get('notes/b.md').includes('Close guard.'));
await page.keyboard.press('Control+w'); await pane('notes/b.md').waitFor({state:'detached'});
await focus('a.md'); await append('a.md','\nOther tab closed.'); await page.keyboard.press('Control+s');
await page.waitForFunction(()=>window.tabMenuTest.files.get('a.md').includes('Other tab closed.'));
await page.waitForFunction(()=>window.__TEST__.files.get('a.md').includes('Other tab closed.'));
assert.equal(await page.evaluate(async()=>{const {monaco}=await import('/src/lib/editor/monacoEnv.ts');return monaco.editor.getModels().some(model=>model.uri.path.endsWith('/b.md'));}),false,'Closing the tab releases only its model');
assert.deepEqual(errors,[]);
console.log(JSON.stringify({passed:['independent Writer/IDE/Reading modes','dirty close cancellation and model release','independent edits and saves','per-pane selections','focus existing duplicate target','closing split retains unsaved tabs and models','nested relative link origin','per-pane conflict resolution','narrow layout and save','light/dark screenshots'],nativeDesktop:'not tested'},null,2));
} catch(error) { await page.screenshot({path:`${output}/failure.png`}); console.log(await page.locator('.status,.rs-menu').allTextContents()); throw error; } finally { await browser.close(); }
}, { timeout: 15000 });
+33 -49
View File
@@ -1,51 +1,36 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
// Custom window controls: maximize, restore, minimize, the terminal close guard, the keyboard tooltip, and the header at 1400 and 880 px.
// @requires plugin:terminal plugin:table-formulas
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1400, height: 900 } });
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const callbacks = new Map(), listeners = new Map();
let sequence = 0;
const state = { maximized: false, confirm: "Cancel", calls: [] };
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
state.calls.push(command);
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return null;
if (command === "plugin:window|is_maximized") return state.maximized;
if (command === "plugin:window|toggle_maximize") { state.maximized = !state.maximized; emit("tauri://resize", { width: 1400, height: 900 }); return; }
if (command === "plugin:window|minimize" || command === "plugin:window|destroy") return;
if (command === "plugin:window|close") { emit("tauri://close-requested"); return; }
if (command === "plugin:dialog|message") return state.confirm;
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { state, emit };
});
try {
const config = JSON.parse(await readFile(new URL("../../../src-tauri/tauri.conf.json", import.meta.url), "utf8"));
import path from "node:path";
import { mockTauri, outputDir, repoRoot, runSmoke, smokeUrl } from "../_harness/index.mjs";
import { mockFeaturePlugins } from "../_harness/pluginMocks.mjs";
await runSmoke("layout/windowControls", async ({ page }) => {
const output = await outputDir("layout/windowControls");
await mockTauri(page, {
state: { maximized: false, confirm: "Cancel" },
commands: test => ({
workspace_last_path: () => null,
"plugin:window|is_maximized": () => test.state.maximized,
"plugin:window|toggle_maximize": () => { test.state.maximized = !test.state.maximized; test.emit("tauri://resize", { width: 1400, height: 900 }); },
"plugin:window|minimize": () => {},
"plugin:window|destroy": () => {},
"plugin:window|close": () => { test.emit("tauri://close-requested"); },
"plugin:dialog|message": () => test.state.confirm,
}),
});
// The Terminal button belongs to the terminal plug-in (src/lib/layout/Workbench.svelte:1305).
await mockFeaturePlugins(page);
const called = command => page.evaluate(command => window.__TEST__.calls.some(call => call.command === command), command);
const config = JSON.parse(await readFile(path.join(repoRoot, "src-tauri/tauri.conf.json"), "utf8"));
assert.equal(config.app.windows[0].decorations, false);
const capability = JSON.parse(await readFile(new URL("../../../src-tauri/capabilities/default.json", import.meta.url), "utf8"));
const capability = JSON.parse(await readFile(path.join(repoRoot, "src-tauri/capabilities/default.json"), "utf8"));
for (const permission of ["close", "minimize", "toggle-maximize", "start-dragging"]) {
assert.ok(capability.permissions.includes(`core:window:allow-${permission}`));
}
await page.goto(process.env.SMOKE_URL || "http://localhost:1420");
await page.goto(smokeUrl);
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 }).click();
@@ -54,17 +39,17 @@ try {
await page.evaluate(() => { window.__TEST__.state.maximized = true; window.__TEST__.emit("tauri://resize", { width: 1920, height: 1080 }); });
await page.getByRole("button", { name: "Restore window", exact: true }).waitFor();
await page.getByRole("button", { name: "Minimize window", exact: true }).click();
assert.ok(await page.evaluate(() => window.__TEST__.state.calls.includes("plugin:window|minimize")));
assert.ok(await called("plugin:window|minimize"));
await page.getByRole("button", { name: "Close window", exact: true }).focus();
await page.getByRole("tooltip", { name: "Close window", exact: true }).waitFor();
// Opening the terminal engages the existing close guard; cancellation must not destroy the window.
await page.getByRole("button", { name: "Terminal", exact: true }).click();
await page.getByRole("button", { name: "Close window", exact: true }).click();
await page.waitForFunction(() => window.__TEST__.state.calls.includes("plugin:dialog|message"));
assert.equal(await page.evaluate(() => window.__TEST__.state.calls.includes("plugin:window|destroy")), false);
await page.waitForFunction(() => window.__TEST__.calls.some(call => call.command === "plugin:dialog|message"));
assert.equal(await called("plugin:window|destroy"), false);
await page.evaluate(() => window.__TEST__.state.confirm = "Ok");
await page.getByRole("button", { name: "Close window", exact: true }).click();
await page.waitForFunction(() => window.__TEST__.state.calls.includes("plugin:window|destroy"));
await page.waitForFunction(() => window.__TEST__.calls.some(call => call.command === "plugin:window|destroy"));
await page.getByRole("button", { name: "Terminal", exact: true }).click();
for (const width of [1400, 880]) {
await page.setViewportSize({ width, height: 900 });
@@ -77,8 +62,7 @@ try {
assert.equal(layout.top, 0);
assert.ok(layout.fits);
assert.ok(layout.drag >= 40);
await page.screenshot({ path: `.audit/window-controls-${width}.png` });
await page.screenshot({ path: path.join(output, `window-controls-${width}.png`) });
}
assert.deepEqual(errors, []);
console.log("Window controls smoke passed: actions, restore state, close guard, keyboard tooltip, and 1400/880px layouts.");
} finally { await browser.close(); }
}, { viewport: { width: 1400, height: 900 }, timeout: 30000 });
+133 -149
View File
@@ -1,106 +1,77 @@
// Core workbench: source edits and history, agent refresh and conflicts, persistent terminals, Reading and Mermaid previews, the live Writer, tables and their menus, and narrow layouts.
// @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";
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
const showcase = await readFile(new URL("../../../fixtures/reader-showcase.md", import.meta.url), "utf8");
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
import path from "node:path";
import { mockTauri, outputDir, repoRoot, runSmoke, smokeUrl } from "../_harness/index.mjs";
import { mockFeaturePlugins } from "../_harness/pluginMocks.mjs";
await runSmoke("layout/workbench", async ({ page }) => {
const output = await outputDir("layout/workbench");
const showcase = await readFile(path.join(repoRoot, "fixtures/reader-showcase.md"), "utf8");
await mockTauri(page, {
commands: test => {
const workspace = test.workspace({
root: "C:\\smoke-workspace",
writeEvents: true,
files: {
"notes/welcome.md": "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n",
"notes/second.md": "# Second note\n",
"src/hello.py": "print('hello')\n",
},
});
Object.assign(test, { files: workspace.files, root: workspace.root });
// The terminal plug-in opens shells through these commands.
const pty = {};
for (const command of ["pty_write", "pty_resize", "pty_close"]) pty[command] = () => {};
return {
...workspace,
...pty,
workspace_write: args => {
if (args.expected !== undefined && workspace.files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
return workspace.workspace_write(args);
},
workspace_search: () => [],
pty_profiles: () => [{ id: "powershell", title: "PowerShell", kind: "powershell" }],
pty_open: async args => {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
test.emit("pty-data", { id: args.id, data: data.slice(0, 8) });
test.emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
},
"plugin:dialog|message": () => "Cancel",
};
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
await mockFeaturePlugins(page);
async function quickOpen(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();
if (await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).count()) {
await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click();
}
await page.locator(".monaco-editor textarea").waitFor();
}
async function contents() {
return page.evaluate(async () => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
return monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected)?.getValue();
});
}
async function waitForText(text) {
await page.evaluate(async () => { window.__MONACO__ = (await import("/src/lib/editor/monacoEnv.ts")).monaco; });
await page.waitForFunction(expected => window.__MONACO__.editor.getEditors().some(editor => editor.getDomNode()?.isConnected && editor.getValue() === expected), text);
}
async function focusEditor() {
await page.locator(".monaco-host .view-lines").click({position:{x:120,y:12}});
}
await mockFeaturePlugins(page);
try {
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
// Choose a mode from a compact mode switcher, such as "Editor layout" or "Document view".
async function mode(group, value) {
await page.getByRole("group", { name: group, exact: true }).hover();
await page.getByRole("button", { name: value, exact: true }).click();
}
async function quickOpen(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 mode("Editor layout", "IDE");
await page.locator(".monaco-editor textarea").waitFor();
}
async function contents() {
return page.evaluate(async () => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
return monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected)?.getValue();
});
}
async function waitForText(text) {
await page.evaluate(async () => { window.__MONACO__ = (await import("/src/lib/editor/monacoEnv.ts")).monaco; });
await page.waitForFunction(expected => window.__MONACO__.editor.getEditors().some(editor => editor.getDomNode()?.isConnected && editor.getValue() === expected), text);
}
async function focusEditor() {
await page.locator(".monaco-host .view-lines").click({position:{x:120,y:12}});
}
await page.goto(smokeUrl);
await page.getByText("smoke-workspace", { exact: true }).waitFor();
await quickOpen("welcome.md");
const original = await contents();
@@ -119,7 +90,7 @@ try {
await page.keyboard.press("Control+s");
await page.waitForFunction(expected => window.__TEST__.files.get("notes/welcome.md") === expected, original + "Added in source.");
await page.getByRole("button", { name: "Split", exact: true }).click();
await mode("Document view", "Split");
await page.locator(".md-page h1").first().waitFor();
assert.ok(await page.locator(".monaco-host").isVisible());
await page.evaluate(() => {
@@ -143,8 +114,8 @@ try {
await page.getByRole("button", { name: "Terminal", exact: true }).click();
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_open"));
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_write" && /\x1b\[\d+;\d+R/.test(c.args.data)));
await page.screenshot({ path: ".audit/core-rebuild-terminal.png" });
await page.getByRole("button", { name: "Hide terminal (sessions keep running)" }).click();
await page.screenshot({ path: path.join(output, "core-rebuild-terminal.png") });
await page.getByRole("button", { name: "Terminal", exact: true }).click();
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_close").length), 0);
await page.getByRole("button", { name: "Terminal", exact: true }).click();
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_open").length), 1);
@@ -152,24 +123,31 @@ try {
await page.waitForFunction(() => window.__TEST__.calls.filter(c => c.command === "pty_open").length === 2);
await page.getByRole("button", { name: "Kill terminal", exact: true }).first().click();
await page.waitForFunction(() => window.__TEST__.calls.filter(c => c.command === "pty_close").length === 1);
await page.getByRole("button", { name: "Hide terminal (sessions keep running)" }).click();
await page.getByRole("button", { name: "Terminal", exact: true }).click();
await page.keyboard.press("Control+n");
await page.getByLabel("New file path relative to the workspace").fill("notes/new-note.md");
await page.getByRole("button", { name: "Continue", exact: true }).click();
await page.getByRole("tab", { name: "new-note.md", exact: true }).waitFor();
await page.screenshot({ path: ".audit/core-rebuild.png" });
// A new note starts in its filename field, which keeps its own keys (src/lib/editor/LiveWriter.svelte:381, src/lib/editor/noteTitle.ts:80).
await page.getByRole("textbox", { name: "Note filename", exact: true }).waitFor();
await page.screenshot({ path: path.join(output, "core-rebuild.png") });
await page.keyboard.press("Escape");
await page.evaluate(text => {
window.__TEST__.files.set("reader-showcase.md", text);
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "create", paths: ["reader-showcase.md"] });
}, showcase);
await quickOpen("reader-showcase.md");
const read = page.getByRole("button", { name: "Read", exact: true });
// The Read mode is a compact switcher button; its tooltip is a decorative child (src/lib/ui/ModeSwitcher.svelte:108).
const documentView = page.getByRole("group", { name: "Document view", exact: true });
const read = documentView.locator('button[aria-label="Read"]');
const readTip = read.locator(".tooltip");
assert.equal(await read.innerText(), "");
assert.equal(await read.locator("svg").count(), 1);
await documentView.hover();
await read.hover();
await page.getByRole("tooltip", { name: "Read", exact: true }).waitFor({ state: "visible" });
const tip = await page.getByRole("tooltip", { name: "Read", exact: true }).boundingBox();
await readTip.waitFor({ state: "visible" });
const tip = await readTip.boundingBox();
assert.ok(tip.x >= 0 && tip.x + tip.width <= 1440);
await read.click();
assert.equal(await read.getAttribute("aria-pressed"), "true");
@@ -184,37 +162,38 @@ try {
const surface = await page.locator(".reading").boundingBox();
assert.ok(surface.width <= 741);
await page.mouse.move(700, 980);
await page.screenshot({ path: ".audit/reader-mode.png" });
await page.screenshot({ path: path.join(output, "reader-mode.png") });
await page.locator(".md-table-scroll").scrollIntoViewIfNeeded();
await page.getByRole("button", { name: "Copy code", exact: true }).click();
await page.getByRole("button", { name: "Copied", exact: true }).waitFor();
await page.screenshot({ path: ".audit/reader-details.png" });
await page.screenshot({ path: path.join(output, "reader-details.png") });
await page.setViewportSize({ width: 1000, height: 900 });
await page.locator(".md-page").evaluate(element => { element.scrollTop = 0; });
await page.screenshot({ path: ".audit/reader-narrow.png" });
await page.screenshot({ path: path.join(output, "reader-narrow.png") });
assert.ok(await page.locator(".md-page").evaluate(element => element.scrollWidth <= element.clientWidth + 1));
await page.getByRole("button", { name: "Split", exact: true }).click();
await mode("Document view", "Split");
await page.waitForFunction(() => {
const host = document.querySelector(".monaco-host");
const rendered = host?.querySelector(".monaco-editor");
return rendered && Math.abs(host.clientWidth - rendered.clientWidth) < 2;
});
assert.equal(await page.locator(".body.split").evaluate(element => getComputedStyle(element).flexDirection), "column");
await page.screenshot({ path: ".audit/reader-split.png" });
await page.screenshot({ path: path.join(output, "reader-split.png") });
assert.ok(await page.locator(".md-page").evaluate(element => element.scrollWidth <= element.clientWidth + 1));
await page.setViewportSize({ width: 1440, height: 1000 });
await page.waitForFunction(() => getComputedStyle(document.querySelector(".body.split")).flexDirection === "row");
await page.screenshot({ path: ".audit/reader-split-wide.png" });
await page.screenshot({ path: path.join(output, "reader-split-wide.png") });
await page.getByRole("button", { name: "Edit", exact: true }).click();
await mode("Document view", "Edit");
assert.equal(await contents(), showcase);
assert.equal(await page.evaluate(() => window.__TEST__.files.get("reader-showcase.md")), showcase);
await page.getByRole("button", { name: "Read", exact: true }).focus();
await page.getByRole("tooltip", { name: "Read", exact: true }).waitFor({ state: "visible" });
await documentView.hover();
await read.focus();
await readTip.waitFor({ state: "visible" });
await page.keyboard.press("Escape");
await page.getByRole("tooltip", { name: "Read", exact: true }).waitFor({ state: "hidden" });
await readTip.waitFor({ state: "hidden" });
// Continuous live Markdown: only active lines reveal source; checkboxes
// remain inline and update the original file without HTML serialization.
@@ -224,7 +203,7 @@ try {
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "create", paths: ["writing.md"] });
}, writingSource);
await quickOpen("writing.md");
await page.getByRole("button", { name: "Switch to writing layout (Ctrl E)", exact: true }).click();
await mode("Editor layout", "Writer");
const writer = page.getByRole("textbox", { name: "Writing editor", exact: true });
await writer.waitFor();
assert.equal(await page.locator('.live-writer [contenteditable="true"]').count(), 1);
@@ -245,12 +224,12 @@ try {
await page.keyboard.press("Control+y");
await page.keyboard.press("Control+s");
await page.waitForFunction(text => window.__TEST__.files.get("writing.md") === text, editedSource);
await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click();
await mode("Editor layout", "IDE");
await waitForText(editedSource);
await focusEditor();
await page.keyboard.press("Control+z");
await waitForText(writingSource);
await page.getByRole("button", { name: "Switch to writing layout (Ctrl E)", exact: true }).click();
await mode("Editor layout", "Writer");
await writer.waitFor();
await paragraph.click();
await page.keyboard.press("End");
@@ -297,9 +276,10 @@ try {
assert.equal(await task.locator('.writer-completed').evaluate(el => getComputedStyle(el).textDecorationLine), 'line-through');
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("writing.md").includes('- [x] Ship draft'));
// Task markers stay rendered until the cursor reaches them (src/lib/editor/liveMarkdown.ts:262-268).
await task.locator('.writer-completed').click();
await page.locator('.live-writer .cm-line').filter({ hasText: '- [x] Ship draft' }).waitFor();
await page.keyboard.press("Home");
await page.locator('.live-writer .cm-line').filter({ hasText: '- [x] Ship draft' }).waitFor();
await page.keyboard.press("Shift+End");
await page.keyboard.type('- [ ] Revised task');
await page.keyboard.press("ArrowUp");
@@ -307,7 +287,7 @@ try {
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("writing.md").includes('- [ ] Revised task'));
await page.locator(".live-writer .md-diagram svg").waitFor();
await page.screenshot({ path: ".audit/writing-continuous.png" });
await page.screenshot({ path: path.join(output, "writing-continuous.png") });
await page.setViewportSize({ width: 1000, height: 900 });
assert.ok(await page.locator(".cm-scroller").evaluate(el => el.scrollWidth <= el.clientWidth + 1));
await page.evaluate(() => {
@@ -315,7 +295,7 @@ try {
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "create", paths: ["crlf.md"] });
});
await quickOpen("crlf.md");
await page.getByRole("button", { name: "Switch to writing layout (Ctrl E)", exact: true }).click();
await mode("Editor layout", "Writer");
await page.locator(".live-writer .cm-line").filter({ hasText: "A paragraph." }).click();
await page.keyboard.press("Home");
await page.keyboard.type("Changed ");
@@ -324,6 +304,8 @@ try {
await page.keyboard.press("Control+n");
await page.getByLabel("New file path relative to the workspace").fill("blank.md");
await page.getByRole("button", { name: "Continue", exact: true }).click();
// Enter keeps the new note's filename and moves to its body (src/lib/editor/noteTitle.ts:57, 83).
await page.getByRole("textbox", { name: "Note filename", exact: true }).press("Enter");
await writer.waitFor();
await page.keyboard.type("One");
await page.keyboard.press("Enter");
@@ -342,7 +324,8 @@ try {
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("blank.md").replace(/\r\n/g, "\n") === "One\nTwo\nThree");
await page.keyboard.press("Control+f");
await page.getByRole("textbox", { name: "Find", exact: true }).fill("Two");
// The find field is labelled "Find in document" (src/lib/editor/FindPanel.svelte:60).
await page.getByRole("textbox", { name: "Find in document", exact: true }).fill("Two");
await page.keyboard.press("Escape");
await page.keyboard.press("Control+a");
await page.keyboard.type("- [ ] First task");
@@ -365,7 +348,7 @@ try {
}, tableSource);
await page.setViewportSize({ width: 1440, height: 1000 });
await quickOpen("tables.md");
await page.getByRole("button", { name: "Switch to writing layout (Ctrl E)", exact: true }).click();
await mode("Editor layout", "Writer");
const table = page.locator('.live-writer table');
await table.waitFor();
assert.equal(await page.locator('.live-writer .document-title').innerText(), 'tables');
@@ -381,7 +364,11 @@ try {
assert.equal(await table.locator('tbody tr').count(), 2);
assert.equal(await table.locator('br').count(), 4);
assert.ok(!(await table.innerText()).includes('<br>'));
assert.ok(await table.locator('th').evaluateAll(cells => cells.every(cell => cell.getBoundingClientRect().width >= 100)));
// Columns keep the 3rem minimum width (src/app.css:289; reduced from 8rem in 909894b).
assert.ok(await table.locator('th').evaluateAll(cells => {
const minimum = 3 * parseFloat(getComputedStyle(document.documentElement).fontSize);
return cells.every(cell => cell.getBoundingClientRect().width >= minimum - 0.5);
}));
assert.ok(await table.locator('td').evaluateAll(cells => cells.every(cell => getComputedStyle(cell).verticalAlign === 'top')));
assert.ok(await page.locator('.cm-scroller').evaluate(el => el.scrollWidth <= el.clientWidth + 1));
const addColumn = page.getByRole('button', { name: 'Add column to the right', exact: true });
@@ -393,12 +380,12 @@ try {
await page.waitForFunction(() => [...document.querySelectorAll('.table-add')].every(button => getComputedStyle(button).opacity === '0'));
await addColumn.hover();
await page.waitForFunction(() => getComputedStyle(document.querySelector('.table-add-column')).opacity === '1');
await page.screenshot({ path: '.audit/writing-table-column.png' });
await page.screenshot({ path: path.join(output, 'writing-table-column.png') });
await addColumn.click();
await page.waitForFunction(() => document.querySelectorAll('.live-writer th').length === 6);
await addRow.hover();
await page.waitForFunction(() => getComputedStyle(document.querySelector('.table-add-row')).opacity === '1');
await page.screenshot({ path: '.audit/writing-table-row.png' });
await page.screenshot({ path: path.join(output, 'writing-table-row.png') });
await addRow.click();
await page.waitForFunction(() => document.querySelectorAll('.live-writer tbody tr').length === 3);
await page.keyboard.press('Control+s');
@@ -426,12 +413,13 @@ try {
await table.locator('tbody tr').first().locator('td').nth(4).click();
assert.equal(await cellEditor.locator('br:not(.ProseMirror-trailingBreak)').count(), 3);
await page.keyboard.press('Control+End');
await page.keyboard.press('Enter');
// Shift+Enter adds a line break in a cell; Enter moves to the next row (src/lib/editor/tableControls.ts:278-286).
await page.keyboard.press('Shift+Enter');
await page.keyboard.type('Plain | pipe and *stars*');
await page.keyboard.press('Control+s');
await page.waitForFunction(() => window.__TEST__.files.get('tables.md').includes('<br>Plain \\| pipe and \\*stars\\*'));
assert.equal(await table.locator('th').count(), 6);
await page.screenshot({ path: '.audit/writing-table-cell-edit.png' });
await page.screenshot({ path: path.join(output, 'writing-table-cell-edit.png') });
await page.keyboard.press('Control+z');
await page.keyboard.press('Control+s');
await page.waitForFunction(() => !window.__TEST__.files.get('tables.md').includes('Plain'));
@@ -453,7 +441,7 @@ try {
await page.keyboard.press('Escape');
await page.setViewportSize({ width: 1000, height: 900 });
assert.ok(await page.locator('.cm-scroller').evaluate(el => el.scrollWidth <= el.clientWidth + 1));
await page.getByRole('button', { name: 'Read', exact: true }).click();
await mode('Document view', 'Read');
assert.equal(await page.locator('.md-page .document-title').innerText(), 'tables');
assert.equal(await page.locator('.md-page table br').count(), 5);
assert.ok(await page.locator('.md-page').evaluate(el => el.scrollWidth <= el.clientWidth + 1));
@@ -463,14 +451,16 @@ try {
window.__TEST__.files.set('selection-table.md', text);
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['selection-table.md'] });
window.__TEST__.clipboard = '';
// Cell copies write plain text and HTML through clipboard.write (src/lib/editor/tableSelectionControls.ts:80-85).
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: {
write: async items => { window.__TEST__.clipboard = await (await items[0].getType('text/plain')).text(); },
writeText: async text => { window.__TEST__.clipboard = text; },
readText: async () => window.__TEST__.clipboard,
} });
}, selectionTable);
await quickOpen('selection-table.md');
await page.getByRole('button', { name: 'Edit', exact: true }).click();
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
await mode('Document view', 'Edit');
await mode('Editor layout', 'Writer');
const selectedTable = page.locator('.live-writer table');
const selectedCell = (r, c) => selectedTable.locator('tr').nth(r).locator('th, td').nth(c);
const fromCell = await selectedCell(1, 0).boundingBox(), toCell = await selectedCell(2, 1).boundingBox();
@@ -482,7 +472,7 @@ try {
await selectedCell(1, 0).click({ button: 'right' });
await page.getByRole('menuitem', { name: 'Format', exact: true }).hover();
await page.getByRole('menuitem', { name: 'Bold', exact: true }).waitFor();
await page.screenshot({ path: '.audit/table-cell-selection-menu.png' });
await page.screenshot({ path: path.join(output, 'table-cell-selection-menu.png') });
await page.getByRole('menuitem', { name: 'Bold', exact: true }).click();
await page.waitForFunction(() => document.querySelectorAll('.live-writer table strong').length === 4);
await page.waitForFunction(() => document.querySelectorAll('.is-cell-selected').length === 4);
@@ -502,7 +492,8 @@ try {
await cellAction('Clear formatting', true);
await page.waitForFunction(() => document.querySelectorAll('.live-writer table strong').length === 0);
await cellAction('Copy');
assert.equal(await page.evaluate(() => window.__TEST__.clipboard), 'one\ttwo\nfour\tfive');
// clipboard.write resolves its items asynchronously.
await page.waitForFunction(expected => window.__TEST__.clipboard === expected, 'one\ttwo\nfour\tfive');
await cellAction('Cut');
await page.waitForFunction(() => [...document.querySelectorAll('.is-cell-selected')].every(cell => !cell.textContent.trim()));
await cellAction('Paste');
@@ -560,8 +551,8 @@ try {
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['table-actions.md'] });
}, actionsSource);
await quickOpen('table-actions.md');
await page.getByRole('button', { name: 'Edit', exact: true }).click();
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
await mode('Document view', 'Edit');
await mode('Editor layout', 'Writer');
const actionTable = page.locator('.live-writer table');
const actionCell = (r, c) => actionTable.locator('tr').nth(r).locator('th, td').nth(c);
async function actionItem(label, group, r = 1, c = 0) {
@@ -623,9 +614,9 @@ try {
assert.equal(await page.getByRole('menuitem', { name: 'Copy', exact: true }).isDisabled(), false);
assert.ok(await page.locator('.table-cell-menu button').evaluateAll(buttons => buttons.every(button => button.querySelector('svg[aria-hidden="true"]'))));
await page.getByRole('menuitem', { name: 'Row', exact: true }).hover();
await page.screenshot({ path: '.audit/table-text-row-menu.png' });
await page.screenshot({ path: path.join(output, 'table-text-row-menu.png') });
await page.getByRole('menuitem', { name: 'Column', exact: true }).hover();
await page.screenshot({ path: '.audit/table-text-column-menu.png' });
await page.screenshot({ path: path.join(output, 'table-text-column-menu.png') });
await page.getByRole('menuitem', { name: 'Column', exact: true }).focus();
await page.keyboard.press('ArrowRight');
assert.equal(await page.evaluate(() => document.activeElement.textContent), 'Add column to the left');
@@ -697,8 +688,8 @@ try {
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['rich-table.md'] });
}, richTable);
await quickOpen('rich-table.md');
await page.getByRole('button', { name: 'Edit', exact: true }).click();
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
await mode('Document view', 'Edit');
await mode('Editor layout', 'Writer');
const richCell = page.locator('.live-writer tbody tr').first().locator('td').last();
assert.equal(await page.locator('.live-writer .document-title').innerText(), 'rich-table');
await richCell.click();
@@ -746,7 +737,7 @@ try {
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['table-hit-testing.md'] });
}, hitTestSource);
await quickOpen('table-hit-testing.md');
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
await mode('Editor layout', 'Writer');
async function clickRenderedLine(locator, expected) {
await locator.scrollIntoViewIfNeeded();
const rect = await locator.boundingBox();
@@ -790,13 +781,6 @@ try {
await checkLinesAfterTables();
await page.setViewportSize({ width: 1000, height: 900 });
await checkLinesAfterTables();
await page.screenshot({ path: '.audit/table-cursor-position.png' });
assert.deepEqual(errors, []);
await page.screenshot({ path: path.join(output, 'table-cursor-position.png') });
console.log("PASS: continuous live Markdown, raw active lines, editable links and checklists, completed-task strikethrough, cross-line selection, preservation and history, search, table layout/line breaks/edge insertion/cell editing/undo, save, agent refresh, conflicts, persistent terminals, reader and Mermaid previews, narrow layouts (mocked desktop IPC).");
} catch (error) {
console.error("Browser errors:", errors);
console.error("Writing source:", await page.evaluate(() => window.__TEST__?.files.get("writing.md")));
console.error("Visible text:", (await page.locator("body").innerText()).slice(0, 5000));
await page.screenshot({ path: ".audit/core-rebuild-failure.png" });
throw error;
} finally { await browser.close(); }
});
+17 -24
View File
@@ -1,17 +1,12 @@
import { createRequire } from "node:module";
import { mkdir, writeFile } from "node:fs/promises";
// Backlinks panel in isolation: both themes, narrow panels, long lists, keyboard use, empty, busy, and error states, and text contrast.
import { writeFile } from "node:fs/promises";
import assert from "node:assert/strict";
import path from "node:path";
import { outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 720, height: 640 } });
const errors = [];
page.on("pageerror", error => errors.push(error.message));
const output = ".audit/backlinks";
await mkdir(output, { recursive: true });
await page.route("**/__backlinks__", route => route.fulfill({ contentType: "text/html", body: `<!doctype html><html><head><meta charset="UTF-8"><title>Backlinks check</title></head><body>
await runSmoke("links/backlinks", async ({ page }) => {
const output = await outputDir("links/backlinks");
await page.route("**/__backlinks__", route => route.fulfill({ contentType: "text/html", body: `<!doctype html><html><head><meta charset="UTF-8"><title>Backlinks check</title></head><body>
<aside id="fixture" style="width:320px;height:500px;display:flex;flex-direction:column;background:var(--rs-bg-elevated);margin:24px"></aside>
<script type="module">
import '/src/app.css';
@@ -29,15 +24,14 @@ await window.renderBacklinks();
window.backlinksReady=true;
</script></body></html>` }));
const entries = Array.from({ length: 28 }, (_, index) => ({
sourcePath: `research/long-folder-name/project-${index + 1}/source-note-with-a-long-readable-title.md`,
line: index + 3, from: index * 100, to: index * 100 + 10,
text: "This source note links to [[Target|the selected note]]. Its visible excerpt can wrap within the panel.",
kind: "wiki", target: "Target",
}));
const measurements = [];
try {
await page.goto(`${process.env.SMOKE_URL || "http://127.0.0.1:1420"}/__backlinks__`);
const entries = Array.from({ length: 28 }, (_, index) => ({
sourcePath: `research/long-folder-name/project-${index + 1}/source-note-with-a-long-readable-title.md`,
line: index + 3, from: index * 100, to: index * 100 + 10,
text: "This source note links to [[Target|the selected note]]. Its visible excerpt can wrap within the panel.",
kind: "wiki", target: "Target",
}));
const measurements = [];
await page.goto(`${smokeUrl}/__backlinks__`);
await page.waitForFunction(() => window.backlinksReady);
const panel = page.getByRole("region", { name: "Backlinks", exact: true });
await panel.getByText("No other notes link to this file.").waitFor();
@@ -84,7 +78,6 @@ try {
assert.equal(await panel.getByRole("button", { name:"Rebuild note index", exact:true }).isDisabled(), true);
await panel.getByText("Reading workspace links…").waitFor();
await page.screenshot({ path:`${output}/busy-error-dark.png` });
assert.deepEqual(errors, []);
await writeFile(`${output}/measurements.json`, JSON.stringify(measurements,null,2));
await writeFile(path.join(output, "measurements.json"), JSON.stringify(measurements,null,2));
console.log("Backlinks smoke passed: themes, narrow panels, long lists, keyboard, empty, busy, error, and contrast.");
} finally { await browser.close(); }
}, { viewport: { width: 720, height: 640 }, timeout: 30000 });
+81
View File
@@ -0,0 +1,81 @@
// File tree drags into Writer and the IDE: documents become escaped links, images embed, and undo restores the source.
import assert from "node:assert/strict";
import { mockTauri, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("links/fileDragLinks", async ({ page }) => {
await page.addInitScript(() => localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false })));
await mockTauri(page, {
commands: test => {
const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="100" height="80"><rect width="100" height="80" fill="#639"/></svg>';
const workspace = test.workspace({
root: "C:\\file-drag-links",
files: { "notes/draft.md": "Before.\n\nAfter.\n", "files/report [Q1] (#1).pdf": "PDF fixture", "images/diagram (#1).svg": btoa(svg) },
});
return {
...workspace,
workspace_read_data_url: ({ rel }) => "data:image/svg+xml;base64," + workspace.files.get(rel),
plugins_snapshot: () => ({ plugins: [], issues: [] }),
spelling_menu_install: () => null,
};
},
});
const row = path => page.locator(`[data-tree-rel="${path}"]`);
async function drag(path, target) {
const from = await row(path).boundingBox(), to = await page.locator(target).boundingBox();
assert.ok(from && to, "The file and editor must be visible");
await page.mouse.move(from.x + Math.min(80, from.width / 2), from.y + from.height / 2);
await page.mouse.down();
await page.mouse.move(to.x + 45, to.y + 12, { steps: 15 });
await page.locator(".image-drop-target").waitFor();
await page.mouse.up();
}
const writerSource = () => page.evaluate(() => window.dragWriter.state.doc.toString());
const ideSource = () => page.evaluate(() => window.dragMonaco.getValue());
await page.goto(smokeUrl);
await row("notes").click();
await row("notes/draft.md").dblclick();
await page.locator(".cm-content").waitFor();
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
window.dragWriter = EditorView.findFromDOM(document.querySelector(".cm-content"));
});
await row("files").click();
const original = await writerSource();
await drag("files/report [Q1] (#1).pdf", ".cm-content");
await page.waitForFunction(() => window.dragWriter.state.doc.toString().includes(".pdf)"));
const linked = await writerSource();
assert.ok(linked.includes("[report \\[Q1\\] (#1).pdf](../files/report%20%5BQ1%5D%20%28%231%29.pdf)"), linked);
assert.ok(!linked.includes("!["), "A document must be a link, not an image");
await page.evaluate(() => window.dragWriter.focus());
await page.keyboard.press("Control+z");
assert.equal(await writerSource(), original, "Writer undo restores the exact source");
await row("images").click();
await drag("images/diagram (#1).svg", ".cm-content");
await page.locator(".md-image-frame img").waitFor();
assert.ok((await writerSource()).includes("![](../images/diagram%20%28%231%29.svg)"));
await page.evaluate(() => window.dragWriter.focus());
await page.keyboard.press("Control+z");
assert.equal(await writerSource(), original);
console.log("PASS: Writer drags insert escaped document links and image embeds, and undo restores the source");
await page.keyboard.press("Control+e");
await page.locator(".monaco-editor textarea").waitFor();
await page.evaluate(async () => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
window.dragMonaco = monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected);
});
const originalIde = await ideSource();
await drag("files/report [Q1] (#1).pdf", ".monaco-editor .view-lines");
await page.waitForFunction(() => window.dragMonaco.getValue().includes(".pdf)"));
assert.ok((await ideSource()).includes("[report \\[Q1\\] (#1).pdf](../files/report%20%5BQ1%5D%20%28%231%29.pdf)"));
await page.evaluate(() => window.dragMonaco.focus());
assert.equal(await page.evaluate(() => window.dragMonaco.hasTextFocus()), true);
await page.keyboard.press("Control+z");
await page.waitForFunction(expected => window.dragMonaco.getValue() === expected, originalIde, { timeout: 3000 });
assert.equal(await ideSource(), originalIde, "IDE undo restores the exact source");
await drag("images/diagram (#1).svg", ".monaco-editor .view-lines");
assert.ok((await ideSource()).includes("![](../images/diagram%20%28%231%29.svg)"));
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(call => ["workspace_rename", "workspace_write_bytes"].includes(call.command)).length), 0);
console.log("PASS: IDE drags insert escaped document links and image embeds, undo restores the source, and no file moves");
}, { timeout: 15000 });
+91 -121
View File
@@ -1,129 +1,99 @@
import { createRequire } from "node:module";
// Link editing in the Writer: link tooltips and source colors, Edit link in prose, table, and wiki cells with undo, multiple links in a cell, and table tooltips at narrow widths.
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 page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(15000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await mkdir(".audit", { recursive: true });
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\tab-menu-workspace";
const files = new Map(["a.md", "b.md", "c.md", "d.md"].map(name => [name, `# ${name}\n\nOriginal [guide](docs/guide.md) text.\n\n| Name | Value |\n| --- | --- |\n| [Roadmap](docs/roadmap.md) | [[guide\\|Guide]] |\n| [One](same.md) + [Two](same.md) | Empty |\n`]));
window.tabMenuTest = { prompts: [], answer: "Cancel", revealed: null, clipboard: null };
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { window.tabMenuTest.clipboard = text; } } });
let sequence = 0;
const callbacks = new Map(), listeners = new Map();
window.spellingTest = { commands: [], emit: payload => callbacks.get(listeners.get("spelling-menu"))?.({ event: "spelling-menu", id: 1, payload }) };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { callbacks.set(++sequence, callback); return sequence; }, unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === "plugin:event|listen") { listeners.set(args.event, args.handler); return ++sequence; }
if (command === "plugin:event|unlisten") return;
if (command.startsWith("spelling_menu_")) { window.spellingTest.commands.push({ method: command, ...args }); return; }
if (command === "spelling_suggestions") return { language: "en-US", words: [], misspelled: false };
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "tab-menu-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_list") return args.rel ? [] : [{ name: "notes", rel_path: "notes", kind: "folder" }, ...[...files.keys()].map(name => ({ name, rel_path: name, kind: "file" }))];
if (command === "workspace_search") return [];
if (command === "workspace_write") { files.set(args.rel, args.contents); return; }
if (command === "workspace_rename") { files.set(args.to, files.get(args.from)); files.delete(args.from); return; }
if (command === "workspace_abs_path") return `${root}\\${args.rel}`;
if (command === "workspace_reveal") { window.tabMenuTest.revealed = args.rel; return; }
if (command === "plugin:dialog|message") { window.tabMenuTest.prompts.push(args.message); return window.tabMenuTest.answer; }
throw new Error(`Unhandled IPC: ${command}`);
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("links/linkEditing", async ({ page }) => {
const output = await outputDir("links/linkEditing");
await mockTauri(page, {
commands: test => {
const note = name => `# ${name}\n\nOriginal [guide](docs/guide.md) text.\n\n| Name | Value |\n| --- | --- |\n| [Roadmap](docs/roadmap.md) | [[guide\\|Guide]] |\n| [One](same.md) + [Two](same.md) | Empty |\n`;
return {
...test.workspace({ root: "C:\\tab-menu-workspace", folders: ["notes"], files: Object.fromEntries(["a.md", "b.md", "c.md", "d.md"].map(name => [name, note(name)])) }),
spelling_menu_install: () => {},
};
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await page.locator('[data-tree-rel="a.md"]').click();
await page.locator('.writer-table').waitFor();
for(const theme of ['dark','light']) {
await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({theme:'default',mode}), theme);
const prose = page.locator('.writer-link').filter({hasText:'guide'}).first();
await prose.hover();
await page.locator('.rs-tooltip:popover-open').waitFor();
assert.equal(await prose.getAttribute('title'),null);
await page.screenshot({path:'.audit/editor-link-tooltip-'+theme+'.png'});
await page.keyboard.press('Escape');
await prose.click();
assert.equal(await page.locator('.writer-link-source').count(),1);
const colored = await page.locator('.writer-link-source').evaluate(el => ({color:getComputedStyle(el).color, parent:getComputedStyle(el.parentElement).color}));
assert.notEqual(colored.color,colored.parent);
await page.screenshot({path:'.audit/editor-link-source-'+theme+'.png'});
const cell=page.locator('.writer-table td').first();
await cell.locator('a').click({position:{x:22,y:8}});
assert.ok(await page.evaluate(()=>getSelection().anchorOffset > 0));
await cell.click({button:'right'});
await page.getByRole('menuitem',{name:'Edit link',exact:true}).click();
assert.equal(await page.getByRole('dialog').count(),0);
assert.equal(await page.evaluate(()=>getSelection().toString()),theme === 'dark' ? 'docs/roadmap.md' : 'docs/new-roadmap.md');
await page.screenshot({path:'.audit/editor-table-source-'+theme+'.png'});
await page.keyboard.type('docs/new-roadmap.md');
await page.keyboard.press('Enter');
assert.equal(await cell.locator('a').getAttribute('href'),'docs/new-roadmap.md');
if(theme === 'dark') {
await page.locator('.cm-line').filter({hasText:'Original'}).click();
await page.keyboard.press('Control+z');
assert.equal(await cell.locator('a').getAttribute('href'),'docs/roadmap.md');
await page.keyboard.press('Control+Shift+z');
assert.equal(await cell.locator('a').getAttribute('href'),'docs/new-roadmap.md');
});
await page.goto(smokeUrl);
await page.locator('[data-tree-rel="a.md"]').click();
await page.locator('.writer-table').waitFor();
for(const theme of ['dark','light']) {
await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({theme:'default',mode}), theme);
const prose = page.locator('.writer-link').filter({hasText:'guide'}).first();
await prose.hover();
// A focused table cell can keep its own tooltip open (src/lib/ui/tooltip.ts:32), so wait for the link's tooltip.
await page.getByRole('tooltip',{name:'Ctrl+click to open link',exact:true}).waitFor();
assert.equal(await prose.getAttribute('title'),null);
await page.screenshot({path:path.join(output, 'editor-link-tooltip-'+theme+'.png')});
await page.keyboard.press('Escape');
await prose.click();
assert.equal(await page.locator('.writer-link-source').count(),1);
const colored = await page.locator('.writer-link-source').evaluate(el => ({color:getComputedStyle(el).color, parent:getComputedStyle(el.parentElement).color}));
assert.notEqual(colored.color,colored.parent);
await page.screenshot({path:path.join(output, 'editor-link-source-'+theme+'.png')});
const cell=page.locator('.writer-table td').first();
await cell.locator('a').click({position:{x:22,y:8}});
assert.ok(await page.evaluate(()=>getSelection().anchorOffset > 0));
await cell.click({button:'right'});
await page.getByRole('menuitem',{name:'Edit link',exact:true}).click();
assert.equal(await page.getByRole('dialog').count(),0);
assert.equal(await page.evaluate(()=>getSelection().toString()),theme === 'dark' ? 'docs/roadmap.md' : 'docs/new-roadmap.md');
await page.screenshot({path:path.join(output, 'editor-table-source-'+theme+'.png')});
await page.keyboard.type('docs/new-roadmap.md');
await page.keyboard.press('Enter');
assert.equal(await cell.locator('a').getAttribute('href'),'docs/new-roadmap.md');
if(theme === 'dark') {
await page.locator('.cm-line').filter({hasText:'Original'}).click();
await page.keyboard.press('Control+z');
assert.equal(await cell.locator('a').getAttribute('href'),'docs/roadmap.md');
await page.keyboard.press('Control+Shift+z');
assert.equal(await cell.locator('a').getAttribute('href'),'docs/new-roadmap.md');
}
await cell.locator('a').click({position:{x:22,y:8}});
const selection=await page.evaluate(()=>{const s=getSelection();return {offset:s.anchorOffset,length:s.anchorNode.textContent.length};});
assert.ok(selection.offset>0 && selection.offset<selection.length,JSON.stringify(selection));
await page.keyboard.type('X');
assert.ok((await cell.innerText()).includes('X'));
await page.keyboard.press('Escape');
const wiki=page.locator('.writer-table td').nth(1);
await wiki.click({button:'right'});
await page.getByRole('menuitem',{name:'Edit link',exact:true}).click();
assert.equal(await page.evaluate(()=>getSelection().toString()),theme==='dark'?'guide':'new-guide');
await page.keyboard.type('new-guide');
await page.keyboard.press('Enter');
assert.equal(await wiki.locator('a').getAttribute('href'),'new-guide');
}
await cell.locator('a').click({position:{x:22,y:8}});
const selection=await page.evaluate(()=>{const s=getSelection();return {offset:s.anchorOffset,length:s.anchorNode.textContent.length};});
assert.ok(selection.offset>0 && selection.offset<selection.length,JSON.stringify(selection));
await page.keyboard.type('X');
assert.ok((await cell.innerText()).includes('X'));
await page.keyboard.press('Escape');
const wiki=page.locator('.writer-table td').nth(1);
await wiki.click({button:'right'});
const multi=page.locator('.writer-table td').nth(2);
await multi.locator('a').nth(1).click({button:'right'});
await page.getByRole('menuitem',{name:'Edit link',exact:true}).click();
assert.equal(await page.evaluate(()=>getSelection().toString()),theme==='dark'?'guide':'new-guide');
await page.keyboard.type('new-guide');
assert.equal(await page.evaluate(()=>getSelection().toString()),'same.md');
await page.keyboard.type('second.md');
await page.keyboard.press('Enter');
assert.equal(await wiki.locator('a').getAttribute('href'),'new-guide');
}
const multi=page.locator('.writer-table td').nth(2);
await multi.locator('a').nth(1).click({button:'right'});
await page.getByRole('menuitem',{name:'Edit link',exact:true}).click();
assert.equal(await page.evaluate(()=>getSelection().toString()),'same.md');
await page.keyboard.type('second.md');
await page.keyboard.press('Enter');
assert.equal(await multi.locator('a').first().getAttribute('href'),'same.md');
assert.equal(await multi.locator('a').nth(1).getAttribute('href'),'second.md');
await page.getByRole('button',{name:'Hide outline',exact:true}).click();
await page.getByRole('button',{name:'Files',exact:true}).click();
await page.setViewportSize({width:620,height:700});
await page.waitForTimeout(250);
await page.locator('.table-add-row').scrollIntoViewIfNeeded();
await page.waitForTimeout(100);
await page.locator('.table-add-row').focus();
await page.locator('.rs-tooltip:popover-open').waitFor();
const rect=await page.locator('.rs-tooltip:popover-open').boundingBox();
assert.ok(rect.x>=0 && rect.x+rect.width<=620);
await page.screenshot({path:'.audit/editor-tooltip-narrow-focus.png'});
await page.keyboard.press('Escape');
assert.equal(await page.locator('.rs-tooltip:popover-open').count(),0);
assert.equal(await page.locator('.table-edit-help:visible').count(),0);
for (const mode of ['light','dark']) {
await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({theme:'default',mode}),mode);
await page.locator('.writer-table td').nth(1).hover();
assert.equal(await multi.locator('a').first().getAttribute('href'),'same.md');
assert.equal(await multi.locator('a').nth(1).getAttribute('href'),'second.md');
await page.getByRole('button',{name:'Hide outline',exact:true}).click();
await page.getByRole('button',{name:'Files',exact:true}).click();
await page.setViewportSize({width:620,height:700});
await page.waitForTimeout(250);
await page.locator('.table-add-row').scrollIntoViewIfNeeded();
await page.waitForTimeout(100);
await page.locator('.table-add-row').focus();
await page.locator('.rs-tooltip:popover-open').waitFor();
assert.match(await page.locator('.rs-tooltip:popover-open').innerText(),/Row 2, column 2/);
await page.screenshot({path:'.audit/editor-cell-tooltip-narrow-'+mode+'.png'});
const rect=await page.locator('.rs-tooltip:popover-open').boundingBox();
assert.ok(rect.x>=0 && rect.x+rect.width<=620);
await page.screenshot({path:path.join(output, 'editor-tooltip-narrow-focus.png')});
await page.keyboard.press('Escape');
await page.mouse.move(5,90);
}
assert.equal(await page.locator('.rs-tooltip:popover-open').count(),0);
assert.equal(await page.locator('.table-edit-help:visible').count(),0);
for (const mode of ['light','dark']) {
await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({theme:'default',mode}),mode);
await page.locator('.writer-table td').nth(1).hover();
await page.locator('.rs-tooltip:popover-open').waitFor();
assert.match(await page.locator('.rs-tooltip:popover-open').innerText(),/Row 2, column 2/);
await page.screenshot({path:path.join(output, 'editor-cell-tooltip-narrow-'+mode+'.png')});
await page.keyboard.press('Escape');
await page.mouse.move(5,90);
}
assert.deepEqual(errors,[]);
console.log('Editor link and tooltip checks passed');
} finally { await browser.close(); }
console.log('Editor link and tooltip checks passed');
}, { timeout: 15000 });
+59 -82
View File
@@ -1,71 +1,48 @@
import { createRequire } from "node:module";
// Link context menus in the Writer, Reading, IDE, and table cells: browser and workspace actions, Edit link with undo, keyboard use, narrow windows, bookmarks, rename, and move.
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 page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(15000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await mkdir(".audit", { recursive: true });
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\tab-menu-workspace";
const files = new Map(["a.md", "b.md", "c.md", "d.md"].map(name => [name, `# ${name}\n\nOriginal text.\n\n\`\`\`js\nconst answer = 42;\n\`\`\`\n\n| Name | Value |\n| --- | --- |\n| Alpha | One |\n`]));
files.set("a.md", "# Links\n\nSelected reading text.\n\n[Web label](https://example.com/path)\n\n[[b.md|Workspace note]]\n\n| Link | Note |\n| --- | --- |\n| [Cell web](https://example.com/cell) | [[b.md\\|Cell note]] |\n");
files.set("sample.txt", "const answer = 42;\n");
window.tabMenuTest = { prompts: [], answer: "Cancel", revealed: null, clipboard: null, opened: null, app: null, windows: [] };
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { window.tabMenuTest.clipboard = text; } } });
window.tabMenuTest.files = files;
let sequence = 0;
const callbacks = new Map(), listeners = new Map();
window.spellingTest = { commands: [], emit: payload => callbacks.get(listeners.get("spelling-menu"))?.({ event: "spelling-menu", id: 1, payload }) };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { callbacks.set(++sequence, callback); return sequence; }, unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === "plugin:event|listen") { listeners.set(args.event, args.handler); return ++sequence; }
if (command === "plugin:event|unlisten") return;
if (command.startsWith("spelling_menu_")) { window.spellingTest.commands.push({ method: command, ...args }); return; }
if (command === "spelling_suggestions") return { language: "en-US", words: ["Corrected"], misspelled: args.word === "Original" };
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "tab-menu-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_list") return [...(!args.rel ? [{ name: "notes", rel_path: "notes", kind: "folder" }] : []), ...[...files.keys()].filter(path => path.split("/").slice(0, -1).join("/") === (args.rel || "")).map(path => ({ name: path.split("/").at(-1), rel_path: path, kind: "file" }))];
if (command === "workspace_search") { window.tabMenuTest.searched = args.query; return []; }
if (command === "plugin:opener|open_url") { window.tabMenuTest.opened = args.url; return; }
if (command === "workspace_open_default") { window.tabMenuTest.app = args.rel; return; }
if (command === "workspace_open_window") { window.tabMenuTest.windows.push(args); return; }
if (command === "workspace_write") { files.set(args.rel, args.contents); return; }
if (command === "workspace_rename") { files.set(args.to, files.get(args.from)); files.delete(args.from); return; }
if (command === "workspace_abs_path") return `${root}\\${args.rel}`;
if (command === "workspace_reveal") { window.tabMenuTest.revealed = args.rel; return; }
if (command === "plugin:dialog|message") { window.tabMenuTest.prompts.push(args.message); return window.tabMenuTest.answer; }
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
const menu = name => page.getByRole('menu', { name, exact: true });
const item = name => page.getByRole('menuitem', { name, exact: true });
const output = '.audit/editor-link-menus';
await mkdir(output, { recursive: true });
const dismiss = async () => { await page.keyboard.press('Escape'); await page.locator('.rs-menu').waitFor({ state: 'detached' }); };
const report = [];
async function writerMenu(target='Web label') {
await page.locator('.cm-content').getByText('Selected reading text.', { exact: true }).click();
await page.locator('.cm-content').getByText(target, { exact: true }).click({ button: 'right' });
await menu('Markdown text actions').waitFor();
}
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await runSmoke("links/linkMenus", async ({ page }) => {
const output = await outputDir("links/linkMenus");
await mockTauri(page, {
commands: test => {
const note = name => `# ${name}\n\nOriginal text.\n\n\`\`\`js\nconst answer = 42;\n\`\`\`\n\n| Name | Value |\n| --- | --- |\n| Alpha | One |\n`;
const files = Object.fromEntries(["b.md", "c.md", "d.md"].map(name => [name, note(name)]));
// Enter in a table cell moves to the next row, and adds one after the last row (src/lib/editor/tableControls.ts:278-285).
// The second row keeps each link edit a single undo step.
files["a.md"] = "# Links\n\nSelected reading text.\n\n[Web label](https://example.com/path)\n\n[[b.md|Workspace note]]\n\n| Link | Note |\n| --- | --- |\n| [Cell web](https://example.com/cell) | [[b.md\\|Cell note]] |\n| Plain | Row |\n";
files["sample.txt"] = "const answer = 42;\n";
const workspace = test.workspace({ root: "C:\\tab-menu-workspace", folders: ["notes"], files });
Object.assign(test, { files: workspace.files, clipboard: null, opened: null, app: null, revealed: null, searched: null, windows: [] });
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { test.clipboard = text; } } });
return {
...workspace,
workspace_search: args => { test.searched = args.query; return []; },
workspace_rename: args => { workspace.files.set(args.to, workspace.files.get(args.from)); workspace.files.delete(args.from); },
workspace_reveal: args => { test.revealed = args.rel; },
workspace_open_default: args => { test.app = args.rel; },
workspace_open_window: args => { test.windows.push(args); },
"plugin:opener|open_url": args => { test.opened = args.url; },
spelling_menu_install: () => {},
};
},
});
const menu = name => page.getByRole('menu', { name, exact: true });
const item = name => page.getByRole('menuitem', { name, exact: true });
const dismiss = async () => { await page.keyboard.press('Escape'); await page.locator('.rs-menu').waitFor({ state: 'detached' }); };
const report = [];
async function writerMenu(target='Web label') {
await page.locator('.cm-content').getByText('Selected reading text.', { exact: true }).click();
await page.locator('.cm-content').getByText(target, { exact: true }).click({ button: 'right' });
await menu('Markdown text actions').waitFor();
}
await page.goto(smokeUrl);
await page.locator('[data-tree-rel="a.md"]').click();
await page.locator('.cm-content').waitFor();
await page.evaluate(async () => {
const { pluginHost } = await import('/src/lib/plugins/registry.ts');
pluginHost.register('link-smoke', 'browser', { open: async target => { window.tabMenuTest.browser = target; return true; }, mountSettings: () => () => {}, mountBookmarks: () => () => {} });
pluginHost.register('link-smoke', 'browser', { open: async target => { window.__TEST__.browser = target; return true; }, mountSettings: () => () => {}, mountBookmarks: () => () => {} });
});
for (const theme of ['dark', 'light']) {
await page.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({theme:'default', mode}); }, theme);
@@ -73,11 +50,11 @@ try {
for (const label of ['Open link in app browser', 'Open link in default browser', 'Copy URL', 'Edit link']) assert.equal(await item(label).count(), 1);
await page.screenshot({ path: `${output}/writer-link-${theme}.png` });
await item('Copy URL').click();
await page.waitForFunction(() => window.tabMenuTest.clipboard === 'https://example.com/path');
await page.waitForFunction(() => window.__TEST__.clipboard === 'https://example.com/path');
await writerMenu(); await item('Open link in default browser').click();
await page.waitForFunction(() => window.tabMenuTest.opened === 'https://example.com/path');
await page.waitForFunction(() => window.__TEST__.opened === 'https://example.com/path');
await writerMenu(); await item('Open link in app browser').click();
await page.waitForFunction(() => window.tabMenuTest.browser === 'https://example.com/path');
await page.waitForFunction(() => window.__TEST__.browser === 'https://example.com/path');
await writerMenu(); await item('Edit link').click();
assert.equal(await page.evaluate(async () => { const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js'); const v = EditorView.findFromDOM(document.querySelector('.cm-content')); return v.state.sliceDoc(v.state.selection.main.from, v.state.selection.main.to); }), 'https://example.com/path');
await page.screenshot({ path: `${output}/edit-url-${theme}.png` });
@@ -98,8 +75,8 @@ try {
await page.getByRole('button',{name:'Files',exact:true}).click(); await page.getByRole('button',{name:'Show outline',exact:true}).click();
await writerMenu('Workspace note');
await item('Copy path').focus(); await page.keyboard.press('ArrowRight'); await item('Workspace path').click();
await page.waitForFunction(() => window.tabMenuTest.clipboard === 'b.md');
await writerMenu('Workspace note'); await item('Show in system explorer').click(); await page.waitForFunction(() => window.tabMenuTest.revealed === 'b.md');
await page.waitForFunction(() => window.__TEST__.clipboard === 'b.md');
await writerMenu('Workspace note'); await item('Show in system explorer').click(); await page.waitForFunction(() => window.__TEST__.revealed === 'b.md');
await writerMenu('Workspace note'); await item('Reveal file in navigation').click();
await page.waitForFunction(() => document.activeElement?.getAttribute('data-tree-rel') === 'b.md');
await page.getByRole('group', { name: 'Document view', exact: true }).hover(); await page.getByRole('button', { name:'Read', exact:true }).click();
@@ -110,13 +87,13 @@ try {
await page.keyboard.press('End'); assert.match(await page.evaluate(() => document.activeElement.textContent), /^Search for/);
await page.screenshot({ path: `${output}/reading-selection-${theme}.png` });
await page.keyboard.press('Home'); await page.keyboard.press('Enter');
await page.waitForFunction(() => window.tabMenuTest.clipboard === 'Selected reading text.');
await page.waitForFunction(() => window.__TEST__.clipboard === 'Selected reading text.');
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem', {name:/^Search for/}).click();
await page.waitForFunction(() => window.tabMenuTest.searched === 'Selected reading text.');
await page.waitForFunction(() => window.__TEST__.searched === 'Selected reading text.');
await page.evaluate(() => getSelection().removeAllRanges());
await reading.getByRole('link',{name:'Web label'}).click({button:'right'});
await item('Copy URL').click(); await page.waitForFunction(() => window.tabMenuTest.clipboard === 'https://example.com/path');
await item('Copy URL').click(); await page.waitForFunction(() => window.__TEST__.clipboard === 'https://example.com/path');
await page.getByRole('button', { name: 'Search', exact: true }).click();
await page.getByRole('button', { name: 'Hide outline', exact: true }).click();
await page.setViewportSize({ width: 560, height: 620 });
@@ -143,7 +120,7 @@ try {
await item('Edit link').waitFor();
await page.screenshot({path:`${output}/table-link-${theme}.png`});
await item('Copy URL').click();
await page.waitForFunction(() => window.tabMenuTest.clipboard === 'https://example.com/cell');
await page.waitForFunction(() => window.__TEST__.clipboard === 'https://example.com/cell');
await cellLink.click({button:'right'}); await item('Edit link').click();
const sourceCell = page.locator('.writer-table .is-source-editing .writer-cell-editor');
await sourceCell.waitFor();
@@ -182,28 +159,28 @@ try {
report.push({theme,passed:['Writer and IDE edit URL selection','browser destinations','workspace file actions','Reader copy/search/link actions','inline table web/wiki link edits and undo','table source Escape and keyboard menu','keyboard focus return','narrow viewport'],nativeDesktop:'not tested'});
}
await writerMenu('Workspace note'); await item('Open in new window').click();
await page.waitForFunction(() => window.tabMenuTest.windows.length === 1);
await page.evaluate(() => { const {transfer}=window.tabMenuTest.windows[0]; dispatchEvent(new StorageEvent('storage',{key:`runestone.tab-transfer.${transfer}.accepted`,newValue:'true'})); });
await page.waitForFunction(() => window.__TEST__.windows.length === 1);
await page.evaluate(() => { const {transfer}=window.__TEST__.windows[0]; dispatchEvent(new StorageEvent('storage',{key:`runestone.tab-transfer.${transfer}.accepted`,newValue:'true'})); });
assert.equal(await page.getByRole('tab',{name:/b.md/}).count(),1,'Opening a linked document in a new window keeps the source tab');
await page.locator('[data-tree-rel="a.md"]').click();
await writerMenu('Workspace note'); await item('Bookmark').click();
await page.waitForFunction(() => JSON.parse(window.tabMenuTest.files.get('.runestone/marks.json') || '{}').bookmarks?.includes('b.md'));
await page.waitForFunction(() => JSON.parse(window.__TEST__.files.get('.runestone/marks.json') || '{}').bookmarks?.includes('b.md'));
await writerMenu('Workspace note'); await item('Copy path').focus(); await page.keyboard.press('ArrowRight'); await item('System path').click();
await page.waitForFunction(() => window.tabMenuTest.clipboard.endsWith('\\b.md'));
await page.waitForFunction(() => window.__TEST__.clipboard.endsWith('\\b.md'));
await page.getByRole('group', { name: 'Document view', exact: true }).hover(); await page.getByRole('button', { name:'Read', exact:true }).click();
const readerWorkspaceMenu = async () => { await page.locator('.reading').getByRole('link',{name:'Workspace note'}).click({button:'right'}); };
await readerWorkspaceMenu(); await item('Open in default app').click();
await page.waitForFunction(() => window.tabMenuTest.app === 'b.md');
await page.waitForFunction(() => window.__TEST__.app === 'b.md');
await readerWorkspaceMenu(); await item('Rename…').click();
await page.getByLabel('New file name').fill('renamed.md'); await page.getByRole('button',{name:'Continue',exact:true}).click();
await page.waitForFunction(() => window.tabMenuTest.files.has('renamed.md') && !window.tabMenuTest.files.has('b.md'));
assert.equal(await page.evaluate(() => JSON.parse(window.tabMenuTest.files.get('.runestone/marks.json')).bookmarks.includes('renamed.md')),true);
await page.waitForFunction(() => window.__TEST__.files.has('renamed.md') && !window.__TEST__.files.has('b.md'));
assert.equal(await page.evaluate(() => JSON.parse(window.__TEST__.files.get('.runestone/marks.json')).bookmarks.includes('renamed.md')),true);
await page.getByRole('group', { name: 'Document view', exact: true }).hover(); await page.getByRole('button', { name:'Edit', exact:true }).click();
await page.locator('.cm-content').evaluate(async node => { const {EditorView}=await import('/node_modules/@codemirror/view/dist/index.js'); const view=EditorView.findFromDOM(node); const from=view.state.doc.toString().indexOf('b.md'); view.dispatch({changes:{from,to:from+4,insert:'renamed.md'}}); });
await page.getByRole('group', { name: 'Document view', exact: true }).hover(); await page.getByRole('button', { name:'Read', exact:true }).click();
await readerWorkspaceMenu(); await item('Move file to…').click();
await page.getByLabel('Move file to (workspace path, including filename)').fill('notes/moved.md'); await page.getByRole('button',{name:'Continue',exact:true}).click();
await page.waitForFunction(() => window.tabMenuTest.files.has('notes/moved.md') && !window.tabMenuTest.files.has('renamed.md'));
assert.equal(await page.evaluate(() => JSON.parse(window.tabMenuTest.files.get('.runestone/marks.json')).bookmarks.includes('notes/moved.md')),true);
assert.deepEqual(errors,[]); console.log(JSON.stringify(report,null,2));
} catch(error) { await page.screenshot({path:`${output}/failure.png`}); console.log(await page.locator('.rs-menu').allTextContents()); throw error; } finally { await browser.close(); }
await page.waitForFunction(() => window.__TEST__.files.has('notes/moved.md') && !window.__TEST__.files.has('renamed.md'));
assert.equal(await page.evaluate(() => JSON.parse(window.__TEST__.files.get('.runestone/marks.json')).bookmarks.includes('notes/moved.md')),true);
console.log(JSON.stringify(report,null,2));
}, { timeout: 15000 });
+36 -66
View File
@@ -1,66 +1,40 @@
import { createRequire } from "node:module";
// Writer previews: ordered-list spacing around fenced code, and local, wiki, and table-source links that open document tabs, in both themes at wide and narrow widths.
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 page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(15000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await mkdir(".audit", { recursive: true });
await page.addInitScript(() => {
localStorage.clear();
window.isTauri = true;
const root = "C:\\tab-menu-workspace";
const files = new Map([["a.md", "# Links\n\nOriginal text.\n"]]);
window.tabMenuTest = { files, calls: [], prompts: [], answer: "Cancel", revealed: null, clipboard: null };
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { window.tabMenuTest.clipboard = text; } } });
let sequence = 0;
const callbacks = new Map(), listeners = new Map();
window.spellingTest = { commands: [], emit: payload => callbacks.get(listeners.get("spelling-menu"))?.({ event: "spelling-menu", id: 1, payload }) };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { callbacks.set(++sequence, callback); return sequence; }, unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
window.tabMenuTest.calls.push({ command, args });
if (command === "plugin:event|listen") { listeners.set(args.event, args.handler); return ++sequence; }
if (command === "plugin:event|unlisten") return;
if (command === "plugin:window|is_maximized") return false;
if (command === "plugins_snapshot") return { root: "C:/plugins", plugins: [] };
if (command.startsWith("spelling_menu_")) { window.spellingTest.commands.push({ method: command, ...args }); return; }
if (command === "spelling_suggestions") return { language: "en-US", words: [], misspelled: false };
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "tab-menu-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_list") return args.rel ? [] : [{ name: "notes", rel_path: "notes", kind: "folder" }, ...[...files.keys()].map(name => ({ name, rel_path: name, kind: "file" }))];
if (command === "workspace_search") return [];
if (command === "workspace_write") { files.set(args.rel, args.contents); return; }
if (command === "workspace_rename") { files.set(args.to, files.get(args.from)); files.delete(args.from); return; }
if (command === "workspace_abs_path") return `${root}\\${args.rel}`;
if (command === "workspace_reveal") { window.tabMenuTest.revealed = args.rel; return; }
if (command === "plugin:dialog|message") { window.tabMenuTest.prompts.push(args.message); return window.tabMenuTest.answer; }
return null;
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("links/previewLinks", async ({ browser, page }) => {
const output = await outputDir("links/previewLinks");
// Every load starts without saved tabs or settings.
await page.addInitScript(() => localStorage.clear());
// Unknown commands return null, as the original mock did.
await mockTauri(page, {
strict: false,
commands: test => {
const workspace = test.workspace({ root: "C:\\tab-menu-workspace", folders: ["notes"], files: { "a.md": "# Links\n\nOriginal text.\n" } });
test.files = workspace.files;
return {
...workspace,
"plugin:window|is_maximized": () => false,
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
spelling_suggestions: () => ({ language: "en-US", words: [], misspelled: false }),
"plugin:dialog|message": () => "Cancel",
};
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
});
// The app stays at its own root URL; compare with the normalized form.
const appUrl = new URL(smokeUrl).href;
const output = '.audit/editor-preview-links';
await mkdir(output, { recursive: true });
const installation = '# Installation\n\nOutside the list.\n\n1. Get `RuneStone_<version>_amd64.deb` and its `SHA256SUMS`.\n2. Save both files to Downloads and open Terminal in that folder.\n3. Verify the download, then install the package:\n\n ```bash\n sha256sum --check SHA256SUMS\n sudo apt install ./RuneStone_0.1.42_amd64.deb\n ```\n\n Stop if verification fails.\n4. Open RuneStone from your applications menu.\n5. Open a workspace outside the application folder.\n\nAfter the list.\n';
async function resetFile(text) {
await page.locator('.cm-content').evaluate(async (node, text) => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
const view = EditorView.findFromDOM(node);
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: text }, selection: { anchor: 0 } });
}, text);
}
try {
const installation = '# Installation\n\nOutside the list.\n\n1. Get `RuneStone_<version>_amd64.deb` and its `SHA256SUMS`.\n2. Save both files to Downloads and open Terminal in that folder.\n3. Verify the download, then install the package:\n\n ```bash\n sha256sum --check SHA256SUMS\n sudo apt install ./RuneStone_0.1.42_amd64.deb\n ```\n\n Stop if verification fails.\n4. Open RuneStone from your applications menu.\n5. Open a workspace outside the application folder.\n\nAfter the list.\n';
async function resetFile(text) {
await page.locator('.cm-content').evaluate(async (node, text) => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
const view = EditorView.findFromDOM(node);
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: text }, selection: { anchor: 0 } });
}, text);
}
for (const theme of ['dark', 'light']) for (const width of [1440, 620]) {
await page.setViewportSize({ width, height: 1000 });
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await page.goto(smokeUrl);
await page.locator('[data-tree-rel="a.md"]').click();
await page.locator('.cm-content').waitFor();
await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({ theme:'default', mode }), theme);
@@ -90,14 +64,14 @@ try {
await page.screenshot({ path:`${output}/ordered-list-${theme}-${width}.png` });
const fixture = '# Links\n\nOutside.\n\n| Task | Link |\n| --- | --- |\n| Plugin setup | [Plugin installation](<docs/plugins.md#install-a-plugin>) |\n| Wiki | [[docs/plugins.md\\|Plugin guide]] |\n';
await resetFile(fixture);
await page.evaluate(() => window.tabMenuTest.files.set('docs/plugins.md', '# Plugins\n\n## Install a plugin\n\nLocal plugin instructions.\n'));
await page.evaluate(() => window.__TEST__.files.set('docs/plugins.md', '# Plugins\n\n## Install a plugin\n\nLocal plugin instructions.\n'));
const localLink = page.locator('.writer-table a').filter({ hasText:'Plugin installation' });
await localLink.click({ modifiers:[width === 620 ? 'Meta' : 'Control'] });
await page.getByRole('tab', { name:'plugins.md', exact:true }).waitFor();
assert.match(await page.locator('.cm-content').innerText(), /Local plugin instructions/);
assert.equal(page.url(), process.env.SMOKE_URL || 'http://127.0.0.1:1420/');
assert.equal(page.url(), appUrl);
assert.equal(browser.contexts().flatMap(context => context.pages()).length, 1, 'Local link cannot open a browser tab');
assert.equal(await page.evaluate(() => window.tabMenuTest.calls.filter(call => /open_url|open_path/.test(call.command)).length), 0);
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(call => /open_url|open_path/.test(call.command)).length), 0);
await page.screenshot({ path:`${output}/local-link-tab-${theme}-${width}.png` });
await page.getByRole('tab', { name:'a.md', exact:true }).click();
const wiki = page.locator('.writer-table a').filter({ hasText:'Plugin guide' });
@@ -113,9 +87,5 @@ try {
await page.getByRole('tab', { name:'plugins.md', exact:true }).waitFor();
assert.match(await page.locator('.cm-content').innerText(), /Local plugin instructions/);
}
assert.deepEqual(errors, []);
console.log('PASS: nested fenced-code list spacing, preserved code newlines, rendered/table-source/wiki local links open document tabs, duplicate target focus, both themes, narrow and wide windows. Native WebView acceptance remains open.');
} catch (error) {
await page.screenshot({ path:`${output}/failure.png` });
throw error;
} finally { await browser.close(); }
}, { timeout: 15000 });
+66 -96
View File
@@ -1,101 +1,73 @@
import { createRequire } from "node:module";
// Section links: heading anchors in the Writer, Reading, Split, and IDE views, an encoded duplicate heading in another file, a missing section, and folded headings, in both themes.
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 page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(15000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await mkdir(".audit", { recursive: true });
await page.addInitScript(() => {
localStorage.clear();
window.isTauri = true;
const root = "C:\\tab-menu-workspace";
const files = new Map([["a.md", "# Links\n\nOriginal text.\n"]]);
window.tabMenuTest = { files, calls: [], prompts: [], answer: "Cancel", revealed: null, clipboard: null };
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { window.tabMenuTest.clipboard = text; } } });
let sequence = 0;
const callbacks = new Map(), listeners = new Map();
window.spellingTest = { commands: [], emit: payload => callbacks.get(listeners.get("spelling-menu"))?.({ event: "spelling-menu", id: 1, payload }) };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { callbacks.set(++sequence, callback); return sequence; }, unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
window.tabMenuTest.calls.push({ command, args });
if (command === "plugin:event|listen") { listeners.set(args.event, args.handler); return ++sequence; }
if (command === "plugin:event|unlisten") return;
if (command === "plugin:window|is_maximized") return false;
if (command === "plugins_snapshot") return { root: "C:/plugins", plugins: [] };
if (command.startsWith("spelling_menu_")) { window.spellingTest.commands.push({ method: command, ...args }); return; }
if (command === "spelling_suggestions") return { language: "en-US", words: [], misspelled: false };
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "tab-menu-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_list") return args.rel ? [] : [{ name: "notes", rel_path: "notes", kind: "folder" }, ...[...files.keys()].map(name => ({ name, rel_path: name, kind: "file" }))];
if (command === "workspace_search") return [];
if (command === "workspace_write") { files.set(args.rel, args.contents); return; }
if (command === "workspace_rename") { files.set(args.to, files.get(args.from)); files.delete(args.from); return; }
if (command === "workspace_abs_path") return `${root}\\${args.rel}`;
if (command === "workspace_reveal") { window.tabMenuTest.revealed = args.rel; return; }
if (command === "plugin:dialog|message") { window.tabMenuTest.prompts.push(args.message); return window.tabMenuTest.answer; }
return null;
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("links/sectionLinks", async ({ page }) => {
const output = await outputDir("links/sectionLinks");
// Every load starts without saved tabs or settings.
await page.addInitScript(() => localStorage.clear());
// Unknown commands return null, as the original mock did.
await mockTauri(page, {
strict: false,
commands: test => {
const workspace = test.workspace({ root: "C:\\tab-menu-workspace", folders: ["notes"], files: { "a.md": "# Links\n\nOriginal text.\n" } });
test.files = workspace.files;
return {
...workspace,
"plugin:window|is_maximized": () => false,
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
spelling_suggestions: () => ({ language: "en-US", words: [], misspelled: false }),
"plugin:dialog|message": () => "Cancel",
};
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const output = '.audit/section-links';
await mkdir(output, { recursive: true });
const url = process.env.SMOKE_URL || 'http://127.0.0.1:1420/';
const filler = Array.from({ length: 50 }, (_, i) => `Paragraph ${i}. Some text before the destination.\n`).join('\n');
const source = '# Install and start\n\nChoose [Windows setup](#windows-installer), [macOS setup](#macos-installer-apple-silicon), or [Linux setup](#linux-intelamd-64-bit).\n\n[Other document](other.md#caf%C3%A9-setup-1)\n\n[Missing section](#no-such-section)\n\n' + filler + '\n## Windows installer\n\nWindows instructions.\n\n' + filler + '\n## macOS installer (Apple Silicon)\n\nMac instructions.\n\n' + filler + '\n## Linux (Intel/AMD 64-bit)\n\nLinux instructions.\n';
const other = '# Other\n\n## Café setup\n\nFirst.\n\n' + filler + '\n## Café setup\n\nSecond.\n';
async function choose(group, value) {
const control = page.getByRole('group', { name: group, exact: true });
await control.hover();
await control.locator(`[data-value="${value}"]`).click();
}
async function writerJump(label, line) {
const link = page.locator('.cm-content .writer-link').filter({ hasText: label }).first();
await link.click({ modifiers: ['Control'] });
await page.waitForFunction(async expected => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
const node = document.querySelector('.cm-content');
const view = node ? EditorView.findFromDOM(node) : null;
return view && view.state.doc.lineAt(view.state.selection.main.head).number === expected;
}, line);
}
async function jumpLine(label) { return source.slice(0, source.indexOf(label)).split('\n').length; }
async function top() {
await page.locator('.cm-content').evaluate(async node => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
const view = EditorView.findFromDOM(node);
view.dispatch({ selection:{ anchor:0 }, effects:EditorView.scrollIntoView(0, { y:'start' }) });
view.scrollDOM.scrollTop = 0;
});
}
async function readerJump(label, text) {
await page.locator('.reading a').filter({ hasText:label }).click();
const heading = page.locator('.reading h2').filter({ hasText:text }).first();
await heading.waitFor();
await page.waitForFunction(text => {
const heading = [...document.querySelectorAll('.reading h2')].find(node => node.textContent === text);
if (!heading) return false;
const rect = heading.getBoundingClientRect(), box = heading.closest('.md-page').getBoundingClientRect();
return !heading.hidden && rect.top >= box.top && rect.bottom <= box.bottom;
}, text);
}
try {
// The app stays at its own root URL; use the normalized form.
const url = new URL(smokeUrl).href;
const filler = Array.from({ length: 50 }, (_, i) => `Paragraph ${i}. Some text before the destination.\n`).join('\n');
const source = '# Install and start\n\nChoose [Windows setup](#windows-installer), [macOS setup](#macos-installer-apple-silicon), or [Linux setup](#linux-intelamd-64-bit).\n\n[Other document](other.md#caf%C3%A9-setup-1)\n\n[Missing section](#no-such-section)\n\n' + filler + '\n## Windows installer\n\nWindows instructions.\n\n' + filler + '\n## macOS installer (Apple Silicon)\n\nMac instructions.\n\n' + filler + '\n## Linux (Intel/AMD 64-bit)\n\nLinux instructions.\n';
const other = '# Other\n\n## Café setup\n\nFirst.\n\n' + filler + '\n## Café setup\n\nSecond.\n';
async function choose(group, value) {
const control = page.getByRole('group', { name: group, exact: true });
await control.hover();
await control.locator(`[data-value="${value}"]`).click();
}
async function writerJump(label, line) {
const link = page.locator('.cm-content .writer-link').filter({ hasText: label }).first();
await link.click({ modifiers: ['Control'] });
await page.waitForFunction(async expected => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
const node = document.querySelector('.cm-content');
const view = node ? EditorView.findFromDOM(node) : null;
return view && view.state.doc.lineAt(view.state.selection.main.head).number === expected;
}, line);
}
async function jumpLine(label) { return source.slice(0, source.indexOf(label)).split('\n').length; }
async function top() {
await page.locator('.cm-content').evaluate(async node => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
const view = EditorView.findFromDOM(node);
view.dispatch({ selection:{ anchor:0 }, effects:EditorView.scrollIntoView(0, { y:'start' }) });
view.scrollDOM.scrollTop = 0;
});
}
async function readerJump(label, text) {
await page.locator('.reading a').filter({ hasText:label }).click();
const heading = page.locator('.reading h2').filter({ hasText:text }).first();
await heading.waitFor();
await page.waitForFunction(text => {
const heading = [...document.querySelectorAll('.reading h2')].find(node => node.textContent === text);
if (!heading) return false;
const rect = heading.getBoundingClientRect(), box = heading.closest('.md-page').getBoundingClientRect();
return !heading.hidden && rect.top >= box.top && rect.bottom <= box.bottom;
}, text);
}
for (const theme of ['dark', 'light']) for (const width of [1440, 620]) {
await page.setViewportSize({ width, height:1000 });
await page.goto(url);
await page.evaluate(({ source, other }) => {
window.tabMenuTest.files.set('a.md', source);
window.tabMenuTest.files.set('other.md', other);
window.__TEST__.files.set('a.md', source);
window.__TEST__.files.set('other.md', other);
}, { source, other });
await page.locator('[data-tree-rel="a.md"]').click();
await page.locator('.cm-content').waitFor();
@@ -151,12 +123,12 @@ try {
});
await page.screenshot({ path:`${output}/ide-${theme}-${width}.png` });
assert.equal(page.url(), url);
assert.equal(await page.evaluate(() => window.tabMenuTest.files.get('a.md')), source);
assert.equal(await page.evaluate(() => window.__TEST__.files.get('a.md')), source);
}
await page.goto(url);
const folded = 'Start.\n\n[Jump to nested](#nested)\n\n[[#Nested|Wiki section]]\n\n# Parent\n\n' + filler + '\n## Nested\n\nDestination text.\n';
await page.evaluate(text => window.tabMenuTest.files.set('a.md', text), folded);
await page.evaluate(text => window.__TEST__.files.set('a.md', text), folded);
await page.locator('[data-tree-rel="a.md"]').click();
await page.locator('.cm-content').waitFor();
await page.getByRole('button', { name:'Collapse Parent', exact:true }).click();
@@ -169,7 +141,5 @@ try {
await readerJump('Jump to nested', 'Nested');
await page.screenshot({ path:`${output}/folded-section-revealed.png` });
assert.deepEqual(errors, []);
console.log('Section links passed: three reported headings, cross-file encoded duplicate, four views, both themes, wide/narrow.');
} finally { await browser.close(); }
}, { timeout: 15000 });
+41 -97
View File
@@ -1,97 +1,43 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
// Workspace links: wiki resolution across folders, backlink navigation, live edits, discarded drafts, created, moved, and deleted notes, and the duplicate-name guard.
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_rename") {
if (window.__TEST__.delayRename) await new Promise(resolve => { window.__TEST__.resumeRename = resolve; });
if (!files.has(args.from)) throw new Error("File is missing");
if (files.has(args.to)) throw new Error("A file with that name already exists");
files.set(args.to, files.get(args.from)); files.delete(args.from); return;
}
if (command === "workspace_search") return [];
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return window.__TEST__.answer ?? "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await page.addInitScript(() => {
localStorage.setItem('runestone.settings',JSON.stringify({autosaveEnabled:false}));
const {files}=window.__TEST__; files.clear();
files.set('projects/source.md','# Source\n\n[[Target]]\n');
files.set('archive/deep/Target.md','# Target\n');
files.set('other.md','# Other\n\n[Target](archive/deep/Target.md)\n');
});
async function openNote(name) {
await page.keyboard.press('Control+p');
await page.getByRole('textbox',{name:'Find a file'}).fill(name);
await page.getByRole('dialog').getByRole('button').filter({hasText:name}).first().click();
await page.getByRole('textbox',{name:'Writing editor',exact:true}).waitFor();
}
const backlink=path=>page.getByRole('button',{name:'Open '+path+', line 3',exact:true});
try {
await page.goto(process.env.SMOKE_URL||'http://127.0.0.1:1420');
await runSmoke("links/workspaceLinks", async ({ page }) => {
const output = await outputDir("links/workspaceLinks");
await mockTauri(page, {
commands: test => {
const workspace = test.workspace({
root: "C:\\smoke-workspace",
writeEvents: true,
files: {
"projects/source.md": "# Source\n\n[[Target]]\n",
"archive/deep/Target.md": "# Target\n",
"other.md": "# Other\n\n[Target](archive/deep/Target.md)\n",
},
});
const { files } = workspace;
Object.assign(test, { files, root: workspace.root });
return {
...workspace,
workspace_write: args => {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
return workspace.workspace_write(args);
},
workspace_search: () => [],
"plugin:dialog|message": () => test.answer ?? "Cancel",
};
},
});
await page.addInitScript(() => localStorage.setItem('runestone.settings',JSON.stringify({autosaveEnabled:false})));
async function openNote(name) {
await page.keyboard.press('Control+p');
await page.getByRole('textbox',{name:'Find a file'}).fill(name);
await page.getByRole('dialog').getByRole('button').filter({hasText:name}).first().click();
await page.getByRole('textbox',{name:'Writing editor',exact:true}).waitFor();
}
const backlink=path=>page.getByRole('button',{name:'Open '+path+', line 3',exact:true});
await page.goto(smokeUrl);
await page.getByText('smoke-workspace',{exact:true}).waitFor();
await openNote('projects/source.md');
await page.locator('.cm-content .writer-link').filter({hasText:'Target'}).click({modifiers:['Control']});
@@ -99,7 +45,7 @@ try {
await backlink('projects/source.md').waitFor();
await backlink('other.md').waitFor();
assert.equal(await page.getByRole('tab',{name:'source.md',exact:true}).count(),1);
await page.screenshot({path:'.audit/workspace-links-dark.png'});
await page.screenshot({path:path.join(output, 'workspace-links-dark.png')});
await backlink('projects/source.md').click();
await page.waitForFunction(()=>document.querySelector('.breadcrumb')?.textContent==='projects/source.md');
const writer=page.getByRole('textbox',{name:'Writing editor',exact:true});
@@ -147,8 +93,6 @@ try {
await page.setViewportSize({width:620,height:850});
await page.evaluate(()=>{document.documentElement.dataset.theme='light';});
await page.getByRole('tab',{name:'Target.md',exact:true}).click();
await page.screenshot({path:'.audit/workspace-links-narrow.png'});
assert.deepEqual(errors,[]);
await page.screenshot({path:path.join(output, 'workspace-links-narrow.png')});
console.log('Workspace link integration passed: workspace wiki resolution, new tabs, backlinks navigation, live edits, discarded drafts, creation, move, deletion and duplicate guard.');
}finally{await browser.close();}
});
+56 -76
View File
@@ -1,70 +1,51 @@
import { createRequire } from "node:module";
// Shared menu design: styles, themes, icons, disabled rows, focus return, submenus, spelling menus, scrolling, and viewport edges.
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 page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(15000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await mkdir(".audit", { recursive: true });
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\tab-menu-workspace";
const files = new Map(["a.md", "b.md", "c.md", "d.md"].map(name => [name, `# ${name}\n\nOriginal text.\n\n| Name | Value |\n| --- | --- |\n| Alpha | One |\n`]));
window.tabMenuTest = { prompts: [], answer: "Cancel", revealed: null, clipboard: null };
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { window.tabMenuTest.clipboard = text; } } });
let sequence = 0;
const callbacks = new Map(), listeners = new Map();
window.spellingTest = { commands: [], emit: payload => callbacks.get(listeners.get("spelling-menu"))?.({ event: "spelling-menu", id: 1, payload }) };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { callbacks.set(++sequence, callback); return sequence; }, unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === "plugin:event|listen") { listeners.set(args.event, args.handler); return ++sequence; }
if (command === "plugin:event|unlisten") return;
if (command.startsWith("spelling_menu_")) { window.spellingTest.commands.push({ method: command, ...args }); return; }
if (command === "spelling_suggestions") {
if (window.spellingTest.delay) return new Promise(resolve => window.spellingTest.resolve = resolve);
return { language: "en-US", words: [], misspelled: false };
}
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "tab-menu-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_list") return args.rel ? [] : [{ name: "notes", rel_path: "notes", kind: "folder" }, ...[...files.keys()].map(name => ({ name, rel_path: name, kind: "file" }))];
if (command === "workspace_search") return [];
if (command === "workspace_write") throw new Error("Keep unsaved edits for the close test");
if (command === "workspace_rename") { files.set(args.to, files.get(args.from)); files.delete(args.from); return; }
if (command === "workspace_abs_path") return `${root}\\${args.rel}`;
if (command === "workspace_reveal") { window.tabMenuTest.revealed = args.rel; return; }
if (command === "plugin:dialog|message") { window.tabMenuTest.prompts.push(args.message); return window.tabMenuTest.answer; }
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
const menu = name => page.getByRole("menu", { name, exact: true });
const item = name => page.getByRole("menuitem", { name, exact: true });
async function metrics(panel) {
return panel.evaluate(node => {
const row = node.querySelector(":scope > button");
const icon = row.querySelector(".action-icon");
const label = row.querySelector(".action-label");
const css = getComputedStyle(node), button = getComputedStyle(row);
return {
panel: [css.padding, css.borderRadius, css.backgroundColor, css.color, css.boxShadow, css.font],
row: [button.padding, button.minHeight, button.borderRadius, button.gap, button.font],
iconWidth: icon.getBoundingClientRect().width,
inset: Math.round(row.getBoundingClientRect().left - node.getBoundingClientRect().left),
labelOffset: Math.round(label.getBoundingClientRect().left - row.getBoundingClientRect().left),
};
await runSmoke("menus/consistency", async ({ page }) => {
const output = await outputDir("menus/consistency");
await mockTauri(page, {
commands: test => {
window.tabMenuTest = { revealed: null };
window.spellingTest = { commands: [], emit: payload => test.emit("spelling-menu", payload) };
const spellingMenu = method => args => { window.spellingTest.commands.push({ method, ...args }); };
const workspace = test.workspace({
root: "C:\\tab-menu-workspace",
folders: ["notes"],
files: Object.fromEntries(["a.md", "b.md", "c.md", "d.md"].map(name => [name, `# ${name}\n\nOriginal text.\n\n| Name | Value |\n| --- | --- |\n| Alpha | One |\n`])),
});
return {
...workspace,
workspace_reveal: ({ rel }) => { window.tabMenuTest.revealed = rel; },
spelling_menu_install: spellingMenu("spelling_menu_install"),
spelling_menu_select: spellingMenu("spelling_menu_select"),
spelling_suggestions: () => {
if (window.spellingTest.delay) return new Promise(resolve => { window.spellingTest.resolve = resolve; });
return { language: "en-US", words: [], misspelled: false };
},
};
},
});
}
async function dismiss() { await page.keyboard.press("Escape"); await page.locator(".rs-menu").waitFor({ state: "detached" }); }
try {
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
const menu = name => page.getByRole("menu", { name, exact: true });
const item = name => page.getByRole("menuitem", { name, exact: true });
async function metrics(panel) {
return panel.evaluate(node => {
const row = node.querySelector(":scope > button");
const icon = row.querySelector(".action-icon");
const label = row.querySelector(".action-label");
const css = getComputedStyle(node), button = getComputedStyle(row);
return {
panel: [css.padding, css.borderRadius, css.backgroundColor, css.color, css.boxShadow, css.font],
row: [button.padding, button.minHeight, button.borderRadius, button.gap, button.font],
iconWidth: icon.getBoundingClientRect().width,
inset: Math.round(row.getBoundingClientRect().left - node.getBoundingClientRect().left),
labelOffset: Math.round(label.getBoundingClientRect().left - row.getBoundingClientRect().left),
};
});
}
async function dismiss() { await page.keyboard.press("Escape"); await page.locator(".rs-menu").waitFor({ state: "detached" }); }
await page.goto(smokeUrl);
const row = page.locator('[data-tree-rel="a.md"]');
await row.waitFor();
await row.click();
@@ -95,20 +76,20 @@ try {
document.documentElement.style.setProperty('--rs-menu-row-padding', '4px 10px');
});
const previousHeight = await file.evaluate(node => node.getBoundingClientRect().height);
await page.screenshot({ path: '.audit/todo-2026-10-14/menu-spacing-before-' + theme + '.png' });
await page.screenshot({ path: path.join(output, `menu-spacing-before-${theme}.png`) });
await page.evaluate(() => {
document.documentElement.style.removeProperty('--rs-menu-row-height');
document.documentElement.style.removeProperty('--rs-menu-row-padding');
});
assert.ok(compactHeight < previousHeight * .85, 'The same actions use at least 15% less vertical space');
console.log(JSON.stringify({ theme, compactHeight, previousHeight }));
await page.screenshot({ path: '.audit/todo-2026-10-14/menu-spacing-after-' + theme + '.png' });
await page.screenshot({ path: path.join(output, `menu-spacing-after-${theme}.png`) });
assert.ok(reference.panel[2].includes('/ 0.82') || /rgba\(.+, 0\.82\)/.test(reference.panel[2]), "Shared menus retain an 82% surface tint");
assert.ok(reference.inset >= 5, "Rows need an inset from the panel border");
assert.equal(await item("Pin").locator("svg.action-icon").count(), 1);
const offsets = await file.locator(":scope > button").evaluateAll(nodes => nodes.map(node => Math.round(node.querySelector(".action-label").getBoundingClientRect().left - node.getBoundingClientRect().left)));
assert.equal(new Set(offsets).size, 1, "All file labels align");
await page.screenshot({ path: ".audit/menu-file-" + theme + ".png" });
await page.screenshot({ path: path.join(output, `menu-file-${theme}.png`) });
await dismiss();
assert.equal(await row.evaluate(node => node === document.activeElement), true);
await page.getByRole("navigation", { name: "Workspace files" }).click({ button: "right", position: { x: 100, y: 350 } });
@@ -134,7 +115,7 @@ try {
await item("Move tab").focus();
await page.keyboard.press("ArrowRight");
assert.deepEqual(await metrics(menu("Move tab")), reference, "Submenus share styles");
await page.screenshot({ path: ".audit/menu-tab-" + theme + ".png" });
await page.screenshot({ path: path.join(output, `menu-tab-${theme}.png`) });
await page.keyboard.press("ArrowLeft");
assert.equal(await item("Move tab").evaluate(node => node === document.activeElement), true);
await dismiss();
@@ -145,7 +126,7 @@ try {
await item("Paragraph").focus();
await page.keyboard.press("ArrowRight");
assert.deepEqual(await metrics(menu("Paragraph")), reference);
await page.screenshot({ path: ".audit/menu-editor-" + theme + ".png" });
await page.screenshot({ path: path.join(output, `menu-editor-${theme}.png`) });
await dismiss();
await page.locator(".live-writer td").first().click({ button: "right" });
assert.deepEqual(await metrics(menu("Table actions")), reference, "Table and file menus share styles");
@@ -188,7 +169,7 @@ try {
await page.keyboard.press("ArrowDown");
await page.keyboard.press("ArrowDown");
assert.equal(await item("Copy Ctrl+C").evaluate(node => node === document.activeElement), true, "Spelling keyboard navigation skips disabled commands");
await page.screenshot({ path: ".audit/menu-spelling-" + theme + ".png" });
await page.screenshot({ path: path.join(output, `menu-spelling-${theme}.png`) });
await page.keyboard.press("Home");
await page.keyboard.press("Enter");
await spelling.waitFor({ state: "detached" });
@@ -224,7 +205,7 @@ try {
assert.equal(await item('Copy').count(), 1, 'Editing actions appear before the spelling service resolves');
await page.evaluate(() => { window.spellingTest.resolve({ language: 'en-US', words: ['received'], misspelled: true }); window.spellingTest.delay = false; });
await item('received').waitFor();
await page.screenshot({ path: `.audit/menu-spelling-async-${theme}.png` });
await page.screenshot({ path: path.join(output, `menu-spelling-async-${theme}.png`) });
await dismiss();
await page.evaluate(() => {
window.spellingTest.delay = true;
@@ -263,7 +244,7 @@ try {
const css = getComputedStyle(node);
return css.whiteSpace === 'normal' && css.textOverflow !== 'ellipsis' && node.scrollWidth <= node.clientWidth;
}), 'Long translated actions wrap without truncation');
await page.screenshot({ path: '.audit/menu-translated-long-label.png' });
await page.screenshot({ path: path.join(output, "menu-translated-long-label.png") });
await dismiss();
await page.evaluate(async () => {
const { actionMenu } = await import("/src/lib/ui/actionMenu.ts");
@@ -298,7 +279,7 @@ try {
}
await page.keyboard.press("End");
assert.equal(await item("Action 29").evaluate(node => node === document.activeElement), true);
await page.screenshot({ path: ".audit/menu-edge.png" });
await page.screenshot({ path: path.join(output, "menu-edge.png") });
await dismiss();
await page.evaluate(async () => {
const { actionMenu } = await import("/src/lib/ui/actionMenu.ts");
@@ -324,11 +305,10 @@ try {
assert.equal(await page.locator("#menu-modal-test").evaluate(dialog => dialog.scrollTop), await page.evaluate(() => window.menuModalScroll), "Keyboard traversal scrolls only the menu panel");
const modalBounds = await modalMenu.boundingBox(), lastBounds = await item("Modal action 29").boundingBox();
assert.ok(lastBounds.y >= modalBounds.y && lastBounds.y + lastBounds.height <= modalBounds.y + modalBounds.height + 1, "End keeps the last row visible inside a short modal");
await page.screenshot({ path: ".audit/menu-modal-end.png" });
await page.screenshot({ path: path.join(output, "menu-modal-end.png") });
await page.keyboard.press("Home");
assert.equal(await item("Modal action 0").evaluate(node => node === document.activeElement), true);
await dismiss();
await page.locator("#menu-modal-test").evaluate(dialog => { dialog.close(); dialog.remove(); });
assert.deepEqual(errors, []);
console.log("PASS: menu styles, dark/light themes, icons, disabled rows, focus return, submenus, scrolling, and viewport edges");
} finally { await browser.close(); }
}, { timeout: 15000 });
+111 -125
View File
@@ -1,129 +1,115 @@
import { createRequire } from "node:module";
// Full-app plug-ins: compact header, navigation, dynamic and restored tabs, dialogs, settings forms across windows, and disable cleanup.
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 context = await browser.newContext({ viewport: { width: 1440, height: 900 } });
const errors = [];
await mkdir(".audit", { recursive: true });
await context.addInitScript(() => {
window.isTauri = true;
const callbacks = new Map(), listeners = new Map();
let sequence = 0;
const emit = (event, payload) => { for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload }); };
const manifest = (id, name) => ({ schemaVersion: 1, id, name, author: "Test", description: "Access test", version: "1.0.0", apiVersion: 1, entry: "main.js", access: "full-app" });
const plugins = [manifest("runestone.local-autocomplete", "Local Autocomplete"), manifest("org.example.browser", "Browser"), manifest("org.example.tasks", "Tasks")];
const modules = {
"runestone.local-autocomplete": `export function activate(api) {
window.accessTest = { mounts: 0, disposed: 0, settings: 0 };
api.settings.subscribe?.(() => { window.accessTest.settings++; });
api.registerView({ id: 'settings', title: 'Local Autocomplete', placement: 'editor', mount(container, context) {
window.accessTest.mounts++;
container.innerHTML = '<h2>Local Autocomplete</h2><label>Model<input aria-label="Model"></label><button>Save model</button><p class="mount-context"></p>';
container.querySelector('p').textContent = context?.surface;
container.querySelector('button').onclick = () => api.settings.write({ model: container.querySelector('input').value });
return () => { window.accessTest.disposed++; };
}});
api.registerCommand({ id: 'configure', title: 'Configure Local Autocomplete', run: () => api.openView('settings') });
api.registerCommand({ id: 'fail', title: 'Failed command', run: () => { throw Error('Command failed for test'); } });
}`,
"org.example.browser": `export function activate(api) {
api.registerCommand({ id: 'new-tab', title: 'New browser tab', category: 'open', run() {
const id = 'tab-' + Date.now(); api.registerView({ id, title: 'Browser instance', placement: 'editor', mount(container) { container.textContent = 'Browser content'; } }); api.openView(id);
}});
}`,
"org.example.tasks": `export function activate(api) {
api.registerView({ id: 'tasks', title: 'All tasks', icon: 'list', navigation: true, placement: 'editor', launch() { api.openView('default-board'); }, mount(container) { container.textContent = 'Task content'; } });
api.registerView({ id: 'default-board', title: 'Default board', launcher: false, placement: 'editor', mount(container) { container.textContent = 'Default board content'; } });
window.taskTestApi = api;
api.registerView({ id: 'dialog', title: 'Task summary', mount(container) { container.textContent = 'Task summary content'; } });
}`,
};
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 === 'plugin:event|listen') { const ids = listeners.get(args.event) || []; ids.push(args.handler); listeners.set(args.event, ids); return args.handler; }
if (command === 'plugin:event|unlisten') { callbacks.delete(args.eventId); return; }
if (command === 'browser_connect') return 'test-session';
if (command === 'browser_stop') return;
if (command === 'workspace_last_path') return null;
if (command === 'plugins_snapshot') return { root: 'C:/test/plugins', plugins: plugins.map(manifest => ({ manifest, hash: 'test', enabled: !(manifest.id === 'runestone.local-autocomplete' && localStorage.getItem('disabled')), installedAt: 1, path: 'C:/test/plugins/' + manifest.id, error: null, removal: false })) };
if (command === 'plugins_load') return modules[args.id];
if (command === 'plugins_data') {
if (args.value !== null) { localStorage.setItem('settings:' + args.id, args.value); emit('plugin-settings-changed', args.id); }
return localStorage.getItem('settings:' + args.id) || 'null';
}
if (command === 'plugins_set_enabled') { if (!args.enabled) localStorage.setItem('disabled', 'true'); emit('plugins-changed', {}); return; }
if (command === 'plugins_release' || command === 'settings_open_window') return;
if (command.startsWith('plugin:window|')) return false;
throw new Error('Unhandled IPC: ' + command);
import path from "node:path";
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("plugins/access", async ({ browser }) => {
const context = await browser.newContext({ viewport: { width: 1440, height: 900 } });
await mockTauri(context, {
commands: test => {
const manifest = (id, name) => ({ schemaVersion: 1, id, name, author: "Test", description: "Access test", version: "1.0.0", apiVersion: 1, entry: "main.js", access: "full-app" });
const plugins = [manifest("runestone.local-autocomplete", "Local Autocomplete"), manifest("org.example.browser", "Browser"), manifest("org.example.tasks", "Tasks")];
const modules = {
"runestone.local-autocomplete": `export function activate(api) {
window.accessTest = { mounts: 0, disposed: 0, settings: 0 };
api.settings.subscribe?.(() => { window.accessTest.settings++; });
api.registerView({ id: 'settings', title: 'Local Autocomplete', placement: 'editor', mount(container, context) {
window.accessTest.mounts++;
container.innerHTML = '<h2>Local Autocomplete</h2><label>Model<input aria-label="Model"></label><button>Save model</button><p class="mount-context"></p>';
container.querySelector('p').textContent = context?.surface;
container.querySelector('button').onclick = () => api.settings.write({ model: container.querySelector('input').value });
return () => { window.accessTest.disposed++; };
}});
api.registerCommand({ id: 'configure', title: 'Configure Local Autocomplete', run: () => api.openView('settings') });
api.registerCommand({ id: 'fail', title: 'Failed command', run: () => { throw Error('Command failed for test'); } });
}`,
"org.example.browser": `export function activate(api) {
api.registerCommand({ id: 'new-tab', title: 'New browser tab', category: 'open', run() {
const id = 'tab-' + Date.now(); api.registerView({ id, title: 'Browser instance', placement: 'editor', mount(container) { container.textContent = 'Browser content'; } }); api.openView(id);
}});
}`,
"org.example.tasks": `export function activate(api) {
api.registerView({ id: 'tasks', title: 'All tasks', icon: 'list', navigation: true, placement: 'editor', launch() { api.openView('default-board'); }, mount(container) { container.textContent = 'Task content'; } });
api.registerView({ id: 'default-board', title: 'Default board', launcher: false, placement: 'editor', mount(container) { container.textContent = 'Default board content'; } });
window.taskTestApi = api;
api.registerView({ id: 'dialog', title: 'Task summary', mount(container) { container.textContent = 'Task summary content'; } });
}`,
};
// Settings and the enabled state live in localStorage, so both windows of the context share them.
window.addEventListener("storage", event => {
if (event.key?.startsWith("settings:")) test.emit("plugin-settings-changed", event.key.slice(9));
if (event.key === "disabled") test.emit("plugins-changed", {});
});
return {
browser_connect: () => "test-session",
workspace_last_path: () => null,
plugins_snapshot: () => ({ root: "C:/test/plugins", plugins: plugins.map(manifest => ({ manifest, hash: "test", enabled: !(manifest.id === "runestone.local-autocomplete" && localStorage.getItem("disabled")), installedAt: 1, path: "C:/test/plugins/" + manifest.id, error: null, removal: false })) }),
plugins_load: ({ id }) => modules[id],
plugins_data: ({ id, value }) => {
if (value !== null) { localStorage.setItem("settings:" + id, value); test.emit("plugin-settings-changed", id); }
return localStorage.getItem("settings:" + id) || "null";
},
plugins_set_enabled: ({ enabled }) => { if (!enabled) localStorage.setItem("disabled", "true"); test.emit("plugins-changed", {}); },
plugins_release: () => null,
"plugin:window|is_maximized": () => false,
};
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.addEventListener('storage', event => { if (event.key?.startsWith('settings:')) emit('plugin-settings-changed', event.key.slice(9)); if (event.key === 'disabled') emit('plugins-changed', {}); });
});
const main = await context.newPage(), settings = await context.newPage();
for (const page of [main, settings]) { page.setDefaultTimeout(10000); page.on('pageerror', error => errors.push(error.message)); }
try {
await main.goto(origin);
await main.getByRole('navigation', { name: 'Plugin shortcuts' }).getByRole('button', { name: 'All tasks', exact: true }).waitFor();
assert.equal(await main.getByRole('button', { name: 'Open tab or view', exact: true }).count(), 0);
assert.equal(await main.getByRole('button', { name: 'Commands', exact: true }).count(), 1);
await main.getByRole('navigation', { name: 'Plugin shortcuts' }).getByRole('button', { name: 'All tasks', exact: true }).click();
await main.getByText('Default board content', { exact: true }).waitFor();
await main.evaluate(() => window.taskTestApi.openView('tasks'));
await main.getByText('Task content', { exact: true }).waitFor();
await main.evaluate(async () => {
const { closePluginEditor, pluginTabState, pluginView, restorePluginTab } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
let view;
const off = pluginView.subscribe(value => { view = value; }); off();
const transfer = pluginTabState(view);
closePluginEditor(view.key);
if (!await restorePluginTab(transfer)) throw Error('Tab restore failed');
});
await main.getByText('Task content', { exact: true }).waitFor();
await main.evaluate(async () => {
const { runPluginCommand } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
await runPluginCommand('org.example.browser', 'new-tab');
});
await main.getByText('Browser content', { exact: true }).waitFor();
await main.evaluate(async () => {
const { openPluginView } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
openPluginView('org.example.tasks', 'dialog');
});
await main.getByRole('dialog', { name: 'Task summary' }).waitFor();
await main.keyboard.press('Escape');
for (const theme of ['dark', 'light']) {
await main.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
await main.screenshot({ path: `.audit/plugin-access-${theme}.png` });
const output = await outputDir("plugins/access");
const main = await openPage(context), settings = await openPage(context);
const external = page => page.evaluate(() => performance.getEntriesByType("resource").find(entry => new URL(entry.name).pathname === "/src/lib/plugins/external.ts").name);
try {
await main.goto(smokeUrl);
await main.getByRole("navigation", { name: "Plugin shortcuts" }).getByRole("button", { name: "All tasks", exact: true }).waitFor();
assert.equal(await main.getByRole("button", { name: "Open tab or view", exact: true }).count(), 0);
assert.equal(await main.getByRole("button", { name: "Commands", exact: true }).count(), 1);
await main.getByRole("navigation", { name: "Plugin shortcuts" }).getByRole("button", { name: "All tasks", exact: true }).click();
await main.getByText("Default board content", { exact: true }).waitFor();
await main.evaluate(() => window.taskTestApi.openView("tasks"));
await main.getByText("Task content", { exact: true }).waitFor();
const module = await external(main);
await main.evaluate(async module => {
const { closePluginEditor, pluginTabState, pluginView, restorePluginTab } = await import(module);
let view;
const off = pluginView.subscribe(value => { view = value; }); off();
const transfer = pluginTabState(view);
closePluginEditor(view.key);
if (!await restorePluginTab(transfer)) throw Error("Tab restore failed");
}, module);
await main.getByText("Task content", { exact: true }).waitFor();
await main.evaluate(async module => { await (await import(module)).runPluginCommand("org.example.browser", "new-tab"); }, module);
await main.getByText("Browser content", { exact: true }).waitFor();
await main.evaluate(async module => { (await import(module)).openPluginView("org.example.tasks", "dialog"); }, module);
await main.getByRole("dialog", { name: "Task summary" }).waitFor();
await main.keyboard.press("Escape");
for (const theme of ["dark", "light"]) {
await main.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
await main.screenshot({ path: path.join(output, `plugin-access-${theme}.png`) });
}
await settings.goto(smokeUrl + "/?settingsWindow=true");
await settings.getByRole("button", { name: "Local Autocomplete", exact: true }).click();
await settings.getByRole("textbox", { name: "Model", exact: true }).fill("unsaved-model");
assert.equal(await settings.locator(".mount-context").innerText(), "settings");
await settings.waitForTimeout(5500);
assert.equal(await settings.getByRole("textbox", { name: "Model", exact: true }).inputValue(), "unsaved-model");
assert.equal(await settings.evaluate(() => window.accessTest.mounts), 1);
await settings.getByRole("button", { name: "Save model", exact: true }).click();
await main.waitForFunction(() => window.accessTest.settings === 1);
await settings.screenshot({ path: path.join(output, "plugin-access-settings.png") });
await settings.getByRole("button", { name: "General", exact: true }).click();
await settings.waitForFunction(() => window.accessTest.disposed === 1);
await settings.getByRole("textbox", { name: "Search settings" }).fill("Local");
await settings.getByRole("textbox", { name: "Model", exact: true }).waitFor();
await settings.getByRole("textbox", { name: "Search settings" }).fill("");
await settings.getByRole("button", { name: "Plug-ins", exact: true }).click();
await settings.getByRole("switch", { name: "Local Autocomplete", exact: true }).uncheck();
await settings.getByRole("button", { name: "Local Autocomplete", exact: true }).waitFor({ state: "detached" });
await main.getByRole("button", { name: "Commands", exact: true }).waitFor({ state: "detached" });
assert.deepEqual([...main.errors, ...settings.errors], []);
} catch (error) {
await settings.screenshot({ path: path.join(output, "plugin-access-failure.png") });
console.log(await settings.locator("body").innerText(), await settings.evaluate(() => window.accessTest), [...main.errors, ...settings.errors]);
throw error;
}
await settings.goto(origin + '/?settingsWindow=true');
await settings.getByRole('button', { name: 'Local Autocomplete', exact: true }).click();
await settings.getByRole('textbox', { name: 'Model', exact: true }).fill('unsaved-model');
assert.equal(await settings.locator('.mount-context').innerText(), 'settings');
await settings.waitForTimeout(5500);
assert.equal(await settings.getByRole('textbox', { name: 'Model', exact: true }).inputValue(), 'unsaved-model');
assert.equal(await settings.evaluate(() => window.accessTest.mounts), 1);
await settings.getByRole('button', { name: 'Save model', exact: true }).click();
await main.waitForFunction(() => window.accessTest.settings === 1);
await settings.screenshot({ path: '.audit/plugin-access-settings.png' });
await settings.getByRole('button', { name: 'General', exact: true }).click();
await settings.waitForFunction(() => window.accessTest.disposed === 1);
await settings.getByRole('textbox', { name: 'Search settings' }).fill('Local');
await settings.getByRole('textbox', { name: 'Model', exact: true }).waitFor();
await settings.getByRole('textbox', { name: 'Search settings' }).fill('');
await settings.getByRole('button', { name: 'Plug-ins', exact: true }).click();
await settings.getByRole('switch', { name: 'Local Autocomplete', exact: true }).uncheck();
await settings.getByRole('button', { name: 'Local Autocomplete', exact: true }).waitFor({ state: 'detached' });
await main.getByRole('button', { name: 'Commands', exact: true }).waitFor({ state: 'detached' });
assert.deepEqual(errors, []);
console.log('Plugin access smoke passed: compact header, navigation, dynamic tabs, dialog, settings search, stable forms, cross-window settings, disable cleanup.');
} catch (error) {
await settings.screenshot({ path: '.audit/plugin-access-failure.png' });
console.log(await settings.locator('body').innerText(), await settings.evaluate(() => window.accessTest), errors);
throw error;
} finally { await browser.close(); }
console.log("Plugin access smoke passed: compact header, navigation, dynamic tabs, dialog, settings search, stable forms, cross-window settings, disable cleanup.");
});
+18 -21
View File
@@ -1,25 +1,23 @@
// Local Autocomplete settings choices use the shared action menu in a modal: keyboard choice, saving, focus return, and cleanup.
// @requires repo:RuneStone_Local_Autocomplete/src
import assert from 'node:assert/strict';
import { readFile, 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 browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage();
const url = process.env.SMOKE_URL || 'http://127.0.0.1:1420';
const errors = [];
page.on('pageerror', error => errors.push(error.message));
await mkdir('.audit/menu-audit', { recursive: true });
await page.route('**/__choice-audit__', route => route.fulfill({ contentType: 'text/html', body: '<link rel="stylesheet" href="/src/lib/theme/tokens.css"><link rel="stylesheet" href="/src/lib/ui/menu.css"><style>dialog{inset:0;margin:0;max-width:none;max-height:none;width:100%;height:100%;box-sizing:border-box;background:var(--rs-bg);color:var(--rs-text);padding:0;border:0}</style><dialog><main></main></dialog>' }));
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_Local_Autocomplete/src/${name}`, import.meta.url), 'utf8') });
});
try {
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { outputDir, pluginRepo, runSmoke, smokeUrl } from '../_harness/index.mjs';
const autocompleteSource = path.join(pluginRepo('RuneStone_Local_Autocomplete'), 'src');
await runSmoke('plugins/choiceMenus', async ({ page }) => {
const output = await outputDir('plugins/choiceMenus');
await page.route('**/__choice-audit__', route => route.fulfill({ contentType: 'text/html', body: '<link rel="stylesheet" href="/src/lib/theme/tokens.css"><link rel="stylesheet" href="/src/lib/ui/menu.css"><style>dialog{inset:0;margin:0;max-width:none;max-height:none;width:100%;height:100%;box-sizing:border-box;background:var(--rs-bg);color:var(--rs-text);padding:0;border:0}</style><dialog><main></main></dialog>' }));
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(path.join(autocompleteSource, name), 'utf8') });
});
for (const theme of ['light', 'dark']) for (const width of [1100, 390]) {
await page.setViewportSize({ width, height: 850 });
await page.goto(url + '/__choice-audit__');
await page.goto(smokeUrl + '/__choice-audit__');
await page.evaluate(async theme => {
document.documentElement.dataset.theme = theme;
const { showActionMenu } = await import('/src/lib/ui/managedActionMenu.ts');
@@ -38,7 +36,7 @@ try {
assert.equal(await menu.evaluate(node => !!node.closest('dialog[open]')), true);
await page.keyboard.press('End');
assert.equal(await page.getByRole('menuitemradio', { name: 'Ollama', exact: true }).evaluate(node => node === document.activeElement), true);
await page.screenshot({ path: `.audit/menu-audit/autocomplete-${theme}-${width}.png` });
await page.screenshot({ path: path.join(output, `autocomplete-${theme}-${width}.png`) });
await page.keyboard.press('Enter');
assert.match(await trigger.innerText(), /Ollama/);
await page.getByRole('button', { name: 'Save settings', exact: true }).click();
@@ -48,6 +46,5 @@ try {
await trigger.click(); await page.evaluate(() => window.choiceAudit.dispose());
assert.equal(await page.locator('.rs-menu').count(), 0);
}
assert.deepEqual(errors, []);
console.log('PASS: Local Autocomplete shared choices, modal input, saved adapter, focus return, and cleanup in both themes at 1100/390px.');
} finally { await browser.close(); }
}, { timeout: 30000 });
+68
View File
@@ -0,0 +1,68 @@
// Git plugin sidebar toolbar: the Graph control is icon-only, keeps its accessible name, shows hover and focus tooltips in both themes, and opens Graph.
// @requires repo:RuneStone_Git/src
// The source loads from the sibling RuneStone_Git checkout (RUNESTONE_PLUGIN_REPOS) without building a plugin ZIP.
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import path from "node:path";
import { mockTauri, outputDir, pluginRepo, runSmoke, smokeUrl } from "../_harness/index.mjs";
const name = "plugins/gitToolbar";
await runSmoke(name, async ({ page }) => {
const output = await outputDir(name);
const source = pluginRepo("RuneStone_Git");
const files = new Map(await Promise.all(["view.js", "model.js"].map(async file => [file, await readFile(path.join(source, "src", file), "utf8")])));
const css = await readFile(path.join(source, "src", "style.css"), "utf8");
await page.route("**/__git_source/*", route => route.fulfill({ contentType: "text/javascript", body: files.get(new URL(route.request().url()).pathname.split("/").pop()) || "" }));
await mockTauri(page, {
commands: test => ({
...test.workspace({ root: "C:\\git-toolbar", files: { "notes/draft.md": "Before.\n" } }),
plugins_snapshot: () => ({ plugins: [], issues: [] }),
spelling_menu_install: () => null,
}),
});
await page.goto(smokeUrl);
await page.locator('[data-tree-rel="notes"]').waitFor();
await page.evaluate(async css => {
const { mountSidebar } = await import("/__git_source/view.js");
const container = document.createElement("div");
container.id = "git-smoke";
container.style.cssText = "position:fixed;inset:45px 0 0 0;z-index:1000;background:var(--rs-bg)";
document.body.append(container);
window.gitGraphOpens = 0;
window.disposeGitSmoke = mountSidebar(container, {
workspace: {},
git: { status: async () => ({ available: true, repository: true, branch: "main", changes: [] }), pull: async () => {}, push: async () => {} },
openView: () => window.gitGraphOpens++,
}, css, () => {});
}, css);
const graph = page.locator("#git-smoke").getByRole("button", { name: "Graph", exact: true });
// The plugin shows the shared host tooltip (a `.rs-tooltip` popover from `data-tooltip`) instead of a title and its own tooltip span.
// RuneStone_Git/src/view.js: button() sets data-tooltip and aria-label; tooltipScope() shows the popover on hover and focus.
const tooltip = page.locator(".rs-tooltip:popover-open");
for (const theme of ["dark", "light"]) {
await page.evaluate(async mode => { const { saveAppearance } = await import("/src/lib/theme/appearance.ts"); saveAppearance({ theme: "default", mode }); }, theme);
await graph.waitFor();
assert.equal(await graph.locator("svg").count(), 1);
assert.equal(await graph.getAttribute("title"), null);
assert.equal(await graph.getAttribute("data-tooltip"), "Graph");
assert.equal(await graph.evaluate(node => [...node.childNodes].filter(child => child.nodeType === Node.TEXT_NODE && child.textContent.trim()).length), 0);
assert.equal(await graph.locator(":scope > :not(.rs-git-icon)").count(), 0, "Graph has no visible text label");
await page.mouse.move(800, 800);
await graph.evaluate(node => node.blur());
assert.equal(await tooltip.count(), 0);
await graph.hover();
await tooltip.waitFor();
assert.equal(await tooltip.innerText(), "Graph");
await page.mouse.move(800, 800);
await page.keyboard.press("Tab");
await graph.focus();
assert.equal(await graph.evaluate(node => node.matches(":focus-visible")), true);
await tooltip.waitFor();
assert.equal(await tooltip.innerText(), "Graph");
await page.screenshot({ path: path.join(output, `git-toolbar-${theme}.png`) });
}
await graph.click();
assert.equal(await page.evaluate(() => window.gitGraphOpens), 1);
await page.evaluate(() => window.disposeGitSmoke());
console.log("PASS: icon-only Graph control with accessible name, hover and focus tooltips in both themes, and Graph opens");
}, { timeout: 15000 });
+184 -233
View File
@@ -1,238 +1,189 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
// Plug-in installation: ZIP and Git-link review, download errors, token clearing, updates, disabled installs, cleanup, and uninstall.
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 }, locale: 'en-US', timezoneId: 'America/Vancouver' });
const page = await context.newPage();
const settingsPage = await context.newPage();
settingsPage.setDefaultTimeout(10000);
await context.exposeBinding("settingsHostInvoke", (_source, command, args) =>
page.evaluate(({ command, args }) => window.__TAURI_INTERNALS__.invoke(command, args), { command, args }));
page.setDefaultTimeout(10000);
const errors = [];
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
settingsPage.on("pageerror", error => errors.push(error.message));
const manifest = JSON.parse(readFileSync('fixtures/plugins/workspace-overview/plugin.json', 'utf8'));
const pluginCode = readFileSync('fixtures/plugins/workspace-overview/main.js', 'utf8') + '\n// Browser cleanup probe\n';
await page.context().addInitScript(({ manifest, pluginCode }) => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
let installed = [];
let removalPrepared = false;
const data = { preserved: true };
const path = "C:\\AppData\\RuneStone\\plugins\\" + manifest.id;
const snapshot = () => ({ root: "C:\\AppData\\RuneStone\\plugins", plugins: installed });
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (location.search.includes("settingsWindow") && !command.startsWith("plugin:event|") && !command.startsWith("plugin:window|"))
return window.settingsHostInvoke(command, args);
calls.push({ command, args });
if (command === "settings_open_window") return;
if (command === "plugin:window|is_maximized") return false;
if (command.startsWith("plugin:window|")) return null;
if (command === "plugins_snapshot") return snapshot();
if (command === "plugins_choose") return [{ token: 'candidate', source: 'C:/Downloads/overview.zip', manifest, error: null }];
if (command === "plugins_from_git") {
if (args.tag === 'missing') throw new Error('Release not found. Publish a release with one plugin ZIP.');
return [{ token: 'git-candidate', source: args.url + ' @ ' + (args.tag || 'v1.0.0'), manifest, error: null }];
import path from "node:path";
import { mockTauri, openPage, outputDir, repoRoot, runSmoke, smokeUrl } from "../_harness/index.mjs";
const fixture = path.join(repoRoot, "fixtures", "plugins", "workspace-overview");
const manifest = JSON.parse(readFileSync(path.join(fixture, "plugin.json"), "utf8"));
const pluginCode = readFileSync(path.join(fixture, "main.js"), "utf8") + "\n// Browser cleanup probe\n";
await runSmoke("plugins/install", async ({ browser }) => {
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 }, locale: "en-US", timezoneId: "America/Vancouver" });
const page = await openPage(context);
const settingsPage = await openPage(context);
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
// The settings window forwards plug-in commands to the main window, which owns the installed state.
await context.exposeBinding("settingsHostInvoke", (_source, command, args) =>
page.evaluate(({ command, args }) => window.__TAURI_INTERNALS__.invoke(command, args), { command, args }));
await mockTauri(context, {
state: { manifest, pluginCode },
commands: test => {
const { manifest, pluginCode } = test.state;
const isMaximized = () => false;
if (location.search.includes("settingsWindow")) {
return new Proxy({}, { get: (_table, command) => command === "plugin:window|is_maximized" ? isMaximized : args => window.settingsHostInvoke(command, args) });
}
if (command === "plugins_cancel") { removalPrepared = false; return; }
if (command === "plugins_install") {
const previous = installed[0];
installed = [{ manifest, hash: 'reviewed-hash', enabled: previous ? previous.enabled : args.enabled, installedAt: Date.parse('2026-10-05T18:24:36Z'), path, error: null, removal: false }];
emit('plugins-changed', null); return [{ name: manifest.name, error: null }];
}
if (command === "plugins_set_enabled") {
installed[0].enabled = args.enabled;
emit('plugins-changed', null); return;
}
if (command === "plugins_load") { window.__TEST__.cleaned = false; window.__TEST__.released = false; return pluginCode.replace('export function activate(api) {', 'export function activate(api) { api.onDispose(() => { window.__TEST__.cleaned = true; });'); }
if (command === "plugins_release") { window.__TEST__.released = true; return; }
if (command === "plugins_data") return JSON.stringify(data);
if (command === "plugins_reveal") return;
if (command === "plugins_prepare_remove") { removalPrepared = true; return { token: 'remove-plan', plugin: installed[0] }; }
if (command === "plugins_remove") {
if (!removalPrepared) throw Error('Missing removal plan');
removalPrepared = false;
installed[0].enabled = false; emit('plugins-changed', null);
for (let i=0; i<100 && !window.__TEST__.released; i++) await new Promise(resolve => setTimeout(resolve, 50));
if (!window.__TEST__.cleaned || !window.__TEST__.released) throw Error('Cleanup was not acknowledged');
installed = []; emit('plugins-changed', null); return;
}
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
let installed = [];
let removalPrepared = false;
const data = { preserved: true };
const pluginPath = "C:\\AppData\\RuneStone\\plugins\\" + manifest.id;
const changed = () => test.emit("plugins-changed", null);
Object.assign(test, { data, cleaned: false, released: false });
const ws = test.workspace({
root: "C:\\smoke-workspace",
files: {
"notes/welcome.md": "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n",
"notes/second.md": "# Second note\n",
"src/hello.py": "print('hello')\n",
},
writeEvents: true,
});
return {
...ws,
"plugin:window|is_maximized": isMaximized,
settings_open_window: () => null,
plugins_snapshot: () => ({ root: "C:\\AppData\\RuneStone\\plugins", plugins: installed }),
plugins_choose: () => [{ token: "candidate", source: "C:/Downloads/overview.zip", manifest, error: null }],
plugins_from_git: ({ url, tag }) => {
if (tag === "missing") throw new Error("Release not found. Publish a release with one plugin ZIP.");
return [{ token: "git-candidate", source: url + " @ " + (tag || "v1.0.0"), manifest, error: null }];
},
plugins_cancel: () => { removalPrepared = false; },
plugins_install: ({ enabled }) => {
const previous = installed[0];
installed = [{ manifest, hash: "reviewed-hash", enabled: previous ? previous.enabled : enabled, installedAt: Date.parse("2026-10-05T18:24:36Z"), path: pluginPath, error: null, removal: false }];
changed();
return [{ name: manifest.name, error: null }];
},
plugins_load: () => {
test.cleaned = false; test.released = false;
return pluginCode.replace("export function activate(api) {", "export function activate(api) { api.onDispose(() => { window.__TEST__.cleaned = true; });");
},
plugins_release: () => { test.released = true; },
plugins_prepare_remove: () => { removalPrepared = true; return { token: "remove-plan", plugin: installed[0] }; },
plugins_remove: async () => {
if (!removalPrepared) throw Error("Missing removal plan");
removalPrepared = false;
installed[0].enabled = false; changed();
for (let i = 0; i < 100 && !test.released; i++) await new Promise(resolve => setTimeout(resolve, 50));
if (!test.cleaned || !test.released) throw Error("Cleanup was not acknowledged");
installed = []; changed();
},
};
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root, data };
}, { manifest, pluginCode });
async function quickOpen(name) {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
await page.locator('.live-writer').waitFor();
}
const settingsDialog = settingsPage.getByRole('dialog', { name: 'Settings', exact: true });
const count = command => page.evaluate(command => window.__TEST__.calls.filter(call => call.command === command).length, command);
async function settings() {
await page.getByRole('button', { name: 'Settings (Ctrl+,)', exact: true }).click();
await settingsPage.goto((process.env.SMOKE_URL || 'http://127.0.0.1:1420') + '/?settingsWindow=true');
await settingsDialog.getByRole('button', { name: 'Plug-ins', exact: true }).click();
}
async function uninstall() { await settingsDialog.locator('.card').filter({ hasText: 'Workspace overview' }).getByRole('button', { name: 'Uninstall', exact: true }).click(); }
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await page.getByText('smoke-workspace', { exact: true }).waitFor();
await settings();
assert.equal(await settingsDialog.getByRole('button', { name: 'Install from folder', exact: true }).count(), 0);
assert.equal(await settingsDialog.getByRole('button', { name: 'Install from file', exact: true }).count(), 0);
await settingsDialog.getByRole('button', { name: 'Install plugin ZIP', exact: true }).click();
let review = settingsPage.getByRole('dialog', { name: 'Review plugin installation', exact: true });
await review.getByText('Source: C:/Downloads/overview.zip', { exact: true }).waitFor();
await review.getByRole('button', { name: 'Cancel', exact: true }).click();
assert.equal(await count('plugins_install'), 0);
const gitButton = settingsDialog.getByRole('button', { name: 'Install from Git link', exact: true });
await gitButton.click();
const gitDialog = settingsPage.getByRole('dialog', { name: 'Install from Git link', exact: true });
await gitDialog.getByLabel('Repository link', { exact: true }).fill('https://git.example/owner/plugin.git');
await gitDialog.getByLabel('Release tag (optional)', { exact: true }).fill('missing');
await gitDialog.getByLabel('Access token (optional)', { exact: true }).fill('test-token');
await gitDialog.getByRole('button', { name: 'Review release', exact: true }).click();
await gitDialog.getByRole('alert').getByText(/Release not found/).waitFor();
assert.equal(await gitDialog.getByLabel('Access token (optional)', { exact: true }).inputValue(), '');
await gitDialog.getByLabel('Release tag (optional)', { exact: true }).fill('v1.0.0');
await gitDialog.getByRole('button', { name: 'Review release', exact: true }).click();
await review.getByText('Source: https://git.example/owner/plugin.git @ v1.0.0', { exact: true }).waitFor();
await review.getByRole('button', { name: 'Cancel', exact: true }).click();
assert.equal(await count('plugins_install'), 0);
assert(await gitButton.evaluate(element => element === document.activeElement));
await settingsDialog.getByRole('button', { name: 'Install plugin ZIP', exact: true }).click();
await review.getByRole('button', { name: 'Install and enable', exact: true }).click();
await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).waitFor();
assert(await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).isChecked());
assert.equal(await settingsDialog.locator('time').getAttribute('datetime'), '2026-10-05T18:24:36.000Z');
assert.match(await settingsDialog.locator('time').innerText(), /Oct 5, 2026.*11:24:36 AM PDT/);
await settingsPage.screenshot({ path: '.audit/plugin-manager-installed.png' });
await settingsPage.keyboard.press('Escape');
await page.getByRole('button', { name: 'Commands', exact: true }).click();
await page.getByRole('menuitem', { name: /Show workspace overview/ }).click();
const view = page.getByRole('dialog', { name: 'Workspace overview', exact: true });
await view.getByText(/files and folders in this workspace/).waitFor();
await view.getByRole('button', { name: 'Close plugin view', exact: true }).click();
await settings();
await settingsDialog.getByRole('button', { name: 'Install plugin ZIP', exact: true }).click();
await review.getByText(/Update .* → .*Settings and enabled state stay the same/).waitFor();
assert.equal(await review.getByRole('button', { name: 'Install and enable', exact: true }).count(), 0);
for (const mode of ['dark', 'light']) {
await settingsPage.evaluate(async mode => {
const { saveAppearance } = await import('/src/lib/theme/appearance.ts');
saveAppearance({ theme: 'default', mode });
}, mode);
for (const width of [1440, 590]) {
await settingsPage.setViewportSize({ width, height: width === 590 ? 820 : 1000 });
await settingsPage.screenshot({ path: `.audit/plugin-update-review-${mode}-${width}.png` });
assert.equal(await review.evaluate(element => element.scrollWidth > element.clientWidth), false);
}
});
const output = await outputDir("plugins/install");
const shot = name => settingsPage.screenshot({ path: path.join(output, name) });
const settingsDialog = settingsPage.getByRole("dialog", { name: "Settings", exact: true });
const count = command => page.evaluate(command => window.__TEST__.calls.filter(call => call.command === command).length, command);
async function settings() {
await page.getByRole("button", { name: "Settings (Ctrl+,)", exact: true }).click();
await settingsPage.goto(smokeUrl + "/?settingsWindow=true");
await settingsDialog.getByRole("button", { name: "Plug-ins", exact: true }).click();
}
await review.getByRole('button', { name: 'Apply packages', exact: true }).click();
assert(await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).isChecked());
assert.equal(await page.evaluate(() => window.__TEST__.data.preserved), true);
assert.equal(await count('plugins_remove'), 0);
await settingsPage.setViewportSize({ width: 1440, height: 1000 });
await uninstall();
const confirmation = settingsPage.getByRole('dialog', { name: 'Uninstall Workspace overview?', exact: true });
assert(await confirmation.getByRole('button', { name: 'Cancel', exact: true }).evaluate(el => el === document.activeElement));
assert.equal(await confirmation.getByRole('button', { name: 'Continue', exact: true }).count(), 0);
await confirmation.getByRole('button', { name: 'Cancel', exact: true }).click();
assert.equal(await count('plugins_remove'), 0);
assert(await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).isChecked());
await uninstall();
await confirmation.waitFor();
await settingsPage.keyboard.press('Escape');
assert(await settingsDialog.isVisible());
assert(await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).isChecked());
assert.equal(await count('plugins_remove'), 0);
await uninstall();
await confirmation.waitFor();
await settingsPage.screenshot({ path: '.audit/plugin-uninstall-confirmation.png' });
await confirmation.getByRole('button', { name: 'Uninstall and delete files', exact: true }).click();
await settingsDialog.getByText('No plugins installed.', { exact: true }).waitFor();
assert.equal(await count('plugins_remove'), 1);
assert.equal(await page.evaluate(() => window.__TEST__.cleaned), true);
assert.equal(await page.evaluate(() => window.__TEST__.data.preserved), true);
await settingsPage.keyboard.press('Escape');
assert.equal(await page.getByRole('button', { name: 'Plugin commands and views', exact: true }).count(), 0);
await settingsPage.setViewportSize({ width: 590, height: 820 });
await settings();
await settingsPage.screenshot({ path: '.audit/plugin-manager-narrow.png' });
assert.equal(await settingsDialog.evaluate(element => element.scrollWidth > element.clientWidth), false);
await gitButton.click();
await gitDialog.getByLabel('Repository link', { exact: true }).fill('https://git.example/owner/plugin.git');
await settingsPage.screenshot({ path: '.audit/plugin-git-narrow.png' });
assert.equal(await gitDialog.evaluate(element => element.scrollWidth > element.clientWidth), false);
await gitDialog.getByRole('button', { name: 'Review release', exact: true }).click();
await review.getByRole('button', { name: 'Install', exact: true }).click();
await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).waitFor();
assert.equal(await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).isChecked(), false);
assert.equal(await count('plugins_from_git'), 3);
assert.deepEqual(errors, []);
console.log('External plugin smoke passed: ZIP and Git-link review, download errors, token clearing, disabled installation, code loading, cancellation, focus, cleanup, and uninstall.');
} catch (error) {
console.log('Main page:', await page.locator('body').innerText());
console.log('Page errors:', errors);
throw error;
} finally { await browser.close(); }
async function uninstall() { await settingsDialog.locator(".card").filter({ hasText: "Workspace overview" }).getByRole("button", { name: "Uninstall", exact: true }).click(); }
try {
await page.goto(smokeUrl);
await page.getByText("smoke-workspace", { exact: true }).waitFor();
await settings();
assert.equal(await settingsDialog.getByRole("button", { name: "Install from folder", exact: true }).count(), 0);
assert.equal(await settingsDialog.getByRole("button", { name: "Install from file", exact: true }).count(), 0);
await settingsDialog.getByRole("button", { name: "Install plugin ZIP", exact: true }).click();
const review = settingsPage.getByRole("dialog", { name: "Review plugin installation", exact: true });
await review.getByText("Source: C:/Downloads/overview.zip", { exact: true }).waitFor();
await review.getByRole("button", { name: "Cancel", exact: true }).click();
assert.equal(await count("plugins_install"), 0);
const gitButton = settingsDialog.getByRole("button", { name: "Install from Git link", exact: true });
await gitButton.click();
const gitDialog = settingsPage.getByRole("dialog", { name: "Install from Git link", exact: true });
await gitDialog.getByLabel("Repository link", { exact: true }).fill("https://git.example/owner/plugin.git");
await gitDialog.getByLabel("Release tag (optional)", { exact: true }).fill("missing");
await gitDialog.getByLabel("Access token (optional)", { exact: true }).fill("test-token");
await gitDialog.getByRole("button", { name: "Review release", exact: true }).click();
await gitDialog.getByRole("alert").getByText(/Release not found/).waitFor();
assert.equal(await gitDialog.getByLabel("Access token (optional)", { exact: true }).inputValue(), "");
await gitDialog.getByLabel("Release tag (optional)", { exact: true }).fill("v1.0.0");
await gitDialog.getByRole("button", { name: "Review release", exact: true }).click();
await review.getByText("Source: https://git.example/owner/plugin.git @ v1.0.0", { exact: true }).waitFor();
await review.getByRole("button", { name: "Cancel", exact: true }).click();
assert.equal(await count("plugins_install"), 0);
assert(await gitButton.evaluate(element => element === document.activeElement));
await settingsDialog.getByRole("button", { name: "Install plugin ZIP", exact: true }).click();
await review.getByRole("button", { name: "Install and enable", exact: true }).click();
await settingsDialog.getByRole("switch", { name: "Workspace overview", exact: true }).waitFor();
assert(await settingsDialog.getByRole("switch", { name: "Workspace overview", exact: true }).isChecked());
assert.equal(await settingsDialog.locator("time").getAttribute("datetime"), "2026-10-05T18:24:36.000Z");
assert.match(await settingsDialog.locator("time").innerText(), /Oct 5, 2026.*11:24:36 AM PDT/);
await shot("plugin-manager-installed.png");
await settingsPage.keyboard.press("Escape");
await page.getByRole("button", { name: "Commands", exact: true }).click();
await page.getByRole("menuitem", { name: /Show workspace overview/ }).click();
const view = page.getByRole("dialog", { name: "Workspace overview", exact: true });
await view.getByText(/files and folders in this workspace/).waitFor();
await view.getByRole("button", { name: "Close plugin view", exact: true }).click();
await settings();
await settingsDialog.getByRole("button", { name: "Install plugin ZIP", exact: true }).click();
await review.getByText(/Update .* → .*Settings and enabled state stay the same/).waitFor();
assert.equal(await review.getByRole("button", { name: "Install and enable", exact: true }).count(), 0);
for (const mode of ["dark", "light"]) {
await settingsPage.evaluate(async mode => {
const { saveAppearance } = await import("/src/lib/theme/appearance.ts");
saveAppearance({ theme: "default", mode });
}, mode);
for (const width of [1440, 590]) {
await settingsPage.setViewportSize({ width, height: width === 590 ? 820 : 1000 });
await shot(`plugin-update-review-${mode}-${width}.png`);
assert.equal(await review.evaluate(element => element.scrollWidth > element.clientWidth), false);
}
}
await review.getByRole("button", { name: "Apply packages", exact: true }).click();
assert(await settingsDialog.getByRole("switch", { name: "Workspace overview", exact: true }).isChecked());
assert.equal(await page.evaluate(() => window.__TEST__.data.preserved), true);
assert.equal(await count("plugins_remove"), 0);
await settingsPage.setViewportSize({ width: 1440, height: 1000 });
await uninstall();
const confirmation = settingsPage.getByRole("dialog", { name: "Uninstall Workspace overview?", exact: true });
assert(await confirmation.getByRole("button", { name: "Cancel", exact: true }).evaluate(el => el === document.activeElement));
assert.equal(await confirmation.getByRole("button", { name: "Continue", exact: true }).count(), 0);
await confirmation.getByRole("button", { name: "Cancel", exact: true }).click();
assert.equal(await count("plugins_remove"), 0);
assert(await settingsDialog.getByRole("switch", { name: "Workspace overview", exact: true }).isChecked());
await uninstall();
await confirmation.waitFor();
await settingsPage.keyboard.press("Escape");
assert(await settingsDialog.isVisible());
assert(await settingsDialog.getByRole("switch", { name: "Workspace overview", exact: true }).isChecked());
assert.equal(await count("plugins_remove"), 0);
await uninstall();
await confirmation.waitFor();
await shot("plugin-uninstall-confirmation.png");
await confirmation.getByRole("button", { name: "Uninstall and delete files", exact: true }).click();
await settingsDialog.getByText("No plugins installed.", { exact: true }).waitFor();
assert.equal(await count("plugins_remove"), 1);
assert.equal(await page.evaluate(() => window.__TEST__.cleaned), true);
assert.equal(await page.evaluate(() => window.__TEST__.data.preserved), true);
await settingsPage.keyboard.press("Escape");
assert.equal(await page.getByRole("button", { name: "Plugin commands and views", exact: true }).count(), 0);
await settingsPage.setViewportSize({ width: 590, height: 820 });
await settings();
await shot("plugin-manager-narrow.png");
assert.equal(await settingsDialog.evaluate(element => element.scrollWidth > element.clientWidth), false);
await gitButton.click();
await gitDialog.getByLabel("Repository link", { exact: true }).fill("https://git.example/owner/plugin.git");
await shot("plugin-git-narrow.png");
assert.equal(await gitDialog.evaluate(element => element.scrollWidth > element.clientWidth), false);
await gitDialog.getByRole("button", { name: "Review release", exact: true }).click();
await review.getByRole("button", { name: "Install", exact: true }).click();
await settingsDialog.getByRole("switch", { name: "Workspace overview", exact: true }).waitFor();
assert.equal(await settingsDialog.getByRole("switch", { name: "Workspace overview", exact: true }).isChecked(), false);
assert.equal(await count("plugins_from_git"), 3);
assert.deepEqual([...page.errors, ...settingsPage.errors], []);
} catch (error) {
console.log("Main page:", await page.locator("body").innerText());
console.log("Page errors:", [...page.errors, ...settingsPage.errors]);
throw error;
}
console.log("External plugin smoke passed: ZIP and Git-link review, download errors, token clearing, disabled installation, code loading, cancellation, focus, cleanup, and uninstall.");
});
+165 -196
View File
@@ -1,203 +1,172 @@
// Feature plug-in lifecycle: Table formulas and Terminal turn off, persist, reopen across windows, and uninstall without restoration.
// @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";
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 context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
await context.route('**/__settings-closed', route => route.fulfill({ contentType: 'text/html', body: '<!doctype html><title>Closed settings</title>' }));
const page = await context.newPage();
const settingsPage = await context.newPage();
page.setDefaultTimeout(10000);
settingsPage.setDefaultTimeout(10000);
const errors = [];
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
settingsPage.on("pageerror", error => errors.push(error.message));
await page.context().addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "settings_open_window") return;
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
import assert from 'node:assert/strict';
import path from 'node:path';
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
import { mockFeaturePlugins } from '../_harness/pluginMocks.mjs';
await runSmoke('plugins/lifecycle', async ({ browser }) => {
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
await context.route('**/__settings-closed', route => route.fulfill({ contentType: 'text/html', body: '<!doctype html><title>Closed settings</title>' }));
const page = await openPage(context);
const settingsPage = await openPage(context);
page.on('console', message => { if (message.type() === 'error' || message.type() === 'warning') console.log(message.type(), message.text()); });
await mockTauri(context, {
commands: test => {
const ws = test.workspace({
root: 'C:\\smoke-workspace',
files: {
'notes/welcome.md': '---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n',
'notes/second.md': '# Second note\n',
'src/hello.py': "print('hello')\n",
},
});
const files = ws.files;
test.files = files;
return {
...ws,
workspace_write: ({ rel, contents, expected }) => {
if (expected !== undefined && files.get(rel) !== expected) throw new Error('Save blocked: file changed on disk');
files.set(rel, contents);
test.emit('workspace-event', { root: ws.root, kind: 'modify', paths: [rel] });
},
settings_open_window: () => null,
pty_profiles: () => [{ id: 'powershell', title: 'PowerShell', kind: 'powershell' }],
pty_open: async ({ id }) => {
const data = [...new TextEncoder().encode('READY 🪨\r\n\x1b[6n')];
test.emit('pty-data', { id, data: data.slice(0, 8) });
test.emit('pty-data', { id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
},
pty_write: () => null,
pty_resize: () => null,
pty_close: () => null,
};
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
await mockFeaturePlugins(page.context());
});
await mockFeaturePlugins(context);
const output = await outputDir('plugins/lifecycle');
const source = '# Formulas\n\n| A | B |\n| --- | --- |\n| 2 | =A2*3 |\n\nAfter.\n';
const table = page.locator('.live-writer table');
const dialog = settingsPage.getByRole('dialog', { name: 'Settings', exact: true });
const switchFor = name => dialog.getByRole('switch', { name, exact: true });
const ptyCalled = command => window.__TEST__.calls.some(call => call.command === command);
const count = command => page.evaluate(command => window.__TEST__.calls.filter(call => call.command === command).length, command);
async function quickOpen(name) {
await page.keyboard.press('Control+p');
await page.getByRole('textbox', { name: 'Find a file' }).fill(name);
await page.getByRole('dialog').getByRole('button').filter({ hasText: name }).first().click();
await page.locator('.live-writer').waitFor();
}
async function settings() {
await page.getByRole('button', { name: 'Settings (Ctrl+,)', exact: true }).click();
await settingsPage.goto(smokeUrl + '/?settingsWindow=true');
await dialog.getByRole('button', { name: 'Plug-ins', exact: true }).click();
}
async function closeSettings() {
await settingsPage.waitForFunction(() => [...document.querySelectorAll('input[role="switch"]')].every(input => !input.disabled));
await settingsPage.goto(smokeUrl + '/__settings-closed');
await page.bringToFront();
}
async function quickOpen(name) {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
await page.locator('.live-writer').waitFor();
}
try {
await page.goto(smokeUrl);
await page.getByText('smoke-workspace', { exact: true }).waitFor();
await page.evaluate(text => window.__TEST__.files.set('formulas.md', text), source);
await quickOpen('formulas.md');
await table.waitFor();
assert.equal(await table.locator('.md-table-formula').innerText(), '6');
await settings();
await switchFor('Table formulas').uncheck();
await closeSettings();
await page.waitForFunction(() => !document.querySelector('.md-table-formula'));
assert.match(await table.innerText(), /=A2\*3/);
assert.equal(await page.locator('.table-formula-tools').count(), 0);
await table.locator('td').last().click();
await page.locator('.writer-cell-editor').fill('=A2*4');
await page.keyboard.press('Enter');
await settings();
await switchFor('Table formulas').check();
await closeSettings();
await page.waitForFunction(() => document.querySelector('.md-table-formula')?.textContent === '8');
await page.getByRole('group', { name: 'Document view', exact: true }).getByRole('button', { pressed: true }).press('ArrowRight');
const preview = page.locator('.md-page table').first();
await preview.locator('.md-table-formula').waitFor();
await settings();
await switchFor('Table formulas').uncheck();
await closeSettings();
await page.waitForFunction(() => !document.querySelector('.md-page .md-table-formula'));
assert.match(await preview.innerText(), /=A2\*4/);
await settings();
await switchFor('Table formulas').check();
await closeSettings();
await preview.locator('.md-table-formula').waitFor();
assert.equal(await preview.locator('.md-table-formula').innerText(), '8');
await page.keyboard.press('Control+s');
await page.waitForFunction(() => window.__TEST__.files.get('formulas.md').includes('=A2*4'));
assert(!await page.evaluate(() => window.__TEST__.files.get('formulas.md').includes('>8<')));
const source = '# Formulas\n\n| A | B |\n| --- | --- |\n| 2 | =A2*3 |\n\nAfter.\n';
const table = page.locator('.live-writer table');
const dialog = settingsPage.getByRole('dialog', { name: 'Settings', exact: true });
const switchFor = name => dialog.getByRole('switch', { name, exact: true });
async function settings() {
await page.getByRole('button', { name: 'Settings (Ctrl+,)', exact: true }).click();
await settingsPage.goto((process.env.SMOKE_URL || 'http://127.0.0.1:1420') + '/?settingsWindow=true');
await dialog.getByRole('button', { name: 'Plug-ins', exact: true }).click();
}
async function closeSettings() {
await settingsPage.waitForFunction(() => [...document.querySelectorAll('input[role="switch"]')].every(input => !input.disabled));
await settingsPage.goto((process.env.SMOKE_URL || 'http://127.0.0.1:1420') + '/__settings-closed');
await page.bringToFront();
}
const count = command => page.evaluate(command => window.__TEST__.calls.filter(call => call.command === command).length, command);
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await page.getByText('smoke-workspace', { exact: true }).waitFor();
await page.evaluate(text => window.__TEST__.files.set('formulas.md', text), source);
await quickOpen('formulas.md');
await table.waitFor();
assert.equal(await table.locator('.md-table-formula').innerText(), '6');
await settings();
await switchFor('Table formulas').uncheck();
await closeSettings();
await page.waitForFunction(() => !document.querySelector('.md-table-formula'));
assert.match(await table.innerText(), /=A2\*3/);
assert.equal(await page.locator('.table-formula-tools').count(), 0);
await table.locator('td').last().click();
await page.locator('.writer-cell-editor').fill('=A2*4');
await page.keyboard.press('Enter');
await settings();
await switchFor('Table formulas').check();
await closeSettings();
await page.waitForFunction(() => document.querySelector('.md-table-formula')?.textContent === '8');
await page.getByRole('group', { name: 'Document view', exact: true }).getByRole('button', { pressed: true }).press('ArrowRight');
const preview = page.locator('.md-page table').first();
await preview.locator('.md-table-formula').waitFor();
await settings();
await switchFor('Table formulas').uncheck();
await closeSettings();
await page.waitForFunction(() => !document.querySelector('.md-page .md-table-formula'));
assert.match(await preview.innerText(), /=A2\*4/);
await settings();
await switchFor('Table formulas').check();
await closeSettings();
await preview.locator('.md-table-formula').waitFor();
assert.equal(await preview.locator('.md-table-formula').innerText(), '8');
await page.keyboard.press('Control+s');
await page.waitForFunction(() => window.__TEST__.files.get('formulas.md').includes('=A2*4'));
assert(!await page.evaluate(() => window.__TEST__.files.get('formulas.md').includes('>8<')));
await page.getByRole('button', { name: 'Terminal', exact: true }).click();
await page.waitForFunction(ptyCalled, 'pty_open');
await settings();
await switchFor('Terminal').uncheck();
await page.waitForFunction(ptyCalled, 'pty_close');
await settingsPage.screenshot({ path: path.join(output, 'plugins-settings.png') });
await closeSettings();
assert.equal(await page.getByRole('button', { name: 'Terminal', exact: true }).count(), 0);
const opened = await count('pty_open');
await page.keyboard.press('Control+j');
assert.equal(await count('pty_open'), opened);
await page.reload();
await page.getByText('smoke-workspace', { exact: true }).waitFor();
assert.equal(await page.getByRole('button', { name: 'Terminal', exact: true }).count(), 0);
await settings();
assert(!await switchFor('Terminal').isChecked());
await page.getByRole('button', { name: 'Terminal', exact: true }).click();
await page.waitForFunction(() => window.__TEST__.calls.some(call => call.command === 'pty_open'));
await settings();
await switchFor('Terminal').uncheck();
await page.waitForFunction(() => window.__TEST__.calls.some(call => call.command === 'pty_close'));
await settingsPage.screenshot({ path: '.audit/plugins-settings.png' });
await closeSettings();
assert.equal(await page.getByRole('button', { name: 'Terminal', exact: true }).count(), 0);
const opened = await count('pty_open');
await page.keyboard.press('Control+j');
assert.equal(await count('pty_open'), opened);
await page.reload();
await page.getByText('smoke-workspace', { exact: true }).waitFor();
assert.equal(await page.getByRole('button', { name: 'Terminal', exact: true }).count(), 0);
await settings();
assert(!await switchFor('Terminal').isChecked());
const standalone = await page.context().newPage();
await standalone.goto((process.env.SMOKE_URL || 'http://127.0.0.1:1420') + '?terminalWindow=C%3A%5Csmoke-workspace');
await standalone.getByText(/Install and enable the Terminal plugin/).waitFor();
await switchFor('Terminal').check();
await standalone.locator('.xterm').waitFor();
await standalone.waitForFunction(() => window.__TEST__.calls.some(call => call.command === 'pty_open'));
await switchFor('Terminal').uncheck();
await standalone.getByText(/Install and enable the Terminal plugin/).waitFor();
await standalone.waitForFunction(() => window.__TEST__.calls.some(call => call.command === 'pty_close'));
await standalone.close();
await switchFor('Terminal').check();
await closeSettings();
await page.getByRole('button', { name: 'Terminal', exact: true }).click();
await page.locator('.xterm').waitFor();
await page.evaluate(text => window.__TEST__.files.set('formulas.md', text.replace('=A2*3', '=A2*4')), source);
await page.getByRole('button', { name: 'Terminal', exact: true }).focus();
await quickOpen('formulas.md');
await settings();
assert.equal(await dialog.getByRole('heading', { name: 'Bundled plugins' }).count(), 0);
for (const name of ['Terminal', 'Table formulas']) {
await settingsPage.waitForFunction(() => [...document.querySelectorAll('input[role="switch"]')].every(input => !input.disabled));
await dialog.locator('.card').filter({ has: settingsPage.getByRole('switch', { name, exact: true }) }).getByRole('button', { name: 'Uninstall', exact: true }).click();
const confirmation = settingsPage.getByRole('dialog', { name: `Uninstall ${name}?`, exact: true });
await confirmation.getByRole('button', { name: 'Uninstall and delete files', exact: true }).click();
await confirmation.waitFor({ state: 'hidden' });
await switchFor(name).waitFor({ state: 'detached' });
const standalone = await openPage(context);
await standalone.goto(smokeUrl + '?terminalWindow=C%3A%5Csmoke-workspace');
await standalone.getByText(/Install and enable the Terminal plugin/).waitFor();
await switchFor('Terminal').check();
await standalone.locator('.xterm').waitFor();
await standalone.waitForFunction(ptyCalled, 'pty_open');
await switchFor('Terminal').uncheck();
await standalone.getByText(/Install and enable the Terminal plugin/).waitFor();
await standalone.waitForFunction(ptyCalled, 'pty_close');
page.errors.push(...standalone.errors);
await standalone.close();
await switchFor('Terminal').check();
await closeSettings();
await page.getByRole('button', { name: 'Terminal', exact: true }).click();
await page.locator('.xterm').waitFor();
await page.evaluate(text => window.__TEST__.files.set('formulas.md', text.replace('=A2*3', '=A2*4')), source);
await page.getByRole('button', { name: 'Terminal', exact: true }).focus();
await quickOpen('formulas.md');
await settings();
assert.equal(await dialog.getByRole('heading', { name: 'Bundled plugins' }).count(), 0);
for (const name of ['Terminal', 'Table formulas']) {
await settingsPage.waitForFunction(() => [...document.querySelectorAll('input[role="switch"]')].every(input => !input.disabled));
await dialog.locator('.card').filter({ has: settingsPage.getByRole('switch', { name, exact: true }) }).getByRole('button', { name: 'Uninstall', exact: true }).click();
const confirmation = settingsPage.getByRole('dialog', { name: `Uninstall ${name}?`, exact: true });
await confirmation.getByRole('button', { name: 'Uninstall and delete files', exact: true }).click();
await confirmation.waitFor({ state: 'hidden' });
await switchFor(name).waitFor({ state: 'detached' });
}
await closeSettings();
await page.waitForFunction(() => !document.querySelector('.md-table-formula') && !document.querySelector('.xterm'));
assert.equal(await page.getByRole('button', { name: 'Terminal', exact: true }).count(), 0);
assert.match(await table.innerText(), /=A2\*4/);
await page.reload();
await page.getByText('smoke-workspace', { exact: true }).waitFor();
await settings();
await dialog.getByText('No plugins installed.', { exact: true }).waitFor();
assert.deepEqual([...page.errors, ...settingsPage.errors], []);
} catch (error) {
await settingsPage.screenshot({ path: path.join(output, 'plugins-settings-failure.png') });
console.log('Settings page:', settingsPage.url(), await settingsPage.locator('body').innerText());
await page.screenshot({ path: path.join(output, 'plugins-failure.png') });
console.log(await page.locator('.md-page').allTextContents());
console.log([...page.errors, ...settingsPage.errors]);
throw error;
}
await closeSettings();
await page.waitForFunction(() => !document.querySelector('.md-table-formula') && !document.querySelector('.xterm'));
assert.equal(await page.getByRole('button', { name: 'Terminal', exact: true }).count(), 0);
assert.match(await table.innerText(), /=A2\*4/);
await page.reload();
await page.getByText('smoke-workspace', { exact: true }).waitFor();
await settings();
await dialog.getByText('No plugins installed.', { exact: true }).waitFor();
assert.deepEqual(errors, []);
console.log('Plugin smoke passed: formulas, source preservation, terminal shutdown, persistence, shortcuts, cross-window enable controls, removal, and no automatic restoration.');
} catch (error) {
await settingsPage.screenshot({ path: ".audit/plugins-settings-failure.png" });
console.log("Settings page:", settingsPage.url(), await settingsPage.locator('body').innerText());
await page.screenshot({ path: ".audit/plugins-failure.png" });
console.log(await page.locator('.md-page').allTextContents());
console.log(errors);
throw error;
} finally { await browser.close(); }
});
@@ -1,165 +0,0 @@
import { createRequire } from 'node:module';
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 context = await browser.newContext({ viewport: { width: 1200, height: 850 } });
const page = await context.newPage();
const errors = [];
page.on('pageerror', error => errors.push(error.message));
await context.addInitScript(() => {
window.isTauri = true;
const root = 'C:\\host-todo-test';
const files = new Map([['a.md', '# Note\n\nOriginal text.'], ['.runestone/templates/Daily.md', '# Daily\n\n## Tasks'], ['.runestone/marks.json', JSON.stringify({ pins: ['a.md'], bookmarks: ['a.md'], order: { '': ['a.md'] } })]]);
const state = { files, calls: [], exportResult: 'C:\\exports\\my-theme.json', exportError: '' };
window.__HOST_TEST__ = state;
let sequence = 0;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
transformCallback: () => ++sequence, unregisterCallback: () => {},
invoke: async (command, args = {}) => {
state.calls.push({ command, args });
if (command === 'plugins_snapshot') return { root: 'C:/plugins', plugins: [] };
if (command === 'workspace_last_path') return root;
if (command === 'workspace_open') return { root, name: 'host-todo-test', watch_mode: 'native' };
if (command === 'workspace_read') { if (!files.has(args.rel)) throw new Error('Missing file'); return files.get(args.rel); }
if (command === 'workspace_list') {
const prefix = args.rel ? args.rel + '/' : '';
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || (!args.rel && path.startsWith('.runestone/'))) continue;
const tail = path.slice(prefix.length), name = tail.split('/')[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes('/') ? 'folder' : 'file' });
}
return [...entries.values()];
}
if (command === 'workspace_create') { if (files.has(args.rel)) throw new Error('Destination exists'); files.set(args.rel, ''); return; }
if (command === 'workspace_write') {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error('Changed on disk');
files.set(args.rel, args.contents); return;
}
if (command === 'workspace_rename') {
if (files.has(args.to)) throw new Error('Destination exists');
if (!files.has(args.from)) throw new Error('Missing file');
files.set(args.to, files.get(args.from)); files.delete(args.from); return;
}
if (command === 'workspace_delete') { files.delete(args.rel); return; }
if (command === 'workspace_search') return [];
if (command === 'plugin:event|listen') return ++sequence;
if (command === 'plugin:window|is_maximized') return false;
if (command === 'plugin:dialog|message') return 'Ok';
if (command === 'theme_export') { if (state.exportError) throw new Error(state.exportError); return state.exportResult; }
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const origin = process.env.SMOKE_URL || 'http://127.0.0.1:5173';
const row = path => page.locator(`[data-tree-rel="${path}"]`);
const item = name => page.getByRole('menuitem', { name, exact: true });
async function paneMenu() { await page.getByRole('navigation', { name: 'Workspace files' }).click({ button: 'right', position: { x: 90, y: 360 } }); }
await mkdir('output/host-todo', { recursive: true });
try {
await page.goto(origin);
await row('a.md').waitFor();
await page.getByRole('button', { name: 'New file Ctrl N' }).click();
await page.getByRole('textbox', { name: 'New file path relative to the workspace' }).waitFor();
await page.mouse.click(5, 700);
assert.equal(await page.locator('dialog').count(), 0, 'Outside click dismisses new-file dialog');
await page.getByRole('button', { name: 'Find a file Ctrl P' }).click();
await page.getByRole('textbox', { name: 'Find a file' }).click();
assert.equal(await page.locator('dialog').count(), 1, 'Inside click keeps file search open');
await page.mouse.click(5, 700);
assert.equal(await page.locator('dialog').count(), 0, 'Outside click dismisses file search');
await row('a.md').click({ button: 'right' });
assert.equal(await item('Copy path').count(), 0);
assert.equal(await item('Copy system path').count(), 1);
await item('Rename').click();
await page.locator('.tree input').fill('renamed.md');
await page.locator('.tree input').press('Enter');
await row('renamed.md').waitFor();
await row('renamed.md').click({ button: 'right' });
assert.equal(await item('Undo rename').count(), 1);
await page.keyboard.press('Escape');
await row('renamed.md').focus(); await page.keyboard.press('Control+z');
await row('a.md').waitFor();
assert.deepEqual(await page.evaluate(() => JSON.parse(window.__HOST_TEST__.files.get('.runestone/marks.json')).pins), ['a.md']);
await row('a.md').focus(); await page.keyboard.press('Control+y');
await row('renamed.md').waitFor();
await paneMenu(); await item('New note').hover();
await item('Daily').click();
await row('Daily.md').waitFor();
assert.equal(await page.evaluate(() => window.__HOST_TEST__.files.get('Daily.md')), '# Daily\n\n## Tasks');
await paneMenu(); await item('New note').hover(); await item('Manage templates…').click();
await page.getByRole('button', { name: 'Rename Daily', exact: true }).click();
await page.getByRole('textbox', { name: 'Template name', exact: true }).fill('Weekly');
await page.getByRole('button', { name: 'Continue', exact: true }).click();
await page.getByRole('button', { name: 'Edit Weekly', exact: true }).waitFor();
await page.evaluate(() => window.__HOST_TEST__.files.set('.runestone/templates/Existing.md', '# Keep this template'));
await page.getByRole('button', { name: 'Rename Weekly', exact: true }).click();
await page.getByRole('textbox', { name: 'Template name', exact: true }).fill('Existing');
await page.getByRole('button', { name: 'Continue', exact: true }).click();
await page.getByRole('alert').filter({ hasText: 'Destination exists' }).waitFor();
assert.equal(await page.evaluate(() => window.__HOST_TEST__.files.get('.runestone/templates/Existing.md')), '# Keep this template');
for (const mode of ['light', 'dark']) {
await page.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); }, mode);
await page.screenshot({ path: `output/host-todo/templates-${mode}.png` });
}
await page.getByRole('button', { name: 'Edit Weekly', exact: true }).click();
await page.getByRole('tab', { name: 'Weekly.md', exact: true }).waitFor();
await paneMenu(); await item('New note').hover(); await item('Manage templates…').click();
await page.getByRole('button', { name: 'New template', exact: true }).click();
await page.getByRole('textbox', { name: 'Template name', exact: true }).fill('Meeting');
await page.getByRole('button', { name: 'Continue', exact: true }).click();
await page.getByRole('tab', { name: 'Meeting.md', exact: true }).waitFor();
assert.equal(await page.evaluate(() => window.__HOST_TEST__.files.get('.runestone/templates/Meeting.md')), '');
await paneMenu(); await item('New note').hover(); await item('Manage templates…').click();
await page.getByRole('button', { name: 'Delete Weekly', exact: true }).click();
await page.getByRole('button', { name: 'Edit Weekly', exact: true }).waitFor({ state: 'detached' });
assert.equal(await page.evaluate(() => window.__HOST_TEST__.files.get('Daily.md')), '# Daily\n\n## Tasks', 'Deleting template preserves notes');
await page.getByRole('button', { name: 'Close templates', exact: true }).click();
await page.evaluate(() => { for (let i = 0; i < 40; i++) window.__HOST_TEST__.files.set(`.runestone/templates/Long template name ${i}.md`, '# Template'); });
await page.setViewportSize({ width: 600, height: 600 });
await paneMenu(); await item('New note').hover(); await item('Manage templates…').click();
assert.ok(await page.locator('dialog .list').evaluate(node => node.scrollHeight > node.clientHeight), 'Long template list scrolls');
await page.screenshot({ path: 'output/host-todo/templates-narrow-long.png' });
await page.getByRole('button', { name: 'Close templates', exact: true }).click();
await page.setViewportSize({ width: 1200, height: 850 });
const settings = await context.newPage(); settings.on('pageerror', error => errors.push(error.message));
await settings.goto(origin + '/?settingsWindow=true');
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
await settings.getByRole('button', { name: 'Export theme template' }).click();
await settings.getByRole('status').filter({ hasText: 'Theme saved to' }).waitFor();
assert.equal(await settings.evaluate(() => JSON.parse(window.__HOST_TEST__.calls.find(call => call.command === 'theme_export').args.contents).schema), 1);
await settings.evaluate(() => window.__HOST_TEST__.exportResult = null);
await settings.getByRole('button', { name: 'Export theme template' }).click();
await settings.getByText('Export canceled.', { exact: true }).waitFor();
await settings.evaluate(() => window.__HOST_TEST__.exportError = 'Disk is full');
await settings.getByRole('button', { name: 'Export theme template' }).click();
await settings.getByRole('alert').filter({ hasText: 'Disk is full' }).waitFor();
await settings.getByRole('button', { name: 'Color theme', exact: true }).click();
await settings.getByRole('menuitemradio', { name: 'RuneStone', exact: true }).focus();
await settings.keyboard.press('ArrowDown'); await settings.keyboard.press('Enter');
assert.equal(await settings.evaluate(() => document.documentElement.dataset.palette), 'claude');
assert.equal(await settings.locator('input[type=color]').count(), 0);
await page.getByRole('button', { name: 'New tab (Ctrl T)', exact: true }).click();
await page.locator('.empty').waitFor();
await page.waitForFunction(() => document.documentElement.dataset.palette === 'claude');
assert.equal(await page.locator('.empty').evaluate(node => { const reference = document.createElement('span'); reference.style.color = 'var(--rs-bg)'; node.append(reference); const matches = getComputedStyle(node).backgroundColor === getComputedStyle(reference).color; reference.remove(); return matches; }), true);
await settings.getByLabel('Background image file', { exact: true }).setInputFiles({ name: 'test.png', mimeType: 'image/png', buffer: Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=', 'base64') });
await page.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('blob:'));
await page.reload(); await page.locator('.empty').waitFor();
assert.ok(await page.locator('.empty').evaluate(node => getComputedStyle(node).backgroundImage.includes('blob:')), 'Background survives restart');
await settings.getByRole('button', { name: 'Remove image', exact: true }).click();
await page.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage === 'none');
for (const mode of ['light', 'dark']) {
await settings.evaluate(async mode => { const { saveAppearance, parseAppearance, APPEARANCE_KEY } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ ...parseAppearance(localStorage.getItem(APPEARANCE_KEY)), theme: 'default', mode }); window.dispatchEvent(new Event('focus')); }, mode);
await settings.setViewportSize({ width: 650, height: 760 });
await settings.screenshot({ path: `output/host-todo/appearance-${mode}-narrow.png` });
}
assert.equal(await settings.getByRole('button', { name: 'Reset background', exact: true }).isDisabled(), true);
await page.waitForFunction(() => !JSON.parse(localStorage.getItem('runestone.appearance')).newTabBackground);
assert.deepEqual(errors, []);
console.log('Host To Do: dialog dismissal, rename undo/redo with marks, template creation/rename/edit/delete, theme export success/cancel/error, shared theme menu, background persistence/reset passed.');
} finally { await browser.close(); }
@@ -1,116 +0,0 @@
// @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 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 });
try {
for (const theme of ['light', 'dark']) {
const page = await browser.newPage({ viewport: { width: 1100, height: 780 } });
const errors = [];
page.on('pageerror', error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } }, transformCallback: () => 1, unregisterCallback() {},
invoke: async (command, args = {}) => {
if (command === 'workspace_last_path') return 'C:/todo-ui';
if (command === 'workspace_open') return { root: 'C:/todo-ui', name: 'todo-ui', watch_mode: 'native' };
if (command === 'workspace_list') return [{ name: 'sample.md', rel_path: 'sample.md', kind: 'file' }];
if (command === 'workspace_read') return '# Selection sample\n\nThe same text color applies to each editor.\n';
if (command === 'plugins_snapshot') return { root: 'C:/plugins', plugins: [] };
if (command === 'workspace_search') return [];
if (command === 'browser_request') {
if (args.command === 'frameAck') window.blankAcks = (window.blankAcks || 0) + 1;
return window.browserSnapshot;
}
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener() {} };
});
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await page.getByText('todo-ui', { exact: true }).waitFor();
await page.evaluate(async theme => {
const { saveAppearance } = await import('/src/lib/theme/appearance.ts');
saveAppearance({ theme: 'default', mode: theme });
const { attachTooltip } = await import('/src/lib/ui/tooltip.ts');
const cell = document.createElement('button');
cell.id = 'tooltip-test'; cell.textContent = 'Formula cell';
Object.assign(cell.style, { position: 'fixed', left: '20px', top: '100px', zIndex: '2000' });
document.body.append(cell);
window.disposeTip = attachTooltip(cell, () => 'B6 · Click to edit · Type = for a formula');
}, theme);
const target = page.locator('#tooltip-test');
await target.hover();
const tooltip = page.locator('.rs-tooltip:popover-open');
await tooltip.waitFor();
assert.equal(await target.getAttribute('title'), null);
assert.equal(await tooltip.evaluate(node => getComputedStyle(node).borderRadius), '5px');
await page.screenshot({ path: `${output}/${theme}-tooltip.png` });
await page.keyboard.press('Escape');
assert.equal(await page.locator('.rs-tooltip:popover-open').count(), 0);
await target.focus();
await tooltip.waitFor();
await page.setViewportSize({ width: 390, height: 620 });
await page.locator('header').first().hover();
await target.hover();
await tooltip.waitFor();
const bounds = await tooltip.boundingBox();
assert(bounds.x >= 8 && bounds.x + bounds.width <= 382);
await page.screenshot({ path: `${output}/${theme}-narrow-tooltip.png` });
await page.evaluate(() => { window.disposeTip(); document.getElementById('tooltip-test').remove(); });
await page.setViewportSize({ width: 1100, height: 780 });
await page.keyboard.press('Control+p');
await page.getByRole('textbox', { name: 'Find a file' }).fill('sample.md');
await page.getByRole('textbox', { name: 'Find a file' }).press('Enter');
const writer = page.getByRole('textbox', { name: 'Writing editor', exact: true });
await writer.waitFor(); await writer.click(); await page.keyboard.press('Control+a');
const colors = await writer.evaluate(node => {
const probe = document.createElement('span'); probe.style.backgroundColor = 'var(--rs-selection)'; node.append(probe);
const expected = getComputedStyle(probe).backgroundColor; probe.remove();
return { expected, native: getComputedStyle(node, '::selection').backgroundColor,
layer: getComputedStyle(document.querySelector('.cm-selectionBackground')).backgroundColor };
});
assert.equal(colors.native, colors.expected); assert.equal(colors.layer, colors.expected);
await page.screenshot({ path: `${output}/${theme}-writer-selection.png` });
await page.getByRole('group', { name: 'Document view', exact: true }).hover();
await page.getByRole('button', { name: 'Read', exact: true }).click();
const reader = page.locator('.reading');
await reader.waitFor();
assert.equal(await reader.evaluate(node => getComputedStyle(node, '::selection').backgroundColor), colors.expected);
await page.evaluate(async () => {
const { mount } = await import('/node_modules/svelte/src/index-client.js');
const { default: Browser } = await import('/src/lib/browser/Browser.svelte');
const client = await import('/src/lib/browser/client.ts');
const container = document.createElement('div'); container.id = 'browser-test';
Object.assign(container.style, { position: 'fixed', inset: '50px 10px 20px', zIndex: '2000', background: 'linear-gradient(120deg,#945975,#395c72)' });
document.body.append(container);
window.browserSnapshot = { profiles: [{ id: 'user', name: 'User' }], tabs: [{ id: 'blank', profileId: 'user', url: 'about:blank', title: '', loading: false }], bookmarks: [], settings: {} };
client.state.set(window.browserSnapshot);
mount(Browser, { target: container, props: { initial: { tabId: 'blank' }, onSessionChange() {}, async newTab() {} } });
window.browserClient = client;
});
const surface = page.locator('#browser-test .surface');
await page.locator('#browser-test [data-browser-state="ready"]').waitFor();
await page.evaluate(() => window.browserClient.frames.get('blank')({ tabId: 'blank', frameId: 1, width: 10, height: 10, mime: 'image/png', data: 'AA==' }));
assert.equal(await surface.evaluate(node => getComputedStyle(node).backgroundColor), 'rgba(0, 0, 0, 0)');
assert.equal(await surface.locator('img').count(), 0);
assert.equal(await page.evaluate(() => window.blankAcks), 1);
await page.screenshot({ path: `${output}/${theme}-blank-browser.png` });
await page.evaluate(() => {
window.browserSnapshot.tabs[0].url = 'https://example.com/minimal';
window.browserClient.state.set({ ...window.browserSnapshot });
const canvas = document.createElement('canvas'); canvas.width = 10; canvas.height = 10;
const ctx = canvas.getContext('2d'); ctx.fillStyle = 'white'; ctx.fillRect(0, 0, 10, 10);
window.browserClient.frames.get('blank')({ tabId: 'blank', frameId: 2, width: 10, height: 10, mime: 'image/png', data: canvas.toDataURL().split(',')[1] });
});
await surface.locator('img').waitFor();
assert.notEqual(await surface.evaluate(node => getComputedStyle(node).backgroundColor), 'rgba(0, 0, 0, 0)');
assert.deepEqual(errors, []);
await page.close();
}
console.log('To do UI smoke passed: tooltips, selection, blank browser, light/dark/narrow.');
} finally { await browser.close(); }
@@ -1,163 +0,0 @@
// @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";
import { resolve } from "node:path";
import assert from "node:assert/strict";
const { chromium } = createRequire(import.meta.url)(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: 1440, height: 1000 } });
const page = await context.newPage();
page.setDefaultTimeout(15000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false }));
const root = "C:\\kanban-root-smoke";
const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="100" height="80"><rect width="100" height="80" fill="#639"/></svg>';
const files = new Map([
["notes/draft.md", "Before.\n\nAfter.\n"],
["files/report [Q1] (#1).pdf", "PDF fixture"],
["images/diagram (#1).svg", btoa(svg)],
]);
const calls = [], callbacks = new Map(), listeners = new Map(); let sequence = 0;
window.kanbanRootSmoke = { files, calls };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback(callback) { callbacks.set(++sequence, callback); return sequence; },
unregisterCallback(id) { callbacks.delete(id); },
async invoke(command, args = {}) {
calls.push({ command, args });
if (command === "plugin:event|listen") { const values = listeners.get(args.event) || []; values.push(args.handler); listeners.set(args.event, values); return args.handler; }
if (command === "plugin:event|unlisten" || command === "spelling_menu_install" || command === "spelling_menu_uninstall") return;
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "kanban-root-smoke", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw Error("File missing"); return files.get(args.rel); }
if (command === "workspace_read_data_url") return "data:image/svg+xml;base64," + files.get(args.rel);
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw Error("Save conflict");
files.set(args.rel, args.contents); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "", entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length), name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_search") return [];
if (command === "workspace_recent") return [root];
if (command === "plugins_snapshot") return { plugins: [], issues: [] };
if (command === "plugin:dialog|message") return "Cancel";
if (command.startsWith("plugin:window|") || command === "browser_stop") return;
throw Error("Unhandled IPC: " + command);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener() {} };
});
const row = path => page.locator(`[data-tree-rel="${path}"]`);
async function drag(path, target) {
const from = await row(path).boundingBox(), to = await page.locator(target).boundingBox();
assert.ok(from && to, "The file and editor must be visible");
await page.mouse.move(from.x + Math.min(80, from.width / 2), from.y + from.height / 2);
await page.mouse.down();
await page.mouse.move(to.x + 45, to.y + 12, { steps: 15 });
await page.locator(".image-drop-target").waitFor();
await page.mouse.up();
}
async function writerSource() { return page.evaluate(() => window.kanbanWriter.state.doc.toString()); }
async function ideSource() {
return page.evaluate(async () => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
return monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected)?.getValue();
});
}
try {
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:5173");
await row("notes").click(); await row("notes/draft.md").dblclick();
await page.locator(".cm-content").waitFor();
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
window.kanbanWriter = EditorView.findFromDOM(document.querySelector(".cm-content"));
});
await row("files").click();
const original = await writerSource();
await drag("files/report [Q1] (#1).pdf", ".cm-content");
await page.waitForFunction(() => window.kanbanWriter.state.doc.toString().includes(".pdf)"));
const linked = await writerSource();
assert.ok(linked.includes("[report \\[Q1\\] (#1).pdf](../files/report%20%5BQ1%5D%20%28%231%29.pdf)"), linked);
assert.ok(!linked.includes("!["), "A document must be a link, not an image");
await page.evaluate(() => window.kanbanWriter.focus()); await page.keyboard.press("Control+z");
assert.equal(await writerSource(), original, "Writer undo restores the exact source");
await row("images").click();
await drag("images/diagram (#1).svg", ".cm-content");
await page.locator(".md-image-frame img").waitFor();
assert.ok((await writerSource()).includes("![](../images/diagram%20%28%231%29.svg)"));
await page.evaluate(() => window.kanbanWriter.focus()); await page.keyboard.press("Control+z");
assert.equal(await writerSource(), original);
await page.keyboard.press("Control+e");
await page.locator(".monaco-editor textarea").waitFor();
const originalIde = await ideSource();
await page.evaluate(async () => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
const editor = monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected);
window.kanbanMonaco = editor;
});
await drag("files/report [Q1] (#1).pdf", ".monaco-editor .view-lines");
await page.waitForFunction(() => window.kanbanMonaco.getValue().includes(".pdf)"));
assert.ok((await ideSource()).includes("[report \\[Q1\\] (#1).pdf](../files/report%20%5BQ1%5D%20%28%231%29.pdf)"));
await page.evaluate(() => window.kanbanMonaco.focus());
assert.equal(await page.evaluate(() => window.kanbanMonaco.hasTextFocus()), true);
await page.keyboard.press("Control+z");
await page.waitForFunction(expected => window.kanbanMonaco.getValue() === expected, originalIde, { timeout: 3000 });
assert.equal(await ideSource(), originalIde, "IDE undo restores the exact source");
await drag("images/diagram (#1).svg", ".monaco-editor .view-lines");
assert.ok((await ideSource()).includes("![](../images/diagram%20%28%231%29.svg)"));
assert.equal(await page.evaluate(() => window.kanbanRootSmoke.calls.filter(call => ["workspace_rename", "workspace_write_bytes"].includes(call.command)).length), 0);
console.log("PASS: real FileTree pointer drags insert escaped document links in Writer and IDE, undo restores both, and image drags still embed.");
// Load current Git source through the host origin without creating a distributable.
const gitRoot = process.env.RUNESTONE_GIT_ROOT || resolve("../RuneStone_Git");
const sources = new Map(await Promise.all(["view.js", "model.js"].map(async file => [file, await readFile(resolve(gitRoot, "src", file), "utf8")])));
await page.route("**/__kanban_git/*", route => route.fulfill({ contentType: "text/javascript", body: sources.get(new URL(route.request().url()).pathname.split("/").pop()) || "" }));
const css = await readFile(resolve(gitRoot, "src/style.css"), "utf8");
await page.evaluate(async css => {
const { mountSidebar } = await import("/__kanban_git/view.js");
const container = document.createElement("div"); container.id = "git-smoke"; container.style.cssText = "position:fixed;inset:45px 0 0 0;z-index:1000;background:var(--rs-bg)";
document.body.append(container);
window.gitGraphOpens = 0;
window.disposeGitSmoke = mountSidebar(container, {
workspace: {},
git: { status: async () => ({ available: true, repository: true, branch: "main", changes: [] }), pull: async () => {}, push: async () => {} },
openView: () => window.gitGraphOpens++,
}, css, () => {});
}, css);
const graph = page.locator("#git-smoke").getByRole("button", { name: "Graph", exact: true });
for (const theme of ["dark", "light"]) {
await page.evaluate(async mode => { const { saveAppearance } = await import("/src/lib/theme/appearance.ts"); saveAppearance({ theme: "default", mode }); }, theme);
await graph.waitFor();
assert.equal(await graph.locator("svg").count(), 1);
assert.equal(await graph.getAttribute("title"), "Graph");
assert.equal(await graph.evaluate(node => [...node.childNodes].filter(child => child.nodeType === Node.TEXT_NODE && child.textContent.trim()).length), 0);
assert.equal(await graph.locator(":scope > :not(.rs-git-icon):not(.rs-git-tooltip)").count(), 0, "Graph has no visible text label");
await page.mouse.move(800, 800); await graph.evaluate(node => node.blur());
assert.equal(await graph.locator(".rs-git-tooltip").isVisible(), false);
await graph.hover(); await graph.locator(".rs-git-tooltip").waitFor({ state: "visible" });
await page.mouse.move(800, 800); await page.keyboard.press("Tab"); await graph.focus();
assert.equal(await graph.evaluate(node => node.matches(":focus-visible")), true);
await graph.locator(".rs-git-tooltip").waitFor({ state: "visible" });
await mkdir(".audit", { recursive: true });
await page.screenshot({ path: `.audit/kanban-git-toolbar-${theme}.png` });
}
await graph.click(); assert.equal(await page.evaluate(() => window.gitGraphOpens), 1);
await page.evaluate(() => window.disposeGitSmoke());
assert.deepEqual(errors, []);
console.log("PASS: current Git Graph toolbar control is icon-only, keeps its accessible name, shows hover and focus tooltips in both themes, and opens Graph.");
} catch (error) {
await mkdir(".audit", { recursive: true });
await page.screenshot({ path: ".audit/kanban-root-failure.png" });
console.error(errors); throw error;
} finally { await browser.close(); }
@@ -1,152 +0,0 @@
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 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(() => {
window.isTauri = true;
const root = 'C:\\kanban-smoke';
const files = new Map([['a.md', '# Alpha\n\nTemplate body.\n'], ['b.md', '# Beta\n'], ['folder/keep.md', '# Keep\n'], ['.runestone/config.json', '{}']]);
const calls = [], callbacks = new Map(); let id = 0;
window.workspaceSmoke = { files, calls, transfer: null };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
transformCallback: callback => { callbacks.set(++id, callback); return id; }, unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === 'plugin:event|listen') return ++id;
if (command === 'plugin:event|unlisten' || command === 'spelling_menu_install' || command === 'spelling_menu_uninstall') return;
if (command === 'workspace_last_path') return root;
if (command === 'workspace_open') return { root, name: 'kanban-smoke', watch_mode: 'native' };
if (command === 'workspace_read') { if (!files.has(args.rel)) throw Error('File missing'); return files.get(args.rel); }
if (command === 'workspace_write') {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw Error('Save conflict');
files.set(args.rel, args.contents); return;
}
if (command === 'workspace_create') { if (files.has(args.rel)) throw Error('Exists'); files.set(args.rel, ''); return; }
if (command === 'workspace_list') {
const prefix = args.rel ? args.rel + '/' : ''; const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || (!args.rel && path.startsWith('.runestone/') && !args.showInternal)) continue;
const tail = path.slice(prefix.length), name = tail.split('/')[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes('/') ? 'folder' : 'file' });
}
return [...entries.values()];
}
if (command === 'workspace_rename') {
if (files.has(args.to)) throw Error('Destination exists');
const matches = [...files].filter(([path]) => path === args.from || path.startsWith(args.from + '/'));
if (!matches.length) throw Error('Source missing');
for (const [path, contents] of matches) { files.delete(path); files.set(args.to + path.slice(args.from.length), contents); }
return;
}
if (command === 'workspace_copy') {
const path = (args.parent ? args.parent + '/' : '') + args.rel.split('/').pop();
if (files.has(path)) throw Error('Destination exists');
files.set(path, files.get(args.rel)); return { rel_path: path, name: path.split('/').pop(), kind: 'file' };
}
if (command === 'workspace_open_window') { window.workspaceSmoke.transfer = args.transfer; return; }
if (command === 'workspace_abs_path') return root + '\\' + args.rel;
if (command === 'workspace_recent') return [root];
if (command === 'workspace_search') return [];
if (command === 'plugin:dialog|message') return 'Cancel';
if (command === 'plugins_snapshot') return { plugins: [], issues: [] };
if (command.startsWith('plugin:window|') || command === 'workspace_open_terminal' || command === 'workspace_open_default') return;
if (command === 'browser_stop') return;
throw Error('Unhandled IPC: ' + command);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener() {} };
});
const page = await context.newPage();
const errors = [];
page.on('pageerror', error => errors.push(error.message));
page.setDefaultTimeout(15000);
const url = process.env.SMOKE_URL || 'http://127.0.0.1:1420';
const row = path => page.locator(`[data-tree-rel="${path}"]`);
const menu = label => page.getByRole('menuitem', { name: label, exact: true });
try {
await page.goto(url);
await row('a.md').click();
await page.locator('.cm-content').waitFor();
await page.locator('.mode-switcher').first().hover();
await page.waitForFunction(() => document.querySelector('.mode-switcher')?.classList.contains('expanded'), null, { timeout: 500 });
await page.mouse.move(500, 400);
await row('a.md').click({ button: 'right' });
await menu('Save as template').click();
await page.getByRole('textbox', { name: 'Template name' }).fill('Meeting');
await page.getByRole('button', { name: 'Continue', exact: true }).click();
await page.waitForFunction(() => window.workspaceSmoke.files.has('.runestone/templates/Meeting.md'));
await page.getByRole('button', { name: 'New tab (Ctrl T)', exact: true }).click();
await page.getByRole('button', { name: 'New note', exact: true }).click();
await menu('Meeting').click();
await page.getByRole('tab', { name: /Meeting/ }).waitFor();
assert.equal(await page.evaluate(() => window.workspaceSmoke.files.get('Meeting.md')), '# Alpha\n\nTemplate body.\n');
const before = await page.getByRole('tab', { selected: true }).getAttribute('data-path');
await page.keyboard.press('Control+Tab');
assert.notEqual(await page.getByRole('tab', { selected: true }).getAttribute('data-path'), before);
await page.keyboard.press('Control+Shift+Tab');
assert.equal(await page.getByRole('tab', { selected: true }).getAttribute('data-path'), before);
await row('b.md').click({ button: 'right' }); await menu('Cut').click();
await row('folder').click({ button: 'right' }); await menu('Paste').click();
await page.waitForFunction(() => window.workspaceSmoke.files.has('folder/b.md'));
await row('folder').click({ button: 'right' }); await menu('Undo file move').click();
await page.waitForFunction(() => window.workspaceSmoke.files.has('b.md'));
await row('folder').click({ button: 'right' }); await menu('Redo file move').click();
await page.waitForFunction(() => window.workspaceSmoke.files.has('folder/b.md'));
await row('folder').focus();
await page.keyboard.press('Control+z');
await page.waitForFunction(() => window.workspaceSmoke.files.has('b.md'));
const sourceBox = await row('b.md').boundingBox(), folderBox = await row('folder').boundingBox();
await page.mouse.move(sourceBox.x + 50, sourceBox.y + sourceBox.height / 2);
await page.mouse.down();
await page.mouse.move(folderBox.x + 70, folderBox.y + folderBox.height / 2, { steps: 12 });
await page.mouse.up();
await page.waitForFunction(() => window.workspaceSmoke.files.has('folder/b.md'));
await page.keyboard.press('Control+z');
await page.waitForFunction(() => window.workspaceSmoke.files.has('b.md'));
await row('folder').click({ button: 'right' }); await menu('Open in terminal').click();
assert.ok(await page.evaluate(() => window.workspaceSmoke.calls.some(call => call.command === 'workspace_open_terminal' && call.args.rel === 'folder')));
await page.keyboard.press('Control+,');
const settingsPage = await context.newPage();
await settingsPage.goto(url + '/?settingsWindow=true');
await settingsPage.getByRole('switch', { name: 'Show .runestone folder' }).check();
await settingsPage.getByRole('button', { name: 'Appearance', exact: true }).click();
const theme = { schema: 1, id: 'smoke', name: 'Smoke theme', light: { bg: '#fefefe', text: '#222222', accent: '#334499' }, dark: { bg: '#181820', text: '#eeeeee', accent: '#aabbff' } };
await settingsPage.locator('input[type=file][aria-label="Theme JSON file"]').setInputFiles({ name: 'smoke.json', mimeType: 'application/json', buffer: Buffer.from(JSON.stringify(theme)) });
await settingsPage.waitForFunction(() => document.documentElement.dataset.palette === 'custom:smoke');
assert.equal(await settingsPage.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--rs-bg').trim()), '#181820');
await settingsPage.getByRole('combobox', { name: 'Appearance', exact: true }).selectOption('light');
assert.equal(await settingsPage.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--rs-bg').trim()), '#fefefe');
await mkdir('.audit', { recursive: true });
await settingsPage.screenshot({ path: '.audit/kanban-custom-theme-light.png' });
await settingsPage.close();
await row('.runestone').waitFor();
await page.getByRole('tab', { name: /Meeting/ }).click();
const editor = page.locator('.cm-content'); await editor.click(); await page.keyboard.press('Control+End'); await page.keyboard.type('Unsaved transfer');
await page.getByRole('tab', { name: /Meeting/ }).click({ button: 'right' });
await menu('Open in new window').click();
await page.waitForFunction(() => window.workspaceSmoke.transfer);
const token = await page.evaluate(() => window.workspaceSmoke.transfer);
const target = await context.newPage();
target.on('pageerror', error => errors.push(error.message));
await target.goto(url + '/?tabTransfer=' + token);
await target.getByRole('tab', { name: /Meeting/ }).waitFor();
await target.waitForFunction(() => document.querySelector('.cm-content')?.textContent.includes('Unsaved transfer'));
await page.getByRole('tab', { name: /Meeting/ }).waitFor({ state: 'detached' });
await page.evaluate(() => { window.workspaceSmoke.transfer = null; });
const draggedTab = page.getByRole('tab').first();
const draggedPath = await draggedTab.getAttribute('data-path');
const tabBox = await draggedTab.boundingBox();
await page.mouse.move(tabBox.x + tabBox.width / 2, tabBox.y + tabBox.height / 2);
await page.mouse.down();
await page.mouse.move(1480, 180, { steps: 12 });
await page.mouse.up();
await page.waitForFunction(() => window.workspaceSmoke.transfer);
assert.notEqual(await page.evaluate(() => window.workspaceSmoke.transfer), token);
assert.equal(await page.locator(`[role="tab"][data-path="${draggedPath}"]`).count(), 1, 'Keep the source tab until the new window accepts it');
assert.equal(errors.length, 0, errors.join('\n'));
console.log('PASS: templates, tab shortcuts, move undo/redo, terminal action, internal folder, theme import, and acknowledged unsaved tab transfer');
} finally { await browser.close(); }
+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(); }
});
+47 -117
View File
@@ -1,110 +1,50 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
// Table drag handles: hover and focus grips, previews, row and column moves, undo, cancellation, keyboard moves, and auto-scroll.
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
async function quickOpen(name) {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
await page.getByRole("group", { name: "Editor layout" }).locator("button.current").press("Home");
await page.locator(".monaco-editor textarea").waitFor();
}
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
const source = '# Drag tables\n\n| Name | Value | Notes |\n| :--- | ---: | :---: |\n| Alpha | 10 | **Bold**<br>second line |\n| Beta | 20 | Two |\n| Gamma | 30 | Three |\n| Delta | 40 | Four |\n\nAfter.\n';
const table = page.locator('.live-writer table');
const rows = () => table.locator('tbody tr td:first-child').allTextContents();
const headers = () => table.locator('th').allTextContents();
async function grip(axis, index) {
const handle = page.locator(`.table-drag-${axis}[data-index="${index}"]`);
await handle.scrollIntoViewIfNeeded();
const rect = await handle.boundingBox();
await page.mouse.move(rect.x + rect.width / 2, rect.y + rect.height / 2);
await page.mouse.down();
}
async function target(axis, index, after = false) {
const rect = await (axis === 'row' ? table.locator('tr').nth(index) : table.locator('th').nth(index)).boundingBox();
await page.mouse.move(axis === 'row' ? rect.x + 10 : rect.x + (after ? rect.width - 2 : 2), axis === 'row' ? rect.y + (after ? rect.height - 2 : 2) : rect.y + 10, { steps: 8 });
}
async function save() {
await page.keyboard.press('Control+s');
await page.waitForFunction(() => !document.querySelector('[aria-label^="Save changes"]'));
return page.evaluate(() => window.__TEST__.files.get('drag.md'));
}
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
const long = '# Long table\n\n| Item | Value |\n| --- | --- |\n' + Array.from({ length: 30 }, (_, i) => `| Item ${i + 1} | ${i + 1} |`).join('\n') + '\n\nAfter.\n';
await runSmoke("tables/drag", async ({ page }) => {
const output = await outputDir("tables/drag");
await mockTauri(page, {
state: { files: { 'drag.md': source, 'long.md': long } },
commands: test => {
const workspace = test.workspace({ root: "C:\\smoke-workspace", files: test.state.files, writeEvents: true });
test.files = workspace.files;
return workspace;
},
});
async function quickOpen(name) {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
await page.getByRole("group", { name: "Editor layout" }).locator("button.current").press("Home");
await page.locator(".monaco-editor textarea").waitFor();
}
const table = page.locator('.live-writer table');
const rows = () => table.locator('tbody tr td:first-child').allTextContents();
const headers = () => table.locator('th').allTextContents();
async function grip(axis, index) {
const handle = page.locator(`.table-drag-${axis}[data-index="${index}"]`);
await handle.scrollIntoViewIfNeeded();
const rect = await handle.boundingBox();
await page.mouse.move(rect.x + rect.width / 2, rect.y + rect.height / 2);
await page.mouse.down();
}
async function target(axis, index, after = false) {
const rect = await (axis === 'row' ? table.locator('tr').nth(index) : table.locator('th').nth(index)).boundingBox();
await page.mouse.move(axis === 'row' ? rect.x + 10 : rect.x + (after ? rect.width - 2 : 2), axis === 'row' ? rect.y + (after ? rect.height - 2 : 2) : rect.y + 10, { steps: 8 });
}
async function save() {
await page.keyboard.press('Control+s');
await page.waitForFunction(() => !document.querySelector('[aria-label^="Save changes"]'));
return page.evaluate(() => window.__TEST__.files.get('drag.md'));
}
await page.goto(smokeUrl);
await page.getByText('smoke-workspace', { exact: true }).waitFor();
await page.evaluate(text => {
window.__TEST__.files.set('drag.md', text);
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['drag.md'] });
}, source);
await quickOpen('drag.md');
await page.getByRole("group", { name: "Editor layout" }).locator("button.current").press("End");
await table.waitFor();
@@ -131,7 +71,7 @@ try {
assert.equal(await preview.locator('.table-drag-preview-label').innerText(), 'Row 2 → 5');
assert.equal(await table.locator('.is-cell-selected').count(), 3);
await page.locator('.table-drop-indicator:visible').waitFor();
await page.screenshot({ path: '.audit/table-drag-row.png' });
await page.screenshot({ path: path.join(output, 'row.png') });
await page.mouse.up();
assert.equal(await preview.count(), 0);
await page.mouse.move(5, 5);
@@ -148,7 +88,7 @@ try {
await grip('column', 0); await target('column', 2, true);
assert.deepEqual(await preview.locator('tr').allTextContents(), ['Name', 'Alpha', 'Beta', 'Gamma', 'Delta']);
await page.locator('.table-drop-indicator:visible').waitFor();
await page.screenshot({ path: '.audit/table-drag-column.png' });
await page.screenshot({ path: path.join(output, 'column.png') });
await page.mouse.up();
assert.deepEqual(await headers(), ['Value', 'Notes', 'Name']);
await save();
@@ -192,13 +132,9 @@ try {
await page.waitForFunction(() => { const el = document.querySelector('.writer-table .md-table-scroll'); return el.scrollLeft + el.clientWidth >= el.scrollWidth - 2; });
await target('column', 2, true); await page.mouse.up();
assert.deepEqual(await headers(), ['Value', 'Notes', 'Name']);
await page.screenshot({ path: '.audit/table-drag-narrow.png' });
await page.screenshot({ path: path.join(output, 'narrow.png') });
// Long tables scroll the document while the pointer stays at its lower edge.
await page.setViewportSize({ width: 1440, height: 700 });
await page.evaluate(() => {
window.__TEST__.files.set('long.md', '# Long table\n\n| Item | Value |\n| --- | --- |\n' + Array.from({ length: 30 }, (_, i) => `| Item ${i + 1} | ${i + 1} |`).join('\n') + '\n\nAfter.\n');
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['long.md'] });
});
await quickOpen('long.md');
await page.getByRole("group", { name: "Editor layout" }).locator("button.current").press("End");
await table.waitFor();
@@ -223,10 +159,4 @@ try {
assert.equal((await rows())[1], 'Item 2');
assert.equal(await page.locator('.is-table-dragging').count(), 0);
assert.equal(await preview.count(), 0);
assert.deepEqual(errors, []);
console.log('PASS: hover/focus grips, pointer-following previews and cleanup, row/column drag in both directions, indicators, alignment, undo/redo, cancellation, keyboard movement, active edits, horizontal and vertical auto-scroll.');
} catch (error) {
console.error('Browser errors:', errors);
await page.screenshot({ path: '.audit/table-drag-failure.png' });
throw error;
} finally { await browser.close(); }
});
+20 -87
View File
@@ -1,80 +1,17 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
// Table Enter and Shift+Enter, table clipboard with line breaks, task marker editing, and title Tab, in both themes and a narrow window.
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 page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
await mkdir(".audit", { recursive: true });
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "spelling_menu_install") return;
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
try {
await mkdir('output/october15-editor', { recursive: true });
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await runSmoke("tables/enterKey", async ({ page }) => {
const output = await outputDir("tables/enterKey");
await mockTauri(page, {
commands: test => ({
...test.workspace({ root: "C:\\smoke-workspace", files: { "notes/welcome.md": "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n" }, writeEvents: true }),
spelling_menu_install: () => null,
}),
});
await page.goto(smokeUrl);
await page.getByText('smoke-workspace', { exact: true }).waitFor();
await page.keyboard.press('Control+p');
await page.getByRole('textbox', { name: 'Find a file' }).fill('welcome.md');
@@ -90,6 +27,7 @@ try {
await page.locator('.live-writer table').waitFor();
};
const cell = (r, c) => page.locator('.live-writer table tr').nth(r).locator('th,td').nth(c);
const shot = name => page.screenshot({ path: path.join(output, `${name}.png`) });
for (const mode of ['dark', 'light']) {
await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({ theme: 'default', mode }), mode);
await reset();
@@ -103,7 +41,7 @@ try {
await page.keyboard.press('Shift+Enter');
await page.keyboard.type('Line');
assert.match(await page.evaluate(() => window.__CM__.state.sliceDoc()), /New<br>Line/);
await page.screenshot({ path: `output/october15-editor/${mode}-table-enter.png` });
await shot(`${mode}-table-enter`);
await reset();
await cell(0, 0).click();
await page.keyboard.press('Shift+F10');
@@ -128,32 +66,27 @@ try {
}, copied);
assert.equal(await page.locator('.live-writer table').count(), 2);
assert.match(await page.evaluate(() => window.__CM__.state.sliceDoc()), /First<br>Second/);
await page.screenshot({ path: `output/october15-editor/${mode}-table-paste.png` });
await shot(`${mode}-table-paste`);
await reset();
await page.evaluate(() => {
const view = window.__CM__;
view.dispatch({ selection: { anchor: view.state.sliceDoc().indexOf('A task') + 3 } }); view.focus();
});
assert.equal(await page.locator('.writer-checkbox').count(), 1);
await page.screenshot({ path: `output/october15-editor/${mode}-checklist-text.png` });
await shot(`${mode}-checklist-text`);
await page.evaluate(() => {
const view = window.__CM__;
view.dispatch({ selection: { anchor: view.state.sliceDoc().indexOf('[ ]') + 1 } }); view.focus();
});
assert.equal(await page.locator('.writer-checkbox').count(), 0);
await page.screenshot({ path: `output/october15-editor/${mode}-checklist-source.png` });
await shot(`${mode}-checklist-source`);
await page.getByRole('button', { name: 'Rename note', exact: true }).click();
await page.getByRole('textbox', { name: 'Note filename', exact: true }).press('Tab');
await page.waitForFunction(() => document.activeElement?.classList.contains('cm-content'));
await page.screenshot({ path: `output/october15-editor/${mode}-title-tab.png` });
await shot(`${mode}-title-tab`);
await page.setViewportSize({ width: 600, height: 760 });
await reset();
await page.screenshot({ path: `output/october15-editor/${mode}-narrow.png` });
await shot(`${mode}-narrow`);
await page.setViewportSize({ width: 1440, height: 1000 });
}
assert.deepEqual(errors, []);
console.log('PASS: Enter advances and creates rows in the same column, Shift+Enter, table clipboard with line breaks, task marker editing, title Tab, both themes and narrow layouts.');
} catch (error) {
await page.screenshot({ path: 'output/october15-editor/failure.png' });
throw error;
} finally { await browser.close(); }
});
+63 -123
View File
@@ -1,105 +1,61 @@
// Table formulas: live recalculation, raw formula editing, Enter and Tab, undo, cycles, saving, the footer layout, and the Read and Split views.
// @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";
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
await mockFeaturePlugins(page);
async function quickOpen(name) {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
await page.locator('.live-writer').waitFor();
await page.keyboard.press('Control+e');
await page.locator(".monaco-editor textarea").waitFor();
}
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
import { mockFeaturePlugins } from "../_harness/pluginMocks.mjs";
const source = '# Table formulas\n\n| Name | Appearance | Charisma | Combined |\n| --- | ---: | ---: | ---: |\n| First | 9 | 10 | =AVERAGE(B2:C2) |\n| Second | 7 | 9 | =SUM(B3+C3)/2 |\n| Total | | | =SUM(D2:D3) |\n\nAfter.\n';
const table = page.locator('.live-writer table');
const cell = (r, c) => table.locator('tr').nth(r).locator('th, td').nth(c);
const edit = page.locator('.writer-cell-editor');
const result = (r, c) => cell(r, c).locator('.md-table-formula');
async function save() {
await page.keyboard.press('Control+s');
await page.waitForFunction(() => !document.querySelector('[aria-label^="Save changes"]'));
return page.evaluate(() => window.__TEST__.files.get('formulas.md'));
}
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await runSmoke("tables/formulas", async ({ page }) => {
const output = await outputDir("tables/formulas");
await mockTauri(page, {
state: { files: { 'formulas.md': source } },
commands: test => {
const workspace = test.workspace({ root: "C:\\smoke-workspace", files: test.state.files, writeEvents: true });
test.files = workspace.files;
return workspace;
},
});
await mockFeaturePlugins(page);
async function quickOpen(name) {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
await page.locator('.live-writer').waitFor();
await page.keyboard.press('Control+e');
await page.locator(".monaco-editor textarea").waitFor();
}
const table = page.locator('.live-writer table');
const cell = (r, c) => table.locator('tr').nth(r).locator('th, td').nth(c);
const edit = page.locator('.writer-cell-editor');
const result = (r, c) => cell(r, c).locator('.md-table-formula');
const shot = name => page.screenshot({ path: path.join(output, `${name}.png`) });
async function save() {
await page.keyboard.press('Control+s');
await page.waitForFunction(() => !document.querySelector('[aria-label^="Save changes"]'));
return page.evaluate(() => window.__TEST__.files.get('formulas.md'));
}
// Footer controls share one normal-flow block aligned to the table at any width.
async function checkFooter() {
const geometry = await page.evaluate(() => {
const rect = selector => document.querySelector(selector).getBoundingClientRect().toJSON();
return { table: rect('.live-writer .md-table-scroll'), footer: rect('.table-footer'), tools: rect('.table-formula-tools'), help: rect('.table-edit-help'), helpHidden: document.querySelector('.table-edit-help').hidden, summary: rect('.table-formula-help summary'), status: rect('.table-formula-status') };
});
assert.ok(Math.abs(geometry.table.x - geometry.footer.x) < 2);
assert.ok(Math.abs(geometry.footer.x - geometry.tools.x) < 2);
if (!geometry.helpHidden) assert.ok(Math.abs(geometry.help.x - geometry.tools.x) < 2);
assert.ok(geometry.footer.y >= geometry.table.bottom);
assert.ok(geometry.footer.y - geometry.table.bottom <= 28, 'Only the add-row control sits between table and footer');
if (!geometry.helpHidden) {
assert.ok(geometry.tools.y >= geometry.help.bottom, 'Help must not overlap the controls');
assert.ok(geometry.help.right <= geometry.footer.right + 1);
}
if (geometry.status.x > geometry.summary.right) assert.ok(Math.abs((geometry.status.y + geometry.status.height / 2) - (geometry.summary.y + geometry.summary.height / 2)) < 2);
}
await page.goto(smokeUrl);
await page.getByText('smoke-workspace', { exact: true }).waitFor();
await page.evaluate(text => {
window.__TEST__.files.set('formulas.md', text);
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['formulas.md'] });
}, source);
await quickOpen('formulas.md');
await page.keyboard.press('Control+e');
await table.waitFor();
@@ -109,7 +65,7 @@ try {
await page.locator('.rs-tooltip:popover-open').waitFor();
assert.equal(await cell(1, 3).getAttribute('title'), null);
assert.match(await page.locator('.rs-tooltip:popover-open').innerText(), /D2.*AVERAGE/);
await page.screenshot({ path: '.audit/table-cell-hint.png' });
await shot('cell-hint');
await page.keyboard.press('Escape');
assert.equal(await page.locator('.rs-tooltip:popover-open').count(), 0);
await cell(1, 3).click();
@@ -144,7 +100,8 @@ try {
assert.equal(await result(3, 3).innerText(), '58');
await cell(2, 3).click();
await edit.fill('=D3');
await page.keyboard.press('Enter');
// Enter would start editing D4 below (src/lib/editor/tableControls.ts:283), so leave the table to render both results.
await page.keyboard.press('Control+Enter');
assert.equal(await result(2, 3).innerText(), '#CYCLE!');
assert.equal(await result(3, 3).innerText(), '#CYCLE!');
await cell(2, 3).click();
@@ -157,34 +114,17 @@ try {
const saved = await save();
assert.match(saved, /=SUM\(B2:B3\)/);
assert.doesNotMatch(saved, /\\=/);
// Footer controls share one normal-flow block aligned to the table at any width.
async function checkFooter() {
const geometry = await page.evaluate(() => {
const rect = selector => document.querySelector(selector).getBoundingClientRect().toJSON();
return { table: rect('.live-writer .md-table-scroll'), footer: rect('.table-footer'), tools: rect('.table-formula-tools'), help: rect('.table-edit-help'), helpHidden: document.querySelector('.table-edit-help').hidden, summary: rect('.table-formula-help summary'), status: rect('.table-formula-status') };
});
assert.ok(Math.abs(geometry.table.x - geometry.footer.x) < 2);
assert.ok(Math.abs(geometry.footer.x - geometry.tools.x) < 2);
if (!geometry.helpHidden) assert.ok(Math.abs(geometry.help.x - geometry.tools.x) < 2);
assert.ok(geometry.footer.y >= geometry.table.bottom);
assert.ok(geometry.footer.y - geometry.table.bottom <= 28, 'Only the add-row control sits between table and footer');
if (!geometry.helpHidden) {
assert.ok(geometry.tools.y >= geometry.help.bottom, 'Help must not overlap the controls');
assert.ok(geometry.help.right <= geometry.footer.right + 1);
}
if (geometry.status.x > geometry.summary.right) assert.ok(Math.abs((geometry.status.y + geometry.status.height / 2) - (geometry.summary.y + geometry.summary.height / 2)) < 2);
}
await cell(3, 1).click();
await checkFooter();
await page.screenshot({ path: '.audit/table-formula-footer.png' });
await shot('footer');
await page.setViewportSize({ width: 850, height: 1000 });
await checkFooter();
await page.screenshot({ path: '.audit/table-formula-footer-narrow.png' });
await shot('footer-narrow');
await page.locator('.table-formula-help summary').click();
assert.equal(await page.locator('.table-formula-help').getAttribute('open'), '');
await checkFooter();
await page.setViewportSize({ width: 1440, height: 1000 });
await page.screenshot({ path: '.audit/table-formulas.png' });
await shot('formulas');
await page.keyboard.press('Control+e');
await page.keyboard.press('Control+e');
assert.equal(await result(3, 1).innerText(), '12');
@@ -193,8 +133,8 @@ try {
await page.getByRole('group', { name: 'Document view', exact: true }).getByRole('button', { pressed: true }).press('ArrowRight');
const preview = page.locator('.md-page table').first();
await preview.waitFor();
assert.equal(await preview.locator('tbody tr').last().locator('.md-table-formula').last().innerText(), '58');
// Enter in the last row added an empty row below Total (src/lib/editor/tableControls.ts:285).
const total = preview.locator('tbody tr').filter({ hasText: 'Total' });
assert.equal(await total.locator('.md-table-formula').last().innerText(), '58', `${mode} view`);
}
assert.deepEqual(errors, []);
console.log('PASS: live recalculation, raw formula editing, Enter/Tab, undo/redo, cycle recovery, Markdown saves, help, remount, Read, and Split');
} finally { await browser.close(); }
});
+58 -88
View File
@@ -1,82 +1,60 @@
import { createRequire } from "node:module";
// Links in table cells: clicks keep the caret in place, keyboard entry, inline Edit link, wiki aliases, repeated targets, save, and undo, in both themes and a narrow window.
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 page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(15000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await mkdir(".audit", { recursive: true });
await page.addInitScript(() => {
localStorage.clear();
window.isTauri = true;
const root = "C:\\tab-menu-workspace";
const files = new Map([["a.md", '# Links\n\nOutside table.\n\n| Name | Value |\n| --- | --- |\n| One | Text |\n| Two | Text |\n| Three | Text |\n| Four | Text |\n| Five | [Roadmp](docs/roadmap.md) |\n| Keyboard | Before [Guide](docs/guide.md) after |\n| Wiki | [[guide\\|Guide]] |\n| Repeated | **Prefix** [One](same.md) + [Sec**ond**](same.md "Title") |\n']]);
window.tabMenuTest = { files, prompts: [], answer: "Cancel", revealed: null, clipboard: null };
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { window.tabMenuTest.clipboard = text; } } });
let sequence = 0;
const callbacks = new Map(), listeners = new Map();
window.spellingTest = { commands: [], emit: payload => callbacks.get(listeners.get("spelling-menu"))?.({ event: "spelling-menu", id: 1, payload }) };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { callbacks.set(++sequence, callback); return sequence; }, unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === "plugin:event|listen") { listeners.set(args.event, args.handler); return ++sequence; }
if (command === "plugin:event|unlisten") return;
if (command.startsWith("spelling_menu_")) { window.spellingTest.commands.push({ method: command, ...args }); return; }
if (command === "spelling_suggestions") return { language: "en-US", words: [], misspelled: false };
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "tab-menu-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_list") return args.rel ? [] : [{ name: "notes", rel_path: "notes", kind: "folder" }, ...[...files.keys()].map(name => ({ name, rel_path: name, kind: "file" }))];
if (command === "workspace_search") return [];
if (command === "workspace_write") { files.set(args.rel, args.contents); return; }
if (command === "workspace_rename") { files.set(args.to, files.get(args.from)); files.delete(args.from); return; }
if (command === "workspace_abs_path") return `${root}\\${args.rel}`;
if (command === "workspace_reveal") { window.tabMenuTest.revealed = args.rel; return; }
if (command === "plugin:dialog|message") { window.tabMenuTest.prompts.push(args.message); return window.tabMenuTest.answer; }
throw new Error(`Unhandled IPC: ${command}`);
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("tables/linkCaret", async ({ page }) => {
const output = await outputDir("tables/linkCaret");
await mockTauri(page, {
commands: test => {
localStorage.clear();
const workspace = test.workspace({
root: "C:\\tab-menu-workspace",
folders: ["notes"],
files: { "a.md": '# Links\n\nOutside table.\n\n| Name | Value |\n| --- | --- |\n| One | Text |\n| Two | Text |\n| Three | Text |\n| Four | Text |\n| Five | [Roadmp](docs/roadmap.md) |\n| Keyboard | Before [Guide](docs/guide.md) after |\n| Wiki | [[guide\\|Guide]] |\n| Repeated | **Prefix** [One](same.md) + [Sec**ond**](same.md "Title") |\n' },
});
test.files = workspace.files;
test.prompts = [];
return {
...workspace,
spelling_menu_install: () => null,
"plugin:dialog|message": ({ message }) => { test.prompts.push(message); return "Cancel"; },
};
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
});
page.setDefaultTimeout(15000);
const sourceCell = () => page.locator('.is-source-editing .writer-cell-editor');
async function clickTextAt(locator, offset, button = 'left') {
const point = await locator.evaluate((element, offset) => {
const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT);
let node;
while ((node = walker.nextNode())) {
if (offset > node.textContent.length) { offset -= node.textContent.length; continue; }
const range = document.createRange();
range.setStart(node, offset); range.collapse(true);
const rect = range.getBoundingClientRect();
return { x: rect.x, y: rect.y + rect.height / 2 };
}
throw new Error('No text position');
}, offset);
await page.mouse.click(point.x, point.y, { button });
}
const selected = () => page.evaluate(() => getSelection().toString());
const caretPrefix = () => page.evaluate(() => {
const selection = getSelection(), range = document.createRange();
range.selectNodeContents(document.querySelector('.is-source-editing .writer-cell-editor'));
range.setEnd(selection.anchorNode, selection.anchorOffset);
return range.toString();
});
const documentText = () => page.locator('.cm-content').evaluate(async node => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
return EditorView.findFromDOM(node).state.doc.toString();
});
const shot = name => page.screenshot({ path: path.join(output, `${name}.png`) });
const output = '.audit/table-link-caret';
await mkdir(output, { recursive: true });
const sourceCell = () => page.locator('.is-source-editing .writer-cell-editor');
async function clickTextAt(locator, offset, button = 'left') {
const point = await locator.evaluate((element, offset) => {
const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT);
let node;
while ((node = walker.nextNode())) {
if (offset > node.textContent.length) { offset -= node.textContent.length; continue; }
const range = document.createRange();
range.setStart(node, offset); range.collapse(true);
const rect = range.getBoundingClientRect();
return { x: rect.x, y: rect.y + rect.height / 2 };
}
throw new Error('No text position');
}, offset);
await page.mouse.click(point.x, point.y, { button });
}
const selected = () => page.evaluate(() => getSelection().toString());
const caretPrefix = () => page.evaluate(() => {
const selection = getSelection(), range = document.createRange();
range.selectNodeContents(document.querySelector('.is-source-editing .writer-cell-editor'));
range.setEnd(selection.anchorNode, selection.anchorOffset);
return range.toString();
});
const documentText = () => page.locator('.cm-content').evaluate(async node => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
return EditorView.findFromDOM(node).state.doc.toString();
});
try {
for (const theme of ['dark', 'light']) for (const width of [1440, 620]) {
await page.setViewportSize({ width, height: 1000 });
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await page.goto(smokeUrl);
await page.locator('[data-tree-rel="a.md"]').click();
await page.locator('.writer-table').waitFor();
await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({ theme:'default', mode }), theme);
@@ -91,7 +69,7 @@ try {
assert.equal(await caretPrefix(), '[Roadm', 'The caret stays at the clicked label character');
await page.keyboard.type('a');
assert.equal(await sourceCell().innerText(), '[Roadmap](docs/roadmap.md)');
await page.screenshot({ path:`${output}/click-label-${theme}-${width}.png` });
await shot(`click-label-${theme}-${width}`);
await page.keyboard.press('Escape');
assert.equal(await cell.locator('a').innerText(), 'Roadmap');
await clickTextAt(cell.locator('a'), 3);
@@ -99,7 +77,7 @@ try {
await page.getByRole('menuitem', { name:'Edit link', exact:true }).click();
assert.equal(await selected(), 'docs/roadmap.md');
assert.equal(await page.getByRole('dialog').count(), 0);
await page.screenshot({ path:`${output}/edit-target-${theme}-${width}.png` });
await shot(`edit-target-${theme}-${width}`);
await page.keyboard.type('docs/changed.md');
await page.keyboard.press('Enter');
assert.equal(await cell.locator('a').getAttribute('href'), 'docs/changed.md');
@@ -109,7 +87,7 @@ try {
await page.keyboard.press('Control+y');
assert.equal(await cell.locator('a').getAttribute('href'), 'docs/changed.md');
await page.keyboard.press('Control+s');
assert.match(await page.evaluate(() => window.tabMenuTest.files.get('a.md')), /\[Roadmap\]\(docs\/changed.md\)/);
assert.match(await page.evaluate(() => window.__TEST__.files.get('a.md')), /\[Roadmap\]\(docs\/changed.md\)/);
const keyboard = page.getByRole('cell', { name:'Row 7, column 2', exact:true });
await clickTextAt(keyboard, 7);
@@ -118,7 +96,7 @@ try {
await sourceCell().waitFor();
assert.equal(await keyboard.locator('.writer-link-target').innerText(), 'docs/guide.md');
assert.equal(await caretPrefix(), 'Before [G');
await page.screenshot({ path:`${output}/keyboard-${theme}-${width}.png` });
await shot(`keyboard-${theme}-${width}`);
await page.keyboard.press('Escape');
const wiki = page.getByRole('cell', { name:'Row 8, column 2', exact:true });
@@ -144,14 +122,6 @@ try {
assert.equal(await repeated.locator('a').first().getAttribute('href'), 'same.md');
assert.equal(await repeated.locator('a').nth(1).getAttribute('href'), 'second.md');
assert.match(await documentText(), /\[Sec\*\*ond\*\*\]\(second.md "Title"\)/);
assert.deepEqual(await page.evaluate(() => window.tabMenuTest.prompts), []);
assert.deepEqual(await page.evaluate(() => window.__TEST__.prompts), []);
}
assert.deepEqual(errors, []);
console.log('PASS: ordinary link click reveals Markdown, exact spelling caret, keyboard entry, inline Edit link, URL selection, wiki aliases, repeated targets, formatted labels, title preservation, save, undo/redo, both themes, and narrow windows. Native WebView acceptance remains open.');
} catch (error) {
console.error(error);
await page.screenshot({ path:`${output}/failure.png` });
console.log(await page.locator('.writer-cell-editor').allTextContents());
console.log({errors, active:await page.evaluate(() => document.activeElement?.outerHTML.slice(0,300))});
throw error;
} finally { await browser.close(); }
});
+69 -144
View File
@@ -1,134 +1,73 @@
// Table keyboard navigation: arrows, caret positions, entry and exit in all directions, goal columns, line breaks, stable cell sizes, saving, and undo.
// @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";
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
import { mockTauri, runSmoke, settle, smokeUrl } from "../_harness/index.mjs";
import { mockFeaturePlugins } from "../_harness/pluginMocks.mjs";
await runSmoke("tables/navigation", async ({ page }) => {
await mockTauri(page, {
commands: test => {
const workspace = test.workspace({ root: "C:\\smoke-workspace", writeEvents: true });
test.files = workspace.files;
return workspace;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
await mockFeaturePlugins(page);
async function quickOpen(name) {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
await page.locator('.live-writer .cm-content').waitFor();
}
const source = '# Navigation\n\nBefore.\n\n| Name | Value | Formula |\n| --- | --- | --- |\n| Alpha | 12 | =B2*2 |\n| Beta | | tail |\n| Two<br>lines | short | end |\n\nAfter.\n';
const table = page.locator('.live-writer table');
const cell = (r, c) => table.locator('tr').nth(r).locator('th, td').nth(c);
const edit = page.locator('.writer-cell-editor');
async function expectCell(r, c) {
await page.waitForFunction(({ r, c }) => {
const active = document.activeElement;
const cell = active?.closest('th, td');
return active?.matches('.writer-cell-editor') && cell?.cellIndex === c && cell.parentElement.rowIndex === r;
}, { r, c });
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
}
async function at(r, c, edge = 'End') {
await cell(r, c).click();
// ProseMirror guards native selections at the start for 200ms after focus.
await page.waitForTimeout(220);
await page.keyboard.press(`Control+${edge}`);
await expectCell(r, c);
}
async function arrow(key, r, c) {
await page.keyboard.press(key);
await expectCell(r, c);
}
async function expectProse(after) {
await page.waitForFunction(after => {
const content = document.querySelector('.live-writer .cm-content');
const table = content?.querySelector('table');
const caret = document.getSelection()?.focusNode;
return content === document.activeElement && !content.querySelector('.writer-cell-editor') && table && caret &&
(table.compareDocumentPosition(caret) & (after ? Node.DOCUMENT_POSITION_FOLLOWING : Node.DOCUMENT_POSITION_PRECEDING));
}, after);
}
async function caret() {
return edit.evaluate(el => {
const selection = window.getSelection();
const range = document.createRange();
range.selectNodeContents(el);
range.setEnd(selection.focusNode, selection.focusOffset);
return { offset: range.toString().length, selected: selection.toString() };
});
}
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await mockFeaturePlugins(page);
// Add a file after the workspace opens, as an external change would.
const addFile = (name, text) => page.evaluate(({ name, text }) => {
window.__TEST__.files.set(name, text);
window.__TEST__.emit('workspace-event', { root: 'C:\\smoke-workspace', kind: 'create', paths: [name] });
}, { name, text });
async function quickOpen(name) {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
await page.locator('.live-writer .cm-content').waitFor();
}
const source = '# Navigation\n\nBefore.\n\n| Name | Value | Formula |\n| --- | --- | --- |\n| Alpha | 12 | =B2*2 |\n| Beta | | tail |\n| Two<br>lines | short | end |\n\nAfter.\n';
const table = page.locator('.live-writer table');
const cell = (r, c) => table.locator('tr').nth(r).locator('th, td').nth(c);
const edit = page.locator('.writer-cell-editor');
async function expectCell(r, c) {
await page.waitForFunction(({ r, c }) => {
const active = document.activeElement;
const cell = active?.closest('th, td');
return active?.matches('.writer-cell-editor') && cell?.cellIndex === c && cell.parentElement.rowIndex === r;
}, { r, c });
await settle(page);
}
async function at(r, c, edge = 'End') {
await cell(r, c).click();
// ProseMirror guards native selections at the start for 200ms after focus.
await page.waitForTimeout(220);
await page.keyboard.press(`Control+${edge}`);
await expectCell(r, c);
}
async function arrow(key, r, c) {
await page.keyboard.press(key);
await expectCell(r, c);
}
async function expectProse(after) {
await page.waitForFunction(after => {
const content = document.querySelector('.live-writer .cm-content');
const table = content?.querySelector('table');
const caret = document.getSelection()?.focusNode;
return content === document.activeElement && !content.querySelector('.writer-cell-editor') && table && caret &&
(table.compareDocumentPosition(caret) & (after ? Node.DOCUMENT_POSITION_FOLLOWING : Node.DOCUMENT_POSITION_PRECEDING));
}, after);
}
async function caret() {
return edit.evaluate(el => {
const selection = window.getSelection();
const range = document.createRange();
range.selectNodeContents(el);
range.setEnd(selection.focusNode, selection.focusOffset);
return { offset: range.toString().length, selected: selection.toString() };
});
}
await page.goto(smokeUrl);
await page.getByText('smoke-workspace', { exact: true }).waitFor();
await page.evaluate(text => {
window.__TEST__.files.set('navigation.md', text);
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['navigation.md'] });
}, source);
await addFile('navigation.md', source);
await quickOpen('navigation.md');
await table.waitFor();
@@ -307,10 +246,7 @@ try {
await page.setViewportSize({ width, height: 1000 });
await page.evaluate(theme => { document.documentElement.dataset.theme = theme; }, theme);
const name = `stable-${theme}-${width}.md`;
await page.evaluate(({ name, text }) => {
window.__TEST__.files.set(name, text);
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: [name] });
}, { name, text: stableSource });
await addFile(name, stableSource);
await quickOpen(name);
await table.waitFor();
const initial = await dimensions();
@@ -352,10 +288,7 @@ try {
// A line break in a tall table keeps the caret and viewport in the active cell.
const tallSource = '# Tall table\n\nBefore.\n\n| Name | Value |\n| --- | --- |\n' +
Array.from({ length: 45 }, (_, i) => `| Row ${i + 1} | |`).join('\n') + '\n\nAfter.\n';
await page.evaluate(text => {
window.__TEST__.files.set('line-breaks.md', text);
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['line-breaks.md'] });
}, tallSource);
await addFile('line-breaks.md', tallSource);
await quickOpen('line-breaks.md');
await table.waitFor();
for (const [r, c, key] of [[1, 0, 'Shift+Enter'], [20, 0, 'Shift+Enter'], [21, 0, 'Shift+Enter'], [20, 0, 'Shift+Enter'], [20, 1, 'Shift+Enter'], [0, 0, 'Shift+Enter']]) {
@@ -383,10 +316,7 @@ try {
const loneTable = '| Name |\n| --- |\n| Value |';
for (const [key, after] of [['ArrowLeft', false], ['ArrowUp', false], ['ArrowRight', true], ['ArrowDown', true]]) {
const name = `${key}.md`;
await page.evaluate(({ name, text }) => {
window.__TEST__.files.set(name, text);
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: [name] });
}, { name, text: loneTable });
await addFile(name, loneTable);
await quickOpen(name);
await table.waitFor();
await at(after ? 1 : 0, 0, after ? 'End' : 'Home');
@@ -404,9 +334,4 @@ try {
const expected = after ? `${loneTable}\n\nOutside.` : `\nOutside.\n${loneTable}`;
await page.waitForFunction(({ name, expected }) => window.__TEST__.files.get(name) === expected, { name, expected });
}
assert.deepEqual(errors, []);
console.log('PASS: arrows, caret positions, row wrapping, empty/formula/header cells, entry/exit in all directions, goal columns, document boundaries, text selection, word movement, multiline/wrapped text, line breaks and scrolling in tall tables, save, undo/redo, Tab and Escape, stable cell dimensions and table/prose boundaries in both themes at wide/narrow widths');
} catch (error) {
await page.screenshot({ path: '.audit/table-navigation-failure.png' });
throw error;
} finally { await browser.close(); }
});
+18 -87
View File
@@ -1,81 +1,17 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
// Table cell selection: drag and Shift-click ranges, keyboard ranges, and clearing or deleting cells, rows, columns, and tables, in both themes and a narrow window.
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 page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
await mkdir(".audit", { recursive: true });
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "spelling_menu_install") return;
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
try {
await mkdir('output/todo-table', { recursive: true });
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await runSmoke("tables/selection", async ({ page }) => {
const output = await outputDir("tables/selection");
await mockTauri(page, {
commands: test => ({
...test.workspace({ root: "C:\\smoke-workspace", files: { "notes/welcome.md": "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n" }, writeEvents: true }),
spelling_menu_install: () => null,
}),
});
await page.goto(smokeUrl);
await page.getByText('smoke-workspace', { exact: true }).waitFor();
await page.keyboard.press('Control+p');
await page.getByRole('textbox', { name: 'Find a file' }).fill('welcome.md');
@@ -94,6 +30,7 @@ try {
await table.waitFor();
}
const contents = () => page.evaluate(() => window.__CM__.state.sliceDoc());
const shot = name => page.screenshot({ path: path.join(output, `${name}.png`) });
async function drag(r,c,r2,c2) {
const start = await cell(r,c).boundingBox(), end = await cell(r2,c2).boundingBox();
await page.mouse.move(start.x+start.width/2,start.y+start.height/2);
@@ -156,9 +93,9 @@ try {
for (let row = 0; row < 3; row++) await page.keyboard.press('Shift+ArrowDown');
assert.equal(await selected.count(),8);
assert.ok(await selected.evaluateAll(cells => cells.every(c => getComputedStyle(c).borderRadius === '0px')));
await page.screenshot({path:`output/todo-table/selection-${theme}-${width}.png`});
await shot(`selection-${theme}-${width}`);
await page.keyboard.press('Shift+F10');
await page.screenshot({path:`output/todo-table/menu-${theme}-${width}.png`});
await shot(`menu-${theme}-${width}`);
await page.keyboard.press('Escape');
assert.equal(await page.locator('.writer-table').evaluate(el => document.activeElement === el),true);
await page.evaluate(source => window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: source }, selection: { anchor: 0 } }), emptyColumns);
@@ -170,13 +107,13 @@ try {
for (let col = 0; col < 2; col++) await page.keyboard.press('Shift+ArrowRight');
for (let row = 0; row < 4; row++) await page.keyboard.press('Shift+ArrowDown');
assert.equal(await selected.count(),15);
await page.screenshot({path:`output/todo-table/empty-columns-selected-${theme}-${width}.png`});
await shot(`empty-columns-selected-${theme}-${width}`);
await page.keyboard.press('Delete');
assert.equal(await table.locator('th').count(),3);
assert.equal(await table.locator('tr').count(),5);
assert.equal(await selected.count(),1);
assert.ok((await contents()).includes('| 2cm | Value | |'));
await page.screenshot({path:`output/todo-table/empty-columns-deleted-${theme}-${width}.png`});
await shot(`empty-columns-deleted-${theme}-${width}`);
await page.keyboard.press('Control+z');
await page.waitForFunction(source => window.__CM__.state.sliceDoc() === source,emptyColumns);
await cell(0,0).click();
@@ -213,10 +150,4 @@ try {
assert.equal(await table.count(),0);
assert.ok((await contents()).includes('After.'));
}
assert.deepEqual(errors,[]);
console.log('PASS: drag and Shift-click ranges, keyboard range entry and extension, Delete/Backspace remove cells, explicit clear, undo, partial/row/column/all delete, outer edges, light/dark narrow screenshots.');
} catch(error) {
await page.screenshot({path:'output/todo-table/failure.png'});
console.error(errors);
throw error;
} finally { await browser.close(); }
});
+31
View File
@@ -0,0 +1,31 @@
// Ctrl+Tab selects the next working tab and Ctrl+Shift+Tab returns to the previous one.
import assert from "node:assert/strict";
import { mockTauri, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("tabs/cycleShortcuts", async ({ page }) => {
await mockTauri(page, {
commands: test => ({
...test.workspace({ root: "C:\\tab-cycle", files: { "a.md": "# Alpha\n", "b.md": "# Beta\n" } }),
plugins_snapshot: () => ({ plugins: [], issues: [] }),
spelling_menu_install: () => null,
}),
});
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 page.getByRole("tab", { name, exact: true }).waitFor();
}
const selected = () => page.getByRole("tab", { selected: true }).getAttribute("data-path");
await page.goto(smokeUrl);
await page.getByText("tab-cycle", { exact: true }).waitFor();
await open("a.md");
await open("b.md");
await page.locator(".cm-content").click();
const before = await selected();
await page.keyboard.press("Control+Tab");
assert.notEqual(await selected(), before);
await page.keyboard.press("Control+Shift+Tab");
assert.equal(await selected(), before);
console.log("PASS: Ctrl+Tab and Ctrl+Shift+Tab cycle working tabs");
});
+95 -117
View File
@@ -1,17 +1,9 @@
import { createRequire } from "node:module";
// The last tab becomes a new tab, compact tab widths, site icons, mixed file and plugin tabs, close actions, plugin disable, and secondary windows.
// @known-issue Without a workspace, plugin tabs cannot be dragged to reorder: they are native-draggable but get no drag data (Workbench.svelte workingTabDragData).
import assert from "node:assert/strict";
import { mkdir } from "node:fs/promises";
import path from "node:path";
import { mockTauri, openPage, outputDir, runSmoke, settle as settleFrames, smokeUrl } from "../_harness/index.mjs";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
const page = await context.newPage();
await context.exposeBinding("settingsHostInvoke", (_source, command, args) =>
page.evaluate(({ command, args }) => window.__TAURI_INTERNALS__.invoke(command, args), { command, args }));
page.setDefaultTimeout(10000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
const pluginCode = `export function activate(api) {
window.tabTest.api = api;
const mount = (id, container) => {
@@ -33,90 +25,84 @@ const pluginCode = `export function activate(api) {
mount: (container, document) => mount(document.id, container),
});
}`;
await context.addInitScript(({ pluginCode }) => {
window.isTauri = true;
localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false, autosaveSeconds: 5 }));
const root = "C:\\plugin-tab-workspace";
const files = new Map(["a.md", "b.md", "c.md", ...Array.from({ length: 14 }, (_, index) => `note-${index}.md`)].map(name => [name, `# ${name}\n\nOriginal text.\n`]));
files.set("project.board", "project-board");
const callbacks = new Map(), listeners = new Map();
let sequence = 0, enabled = true;
const manifest = { schemaVersion: 1, id: "test.tabs", name: "Tab fixtures", author: "Tests", description: "Test editor tabs.", version: "1.0.0", apiVersion: 1, entry: "main.js", access: "full-app" };
const emit = async (event, payload) => {
await Promise.all((listeners.get(event) || []).map(id => callbacks.get(id)?.({ event, id, payload })));
};
window.tabTest = { mounts: {}, disposals: {}, answer: "Cancel", prompts: 0, closeRequests: 0, destroys: 0, files };
const label = location.search.includes("secondary") ? "workspace-2" : "main";
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label }, currentWebview: { label } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (location.search.includes("settingsWindow") && !command.startsWith("plugin:event|") && !command.startsWith("plugin:window|"))
return window.settingsHostInvoke(command, args);
if (command === "settings_open_window") return;
if (command === "plugin:event|listen") {
const ids = listeners.get(args.event) || []; ids.push(args.handler); listeners.set(args.event, ids); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "plugin:window|is_maximized") return false;
if (command === "plugin:window|close") {
window.tabTest.closeRequests++;
await emit("tauri://close-requested");
return;
}
if (command === "plugin:window|destroy") { window.tabTest.destroys++; return; }
if (command.startsWith("plugin:window|")) return;
if (command === "plugins_snapshot") return { root, plugins: [{ manifest, hash: "test", enabled, path: root, error: null, removal: false }] };
if (command === "plugins_load") return pluginCode;
if (command === "plugins_data") return "null";
if (command === "plugins_release") return;
if (command === "plugins_set_enabled") { enabled = args.enabled; emit("plugins-changed"); return; }
if (command === "workspace_last_path") return location.search.includes("no-workspace") ? null : root;
if (command === "workspace_open") return { root, name: "plugin-tab-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") { window.tabTest.prompts++; return window.tabTest.answer; }
throw new Error(`Unhandled IPC: ${command}`);
// `?secondary` loads a secondary window. `?settingsWindow` loads the settings window, which sends its commands to the main page.
function windowRoles(context) {
return context.addInitScript(() => {
const internals = window.__TAURI_INTERNALS__;
if (location.search.includes("secondary")) internals.metadata = { currentWindow: { label: "workspace-2" }, currentWebview: { label: "workspace-2" } };
if (!location.search.includes("settingsWindow")) return;
const { invoke } = internals;
internals.invoke = (command, args = {}) => command.startsWith("plugin:event|") || command.startsWith("plugin:window|")
? invoke(command, args)
: window.settingsHostInvoke(command, args);
});
}
await runSmoke("tabs/lastTabAndSiteIcons", async ({ browser }) => {
const output = await outputDir("tabs/lastTabAndSiteIcons");
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
await mockTauri(context, {
state: { pluginCode },
commands: test => {
localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false, autosaveSeconds: 5 }));
const root = "C:\\plugin-tab-workspace";
const files = Object.fromEntries(["a.md", "b.md", "c.md", ...Array.from({ length: 14 }, (_, index) => `note-${index}.md`)].map(name => [name, `# ${name}\n\nOriginal text.\n`]));
files["project.board"] = "project-board";
const manifest = { schemaVersion: 1, id: "test.tabs", name: "Tab fixtures", author: "Tests", description: "Test editor tabs.", version: "1.0.0", apiVersion: 1, entry: "main.js", access: "full-app" };
let enabled = true;
window.tabTest = { mounts: {}, disposals: {}, answer: "Cancel", prompts: 0, closeRequests: 0, destroys: 0 };
const workspace = test.workspace({ root, files });
return {
...workspace,
workspace_last_path: () => location.search.includes("no-workspace") ? null : root,
settings_open_window: () => null,
"plugin:window|is_maximized": () => false,
"plugin:window|close": () => { window.tabTest.closeRequests++; test.emit("tauri://close-requested"); },
"plugin:window|destroy": () => { window.tabTest.destroys++; },
"plugin:dialog|message": () => { window.tabTest.prompts++; return window.tabTest.answer; },
plugins_snapshot: () => ({ root, plugins: [{ manifest, hash: "test", enabled, path: root, error: null, removal: false }] }),
plugins_load: () => test.state.pluginCode,
plugins_release: () => null,
plugins_set_enabled: args => { enabled = args.enabled; test.emit("plugins-changed"); },
};
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
}, { pluginCode });
});
await windowRoles(context);
const page = await openPage(context);
const pages = [page];
await context.exposeBinding("settingsHostInvoke", (_source, command, args) =>
page.evaluate(({ command, args }) => window.__TAURI_INTERNALS__.invoke(command, args), { command, args }));
const tab = name => page.getByRole("tab", { name, exact: true });
const bar = page.getByRole("tablist", { name: "Working tabs" });
const order = () => bar.getByRole("tab").evaluateAll(nodes => nodes.map(node => node.textContent.trim()));
const settle = () => settleFrames(page);
async function openFile(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 settle();
}
async function openView(name) {
await page.getByRole("navigation", { name: "Plugin shortcuts" }).getByRole("button", { name, exact: true }).click();
await tab(name).waitFor();
}
async function drag(from, to, side = "before", cancel) {
const source = await tab(from).boundingBox(), 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();
}
async function menu(name) {
await tab(name).click({ button: "right" });
await page.getByRole("menu", { name: "Tab actions" }).waitFor();
}
const tab = name => page.getByRole("tab", { name, exact: true });
const bar = page.getByRole("tablist", { name: "Working tabs" });
const order = () => bar.getByRole("tab").evaluateAll(nodes => nodes.map(node => node.textContent.trim()));
const settle = () => page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
async function openFile(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 settle();
}
async function openView(name) {
await page.getByRole("navigation", { name: "Plugin shortcuts" }).getByRole("button", { name, exact: true }).click();
await tab(name).waitFor();
}
async function drag(from, to, side = "before", cancel) {
const source = await tab(from).boundingBox(), 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();
}
async function menu(name) {
await tab(name).click({ button: "right" });
await page.getByRole("menu", { name: "Tab actions" }).waitFor();
}
try {
const url = process.env.SMOKE_URL || "http://127.0.0.1:1420";
await page.goto(url);
await page.goto(smokeUrl);
await page.getByText("plugin-tab-workspace", { exact: true }).waitFor();
await tab("New tab").waitFor();
for (const close of ["button", "middle", "shortcut", "all"]) {
@@ -165,8 +151,7 @@ try {
await plus.focus();
await page.locator('[role="tooltip"]:popover-open').filter({ hasText: "New tab (Ctrl T)" }).waitFor();
await page.keyboard.press("Escape");
await mkdir(".audit", { recursive: true });
await page.locator(".header").screenshot({ path: `.audit/compact-tabs-${width}-${theme}.png` });
await page.locator(".header").screenshot({ path: path.join(output, `compact-tabs-${width}-${theme}.png`) });
}
}
await menu("note-0.md");
@@ -187,8 +172,7 @@ try {
assert.equal(await tab("Browser").locator("img").getAttribute("draggable"), "false");
for (const theme of ["dark", "light"]) {
await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
await mkdir("output", { recursive: true });
await page.locator(".header").screenshot({ path: `output/tab-site-icon-${theme}.png` });
await page.locator(".header").screenshot({ path: path.join(output, `site-icon-${theme}.png`) });
}
await page.evaluate(() => window.tabTest.api.updateViewIcon("browser", "data:image/png;base64,aW1hZ2U="));
await tab("Browser").locator("img").waitFor({ state: "detached" });
@@ -274,6 +258,9 @@ try {
const bar = document.querySelector('[aria-label="Working tabs"]');
return bar.scrollLeft >= bar.scrollWidth - bar.clientWidth - 2;
});
// Native drag needs a fresh pointer event after the strip scrolls beneath it, as in tabs/order.
await page.mouse.move(bounds.x + bounds.width - 4, source.y + source.height / 2);
await page.mouse.move(bounds.x + bounds.width - 3, source.y + source.height / 2);
await page.mouse.up();
await settle();
assert.equal((await order()).at(-1), "Overview");
@@ -283,9 +270,9 @@ try {
assert.equal((await order())[0], "c.md");
const fileOrder = (await order()).filter(name => name !== "Overview");
await page.keyboard.press("Control+,");
const settingsPage = await context.newPage();
settingsPage.on("pageerror", error => errors.push(error.message));
await settingsPage.goto(url + '/?settingsWindow=true');
const settingsPage = await openPage(context);
pages.push(settingsPage);
await settingsPage.goto(smokeUrl + '/?settingsWindow=true');
await settingsPage.getByRole("button", { name: "Plug-ins", exact: true }).click();
await settingsPage.getByRole("switch", { name: "Tab fixtures", exact: true }).click();
await settingsPage.waitForFunction(() => document.getElementById("external-test.tabs")?.checked === false);
@@ -294,7 +281,7 @@ try {
console.log("PASS: plugin drag auto-scroll, empty-tab replacement, and plugin disable preserve the mixed order");
await settingsPage.close();
await page.goto(`${url}?no-workspace`);
await page.goto(`${smokeUrl}?no-workspace`);
await tab("New tab").waitFor();
await openView("Overview");
await page.getByRole("button", { name: "Close New tab", exact: true }).click();
@@ -302,17 +289,16 @@ try {
await drag("Browser", "Overview");
assert.deepEqual(await order(), ["Browser", "Overview"]);
await page.setViewportSize({ width: 880, height: 700 });
await mkdir(".audit", { recursive: true });
await page.screenshot({ path: ".audit/plugin-tab-order.png" });
await page.screenshot({ path: path.join(output, "plugin-tab-order.png") });
await tab("Browser").click({ button: "middle" });
assert.deepEqual(await order(), ["Overview"]);
await page.getByRole("button", { name: "Close Overview", exact: true }).click();
await tab("New tab").waitFor();
assert.deepEqual(await order(), ["New tab"]);
assert.deepEqual(errors, []);
assert.deepEqual(pages.flatMap(page => page.errors), []);
console.log("PASS: plugin tabs reorder and close without an open workspace");
for (const close of ["button", "middle", "shortcut", "all", "plugin", "dirty"]) {
await page.goto(`${url}?secondary`);
await page.goto(`${smokeUrl}?secondary`);
await tab("New tab").waitFor();
if (close === "plugin") {
await openView("Overview");
@@ -326,8 +312,7 @@ try {
await page.waitForFunction(() => window.tabTest.prompts === 1);
assert.equal(await page.evaluate(() => window.tabTest.destroys), 0);
assert.match(await page.locator(".cm-content").innerText(), /Keep these unsaved edits/);
await mkdir(".audit", { recursive: true });
await page.screenshot({ path: ".audit/secondary-last-tab-cancel.png" });
await page.screenshot({ path: path.join(output, "secondary-last-tab-cancel.png") });
await page.evaluate(() => window.tabTest.answer = "Ok");
await page.keyboard.press("Control+w");
} else if (close === "button") {
@@ -345,13 +330,6 @@ try {
await page.waitForFunction(() => window.tabTest.destroys === 1);
assert.equal(await page.evaluate(() => window.tabTest.closeRequests), close === "dirty" ? 2 : 1);
}
assert.deepEqual(errors, []);
assert.deepEqual(pages.flatMap(page => page.errors), []);
console.log("PASS: secondary windows close through the window guard for the last empty, document, or plugin tab; Cancel preserves unsaved edits");
} catch (error) {
await mkdir(".audit", { recursive: true });
await page.screenshot({ path: ".audit/plugin-tab-order-failure.png" });
console.error("Browser errors:", errors);
throw error;
} finally {
await browser.close();
}
});
+113 -111
View File
@@ -1,10 +1,8 @@
import { createRequire } from "node:module";
// Tab sessions: restore after a normal close, missing files, cancelled closes, plugin documents, and plugin tab transfers between windows and workspaces.
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 context = await browser.newContext({ viewport: { width: 1400, height: 900 } });
import path from "node:path";
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
const pluginCode = `export function activate(api) {
let state = "Board state";
api.registerView({ id: "board", title: "Board", icon: "kanban", placement: "editor", navigation: true,
@@ -20,122 +18,129 @@ const pluginCode = `export function activate(api) {
mount(container) { container.textContent = "Saved board document"; return () => { container.textContent = ""; }; }
});
}`;
await context.addInitScript(({ pluginCode }) => {
window.isTauri = true;
localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false }));
const params = new URLSearchParams(location.search);
const root = params.has("other") ? "C:\\other-lifecycle" : params.has("plugins") ? "C:\\plugins-lifecycle" : "C:\\document-lifecycle";
const files = new Map(["a.md", "b.md", "c.md"].map(name => [name, `# ${name}\n\nSaved text.\n`]));
files.set("saved.board", "board document");
if (params.has("missing")) files.delete("a.md");
let sequence = 0;
const callbacks = new Map(), listeners = new Map();
const emit = async event => { for (const id of listeners.get(event) || []) await callbacks.get(id)?.({ event, id, payload: null }); };
window.lifecycle = { answer: "Cancel", close: () => emit("tauri://close-requested"), root, transfer: null };
const manifest = { schemaVersion: 1, id: "test.lifecycle", name: "Lifecycle", author: "Tests", description: "Tab fixture", version: "1.0.0", apiVersion: 1, entry: "main.js", access: "full-app" };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: fn => { const id = ++sequence; callbacks.set(id, fn); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === "plugin:event|listen") { const ids = listeners.get(args.event) || []; ids.push(args.handler); listeners.set(args.event, ids); return args.handler; }
if (command === "plugin:event|unlisten") return;
if (command.startsWith("plugin:window|")) return;
if (command === "plugin:dialog|message") return window.lifecycle.answer;
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "Lifecycle", watch_mode: "native" };
if (command === "workspace_open_window") { window.lifecycle.transfer = args.transfer; return; }
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("Missing file"); return files.get(args.rel); }
if (command === "workspace_list") return args.rel ? [] : [...files.keys()].map(name => ({ name, rel_path: name, kind: "file" }));
if (command === "workspace_search") return [];
if (command === "plugins_snapshot") return { root, plugins: params.has("disabled") ? [] : [{ manifest, hash: "test", enabled: true, path: root, error: null, removal: false }] };
if (command === "plugins_load") return pluginCode;
if (command === "plugins_data") return "null";
if (command === "plugins_release") return;
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
}, { pluginCode });
const url = process.env.SMOKE_URL || "http://127.0.0.1:1420";
const errors = [];
const dragSources = new Map();
const tab = (page, name) => page.getByRole("tab", { name, exact: true });
const bar = page => page.getByRole("tablist", { name: "Working tabs" });
async function create(query = "") {
const page = await context.newPage(); page.setDefaultTimeout(15000);
page.on("pageerror", error => errors.push(error.message));
await page.goto(url + query); await page.getByRole("tab").first().waitFor(); return page;
}
async function open(page, name) {
await page.bringToFront(); 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(page, name === "saved.board" ? "saved" : name).waitFor();
}
async function openBoard(page) {
await page.getByRole("navigation", { name: "Plugin shortcuts" }).getByRole("button", { name: "Board", exact: true }).click();
await page.getByRole("textbox", { name: "Board state" }).waitFor();
}
async function pin(page, name) {
await tab(page, name).click({ button: "right" }); await page.getByRole("menuitem", { name: "Pin", exact: true }).click();
}
async function start(page, name) {
const data = await tab(page, name).evaluate(node => {
assertDraggable(node);
function assertDraggable(node) { if (node.getAttribute("draggable") !== "true") throw new Error("The tab must support native transfer."); }
const transfer = new DataTransfer(); node.dispatchEvent(new DragEvent("dragstart", { bubbles: true, dataTransfer: transfer }));
return transfer.getData("application/x-runestone-tab");
// `window.requestClose()` sends the native close request and waits for the async close guard, which the harness emit does not await.
function closeRequests(target) {
return target.addInitScript(() => {
const internals = window.__TAURI_INTERNALS__;
const { transformCallback, invoke } = internals;
const callbacks = new Map(), handlers = [];
internals.transformCallback = (callback, once) => { const id = transformCallback(callback, once); callbacks.set(id, callback); return id; };
internals.invoke = (command, args = {}) => {
if (command === "plugin:event|listen" && args.event === "tauri://close-requested") handlers.push(args.handler);
return invoke(command, args);
};
window.requestClose = async () => {
for (const id of handlers) await callbacks.get(id)?.({ event: "tauri://close-requested", id, payload: null });
};
});
dragSources.set(data, { page, name });
return data;
}
async function drop(page, data) {
await bar(page).evaluate((node, data) => {
const transfer = new DataTransfer(); transfer.setData("application/x-runestone-tab", data);
const options = { bubbles: true, cancelable: true, clientX: node.getBoundingClientRect().left, dataTransfer: transfer };
node.dispatchEvent(new DragEvent("dragover", options)); node.dispatchEvent(new DragEvent("drop", options));
}, data);
const source = dragSources.get(data);
if (source) {
await tab(source.page, source.name).evaluateAll(nodes => nodes[0]?.dispatchEvent(new DragEvent("dragend", { bubbles: true })));
await runSmoke("tabs/lifecycle", async ({ browser }) => {
const output = await outputDir("tabs/lifecycle");
const context = await browser.newContext({ viewport: { width: 1400, height: 900 } });
await mockTauri(context, {
state: { pluginCode },
commands: test => {
localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false }));
const params = new URLSearchParams(location.search);
const root = params.has("other") ? "C:\\other-lifecycle" : params.has("plugins") ? "C:\\plugins-lifecycle" : "C:\\document-lifecycle";
const files = Object.fromEntries(["a.md", "b.md", "c.md"].map(name => [name, `# ${name}\n\nSaved text.\n`]));
files["saved.board"] = "board document";
if (params.has("missing")) delete files["a.md"];
const manifest = { schemaVersion: 1, id: "test.lifecycle", name: "Lifecycle", author: "Tests", description: "Tab fixture", version: "1.0.0", apiVersion: 1, entry: "main.js", access: "full-app" };
Object.assign(test, { answer: "Cancel", root, transfer: null });
return {
...test.workspace({ root, name: "Lifecycle", files }),
"plugin:window|is_maximized": () => false,
"plugin:window|destroy": () => null,
"plugin:dialog|message": () => test.answer,
workspace_open_window: ({ transfer }) => { test.transfer = transfer; },
plugins_snapshot: () => ({ root, plugins: params.has("disabled") ? [] : [{ manifest, hash: "test", enabled: true, path: root, error: null, removal: false }] }),
plugins_load: () => test.state.pluginCode,
};
},
});
await closeRequests(context);
const pages = [];
const dragSources = new Map();
const tab = (page, name) => page.getByRole("tab", { name, exact: true });
const bar = page => page.getByRole("tablist", { name: "Working tabs" });
const session = page => page.evaluate(() => JSON.parse(localStorage.getItem(`runestone.document-session.${encodeURIComponent(window.__TEST__.root)}`)));
async function create(query = "") {
const page = await openPage(context, { timeout: 15000 });
pages.push(page);
await page.goto(smokeUrl + query); await page.getByRole("tab").first().waitFor(); return page;
}
}
async function screenshots(page, prefix) {
await mkdir("output/tab-lifecycle", { recursive: true });
for (const mode of ["dark", "light"]) {
await page.evaluate(async mode => { const { applyAppearance } = await import("/src/lib/theme/appearance.ts"); await applyAppearance({ theme: "default", mode }); }, mode);
await page.screenshot({ path: `output/tab-lifecycle/${prefix}-${mode}.png` });
async function open(page, name) {
await page.bringToFront(); 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(page, name === "saved.board" ? "saved" : name).waitFor();
}
await page.setViewportSize({ width: 700, height: 700 });
await page.screenshot({ path: `output/tab-lifecycle/${prefix}-narrow.png` });
await page.setViewportSize({ width: 1400, height: 900 });
}
try {
async function openBoard(page) {
await page.getByRole("navigation", { name: "Plugin shortcuts" }).getByRole("button", { name: "Board", exact: true }).click();
await page.getByRole("textbox", { name: "Board state" }).waitFor();
}
async function pin(page, name) {
await tab(page, name).click({ button: "right" }); await page.getByRole("menuitem", { name: "Pin", exact: true }).click();
}
async function start(page, name) {
const data = await tab(page, name).evaluate(node => {
if (node.getAttribute("draggable") !== "true") throw new Error("The tab must support native transfer.");
const transfer = new DataTransfer(); node.dispatchEvent(new DragEvent("dragstart", { bubbles: true, dataTransfer: transfer }));
return transfer.getData("application/x-runestone-tab");
});
dragSources.set(data, { page, name });
return data;
}
async function drop(page, data) {
await bar(page).evaluate((node, data) => {
const transfer = new DataTransfer(); transfer.setData("application/x-runestone-tab", data);
const options = { bubbles: true, cancelable: true, clientX: node.getBoundingClientRect().left, dataTransfer: transfer };
node.dispatchEvent(new DragEvent("dragover", options)); node.dispatchEvent(new DragEvent("drop", options));
}, data);
const source = dragSources.get(data);
if (source) {
await tab(source.page, source.name).evaluateAll(nodes => nodes[0]?.dispatchEvent(new DragEvent("dragend", { bubbles: true })));
}
}
async function screenshots(page, prefix) {
for (const mode of ["dark", "light"]) {
await page.evaluate(async mode => { const { applyAppearance } = await import("/src/lib/theme/appearance.ts"); await applyAppearance({ theme: "default", mode }); }, mode);
await page.screenshot({ path: path.join(output, `${prefix}-${mode}.png`) });
}
await page.setViewportSize({ width: 700, height: 700 });
await page.screenshot({ path: path.join(output, `${prefix}-narrow.png`) });
await page.setViewportSize({ width: 1400, height: 900 });
}
const page = await create();
for (const name of ["a.md", "b.md", "c.md"]) await open(page, name);
await tab(page, "c.md").focus(); await page.keyboard.press("Alt+Shift+ArrowLeft"); await page.keyboard.press("Alt+Shift+ArrowLeft");
await pin(page, "b.md"); await tab(page, "b.md").click();
await page.evaluate(() => window.lifecycle.close());
const session = await page.evaluate(() => JSON.parse(localStorage.getItem(`runestone.document-session.${encodeURIComponent(window.lifecycle.root)}`)));
assert.deepEqual(session.documents.map(item => item.path), ["c.md", "a.md", "b.md"]);
assert.equal(session.activePath, "b.md"); assert.equal(session.documents[2].pinned, true);
assert.ok(!JSON.stringify(session).includes("Saved text"));
await page.goto(url + "?missing"); await tab(page, "b.md").waitFor();
await page.evaluate(() => window.requestClose());
const saved = await session(page);
assert.deepEqual(saved.documents.map(item => item.path), ["c.md", "a.md", "b.md"]);
assert.equal(saved.activePath, "b.md"); assert.equal(saved.documents[2].pinned, true);
assert.ok(!JSON.stringify(saved).includes("Saved text"));
await page.goto(smokeUrl + "?missing"); await tab(page, "b.md").waitFor();
assert.deepEqual(await bar(page).getByRole("tab").evaluateAll(nodes => nodes.map(node => node.dataset.path)), ["c.md", "b.md"]);
assert.equal(await tab(page, "b.md").getAttribute("aria-selected"), "true");
await tab(page, "b.md").click({ button: "right" }); await page.getByRole("menuitem", { name: "Unpin", exact: true }).waitFor(); await page.keyboard.press("Escape");
await screenshots(page, "restored-documents");
await page.locator(".cm-content").fill("Unsaved draft");
await page.evaluate(() => window.lifecycle.close());
assert.deepEqual(await page.evaluate(() => JSON.parse(localStorage.getItem(`runestone.document-session.${encodeURIComponent(window.lifecycle.root)}`))), session);
await page.evaluate(() => { window.lifecycle.answer = "Ok"; return window.lifecycle.close(); });
await page.evaluate(() => window.requestClose());
assert.deepEqual(await session(page), saved);
await page.evaluate(() => { window.__TEST__.answer = "Ok"; return window.requestClose(); });
page.on("dialog", dialog => dialog.accept());
await page.reload(); await tab(page, "b.md").waitFor();
assert.match(await page.locator(".cm-content").innerText(), /Saved text/);
await open(page, "saved.board"); await page.getByText("Saved board document", { exact: true }).waitFor();
await page.evaluate(() => window.lifecycle.close()); await page.reload();
await page.evaluate(() => window.requestClose()); await page.reload();
await tab(page, "saved").waitFor(); await page.getByText("Saved board document", { exact: true }).waitFor();
console.log("PASS: normal-close restore, order, active tab, pins, missing files, canceled close, disk-only restore, and plugin documents");
const source = await create("?plugins"), target = await create("?plugins"), other = await create("?other"), disabled = await create("?plugins&disabled");
assert.equal(await tab(other, "New tab").count(), 1);
await openBoard(source); await source.getByRole("textbox", { name: "Board state" }).fill("Transferred board state"); await pin(source, "Board");
@@ -154,14 +159,11 @@ try {
assert.equal(await target.getByRole("textbox", { name: "Board state" }).inputValue(), "Destination state"); assert.equal(await tab(source, "Board").count(), 1);
await tab(source, "Board").evaluate(node => node.dispatchEvent(new DragEvent("dragend", { bubbles: true })));
await tab(source, "Board").click({ button: "right" }); await source.getByRole("menuitem", { name: "Open in new window", exact: true }).click();
const token = await source.evaluate(() => window.lifecycle.transfer); assert.ok(token);
const token = await source.evaluate(() => window.__TEST__.transfer); assert.ok(token);
const detached = await create(`?plugins&tabTransfer=${token}`); await detached.getByRole("textbox", { name: "Board state" }).waitFor();
await tab(source, "Board").waitFor({ state: "detached" });
data = await start(detached, "Board"); await drop(source, data); await tab(detached, "Board").waitFor({ state: "detached" });
assert.equal(await source.getByRole("textbox", { name: "Board state" }).inputValue(), "Transferred board state");
assert.deepEqual(errors, []);
console.log("PASS: normal-close restore, order, active tab, pins, missing files, workspace isolation, canceled close, disk-only restore, plugin documents, plugin join, duplicate protection, disabled plugin, and tear-out return");
} catch (reason) {
for (const page of context.pages()) console.error(page.url(), (await page.locator("body").innerText()).slice(-1000));
throw reason;
} finally { await browser.close(); }
assert.deepEqual(pages.flatMap(page => page.errors), []);
console.log("PASS: workspace isolation, plugin join, duplicate protection, disabled plugin, and tear-out return");
});
+44 -63
View File
@@ -1,55 +1,36 @@
import { createRequire } from "node:module";
// Tab menus: active and inactive tabs, keyboard focus, pinning, view modes, file actions, ordered closes, cancelled discards, and empty tabs.
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 page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(15000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await mkdir(".audit", { recursive: true });
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\tab-menu-workspace";
const files = new Map(["a.md", "b.md", "c.md", "d.md"].map(name => [name, `# ${name}\n\nOriginal text.\n`]));
window.tabMenuTest = { prompts: [], answer: "Cancel", revealed: null, clipboard: null };
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { window.tabMenuTest.clipboard = text; } } });
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-menu-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_list") return args.rel ? [] : [...files.keys()].map(name => ({ name, rel_path: name, kind: "file" }));
if (command === "workspace_search") return [];
if (command === "workspace_write") throw new Error("Keep unsaved edits for the close test");
if (command === "workspace_rename") { files.set(args.to, files.get(args.from)); files.delete(args.from); return; }
if (command === "workspace_abs_path") return `${root}\\${args.rel}`;
if (command === "workspace_reveal") { window.tabMenuTest.revealed = args.rel; return; }
if (command === "plugin:dialog|message") { window.tabMenuTest.prompts.push(args.message); return window.tabMenuTest.answer; }
throw new Error(`Unhandled IPC: ${command}`);
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("tabs/menus", async ({ page }) => {
const output = await outputDir("tabs/menus");
await mockTauri(page, {
commands: test => {
test.prompts = [];
test.answer = "Cancel";
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { test.clipboard = text; } } });
return {
...test.workspace({ root: "C:\\tab-menu-workspace", files: Object.fromEntries(["a.md", "b.md", "c.md", "d.md"].map(name => [name, `# ${name}\n\nOriginal text.\n`])) }),
workspace_write: () => { throw new Error("Keep unsaved edits for the close test"); },
workspace_reveal: ({ rel }) => { test.revealed = rel; },
"plugin:dialog|message": ({ message }) => { test.prompts.push(message); return test.answer; },
};
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const tab = name => page.getByRole("tab", { name, exact: true });
const menu = () => page.getByRole("menu", { name: "Tab actions", exact: true });
const item = name => page.getByRole("menuitem", { name, exact: true });
const order = () => page.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 show(name) { await tab(name).click({ button: "right" }); await menu().waitFor(); }
try {
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
});
const tab = name => page.getByRole("tab", { name, exact: true });
const menu = () => page.getByRole("menu", { name: "Tab actions", exact: true });
const item = name => page.getByRole("menuitem", { name, exact: true });
const order = () => page.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 show(name) { await tab(name).click({ button: "right" }); await menu().waitFor(); }
await page.goto(smokeUrl);
await page.getByText("tab-menu-workspace", { exact: true }).waitFor();
for (const name of ["a.md", "b.md", "c.md", "d.md"]) await open(name);
await page.locator(".cm-content").filter({ hasText: "Original text." }).waitFor();
@@ -58,13 +39,13 @@ try {
assert.equal(await item("Rename…").count(), 0);
assert.equal(await item("Reading view").count(), 0);
assert.doesNotMatch(await menu().innerText(), /Alt|Shift|Ctrl/);
await page.screenshot({ path: ".audit/tab-menu-inactive.png" });
await page.screenshot({ path: path.join(output, "inactive.png") });
await item("Pin").click();
assert.equal(await tab("d.md").getAttribute("aria-selected"), "true");
assert.ok(await tab("b.md").getAttribute("aria-describedby"));
await show("d.md");
assert.equal(await item("Close tabs after").isDisabled(), true);
await page.screenshot({ path: ".audit/tab-menu-active.png" });
await page.screenshot({ path: path.join(output, "active.png") });
await page.keyboard.press("Escape");
assert.equal(await tab("d.md").evaluate(node => node === document.activeElement), true);
await tab("d.md").press("Shift+F10");
@@ -89,10 +70,10 @@ try {
await show("d.md");
await item("Copy path").click();
await item("Workspace path").click();
assert.equal(await page.evaluate(() => window.tabMenuTest.clipboard), "d.md");
assert.equal(await page.evaluate(() => window.__TEST__.clipboard), "d.md");
await show("d.md");
await item("Show in system explorer").click();
assert.equal(await page.evaluate(() => window.tabMenuTest.revealed), "d.md");
assert.equal(await page.evaluate(() => window.__TEST__.revealed), "d.md");
await show("d.md");
await item("Rename…").click();
await page.getByRole("dialog").getByRole("textbox").fill("renamed.md");
@@ -113,9 +94,9 @@ try {
await tab("c.md •").waitFor();
await show("c.md •");
await item("Close all").click();
await page.waitForFunction(() => window.tabMenuTest.prompts.length === 1);
await page.waitForFunction(() => window.__TEST__.prompts.length === 1);
assert.deepEqual(await order(), ["b.md", "c.md"]);
await page.evaluate(() => { window.tabMenuTest.answer = "Ok"; });
await page.evaluate(() => { window.__TEST__.answer = "Ok"; });
await show("c.md •");
await item("Close all").click();
await tab("c.md •").waitFor({ state: "detached" });
@@ -126,14 +107,14 @@ try {
await show("b.md");
await item("Close").click();
await tab("b.md").waitFor({ state: "detached" });
// Closing the last tab leaves an empty tab (src/lib/layout/Workbench.svelte:291), so the plus button adds a second one.
await tab("New tab").waitFor();
await page.getByRole("button", { name: "New tab (Ctrl T)", exact: true }).click();
await show("New tab");
const added = page.getByRole("tab", { name: "New tab", exact: true, selected: true });
await page.waitForFunction(() => document.querySelectorAll('[role="tab"][data-path^="empty:"]').length === 2);
await added.click({ button: "right" });
await menu().waitFor();
assert.equal(await item("Rename…").count(), 0);
assert.equal(await item("Reading view").count(), 0);
await page.keyboard.press("Escape");
assert.deepEqual(errors, []);
console.log("PASS: active/inactive menus, keyboard focus, pinning, view modes, file actions, ordered closes, cancelled discard, and empty tabs");
} catch (error) {
await page.screenshot({ path: ".audit/tab-menu-failure.png" });
throw error;
} finally { await browser.close(); }
}, { timeout: 15000 });
+94 -128
View File
@@ -1,10 +1,8 @@
import { createRequire } from "node:module";
// Tab drops on the titlebar ribbon: broad and nearby targets, exact ordering, rejected areas, ordinary drags, pinned unsaved documents, and plugin tabs.
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 context = await browser.newContext({ viewport: { width: 1400, height: 900 } });
import path from "node:path";
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
const pluginCode = `export function activate(api) {
let state = "Board state";
api.registerView({ id: "board", title: "Board", icon: "kanban", placement: "editor", navigation: true,
@@ -15,119 +13,95 @@ const pluginCode = `export function activate(api) {
return () => input.remove();
}
});
api.registerDocumentType({ id: "document", title: "Board document", extensions: ["board"], icon: "kanban",
identify: (path, source) => source === "board document" ? { id: path } : null,
mount(container) { container.textContent = "Saved board document"; return () => { container.textContent = ""; }; }
});
}`;
await context.addInitScript(({ pluginCode }) => {
window.isTauri = true;
localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false }));
const params = new URLSearchParams(location.search);
const root = params.has("other") ? "C:\\other-lifecycle" : params.has("plugins") ? "C:\\plugins-lifecycle" : "C:\\document-lifecycle";
const files = new Map(["a.md", "b.md", "c.md"].map(name => [name, `# ${name}\n\nSaved text.\n`]));
files.set("saved.board", "board document");
if (params.has("missing")) files.delete("a.md");
let sequence = 0;
const callbacks = new Map(), listeners = new Map();
const emit = async event => { for (const id of listeners.get(event) || []) await callbacks.get(id)?.({ event, id, payload: null }); };
window.lifecycle = { answer: "Cancel", close: () => emit("tauri://close-requested"), root, transfer: null };
const manifest = { schemaVersion: 1, id: "test.lifecycle", name: "Lifecycle", author: "Tests", description: "Tab fixture", version: "1.0.0", apiVersion: 1, entry: "main.js", access: "full-app" };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: fn => { const id = ++sequence; callbacks.set(id, fn); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === "plugin:event|listen") { const ids = listeners.get(args.event) || []; ids.push(args.handler); listeners.set(args.event, ids); return args.handler; }
if (command === "plugin:event|unlisten") return;
if (command.startsWith("plugin:window|")) return;
if (command === "plugin:dialog|message") return window.lifecycle.answer;
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "Lifecycle", watch_mode: "native" };
if (command === "workspace_open_window") { window.lifecycle.transfer = args.transfer; return; }
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("Missing file"); return files.get(args.rel); }
if (command === "workspace_list") return args.rel ? [] : [...files.keys()].map(name => ({ name, rel_path: name, kind: "file" }));
if (command === "workspace_search") return [];
if (command === "plugins_snapshot") return { root, plugins: params.has("disabled") ? [] : [{ manifest, hash: "test", enabled: true, path: root, error: null, removal: false }] };
if (command === "plugins_load") return pluginCode;
if (command === "plugins_data") return "null";
if (command === "plugins_release") return;
throw new Error(`Unhandled IPC: ${command}`);
await runSmoke("tabs/ribbonDrop", async ({ browser }) => {
const output = await outputDir("tabs/ribbonDrop");
const context = await browser.newContext({ viewport: { width: 1400, height: 900 } });
await mockTauri(context, {
state: { pluginCode },
commands: test => {
localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false }));
const root = "C:\\plugins-lifecycle";
const manifest = { schemaVersion: 1, id: "test.lifecycle", name: "Lifecycle", author: "Tests", description: "Tab fixture", version: "1.0.0", apiVersion: 1, entry: "main.js", access: "full-app" };
return {
...test.workspace({ root, name: "Lifecycle", files: Object.fromEntries(["a.md", "b.md", "c.md"].map(name => [name, `# ${name}\n\nSaved text.\n`])) }),
"plugin:window|is_maximized": () => false,
plugins_snapshot: () => ({ root, plugins: [{ manifest, hash: "test", enabled: true, path: root, error: null, removal: false }] }),
plugins_load: () => test.state.pluginCode,
};
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
}, { pluginCode });
const url = process.env.SMOKE_URL || "http://127.0.0.1:1420";
const errors = [];
const tab = (page, name) => page.getByRole("tab", { name, exact: true });
const bar = page => page.getByRole("tablist", { name: "Working tabs" });
async function create(query = "") {
const page = await context.newPage(); page.setDefaultTimeout(15000);
page.on("pageerror", error => errors.push(error.message));
await page.goto(url + query); await page.getByRole("tab").first().waitFor(); return page;
}
async function open(page, name) {
await page.bringToFront(); 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(page, name === "saved.board" ? "saved" : name).waitFor();
}
async function openBoard(page) {
await page.getByRole("navigation", { name: "Plugin shortcuts" }).getByRole("button", { name: "Board", exact: true }).click();
await page.getByRole("textbox", { name: "Board state" }).waitFor();
}
async function pin(page, name) {
await tab(page, name).click({ button: "right" }); await page.getByRole("menuitem", { name: "Pin", exact: true }).click();
}
async function start(page, name) {
const data = await tab(page, name).evaluate(node => {
assertDraggable(node);
function assertDraggable(node) { if (node.getAttribute("draggable") !== "true") throw new Error("The tab must support native transfer."); }
const transfer = new DataTransfer(); node.dispatchEvent(new DragEvent("dragstart", { bubbles: true, dataTransfer: transfer }));
return transfer.getData("application/x-runestone-tab");
});
return data;
}
async function screenshots(page, prefix) {
await mkdir("output/tab-ribbon-drop", { recursive: true });
for (const mode of ["dark", "light"]) {
await page.evaluate(async mode => { const { applyAppearance } = await import("/src/lib/theme/appearance.ts"); await applyAppearance({ theme: "default", mode }); }, mode);
await page.screenshot({ path: `output/tab-ribbon-drop/${prefix}-${mode}.png` });
const pages = [];
const tab = (page, name) => page.getByRole("tab", { name, exact: true });
const bar = page => page.getByRole("tablist", { name: "Working tabs" });
const order = page => bar(page).getByRole("tab").evaluateAll(nodes => nodes.map(node => node.textContent.trim()));
async function create() {
const page = await openPage(context, { timeout: 15000 });
pages.push(page);
await page.goto(smokeUrl + "?plugins"); await page.getByRole("tab").first().waitFor(); return page;
}
await page.setViewportSize({ width: 700, height: 700 });
await page.screenshot({ path: `output/tab-ribbon-drop/${prefix}-narrow.png` });
await page.setViewportSize({ width: 1400, height: 900 });
}
const order = page => bar(page).getByRole("tab").evaluateAll(nodes => nodes.map(node => node.textContent.trim()));
async function eventAt(page, data, point, type = "dragover", mime = "application/x-runestone-tab") {
return page.evaluate(({ data, point, type, mime }) => {
const transfer = new DataTransfer(); transfer.setData(mime, data);
const node = document.elementFromPoint(point.x, point.y) || document.body;
const event = new DragEvent(type, { bubbles: true, cancelable: true, clientX: point.x, clientY: point.y, dataTransfer: transfer });
node.dispatchEvent(event);
return event.defaultPrevented;
}, { data, point, type, mime });
}
async function receive(page, data, point) {
assert.equal(await eventAt(page, data, point), true);
assert.equal(await eventAt(page, data, point, "drop"), true);
}
async function point(page, kind) {
return page.locator(".header").evaluate((header, kind) => {
const bounds = header.getBoundingClientRect();
const bar = header.querySelector('[role="tablist"]').getBoundingClientRect();
const plus = header.querySelector('[aria-label="New tab (Ctrl T)"]').getBoundingClientRect();
const first = header.querySelector('.tab').getBoundingClientRect();
if (kind === "near") return { x: first.left + first.width / 2, y: bounds.bottom + 18 };
if (kind === "outside") return { x: first.left + first.width / 2, y: bounds.bottom + 80 };
if (kind === "precise") return { x: bar.left + 2, y: bar.top + bar.height / 2 };
if (kind === "controls") { const controls = header.querySelector('.window-controls').getBoundingClientRect(); return { x: controls.left + 10, y: controls.top + controls.height / 2 }; }
if (kind === "blank") return { x: plus.right + 16, y: bounds.top + bounds.height / 2 };
return { x: plus.left + plus.width / 2, y: plus.top + plus.height / 2 };
}, kind);
}
try {
const source = await create("?plugins"), target = await create("?plugins");
async function open(page, name) {
await page.bringToFront(); 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(page, name).waitFor();
}
async function openBoard(page) {
await page.getByRole("navigation", { name: "Plugin shortcuts" }).getByRole("button", { name: "Board", exact: true }).click();
await page.getByRole("textbox", { name: "Board state" }).waitFor();
}
async function pin(page, name) {
await tab(page, name).click({ button: "right" }); await page.getByRole("menuitem", { name: "Pin", exact: true }).click();
}
function start(page, name) {
return tab(page, name).evaluate(node => {
if (node.getAttribute("draggable") !== "true") throw new Error("The tab must support native transfer.");
const transfer = new DataTransfer(); node.dispatchEvent(new DragEvent("dragstart", { bubbles: true, dataTransfer: transfer }));
return transfer.getData("application/x-runestone-tab");
});
}
async function setTheme(page, mode) {
await page.evaluate(async mode => { const { applyAppearance } = await import("/src/lib/theme/appearance.ts"); await applyAppearance({ theme: "default", mode }); }, mode);
}
async function screenshots(page, prefix) {
for (const mode of ["dark", "light"]) {
await setTheme(page, mode);
await page.screenshot({ path: path.join(output, `${prefix}-${mode}.png`) });
}
await page.setViewportSize({ width: 700, height: 700 });
await page.screenshot({ path: path.join(output, `${prefix}-narrow.png`) });
await page.setViewportSize({ width: 1400, height: 900 });
}
async function eventAt(page, data, point, type = "dragover", mime = "application/x-runestone-tab") {
return page.evaluate(({ data, point, type, mime }) => {
const transfer = new DataTransfer(); transfer.setData(mime, data);
const node = document.elementFromPoint(point.x, point.y) || document.body;
const event = new DragEvent(type, { bubbles: true, cancelable: true, clientX: point.x, clientY: point.y, dataTransfer: transfer });
node.dispatchEvent(event);
return event.defaultPrevented;
}, { data, point, type, mime });
}
async function receive(page, data, point) {
assert.equal(await eventAt(page, data, point), true);
assert.equal(await eventAt(page, data, point, "drop"), true);
}
async function point(page, kind) {
return page.locator(".header").evaluate((header, kind) => {
const bounds = header.getBoundingClientRect();
const bar = header.querySelector('[role="tablist"]').getBoundingClientRect();
const plus = header.querySelector('[aria-label="New tab (Ctrl T)"]').getBoundingClientRect();
const first = header.querySelector('.tab').getBoundingClientRect();
if (kind === "near") return { x: first.left + first.width / 2, y: bounds.bottom + 18 };
if (kind === "outside") return { x: first.left + first.width / 2, y: bounds.bottom + 80 };
if (kind === "precise") return { x: bar.left + 2, y: bar.top + bar.height / 2 };
if (kind === "controls") { const controls = header.querySelector('.window-controls').getBoundingClientRect(); return { x: controls.left + 10, y: controls.top + controls.height / 2 }; }
if (kind === "blank") return { x: plus.right + 16, y: bounds.top + bounds.height / 2 };
return { x: plus.left + plus.width / 2, y: plus.top + plus.height / 2 };
}, kind);
}
const source = await create(), target = await create();
await open(target, "b.md");
await open(source, "a.md"); await pin(source, "a.md");
await source.locator(".cm-content").fill("Unsaved ribbon transfer");
@@ -139,11 +113,10 @@ try {
assert.equal(await bar(target).evaluate(node => node.classList.contains("receiving")), false);
assert.equal(await eventAt(target, data, await point(target, "controls")), false, "Window controls stay outside the drop target");
assert.equal(await eventAt(target, data, broad, "dragover", "text/plain"), false, "Ordinary file and text drags retain their behavior");
await mkdir("output/tab-ribbon-drop", { recursive: true });
for (const mode of ["light", "dark"]) {
await target.evaluate(async mode => { const { applyAppearance } = await import("/src/lib/theme/appearance.ts"); await applyAppearance({ theme: "default", mode }); }, mode);
await setTheme(target, mode);
await eventAt(target, data, broad);
await target.screenshot({ path: `output/tab-ribbon-drop/${mode}-blank-receiving.png` });
await target.screenshot({ path: path.join(output, `${mode}-blank-receiving.png`) });
}
await receive(target, data, broad);
await tab(target, "a.md •").waitFor(); await tab(source, "a.md •").waitFor({ state: "detached" });
@@ -160,7 +133,7 @@ try {
const nearby = await point(target, "near");
await eventAt(target, data, nearby);
await bar(target).and(target.locator('.receiving')).waitFor();
await target.screenshot({ path: "output/tab-ribbon-drop/narrow-near-receiving.png" });
await target.screenshot({ path: path.join(output, "narrow-near-receiving.png") });
await receive(target, data, nearby);
await tab(target, "Board").waitFor(); await tab(source, "Board").waitFor({ state: "detached" });
assert.deepEqual(await order(target), ["c.md", "b.md", "a.md •", "Board"]);
@@ -172,12 +145,5 @@ try {
await receive(target, data, await point(target, "precise"));
assert.deepEqual(await order(target), ["Board", "c.md", "b.md", "a.md •"]);
await tab(target, "Board").evaluate(node => node.dispatchEvent(new DragEvent("dragend", { bubbles: true })));
assert.deepEqual(errors, []);
console.log("PASS: broad titlebar and nearby ribbon drops, exact tab ordering, rejection outside the ribbon and over window controls, ordinary drag isolation, pinned unsaved documents, narrow plugin transfers, and source acknowledgement");
} catch (error) {
await mkdir("output/tab-ribbon-drop", { recursive: true });
for (const [index, page] of context.pages().entries()) await page.screenshot({ path: `output/tab-ribbon-drop/failure-${index}.png` });
throw error;
} finally { await browser.close(); }
assert.deepEqual(pages.flatMap(page => page.errors), []);
});
+79 -137
View File
@@ -1,148 +1,90 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
// Each tab keeps its own scroll position in the Writing, Reading, Split, and IDE layouts.
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
import { mockTauri, runSmoke, settle as settleFrames, smokeUrl } from "../_harness/index.mjs";
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();
}
async function settle() {
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
}
async function roundTrip(selector, label) {
const scroller = page.locator(selector);
const position = async (top) => label === 'IDE'
? page.evaluate(async top => {
const { monaco } = await import('/src/lib/editor/monacoEnv.ts');
const editor = monaco.editor.getEditors().find(view => view.getDomNode()?.isConnected);
if (top !== undefined) editor.setScrollTop(top, 1);
return editor.getScrollTop();
}, top)
: scroller.evaluate((el, top) => {
if (top !== undefined) el.scrollTop = top;
return el.scrollTop;
}, top);
await scroller.waitFor({ state: 'visible' });
await settle();
await position(1800);
await settle();
const first = await position();
assert.ok(first > 1000, `${label}: first document is scrollable`);
await page.getByRole('tab', { name: 'scroll-b.md', exact: true }).click();
await scroller.waitFor({ state: 'visible' });
await settle();
await position(650);
await settle();
const second = await position();
for (let repeat = 0; repeat < 2; repeat++) {
for (const [name, expected] of [['scroll-a.md', first], ['scroll-b.md', second]]) {
await page.getByRole('tab', { name, exact: true }).click();
await scroller.waitFor({ state: 'visible' });
await settle();
const actual = await position();
assert.ok(Math.abs(actual - expected) < 5, `${label}: ${name} expected ${expected}, got ${actual}`);
}
}
console.log(`PASS: ${label} retains independent tab scroll positions`);
await page.getByRole('tab', { name: 'scroll-a.md', exact: true }).click();
}
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await page.getByText('smoke-workspace', { exact: true }).waitFor();
await page.evaluate(() => {
for (const name of ['scroll-a.md', 'scroll-b.md']) {
window.__TEST__.files.set(name, Array.from({ length: 200 }, (_, i) => `Paragraph ${i} of ${name}.\n\n`).join(''));
}
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['scroll-a.md', 'scroll-b.md'] });
await runSmoke("tabs/scroll", async ({ page }) => {
await mockTauri(page, {
commands: test => test.workspace({
root: "C:\\smoke-workspace",
files: Object.fromEntries(["scroll-a.md", "scroll-b.md"].map(name => [name, Array.from({ length: 200 }, (_, i) => `Paragraph ${i} of ${name}.\n\n`).join("")])),
}),
});
const settle = () => settleFrames(page);
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();
}
async function roundTrip(selector, label) {
const scroller = page.locator(selector);
const position = async (top) => label === 'IDE'
? page.evaluate(async top => {
const { monaco } = await import('/src/lib/editor/monacoEnv.ts');
const editor = monaco.editor.getEditors().find(view => view.getDomNode()?.isConnected);
if (top !== undefined) editor.setScrollTop(top, 1);
return editor.getScrollTop();
}, top)
: scroller.evaluate((el, top) => {
if (top !== undefined) el.scrollTop = top;
return el.scrollTop;
}, top);
// The Writing layout restores a line-anchored CodeMirror scrollSnapshot (src/lib/editor/LiveWriter.svelte:330-333).
// Re-estimated heights of the lines above can move scrollTop, so compare the top visible line and its offset.
const visibleTop = () => label === 'Writing'
? scroller.evaluate(async el => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
const view = EditorView.findFromDOM(el.querySelector('.cm-content'));
const top = el.getBoundingClientRect().top - view.documentTop;
const block = view.lineBlockAtHeight(top);
return { line: view.state.doc.lineAt(block.from).number, offset: top - block.top };
})
: position().then(top => ({ line: 0, offset: top }));
await scroller.waitFor({ state: 'visible' });
await settle();
await position(1800);
await settle();
assert.ok(await position() > 1000, `${label}: first document is scrollable`);
const first = await visibleTop();
await page.getByRole('tab', { name: 'scroll-b.md', exact: true }).click();
await scroller.waitFor({ state: 'visible' });
await settle();
await position(650);
await settle();
const second = await visibleTop();
for (let repeat = 0; repeat < 2; repeat++) {
for (const [name, expected] of [['scroll-a.md', first], ['scroll-b.md', second]]) {
await page.getByRole('tab', { name, exact: true }).click();
await scroller.waitFor({ state: 'visible' });
await settle();
const actual = await visibleTop();
assert.ok(actual.line === expected.line && Math.abs(actual.offset - expected.offset) < 5, `${label}: ${name} expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`);
}
}
console.log(`PASS: ${label} retains independent tab scroll positions`);
await page.getByRole('tab', { name: 'scroll-a.md', exact: true }).click();
}
// The view and layout switchers show only the current mode until hovered (src/lib/ui/ModeSwitcher.svelte:92, :153).
async function mode(group, name) {
const switcher = page.getByRole('group', { name: group, exact: true });
await switcher.hover();
await switcher.getByRole('button', { name, exact: true }).click();
}
await page.goto(smokeUrl);
await page.getByText('smoke-workspace', { exact: true }).waitFor();
await open('scroll-b.md');
await open('scroll-a.md');
if (await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).count()) {
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
}
await mode('Editor layout', 'Writer');
await roundTrip('.cm-scroller', 'Writing');
await page.getByRole('button', { name: 'Read', exact: true }).click();
await mode('Document view', 'Read');
await roundTrip('.md-page', 'Reading');
await page.getByRole('button', { name: 'Split', exact: true }).click();
await mode('Document view', 'Split');
await roundTrip('.md-page', 'Split preview');
await page.getByRole('button', { name: 'Edit', exact: true }).click();
await page.getByRole('button', { name: 'Switch to IDE layout (Ctrl E)', exact: true }).click();
await mode('Document view', 'Edit');
await mode('Editor layout', 'IDE');
await page.getByRole('tab', { name: 'scroll-b.md', exact: true }).click();
await page.getByRole('button', { name: 'Switch to IDE layout (Ctrl E)', exact: true }).click();
await mode('Editor layout', 'IDE');
await page.getByRole('tab', { name: 'scroll-a.md', exact: true }).click();
await roundTrip('.monaco-scrollable-element', 'IDE');
assert.deepEqual(errors, []);
} catch (error) {
console.error('Browser errors:', errors);
console.error((await page.locator('body').innerText()).slice(-2000));
throw error;
} finally { await browser.close(); }
});
+69 -88
View File
@@ -1,79 +1,72 @@
import { createRequire } from "node:module";
// Tab transfer between windows: same-workspace moves with unsaved text and pins, insertion order, other-workspace rejection, duplicates, and source edits during a transfer.
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 context = await browser.newContext({ viewport: { width: 1440, height: 900 } });
await context.addInitScript(() => {
window.isTauri = true;
localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false }));
const root = location.search.includes("other") ? "C:\\other" : "C:\\transfer";
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" || command.startsWith("plugin:window|")) return;
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "transfer", watch_mode: "native" };
if (command === "workspace_read") return "# " + args.rel + "\n\nOriginal text.\n";
if (command === "workspace_list") return args.rel ? [] : ["a.md", "b.md"].map(name => ({ name, rel_path: name, kind: "file" }));
if (command === "workspace_search") return [];
if (command === "plugins_snapshot") return { root, plugins: [] };
throw new Error(`Unhandled IPC: ${command}`);
import path from "node:path";
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("tabs/transfer", async ({ browser }) => {
const output = await outputDir("tabs/transfer");
const context = await browser.newContext({ viewport: { width: 1440, height: 900 } });
await mockTauri(context, {
commands: test => {
localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false }));
const root = location.search.includes("other") ? "C:\\other" : "C:\\transfer";
const workspace = test.workspace({ root, name: "transfer", files: Object.fromEntries(["a.md", "b.md"].map(name => [name, `# ${name}\n\nOriginal text.\n`])) });
return {
...workspace,
plugins_snapshot: () => ({ root, plugins: [] }),
"plugin:window|is_maximized": () => false,
};
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const url = process.env.SMOKE_URL || "http://127.0.0.1:1420";
const source = await context.newPage(), target = await context.newPage(), other = await context.newPage();
for (const page of [source, target, other]) page.setDefaultTimeout(10000);
const errors = [];
for (const page of [source, target, other]) page.on("pageerror", error => errors.push(error.message));
const tab = (page, name) => page.locator('[role="tab"]').filter({ hasText: name });
async function open(page, name) {
await page.bringToFront();
await page.getByRole("tablist", { name: "Working tabs" }).waitFor();
await page.getByRole("tab").first().waitFor();
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(page, name).waitFor();
}
async function start(page, name) {
return tab(page, name).evaluate(node => {
const transfer = new DataTransfer();
node.dispatchEvent(new DragEvent("dragstart", { bubbles: true, dataTransfer: transfer }));
return transfer.getData("application/x-runestone-tab");
});
}
async function drop(page, data) {
await page.getByRole("tablist", { name: "Working tabs" }).evaluate((node, data) => {
const transfer = new DataTransfer();
transfer.setData("application/x-runestone-tab", data);
node.dispatchEvent(new DragEvent("dragover", { bubbles: true, cancelable: true, clientX: node.getBoundingClientRect().left, dataTransfer: transfer }));
node.dispatchEvent(new DragEvent("drop", { bubbles: true, cancelable: true, clientX: node.getBoundingClientRect().left, dataTransfer: transfer }));
}, data);
}
async function captureTransfer(page, data) {
await mkdir("output/tab-transfer", { recursive: true });
for (const theme of ["light", "dark"]) {
const pages = [];
async function newPage() {
const page = await openPage(context);
pages.push(page);
return page;
}
const source = await newPage(), target = await newPage(), other = await newPage();
const tab = (page, name) => page.locator('[role="tab"]').filter({ hasText: name });
async function open(page, name) {
await page.bringToFront();
await page.getByRole("tablist", { name: "Working tabs" }).waitFor();
await page.getByRole("tab").first().waitFor();
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(page, name).waitFor();
}
async function start(page, name) {
return tab(page, name).evaluate(node => {
const transfer = new DataTransfer();
node.dispatchEvent(new DragEvent("dragstart", { bubbles: true, dataTransfer: transfer }));
return transfer.getData("application/x-runestone-tab");
});
}
function dragOver(page, data, drop) {
return page.getByRole("tablist", { name: "Working tabs" }).evaluate((node, { data, drop }) => {
const transfer = new DataTransfer();
transfer.setData("application/x-runestone-tab", data);
const options = { bubbles: true, cancelable: true, clientX: node.getBoundingClientRect().left, dataTransfer: transfer };
node.dispatchEvent(new DragEvent("dragover", options));
if (drop) node.dispatchEvent(new DragEvent("drop", options));
}, { data, drop });
}
const drop = (page, data) => dragOver(page, data, true);
async function setTheme(page, mode) {
await page.evaluate(async mode => {
const { applyAppearance } = await import('/src/lib/theme/appearance.ts');
await applyAppearance({ theme: 'default', mode });
}, theme);
await page.getByRole("tablist", { name: "Working tabs" }).evaluate((node, data) => {
const transfer = new DataTransfer();
transfer.setData("application/x-runestone-tab", data);
node.dispatchEvent(new DragEvent("dragover", { bubbles: true, cancelable: true, clientX: node.getBoundingClientRect().left, dataTransfer: transfer }));
}, data);
await page.screenshot({ path: `output/tab-transfer/${theme}-receiving.png` });
}, mode);
}
}
try {
await Promise.all([source.goto(url), target.goto(url), other.goto(url + "/?other")]);
async function captureTransfer(page, data) {
for (const theme of ["light", "dark"]) {
await setTheme(page, theme);
await dragOver(page, data, false);
await page.screenshot({ path: path.join(output, `${theme}-receiving.png`) });
}
}
await Promise.all([source.goto(smokeUrl), target.goto(smokeUrl), other.goto(smokeUrl + "/?other")]);
await open(source, "a.md");
await open(target, "b.md");
await tab(source, "a.md").click({ button: "right" });
@@ -86,14 +79,11 @@ try {
assert.equal(await tab(source, "a.md").count(), 1);
await captureTransfer(target, data);
await drop(target, data);
console.log("Dropped into matching workspace");
await tab(target, "a.md").waitFor();
await tab(source, "a.md").waitFor({ state: "detached" });
console.log("Source acknowledged transfer");
assert.match(await target.locator(".cm-content").innerText(), /Unsaved transfer text/);
const changedTarget = await context.newPage();
changedTarget.on("pageerror", error => errors.push(error.message));
await changedTarget.goto(url);
const changedTarget = await newPage();
await changedTarget.goto(smokeUrl);
await changedTarget.getByRole("tab").first().waitFor();
await open(source, "a.md");
data = await start(source, "a.md");
@@ -110,20 +100,11 @@ try {
await target.getByText("This tab is already open in this window. The source tab remains open.").waitFor();
assert.equal(await tab(source, "a.md").count(), 1);
assert.match(await target.locator(".cm-content").innerText(), /Unsaved transfer text/);
await mkdir("output/tab-transfer", { recursive: true });
for (const theme of ["light", "dark"]) {
await target.evaluate(async mode => {
const { applyAppearance } = await import('/src/lib/theme/appearance.ts');
await applyAppearance({ theme: 'default', mode });
}, theme);
await target.screenshot({ path: `output/tab-transfer/${theme}.png` });
await setTheme(target, theme);
await target.screenshot({ path: path.join(output, `${theme}.png`) });
}
await target.setViewportSize({ width: 700, height: 700 });
await target.screenshot({ path: "output/tab-transfer/narrow.png" });
assert.deepEqual(errors, []);
console.log("PASS: same-workspace transfer, unsaved text, pinned state, insertion order, other-workspace rejection, duplicate protection, and source edits during transfer");
} catch (reason) {
console.log(await other.locator("body").innerText());
console.log(await target.locator("body").innerText());
throw reason;
} finally { await browser.close(); }
await target.screenshot({ path: path.join(output, "narrow.png") });
assert.deepEqual(pages.flatMap(page => page.errors), []);
});
+56
View File
@@ -0,0 +1,56 @@
// Move a tab to a new window: Open in new window carries unsaved text, and a tab dragged out stays until the new window accepts it.
import assert from "node:assert/strict";
import { mockTauri, openPage, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("tabs/windowTransfer", async ({ browser }) => {
// The transfer passes through localStorage, so the source and target windows need one context.
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
await mockTauri(context, {
commands: test => ({
...test.workspace({ root: "C:\\window-transfer", files: { "a.md": "# Alpha\n", "b.md": "# Beta\n" } }),
workspace_open_window: ({ transfer }) => { test.transfer = transfer; },
plugins_snapshot: () => ({ plugins: [], issues: [] }),
spelling_menu_install: () => null,
}),
});
const page = await openPage(context, { timeout: 15000 });
const tab = name => page.getByRole("tab", { name, exact: true });
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();
}
await page.goto(smokeUrl);
await page.getByText("window-transfer", { exact: true }).waitFor();
await open("a.md");
await open("b.md");
const editor = page.locator(".cm-content");
await editor.click();
await page.keyboard.press("Control+End");
await page.keyboard.type("Unsaved transfer");
await tab("b.md").click({ button: "right" });
await page.getByRole("menuitem", { name: "Open in new window", exact: true }).click();
await page.waitForFunction(() => window.__TEST__.transfer);
const token = await page.evaluate(() => window.__TEST__.transfer);
const target = await openPage(context, { timeout: 15000 });
await target.goto(smokeUrl + "/?tabTransfer=" + token);
await target.getByRole("tab", { name: "b.md", exact: true }).waitFor();
await target.waitForFunction(() => document.querySelector(".cm-content")?.textContent.includes("Unsaved transfer"));
await tab("b.md").waitFor({ state: "detached" });
console.log("PASS: Open in new window carries unsaved text and removes the source tab");
await page.evaluate(() => { window.__TEST__.transfer = null; });
const draggedTab = page.getByRole("tab").first();
const draggedPath = await draggedTab.getAttribute("data-path");
const tabBox = await draggedTab.boundingBox();
await page.mouse.move(tabBox.x + tabBox.width / 2, tabBox.y + tabBox.height / 2);
await page.mouse.down();
await page.mouse.move(1480, 180, { steps: 12 });
await page.mouse.up();
await page.waitForFunction(() => window.__TEST__.transfer);
assert.notEqual(await page.evaluate(() => window.__TEST__.transfer), token);
assert.equal(await page.locator(`[role="tab"][data-path="${draggedPath}"]`).count(), 1, "Keep the source tab until the new window accepts it");
assert.equal([...page.errors, ...target.errors].length, 0, [...page.errors, ...target.errors].join("\n"));
console.log("PASS: a tab dragged out of the window stays until the new window accepts it");
});
+77 -113
View File
@@ -1,105 +1,75 @@
import { createRequire } from "node:module";
// File tree actions on multiple selections: clipboard paths, marks, copies, deletion, group moves, and reordering.
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\tree-actions-test";
const files = new Map([
["notes/a.md", "# A"], ["notes/nested/b.md", "# B"],
["target/a.md", "# Existing"], ["a.md", "# A"], ["b.md", "# B"], ["c.md", "# C"],
]);
const calls = [];
const state = { files, calls, answer: "Ok", fail: "", clipboard: "" };
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { state.clipboard = text; } } });
let sequence = 0;
const contains = (parent, path) => path === parent || path.startsWith(parent + "/");
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: () => ++sequence,
unregisterCallback: () => {},
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") return ++sequence;
if (command === "plugin:event|unlisten") return;
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "tree-actions-test", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") { files.set(args.rel, args.contents); return; }
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length);
const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_delete") {
if (args.rel === state.fail) throw new Error("Access denied");
for (const path of [...files.keys()]) if (contains(args.rel, path)) files.delete(path);
return;
}
if (command === "workspace_copy") {
const to = args.rel + "-copy";
for (const [path, text] of [...files]) if (contains(args.rel, path)) files.set(to + path.slice(args.rel.length), text);
return { name: to.split("/").pop(), rel_path: to, kind: files.has(to) ? "file" : "folder" };
}
if (command === "workspace_rename") {
if ([...files.keys()].some(path => contains(args.to, path))) throw new Error("Destination exists");
for (const [path, text] of [...files]) if (contains(args.from, path)) {
files.delete(path);
files.set(args.to + path.slice(args.from.length), text);
}
return;
}
if (command === "workspace_abs_path") return root + "\\" + args.rel.replaceAll("/", "\\");
if (command === "workspace_reveal") return;
if (command === "workspace_search") return [];
if (command === "plugin:dialog|message") return state.answer;
throw new Error(`Unhandled IPC: ${command}`);
import { mockTauri, runSmoke, settle as settleFrames, smokeUrl } from "../_harness/index.mjs";
await runSmoke("tree/actions", async ({ page }) => {
await mockTauri(page, {
commands: test => {
const contains = (parent, path) => path === parent || path.startsWith(parent + "/");
const ws = test.workspace({
root: "C:\\tree-actions-test",
files: { "notes/a.md": "# A", "notes/nested/b.md": "# B", "target/a.md": "# Existing", "a.md": "# A", "b.md": "# B", "c.md": "# C" },
});
const files = ws.files;
Object.assign(test, { files, answer: "Ok", fail: "", clipboard: "" });
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { test.clipboard = text; } } });
return {
...ws,
workspace_list: args => ws.workspace_list(args).filter(entry => !entry.rel_path.startsWith(".runestone")),
workspace_delete: ({ rel }) => {
if (rel === test.fail) throw new Error("Access denied");
for (const path of [...files.keys()]) if (contains(rel, path)) files.delete(path);
},
workspace_copy: ({ rel }) => {
const to = rel + "-copy";
for (const [path, text] of [...files]) if (contains(rel, path)) files.set(to + path.slice(rel.length), text);
return { name: to.split("/").pop(), rel_path: to, kind: files.has(to) ? "file" : "folder" };
},
workspace_rename: ({ from, to }) => {
if ([...files.keys()].some(path => contains(to, path))) throw new Error("Destination exists");
for (const [path, text] of [...files]) if (contains(from, path)) {
files.delete(path);
files.set(to + path.slice(from.length), text);
}
},
workspace_reveal: () => null,
"plugin:dialog|message": () => test.answer,
};
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
window.__TEST__ = state;
});
const row = rel => page.locator(`[data-tree-rel="${rel}"]`);
const selected = () => page.locator('[role="treeitem"][aria-selected="true"]').evaluateAll(nodes => nodes.map(node => node.dataset.treeRel));
const calls = command => page.evaluate(command => window.__TEST__.calls.filter(call => call.command === command).map(call => call.args), command);
const settle = () => page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
async function reset() {
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
await row("notes").waitFor();
}
async function action(path, name) {
await row(path).click({ button: "right" });
await page.getByRole("menuitem", { name, exact: true }).click();
await settle();
}
async function selectFiles() {
await row("a.md").click();
await page.getByRole("tab", { name: "a.md", exact: true }).waitFor();
await settle();
await row("b.md").click({ modifiers: ["Control"] });
await settle();
}
async function drag(sourcePath, targetPath, place = "inside") {
const source = await row(sourcePath).boundingBox();
const target = await row(targetPath).boundingBox();
await page.mouse.move(source.x + source.width / 2, source.y + source.height / 2);
await page.mouse.down();
await page.mouse.move(target.x + target.width / 2, target.y + target.height * (place === "before" ? 0.1 : place === "after" ? 0.9 : 0.5), { steps: 10 });
await page.mouse.up();
await settle();
}
try {
});
const row = rel => page.locator(`[data-tree-rel="${rel}"]`);
const selected = () => page.locator('[role="treeitem"][aria-selected="true"]').evaluateAll(nodes => nodes.map(node => node.dataset.treeRel));
const calls = command => page.evaluate(command => window.__TEST__.calls.filter(call => call.command === command).map(call => call.args), command);
const settle = () => settleFrames(page);
const marks = () => page.evaluate(() => JSON.parse(window.__TEST__.files.get(".runestone/marks.json")));
// Mutations name the workspace root they expect (src/lib/workspace/api.ts:63).
const expectedRoot = "C:\\tree-actions-test";
async function reset() {
await page.goto(smokeUrl);
await row("notes").waitFor();
}
async function action(path, name) {
await row(path).click({ button: "right" });
await page.getByRole("menuitem", { name, exact: true }).click();
await settle();
}
async function selectFiles() {
await row("a.md").click();
await page.getByRole("tab", { name: "a.md", exact: true }).waitFor();
await settle();
await row("b.md").click({ modifiers: ["Control"] });
await settle();
}
async function drag(sourcePath, targetPath, place = "inside") {
const source = await row(sourcePath).boundingBox();
const target = await row(targetPath).boundingBox();
await page.mouse.move(source.x + source.width / 2, source.y + source.height / 2);
await page.mouse.down();
await page.mouse.move(target.x + target.width / 2, target.y + target.height * (place === "before" ? 0.1 : place === "after" ? 0.9 : 0.5), { steps: 10 });
await page.mouse.up();
await settle();
}
await reset();
await selectFiles();
await row("a.md").click({ button: "right" });
@@ -114,9 +84,8 @@ try {
assert.deepEqual((await calls("workspace_reveal")).map(args => args.rel), ["a.md", "b.md"]);
await action("a.md", "Bookmark");
await action("b.md", "Pin");
let marks = await page.evaluate(() => JSON.parse(window.__TEST__.files.get(".runestone/marks.json")));
assert.deepEqual(marks.bookmarks, ["a.md", "b.md"]);
assert.deepEqual(marks.pins, ["a.md", "b.md"]);
assert.deepEqual((await marks()).bookmarks, ["a.md", "b.md"]);
assert.deepEqual((await marks()).pins, ["a.md", "b.md"]);
await action("a.md", "Unpin");
await action("a.md", "Remove bookmarks");
await action("a.md", "Make copies (2)");
@@ -161,7 +130,7 @@ try {
await selectFiles();
await drag("a.md", "target");
await row("target/b.md").waitFor();
assert.deepEqual((await calls("workspace_rename")), [{ from: "a.md", to: "target/a 2.md" }, { from: "b.md", to: "target/b.md" }]);
assert.deepEqual(await calls("workspace_rename"), [{ from: "a.md", to: "target/a 2.md", expectedRoot }, { from: "b.md", to: "target/b.md", expectedRoot }]);
assert.deepEqual(await selected(), ["target/a 2.md", "target/b.md"]);
console.log("PASS: group move into a collapsed folder preserves an existing same-name file");
@@ -173,7 +142,7 @@ try {
assert.equal((await calls("workspace_rename")).length, 0);
await drag("notes/a.md", "target");
await row("target/notes").waitFor();
assert.deepEqual(await calls("workspace_rename"), [{ from: "notes", to: "target/notes" }, { from: "c.md", to: "target/c.md" }]);
assert.deepEqual(await calls("workspace_rename"), [{ from: "notes", to: "target/notes", expectedRoot }, { from: "c.md", to: "target/c.md", expectedRoot }]);
assert.deepEqual(await selected(), ["target/notes", "target/c.md"]);
await row("target/notes").click();
await row("target/notes/a.md").waitFor();
@@ -182,17 +151,12 @@ try {
await reset();
await selectFiles();
await drag("a.md", "c.md", "after");
marks = await page.evaluate(() => JSON.parse(window.__TEST__.files.get(".runestone/marks.json")));
assert.deepEqual(marks.order[""].filter(name => name.endsWith(".md")), ["c.md", "a.md", "b.md"]);
assert.deepEqual((await marks()).order[""].filter(name => name.endsWith(".md")), ["c.md", "a.md", "b.md"]);
await drag("b.md", "c.md", "before");
marks = await page.evaluate(() => JSON.parse(window.__TEST__.files.get(".runestone/marks.json")));
assert.deepEqual(marks.order[""].filter(name => name.endsWith(".md")), ["a.md", "b.md", "c.md"]);
assert.deepEqual(errors, []);
assert.deepEqual((await marks()).order[""].filter(name => name.endsWith(".md")), ["a.md", "b.md", "c.md"]);
if (process.env.SCREENSHOT_PATH) {
await row("a.md").click({ button: "right" });
await page.screenshot({ path: process.env.SCREENSHOT_PATH });
}
console.log("PASS: group reorder preserves selected row order in both directions");
} finally {
await browser.close();
}
});
+38
View File
@@ -0,0 +1,38 @@
// Folder actions in the tree: Open in terminal, and the Show .runestone folder setting from the settings window.
import assert from "node:assert/strict";
import { mockTauri, openPage, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("tree/folderActions", async ({ browser }) => {
// The settings window shares localStorage with the main window, so both pages need one context.
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
await mockTauri(context, {
commands: test => {
const workspace = test.workspace({ root: "C:\\folder-actions", files: { "a.md": "# Alpha\n", "folder/keep.md": "# Keep\n", ".runestone/config.json": "{}" } });
return {
...workspace,
workspace_list: args => workspace.workspace_list(args).filter(entry => args.rel || args.showInternal || entry.rel_path !== ".runestone"),
workspace_open_terminal: () => null,
settings_open_window: () => null,
plugins_snapshot: () => ({ plugins: [], issues: [] }),
spelling_menu_install: () => null,
};
},
});
const page = await openPage(context, { timeout: 15000 });
const row = path => page.locator(`[data-tree-rel="${path}"]`);
await page.goto(smokeUrl);
await row("folder").click({ button: "right" });
await page.getByRole("menuitem", { name: "Open in terminal", exact: true }).click();
assert.ok(await page.evaluate(() => window.__TEST__.calls.some(call => call.command === "workspace_open_terminal" && call.args.rel === "folder")));
console.log("PASS: Open in terminal");
await page.keyboard.press("Control+,");
const settings = await openPage(context, { timeout: 15000 });
await settings.goto(smokeUrl + "/?settingsWindow=true");
await settings.getByRole("switch", { name: "Show .runestone folder" }).check();
await settings.close();
await row(".runestone").waitFor();
const errors = [...page.errors, ...settings.errors];
assert.deepEqual(errors, []);
console.log("PASS: Show .runestone folder reveals the internal folder");
});
+45
View File
@@ -0,0 +1,45 @@
// File moves in the tree: cut and paste, Undo and Redo file move from the folder menu, Ctrl+Z, and drag into a folder.
import { mockTauri, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("tree/moveUndo", async ({ page }) => {
await mockTauri(page, {
commands: test => {
const workspace = test.workspace({ root: "C:\\move-undo", files: { "a.md": "# Alpha\n", "b.md": "# Beta\n", "folder/keep.md": "# Keep\n" } });
test.files = workspace.files;
return {
...workspace,
plugins_snapshot: () => ({ plugins: [], issues: [] }),
spelling_menu_install: () => null,
};
},
});
const row = path => page.locator(`[data-tree-rel="${path}"]`);
const menu = label => page.getByRole("menuitem", { name: label, exact: true });
const has = path => page.waitForFunction(path => window.__TEST__.files.has(path), path);
await page.goto(smokeUrl);
await row("b.md").click({ button: "right" });
await menu("Cut").click();
await row("folder").click({ button: "right" });
await menu("Paste").click();
await has("folder/b.md");
await row("folder").click({ button: "right" });
await menu("Undo file move").click();
await has("b.md");
await row("folder").click({ button: "right" });
await menu("Redo file move").click();
await has("folder/b.md");
await row("folder").focus();
await page.keyboard.press("Control+z");
await has("b.md");
console.log("PASS: cut and paste, menu undo and redo, and Ctrl+Z");
const sourceBox = await row("b.md").boundingBox(), folderBox = await row("folder").boundingBox();
await page.mouse.move(sourceBox.x + 50, sourceBox.y + sourceBox.height / 2);
await page.mouse.down();
await page.mouse.move(folderBox.x + 70, folderBox.y + folderBox.height / 2, { steps: 12 });
await page.mouse.up();
await has("folder/b.md");
await page.keyboard.press("Control+z");
await has("b.md");
console.log("PASS: drag into a folder, and Ctrl+Z");
}, { timeout: 15000 });
+51 -75
View File
@@ -1,70 +1,44 @@
import { createRequire } from 'node:module';
// Splash actions and order, and New folder with inline rename in the root, collapsed, and empty folders, with and without a workspace.
import assert from 'node:assert/strict';
import { mkdir, writeFile } from 'node:fs/promises';
import { writeFile } from 'node:fs/promises';
import path from 'node:path';
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const context = await browser.newContext({ viewport: { width: 1280, height: 850 } });
const page = await context.newPage();
page.setDefaultTimeout(10000);
const errors = [];
page.on('pageerror', error => errors.push(error.message));
await context.addInitScript(() => {
window.isTauri = true;
const root = 'C:\\navigation-check';
const folders = new Set(['Untitled', 'Parent', 'Empty']);
const files = new Map([['note.md', '# Note'], ['Parent/existing.md', '# Existing']]);
const state = { folders, files, calls: [] };
window.__NAVIGATION_CHECK__ = state;
let sequence = 0;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
transformCallback: () => ++sequence, unregisterCallback: () => {},
invoke: async (command, args = {}) => {
state.calls.push({ command, args });
if (command === 'plugins_snapshot') return { root: 'C:/plugins', plugins: [] };
if (command === 'workspace_last_path') return state.noWorkspace ? null : root;
if (command === 'workspace_open') return { root, name: 'navigation-check', watch_mode: 'native' };
if (command === 'workspace_read') { if (!files.has(args.rel)) throw new Error('Missing file'); return files.get(args.rel); }
if (command === 'workspace_write') { files.set(args.rel, args.contents); return; }
if (command === 'workspace_list') {
const prefix = args.rel ? args.rel + '/' : '';
return [...[...folders].filter(path => path.startsWith(prefix) && !path.slice(prefix.length).includes('/')).map(path => ({ name: path.slice(prefix.length), rel_path: path, kind: 'folder' })),
...[...files.keys()].filter(path => path.startsWith(prefix) && !path.slice(prefix.length).includes('/') && !path.startsWith('.runestone/')).map(path => ({ name: path.slice(prefix.length), rel_path: path, kind: 'file' }))];
}
if (command === 'workspace_create') { if (folders.has(args.rel) || files.has(args.rel)) throw new Error('Destination exists'); if (args.kind === 'folder') folders.add(args.rel); else files.set(args.rel, ''); return; }
if (command === 'workspace_rename') {
if (folders.has(args.to) || files.has(args.to)) throw new Error('Destination exists');
if (folders.delete(args.from)) folders.add(args.to);
else { files.set(args.to, files.get(args.from)); files.delete(args.from); }
return;
}
if (command === 'plugin:event|listen') return ++sequence;
if (command === 'plugin:window|is_maximized') return false;
if (command === 'workspace_recent' || command === 'workspace_search') return [];
return null;
await runSmoke('tree/navigation', async ({ browser }) => {
const context = await browser.newContext({ viewport: { width: 1280, height: 850 } });
await mockTauri(context, {
strict: false,
commands: test => {
const ws = test.workspace({ root: 'C:\\navigation-check', folders: ['Untitled', 'Parent', 'Empty'], files: { 'note.md': '# Note', 'Parent/existing.md': '# Existing' } });
test.folders = ws.folders;
return {
...ws,
workspace_last_path: () => test.noWorkspace ? null : ws.root,
workspace_list: args => ws.workspace_list(args).filter(entry => !entry.rel_path.startsWith('.runestone')),
workspace_search: () => [],
plugins_snapshot: () => ({ root: 'C:/plugins', plugins: [] }),
'plugin:window|is_maximized': () => false,
};
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const output = '.audit/todo-navigation';
await mkdir(output, { recursive: true });
const row = path => page.locator(`[data-tree-rel="${path}"]`);
const input = () => page.locator('.tree input');
const folderAction = () => page.getByRole('menuitem', { name: 'New folder', exact: true });
async function checkRename(name) {
await input().waitFor();
await page.waitForFunction(() => document.activeElement?.matches('.tree input'));
const state = await input().evaluate(node => ({ name: node.value, start: node.selectionStart, end: node.selectionEnd }));
assert.deepEqual(state, { name, start: 0, end: name.length });
assert.equal(await page.getByRole('dialog').count(), 0, 'New folder uses inline rename');
}
async function setMode(mode) {
await page.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); }, mode);
}
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:5194');
});
const page = await openPage(context);
const output = await outputDir('tree/navigation');
const shot = name => page.screenshot({ path: path.join(output, name) });
const row = rel => page.locator(`[data-tree-rel="${rel}"]`);
const input = () => page.locator('.tree input');
const folderAction = () => page.getByRole('menuitem', { name: 'New folder', exact: true });
async function checkRename(name) {
await input().waitFor();
await page.waitForFunction(() => document.activeElement?.matches('.tree input'));
const state = await input().evaluate(node => ({ name: node.value, start: node.selectionStart, end: node.selectionEnd }));
assert.deepEqual(state, { name, start: 0, end: name.length });
assert.equal(await page.getByRole('dialog').count(), 0, 'New folder uses inline rename');
}
async function setMode(mode) {
await page.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); }, mode);
}
await page.goto(smokeUrl);
await row('Untitled').waitFor();
const welcome = page.locator('.welcome-actions');
await welcome.waitFor();
@@ -82,9 +56,9 @@ try {
for (const mode of ['dark', 'light']) {
await setMode(mode);
await welcome.getByRole('button', { name: /^New file/ }).focus();
await page.screenshot({ path: `${output}/splash-${mode}.png` });
await shot(`splash-${mode}.png`);
await page.setViewportSize({ width: 850, height: 650 });
await page.screenshot({ path: `${output}/splash-${mode}-narrow.png` });
await shot(`splash-${mode}-narrow.png`);
assert.ok(await welcome.locator('button').evaluateAll(nodes => nodes.every(node => { const rect = node.getBoundingClientRect(); return rect.left >= 0 && rect.right <= innerWidth; })), 'Narrow splash controls fit');
await page.setViewportSize({ width: 1280, height: 850 });
}
@@ -110,9 +84,9 @@ try {
await folderAction().click();
const expected = mode === 'dark' ? 'untitled 2' : 'untitled 3';
await checkRename(expected);
await page.screenshot({ path: `${output}/new-folder-${mode}.png` });
await shot(`new-folder-${mode}.png`);
await page.setViewportSize({ width: 850, height: 650 });
await page.screenshot({ path: `${output}/new-folder-${mode}-narrow.png` });
await shot(`new-folder-${mode}-narrow.png`);
await input().press('Escape');
await page.setViewportSize({ width: 1280, height: 850 });
}
@@ -122,16 +96,18 @@ try {
await input().fill('First folder');
await input().press('Enter');
await row('Empty/First folder').waitFor();
assert.equal(await page.evaluate(() => window.__NAVIGATION_CHECK__.folders.has('Empty/First folder')), true);
const emptyPage = await context.newPage();
await emptyPage.addInitScript(() => { window.__NAVIGATION_CHECK__.noWorkspace = true; });
await emptyPage.goto(process.env.SMOKE_URL || 'http://127.0.0.1:5194');
assert.equal(await page.evaluate(() => window.__TEST__.folders.has('Empty/First folder')), true);
const emptyPage = await openPage(context);
await emptyPage.addInitScript(() => { window.__TEST__.noWorkspace = true; });
await emptyPage.goto(smokeUrl);
await emptyPage.locator('.welcome-actions').waitFor();
await emptyPage.locator('.welcome-actions').getByRole('button', { name: 'Open browser', exact: true }).waitFor();
assert.deepEqual(await emptyPage.locator('.welcome-actions button').allTextContents().then(values => values.map(value => value.replace(/Ctrl O/g, '').trim())), ['Open folder', 'Open browser']);
await emptyPage.screenshot({ path: `${output}/splash-no-workspace.png` });
await emptyPage.screenshot({ path: path.join(output, 'splash-no-workspace.png') });
await emptyPage.close();
const errors = [...page.errors, ...emptyPage.errors];
assert.deepEqual(errors, []);
await writeFile(`${output}/checks.json`, JSON.stringify({ passed: true, checks: ['Case-insensitive root name collision', 'Selected inline name and no dialog', 'Enter saves rename', 'Escape retains created folder', 'Collapsed cached parent opens', 'Empty parent', 'Repeated unique names', 'Splash order and three-column maximum', 'Keyboard tab order', 'No workspace actions', 'Dark/light wide/narrow screenshots'], errors }, null, 2));
await writeFile(path.join(output, 'checks.json'), JSON.stringify({ passed: true, checks: ['Case-insensitive root name collision', 'Selected inline name and no dialog', 'Enter saves rename', 'Escape retains created folder', 'Collapsed cached parent opens', 'Empty parent', 'Repeated unique names', 'Splash order and three-column maximum', 'Keyboard tab order', 'No workspace actions', 'Dark/light wide/narrow screenshots'], errors }, null, 2));
console.log(`Navigation checks passed. Evidence: ${output}`);
} finally { await browser.close(); }
});
+65 -76
View File
@@ -1,85 +1,71 @@
import { createRequire } from "node:module";
// New files keep exact names and extensions, renames change the code language, and Writer menus work in both themes.
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1280, height: 900 } });
page.setDefaultTimeout(15000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\editor-files-smoke";
const files = new Map([
["note.md", "Mispelled text.\n\n| Word | Value |\n| --- | --- |\n| Speling | Other |\n"],
["hello.txt", "print('hello')\n"],
["notes/existing.md", "Existing note"],
]);
window.editorFilesTest = { files, calls: [] };
let sequence = 0;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: () => ++sequence, unregisterCallback: () => {},
invoke: async (command, args = {}) => {
window.editorFilesTest.calls.push({ command, args });
if (command === "plugin:event|listen") return ++sequence;
if (command === "plugin:event|unlisten") return;
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "editor-files-smoke", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") { files.set(args.rel, args.contents); return; }
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "", entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length), name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") {
if (files.has(args.rel)) throw new Error("path already exists");
files.set(args.rel, ""); return;
}
if (command === "workspace_rename") {
if (files.has(args.to)) throw new Error("destination already exists");
files.set(args.to, files.get(args.from)); files.delete(args.from); return;
}
if (command === "workspace_search") return [];
throw new Error(`Unhandled IPC: ${command}`);
import { mockTauri, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("tree/newFiles", async ({ page }) => {
await mockTauri(page, {
commands: test => {
const ws = test.workspace({
root: "C:\\editor-files-smoke",
files: {
"note.md": "Mispelled text.\n\n| Word | Value |\n| --- | --- |\n| Speling | Other |\n",
"hello.txt": "print('hello')\n",
"notes/existing.md": "Existing note",
},
});
const files = ws.files;
test.files = files;
return {
...ws,
workspace_list: args => ws.workspace_list(args).filter(entry => !entry.rel_path.startsWith(".runestone")),
workspace_create: ({ rel }) => {
if (files.has(rel)) throw new Error("path already exists");
files.set(rel, "");
},
workspace_rename: ({ from, to }) => {
if (files.has(to)) throw new Error("destination already exists");
files.set(to, files.get(from));
files.delete(from);
},
spelling_suggestions: ({ word }) => ({ language: "en-US", words: word === "Mispelled" ? ["Misspelled"] : [], misspelled: word === "Mispelled" }),
};
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const row = name => page.locator(`[data-tree-rel="${name}"]`);
async function enterName(name) {
await page.locator("#text-request").fill(name);
await page.getByRole("button", { name: "Continue", exact: true }).click();
}
async function modelDetails() {
return page.evaluate(async () => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
const editor = monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected);
return editor && { language: editor.getModel().getLanguageId(), value: editor.getValue(), fontSize: editor.getOption(monaco.editor.EditorOption.fontSize) };
});
}
try {
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
const row = name => page.locator(`[data-tree-rel="${name}"]`);
// The file pane header offers New note and New folder (src/lib/layout/FileTree.svelte:886-887);
// New file… is in the pane menu (src/lib/layout/FileTree.svelte:716-720).
async function newRootFile() {
await page.getByRole("navigation", { name: "Workspace files" }).click({ button: "right", position: { x: 80, y: 320 } });
await page.getByRole("menuitem", { name: "New file…", exact: true }).click();
}
async function enterName(name) {
await page.locator("#text-request").fill(name);
await page.getByRole("button", { name: "Continue", exact: true }).click();
}
async function modelDetails() {
return page.evaluate(async () => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
const editor = monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected);
return editor && { language: editor.getModel().getLanguageId(), value: editor.getValue(), fontSize: editor.getOption(monaco.editor.EditorOption.fontSize) };
});
}
await page.goto(smokeUrl);
await row("note.md").waitFor();
await page.getByRole("button", { name: "New file", exact: true }).click();
await newRootFile();
await enterName("LICENSE");
await row("LICENSE").waitFor();
await page.evaluate(() => window.editorFilesTest.files.set("LICENSE", "Keep this content"));
await page.getByRole("button", { name: "New file", exact: true }).click();
await page.evaluate(() => window.__TEST__.files.set("LICENSE", "Keep this content"));
await newRootFile();
await enterName("LICENSE");
await page.getByText("path already exists", { exact: true }).waitFor();
assert.equal(await page.evaluate(() => window.editorFilesTest.files.get("LICENSE")), "Keep this content");
assert.equal(await page.evaluate(() => window.editorFilesTest.files.has("LICENSE 2")), false);
assert.equal(await page.evaluate(() => window.__TEST__.files.get("LICENSE")), "Keep this content");
assert.equal(await page.evaluate(() => window.__TEST__.files.has("LICENSE 2")), false);
await row("notes").click({ button: "right" });
await page.getByRole("menuitem", { name: "New file…", exact: true }).click();
await enterName("hello_world.py");
await row("notes/hello_world.py").waitFor();
assert.equal(await page.evaluate(() => window.editorFilesTest.files.has("notes/hello_world.py.md")), false);
assert.equal(await page.evaluate(() => window.__TEST__.files.has("notes/hello_world.py.md")), false);
await row("hello.txt").dblclick();
await page.waitForFunction(() => !!document.querySelector(".monaco-editor .view-line"));
await row("hello.txt").click({ button: "right" });
@@ -105,8 +91,8 @@ try {
});
for (const theme of ["dark", "light"]) {
await page.evaluate(async mode => {
const { saveAppearance } = await import('/src/lib/theme/appearance.ts');
saveAppearance({ theme: 'default', mode });
const { saveAppearance } = await import("/src/lib/theme/appearance.ts");
saveAppearance({ theme: "default", mode });
}, theme);
const nativeAllowed = await page.evaluate(() => {
window.writerTest.dispatch({ selection: { anchor: 3 } });
@@ -115,7 +101,12 @@ try {
line.dispatchEvent(event);
return !event.defaultPrevented;
});
assert.equal(nativeAllowed, true, "The native spelling menu is available on plain text");
// Writer combines spelling suggestions with the Markdown actions (docs/design-decisions.md UI-027;
// src/lib/editor/LiveWriter.svelte:255-262 prevents the native menu and passes the spelling offset).
assert.equal(nativeAllowed, false, "Plain text opens the shared Markdown menu instead of the native one");
const textMenu = page.getByRole("menu", { name: "Markdown text actions", exact: true });
await textMenu.getByRole("menuitem", { name: "Misspelled", exact: true }).waitFor();
await page.keyboard.press("Escape");
assert.equal(await page.getByRole("menu").count(), 0);
await page.evaluate(() => { window.writerTest.focus(); });
await page.keyboard.press("Shift+F10");
@@ -137,6 +128,4 @@ try {
}), true, "Active table text permits the native spelling menu");
await page.locator(".cm-line").first().click();
}
assert.deepEqual(errors, []);
console.log("PASS: exact filenames, extensionless creation, extension rename and language, equal code font sizes, native spelling event, shared selection and table menus in both themes");
} finally { await browser.close(); }
}, { viewport: { width: 1280, height: 900 }, timeout: 15000 });
+42
View File
@@ -0,0 +1,42 @@
// Tree rename keeps pins and bookmarks: the file menu offers Copy system path, and Undo rename, Ctrl+Z, and Ctrl+Y restore the marks.
import assert from "node:assert/strict";
import { mockTauri, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("tree/renameMarks", async ({ page }) => {
await mockTauri(page, {
commands: test => {
const workspace = test.workspace({
root: "C:\\rename-marks",
files: { "a.md": "# Note\n\nOriginal text.", ".runestone/marks.json": JSON.stringify({ pins: ["a.md"], bookmarks: ["a.md"], order: { "": ["a.md"] } }) },
});
test.files = workspace.files;
return {
...workspace,
workspace_list: args => workspace.workspace_list(args).filter(entry => args.rel || entry.rel_path !== ".runestone"),
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
spelling_menu_install: () => null,
};
},
});
const row = path => page.locator(`[data-tree-rel="${path}"]`);
const item = name => page.getByRole("menuitem", { name, exact: true });
await page.goto(smokeUrl);
await row("a.md").click({ button: "right" });
assert.equal(await item("Copy path").count(), 0);
assert.equal(await item("Copy system path").count(), 1);
await item("Rename").click();
await page.locator(".tree input").fill("renamed.md");
await page.locator(".tree input").press("Enter");
await row("renamed.md").waitFor();
await row("renamed.md").click({ button: "right" });
assert.equal(await item("Undo rename").count(), 1);
await page.keyboard.press("Escape");
await row("renamed.md").focus();
await page.keyboard.press("Control+z");
await row("a.md").waitFor();
assert.deepEqual(await page.evaluate(() => JSON.parse(window.__TEST__.files.get(".runestone/marks.json")).pins), ["a.md"]);
await row("a.md").focus();
await page.keyboard.press("Control+y");
await row("renamed.md").waitFor();
console.log("PASS: Copy system path, rename, Undo rename, and Ctrl+Z and Ctrl+Y with marks");
}, { viewport: { width: 1200, height: 850 } });
+38 -126
View File
@@ -1,132 +1,44 @@
import { createRequire } from "node:module";
// Rename fields select the file stem, the folder name, or the tab dialog name, in dark/wide and light/narrow layouts.
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\tree-actions-test";
const files = new Map([
["notes/a.md", "# A"], ["notes/nested/b.md", "# B"],
["target/a.md", "# Existing"], ["a.md", "# A"], ["b.md", "# B"], ["c.md", "# C"],
]);
const calls = [];
const state = { files, calls, answer: "Ok", fail: "", clipboard: "" };
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { state.clipboard = text; } } });
let sequence = 0;
const contains = (parent, path) => path === parent || path.startsWith(parent + "/");
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: () => ++sequence,
unregisterCallback: () => {},
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") return ++sequence;
if (command === "plugin:event|unlisten") return;
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "tree-actions-test", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") { files.set(args.rel, args.contents); return; }
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length);
const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_delete") {
if (args.rel === state.fail) throw new Error("Access denied");
for (const path of [...files.keys()]) if (contains(args.rel, path)) files.delete(path);
return;
}
if (command === "workspace_copy") {
const to = args.rel + "-copy";
for (const [path, text] of [...files]) if (contains(args.rel, path)) files.set(to + path.slice(args.rel.length), text);
return { name: to.split("/").pop(), rel_path: to, kind: files.has(to) ? "file" : "folder" };
}
if (command === "workspace_rename") {
if ([...files.keys()].some(path => contains(args.to, path))) throw new Error("Destination exists");
for (const [path, text] of [...files]) if (contains(args.from, path)) {
files.delete(path);
files.set(args.to + path.slice(args.from.length), text);
}
return;
}
if (command === "workspace_abs_path") return root + "\\" + args.rel.replaceAll("/", "\\");
if (command === "workspace_reveal") return;
if (command === "workspace_search") return [];
if (command === "plugin:dialog|message") return state.answer;
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
window.__TEST__ = state;
});
const row = rel => page.locator(`[data-tree-rel="${rel}"]`);
const selected = () => page.locator('[role="treeitem"][aria-selected="true"]').evaluateAll(nodes => nodes.map(node => node.dataset.treeRel));
const calls = command => page.evaluate(command => window.__TEST__.calls.filter(call => call.command === command).map(call => call.args), command);
const settle = () => page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
async function reset() {
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("tree/renameSelection", async ({ page }) => {
await mockTauri(page, {
commands: test => test.workspace({
root: "C:\\tree-actions-test",
files: { "notes/a.md": "# A", "notes/nested/b.md": "# B", "target/a.md": "# Existing", "a.md": "# A", "b.md": "# B", "c.md": "# C" },
}),
});
const output = await outputDir("tree/renameSelection");
const row = rel => page.locator(`[data-tree-rel="${rel}"]`);
const selection = input => input.evaluate(node => [node.selectionStart, node.selectionEnd, node.value]);
await page.goto(smokeUrl);
await row("notes").waitFor();
}
async function action(path, name) {
await row(path).click({ button: "right" });
await page.getByRole("menuitem", { name, exact: true }).click();
await settle();
}
async function selectFiles() {
await row("a.md").click();
await page.getByRole("tab", { name: "a.md", exact: true }).waitFor();
await settle();
await row("b.md").click({ modifiers: ["Control"] });
await settle();
}
async function drag(sourcePath, targetPath, place = "inside") {
const source = await row(sourcePath).boundingBox();
const target = await row(targetPath).boundingBox();
await page.mouse.move(source.x + source.width / 2, source.y + source.height / 2);
await page.mouse.down();
await page.mouse.move(target.x + target.width / 2, target.y + target.height * (place === "before" ? 0.1 : place === "after" ? 0.9 : 0.5), { steps: 10 });
await page.mouse.up();
await settle();
}
try {
await reset();
for (const [theme, width] of [['dark',1440],['light',620]]) {
await page.setViewportSize({width,height:850});
await page.evaluate(theme => { document.documentElement.dataset.theme = theme; document.documentElement.dataset.palette = 'default'; },theme);
await row('a.md').click();
await row('a.md').focus();
await page.keyboard.press('F2');
const input=row('a.md').locator('input');
for (const [theme, width] of [["dark", 1440], ["light", 620]]) {
await page.setViewportSize({ width, height: 850 });
await page.evaluate(theme => { document.documentElement.dataset.theme = theme; document.documentElement.dataset.palette = "default"; }, theme);
await row("a.md").click();
await row("a.md").focus();
await page.keyboard.press("F2");
const input = row("a.md").locator("input");
await input.waitFor();
assert.deepEqual(await input.evaluate(node=>[node.selectionStart,node.selectionEnd,node.value]),[0,1,'a.md']);
await page.screenshot({path:'.audit/rename-selection-'+theme+'.png'});
await input.press('Escape');
await row('notes').click();
await row('notes').focus();
await page.keyboard.press('F2');
const folder=row('notes').locator('input');
assert.deepEqual(await selection(input), [0, 1, "a.md"]);
await page.screenshot({ path: path.join(output, `rename-selection-${theme}.png`) });
await input.press("Escape");
await row("notes").click();
await row("notes").focus();
await page.keyboard.press("F2");
const folder = row("notes").locator("input");
await folder.waitFor();
assert.deepEqual(await folder.evaluate(node=>[node.selectionStart,node.selectionEnd,node.value]),[0,5,'notes']);
await folder.press('Escape');
await page.getByRole('tab',{name:'a.md',exact:true}).click();
await page.getByRole('tab',{name:'a.md',exact:true}).click({button:'right'});
await page.getByRole('menuitem',{name:'Rename…',exact:true}).click();
const dialogInput=page.locator('#text-request');
assert.deepEqual(await selection(folder), [0, 5, "notes"]);
await folder.press("Escape");
await page.getByRole("tab", { name: "a.md", exact: true }).click();
await page.getByRole("tab", { name: "a.md", exact: true }).click({ button: "right" });
await page.getByRole("menuitem", { name: "Rename…", exact: true }).click();
const dialogInput = page.locator("#text-request");
await dialogInput.waitFor();
assert.deepEqual(await dialogInput.evaluate(node=>[node.selectionStart,node.selectionEnd,node.value]),[0,1,'a.md']);
await dialogInput.press('Escape');
assert.deepEqual(await selection(dialogInput), [0, 1, "a.md"]);
await dialogInput.press("Escape");
}
assert.deepEqual(errors,[]);
console.log('Rename selection passed: file, folder, editor dialog, dark/wide and light/narrow.');
} finally { await browser.close(); }
});
+118 -155
View File
@@ -1,158 +1,121 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
// Inline note title rename: tabs and tree, undo of contents, Enter/Tab/Escape, validation, collisions, tab switches mid-rename, and reload.
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_rename") {
if (window.__TEST__.delayRename) await new Promise(resolve => { window.__TEST__.resumeRename = resolve; });
if (!files.has(args.from)) throw new Error("File is missing");
if (files.has(args.to)) throw new Error("A file with that name already exists");
files.set(args.to, files.get(args.from)); files.delete(args.from); return;
}
if (command === "workspace_search") return [];
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("tree/renameTitle", async ({ page }) => {
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
await mockTauri(page, {
commands: test => {
const ws = test.workspace({
root: "C:\\smoke-workspace",
files: {
"notes/welcome.md": "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n",
"notes/second.md": "# Second note\n",
"src/hello.py": "print('hello')\n",
},
});
const files = ws.files;
Object.assign(test, { files, root: ws.root });
return {
...ws,
workspace_write: ({ rel, contents, expected }) => {
if (expected !== undefined && files.get(rel) !== expected) throw new Error("Save blocked: file changed on disk");
files.set(rel, contents);
test.emit("workspace-event", { root: ws.root, kind: "modify", paths: [rel] });
},
workspace_rename: async ({ from, to }) => {
if (test.delayRename) await new Promise(resolve => { test.resumeRename = resolve; });
if (!files.has(from)) throw new Error("File is missing");
if (files.has(to)) throw new Error("A file with that name already exists");
files.set(to, files.get(from));
files.delete(from);
},
};
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
async function openNote(name) {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
await page.getByRole("button", { name: "Rename note", exact: true }).waitFor();
}
const title = page.getByRole("button", { name: "Rename note", exact: true });
const input = page.getByRole("textbox", { name: "Note filename", exact: true });
const writer = page.getByRole("textbox", { name: "Writing editor", exact: true });
async function editTitle(value) { await title.click(); await input.fill(value); }
const renamed = name => page.waitForFunction(expected => document.querySelector(".breadcrumb")?.textContent === expected, name);
try {
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
await page.getByText("smoke-workspace", { exact: true }).waitFor();
await openNote("welcome.md");
const original = await page.evaluate(() => window.__TEST__.files.get("notes/welcome.md"));
await writer.click();
await page.keyboard.press("Control+End");
await page.keyboard.type("Unsaved text");
await editTitle("Release 1.2");
await input.press("Enter");
await renamed("notes/Release 1.2.md");
assert.equal(await page.evaluate(() => window.__TEST__.files.has("notes/welcome.md")), false);
await page.getByRole("tab", { name: /Release 1\.2\.md/ }).waitFor();
await page.locator('.tree').getByText("notes", { exact: true }).click();
await page.locator('.tree').getByText("Release 1.2", { exact: true }).waitFor();
await writer.click();
await page.keyboard.press("Control+z");
await page.keyboard.press("Control+s");
await page.waitForFunction(text => window.__TEST__.files.get("notes/Release 1.2.md") === text, original);
await page.keyboard.press("Control+y");
await page.keyboard.press("Control+s");
await page.waitForFunction(text => window.__TEST__.files.get("notes/Release 1.2.md") === text, original + "Unsaved text");
await editTitle("Cancelled");
await input.press("Escape");
await renamed("notes/Release 1.2.md");
assert.equal(await input.isVisible(), false);
// Keyboard activation and filename errors stay outside Markdown editing.
await title.focus(); await title.press("Enter");
await input.fill(" "); await input.press("Enter");
await page.getByRole("alert").filter({ hasText: "Name is empty" }).waitFor();
await input.fill("folder/note"); await input.press("Enter");
await page.getByRole("alert").filter({ hasText: "path separator" }).waitFor();
await input.fill("second"); await input.press("Enter");
await page.getByRole("alert").filter({ hasText: "already exists" }).waitFor();
assert.equal(await input.inputValue(), "second");
assert.equal(await page.evaluate(() => window.__TEST__.files.get("notes/second.md")), "# Second note\n");
await input.fill("Renamed.md"); await input.press("Tab");
await renamed("notes/Renamed.md");
await page.mouse.move(10, 10);
await page.screenshot({ path: ".audit/rename-title.png" });
// A pending rename belongs to its original document even if the tab changes.
await page.evaluate(() => { window.__TEST__.delayRename = true; });
await editTitle("Background"); await input.press("Enter");
await page.waitForFunction(() => !!window.__TEST__.resumeRename);
await page.locator('.tree').getByText("second", { exact: true }).click();
await renamed("notes/second.md");
await page.evaluate(() => { window.__TEST__.resumeRename(); window.__TEST__.delayRename = false; });
await page.getByRole("tab", { name: "Background.md", exact: true }).waitFor();
await renamed("notes/second.md");
await page.getByRole("tab", { name: "Background.md", exact: true }).click();
await renamed("notes/Background.md");
// Disk reload after rename must not restore the old displayed title.
await page.evaluate(() => {
window.__TEST__.files.set("notes/Background.md", "Reloaded\n");
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "modify", paths: ["notes/Background.md"] });
});
await page.waitForFunction(() => document.querySelector(".cm-line")?.textContent === "Reloaded");
assert.ok((await title.innerText()).startsWith("Background"));
assert.deepEqual(errors, []);
console.log("PASS: inline filename rename, folder/extension preservation, tabs/tree, contents and undo, Enter/blur/Escape, validation/collisions, tab switching during rename, and reload (mocked desktop IPC).");
} catch (error) {
console.error("Browser errors:", errors);
console.error("Visible text:", (await page.locator("body").innerText()).slice(0, 3000));
await page.screenshot({ path: ".audit/rename-title-failure.png" });
throw error;
} finally { await browser.close(); }
const output = await outputDir("tree/renameTitle");
const title = page.getByRole("button", { name: "Rename note", exact: true });
const input = page.getByRole("textbox", { name: "Note filename", exact: true });
const writer = page.getByRole("textbox", { name: "Writing editor", exact: true });
// Empty names and path separators share one message (src/lib/workspace/renamePath.ts:56-57, used by Workbench.svelte:958).
const invalidName = "Enter a document name without a leading dot or reserved filename characters.";
async function openNote(name) {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
await title.waitFor();
}
async function editTitle(value) { await title.click(); await input.fill(value); }
const renamed = name => page.waitForFunction(expected => document.querySelector(".breadcrumb")?.textContent === expected, name);
try {
await page.goto(smokeUrl);
await page.getByText("smoke-workspace", { exact: true }).waitFor();
await openNote("welcome.md");
const original = await page.evaluate(() => window.__TEST__.files.get("notes/welcome.md"));
await writer.click();
await page.keyboard.press("Control+End");
await page.keyboard.type("Unsaved text");
await editTitle("Release 1.2");
await input.press("Enter");
await renamed("notes/Release 1.2.md");
assert.equal(await page.evaluate(() => window.__TEST__.files.has("notes/welcome.md")), false);
await page.getByRole("tab", { name: /Release 1\.2\.md/ }).waitFor();
await page.locator(".tree").getByText("notes", { exact: true }).click();
await page.locator(".tree").getByText("Release 1.2", { exact: true }).waitFor();
await writer.click();
await page.keyboard.press("Control+z");
await page.keyboard.press("Control+s");
await page.waitForFunction(text => window.__TEST__.files.get("notes/Release 1.2.md") === text, original);
await page.keyboard.press("Control+y");
await page.keyboard.press("Control+s");
await page.waitForFunction(text => window.__TEST__.files.get("notes/Release 1.2.md") === text, original + "Unsaved text");
await editTitle("Cancelled");
await input.press("Escape");
await renamed("notes/Release 1.2.md");
assert.equal(await input.isVisible(), false);
// Keyboard activation and filename errors stay outside Markdown editing.
await title.focus(); await title.press("Enter");
await input.fill(" "); await input.press("Enter");
await page.getByRole("alert").filter({ hasText: invalidName }).waitFor();
await input.fill("folder/note"); await input.press("Enter");
await page.getByRole("alert").filter({ hasText: invalidName }).waitFor();
await page.waitForFunction(() => !document.querySelector(".note-title-input[aria-busy]"));
assert.equal(await page.evaluate(() => window.__TEST__.calls.some(call => call.command === "workspace_rename" && call.args.to.includes("folder"))), false);
await input.fill("second"); await input.press("Enter");
await page.getByRole("alert").filter({ hasText: "already exists" }).waitFor();
assert.equal(await input.inputValue(), "second");
assert.equal(await page.evaluate(() => window.__TEST__.files.get("notes/second.md")), "# Second note\n");
await input.fill("Renamed.md"); await input.press("Tab");
await renamed("notes/Renamed.md");
await page.mouse.move(10, 10);
await page.screenshot({ path: path.join(output, "rename-title.png") });
// A pending rename belongs to its original document even if the tab changes.
await page.evaluate(() => { window.__TEST__.delayRename = true; });
await editTitle("Background"); await input.press("Enter");
await page.waitForFunction(() => !!window.__TEST__.resumeRename);
// A plain tree click replaces the current tab (src/lib/layout/Workbench.svelte:1347), so open the other note in a new tab.
await page.locator('[data-tree-rel="notes/second.md"]').click({ button: "right" });
await page.getByRole("menuitem", { name: "Open in new tab", exact: true }).click();
await renamed("notes/second.md");
await page.evaluate(() => { window.__TEST__.resumeRename(); window.__TEST__.delayRename = false; });
await page.getByRole("tab", { name: "Background.md", exact: true }).waitFor();
await renamed("notes/second.md");
await page.getByRole("tab", { name: "Background.md", exact: true }).click();
await renamed("notes/Background.md");
// Disk reload after rename must not restore the old displayed title.
await page.evaluate(() => {
window.__TEST__.files.set("notes/Background.md", "Reloaded\n");
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "modify", paths: ["notes/Background.md"] });
});
await page.waitForFunction(() => document.querySelector(".cm-line")?.textContent === "Reloaded");
assert.ok((await title.innerText()).startsWith("Background"));
} catch (error) {
console.error("Visible text:", (await page.locator("body").innerText()).slice(0, 3000));
await page.screenshot({ path: path.join(output, "rename-title-failure.png") });
throw error;
}
});
+89 -98
View File
@@ -1,123 +1,115 @@
// Tree rename undo and redo keep folders expanded; New note templates, Git plug-in navigation, and detached tab layout isolation.
// @requires repo:RuneStone_Git/dist
import { createRequire } from 'node:module';
import assert from 'node:assert/strict';
import { mkdir, readFile } from 'node:fs/promises';
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const context = await browser.newContext({ viewport: { width: 1200, height: 850 } });
const page = await context.newPage();
const errors = [];
page.on('pageerror', error => errors.push(error.message));
const gitRoot = new URL('../../../../RuneStone_Git/dist/', import.meta.url);
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { mockTauri, openPage, outputDir, pluginRepo, runSmoke, smokeUrl } from '../_harness/index.mjs';
const gitRoot = path.join(pluginRepo('RuneStone_Git'), 'dist');
const git = {
manifest: JSON.parse(await readFile(new URL('plugin.json', gitRoot), 'utf8')),
code: await readFile(new URL('main.js', gitRoot), 'utf8'),
css: (await readFile(new URL('style.css', gitRoot))).toString('base64'),
manifest: JSON.parse(await readFile(path.join(gitRoot, 'plugin.json'), 'utf8')),
code: await readFile(path.join(gitRoot, 'main.js'), 'utf8'),
css: (await readFile(path.join(gitRoot, 'style.css'))).toString('base64'),
};
await context.addInitScript(git => {
window.isTauri = true;
const root = 'C:\\host-todo-test';
const files = new Map([['a.md', '# Note\n\nOriginal text.'], ['folder/nested/note.md', '# Nested'], ['other/keep.md', '# Keep'], ['.runestone/templates/Daily.md', '# Daily\n\n## Tasks'], ['.runestone/marks.json', JSON.stringify({ pins: ['a.md'], bookmarks: ['a.md'], order: { '': ['a.md'] } })]]);
const state = { files, calls: [], exportResult: 'C:\\exports\\my-theme.json', exportError: '' };
window.__HOST_TEST__ = state;
let sequence = 0;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
transformCallback: () => ++sequence, unregisterCallback: () => {},
invoke: async (command, args = {}) => {
state.calls.push({ command, args });
if (command === 'plugins_snapshot') return { root: 'C:/plugins', plugins: [{ manifest: git.manifest, hash: 'navigation-git', enabled: true, installedAt: 1, path: 'C:/plugins/runestone.git', error: null, removal: false }] };
if (command === 'plugins_load') return git.code;
if (command === 'plugins_asset') return git.css;
if (command === 'plugins_data') return 'null';
if (command === 'workspace_last_path') return root;
if (command === 'workspace_open') return { root, name: 'host-todo-test', watch_mode: 'native' };
if (command === 'workspace_read') { if (!files.has(args.rel)) throw new Error('Missing file'); return files.get(args.rel); }
if (command === 'workspace_list') {
const prefix = args.rel ? args.rel + '/' : '';
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || (!args.rel && path.startsWith('.runestone/'))) continue;
const tail = path.slice(prefix.length), name = tail.split('/')[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes('/') ? 'folder' : 'file' });
}
return [...entries.values()];
}
if (command === 'workspace_create') { if (files.has(args.rel)) throw new Error('Destination exists'); files.set(args.rel, ''); return; }
if (command === 'workspace_write') {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error('Changed on disk');
files.set(args.rel, args.contents); return;
}
if (command === 'workspace_rename') {
if (files.has(args.to)) throw new Error('Destination exists');
if (![...files.keys()].some(path => path === args.from || path.startsWith(args.from + '/'))) throw new Error('Missing file');
for (const [path, contents] of [...files]) { if (path === args.from || path.startsWith(args.from + '/')) { files.set(args.to + path.slice(args.from.length), contents); files.delete(path); } } return;
}
if (command === 'workspace_delete') { files.delete(args.rel); return; }
if (command === 'workspace_search') return [];
if (command === 'plugin:event|listen') return ++sequence;
if (command === 'plugin:window|is_maximized') return false;
if (command === 'plugin:dialog|message') return 'Ok';
if (command === 'theme_export') { if (state.exportError) throw new Error(state.exportError); return state.exportResult; }
return null;
await runSmoke('tree/renameUndo', async ({ browser }) => {
const context = await browser.newContext({ viewport: { width: 1200, height: 850 } });
await mockTauri(context, {
strict: false,
state: git,
commands: test => {
const git = test.state;
const ws = test.workspace({
root: 'C:\\host-todo-test',
files: {
'a.md': '# Note\n\nOriginal text.', 'folder/nested/note.md': '# Nested', 'other/keep.md': '# Keep', '.runestone/templates/Daily.md': '# Daily\n\n## Tasks',
'.runestone/marks.json': JSON.stringify({ pins: ['a.md'], bookmarks: ['a.md'], order: { '': ['a.md'] } }),
},
});
const files = ws.files;
const within = (from, path) => path === from || path.startsWith(from + '/');
test.files = files;
return {
workspace_last_path: ws.workspace_last_path,
workspace_open: ws.workspace_open,
workspace_read: ws.workspace_read,
workspace_list: args => ws.workspace_list(args).filter(entry => args.rel || !entry.rel_path.startsWith('.runestone')),
workspace_create: ({ rel }) => { if (files.has(rel)) throw new Error('Destination exists'); files.set(rel, ''); },
workspace_write: ({ rel, contents, expected }) => {
if (expected !== undefined && files.get(rel) !== expected) throw new Error('Changed on disk');
files.set(rel, contents);
},
workspace_rename: ({ from, to }) => {
if (files.has(to)) throw new Error('Destination exists');
if (![...files.keys()].some(path => within(from, path))) throw new Error('Missing file');
for (const [path, contents] of [...files]) if (within(from, path)) { files.set(to + path.slice(from.length), contents); files.delete(path); }
},
workspace_delete: ({ rel }) => { files.delete(rel); },
workspace_search: () => [],
plugins_snapshot: () => ({ root: 'C:/plugins', plugins: [{ manifest: git.manifest, hash: 'navigation-git', enabled: true, installedAt: 1, path: 'C:/plugins/runestone.git', error: null, removal: false }] }),
plugins_load: () => git.code,
plugins_asset: () => git.css,
plugins_data: () => 'null',
'plugin:window|is_maximized': () => false,
'plugin:dialog|message': () => 'Ok',
};
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
}, git);
const origin = process.env.SMOKE_URL || 'http://127.0.0.1:5186';
const row = path => page.locator(`[data-tree-rel="${path}"]`);
const item = name => page.getByRole('menuitem', { name, exact: true });
async function paneMenu() { await page.getByRole('navigation', { name: 'Workspace files' }).click({ button: 'right', position: { x: 90, y: 360 } }); }
async function rename(path, name) {
await row(path).click({ button: 'right' }); await item('Rename').click();
await page.locator('.tree input').fill(name); await page.locator('.tree input').press('Enter');
}
async function expanded(path) { assert.equal(await row(path).getAttribute('aria-expanded'), 'true', `${path} stays expanded`); }
await mkdir('output/host-navigation-pass3', { recursive: true });
try {
await page.goto(origin);
});
const page = await openPage(context, { timeout: 30000 });
const output = await outputDir('tree/renameUndo');
const shot = (target, name) => target.screenshot({ path: path.join(output, name) });
const row = rel => page.locator(`[data-tree-rel="${rel}"]`);
const item = name => page.getByRole('menuitem', { name, exact: true });
const setMode = (target, mode) => target.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); }, mode);
async function paneMenu() { await page.getByRole('navigation', { name: 'Workspace files' }).click({ button: 'right', position: { x: 90, y: 360 } }); }
async function rename(rel, name) {
await row(rel).click({ button: 'right' }); await item('Rename').click();
await page.locator('.tree input').fill(name); await page.locator('.tree input').press('Enter');
}
async function expanded(rel) { assert.equal(await row(rel).getAttribute('aria-expanded'), 'true', `${rel} stays expanded`); }
await page.goto(smokeUrl);
await row('folder').click(); await row('folder/nested').click(); await row('other').click();
await rename('folder/nested/note.md', 'renamed.md'); await row('folder/nested/renamed.md').waitFor();
await row('folder/nested/renamed.md').focus(); await page.keyboard.press('Control+z');
await row('folder/nested/note.md').waitFor();
for (const path of ['folder', 'folder/nested', 'other']) await expanded(path);
for (const rel of ['folder', 'folder/nested', 'other']) await expanded(rel);
await page.keyboard.press('Control+y'); await row('folder/nested/renamed.md').waitFor();
for (const path of ['folder', 'folder/nested', 'other']) await expanded(path);
for (const rel of ['folder', 'folder/nested', 'other']) await expanded(rel);
await rename('folder', 'renamed-folder'); await row('renamed-folder/nested/renamed.md').waitFor();
await row('renamed-folder').focus(); await page.keyboard.press('Control+z');
await row('folder/nested/renamed.md').waitFor();
for (const path of ['folder', 'folder/nested', 'other']) await expanded(path);
for (const rel of ['folder', 'folder/nested', 'other']) await expanded(rel);
await page.keyboard.press('Control+y'); await row('renamed-folder/nested/renamed.md').waitFor();
for (const path of ['renamed-folder', 'renamed-folder/nested', 'other']) await expanded(path);
for (const rel of ['renamed-folder', 'renamed-folder/nested', 'other']) await expanded(rel);
await paneMenu(); assert.equal(await item('Manage templates…').isVisible(), false);
await item('New note').click(); await row('untitled.md').waitFor();
assert.equal(await page.evaluate(() => window.__HOST_TEST__.files.get('untitled.md')), '');
assert.equal(await page.evaluate(() => window.__TEST__.files.get('untitled.md')), '');
await paneMenu(); await item('New note').focus(); await page.keyboard.press('ArrowRight');
await item('Daily').click(); await row('Daily.md').waitFor();
assert.equal(await page.evaluate(() => window.__HOST_TEST__.files.get('Daily.md')), '# Daily\n\n## Tasks');
assert.equal(await page.evaluate(() => window.__TEST__.files.get('Daily.md')), '# Daily\n\n## Tasks');
await paneMenu(); await item('New note').hover(); await item('Manage templates…').click();
await page.getByRole('button', { name: 'Close templates', exact: true }).click();
for (const mode of ['light', 'dark']) {
await page.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); }, mode);
await setMode(page, mode);
await paneMenu(); await item('New note').focus(); await page.keyboard.press('ArrowRight');
await page.screenshot({ path: `output/host-navigation-pass3/note-menu-${mode}.png` });
await shot(page, `note-menu-${mode}.png`);
await page.keyboard.press('Escape'); await page.keyboard.press('Escape');
}
await page.setViewportSize({ width: 600, height: 600 });
await paneMenu(); await item('New note').focus(); await page.keyboard.press('ArrowRight');
await page.screenshot({ path: 'output/host-navigation-pass3/note-menu-dark-narrow.png' });
await shot(page, 'note-menu-dark-narrow.png');
assert.ok(await item('Manage templates…').evaluate(node => node.getBoundingClientRect().right <= innerWidth));
await page.keyboard.press('Escape'); await page.keyboard.press('Escape');
await page.setViewportSize({ width: 1200, height: 850 });
await page.evaluate(() => { window.__HOST_TEST__.files.delete('.runestone/templates/Daily.md'); window.dispatchEvent(new Event('runestone-templates-changed')); });
await page.evaluate(() => { window.__TEST__.files.delete('.runestone/templates/Daily.md'); window.dispatchEvent(new Event('runestone-templates-changed')); });
await paneMenu(); await item('New note').focus(); await page.keyboard.press('ArrowRight');
assert.equal(await item('Daily').count(), 0);
await item('Manage templates…').click();
await page.getByRole('button', { name: 'Close templates', exact: true }).click();
const creations = await page.evaluate(() => window.__HOST_TEST__.calls.filter(call => call.command === 'workspace_create').length);
const creations = await page.evaluate(() => window.__TEST__.calls.filter(call => call.command === 'workspace_create').length);
await paneMenu(); await item('New note').focus(); await page.keyboard.press('Enter');
await page.waitForFunction(count => window.__HOST_TEST__.calls.filter(call => call.command === 'workspace_create').length === count + 1, creations);
await page.waitForFunction(count => window.__TEST__.calls.filter(call => call.command === 'workspace_create').length === count + 1, creations);
await page.getByRole('button', { name: 'Source control', exact: true }).waitFor();
assert.equal(await page.locator('.header-left').getByRole('button', { name: 'Source control', exact: true }).count(), 1);
await page.getByRole('button', { name: 'Plug-in views', exact: true }).click();
@@ -127,7 +119,7 @@ try {
const graphIcon = await graph.locator('.action-icon').innerHTML();
const expectedIcon = await page.evaluate(async () => (await import('/src/lib/ui/actionIcons.ts')).actionIcon('git').innerHTML);
assert.equal(graphIcon, expectedIcon, 'The real Git graph command uses the shared Git icon');
await page.screenshot({ path: 'output/host-navigation-pass3/real-git-command-dark.png' });
await shot(page, 'real-git-command-dark.png');
await page.keyboard.press('Escape');
await page.evaluate(async () => {
const external = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
@@ -135,10 +127,10 @@ try {
external.pluginTools.set([{ owner: 'pm-test', id: 'pm', title: 'Project Management', kind: 'view', surface: 'open' }, { owner: 'git-test', id: 'graph', title: 'Graph view', kind: 'command', surface: 'open', icon: 'git' }]);
external.pluginTools.update(items => [...items, { owner: 'runestone.browser', id: 'new-tab', title: 'New browser tab', kind: 'command', surface: 'open' }]);
const registry = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/registry.ts').name);
registry.pluginHost.get('browser').newTab = async () => { window.__HOST_TEST__.browserOpened = true; };
registry.pluginHost.get('browser').newTab = async () => { window.__TEST__.browserOpened = true; };
});
await page.locator('.header-right').getByRole('button', { name: 'New browser tab', exact: true }).click();
assert.equal(await page.evaluate(() => window.__HOST_TEST__.browserOpened), true);
assert.equal(await page.evaluate(() => window.__TEST__.browserOpened), true);
assert.equal(await page.locator('.header-right').getByRole('button', { name: 'Project Management', exact: true }).count(), 0);
assert.equal(await page.locator('.header-left').getByRole('button', { name: 'Source control', exact: true }).count(), 1);
assert.equal(await page.locator('.header-right').getByRole('button', { name: 'Source control', exact: true }).count(), 0);
@@ -147,9 +139,9 @@ try {
assert.equal(await page.getByRole('menuitem', { name: /New browser tab/ }).count(), 0);
await page.getByRole('menuitem', { name: /Graph view/ }).waitFor(); await page.keyboard.press('Escape');
for (const mode of ['light', 'dark']) {
await page.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); }, mode);
await setMode(page, mode);
await page.getByRole('button', { name: 'Plug-in views', exact: true }).click();
await page.screenshot({ path: `output/host-navigation-pass3/plugin-navigation-${mode}.png` });
await shot(page, `plugin-navigation-${mode}.png`);
await page.keyboard.press('Escape');
}
const token = '00000000-0000-4000-8000-000000000001';
@@ -159,9 +151,8 @@ try {
localStorage.setItem(`runestone.tab-transfer.${token}`, JSON.stringify({ root: 'C:\\host-todo-test', created: Date.now(), buffer: { id: 'moved', relPath: 'a.md', name: 'a.md', kind: 'text', contents: '# Transferred', saved: '# Note', chrome: 'Writing', pinned: true } }));
return layout;
}, token);
const detached = await context.newPage();
detached.on('pageerror', error => errors.push(error.message));
await detached.goto(`${origin}/?tabTransfer=${token}`);
const detached = await openPage(context, { timeout: 30000 });
await detached.goto(`${smokeUrl}/?tabTransfer=${token}`);
await detached.getByRole('tab', { name: /a.md/ }).waitFor();
await detached.getByText('# Transferred', { exact: true }).waitFor();
assert.equal(await detached.locator('.shell.left-open,.shell.right-open').count(), 0);
@@ -174,10 +165,10 @@ try {
await detached.keyboard.press('Escape');
assert.equal(await detached.evaluate(() => localStorage.getItem('runestone.workbenchLayout')), saved);
for (const mode of ['light', 'dark']) {
await detached.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); }, mode);
await setMode(detached, mode);
await detached.setViewportSize({ width: 650, height: 600 });
await detached.screenshot({ path: `output/host-navigation-pass3/detached-${mode}-narrow.png` });
await shot(detached, `detached-${mode}-narrow.png`);
}
assert.deepEqual(errors, []);
assert.deepEqual([...page.errors, ...detached.errors], []);
console.log('Host navigation passed: nested file/folder rename undo/redo, expanded folders, blank New note parent, template submenu, plugin navigation dedup, detached layout isolation.');
} finally { await browser.close(); }
});

Some files were not shown because too many files have changed in this diff Show More