RuneStone 1.0.0

This commit is contained in:
Knotty Wyvern
2026-11-03 00:23:07 -07:00
commit 5557443ed1
818 changed files with 239368 additions and 0 deletions
+145
View File
@@ -0,0 +1,145 @@
// Start the test build, attach to its WebView2 through CDP, read the metrics, and stop only the started process tree.
import { spawn } from "node:child_process";
import { existsSync } from "node:fs";
import path from "node:path";
import { setTimeout as sleep } from "node:timers/promises";
import { playwright } from "../../tests/smoke/_harness/index.mjs";
import { processTree } from "./core.mjs";
import { listProcesses, stopTree } from "./processes.mjs";
import { TABLE } from "./scenarios.mjs";
const isMainPage = page => { try { const url = new URL(page.url()); return url.pathname === "/" && !url.search && url.protocol.startsWith("http"); } catch { return false; } };
async function cdpResponds(port) {
try {
const response = await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(1000) });
return response.ok;
} catch { return false; }
}
/** Call a Rust command from the page. */
export function invoke(page, command, args = {}) {
return page.evaluate(([command, args]) => window.__TAURI_INTERNALS__.invoke(command, args), [command, args]);
}
/**
* Start `exe` with remote debugging on `port` and attach to its main page.
* Refuse when another program already answers on the port, because the tool must not drive a foreign browser.
*/
export async function launch({ exe, port, timeout = 90000 }) {
if (await cdpResponds(port)) throw new Error(`Port ${port} already answers CDP requests. Stop that program or choose another --port.`);
const env = { ...process.env, WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS: `--remote-debugging-port=${port}`, NO_PROXY: "127.0.0.1,localhost", no_proxy: "127.0.0.1,localhost" };
const started = performance.now();
const startedAt = Date.now();
const child = spawn(exe, [], { env, cwd: path.dirname(exe), stdio: "ignore", windowsHide: false });
let exited = null;
child.on("exit", code => { exited = code ?? -1; });
child.on("error", error => { exited = String(error); });
await new Promise(resolve => child.once("spawn", resolve).once("error", resolve));
const app = { child, pid: child.pid, started, startedAt, browser: null, page: null, cdpMs: null };
if (!app.pid) throw new Error(`Cannot start ${exe}: ${exited}`);
try {
const { chromium } = playwright();
while (!app.browser) {
if (exited !== null) throw new Error(`The app stopped during the start (exit ${exited}).`);
if (performance.now() - started > timeout) throw new Error("CDP did not answer during the start.");
if (await cdpResponds(port)) app.browser = await chromium.connectOverCDP(`http://127.0.0.1:${port}`, { timeout: 10000 });
else await sleep(50);
}
app.cdpMs = performance.now() - started;
while (!app.page) {
if (performance.now() - started > timeout) throw new Error("The main window page did not open.");
app.page = app.browser.contexts().flatMap(context => context.pages()).find(isMainPage) ?? null;
if (!app.page) await sleep(50);
}
app.page.setDefaultTimeout(30000);
return app;
} catch (error) {
await stop(app);
throw error;
}
}
/** Wait for the known tree row. Return the start time in milliseconds from the spawn, and page timing values. */
export async function waitForWorkbench(app, timeout = 60000) {
await app.page.locator(TABLE.knownRow).waitFor({ state: "visible", timeout });
const startMs = performance.now() - app.started;
const timing = await app.page.evaluate(() => ({ timeOrigin: performance.timeOrigin, domContentLoaded: performance.getEntriesByType("navigation")[0]?.domContentLoadedEventEnd ?? null, tabs: document.querySelectorAll('[role="tab"]').length }));
return { startMs, navigationMs: timing.timeOrigin - app.startedAt, domContentLoadedMs: timing.domContentLoaded === null ? null : timing.timeOrigin + timing.domContentLoaded - app.startedAt, tabsAtStart: timing.tabs };
}
/** Start a long task observer in the page. */
export function observeLongTasks(page) {
return page.evaluate(() => {
const state = { count: 0, max: 0 };
const record = entries => { for (const entry of entries) { state.count++; state.max = Math.max(state.max, entry.duration); } };
const observer = new PerformanceObserver(list => record(list.getEntries()));
observer.observe({ type: "longtask" });
window.__rsLongTasks = { state, observer, record };
});
}
/** Stop the long task observer. Return the count and the longest duration. */
export function collectLongTasks(page) {
return page.evaluate(() => {
const tasks = window.__rsLongTasks;
if (!tasks) return null;
tasks.record(tasks.observer.takeRecords());
tasks.observer.disconnect();
return { count: tasks.state.count, maxMs: Math.round(tasks.state.max) };
});
}
/** Collect garbage in the main page, wait, and read the heap and the process tree. */
export async function readMemory(app, { settleMs = 5000 } = {}) {
const cdp = await app.page.context().newCDPSession(app.page);
try {
await cdp.send("HeapProfiler.collectGarbage");
await sleep(settleMs);
const heap = await cdp.send("Runtime.getHeapUsage");
const tree = processTree(await listProcesses(), app.pid);
return {
heapMB: heap.usedSize / 1048576,
heapTotalMB: heap.totalSize / 1048576,
privateMB: tree.privateBytes / 1048576,
workingSetMB: tree.workingSet / 1048576,
processCount: tree.count,
processNames: tree.names,
processes: tree.processes.map(item => ({ pid: item.ProcessId, parent: item.ParentProcessId, name: item.Name, privateMB: +(item.PrivatePageCount / 1048576).toFixed(1), workingSetMB: +(item.WorkingSetSize / 1048576).toFixed(1), created: item.Created })),
};
} finally { await cdp.detach().catch(() => {}); }
}
/**
* Clear the open tabs and the layout in the page storage, so the next start restores no tab and shows the file tree.
* Chromium writes local storage to disk after a delay, so the function waits before it returns.
*/
export async function clearViewState(page, flushMs = 6000) {
await page.evaluate(layout => {
for (const key of Object.keys(localStorage)) if (key.startsWith("runestone.document-session.")) localStorage.removeItem(key);
localStorage.setItem("runestone.workbenchLayout", JSON.stringify(layout));
}, TABLE.layout);
await sleep(flushMs);
}
/** Stop the started process tree and make sure that none of its processes remain. */
export async function stop(app) {
if (!app?.pid) return { stopped: false };
const before = processTree(await listProcesses().catch(() => []), app.pid).processes;
const result = await stopTree(app.pid);
await app.browser?.close().catch(() => {});
for (let attempt = 0; attempt < 50; attempt++) {
const now = await listProcesses().catch(() => []);
const left = before.filter(item => now.some(other => other.ProcessId === item.ProcessId && other.Created === item.Created));
if (!left.length) return { ...result, remaining: [] };
if (attempt === 10) for (const item of left) await stopTree(item.ProcessId);
await sleep(200);
}
throw new Error(`Processes of the stopped app remain: ${before.map(item => item.ProcessId).join(", ")}.`);
}
/** The WebView2 folder of the test identity. It exists after the first start of a build with that identifier. */
export function webviewFolder(localData) {
return path.join(localData, "EBWebView");
}
export const hasWebviewFolder = localData => existsSync(webviewFolder(localData));
+157
View File
@@ -0,0 +1,157 @@
// Pure parts of the feature measurement tool: arguments, safety refusals, statistics, the process tree, and the report table.
import path from "node:path";
export const FEATURES = ["git", "background", "terminal", "pdf", "pm"];
export const MODES = ["plugin", "native"];
export const SCENARIOS = ["on-idle", "in-use", "after-off"];
/** The app that the owner installed. The tool never starts it, stops it, or touches its data. */
export const INSTALLED_EXE = "D:\\Users\\KnottyWyvern\\AppData\\Local\\RuneStone\\runestone.exe";
export const INSTALLED_IDENTIFIER = "com.runestone.app";
export const USAGE = "Usage: node scripts/measureFeatures.mjs --exe <path> --identifier com.runestone.<name> --stage <name> --mode plugin|native --features git,background,terminal,pdf,pm [--runs 3] [--port 9241] [--fresh-fixture] [--only base,<feature>:<scenario>,...] [--skip-base]";
/** Read the command line. Throw an error with the usage text for a missing or unknown argument. */
export function parseArguments(args) {
const options = { exe: undefined, identifier: undefined, stage: undefined, mode: undefined, features: undefined, runs: 3, port: 9241, freshFixture: false, only: undefined, skipBase: false };
const values = { "--exe": "exe", "--identifier": "identifier", "--stage": "stage", "--mode": "mode", "--features": "features", "--runs": "runs", "--port": "port", "--only": "only" };
const seen = new Set();
for (let index = 0; index < args.length; index++) {
const arg = args[index];
if (arg === "--fresh-fixture") { options.freshFixture = true; continue; }
if (arg === "--skip-base") { options.skipBase = true; continue; }
const key = values[arg];
if (!key) throw new Error(`Unknown argument ${arg}. ${USAGE}`);
if (seen.has(arg)) throw new Error(`Give ${arg} one time only. ${USAGE}`);
seen.add(arg);
const value = args[++index];
if (value === undefined || value.startsWith("--")) throw new Error(`${arg} needs a value. ${USAGE}`);
options[key] = value;
}
for (const key of ["exe", "identifier", "stage", "mode", "features"]) if (options[key] === undefined) throw new Error(`--${key} is required. ${USAGE}`);
if (!MODES.includes(options.mode)) throw new Error(`--mode must be plugin or native. ${USAGE}`);
if (!/^[a-z0-9][a-z0-9._-]{0,63}$/i.test(options.stage)) throw new Error("--stage must be a simple folder name.");
const features = options.features.split(",").map(feature => feature.trim()).filter(Boolean);
const unknown = features.filter(feature => !FEATURES.includes(feature));
if (!features.length || unknown.length) throw new Error(`Unknown feature ${unknown.join(", ") || "(none)"}. Use ${FEATURES.join(", ")}.`);
options.features = [...new Set(features)];
for (const key of ["runs", "port"]) {
const number = Number(options[key]);
if (typeof options[key] === "string" && !/^\d+$/.test(options[key])) throw new Error(`--${key} must be a whole number.`);
options[key] = number;
}
if (options.runs < 1 || options.runs > 20) throw new Error("--runs must be from 1 to 20.");
if (options.port < 1024 || options.port > 65535) throw new Error("--port must be from 1024 to 65535.");
if (options.only !== undefined) {
options.only = options.only.split(",").map(item => item.trim()).filter(Boolean);
for (const item of options.only) {
const [feature, scenario] = item.split(":");
if (!(item === "base" || (options.features.includes(feature) && SCENARIOS.includes(scenario)))) throw new Error(`--only takes base or <feature>:<scenario>, not ${item}.`);
}
}
return options;
}
function samePath(a, b) {
return path.win32.resolve(a).toLowerCase() === path.win32.resolve(b).toLowerCase();
}
/**
* Refuse an unsafe target. The executable must not be the installed app or be in its folder.
* The identifier must start with `com.runestone.` and must not be the identifier of the installed app.
* `env` supplies LOCALAPPDATA and APPDATA. Return the two data folders that the tool may reset.
*/
export function checkTarget({ exe, identifier }, env = process.env) {
const installed = [INSTALLED_EXE];
if (env.LOCALAPPDATA) installed.push(path.win32.join(env.LOCALAPPDATA, "RuneStone", "runestone.exe"));
const resolved = path.win32.resolve(exe);
for (const target of installed) {
if (samePath(resolved, target) || samePath(path.win32.dirname(resolved), path.win32.dirname(target)))
throw new Error(`Refusing to run the installed RuneStone (${target}). Give a copy of a test build.`);
}
if (typeof identifier !== "string" || identifier.toLowerCase() === INSTALLED_IDENTIFIER)
throw new Error(`Refusing the identifier ${identifier}. It belongs to the installed RuneStone.`);
if (!/^com\.runestone\.[a-z0-9][a-z0-9-]*$/.test(identifier))
throw new Error(`Refusing the identifier ${identifier}. A test identifier starts with com.runestone. and has lowercase letters, digits, and hyphens.`);
if (!env.APPDATA || !env.LOCALAPPDATA) throw new Error("APPDATA and LOCALAPPDATA must be set.");
return { roaming: path.win32.join(env.APPDATA, identifier), local: path.win32.join(env.LOCALAPPDATA, identifier) };
}
/** The median of the finite numbers in `values`, or null when there is none. */
export function median(values) {
const numbers = values.filter(value => typeof value === "number" && Number.isFinite(value)).sort((a, b) => a - b);
if (!numbers.length) return null;
const middle = Math.floor(numbers.length / 2);
return numbers.length % 2 ? numbers[middle] : (numbers[middle - 1] + numbers[middle]) / 2;
}
/**
* Walk the descendants of `rootPid` in a process list from Win32_Process.
* A child counts only when it started after its parent, so a reused parent process ID does not add a stranger.
* Return the processes of the tree, with the root first, and the sums of the private bytes and the working sets.
*/
export function processTree(list, rootPid) {
const byParent = new Map();
for (const item of list) {
if (!byParent.has(item.ParentProcessId)) byParent.set(item.ParentProcessId, []);
byParent.get(item.ParentProcessId).push(item);
}
const root = list.find(item => item.ProcessId === rootPid);
if (!root) return { processes: [], privateBytes: 0, workingSet: 0, count: 0, names: {} };
const processes = [root];
const seen = new Set([rootPid]);
for (let index = 0; index < processes.length; index++) {
const parent = processes[index];
for (const child of byParent.get(parent.ProcessId) ?? []) {
if (seen.has(child.ProcessId)) continue;
if (typeof child.Created === "number" && typeof parent.Created === "number" && child.Created < parent.Created) continue;
seen.add(child.ProcessId);
processes.push(child);
}
}
const names = {};
for (const item of processes) names[item.Name] = (names[item.Name] ?? 0) + 1;
return {
processes,
privateBytes: processes.reduce((sum, item) => sum + Number(item.PrivatePageCount ?? 0), 0),
workingSet: processes.reduce((sum, item) => sum + Number(item.WorkingSetSize ?? 0), 0),
count: processes.length,
names,
};
}
export const METRICS = ["privateMB", "workingSetMB", "heapMB", "startMs", "firstNeedMs", "longTaskCount", "longTaskMaxMs", "processCount"];
/** The median of each metric over the samples that did not fail. */
export function summarize(samples) {
const good = samples.filter(sample => !sample.error);
const result = { runs: samples.length, failed: samples.length - good.length };
for (const metric of METRICS) result[metric] = median(good.map(sample => sample[metric]));
return result;
}
const fixed = (value, digits = 1) => value === null || value === undefined ? "–" : Number(value).toFixed(digits);
/** The Markdown report: one table row for each feature and scenario. */
export function markdownTable(report) {
const lines = [
`# Feature memory: ${report.stage}`,
"",
`Build: \`${report.build}\` (${report.identifier}), mode ${report.mode}, ${report.runs} runs for each scenario, ${report.date}.`,
`Machine: ${report.machine.cpu}, ${fixed(report.machine.ramGB)} GB RAM, ${report.machine.windows}.`,
"Each value is the median of the runs. Private and working set are sums over the process tree of the app.",
"",
"| Feature | Scenario | Private MB | Working set MB | JS heap MB | Start ms | First need ms | Long tasks (count / longest ms) |",
"| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: |",
];
for (const row of report.rows) {
const m = row.median;
if (!m || m.runs === m.failed) {
lines.push(`| ${row.feature} | ${row.scenario} | failed | | | | | ${row.reason ? row.reason.replace(/\|/g, "/").slice(0, 160) : ""} |`);
continue;
}
const failed = m.failed ? ` (${m.failed} of ${m.runs} runs failed)` : "";
lines.push(`| ${row.feature} | ${row.scenario}${failed} | ${fixed(m.privateMB)} | ${fixed(m.workingSetMB)} | ${fixed(m.heapMB)} | ${fixed(m.startMs, 0)} | ${fixed(m.firstNeedMs, 0)} | ${fixed(m.longTaskCount, 0)} / ${fixed(m.longTaskMaxMs, 0)} |`);
}
if (report.notes?.length) lines.push("", "Notes:", "", ...report.notes.map(note => `- ${note}`));
return lines.join("\n") + "\n";
}
+201
View File
@@ -0,0 +1,201 @@
// The fixture workspace: a Git repository with history and changes, a 50-page PDF, background images, and a Project Management store.
// It lives in the system temporary folder, outside the repository, so the file watcher of the app does not see the worktree.
import { execFile } from "node:child_process";
import { createHash } from "node:crypto";
import { existsSync, realpathSync } from "node:fs";
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { promisify } from "node:util";
import { encodePng, gradientPixel } from "./png.mjs";
import { writePdf } from "./pdf.mjs";
const run = promisify(execFile);
export const FIXTURE_VERSION = 1;
export const COMMITS = 30;
export const TEXT_FILES = 50;
export const PDF_PAGES = 50;
export const BOARDS = 8;
export const CARDS_PER_BOARD = 50;
export const IMAGES = 5;
export const IMAGE_SIZE = { width: 1920, height: 1080 };
/** A file at the workspace root that the tree shows at once. The start time waits for its row. */
export const KNOWN_ROW = "sample.pdf";
export const fixtureRoot = () => path.join(tmpdir(), "runestone-phase7-fixture");
/** A UUID with the version 4 layout, made from `seed`, so each fixture build has the same IDs. */
export function seededUuid(seed) {
const hex = createHash("sha256").update(seed).digest("hex");
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-${"89ab"[parseInt(hex[16], 16) % 4]}${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
}
/** The card file name: the hex of the UTF-8 card ID, then `.md`. */
export const cardFileName = id => `${Buffer.from(id, "utf8").toString("hex")}.md`;
/** An order key that sorts in the same order as `index`. */
const orderKey = index => `a${String.fromCharCode(97 + Math.floor(index / 26))}${String.fromCharCode(97 + (index % 26))}`;
const textName = index => `note-${String(index + 1).padStart(2, "0")}.txt`;
function git(cwd, args, env = {}) {
const config = ["-c", "user.name=RuneStone Fixture", "-c", "[email protected]", "-c", "commit.gpgsign=false", "-c", "core.autocrlf=false", "-c", "init.defaultBranch=main"];
return run("git", ["-C", cwd, ...config, ...args], { env: { ...process.env, GIT_TERMINAL_PROMPT: "0", ...env }, windowsHide: true, maxBuffer: 16 * 1024 * 1024 });
}
const LISTS = [
{ id: "backlog", name: "Backlog", status: null },
{ id: "todo", name: "To do", status: "todo" },
{ id: "doing", name: "In progress", status: "doing" },
{ id: "done", name: "Done", status: "done" },
];
/** The Project Management store: `workspace.json`, the card files, and the two `.gitignore` files. */
export function pmFiles() {
const files = new Map();
files.set(".runestone/pm/.gitignore", "# RuneStone PM local data\n*\n");
files.set(".runestone/pm/cards/.gitignore", "*\n");
const boards = [];
for (let b = 0; b < BOARDS; b++) {
const id = seededUuid(`board-${b}`);
boards.push({
name: `Fixture board ${b + 1}`,
value: {
schema: 1, kind: "board", id,
lists: LISTS.map(list => ({ id: list.id, name: list.name, status: list.status, collapsed: false })),
defaults: { todo: "todo", doing: "doing", done: "done" },
},
});
for (let c = 0; c < CARDS_PER_BOARD; c++) {
const cardId = seededUuid(`card-${b}-${c}`);
const list = LISTS[c % LISTS.length];
const status = list.status ?? "todo";
const source = [
"---",
"runestone_pm:",
" schema: 1",
` id: ${cardId}`,
" kind: task",
` status: ${status}`,
" tags: []",
" sessions: []",
" archived: false",
` order: ${orderKey(b * CARDS_PER_BOARD + c)}`,
" placements:",
` ${id}:`,
` listId: ${list.id}`,
` order: ${orderKey(c)}`,
` title: Fixture card ${c + 1} on board ${b + 1}`,
` priority: ${["low", "medium", "high"][c % 3]}`,
"---",
"",
`This card is fixture data for the memory measurement. Board ${b + 1}, card ${c + 1}.`,
"",
].join("\n");
files.set(`.runestone/pm/cards/${cardFileName(cardId)}`, source);
}
}
files.set(".runestone/pm/workspace.json", JSON.stringify({ schema: 1, boards, deletedBoardIds: [] }, null, 2) + "\n");
return files;
}
const COLORS = [
[[16, 42, 120], [220, 90, 40], 0.3],
[[10, 110, 80], [240, 220, 60], 1.2],
[[120, 20, 90], [40, 200, 230], 2.1],
[[30, 30, 30], [200, 200, 210], 0],
[[200, 40, 40], [20, 60, 160], Math.PI / 2],
];
async function writeFiles(root, files) {
for (const [rel, contents] of files) {
const target = path.join(root, ...rel.split("/"));
await mkdir(path.dirname(target), { recursive: true });
await writeFile(target, contents);
}
}
/** Build the fixture in `root`. The caller removes an old fixture first. */
export async function buildFixture(root) {
const workspace = path.join(root, "workspace");
const backgrounds = path.join(root, "backgrounds");
await mkdir(workspace, { recursive: true });
await mkdir(backgrounds, { recursive: true });
for (const [index, [from, to, angle]] of COLORS.entries()) {
const { width, height } = IMAGE_SIZE;
await writeFile(path.join(backgrounds, `background-${index + 1}.png`), encodePng(width, height, gradientPixel(width, height, from, to, angle)));
}
await git(workspace, ["init", "-q"]);
await writeFile(path.join(workspace, ".gitignore"), ".runestone/\n");
await writeFile(path.join(workspace, "sample.pdf"), writePdf(Array.from({ length: PDF_PAGES }, (_, index) => `Page ${index + 1}`)));
const line = (file, version) => `Fixture file ${file + 1}, version ${version}.\n`;
const versions = Array(TEXT_FILES).fill(0);
for (let file = 0; file < TEXT_FILES; file++) await writeFile(path.join(workspace, textName(file)), line(file, 0));
for (let commit = 0; commit < COMMITS; commit++) {
if (commit > 0) {
// Each later commit changes five files, so the graph and the diffs have content.
for (let k = 0; k < 5; k++) {
const file = (commit * 7 + k * 11) % TEXT_FILES;
versions[file]++;
await writeFile(path.join(workspace, textName(file)), Array.from({ length: versions[file] + 1 }, (_, v) => line(file, v)).join(""));
}
}
await git(workspace, ["add", "-A"]);
const date = new Date(Date.UTC(2026, 0, 1 + commit, 12)).toISOString();
await git(workspace, ["commit", "-q", "--no-verify", "-m", commit === 0 ? "Add the fixture files" : `Change fixture files, step ${commit}`], { GIT_AUTHOR_DATE: date, GIT_COMMITTER_DATE: date });
}
for (let file = 0; file < TEXT_FILES; file++) {
const target = path.join(workspace, textName(file));
await writeFile(target, (await readFile(target, "utf8")) + `Changed after the last commit (file ${file + 1}).\n`);
}
await writeFiles(workspace, pmFiles());
await writeFile(path.join(root, "fixture.json"), JSON.stringify({ version: FIXTURE_VERSION, commits: COMMITS, changes: TEXT_FILES, pages: PDF_PAGES, boards: BOARDS, cards: BOARDS * CARDS_PER_BOARD, images: IMAGES }, null, 2) + "\n");
}
/** Check that the fixture in `root` is complete and unchanged. Return a list of problems, empty when it matches. */
export async function checkFixture(root) {
const problems = [];
const workspace = path.join(root, "workspace");
try {
const record = JSON.parse(await readFile(path.join(root, "fixture.json"), "utf8"));
if (record.version !== FIXTURE_VERSION) problems.push(`fixture version ${record.version}`);
} catch { problems.push("no fixture.json"); return problems; }
for (let index = 0; index < IMAGES; index++) if (!existsSync(path.join(root, "backgrounds", `background-${index + 1}.png`))) problems.push(`no background ${index + 1}`);
if (!existsSync(path.join(workspace, "sample.pdf"))) problems.push("no sample.pdf");
try {
const status = (await git(workspace, ["status", "--porcelain"])).stdout.split("\n").filter(Boolean);
if (status.length !== TEXT_FILES || status.some(entry => !entry.startsWith(" M "))) problems.push(`git status shows ${status.length} entries, not ${TEXT_FILES} changed files`);
const count = Number((await git(workspace, ["rev-list", "--count", "HEAD"])).stdout.trim());
if (count !== COMMITS) problems.push(`${count} commits, not ${COMMITS}`);
} catch (error) { problems.push(`git: ${error.message}`); }
for (const [rel, contents] of pmFiles()) {
const target = path.join(workspace, ...rel.split("/"));
if (!existsSync(target)) { problems.push(`no ${rel}`); break; }
if (rel.endsWith("workspace.json") && (await readFile(target, "utf8")) !== contents) problems.push("workspace.json changed");
}
return problems;
}
/** Reuse the fixture when it matches, or build it again. Return the canonical paths. */
export async function prepareFixture({ fresh = false, root = fixtureRoot(), log = () => {} } = {}) {
let problems = fresh ? ["--fresh-fixture"] : await checkFixture(root);
if (problems.length) {
log(`Building the fixture in ${root} (${problems.join(", ")}).`);
// The fixture folder belongs to this tool. It is in the system temporary folder.
if (path.basename(root) !== "runestone-phase7-fixture") throw new Error(`Refusing to remove ${root}.`);
await rm(root, { recursive: true, force: true });
await buildFixture(root);
problems = await checkFixture(root);
if (problems.length) throw new Error(`The new fixture does not match: ${problems.join(", ")}.`);
} else log(`Reusing the fixture in ${root}.`);
// The canonical path expands short 8.3 names, so the app and the grants see the same path.
const real = realpathSync.native(root);
return { root: real, workspace: path.join(real, "workspace"), backgrounds: path.join(real, "backgrounds") };
}
/** Run the read-only Project Management helper of the skill. Return the number of boards that it lists. */
export async function inspectPmBoards(workspace, helper = path.join(process.env.USERPROFILE ?? "", ".claude", "skills", "runestone-project-management", "scripts", "inspect.mjs")) {
if (!existsSync(helper)) return { checked: false, reason: `no helper at ${helper}` };
const { stdout } = await run(process.execPath, [helper, "boards", "--workspace", workspace], { windowsHide: true, maxBuffer: 16 * 1024 * 1024 });
return { checked: true, output: stdout };
}
+47
View File
@@ -0,0 +1,47 @@
// A local fake Gitea release server. The host installs plugin ZIPs through its Gitea path from this server.
import { createServer } from "node:http";
import { readFile } from "node:fs/promises";
import path from "node:path";
/**
* Serve the releases in `packages`: a list of `{ repo, tag, file }`, with `file` the path of a plugin ZIP.
* The server answers `GET /api/v1/repos/test/<repo>/releases/tags/<tag>` and serves the ZIP at its download link.
* Return the base URL, the repository link of each package, the request log, and `close`.
*/
export async function startGiteaServer(packages, owner = "test") {
const bodies = new Map();
for (const item of packages) bodies.set(item.repo, { ...item, name: path.basename(item.file), bytes: await readFile(item.file) });
const requests = [];
const server = createServer((request, response) => {
const url = new URL(request.url, "http://127.0.0.1");
requests.push(`${request.method} ${url.pathname}`);
const release = /^\/api\/v1\/repos\/([^/]+)\/([^/]+)\/releases\/tags\/([^/]+)$/.exec(url.pathname);
const download = /^\/download\/([^/]+)\/([^/]+)$/.exec(url.pathname);
if (request.method === "GET" && release && release[1] === owner && bodies.get(release[2])?.tag === decodeURIComponent(release[3])) {
const item = bodies.get(release[2]);
const body = JSON.stringify({
tag_name: item.tag, draft: false,
assets: [{ name: item.name, size: item.bytes.length, browser_download_url: `${base}/download/${item.repo}/${encodeURIComponent(item.name)}` }],
});
response.writeHead(200, { "content-type": "application/json", "content-length": Buffer.byteLength(body) });
response.end(body);
return;
}
if (request.method === "GET" && download && bodies.get(download[1])?.name === decodeURIComponent(download[2])) {
const item = bodies.get(download[1]);
response.writeHead(200, { "content-type": "application/zip", "content-length": item.bytes.length });
response.end(item.bytes);
return;
}
response.writeHead(404, { "content-type": "text/plain" });
response.end("not found");
});
await new Promise((resolve, reject) => { server.once("error", reject); server.listen(0, "127.0.0.1", resolve); });
const base = `http://127.0.0.1:${server.address().port}`;
return {
base,
requests,
repository: repo => `${base}/${owner}/${repo}`,
close: () => new Promise(resolve => server.close(() => resolve())),
};
}
+45
View File
@@ -0,0 +1,45 @@
// A small PDF writer for the fixture document: one page for each text, in Helvetica, with a correct cross-reference table.
function escapeText(text) {
return text.replace(/[\\()]/g, match => `\\${match}`);
}
/** Write a PDF with one US Letter page for each entry of `texts`. Return the bytes. */
export function writePdf(texts) {
if (!texts.length) throw new Error("A PDF needs at least one page.");
// Object numbers: 1 catalog, 2 page tree, 3 font, then a page and its content stream for each text.
const pageIds = texts.map((_, index) => 4 + index * 2);
const objects = [
"<< /Type /Catalog /Pages 2 0 R >>",
`<< /Type /Pages /Kids [${pageIds.map(id => `${id} 0 R`).join(" ")}] /Count ${texts.length} >>`,
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>",
];
for (const [index, text] of texts.entries()) {
const stream = `BT /F1 48 Tf 72 680 Td (${escapeText(text)}) Tj ET\nBT /F1 14 Tf 72 640 Td (RuneStone measurement fixture, page ${index + 1} of ${texts.length}) Tj ET\n`;
objects.push(`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 3 0 R >> >> /Contents ${pageIds[index] + 1} 0 R >>`);
objects.push(`<< /Length ${Buffer.byteLength(stream, "latin1")} >>\nstream\n${stream}endstream`);
}
let body = "%PDF-1.4\n%\xe2\xe3\xcf\xd3\n";
const offsets = [];
for (const [index, object] of objects.entries()) {
offsets.push(Buffer.byteLength(body, "latin1"));
body += `${index + 1} 0 obj\n${object}\nendobj\n`;
}
const xref = Buffer.byteLength(body, "latin1");
// Each entry is exactly 20 bytes, with a space and a line feed at the end.
body += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n`;
for (const offset of offsets) body += `${String(offset).padStart(10, "0")} 00000 n \n`;
body += `trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF\n`;
return Buffer.from(body, "latin1");
}
/** Read the cross-reference table of a PDF from `writePdf`. Return `startxref` and the offsets of the objects in use. */
export function readPdfXref(bytes) {
const text = bytes.toString("latin1");
const start = Number(/startxref\n(\d+)\n%%EOF\n?$/.exec(text)?.[1]);
if (!Number.isInteger(start) || !text.startsWith("xref\n", start)) throw new Error("The startxref offset does not point to the xref table.");
const lines = text.slice(start).split("\n");
const [, count] = lines[1].split(" ").map(Number);
const entries = lines.slice(2, 2 + count).map(line => ({ line, offset: Number(line.slice(0, 10)), used: line.slice(17, 18) === "n" }));
return { start, count, entries };
}
+80
View File
@@ -0,0 +1,80 @@
// A small PNG encoder for the fixture images. It writes 8-bit RGB images without a dependency.
import { deflateSync } from "node:zlib";
const CRC_TABLE = (() => {
const table = new Uint32Array(256);
for (let n = 0; n < 256; n++) {
let c = n;
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
table[n] = c >>> 0;
}
return table;
})();
/** The CRC-32 of `bytes`, as PNG and ZIP use it. */
export function crc32(bytes) {
let crc = 0xffffffff;
for (const byte of bytes) crc = CRC_TABLE[(crc ^ byte) & 0xff] ^ (crc >>> 8);
return (crc ^ 0xffffffff) >>> 0;
}
export const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
function chunk(type, data) {
const length = Buffer.alloc(4);
length.writeUInt32BE(data.length);
const body = Buffer.concat([Buffer.from(type, "ascii"), data]);
const crc = Buffer.alloc(4);
crc.writeUInt32BE(crc32(body));
return Buffer.concat([length, body, crc]);
}
/** Encode an RGB image. `pixel(x, y)` returns `[r, g, b]` with values from 0 to 255. */
export function encodePng(width, height, pixel) {
if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1) throw new Error("The image size must be positive whole numbers.");
const stride = width * 3 + 1;
const raw = Buffer.alloc(stride * height);
for (let y = 0; y < height; y++) {
const row = y * stride;
raw[row] = 0; // Filter type None.
for (let x = 0; x < width; x++) {
const [r, g, b] = pixel(x, y);
const at = row + 1 + x * 3;
raw[at] = r; raw[at + 1] = g; raw[at + 2] = b;
}
}
const header = Buffer.alloc(13);
header.writeUInt32BE(width, 0);
header.writeUInt32BE(height, 4);
header[8] = 8; // Bit depth.
header[9] = 2; // Color type RGB.
header[10] = 0; header[11] = 0; header[12] = 0;
return Buffer.concat([PNG_SIGNATURE, chunk("IHDR", header), chunk("IDAT", deflateSync(raw, { level: 6 })), chunk("IEND", Buffer.alloc(0))]);
}
/** Read the chunks of a PNG file. Each chunk has its type, data, stored CRC, and computed CRC. */
export function readPngChunks(bytes) {
if (!bytes.subarray(0, 8).equals(PNG_SIGNATURE)) throw new Error("The file has no PNG signature.");
const chunks = [];
let at = 8;
while (at < bytes.length) {
const length = bytes.readUInt32BE(at);
const type = bytes.toString("ascii", at + 4, at + 8);
const data = bytes.subarray(at + 8, at + 8 + length);
const stored = bytes.readUInt32BE(at + 8 + length);
chunks.push({ type, data, stored, computed: crc32(bytes.subarray(at + 4, at + 8 + length)) });
at += 12 + length;
}
return chunks;
}
/** A diagonal gradient between two colors. Each fixture image uses a different pair and angle. */
export function gradientPixel(width, height, from, to, angle) {
const dx = Math.cos(angle), dy = Math.sin(angle);
const span = Math.abs(dx) * width + Math.abs(dy) * height;
const origin = Math.min(0, dx * width) + Math.min(0, dy * height);
return (x, y) => {
const t = (x * dx + y * dy - origin) / span;
return [0, 1, 2].map(i => Math.round(from[i] + (to[i] - from[i]) * t));
};
}
+25
View File
@@ -0,0 +1,25 @@
// Process sampling and the stop of one process tree. The tool never stops a process by its image name.
import { execFile } from "node:child_process";
import { promisify } from "node:util";
const run = promisify(execFile);
const LIST = "Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,Name,PrivatePageCount,WorkingSetSize,@{n='Created';e={if ($_.CreationDate) { $_.CreationDate.ToFileTimeUtc() } else { $null }}} | ConvertTo-Json -Compress";
/** List all processes one time, with the private bytes and the working set of each. */
export async function listProcesses() {
const { stdout } = await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", LIST], { maxBuffer: 64 * 1024 * 1024, windowsHide: true });
const value = JSON.parse(stdout);
return (Array.isArray(value) ? value : [value]).map(item => ({ ...item, PrivatePageCount: Number(item.PrivatePageCount ?? 0), WorkingSetSize: Number(item.WorkingSetSize ?? 0) }));
}
/** Stop the process tree of `pid` with taskkill. Errors are returned, not thrown, because the tree can be gone already. */
export async function stopTree(pid) {
if (!Number.isInteger(pid) || pid <= 4) throw new Error(`Refusing to stop process ID ${pid}.`);
try {
const { stdout } = await run("taskkill.exe", ["/PID", String(pid), "/T", "/F"], { windowsHide: true });
return { stopped: true, output: stdout.trim() };
} catch (error) {
return { stopped: false, output: String(error.stderr || error.message).trim() };
}
}
+187
View File
@@ -0,0 +1,187 @@
// The scenario table: the selectors, names, and feature switches of both modes, and the in-use action of each feature.
// A value with `plugin` and `native` keys differs between the modes. Change the table when a stage changes a name.
const PLUGIN_RELEASES = "D:/Users/KnottyWyvern/Documents";
export const TABLE = {
/** The start time ends when this tree row is visible. */
knownRow: '[data-tree-rel="sample.pdf"]',
/** The command palette. */
palette: { shortcut: "Control+Shift+P", input: "Find a command" },
/** The layout that the cleanup writes, so each start shows the file tree. */
layout: { leftOpen: true, rightOpen: true, leftWidth: 260, rightWidth: 240, leftView: "files" },
/** The settings section of the native feature switches. */
featuresSection: "features",
features: {
git: {
plugin: { id: "runestone.git", repo: "runestone-git", tag: "v0.1.10", zip: `${PLUGIN_RELEASES}/RuneStone_Git/releases/runestone.git-0.1.10.zip` },
nativeKey: "git",
navigation: "Source control",
changeRow: { plugin: ".rs-git-row", native: ".source-control .row" },
changeCount: 50,
changeFile: { plugin: ".rs-git-file", native: ".source-control .file" },
diffTab: "Git diff",
diffText: "Changed after the last commit",
graphCommand: "Show Git graph",
/** Where the command is: `palette`, or `menu:<ribbon menu name>`. Master lists plugin view commands only in the Plug-in views menu. */
graphCommandIn: { plugin: "menu:Plug-in views", native: "palette" },
graphTab: "Git graph",
graphText: "Change fixture files, step 29",
},
background: {
plugin: { id: "runestone.bg-slideshow", repo: "runestone-bg-slideshow", tag: "v0.0.11", zip: `${PLUGIN_RELEASES}/RuneStone_Background_Slideshow/releases/runestone.bg-slideshow-0.0.11.zip` },
nativeKey: "background",
/**
* The style property of the body that holds the current background image. The action counts its changes.
* Native: `backgroundHub.applyApp` (src/lib/plugins/backgrounds.ts) sets it for each new image of Background.
*/
imageProperty: { plugin: "--rs-background-image", native: "--rs-background-image" },
changes: 3,
seconds: 10,
},
terminal: {
plugin: { id: "runestone.terminal", repo: "runestone-terminal", tag: "v0.1.11", zip: `${PLUGIN_RELEASES}/RuneStone_Terminal/releases/runestone.terminal-0.1.11.zip` },
nativeKey: "terminal",
/**
* Both modes use the same names. Native: the ribbon button comes from the feature switch, and the first click loads
* the Terminal feature and xterm (src/lib/features/TerminalHost.svelte), so the action includes that load.
*/
ribbon: ".plugin-ribbon",
button: "Terminal",
surface: ".xterm",
rows: ".xterm-rows",
prompt: "PS [A-Za-z]:\\\\",
command: '1..10000 | % { "line $_" }',
readyText: "line 10000",
},
pdf: {
plugin: { id: "runestone.pdf-viewer", repo: "runestone-pdf-viewer", tag: "v0.0.5", zip: `${PLUGIN_RELEASES}/RuneStone_PDF_Viewer/releases/runestone.pdf-viewer-0.0.5.zip` },
nativeKey: "pdf",
/**
* Both modes use the same names. Native: the tree row opens a PDF tab, and the first tab loads the PDF Viewer feature
* and PDF.js (src/lib/features/pdf/), so the action includes that load. Each page canvas is an image named "PDF page N",
* and the page field is a spin button named "Page number". Enter in the field goes to the page.
*/
row: '[data-tree-rel="sample.pdf"]',
firstPage: "PDF page 1",
pageInput: "Page number",
target: 25,
targetPage: "PDF page 25",
},
pm: {
plugin: { id: "runestone.pm", repo: "runestone-pm", tag: "v0.2.49", zip: `${PLUGIN_RELEASES}/RuneStone_Project_Management/releases/runestone.pm-0.2.49.zip` },
nativeKey: "pm",
/**
* Where the view opens: `palette`, `menu:<ribbon menu name>`, or `ribbon:<ribbon button name>`. Native: the static
* ribbon button opens the default board or All tasks, and the first click loads the feature (src/lib/features/pm/).
*/
openIn: { plugin: "menu:Plug-in views", native: "ribbon:Project Management" },
title: "Project Management",
card: { plugin: ".pm-card", native: ".pm-card" },
minCards: 50,
},
},
};
/** The value of a table entry for `mode`. */
export const pick = (value, mode) => value && typeof value === "object" && !Array.isArray(value) && ("plugin" in value || "native" in value) ? value[mode] : value;
const escape = text => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const starts = text => new RegExp(`^${escape(text)}`);
/** Wait until the page has at least `count` elements for `selector`. The predicate is synchronous on purpose. */
export function waitForCount(page, selector, count, timeout = 60000) {
return page.waitForFunction(([selector, count]) => document.querySelectorAll(selector).length >= count, [selector, count], { timeout, polling: 100 });
}
/** Open a command from the command palette by its exact title. */
export async function runPaletteCommand(page, title) {
await page.keyboard.press(TABLE.palette.shortcut);
const input = page.getByRole("textbox", { name: TABLE.palette.input, exact: true });
await input.waitFor({ timeout: 10000 });
await input.fill(title);
await page.getByRole("button", { name: starts(title) }).first().waitFor({ timeout: 10000 });
await input.press("Enter");
}
/**
* Run a command from the palette, from a ribbon menu, or from a ribbon button.
* `where` is `palette`, `menu:<menu name>`, or `ribbon:<button name>`.
*/
export async function runCommand(page, where, title) {
if (where === "palette") return runPaletteCommand(page, title);
const button = /^ribbon:(.+)$/.exec(where)?.[1];
if (button) return page.locator(".plugin-ribbon").getByRole("button", { name: button, exact: true }).click();
const menu = /^menu:(.+)$/.exec(where)?.[1];
if (!menu) throw new Error(`Unknown command place ${where}.`);
await page.locator(".plugin-ribbon").getByRole("button", { name: menu, exact: true }).click();
await page.getByRole("menuitem", { name: starts(title) }).first().click();
}
/**
* The in-use action of each feature. Each action returns when its ready condition is true.
* `ctx` has `mode` and `log`. Some actions return details for the sample.
*/
export const ACTIONS = {
async git(page, { mode }) {
const git = TABLE.features.git;
await page.getByRole("button", { name: git.navigation, exact: true }).first().click();
await waitForCount(page, pick(git.changeRow, mode), git.changeCount);
await page.locator(pick(git.changeFile, mode)).first().click();
await page.getByRole("tab", { name: starts(git.diffTab) }).first().waitFor({ timeout: 30000 });
await page.getByText(git.diffText).first().waitFor({ timeout: 30000 });
await runCommand(page, pick(git.graphCommandIn, mode), git.graphCommand);
await page.getByRole("tab", { name: starts(git.graphTab) }).first().waitFor({ timeout: 30000 });
await page.getByText(git.graphText, { exact: true }).first().waitFor({ timeout: 30000 });
return { changeRows: await page.locator(pick(git.changeRow, mode)).count() };
},
async background(page, { mode }) {
const background = TABLE.features.background;
const property = pick(background.imageProperty, mode);
const started = Date.now();
// Count the changes in the page, so a short image does not slip between two Node polls.
await page.evaluate(property => {
const state = { values: [], times: [] };
const sample = () => {
const value = document.body.style.getPropertyValue(property);
if (value && value !== state.values.at(-1)) { state.values.push(value); state.times.push(performance.now()); }
};
sample();
state.timer = setInterval(sample, 100);
window.__rsBackgroundProbe = state;
}, property);
const timeout = (background.changes + 2) * background.seconds * 1000 + 30000;
await page.waitForFunction(changes => (window.__rsBackgroundProbe?.values.length ?? 0) >= changes + 1, background.changes, { timeout, polling: 250 });
const result = await page.evaluate(() => {
const state = window.__rsBackgroundProbe;
clearInterval(state.timer);
return { images: state.values.length, intervalsMs: state.times.slice(1).map((time, index) => Math.round(time - state.times[index])) };
});
return { ...result, waitedMs: Date.now() - started };
},
async terminal(page) {
const terminal = TABLE.features.terminal;
await page.locator(terminal.ribbon).getByRole("button", { name: terminal.button, exact: true }).click();
await page.locator(terminal.surface).first().waitFor({ timeout: 30000 });
await page.waitForFunction(([rows, prompt]) => new RegExp(prompt).test((document.querySelector(rows)?.textContent ?? "").replace(/\u00a0/g, " ")), [terminal.rows, terminal.prompt], { timeout: 60000, polling: 100 });
await page.locator(terminal.surface).first().click();
await page.keyboard.type(terminal.command);
await page.keyboard.press("Enter");
await page.waitForFunction(([rows, text]) => (document.querySelector(rows)?.textContent ?? "").replace(/\u00a0/g, " ").includes(text), [terminal.rows, terminal.readyText], { timeout: 120000, polling: 100 });
},
async pdf(page) {
const pdf = TABLE.features.pdf;
await page.locator(pdf.row).click();
await page.getByRole("img", { name: pdf.firstPage, exact: true }).waitFor({ timeout: 60000 });
const input = page.getByRole("textbox", { name: pdf.pageInput, exact: true }).or(page.getByRole("spinbutton", { name: pdf.pageInput, exact: true })).first();
await input.fill(String(pdf.target));
await input.press("Enter");
await page.getByRole("img", { name: pdf.targetPage, exact: true }).waitFor({ timeout: 60000 });
},
async pm(page, { mode }) {
const pm = TABLE.features.pm;
await runCommand(page, pick(pm.openIn, mode), pm.title);
await waitForCount(page, pick(pm.card, mode), pm.minCards);
return { cards: await page.locator(pick(pm.card, mode)).count() };
},
};