Release RuneStone 0.1.7 with plugin documents and shared menus

This commit is contained in:
Knotty Wyvern
2026-10-06 09:29:09 -07:00
parent 6b7af0d527
commit 5d0a4a24f9
75 changed files with 2286 additions and 1665 deletions
+15 -19
View File
@@ -1,23 +1,19 @@
import { build } from "vite";
import { svelte } from "@sveltejs/vite-plugin-svelte";
import { copyFile, mkdir } from "node:fs/promises";
import { mkdir, cp, access } from "node:fs/promises";
import { execFileSync } from "node:child_process";
import { resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { packagePlugin } from "./packagePlugin.mjs";
const root = fileURLToPath(new URL("../", import.meta.url));
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));
const formulasRoot = resolve(process.env.RUNESTONE_TABLE_FORMULAS_ROOT || resolve(root, "../RuneStone_TableFormulas"));
const formulasBuild = resolve(formulasRoot, "scripts/build.mjs");
try {
await access(formulasBuild);
} catch {
throw new Error("Clone RuneStone_TableFormulas beside RuneStone, or set RUNESTONE_TABLE_FORMULAS_ROOT. Install its dependencies before building plugins.");
}
execFileSync(process.execPath, [formulasBuild], { cwd: formulasRoot, stdio: "inherit" });
const formulasOutput = resolve(root, "plugin-packages/table-formulas");
await mkdir(formulasOutput, { recursive: true });
await cp(resolve(formulasRoot, "dist/plugin"), formulasOutput, { recursive: true });
console.log(await packagePlugin(formulasOutput, resolve(root, "plugin-packages")));
+4 -4
View File
@@ -75,9 +75,8 @@ 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.getByRole("tab", { selected: true }).click({ button: "right" });
await page.getByRole("menuitem", { name: "Source mode", exact: true }).click();
await page.locator(".monaco-editor textarea").waitFor();
}
async function contents() {
@@ -112,7 +111,8 @@ try {
await menu.getByRole("menuitem", { name: "Bold", exact: true }).click();
await waitForText("**First** paragraph.\n\nSecond paragraph.\n");
await page.keyboard.press("Control+z"); await waitForText(source);
await page.getByRole("button", { name: "Switch to writing layout (Ctrl E)", exact: true }).click();
await page.getByRole("tab", { selected: true }).click({ button: "right" });
await page.getByRole("menuitem", { name: "Writing mode", exact: true }).click();
const writer = page.getByRole("textbox", { name: "Writing editor", exact: true });
await writer.click(); await page.keyboard.press("Control+Home");
await page.keyboard.press("Control+Shift+ArrowRight");
+140
View File
@@ -0,0 +1,140 @@
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(15000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await mkdir(".audit", { recursive: true });
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\tab-menu-workspace";
const files = new Map(["a.md", "b.md", "c.md", "d.md"].map(name => [name, `# ${name}\n\nOriginal text.\n\n| Name | Value |\n| --- | --- |\n| Alpha | One |\n`]));
window.tabMenuTest = { prompts: [], answer: "Cancel", revealed: null, clipboard: null };
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { window.tabMenuTest.clipboard = text; } } });
let sequence = 0;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: () => ++sequence, unregisterCallback: () => {},
invoke: async (command, args = {}) => {
if (command === "plugin:event|listen") return ++sequence;
if (command === "plugin:event|unlisten") return;
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "tab-menu-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_list") return args.rel ? [] : [{ name: "notes", rel_path: "notes", kind: "folder" }, ...[...files.keys()].map(name => ({ name, rel_path: name, kind: "file" }))];
if (command === "workspace_search") return [];
if (command === "workspace_write") throw new Error("Keep unsaved edits for the close test");
if (command === "workspace_rename") { files.set(args.to, files.get(args.from)); files.delete(args.from); return; }
if (command === "workspace_abs_path") return `${root}\\${args.rel}`;
if (command === "workspace_reveal") { window.tabMenuTest.revealed = args.rel; return; }
if (command === "plugin:dialog|message") { window.tabMenuTest.prompts.push(args.message); return window.tabMenuTest.answer; }
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const menu = name => page.getByRole("menu", { name, exact: true });
const item = name => page.getByRole("menuitem", { name, exact: true });
async function metrics(panel) {
return panel.evaluate(node => {
const row = node.querySelector(":scope > button");
const icon = row.querySelector(".action-icon");
const label = row.querySelector(".action-label");
const css = getComputedStyle(node), button = getComputedStyle(row);
return {
panel: [css.padding, css.borderRadius, css.backgroundColor, css.color, css.boxShadow, css.font],
row: [button.padding, button.minHeight, button.borderRadius, button.gap, button.font],
iconWidth: icon.getBoundingClientRect().width,
inset: Math.round(row.getBoundingClientRect().left - node.getBoundingClientRect().left),
labelOffset: Math.round(label.getBoundingClientRect().left - row.getBoundingClientRect().left),
};
});
}
async function dismiss() { await page.keyboard.press("Escape"); await page.locator(".rs-menu").waitFor({ state: "detached" }); }
try {
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
const row = page.locator('[data-tree-rel="a.md"]');
await row.waitFor();
await row.click();
const tab = page.getByRole("tab", { name: "a.md", exact: true });
await tab.waitFor();
await page.locator(".cm-content").waitFor();
for (const theme of ["dark", "light"]) {
await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
await row.focus();
await row.click({ button: "right" });
const file = menu("File actions");
await file.waitFor();
const reference = await metrics(file);
assert.ok(reference.inset >= 5, "Rows need an inset from the panel border");
assert.equal(await item("Pin").locator("svg.action-icon").count(), 1);
const offsets = await file.locator(":scope > button").evaluateAll(nodes => nodes.map(node => Math.round(node.querySelector(".action-label").getBoundingClientRect().left - node.getBoundingClientRect().left)));
assert.equal(new Set(offsets).size, 1, "All file labels align");
await page.screenshot({ path: ".audit/menu-file-" + theme + ".png" });
await dismiss();
assert.equal(await row.evaluate(node => node === document.activeElement), true);
await page.getByRole("navigation", { name: "Workspace files" }).click({ button: "right", position: { x: 100, y: 350 } });
await file.waitFor();
assert.deepEqual(await metrics(file), reference, "Pane and file menus share styles");
await dismiss();
await page.locator('[data-tree-rel="notes"]').click({ button: "right" });
assert.deepEqual(await metrics(file), reference, "Folder and file menus share styles");
await dismiss();
await tab.click({ button: "right" });
const tabs = menu("Tab actions");
assert.deepEqual(await metrics(tabs), reference, "Tab and file menus share styles");
await item("Close tabs after").hover();
assert.equal(await item("Close tabs after").evaluate(node => getComputedStyle(node).backgroundColor), "rgba(0, 0, 0, 0)");
await item("Move tab").focus();
await page.keyboard.press("ArrowRight");
assert.deepEqual(await metrics(menu("Move tab")), reference, "Submenus share styles");
await page.screenshot({ path: ".audit/menu-tab-" + theme + ".png" });
await page.keyboard.press("ArrowLeft");
assert.equal(await item("Move tab").evaluate(node => node === document.activeElement), true);
await dismiss();
await page.getByText("Original text.", { exact: true }).click({ button: "right" });
const editor = menu("Markdown text actions");
assert.deepEqual(await metrics(editor), reference, "Editor and file menus share styles");
await item("Paragraph").focus();
await page.keyboard.press("ArrowRight");
assert.deepEqual(await metrics(menu("Paragraph")), reference);
await page.screenshot({ path: ".audit/menu-editor-" + theme + ".png" });
await dismiss();
await page.locator(".live-writer td").first().click({ button: "right" });
assert.deepEqual(await metrics(menu("Table actions")), reference, "Table and file menus share styles");
await dismiss();
}
await page.setViewportSize({ width: 420, height: 320 });
await page.evaluate(async () => {
const { actionMenu } = await import("/src/lib/ui/actionMenu.ts");
const root = actionMenu(418, 318, [
{ label: "Without icon", run: () => {} },
{ label: "With icon", icon: "copy", run: () => {} },
{ label: "Unavailable", icon: "trash", disabled: true },
{ label: "More", icon: "plus", children: Array.from({ length: 30 }, (_, i) => ({ label: "Action " + i, icon: "copy" })) },
], () => root.remove(), "Edge test");
});
const edge = menu("Edge test");
const offsets = await edge.locator(":scope > button").evaluateAll(nodes => nodes.map(node => node.querySelector(".action-label").getBoundingClientRect().left));
assert.equal(new Set(offsets).size, 1, "Iconless labels keep the icon column");
await page.keyboard.press("ArrowDown");
await page.keyboard.press("ArrowDown");
assert.equal(await item("More").evaluate(node => node === document.activeElement), true, "Keyboard skips disabled rows");
await page.keyboard.press("ArrowRight");
const sub = menu("More");
for (const panel of [edge, sub]) {
const bounds = await panel.boundingBox();
assert.ok(bounds.x >= 8 && bounds.y >= 8 && bounds.x + bounds.width <= 412 && bounds.y + bounds.height <= 312);
}
await page.keyboard.press("End");
assert.equal(await item("Action 29").evaluate(node => node === document.activeElement), true);
await page.screenshot({ path: ".audit/menu-edge.png" });
await dismiss();
assert.deepEqual(errors, []);
console.log("PASS: menu styles, dark/light themes, icons, disabled rows, focus return, submenus, scrolling, and viewport edges");
} finally { await browser.close(); }
+120
View File
@@ -0,0 +1,120 @@
import { lstat, readdir, readFile, mkdir, writeFile, realpath, rename, unlink } from "node:fs/promises";
import { randomUUID } from "node:crypto";
import { resolve, relative, isAbsolute, join } from "node:path";
import { pathToFileURL } from "node:url";
import { crc32, deflateRawSync } from "node:zlib";
const MiB = 1024 * 1024;
const device = /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i;
function validPath(name) {
return name.length <= 180 && name.split("/").every(part =>
part.length > 0 && part.length <= 120 && /^[a-zA-Z0-9._-]+$/.test(part)
&& !part.endsWith(".") && !device.test(part.split(".")[0]));
}
function requireValue(condition, message) {
if (!condition) throw new Error(message);
}
// ZIP32 with DEFLATE, fixed timestamps, and sorted paths gives repeatable release files.
function zip(files) {
const local = [], central = [];
let offset = 0, centralSize = 0;
for (const [path, bytes] of files) {
const name = Buffer.from(path);
const compressed = deflateRawSync(bytes, { level: 9 });
const header = Buffer.alloc(30);
header.writeUInt32LE(0x04034b50, 0);
header.writeUInt16LE(20, 4);
header.writeUInt16LE(8, 8);
header.writeUInt16LE(33, 12); // January 1, 1980.
header.writeUInt32LE(crc32(bytes), 14);
header.writeUInt32LE(compressed.length, 18);
header.writeUInt32LE(bytes.length, 22);
header.writeUInt16LE(name.length, 26);
local.push(header, name, compressed);
const record = Buffer.alloc(46);
record.writeUInt32LE(0x02014b50, 0);
record.writeUInt16LE(20, 4);
header.copy(record, 6, 4, 30);
record.writeUInt32LE(offset, 42);
central.push(record, name);
offset += header.length + name.length + compressed.length;
centralSize += record.length + name.length;
}
const end = Buffer.alloc(22);
end.writeUInt32LE(0x06054b50, 0);
end.writeUInt16LE(files.length, 8);
end.writeUInt16LE(files.length, 10);
end.writeUInt32LE(centralSize, 12);
end.writeUInt32LE(offset, 16);
return Buffer.concat([...local, ...central, end]);
}
export async function packagePlugin(source, destination = "plugin-packages") {
const input = resolve(source);
const output = resolve(destination);
const inputMeta = await lstat(input);
requireValue(inputMeta.isDirectory() && !inputMeta.isSymbolicLink(), "Select a compiled plugin folder.");
const files = [], names = new Set();
let total = 0, count = 0;
async function walk(directory, prefix = "") {
for (const entry of (await readdir(directory)).sort()) {
const name = prefix + entry;
requireValue(validPath(name), `Invalid package path: ${name}`);
requireValue(!names.has(name.toLowerCase()), `Duplicate package path: ${name}`);
names.add(name.toLowerCase());
requireValue(++count <= 5000, "The package exceeds 5,000 entries.");
const path = join(directory, entry), meta = await lstat(path);
requireValue(!meta.isSymbolicLink(), `Remove the link from the package: ${name}`);
if (meta.isDirectory()) await walk(path, name + "/");
else {
requireValue(meta.isFile() && meta.size <= 25 * MiB, `Invalid or oversized package file: ${name}`);
const bytes = await readFile(path);
requireValue(bytes.length <= 25 * MiB, `The file exceeds 25 MiB: ${name}`);
total += bytes.length;
requireValue(total <= 100 * MiB, "The package exceeds 100 MiB of expanded data.");
files.push([name, bytes]);
}
}
}
await walk(input);
const manifestBytes = files.find(([name]) => name === "plugin.json")?.[1];
requireValue(manifestBytes && manifestBytes.length <= 64 * 1024, "The package needs plugin.json at its root, within 64 KiB.");
const manifest = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(manifestBytes));
requireValue(typeof manifest.id === "string" && validPath(manifest.id) && /^[a-z][a-z0-9.-]*$/.test(manifest.id), "The plugin ID is invalid.");
requireValue(manifest.schemaVersion === 1 && manifest.apiVersion === 1 && manifest.access === "full-app", "Unsupported schema, API version, or access mode.");
for (const key of ["name", "author", "description", "version"]) {
requireValue(typeof manifest[key] === "string" && manifest[key].trim() && Buffer.byteLength(manifest[key]) <= 1000, `The manifest needs a valid ${key}.`);
}
requireValue(/^\d+\.\d+\.\d+$/.test(manifest.version), "Use a plugin version such as 1.0.0.");
requireValue(typeof manifest.entry === "string" && validPath(manifest.entry) && /\.m?js$/.test(manifest.entry), "The entry must be a compiled JavaScript module.");
const entry = files.find(([name]) => name === manifest.entry)?.[1];
requireValue(entry, "The entry module is missing.");
new TextDecoder("utf-8", { fatal: true }).decode(entry);
const filename = `${manifest.id}-${manifest.version}.zip`;
requireValue(filename.length <= 240, "The release filename is too long.");
await mkdir(output, { recursive: true });
const target = join(await realpath(output), filename);
const within = relative(await realpath(input), target);
requireValue(isAbsolute(within) || within === ".." || within.startsWith("../") || within.startsWith("..\\"), "Choose an output folder outside the plugin folder.");
const archive = zip(files.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
requireValue(archive.length <= 100 * MiB, "The archive exceeds 100 MiB.");
const temporary = `${target}.${randomUUID()}.tmp`;
try {
await writeFile(temporary, archive, { flag: "wx" });
await rename(temporary, target);
} finally {
await unlink(temporary).catch(error => { if (error.code !== "ENOENT") throw error; });
}
return target;
}
if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
try {
requireValue(process.argv[2] && process.argv.length <= 4, "Usage: node scripts/packagePlugin.mjs <compiled-folder> [output-folder]");
console.log(await packagePlugin(process.argv[2], process.argv[3]));
} catch (error) {
console.error(error.message);
process.exitCode = 1;
}
}
+96
View File
@@ -0,0 +1,96 @@
import test from "node:test";
import assert from "node:assert/strict";
import { ExternalSession } from "../src/lib/plugins/externalSession.ts";
import type { PluginApi, PluginDocumentType } 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() },
};
const type: PluginDocumentType = {
id: "board", title: "Board", icon: "kanban", extensions: ["md"],
identify: (_path, source) => source === "board" ? { id: "stable" } : null,
create: { label: "New board", defaultName: "Untitled board", extension: "md", contents: () => "board" },
mount: () => {},
};
test("document renames pass the stable identity and stop after shutdown", async () => {
let api!: PluginApi;
const calls: unknown[] = [];
const session = new ExternalSession("fixture", services, () => {}, () => {}, undefined, undefined,
async (document, name) => { calls.push({ document, name }); return "Renamed.md"; });
await session.start({ activate(value) { api = value; } });
assert.equal(await api.renameDocument!({ id: "stable", path: "Board.md" }, "Renamed"), "Renamed.md");
assert.deepEqual(calls, [{ document: { id: "stable", path: "Board.md" }, name: "Renamed" }]);
await session.stop();
assert.throws(() => api.renameDocument!({ id: "stable", path: "Board.md" }, "Other"), /disabled/);
assert.equal(calls.length, 1);
});
test("binary document registration preserves bytes and revokes reads on shutdown", async () => {
let api!: PluginApi;
const bytes = new Uint8Array([0x25, 0x50, 0x44, 0x46, 0xff, 0x00]);
const paths: string[] = [];
const session = new ExternalSession("fixture", {
...services, workspace: { ...services.workspace, readBytes: async path => { paths.push(path); return bytes; } },
}, () => {}, () => {});
await session.start({ activate(value) {
api = value;
api.registerDocumentType({ ...type, id: "pdf", extensions: ["pdf"], content: "binary", create: undefined });
} });
assert.equal(session.documentTypes.get("pdf")?.content, "binary");
assert.deepEqual(await api.workspace.readBytes!("report.pdf"), bytes);
assert.deepEqual(paths, ["report.pdf"]);
assert.throws(() => api.registerDocumentType({ ...type, content: "invalid" as "binary" }), /content type/);
await session.stop();
assert.throws(() => api.workspace.readBytes!("report.pdf"), /disabled/);
});
test("document types have independent registrations and reject invalid creation actions", async () => {
let api!: PluginApi;
const session = new ExternalSession("fixture", services, () => {}, () => {});
await session.start({ activate(value) { api = value; api.registerDocumentType(type); } });
assert.equal(session.documentTypes.get("board")?.identify("Board.md", "board")?.id, "stable");
assert.equal(session.documentTypes.get("board")?.identify("Note.md", "plain"), null);
assert.throws(() => api.registerDocumentType(type), /duplicate/);
assert.throws(() => api.registerDocumentType({ ...type, id: "other", create: { ...type.create!, extension: "exe" } }), /Invalid document creation/);
await session.stop();
assert.equal(session.documentTypes.size, 0);
assert.throws(() => api.registerDocumentType(type), /disabled/);
});
test("two document mounts retain independent context and clean up once", async () => {
const mounted: string[] = [], cleaned: string[] = [];
const session = new ExternalSession("fixture", services, () => {}, () => {});
await session.start({ activate(api) {
api.registerDocumentType({ ...type, mount(_node, context) { mounted.push(context.path); return () => { cleaned.push(context.id); }; } });
} });
const element = () => ({ replaceChildren() {} }) as unknown as HTMLElement;
const first = await session.mount("board", element(), { id: "first", path: "One.md" });
await session.mount("board", element(), { id: "second", path: "Two.md" });
assert.deepEqual(mounted, ["One.md", "Two.md"]);
await first(); await first();
assert.deepEqual(cleaned, ["first"]);
await session.stop();
assert.deepEqual(cleaned, ["first", "second"]);
});
test("document opening and workspace subscriptions stop with their plugin", async () => {
let api!: PluginApi;
let listener: (() => void) | undefined;
let notifications = 0, removed = 0;
const opened: string[] = [];
const session = new ExternalSession("fixture", {
...services,
workspace: { ...services.workspace, subscribe(callback) { listener = callback; return () => { removed++; }; } },
}, () => {}, () => {}, undefined, async path => { opened.push(path); });
await session.start({ activate(value) { api = value; api.workspace.subscribe!(() => { notifications++; }); } });
await api.openDocument("Board.md"); listener!();
assert.deepEqual(opened, ["Board.md"]);
assert.equal(notifications, 1);
await session.stop(); listener!();
assert.equal(notifications, 1);
assert.equal(removed, 1);
assert.throws(() => api.openDocument("Board.md"), /disabled/);
});
+40 -7
View File
@@ -5,7 +5,7 @@ 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 context = await browser.newContext({ viewport: { width: 1440, height: 1000 }, locale: 'en-US', timezoneId: 'America/Vancouver' });
const page = await context.newPage();
page.setDefaultTimeout(10000);
const errors = [];
@@ -42,10 +42,14 @@ await page.context().addInitScript(({ manifest, pluginCode }) => {
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_choose") return [{ token: 'candidate', source: 'C:/Downloads/overview.zip', manifest, error: null }];
if (command === "plugins_from_git") {
if (args.tag === 'missing') throw new Error('Release not found. Publish a release with one plugin ZIP.');
return [{ token: 'git-candidate', source: args.url + ' @ ' + (args.tag || 'v1.0.0'), manifest, error: null }];
}
if (command === "plugins_cancel") { removalPrepared = false; return; }
if (command === "plugins_install") {
installed = [{ manifest, hash: 'reviewed-hash', enabled: args.enabled, path, error: null, removal: false }];
installed = [{ manifest, hash: 'reviewed-hash', 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") {
@@ -119,19 +123,39 @@ 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(); }
async function uninstall() { await settingsDialog.locator('.card').filter({ hasText: 'Workspace overview' }).getByRole('button', { name: 'Uninstall', exact: true }).click(); }
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await page.getByText('smoke-workspace', { exact: true }).waitFor();
await settings();
await settingsDialog.getByRole('button', { name: 'Install from file', exact: true }).click();
assert.equal(await settingsDialog.getByRole('button', { name: 'Install from folder', exact: true }).count(), 0);
assert.equal(await settingsDialog.getByRole('button', { name: 'Install from file', exact: true }).count(), 0);
await settingsDialog.getByRole('button', { name: 'Install plugin ZIP', exact: true }).click();
let review = page.getByRole('dialog', { name: 'Review plugin installation', exact: true });
await review.getByText('Source: C:/Downloads/overview.zip', { exact: true }).waitFor();
await review.getByRole('button', { name: 'Cancel', exact: true }).click();
assert.equal(await count('plugins_install'), 0);
await settingsDialog.getByRole('button', { name: 'Install from folder', exact: true }).click();
const gitButton = settingsDialog.getByRole('button', { name: 'Install from Git link', exact: true });
await gitButton.click();
const gitDialog = page.getByRole('dialog', { name: 'Install from Git link', exact: true });
await gitDialog.getByLabel('Repository link', { exact: true }).fill('https://git.example/owner/plugin.git');
await gitDialog.getByLabel('Release tag (optional)', { exact: true }).fill('missing');
await gitDialog.getByLabel('Access token (optional)', { exact: true }).fill('test-token');
await gitDialog.getByRole('button', { name: 'Review release', exact: true }).click();
await gitDialog.getByRole('alert').getByText(/Release not found/).waitFor();
assert.equal(await gitDialog.getByLabel('Access token (optional)', { exact: true }).inputValue(), '');
await gitDialog.getByLabel('Release tag (optional)', { exact: true }).fill('v1.0.0');
await gitDialog.getByRole('button', { name: 'Review release', exact: true }).click();
await review.getByText('Source: https://git.example/owner/plugin.git @ v1.0.0', { exact: true }).waitFor();
await review.getByRole('button', { name: 'Cancel', exact: true }).click();
assert.equal(await count('plugins_install'), 0);
assert(await gitButton.evaluate(element => element === document.activeElement));
await settingsDialog.getByRole('button', { name: 'Install plugin ZIP', exact: true }).click();
await review.getByRole('button', { name: 'Install and enable', exact: true }).click();
await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).waitFor();
assert(await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).isChecked());
assert.equal(await settingsDialog.locator('time').getAttribute('datetime'), '2026-10-05T18:24:36.000Z');
assert.match(await settingsDialog.locator('time').innerText(), /Oct 5, 2026.*11:24:36 AM PDT/);
await 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();
@@ -167,6 +191,15 @@ try {
await settings();
await page.screenshot({ path: '.audit/plugin-manager-narrow.png' });
assert.equal(await settingsDialog.evaluate(element => element.scrollWidth > element.clientWidth), false);
await gitButton.click();
await gitDialog.getByLabel('Repository link', { exact: true }).fill('https://git.example/owner/plugin.git');
await page.screenshot({ path: '.audit/plugin-git-narrow.png' });
assert.equal(await gitDialog.evaluate(element => element.scrollWidth > element.clientWidth), false);
await gitDialog.getByRole('button', { name: 'Review release', exact: true }).click();
await review.getByRole('button', { name: 'Install', exact: true }).click();
await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).waitFor();
assert.equal(await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).isChecked(), false);
assert.equal(await count('plugins_from_git'), 3);
assert.deepEqual(errors, []);
console.log('External plugin smoke passed: file/folder review, code loading, command/view, one confirmation, cancellation, focus, cleanup, and uninstall.');
console.log('External plugin smoke passed: ZIP and Git-link review, download errors, token clearing, disabled installation, code loading, cancellation, focus, cleanup, and uninstall.');
} finally { await browser.close(); }
+5 -1
View File
@@ -1,9 +1,13 @@
import { readFile } from "node:fs/promises";
import { resolve } from "node:path";
import { pathToFileURL } from "node:url";
/** 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);
const root = name === "terminal"
? (process.env.RUNESTONE_TERMINAL_DIST ? pathToFileURL(resolve(process.env.RUNESTONE_TERMINAL_DIST) + "/") : new URL("../../RuneStone_Terminal/dist/", import.meta.url))
: 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"),
+48
View File
@@ -0,0 +1,48 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtemp, mkdir, readFile, writeFile, rm, realpath } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
// @ts-ignore The build tool is a JavaScript module.
import { packagePlugin } from "./packagePlugin.mjs";
test("plugin packaging rejects invalid release inputs before writing an archive", async () => {
const root = await mkdtemp(join(tmpdir(), "runestone-packaging-"));
const source = join(root, "plugin"), output = join(root, "releases");
await mkdir(source);
const manifest = {
schemaVersion: 1, apiVersion: 1, id: "org.test.demo", name: "Demo", author: "Test",
description: "Test plugin", version: "1.0.0", entry: "main.js", access: "full-app",
};
const save = async (changes = {}) => writeFile(join(source, "plugin.json"), JSON.stringify({ ...manifest, ...changes }));
try {
await assert.rejects(packagePlugin(source, output), /plugin.json at its root/);
await save();
await assert.rejects(packagePlugin(source, output), /entry module is missing/);
await writeFile(join(source, "main.js"), "export function activate() {}");
for (const [changes, message] of [
[{ id: "../escape" }, /ID is invalid/],
[{ version: "1.0" }, /version such as/],
[{ entry: "../main.js" }, /compiled JavaScript/],
[{ apiVersion: 99 }, /Unsupported/],
[{ author: "" }, /valid author/],
] as const) {
await save(changes);
await assert.rejects(packagePlugin(source, output), message);
}
await save();
await assert.rejects(packagePlugin(source, source), /outside the plugin folder/);
await writeFile(join(source, "invalid file.txt"), "test");
await assert.rejects(packagePlugin(source, output), /Invalid package path/);
await rm(join(source, "invalid file.txt"));
const path = await packagePlugin(source, output);
assert.equal(path, join(await realpath(output), "org.test.demo-1.0.0.zip"));
const first = await readFile(path);
await packagePlugin(source, output);
assert.deepEqual(await readFile(path), first);
} finally {
// mkdtemp returns this test's unique directory under the operating system temp folder.
assert.equal(root.startsWith(join(tmpdir(), "runestone-packaging-")), true);
await rm(root, { recursive: true, force: true });
}
});
+1 -1
View File
@@ -170,7 +170,7 @@ try {
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();
await dialog.locator('.card').filter({ has: page.getByRole('switch', { name, exact: true }) }).getByRole('button', { name: 'Uninstall', 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' });
+24 -1
View File
@@ -2,7 +2,8 @@ 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";
// @ts-ignore The compiled package is generated by pnpm build:plugins.
import { activate } from "../plugin-packages/table-formulas/main.js";
import { renderMarkdownHtml, renderMarkdownSections } from "../src/lib/workspace/noteHtml.ts";
import type { PluginApi } from "../src/lib/plugins/sdk.ts";
@@ -11,6 +12,28 @@ const services = {
settings: { read: async () => null, write: async () => {} },
assets: { read: async () => new Uint8Array() },
};
test("optional workspace creation and reads stop when the plugin is disabled", async () => {
const files = new Map<string, string>();
let api!: PluginApi;
const session = new ExternalSession("workspace-test", {
...services,
workspace: {
...services.workspace,
readOptional: async path => files.get(path) ?? null,
create: async (path, contents) => { if (files.has(path)) throw new Error("exists"); files.set(path, contents); },
},
}, () => {}, () => {});
await session.start({ activate(value) { api = value; } });
assert.equal(await api.workspace.readOptional!("board.json"), null);
await api.workspace.create!("board.json", "{}");
assert.equal(await api.workspace.readOptional!("board.json"), "{}");
await assert.rejects(api.workspace.create!("board.json", "replacement"), /exists/);
await session.stop();
assert.throws(() => api.workspace.create!("other.json", "{}"), /disabled/);
assert.throws(() => api.workspace.readOptional!("board.json"), /disabled/);
assert.equal(files.size, 1);
});
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);
+11 -1
View File
@@ -1,6 +1,6 @@
import assert from "node:assert/strict";
import test from "node:test";
import { planRename, planTitleRename, planMarkdownTitleRename } from "../src/lib/workspace/renamePath.ts";
import { planRename, planTitleRename, planMarkdownTitleRename, planDocumentTitleRename } from "../src/lib/workspace/renamePath.ts";
test("rename in a folder keeps the parent", () => {
assert.deepEqual(planRename("notes/a.md", "b.md"), {
@@ -64,3 +64,13 @@ test("writing titles preserve Markdown extensions and allow dots in names", () =
assert.equal(planMarkdownTitleRename("notes/inbox.md", name).action, "error", name);
}
});
test("document names retain their format and cannot hide or move the file", () => {
assert.deepEqual(planDocumentTitleRename("Projects/Board.md", "Renamed"), { action: "rename", to: "Projects/Renamed.md" });
assert.deepEqual(planDocumentTitleRename("Projects/Board.md", "Release 1.2"), { action: "rename", to: "Projects/Release 1.2.md" });
assert.deepEqual(planDocumentTitleRename("Projects/Board.MD", "Renamed.md"), { action: "rename", to: "Projects/Renamed.MD" });
assert.deepEqual(planDocumentTitleRename("Report.pdf", "Next.pdf"), { action: "rename", to: "Next.pdf" });
assert.deepEqual(planDocumentTitleRename("Board.md", "Board"), { action: "noop" });
for (const name of ["", " ", ".md", ".hidden", "../escape", "folder/name", "folder\\name", "a:b", "a?b"])
assert.equal(planDocumentTitleRename("Board.md", name).action, "error", name);
});
+2 -2
View File
@@ -67,7 +67,7 @@ try {
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());
assert(await settings.getByRole("button", { name: "Install plugin ZIP", 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();
@@ -78,7 +78,7 @@ try {
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 page.clock.pauseAt(new Date(await page.evaluate(() => Date.now()) + 1000));
await trigger.click();
await changeSeconds(3);
await page.keyboard.press("Escape");
+3 -66
View File
@@ -1,7 +1,8 @@
import assert from "node:assert/strict";
import test, { before, after } from "node:test";
import { ExternalSession } from "../src/lib/plugins/externalSession.ts";
import { activate } from "../plugins/table-formulas/index.ts";
// @ts-ignore The compiled package is generated by pnpm build:plugins.
import { activate } from "../plugin-packages/table-formulas/main.js";
const session = new ExternalSession("runestone.table-formulas", {
workspace: { list: async () => [], read: async () => "", write: async () => {} },
settings: { read: async () => null, write: async () => {} },
@@ -9,74 +10,10 @@ const session = new ExternalSession("runestone.table-formulas", {
}, () => {}, () => {});
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";
const calculate = (formula: string) => evaluateTableFormulas([[formula]])[0][0]!.text;
test("aggregates distinguish separate cells and ranges from an arithmetic argument", () => {
const evaluate = (formula: string) => evaluateTableFormulas([["Name", "B", "C", "Result"], ["First", "9", "10", formula]])[1][3]!;
for (const [name, separate, combined] of [["SUM", "19", "19"], ["AVERAGE", "9.5", "19"], ["MIN", "9", "19"], ["MAX", "10", "19"], ["COUNT", "2", "1"]]) {
for (const separator of [",", ":"]) {
const result = evaluate(`=${name}(B2${separator}C2)`);
assert.equal(result.text, separate);
}
const result = evaluate(`=${name}(B2+C2)`);
assert.equal(result.text, combined);
}
assert.equal(evaluate("=(B2+C2)/2").text, "9.5");
assert.equal(evaluate("=ROUND(AVERAGE(B2,C2),0)").text, "10");
assert.equal(evaluate("=ABS(B2-C2)").text, "1");
assert.equal(evaluate("=AVERAGE((B2+C2))").text, "19");
});
test("arithmetic, precedence, parentheses, percentages and rounding", () => {
for (const [formula, result] of [
["=SUM(2+3)", "5"], ["=2+3*4", "14"], ["=(2+3)*4", "20"],
["=2^3^2", "512"], ["=-2^2", "-4"], ["=2^-2", "0.25"],
["=200*10%", "20"], ["=0.1+0.2", "0.3"], ["=1e2 + .5", "100.5"],
["=ROUND(-1.25,1)", "-1.3"], ["=ROUND(1.005,2)", "1.01"],
["=ROUND(125,-1)", "130"], ["=ABS(-4)", "4"], ["=sum(1,2,3)", "6"],
]) assert.equal(calculate(formula), result, formula);
});
test("same-table references, ranges, chained dependencies, and empty/text cells", () => {
const results = evaluateTableFormulas([
["Name", "Appearance", "Cha", "Combined"],
["First", "9", "10", "=AVERAGE(B2:C2)"],
["Second", "7", "9", "=SUM(B3,C3)/2"],
["Total", "", "=B4+1", "=SUM(D2:D3)"],
["Count", "=COUNT(A1:C4)", "=MAX(B2:C3)-MIN(B2:C3)", "=ROUND(D4/3,2)"],
["", "=SUM($B$2:$C$3)", "=AVERAGE(B1:B4)", "=SUM(C3:B2)"],
]);
assert.equal(results[1][3]?.text, "9.5");
assert.equal(results[2][3]?.text, "8");
assert.equal(results[3][3]?.text, "17.5");
assert.equal(results[3][2]?.text, "1");
assert.equal(results[4][1]?.text, "5");
assert.equal(results[4][2]?.text, "3");
assert.equal(results[4][3]?.text, "5.83");
assert.equal(results[5][1]?.text, "35");
assert.equal(results[5][2]?.text, "8");
assert.equal(results[5][3]?.text, "35");
assert.equal(results[0][0], null);
assert.equal(cellAddress(1, 26), "AA2");
assert.equal(evaluateTableFormulas([Array.from({ length: 27 }, (_, c) => c === 0 ? "=AA1" : "3")])[0][0]?.text, "3");
});
test("errors are visible, propagated, bounded, and never executed", () => {
for (const [formula, result] of [
["=1/0", "#DIV/0!"], ["=AVERAGE()", "#DIV/0!"], ["=A2", "#REF!"],
["=B1:B999999999", "#REF!"], ["=A0", "#REF!"], ["=1+", "#ERROR!"],
["=1 2", "#ERROR!"], ["=ROUND(1,2,3)", "#ERROR!"], ["=BOGUS(1)", "#NAME?"],
["=A1", "#CYCLE!"], ["=1e999", "#NUM!"], ["=9^9999", "#NUM!"],
["=globalThis.alert(1)", "#ERROR!"], ["=" + "(".repeat(100) + "1" + ")".repeat(100), "#LIMIT!"],
]) assert.equal(calculate(formula), result, formula);
const cycle = evaluateTableFormulas([["=B1", "=A1", "=SUM(A1:B1)", "=2+3"]]);
assert.deepEqual(cycle[0].map(cell => cell?.text), ["#CYCLE!", "#CYCLE!", "#CYCLE!", "5"]);
assert.equal(evaluateTableFormulas([["text", "=A1+1"]])[0][1]?.text, "#VALUE!");
});
test("Markdown rendering isolates tables and preserves literal, formatted, and non-table text", () => {
const source = "| X | Y | Result |\r\n| --- | --- | --- |\r\n| 9 | 10 | =AVERAGE(A2:B2) |\r\n\r\n| X | Y | Result |\r\n| --- | --- | --- |\r\n| 1 | 3 | =A2*B2 |\r\n";
const html = renderMarkdownHtml(source, new Map());
-198
View File
@@ -1,198 +0,0 @@
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";
import { readFile } from "node:fs/promises";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
const showcase = await readFile(new URL("../fixtures/reader-showcase.md", import.meta.url), "utf8");
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return []; if (command === "workspace_abs_path") return root + "\\" + args.rel.replaceAll("/", "\\");
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }, { id: "cmd", title: "Command Prompt", kind: "cmd" }, { id: "git-bash", title: "Git Bash", kind: "bash" }, { id: "node", title: "JavaScript Debug Terminal", kind: "node" }];
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);
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 });
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(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);
assert.equal(await page.getByRole("navigation", { name: "Terminal list" }).count(), 0);
const adjacent = await page.getByRole("button", { name: "New terminal", exact: true }).evaluate(button => { const buttons = [...button.closest(".actions").querySelectorAll("button")]; return buttons[buttons.indexOf(button) + 1]?.getAttribute("aria-label"); });
assert.equal(adjacent, "Terminal profiles and tasks");
await click("Split terminal (Ctrl+Shift+5)");
await waitCount("pty_open", 2);
assert.equal(await page.getByRole("navigation", { name: "Terminal list" }).count(), 1);
assert.equal(await page.locator(".pane.shown").count(), 2);
const original = await page.locator(".pane.shown").first().boundingBox();
await click("Maximize panel");
const enlarged = await page.locator(".pane.shown").first().boundingBox();
assert.ok(enlarged.height > original.height + 100);
assert.equal(await count("pty_close"), 0);
await page.screenshot({ path: ".audit/terminal-splits.png" });
await click("Restore panel");
await click("Hide terminal (sessions keep running)");
assert.equal(await count("pty_close"), 0);
await page.keyboard.press("Control+j");
assert.equal(await count("pty_open"), 2);
await click("Terminal profiles and tasks");
await page.screenshot({ path: ".audit/terminal-profiles.png" });
await menu("Command Prompt");
await waitCount("pty_open", 3);
assert.equal(await page.locator(".pane.shown").count(), 1);
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_open").at(-1).args.profile), "cmd");
await page.keyboard.press("Control+Shift+5");
await waitCount("pty_open", 4);
assert.equal(await page.locator(".pane.shown").count(), 2);
await click("Kill terminal");
await waitCount("pty_close", 1);
assert.equal(await page.locator(".pane.shown").count(), 1);
// OSC prompt integration reaches the history pickers.
await page.evaluate(() => {
const id = window.__TEST__.calls.filter(c => c.command === "pty_open")[2].args.id;
const data = `\x1b]633;RSCommand;${btoa("echo history-check")}\x07\x1b]633;RSCwd;${btoa("C:\\two words")}\x07\x1b]133;A\x07C:\\two words>\x1b]133;B\x07`;
window.__TEST__.emit("pty-data", { id, data: [...new TextEncoder().encode(data)] });
});
await click("More terminal actions");
await page.screenshot({ path: ".audit/terminal-actions.png" });
await menu("Run Recent Command… Ctrl+Alt+R");
await page.getByRole("dialog").getByRole("button", { name: "echo history-check" }).click();
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_write" && c.args.data.includes("echo history-check")));
await page.keyboard.press("Control+g");
await page.getByRole("dialog").getByRole("button", { name: "C:\\two words" }).click();
assert.ok((await writes()).includes('cd /d "C:\\two words"'));
await click("Terminal profiles and tasks");
await menu("Configure Terminal Settings");
await page.getByLabel("Font size", { exact: true }).fill("16");
await page.getByLabel("Default profile", { exact: true }).selectOption("git-bash");
await click("Save settings");
await click("New terminal");
await waitCount("pty_open", 5);
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_open").at(-1).args.profile), "git-bash");
assert.equal(await page.evaluate(() => JSON.parse(localStorage.getItem("runestone.terminal")).fontSize), 16);
await page.evaluate(() => window.__TEST__.files.set(".runestone/tasks.json", JSON.stringify({ tasks: [{ label: "Smoke task", command: "echo task-ok", profile: "powershell" }] })));
await click("Terminal profiles and tasks");
await menu("Run Task…");
await page.getByRole("dialog").getByRole("button", { name: "Smoke task echo task-ok" }).click();
await waitCount("pty_open", 6);
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_write" && c.args.data.includes("echo task-ok")));
// Capture selected source while the terminal menu takes focus.
await page.getByRole("button", { name: /Find a file/ }).click();
await page.getByRole("textbox", { name: "Find a file" }).fill("hello.py");
await page.getByRole("dialog").getByRole("button").filter({ hasText: "hello.py" }).click();
await page.locator(".monaco-editor textarea").waitFor();
await page.evaluate(async () => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
const editor = monaco.editor.getEditors().find(e => e.getDomNode()?.isConnected);
editor.setSelection({ startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 15 });
});
await click("More terminal actions");
await menu("Run Selected Text");
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_write" && c.args.data.includes("print('hello')")));
await click("More terminal actions");
await menu("Run Active File");
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_write" && c.args.data.includes("python 'C:\\smoke-workspace\\src\\hello.py'")));
await click("Terminal profiles and tasks");
await menu("New Terminal Window Ctrl+Shift+Alt+`");
await waitCount("pty_new_window", 1);
await click("More terminal actions");
await menu("Start Dictation");
await waitCount("pty_dictation", 1);
await click("More terminal actions");
await menu("Clear Terminal");
assert.equal(await count("pty_close"), 1);
await page.setViewportSize({ width: 880, height: 600 });
await page.screenshot({ path: ".audit/terminal-narrow.png" });
for (let remaining = 5; remaining > 1; remaining--) await click("Kill terminal");
await waitCount("pty_close", 5);
assert.equal(await page.getByRole("navigation", { name: "Terminal list" }).count(), 0);
await page.screenshot({ path: ".audit/terminal-single.png" });
await click("Kill terminal");
await waitCount("pty_close", 6);
await click("Start a terminal");
await waitCount("pty_open", 7);
await page.locator(".pane.shown .xterm-helper-textarea").focus();
await page.keyboard.press("Control+Shift+Backquote");
await waitCount("pty_open", 8);
await page.keyboard.press("Control+Shift+Alt+Backquote");
await waitCount("pty_new_window", 2);
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);
assert.equal(await page.getByRole("navigation", { name: "Terminal list" }).count(), 0);
await page.screenshot({ path: ".audit/terminal-window.png" });
assert.deepEqual(errors, []);
console.log("PASS: split groups, profile selection, maximize/restore/hide, shell history, directory quoting, settings persistence, tasks, editor selection/file execution, window/dictation IPC, and narrow layout.");
} catch (error) { console.log("errors", errors, "writes", await writes());
await page.screenshot({ path: ".audit/terminal-failure.png" });
throw error;
} finally { await browser.close(); }
-39
View File
@@ -1,39 +0,0 @@
import assert from "node:assert/strict";
import test from "node:test";
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'");
assert.equal(quoteShell("/tmp/it's $(bad)", "bash"), "'/tmp/it'\\''s $(bad)'");
assert.equal(directoryCommand("C:\\two words", "cmd"), 'cd /d "C:\\two words"');
assert.equal(directoryCommand("C:\\two words", "node"), 'process.chdir("C:\\\\two words")');
assert.throws(() => quoteShell("C:\\%PATH%", "cmd"));
assert.throws(() => fileCommand("a\nwhoami.py", "powershell"));
});
test("run file selects a runner and rejects non-executable documents", () => {
assert.equal(fileCommand("D:\\project\\hello world.py", "powershell"), "python 'D:\\project\\hello world.py'");
assert.equal(fileCommand("/project/app.mjs", "bash"), "node '/project/app.mjs'");
assert.throws(() => fileCommand("notes.md", "powershell"));
assert.throws(() => fileCommand("app.js", "node"));
});
test("task config validates every entry before offering execution", () => {
assert.deepEqual(parseTasks('{"tasks":[{"label":"Test","command":"npm test","profile":"pwsh"}]}'), [{ label: "Test", command: "npm test", profile: "pwsh" }]);
for (const text of ['{}', '{"tasks":[null]}', '{"tasks":[{"label":"x","command":" "}]}', '{"tasks":[{"label":"x","command":"echo hi","profile":4}]}']) assert.throws(() => parseTasks(text));
});
test("history deduplicates most recent entries and is bounded", () => {
assert.deepEqual(remember(["one", "two"], "two"), ["two", "one"]);
assert.equal(remember(Array.from({ length: 100 }, (_, i) => String(i)), "new").length, 100);
assert.deepEqual(remember(["one"], " "), ["one"]);
});
test("physical key shortcuts distinguish new, split, window, and hide", () => {
const key = { ctrlKey: true, metaKey: false, altKey: false, shiftKey: true, code: "Backquote", key: "~" };
assert.equal(terminalShortcut(key), "new");
assert.equal(terminalShortcut({ ...key, altKey: true }), "window");
assert.equal(terminalShortcut({ ...key, code: "Digit5", key: "%" }), "split");
assert.equal(terminalShortcut({ ...key, shiftKey: false, code: "KeyJ", key: "j" }), "toggle");
assert.equal(terminalShortcut({ ...key, shiftKey: false, code: "KeyC", key: "c" }), null);
});