Improve editor, plugin updates, and window transfers for 0.1.41

This commit is contained in:
Knotty Wyvern
2026-10-21 10:42:44 -07:00
parent 68e86ab6eb
commit 42dd0fa711
56 changed files with 2313 additions and 221 deletions
+2 -2
View File
@@ -65,13 +65,13 @@ test('Full transparency range produces valid surface opacity values', () => {
}
}
});
test('Opaque mode removes surface transparency and retains the amount for re-enabling', () => {
test('Opaque mode retains background ownership and the amount for re-enabling', () => {
const values = new Map<string, string>();
const root = { dataset: {} as Record<string, string>, style: { setProperty: (key: string, value: string) => values.set(key, value) } } as unknown as HTMLElement;
applyTransparency({ enabled: false, amount: 32 }, root);
assert.equal(values.get('--rs-surface-opacity'), '100%');
assert.equal(values.get('--rs-editor-surface-opacity'), '100%');
assert.equal(values.get('--rs-transparent-plugin-bg'), 'var(--rs-bg)');
assert.equal(values.get('--rs-transparent-plugin-bg'), 'transparent');
assert.equal(root.dataset.transparency, 'off');
applyTransparency({ enabled: true, amount: 18 }, root);
assert.equal(values.get('--rs-surface-opacity'), '82%');
+23
View File
@@ -0,0 +1,23 @@
import test from "node:test";
import assert from "node:assert/strict";
import { SearchQuery } from "@codemirror/search";
import { documentMatches, replacementText } from "../src/lib/editor/findTarget.ts";
test("document search uses Writer word matching and normalized CRLF positions", () => {
const query = new SearchQuery({ search: "Alpha", wholeWord: true, caseSensitive: true });
const { state, matches } = documentMatches("Alpha alphabet\r\nalpha Alpha", query);
assert.deepEqual(matches.map(({ from, to }) => ({ from, to })), [{ from: 0, to: 5 }, { from: 21, to: 26 }]);
assert.equal(state.doc.lineAt(matches[1].from).number, 2);
assert.equal(state.doc.lineAt(matches[1].from).from, 15);
});
test("replacement keeps regex context, capture groups, dollars, and line breaks", () => {
const query = new SearchQuery({ search: "(?<=G)(amma)", regexp: true, replace: "$1-$12-$&-$$\\n" });
assert.equal(replacementText("Gamma", 1, query), "amma-amma2-amma-$\n");
assert.equal(replacementText("Alpha", 0, new SearchQuery({ search: "Alpha", replace: "$1\\t" })), "$1\t");
});
test("empty and invalid queries do not produce matches", () => {
assert.deepEqual(documentMatches("Alpha", new SearchQuery({ search: "" })).matches, []);
assert.deepEqual(documentMatches("Alpha", new SearchQuery({ search: "[", regexp: true })).matches, []);
});
+19
View File
@@ -24,6 +24,25 @@ function setup() {
return { docs, disk, io };
}
test("imported tabs retain unsaved text and preserve pinned empty tabs", async () => {
const { docs } = setup();
docs.newTab();
const empty = docs.active!;
docs.togglePin(empty.relPath);
const source = setup().docs;
await source.open(entry("note.md"));
source.edit(source.active!.id, "unsaved source text");
source.togglePin("note.md");
assert.equal(docs.importTab(source.active!), true);
assert.equal(docs.active!.contents, "unsaved source text");
assert.equal(docs.active!.saved, "original");
assert.equal(docs.active!.pinned, true);
assert.notEqual(docs.active!.id, source.active!.id);
assert.ok(docs.buffers.some(tab => tab.id === empty.id));
assert.equal(docs.importTab({ ...source.active!, contents: "different" }), false);
assert.equal(docs.active!.contents, "unsaved source text");
});
test("background loading for a split preserves the selected document and its unsaved edits", async () => {
const { docs } = setup();
await docs.open(entry("note.md"));
+149
View File
@@ -0,0 +1,149 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
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 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 };
});
try {
await mkdir('output/editor-clipboard-checklist', { 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();
await page.evaluate(async () => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
window.__CM__ = EditorView.findFromDOM(document.querySelector('.cm-content'));
});
const source = '# Clipboard and tasks\n\n- [ ] CCNA lab\n- [x] CCNA course\n\nPaste here.\n';
const reset = async () => page.evaluate(source => {
window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: source }, selection: { anchor: source.indexOf('CCNA lab') } });
window.__CM__.focus();
}, source);
const count = () => page.locator('.writer-checkbox').count();
const clipboard = '<html><body><!--StartFragment--><table><thead><tr><th>Ticker</th><th>Name</th></tr></thead><tbody><tr><td>ADBE.US</td><td>Adobe</td></tr><tr><td>ADSK.US</td><td>Autodesk</td></tr></tbody></table><!--EndFragment--></body></html>';
for (const mode of ['dark', 'light']) {
await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({ theme: 'default', mode }), mode);
for (const width of [1440, 600]) {
if (width === 600) {
await page.getByRole('button', { name: 'Files', exact: true }).click();
await page.getByRole('button', { name: 'Hide outline', exact: true }).click();
}
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.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.keyboard.press('Home');
assert.equal(await count(), 1, 'Home keeps the marker editable');
await page.keyboard.press('ArrowRight');
await page.keyboard.press('ArrowRight');
await page.keyboard.press('ArrowRight');
await page.keyboard.press('Delete');
await page.keyboard.type('x');
assert.match(await page.evaluate(() => window.__CM__.state.sliceDoc()), /- \[x\] CCNA lab/);
await page.keyboard.press('Home');
for (let i = 0; i < 6; i++) await page.keyboard.press('ArrowRight');
assert.equal(await count(), 2, 'Leaving the marker restores the checkbox');
await page.keyboard.type('New ');
assert.equal(await count(), 2, 'Typing task text keeps the checkbox');
await page.locator('.writer-checkbox').first().click();
assert.match(await page.evaluate(() => window.__CM__.state.sliceDoc()), /- \[ \] New CCNA lab/);
await page.evaluate(() => {
const view = window.__CM__;
view.dispatch({ selection: { anchor: view.state.sliceDoc().indexOf('Paste here.') } }); view.focus();
});
await page.getByRole('textbox', { name: 'Writing editor', exact: true }).evaluate((node, html) => {
const data = new DataTransfer(); data.setData('text/html', html); data.setData('text/plain', 'Ticker\tName\nADBE.US\tAdobe\nADSK.US\tAutodesk');
node.dispatchEvent(new ClipboardEvent('paste', { clipboardData: data, bubbles: true, cancelable: true }));
}, clipboard);
await page.locator('.live-writer table').waitFor();
const pasted = await page.evaluate(() => window.__CM__.state.sliceDoc());
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` });
if (width === 600) {
await page.setViewportSize({ width: 1440, height: 1000 });
await page.getByRole('button', { name: 'Files', exact: true }).click();
await page.getByRole('button', { name: 'Show outline', exact: true }).click();
}
}
}
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(); }
+155
View File
@@ -0,0 +1,155 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
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 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 };
});
try {
await mkdir('output/editor-template-hyphen', { recursive: true });
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
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.
await page.evaluate(async () => {
const { saveNoteTemplate } = await import('/src/lib/workspace/templates.ts');
await saveNoteTemplate('To Do', '- [ ] \n'.repeat(10));
});
await page.getByRole('button', { name: 'New tab (Ctrl T)', exact: true }).click();
await page.getByRole('button', { name: 'New note', exact: true }).last().click();
await page.getByRole('menuitem', { name: 'To Do', exact: true }).click();
const title = page.getByRole('textbox', { name: 'Note filename', exact: true });
await title.waitFor();
await page.waitForFunction(() => document.activeElement?.getAttribute('aria-label') === 'Note filename');
await page.evaluate(async () => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
window.__CM__ = EditorView.findFromDOM(document.querySelector('.cm-content'));
});
const count = () => page.locator('.writer-checkbox').count();
const expectCount = async expected => {
await page.waitForFunction(expected => document.querySelectorAll('.writer-checkbox').length === expected, expected);
assert.equal(await count(), expected);
};
const setSource = source => page.evaluate(source => {
window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: source }, selection: { anchor: source.length } });
window.__CM__.focus();
}, source);
const plain = 'Some generic mobs or factions,\n-';
for (const mode of ['dark', 'light']) {
await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({ theme: 'default', mode }), mode);
for (const width of [1440, 600]) {
await page.setViewportSize({ width, height: width === 600 ? 760 : 1000 });
if (width === 600) {
await page.getByRole('button', { name: 'Files', exact: true }).click();
await page.getByRole('button', { name: 'Hide outline', exact: true }).click();
}
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.keyboard.press('Escape');
await page.evaluate(() => {
const view = window.__CM__;
view.dispatch({ selection: { anchor: 0 } }); view.focus();
});
await expectCount(9);
await page.keyboard.press('End');
await page.keyboard.type('First task');
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 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.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');
await setSource(plain + '-');
assert.equal(await page.locator('.writer-h2').count(), 1, 'Two hyphens retain Setext heading support');
await setSource('A normal heading\n===\n');
assert.equal(await page.locator('.writer-h1').count(), 1);
// Restore the template for the next theme and size without an active body caret.
await setSource('- [ ] \n'.repeat(10));
await page.getByRole('button', { name: 'Rename note', exact: true }).click();
if (width === 600) {
await page.setViewportSize({ width: 1440, height: 1000 });
await page.getByRole('button', { name: 'Files', exact: true }).click();
await page.getByRole('button', { name: 'Show outline', exact: true }).click();
}
}
}
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(); }
+23 -20
View File
@@ -2,7 +2,6 @@ import test from "node:test";
import assert from "node:assert/strict";
import { ExternalSession } from "../src/lib/plugins/externalSession.ts";
import type { PluginApi } from "../src/lib/plugins/sdk.ts";
import { locale } from "../src/lib/i18n/index.ts";
function fixture() {
let writes = 0;
const session = new ExternalSession("org.test.demo", {
@@ -13,25 +12,6 @@ function fixture() {
return { session, writes: () => writes };
}
test("plugin language changes stop before cleanup and reject later access", async () => {
const { session } = fixture();
const changes: string[] = [];
let api!: PluginApi;
try {
await session.start({ activate(value) {
api = value;
api.i18n!.subscribe(language => changes.push(language));
api.onDispose(() => { locale.set('ja'); });
} });
locale.set('fr');
assert.equal(api.i18n!.t('Settings'), 'Paramètres');
await session.stop();
assert.deepEqual(changes, ['en', 'fr']);
assert.throws(() => api.i18n!.t('Settings'), /disabled/);
assert.throws(() => api.i18n!.locale, /disabled/);
} finally { await session.stop(); locale.set('en'); }
});
test("native Markdown discovery remains optional and is revoked on disable", async () => {
let api!: PluginApi;
let scans = 0;
@@ -133,3 +113,26 @@ test("batch workspace reads remain optional and stop when the plugin is disabled
await old.start({ activate(value) { assert.equal(value.workspace.readMany, undefined); } });
await old.stop();
});
test("view launch selects a default while explicit opens preserve their target", async () => {
const opened: string[] = [];
let api!: PluginApi;
const session = new ExternalSession("org.test.launch", {
workspace: { list: async () => [], read: async () => "", write: async () => {} },
settings: { read: async () => null, write: async () => {} },
assets: { read: async () => new Uint8Array() },
}, () => {}, id => { opened.push(id); });
await session.start({ activate(value) {
api = value;
api.registerView({ id: "all", title: "All", launch: async () => { api.openView("board"); }, mount() {} });
api.registerView({ id: "board", title: "Board", mount() {} });
assert.throws(() => api.registerView({ id: "invalid", title: "Invalid", launch: true as never, mount() {} }), /launch handler/);
} });
await session.launch("all");
api.openView("all");
await session.launch("board");
assert.deepEqual(opened, ["board", "all", "board"]);
await assert.rejects(session.launch("missing"), /Unknown plugin view/);
await session.stop();
await assert.rejects(session.launch("all"), /disabled/);
});
+17
View File
@@ -0,0 +1,17 @@
import assert from "node:assert/strict";
import test from "node:test";
import { htmlToMarkdown } from "../src/lib/workspace/htmlToMarkdown.ts";
test("Windows HTML clipboard fragment comments do not become table content", () => {
const html = '<html><body><!--StartFragment--><table><tr><th>Ticker</th><th>Name</th></tr><tr><td>ADBE.US</td><td>Adobe</td></tr><tr><td>ADSK.US</td><td>Autodesk</td></tr></table><!--EndFragment--></body></html>';
assert.equal(htmlToMarkdown(html), '| Ticker | Name |\n| --- | --- |\n| ADBE.US | Adobe |\n| ADSK.US | Autodesk |');
});
test("comments inside cells preserve adjacent text and formatting", () => {
const html = '<table><tr><th>Notes</th></tr><tr><td>First<!-- multi-line\n <b>comment</b> --> part<br><strong>Second</strong></td></tr></table>';
assert.equal(htmlToMarkdown(html), '| Notes |\n| --- |\n| First part<br>**Second** |');
});
test("escaped comment text remains user content", () => {
assert.equal(htmlToMarkdown('<p>&lt;!--Example--&gt;</p>'), '<!--Example-->');
});
+166
View File
@@ -0,0 +1,166 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
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 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 };
});
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 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();
}
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(); }
+159
View File
@@ -0,0 +1,159 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
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 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 };
});
try {
await mkdir('output/october15-editor', { 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();
await page.evaluate(async () => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
window.__CM__ = EditorView.findFromDOM(document.querySelector('.cm-content'));
});
const source = '# Example\n\n| Name | Notes |\n| --- | --- |\n| Alpha | First<br>Second |\n| Beta | Last |\n\nAfter.\n\n- [ ] A task\n';
const reset = async () => {
await page.evaluate(source => window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: source }, selection: { anchor: 0 } }), source);
await page.locator('.live-writer table').waitFor();
};
const cell = (r, c) => page.locator('.live-writer table tr').nth(r).locator('th,td').nth(c);
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();
await cell(1, 1).click();
await page.keyboard.press('Enter');
await page.waitForFunction(() => document.activeElement?.closest('td')?.cellIndex === 1 && document.activeElement.closest('tr').rowIndex === 2);
await page.keyboard.press('Enter');
await page.waitForFunction(() => document.activeElement?.closest('td')?.cellIndex === 1 && document.activeElement.closest('tr').rowIndex === 3);
assert.equal(await page.locator('.live-writer table tr').count(), 4);
await page.keyboard.type('New');
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 reset();
await cell(0, 0).click();
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem', { name: 'Select cell', exact: true }).click();
await page.keyboard.press('Shift+ArrowRight');
await page.keyboard.press('Shift+ArrowDown');
const copied = await page.locator('.writer-table').evaluate(node => {
const data = new DataTransfer();
node.dispatchEvent(new ClipboardEvent('copy', { clipboardData: data, bubbles: true, cancelable: true }));
return { html: data.getData('text/html'), text: data.getData('text/plain') };
});
assert.match(copied.html, /<table>/);
assert.match(copied.text, /Name\tNotes/);
await page.evaluate(() => {
const view = window.__CM__;
const anchor = view.state.sliceDoc().indexOf('After.');
view.dispatch({ selection: { anchor } }); view.focus();
});
await page.getByRole('textbox', { name: 'Writing editor', exact: true }).evaluate((node, copied) => {
const data = new DataTransfer(); data.setData('text/html', copied.html); data.setData('text/plain', copied.text);
node.dispatchEvent(new ClipboardEvent('paste', { clipboardData: data, bubbles: true, cancelable: true }));
}, 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 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 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 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 page.setViewportSize({ width: 600, height: 760 });
await reset();
await page.screenshot({ path: `output/october15-editor/${mode}-narrow.png` });
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(); }
+14 -1
View File
@@ -35,7 +35,9 @@ await context.addInitScript(() => {
}});
}`,
"org.example.tasks": `export function activate(api) {
api.registerView({ id: 'tasks', title: 'All tasks', icon: 'list', navigation: true, placement: 'editor', mount(container) { container.textContent = 'Task content'; } });
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'; } });
}`,
};
@@ -72,6 +74,17 @@ try {
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);
+176
View File
@@ -0,0 +1,176 @@
// 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;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener() {} };
window.__FILES__ = files;
}, { pm });
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
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.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
await page.getByRole('textbox', { name: 'Writing editor', exact: true }).click();
await page.keyboard.press('Control+f');
for (const label of ['Find in document', 'Replace with']) {
assert.equal(await page.getByRole('textbox', { name: label, exact: true }).getAttribute('autocomplete'), 'off');
}
await page.keyboard.press('Escape');
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'));
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();
await page.getByRole('textbox', { name: 'Writing editor', exact: true }).click();
await page.keyboard.press('Control+f');
const writerFind = page.getByRole('textbox', { name: 'Find in document', exact: true });
await writerFind.fill('fift');
assert.equal(await writerFind.getAttribute('autocomplete'), 'off');
assert.equal(await page.getByRole('textbox', { name: 'Replace with', exact: true }).getAttribute('autocomplete'), 'off');
await page.screenshot({ path: `${output}/find-privacy-${theme}.png` });
await page.setViewportSize({ width: 650, height: 800 });
await page.screenshot({ path: `${output}/find-privacy-${theme}-narrow.png` });
await page.keyboard.press('Escape');
await page.setViewportSize({ width: 1440, height: 1000 });
await page.mouse.move(900, 400);
await note.hover();
await page.getByRole('tooltip').filter({ hasText: /^New note$/ }).waitFor();
await page.screenshot({ path: `${output}/new-note-tooltip-${theme}.png` });
for (const name of ['Board', 'Changes']) {
await page.getByRole('navigation', { name: 'Plugin shortcuts' }).getByRole('button', { name, exact: true }).click();
const pane = page.getByRole('tabpanel', { name, exact: true });
await pane.getByRole('button', { name: 'Details', exact: true }).focus();
await page.keyboard.press('Control+f');
assert.equal(await pane.locator('.rs-find-bar').count(), 0, 'Non-document plugin views do not show document Find');
await page.screenshot({ path: `${output}/${name}-${theme}.png` });
await page.setViewportSize({ width: 650, height: 800 });
await page.keyboard.press('Control+f');
assert.equal(await pane.locator('.rs-find-bar').count(), 0);
await page.screenshot({ path: `${output}/${name}-${theme}-narrow.png` });
await page.setViewportSize({ width: 1440, height: 1000 });
}
for (const surface of ['all-tasks', 'board-document']) {
if (surface === 'all-tasks') {
await page.getByRole('button', { name: 'Plug-in views', exact: true }).click();
await page.getByRole('menuitem', { name: /^Project Management/ }).click();
} else await page.getByRole('tree', { name: 'Workspace files' }).getByText('Board', { exact: true }).dblclick();
const pane = page.locator('.plugin-editor-pane:visible');
await pane.locator('.pm-board').waitFor();
await pane.focus();
await page.keyboard.press('Control+f');
assert.equal(await pane.locator('.rs-find-bar').count(), 0, 'Actual PM views do not show host Find');
await page.screenshot({ path: `${output}/pm-${surface}-${theme}.png` });
await page.setViewportSize({ width: 650, height: 800 });
await page.keyboard.press('Control+f');
assert.equal(await pane.locator('.rs-find-bar').count(), 0);
await page.screenshot({ path: `${output}/pm-${surface}-${theme}-narrow.png` });
await page.setViewportSize({ width: 1440, height: 1000 });
}
await page.getByRole('tree', { name: 'Workspace files' }).getByText('sample', { exact: true }).dblclick();
for (const name of ['sample']) {
const pane = page.getByRole('tabpanel', { name, exact: true });
const returnButton = pane.getByRole('button', { name: 'Details', exact: true });
await returnButton.focus();
await page.keyboard.press('Control+f');
const find = pane.getByRole('textbox', { name: 'Find in document', exact: true });
assert.equal(await find.getAttribute('autocomplete'), 'off');
await find.fill('Alpha');
assert.equal(await page.locator('.rs-find-bar:visible').count(), 1);
assert.equal(await pane.getByRole('textbox', { name: 'Replace with' }).count(), 0);
await page.keyboard.press('Enter');
assert.equal(await page.evaluate(() => getSelection().toString()), 'Alpha');
await page.keyboard.press('F3');
assert.equal(await page.evaluate(() => getSelection().toString()), 'alpha');
await pane.getByText('Whole word', { exact: true }).click();
await find.focus();
const matches = [];
for (let i = 0; i < 4; i++) {
await page.keyboard.press('Enter');
matches.push(await page.evaluate(() => ({ text: getSelection().toString(), button: !!getSelection().anchorNode?.parentElement?.closest('button') })));
}
assert.equal(matches.filter(match => match.button).length, 1, 'Rendered card buttons participate in search');
assert.ok(matches.every(match => /^alpha$/i.test(match.text)));
await page.screenshot({ path: `${output}/${name}-${theme}.png` });
await page.setViewportSize({ width: 650, height: 800 });
await page.screenshot({ path: `${output}/${name}-${theme}-narrow.png` });
const bar = await pane.locator('.rs-find-bar').boundingBox(), bounds = await pane.boundingBox();
assert.ok(bar.x >= bounds.x && bar.x + bar.width <= bounds.x + bounds.width + 1);
await page.getByRole('button', { name: 'Files', exact: true }).click();
await page.getByRole('button', { name: 'Hide outline', exact: true }).click();
await page.screenshot({ path: `${output}/${name}-${theme}-narrow-focused.png` });
await find.focus();
await page.keyboard.press('Escape');
assert.equal(await returnButton.evaluate(node => node === document.activeElement), true);
await page.setViewportSize({ width: 1440, height: 1000 });
await page.getByRole('button', { name: 'Files', exact: true }).click();
await page.getByRole('button', { name: 'Show outline', exact: true }).click();
}
}
await page.getByRole('navigation', { name: 'Plugin shortcuts' }).getByRole('button', { name: 'Custom find', exact: true }).click();
await page.getByRole('tabpanel', { name: 'Custom find' }).focus();
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(); }
+27 -5
View File
@@ -57,7 +57,8 @@ await page.context().addInitScript(({ manifest, pluginCode }) => {
}
if (command === "plugins_cancel") { removalPrepared = false; return; }
if (command === "plugins_install") {
installed = [{ manifest, hash: 'reviewed-hash', enabled: args.enabled, installedAt: Date.parse('2026-10-05T18:24:36Z'), path, error: null, removal: false }];
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") {
@@ -167,14 +168,31 @@ try {
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.evaluate(async pluginId => {
const { runPluginCommand } = await import('/src/lib/plugins/external.ts');
await runPluginCommand(pluginId, 'show-overview');
}, manifest.id);
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);
}
}
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));
@@ -213,4 +231,8 @@ try {
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(); }
-35
View File
@@ -1,35 +0,0 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { locale } from '../src/lib/i18n/index.ts';
import { pluginTranslation } from '../src/lib/plugins/translation.ts';
test('Plugin messages use the host language, explicit catalogs, and safe fallbacks', () => {
const api = pluginTranslation(() => {}, () => {});
try {
locale.set('fr');
assert.equal(api.locale, 'fr');
assert.equal(api.t('Settings'), 'Paramètres');
assert.equal(api.t('Column {name}', { name: '<b>User data</b>' }, { fr: { 'Column {name}': 'Colonne {name}' } }), 'Colonne <b>User data</b>');
assert.equal(api.t('Unknown {name}', { name: 'text' }), 'Unknown text');
assert.equal(api.t('constructor'), 'constructor');
assert.equal(api.t('Settings', {}, { fr: Object.create({ Settings: 'Inherited' }) }), 'Paramètres');
} finally { locale.set('en'); }
});
test('Plugin language subscriptions stop at disposal and reject access after disable', () => {
const cleanup: (() => void)[] = [], languages: string[] = [];
let stopped = false;
const api = pluginTranslation(() => { if (stopped) throw new Error('Disabled'); }, off => cleanup.push(off));
try {
api.subscribe(language => languages.push(language));
locale.set('ja');
assert.deepEqual(languages, ['en', 'ja']);
stopped = true;
for (const off of cleanup) off();
locale.set('zh-CN');
assert.deepEqual(languages, ['en', 'ja']);
assert.throws(() => api.locale, /Disabled/);
assert.throws(() => api.t('Settings'), /Disabled/);
assert.throws(() => api.subscribe(() => {}), /Disabled/);
} finally { locale.set('en'); }
});
+3
View File
@@ -114,6 +114,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.
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), "note-15.md");
+129
View File
@@ -0,0 +1,129 @@
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: 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}`);
},
};
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"]) {
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` });
}
}
try {
await Promise.all([source.goto(url), target.goto(url), other.goto(url + "/?other")]);
await open(source, "a.md");
await open(target, "b.md");
await tab(source, "a.md").click({ button: "right" });
await source.getByRole("menuitem", { name: "Pin", exact: true }).click();
await source.locator(".cm-content").fill("Unsaved transfer text");
let data = await start(source, "a.md");
assert.ok(JSON.parse(data).tabTransfer);
await drop(other, data);
await other.getByText("Move tabs only between windows of the same workspace.").waitFor();
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);
await changedTarget.getByRole("tab").first().waitFor();
await open(source, "a.md");
data = await start(source, "a.md");
await source.locator(".cm-content").fill("Changed during transfer");
await drop(changedTarget, data);
await tab(changedTarget, "a.md").waitFor();
assert.equal(await tab(source, "a.md").count(), 1);
assert.match(await source.locator(".cm-content").innerText(), /Changed during transfer/);
assert.ok(await tab(target, "a.md").getAttribute("aria-describedby"));
assert.deepEqual(await target.getByRole("tablist", { name: "Working tabs" }).getByRole("tab").evaluateAll(nodes => nodes.map(node => node.dataset.path)), ["a.md", "b.md"]);
await open(source, "a.md");
data = await start(source, "a.md");
await drop(target, data);
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 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(); }
+1 -1
View File
@@ -357,7 +357,7 @@ try {
}, 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, 'Enter'], [20, 0, 'Shift+Enter'], [20, 1, 'Shift+Enter'], [0, 0, 'Shift+Enter']]) {
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']]) {
await at(r, c);
const before = await page.locator('.live-writer .cm-scroller').evaluate(el => el.scrollTop);
await page.keyboard.press(key);
+13 -1
View File
@@ -1,12 +1,24 @@
import assert from "node:assert/strict";
import test from "node:test";
import { alignTableCells, clipboardCells, copyTableCells, deleteTableCells, formatTableCells, mapTableCells, pasteTableCells } from "../src/lib/editor/tableSelection.ts";
import { alignTableCells, clipboardCells, copyTableCells, copyTableMarkdown, deleteTableCells, formatTableCells, mapTableCells, pasteTableCells } from "../src/lib/editor/tableSelection.ts";
import { htmlToMarkdown } from "../src/lib/workspace/htmlToMarkdown.ts";
import { parseMarkdownTable } from "../src/lib/editor/markdownTable.ts";
import { renderMarkdownHtml, plainInlineMarkdown } from "../src/lib/workspace/noteHtml.ts";
import { tableCellMarkdown } from "../src/lib/editor/tableCellMarkdown.ts";
const source = "| A | B | C |\r\n| --- | :---: | ---: |\r\n| one | two | three |\r\n| four | five | six |\r\n\r\nTail";
const range = { anchor: { row: 2, column: 1 }, head: { row: 1, column: 0 } };
test("selected cells retain table structure and line breaks through HTML clipboard", () => {
const source = "| Name | Notes |\n| --- | --- |\n| **Alpha** | First<br>Second |";
const range = { anchor: { row: 0, column: 0 }, head: { row: 1, column: 1 } };
const copied = copyTableMarkdown(source, range);
const pasted = htmlToMarkdown(renderMarkdownHtml(copied, new Map()));
const table = parseMarkdownTable(pasted)!;
assert.equal(table.columns, 2);
assert.equal(table.rows.length, 3);
assert.equal(table.rows[2].cells[0].text, "**Alpha**");
assert.equal(table.rows[2].cells[1].text, "First<br>Second");
});
test("reversed rectangular selections only change selected cells and preserve CRLF", () => {
const changed = formatTableCells(source, range, "bold");
assert.equal(changed, source.replace("one", "**one**").replace("two", "**two**").replace("four", "**four**").replace("five", "**five**"));
+200
View File
@@ -0,0 +1,200 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
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 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 };
});
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();
});
}
try {
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();
for (const theme of ['dark', 'light']) {
await page.evaluate(async theme => {
const { saveAppearance } = await import('/src/lib/theme/appearance.ts');
saveAppearance({ theme: 'default', mode: theme });
}, theme);
await page.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
await page.evaluate(async sample => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
window.__CM__ = EditorView.findFromDOM(document.querySelector('.live-writer > .cm-editor .cm-content'));
window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: sample }, selection: { anchor: 0 } });
window.__CM__.focus();
}, sample);
await page.keyboard.press('Control+f');
await find.fill('Alpha');
await onePanel();
await page.screenshot({ path: `${output}/writer-${theme}.png` });
await page.keyboard.press('Escape');
await page.locator('.live-writer td').first().dblclick();
await page.locator('.writer-cell-editor').waitFor();
await page.keyboard.press('Control+f');
await onePanel();
assert.equal(await find.evaluate(node => node === document.activeElement), true, 'Table focus opens the document find');
assert.equal(await page.locator('.writer-cell-editor .rs-find-bar').count(), 0);
await find.fill('Last Alpha');
await page.keyboard.press('Enter');
assert.match(await page.evaluate(() => window.__CM__.state.sliceDoc(window.__CM__.state.selection.main.from, window.__CM__.state.selection.main.to)), /Last Alpha/);
await page.screenshot({ path: `${output}/table-focus-${theme}.png` });
await page.keyboard.press('Escape');
await mode('Editor layout', 'IDE');
await sourceEditor();
await page.evaluate(() => { window.__MONACO__.getModel().setValue('Alpha alpha alphabet\r\nAlpha second\r\nAlpha third'); window.__MONACO__.setPosition({ lineNumber: 1, column: 1 }); });
await page.keyboard.press('Control+f');
await find.fill('Alpha');
await onePanel();
await page.keyboard.press('Enter');
const first = await page.evaluate(() => window.__MONACO__.getSelection().toString());
await page.keyboard.press('Enter');
assert.notEqual(await page.evaluate(() => window.__MONACO__.getSelection().toString()), first);
await page.keyboard.press('Shift+Enter');
assert.equal(await page.evaluate(() => window.__MONACO__.getSelection().toString()), first);
await page.getByRole('checkbox', { name: 'Match case' }).check();
await page.getByRole('checkbox', { name: 'Whole word' }).check();
await replace.fill('Gamma');
await page.getByRole('button', { name: 'Replace all', exact: true }).click();
assert.equal(await page.evaluate(() => window.__MONACO__.getValue().replace(/\r\n/g, '\n')), 'Gamma alpha alphabet\nGamma second\nGamma third');
await page.getByRole('checkbox', { name: 'Regex' }).check();
await find.fill('[');
assert.equal(await find.getAttribute('aria-invalid'), 'true');
assert.equal(await page.getByRole('button', { name: 'Replace all', exact: true }).isDisabled(), true);
await find.fill('(?<=G)(amma)');
await page.getByRole('checkbox', { name: 'Whole word' }).uncheck();
await replace.fill('$1!');
await page.getByRole('button', { name: 'Replace all', exact: true }).click();
assert.match(await page.evaluate(() => window.__MONACO__.getValue()), /^Gamma! alpha/);
await page.getByRole('checkbox', { name: 'Regex' }).uncheck();
await find.fill('Gamma');
await page.getByRole('button', { name: 'Select all', exact: true }).click();
assert.equal(await page.evaluate(() => window.__MONACO__.getSelections().length), 3);
await page.screenshot({ path: `${output}/source-${theme}.png` });
await find.focus(); await page.keyboard.press('Escape');
assert.equal(await find.count(), 0);
assert.equal(await page.evaluate(() => window.__MONACO__.hasTextFocus()), true);
await page.keyboard.press('Control+h');
assert.equal(await replace.evaluate(node => node === document.activeElement), true);
await find.fill('Gamma');
await page.keyboard.press('Enter');
await page.keyboard.press('F3');
await page.screenshot({ path: `${output}/source-replace-${theme}.png` });
await page.setViewportSize({ width: 800, height: 700 });
await onePanel();
assert.equal(await page.locator('.rs-find-bar').evaluate(node => node.scrollWidth <= node.clientWidth), true);
await page.screenshot({ path: `${output}/source-narrow-${theme}.png` });
await page.setViewportSize({ width: 1440, height: 1000 });
await find.focus(); await page.keyboard.press('Escape');
await page.evaluate(sample => window.__MONACO__.getModel().setValue(sample), sample);
await mode('Document view', 'Read');
await page.locator('.reading').focus();
await page.keyboard.press('Control+f');
await find.fill('Alpha'); await page.keyboard.press('Enter');
await onePanel();
assert.equal(await replace.count(), 0, 'Reading search does not offer replacement');
assert.equal(await page.evaluate(() => window.getSelection().toString()), 'Alpha');
const anchor = await page.evaluate(() => window.getSelection().anchorNode.parentElement.outerHTML);
await page.keyboard.press('Enter');
assert.notEqual(await page.evaluate(() => window.getSelection().anchorNode.parentElement.outerHTML), anchor);
await page.screenshot({ path: `${output}/reading-${theme}.png` });
await page.keyboard.press('Escape');
assert.equal(await page.locator('.reading').evaluate(node => node === document.activeElement), true);
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(); }