Release RuneStone 0.1.4 with installable plugins and settings

This commit is contained in:
Knotty Wyvern
2026-10-04 15:05:51 -07:00
parent 0268c5c9f0
commit 6b7af0d527
82 changed files with 4150 additions and 212 deletions
+23
View File
@@ -0,0 +1,23 @@
import { build } from "vite";
import { svelte } from "@sveltejs/vite-plugin-svelte";
import { copyFile, mkdir } from "node:fs/promises";
import { fileURLToPath } from "node:url";
const root = fileURLToPath(new URL("../", import.meta.url));
for (const name of ["terminal", "table-formulas"]) {
const source = new URL(`../plugins/${name}/`, import.meta.url);
const output = new URL(`../plugin-packages/${name}/`, import.meta.url);
await build({
configFile: false,
root,
plugins: [svelte({ configFile: false, compilerOptions: { dev: false } })],
resolve: { alias: { $lib: fileURLToPath(new URL("../src/lib/", import.meta.url)) }, conditions: ["browser"] },
build: {
outDir: fileURLToPath(output), emptyOutDir: true,
lib: { entry: fileURLToPath(new URL("index.ts", source)), formats: ["es"], fileName: () => "main.js", cssFileName: "style" },
rolldownOptions: { output: { codeSplitting: false } },
},
});
await mkdir(output, { recursive: true });
await copyFile(new URL("plugin.json", source), new URL("plugin.json", output));
}
+77
View File
@@ -0,0 +1,77 @@
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";
function fixture() {
let writes = 0;
const session = new ExternalSession("org.test.demo", {
workspace: { list: async () => [], read: async () => "original", write: async () => { writes++; } },
settings: { read: async () => null, write: async () => {} },
assets: { read: async () => new Uint8Array() },
}, () => {}, () => {});
return { session, writes: () => writes };
}
test("external commands run and all host access stops before cleanup", async () => {
const { session, writes } = fixture(); let api!: PluginApi; let ran = 0;
await session.start({ activate(value) {
api = value;
api.registerCommand({ id: "run", title: "Run", run: () => { ran++; } });
api.registerView({ id: "view", title: "View", mount: () => {} });
api.onDispose(() => { assert(api.signal.aborted); assert.throws(() => api.workspace.read("x"), /disabled/); });
} });
await session.run("run"); assert.equal(ran, 1);
assert.throws(() => api.workspace.write("x", "new", undefined!), /original/);
await api.workspace.write("x", "new", "original"); assert.equal(writes(), 1);
await session.stop(); assert.equal(session.commands.size, 0); assert.equal(session.views.size, 0);
await assert.rejects(session.run("run"), /disabled/);
assert.throws(() => api.settings.read(), /disabled/);
});
test("async activation cleanup runs once even when disabled before activation finishes", async () => {
const { session } = fixture(); let resolve!: () => void; let cleaned = 0;
const gate = new Promise<void>(done => resolve = done);
const start = session.start({ async activate() { await gate; return () => { cleaned++; }; } });
await Promise.resolve();
const stopped = session.stop(); resolve();
await Promise.all([start, stopped]); await session.stop(); assert.equal(cleaned, 1);
});
test("failed cleanup does not skip other callbacks and blocks successful shutdown", async () => {
const { session } = fixture(); const calls: number[] = [];
await session.start({ activate(api) {
api.onDispose(() => { calls.push(1); });
api.onDispose(() => { calls.push(2); throw new Error("Cleanup failed"); });
api.onDispose(() => { calls.push(3); });
} });
await assert.rejects(session.stop(), /Cleanup failed/); assert.deepEqual(calls, [3, 2, 1]);
});
test("duplicate contribution IDs fail and partial activation can be cleaned", async () => {
const { session } = fixture(); let cleaned = false;
await assert.rejects(session.start({ activate(api) {
api.onDispose(() => { cleaned = true; });
api.registerCommand({ id: "run", title: "Run", run() {} });
api.registerCommand({ id: "run", title: "Again", run() {} });
} }), /duplicate/);
await session.stop(); assert(cleaned); assert.equal(session.commands.size, 0);
});
test("view disposal is idempotent and participates in plugin shutdown", async () => {
const { session } = fixture(); let cleaned = 0; let cleared = 0;
await session.start({ activate(api) { api.registerView({ id: "view", title: "View", mount: () => () => { cleaned++; } }); } });
const cleanup = await session.mount("view", { replaceChildren() { cleared++; } } as unknown as HTMLElement);
await session.stop(); await cleanup(); assert.equal(cleaned, 1); assert.equal(cleared, 1);
});
test("shutdown waits for view cleanup that already started when the view closed", async () => {
const { session } = fixture(); let done!: () => void; let cleaned = false;
const gate = new Promise<void>(resolve => done = resolve);
await session.start({ activate(api) { api.registerView({ id: "view", title: "View", mount: () => async () => { await gate; cleaned = true; } }); } });
const cleanup = await session.mount("view", { replaceChildren() {} } as unknown as HTMLElement);
const closing = cleanup(); await Promise.resolve();
let stopped = false; const stopping = session.stop().then(() => { stopped = true; });
await Promise.resolve(); await Promise.resolve(); assert.equal(stopped, false);
done(); await Promise.all([closing, stopping]); assert(cleaned);
});
test("cleanup returned by late activation still blocks shutdown when it fails", async () => {
const { session } = fixture(); let done!: () => void;
const gate = new Promise<void>(resolve => done = resolve);
const starting = session.start({ async activate() { await gate; return () => { throw new Error("Late cleanup failed"); }; } });
await Promise.resolve(); const stopping = session.stop(); done();
await assert.rejects(starting, /Late cleanup failed/); await assert.rejects(stopping, /Late cleanup failed/);
});
+172
View File
@@ -0,0 +1,172 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
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 } });
const page = await context.newPage();
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));
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 = {}) => {
calls.push({ command, args });
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.runestone-plugin', manifest, error: null }];
if (command === "plugins_cancel") { removalPrepared = false; return; }
if (command === "plugins_install") {
installed = [{ manifest, hash: 'reviewed-hash', enabled: args.enabled, 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}`);
},
};
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 = page.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 settingsDialog.getByRole('button', { name: 'Plug-ins', exact: true }).click();
}
async function uninstall() { await settingsDialog.getByRole('button', { name: 'Uninstall Workspace overview', 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();
await settingsDialog.getByRole('button', { name: 'Install from file', exact: true }).click();
let review = page.getByRole('dialog', { name: 'Review plugin installation', exact: true });
await review.getByRole('button', { name: 'Cancel', exact: true }).click();
assert.equal(await count('plugins_install'), 0);
await settingsDialog.getByRole('button', { name: 'Install from folder', 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());
await page.screenshot({ path: '.audit/plugin-manager-installed.png' });
await page.keyboard.press('Escape');
await page.getByRole('button', { name: 'Plugin commands and views', exact: true }).click();
await page.getByRole('button', { 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 uninstall();
const confirmation = page.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 page.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 page.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 page.keyboard.press('Escape');
assert.equal(await page.getByRole('button', { name: 'Plugin commands and views', exact: true }).count(), 0);
await page.setViewportSize({ width: 590, height: 820 });
await settings();
await page.screenshot({ path: '.audit/plugin-manager-narrow.png' });
assert.equal(await settingsDialog.evaluate(element => element.scrollWidth > element.clientWidth), false);
assert.deepEqual(errors, []);
console.log('External plugin smoke passed: file/folder review, code loading, command/view, one confirmation, cancellation, focus, cleanup, and uninstall.');
} finally { await browser.close(); }
+36
View File
@@ -0,0 +1,36 @@
import { readFile } from "node:fs/promises";
/** Load the actual compiled packages through the production Blob module loader. */
export async function mockFeaturePlugins(surface) {
const packages = await Promise.all(["terminal", "table-formulas"].map(async name => {
const root = new URL(`../plugin-packages/${name}/`, import.meta.url);
return {
manifest: JSON.parse(await readFile(new URL("plugin.json", root), "utf8")),
code: await readFile(new URL("main.js", root), "utf8"),
css: name === "terminal" ? await readFile(new URL("style.css", root), "base64") : "",
};
}));
await surface.addInitScript(packages => {
const key = "test.installed-plugins";
const root = "C:\\AppData\\RuneStone\\plugins";
const defaults = packages.map(item => ({ manifest: item.manifest, hash: "test-hash", enabled: true, path: root + "\\" + item.manifest.id, error: null, removal: false }));
const read = () => JSON.parse(localStorage.getItem(key) || JSON.stringify(defaults));
const write = rows => { localStorage.setItem(key, JSON.stringify(rows)); window.__TEST__?.emit("plugins-changed", {}); };
if (!localStorage.getItem(key)) localStorage.setItem(key, JSON.stringify(defaults));
window.addEventListener("storage", event => { if (event.key === key) window.__TEST__?.emit("plugins-changed", {}); });
const original = window.__TAURI_INTERNALS__.invoke;
window.__TAURI_INTERNALS__.invoke = async (command, args = {}) => {
if (!command.startsWith("plugins_")) return original(command, args);
window.__TEST__?.calls.push({ command, args });
if (command === "plugins_snapshot") return { root, plugins: read() };
if (command === "plugins_load") return packages.find(item => item.manifest.id === args.id).code;
if (command === "plugins_asset") return packages.find(item => item.manifest.id === args.id).css;
if (command === "plugins_set_enabled") { write(read().map(item => item.manifest.id === args.id ? { ...item, enabled: args.enabled } : item)); return; }
if (command === "plugins_prepare_remove") return { token: args.id, plugin: read().find(item => item.manifest.id === args.id) };
if (command === "plugins_remove") { write(read().filter(item => item.manifest.id !== args.token)); return; }
if (command === "plugins_data") return "null";
if (["plugins_release", "plugins_cancel", "plugins_reveal"].includes(command)) return;
throw new Error(`Unhandled plugin IPC: ${command}`);
};
}, packages);
}
+194
View File
@@ -0,0 +1,194 @@
import { mockFeaturePlugins } from "./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 } });
const page = await context.newPage();
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.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 === "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.context());
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 source = '# Formulas\n\n| A | B |\n| --- | --- |\n| 2 | =A2*3 |\n\nAfter.\n';
const table = page.locator('.live-writer table');
const dialog = page.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 dialog.getByRole('button', { name: 'Plug-ins', exact: true }).click();
}
async function closeSettings() {
await page.waitForFunction(() => [...document.querySelectorAll('input[role="switch"]')].every(input => !input.disabled));
await page.keyboard.press('Escape');
await dialog.waitFor({ state: 'hidden' });
}
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(() => 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 page.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 page.waitForFunction(() => [...document.querySelectorAll('input[role="switch"]')].every(input => !input.disabled));
await dialog.getByRole('button', { name: `Uninstall ${name}`, exact: true }).click();
const confirmation = page.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(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 page.screenshot({ path: ".audit/plugins-failure.png" });
console.log(await page.locator('.md-page').allTextContents());
console.log(errors);
throw error;
} finally { await browser.close(); }
+62
View File
@@ -0,0 +1,62 @@
import test from "node:test";
import assert from "node:assert/strict";
import { ContributionRegistry, pluginHost } from "../src/lib/plugins/registry.ts";
import { ExternalSession } from "../src/lib/plugins/externalSession.ts";
import { activate } from "../plugins/table-formulas/index.ts";
import { renderMarkdownHtml, renderMarkdownSections } from "../src/lib/workspace/noteHtml.ts";
import type { PluginApi } from "../src/lib/plugins/sdk.ts";
const services = {
workspace: { list: async () => [], read: async () => "", write: async () => {} },
settings: { read: async () => null, write: async () => {} },
assets: { read: async () => new Uint8Array() },
};
test("core starts without optional features and formula packages preserve source when stopped", async () => {
assert.equal(pluginHost.get("terminal"), undefined);
assert.equal(pluginHost.get("tableFormulas"), undefined);
const source = "| A | B |\n| --- | --- |\n| 2 | =A2*3 |\n";
assert.doesNotMatch(renderMarkdownHtml(source, new Map()), /md-table-formula/);
const session = new ExternalSession("runestone.table-formulas", services, () => {}, () => {});
await session.start({ activate });
const enabled = renderMarkdownHtml(source, new Map());
assert.match(enabled, />6<\/span>/);
await session.stop();
for (const html of [renderMarkdownHtml(source, new Map()), ...renderMarkdownSections(source, new Map()).map(section => section.html)]) {
assert.doesNotMatch(html, /md-table-formula/);
assert.match(html, /=A2\*3/);
assert.match(html, /<table>/);
}
const next = new ExternalSession("runestone.table-formulas", services, () => {}, () => {});
await next.start({ activate });
assert.equal(renderMarkdownHtml(source, new Map()), enabled);
await next.stop();
});
test("package contribution conflicts preserve the first owner and revoke access before cleanup", async () => {
const registry = new ContributionRegistry();
const first = new ExternalSession("first", services, () => {}, () => {}, registry);
const second = new ExternalSession("second", services, () => {}, () => {}, registry);
let api!: PluginApi;
await first.start({ activate(value) { api = value; activate(api); } });
const contribution = registry.get("tableFormulas");
await assert.rejects(second.start({ activate }), /already registered/);
await second.stop();
assert.equal(registry.get("tableFormulas"), contribution);
api.onDispose(() => {
assert.equal(registry.get("tableFormulas"), undefined);
assert.throws(() => api.contribute("tableFormulas", contribution!), /disabled/);
});
await first.stop();
});
test("partial activation and failed cleanup cannot retain feature contributions", async () => {
const registry = new ContributionRegistry();
const session = new ExternalSession("failed", services, () => {}, () => {}, registry);
await assert.rejects(session.start({ activate(api) {
activate(api);
api.onDispose(() => { throw new Error("Cleanup failed"); });
throw new Error("Activation failed");
} }), /Activation failed/);
await assert.rejects(session.stop(), /Cleanup failed/);
assert.equal(registry.get("tableFormulas"), undefined);
});
+165
View File
@@ -0,0 +1,165 @@
// Run against pnpm dev with PLAYWRIGHT_MODULE and CHROME_PATH if needed.
import { createRequire } from "node:module";
import { mkdirSync, 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 errors = [];
page.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;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const url = process.env.SMOKE_URL || "http://127.0.0.1:1420";
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
const trigger = page.getByRole("button", { name: "Settings (Ctrl+,)", exact: true });
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 {
await page.clock.install();
await page.goto(url);
await page.locator(".ws").filter({ hasText: "Notes" }).waitFor();
await trigger.click();
assert.equal(await interval.inputValue(), "5");
assert(await enabled.isChecked());
await changeSeconds(2);
await settings.getByRole("status").filter({ hasText: "Changes saved." }).waitFor();
await page.keyboard.press("Escape");
assert(await trigger.evaluate(element => element === document.activeElement), "Closing restores focus");
await page.reload();
await trigger.click();
assert.equal(await interval.inputValue(), "2", "Interval survives reload");
await changeSeconds(0);
await settings.getByRole("alert").filter({ hasText: "whole number" }).waitFor();
assert.equal(await page.evaluate(() => JSON.parse(localStorage.getItem("runestone.settings")).autosaveSeconds), 2);
await changeSeconds(2);
await settings.getByRole("textbox", { name: "Search settings" }).fill("plugins");
await settings.getByText("No plugins installed.", { exact: true }).waitFor();
assert(await settings.getByRole("button", { name: "Install from folder", exact: true }).isEnabled());
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 page.screenshot({ path: ".audit/settings-general.png" });
await page.keyboard.press("Escape");
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill("note.txt");
await page.getByRole("dialog").getByRole("button").filter({ hasText: "note.txt" }).first().click();
await page.locator(".monaco-editor textarea").waitFor();
await page.clock.pauseAt(new Date());
await trigger.click();
await changeSeconds(3);
await page.keyboard.press("Escape");
await edit("Saved at three seconds");
const before = await writes();
await page.clock.runFor(2100);
assert.equal(await writes(), before, "Old two-second timer is removed");
await page.clock.runFor(1000);
assert.equal(await writes(), before + 1, "New interval saves the dirty buffer");
await page.clock.runFor(3100);
assert.equal(await writes(), before + 1, "Clean files are not rewritten");
await trigger.click();
await enabled.uncheck();
assert(await interval.isDisabled());
await page.keyboard.press("Escape");
await edit("Manual save while auto-save is disabled");
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.locator(".monaco-editor textarea").focus();
await page.keyboard.press("Control+,");
await settings.waitFor();
await page.keyboard.press("Escape");
await page.locator(".monaco-editor textarea").focus();
await page.keyboard.press("F1");
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);
await other.getByRole("button", { name: "Settings (Ctrl+,)" }).click();
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();
await page.waitForFunction(() => JSON.parse(localStorage.getItem("runestone.settings")).autosaveEnabled);
await trigger.click();
await enabled.waitFor();
assert(await enabled.isChecked(), "Other windows receive changes");
assert.equal(await interval.inputValue(), "5");
await page.keyboard.press("Escape");
await edit("Auto-save enabled from another window");
await page.clock.runFor(5100);
assert.equal(await writes(), before + 3);
await other.close();
await trigger.click();
await page.evaluate(() => {
window.__SET_ITEM__ = Storage.prototype.setItem;
Storage.prototype.setItem = () => { throw new Error("Storage unavailable"); };
});
await changeSeconds(7);
await settings.getByRole("alert").filter({ hasText: "Could not save" }).waitFor();
await page.evaluate(() => { Storage.prototype.setItem = window.__SET_ITEM__; });
await page.keyboard.press("Escape");
await trigger.click();
assert.equal(await interval.inputValue(), "5", "Failed writes preserve applied settings");
await page.keyboard.press("Escape");
await page.getByRole("button", { name: "Help and about (F1)" }).click();
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.keyboard.press("Escape");
await page.keyboard.press("Control+b");
await page.keyboard.press("Control+,");
await settings.waitFor();
await page.keyboard.press("Escape");
await page.keyboard.press("F1");
await help.waitFor();
await page.keyboard.press("Escape");
await page.setViewportSize({ width: 420, height: 650 });
await page.keyboard.press("Control+,");
await settings.waitFor();
assert(await settings.evaluate(el => el.scrollWidth === el.clientWidth), "Narrow layout fits");
await page.screenshot({ path: ".audit/settings-narrow.png" });
for (let i = 0; i < 12; i++) {
await page.keyboard.press("Tab");
assert(await settings.evaluate(el => el.contains(document.activeElement)), "Focus stays in the modal");
}
assert.deepEqual(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(); }
+32
View File
@@ -0,0 +1,32 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { DEFAULT_SETTINGS, SETTINGS_KEY, parseSettings, saveSettings } from "../src/lib/workspace/settings.ts";
test("missing or damaged preferences keep safe defaults", () => {
for (const raw of [null, "{broken", "null", "[]", "42", '"text"']) {
assert.deepEqual(parseSettings(raw), DEFAULT_SETTINGS);
}
for (const autosaveSeconds of [0, -1, 301, 1.5, "10", null]) {
assert.deepEqual(parseSettings(JSON.stringify({ autosaveEnabled: false, autosaveSeconds })), { autosaveEnabled: false, autosaveSeconds: 5 });
}
assert.deepEqual(parseSettings('{"autosaveEnabled":"false","autosaveSeconds":10}'), { autosaveEnabled: true, autosaveSeconds: 10 });
});
test("preferences persist and load at both interval limits", () => {
const store = new Map<string, string>();
for (const autosaveSeconds of [1, 23, 300]) {
const settings = { autosaveEnabled: false, autosaveSeconds };
saveSettings({ setItem: (key, value) => { store.set(key, value); } }, settings);
assert.deepEqual(parseSettings(store.get(SETTINGS_KEY)!), settings);
}
});
test("invalid changes never reach storage and storage failures reach the caller", () => {
let writes = 0;
const storage = { setItem: () => { writes++; } };
for (const autosaveSeconds of [NaN, Infinity, 0, 301, 2.5]) {
assert.throws(() => saveSettings(storage, { autosaveEnabled: true, autosaveSeconds }));
}
assert.equal(writes, 0);
assert.throws(() => saveSettings({ setItem: () => { throw new Error("Storage unavailable"); } }, { ...DEFAULT_SETTINGS }), /Storage unavailable/);
});
+9 -7
View File
@@ -1,3 +1,4 @@
import { mockFeaturePlugins } from "./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";
@@ -69,14 +70,15 @@ await page.addInitScript(() => {
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('.live-writer').waitFor();
await page.keyboard.press('Control+e');
await page.locator(".monaco-editor textarea").waitFor();
}
@@ -98,7 +100,7 @@ try {
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['formulas.md'] });
}, source);
await quickOpen('formulas.md');
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
await page.keyboard.press('Control+e');
await table.waitFor();
assert.equal(await result(1, 3).innerText(), '9.5');
assert.equal(await result(3, 3).innerText(), '17.5');
@@ -172,12 +174,12 @@ try {
await checkFooter();
await page.setViewportSize({ width: 1440, height: 1000 });
await page.screenshot({ path: '.audit/table-formulas.png' });
await page.getByRole('button', { name: 'Switch to IDE layout (Ctrl E)', exact: true }).click();
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
await page.keyboard.press('Control+e');
await page.keyboard.press('Control+e');
assert.equal(await result(3, 1).innerText(), '12');
assert.equal(await result(3, 3).innerText(), '58');
for (const mode of ['Read', 'Split']) {
await page.getByRole('button', { name: mode, exact: true }).click();
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');
+11 -2
View File
@@ -1,6 +1,15 @@
import assert from "node:assert/strict";
import test from "node:test";
import { cellAddress, evaluateTableFormulas } from "../src/lib/editor/tableFormulas.ts";
import test, { before, after } from "node:test";
import { ExternalSession } from "../src/lib/plugins/externalSession.ts";
import { activate } from "../plugins/table-formulas/index.ts";
const session = new ExternalSession("runestone.table-formulas", {
workspace: { list: async () => [], read: async () => "", write: async () => {} },
settings: { read: async () => null, write: async () => {} },
assets: { read: async () => new Uint8Array() },
}, () => {}, () => {});
before(() => session.start({ activate }));
after(() => session.stop());
import { cellAddress, evaluateTableFormulas } from "../plugins/table-formulas/formulas.ts";
import { tableCellMarkdown } from "../src/lib/editor/tableCellMarkdown.ts";
import { renderMarkdownHtml, renderMarkdownSections } from "../src/lib/workspace/noteHtml.ts";
+5 -2
View File
@@ -1,3 +1,4 @@
import { mockFeaturePlugins } from "./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";
@@ -71,6 +72,8 @@ await page.addInitScript(() => {
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
await mockFeaturePlugins(page);
const count = command => page.evaluate(command => window.__TEST__.calls.filter(c => c.command === command).length, command);
const waitCount = (command, n) => page.waitForFunction(({ command, n }) => window.__TEST__.calls.filter(c => c.command === command).length === n, { command, n });
@@ -78,7 +81,7 @@ const click = name => page.getByRole("button", { name, exact: true }).click();
const menu = name => page.getByRole("menuitem", { name, exact: true }).click();
const writes = () => page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_write").map(c => c.args.data).join(""));
try {
await page.goto("http://127.0.0.1:1420");
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
await page.getByText("smoke-workspace", { exact: true }).waitFor();
await click("Terminal");
await waitCount("pty_open", 1);
@@ -181,7 +184,7 @@ try {
await waitCount("pty_open", 8);
await page.keyboard.press("Control+Shift+Alt+Backquote");
await waitCount("pty_new_window", 2);
await page.goto("http://127.0.0.1:1420/?terminalWindow=C%3A%5Csmoke-workspace");
await page.goto((process.env.SMOKE_URL || "http://127.0.0.1:1420") + "/?terminalWindow=C%3A%5Csmoke-workspace");
await waitCount("pty_open", 1);
assert.equal(await count("workspace_open"), 0);
assert.equal(await page.getByRole("button", { name: "Close terminal window", exact: true }).count(), 1);
+1 -1
View File
@@ -1,6 +1,6 @@
import assert from "node:assert/strict";
import test from "node:test";
import { directoryCommand, fileCommand, parseTasks, quoteShell, remember, terminalShortcut } from "../src/lib/terminal/model.ts";
import { directoryCommand, fileCommand, parseTasks, quoteShell, remember, terminalShortcut } from "../plugins/terminal/model.ts";
test("paths are shell-quoted without evaluating metacharacters", () => {
assert.equal(directoryCommand("C:\\a'b\\$notes", "powershell"), "Set-Location -LiteralPath 'C:\\a''b\\$notes'");
+3
View File
@@ -1,3 +1,4 @@
import { mockFeaturePlugins } from "./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";
@@ -71,6 +72,8 @@ await page.addInitScript(() => {
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");