Make Terminal a native feature

- Move the Terminal plugin into src/lib/features/terminal/ on the host Svelte runtime, with xterm 6.0.0 and addon-fit 0.11.0.
- Buttons, shortcuts, Help rows, and the close guard follow the Terminal switch. The first use loads the module.
- Add Settings → Terminal and the terminal settings section. The first start copies the old runestone.terminal key.
- The 16 ANSI colors come from the --rs-ansi-* tokens.
- Off asks first when a shell runs in any window (pty_running).
- Rust: no pty-data or pty-exit events, an owner check for write, resize, and close, output joined up to 64 KiB or 8 ms, and the sessions of a reloaded page close.
- Remove api.pty, the terminal contribution, TerminalSlot, and the plugin loader of the smoke harness.
- Check only the tested switches in the Background smoke test.
- Update the tests, the menu inventory, the docs, and UI-058.
This commit is contained in:
Knotty Wyvern
2026-10-29 19:02:58 -07:00
parent 53b9cea7f0
commit 833f793244
78 changed files with 2971 additions and 659 deletions
+44 -5
View File
@@ -105,11 +105,14 @@ export async function showSavedImage(page) {
*
* `commands(test)` runs in the page and returns a map from command name to handler `(args, test) => result`.
* It cannot use variables from the test file. Pass data through `state`, which must be JSON.
* `test` is also `window.__TEST__`: `{ state, calls, emit(event, payload), label, workspace(options), settings(section), writeSettings(section, value) }`.
* `test` is also `window.__TEST__`: `{ state, calls, emit(event, payload), label, workspace(options), pty, settings(section), writeSettings(section, value) }`.
* A command without a handler throws "Unhandled IPC", or returns null when `strict` is false.
*
* Default handlers serve the settings file (`settings_*`), tab transfers (`tab_transfer_*`), and an installed browser engine
* (`browser_engine_status`). `commands` can replace them.
* Default handlers serve the settings file (`settings_*`), tab transfers (`tab_transfer_*`), an installed browser engine
* (`browser_engine_status`), and the shells of the Terminal feature (`pty_*`). `commands` can replace them.
* The mock shell sends "READY 🪨" and a cursor position query through the channel of `pty_open`, before the open returns.
* `test.pty.output(id, text)` and `test.pty.exit(id, code)` send more to an open session. `pty_running` counts the open
* sessions of all pages of the context.
* All pages of one browser context share their state: the settings file and the offers are in localStorage under
* test keys, and a BroadcastChannel sends `settings-changed` to every page and `tab-transfer-accepted` to the source page.
* Without a settings file, the app migrates the old localStorage keys, so a test can seed preferences there before the first load.
@@ -207,7 +210,7 @@ function installMock(options, commands) {
if (target !== pageId) channel.postMessage({ event, payload, target });
};
const SETTINGS_FILE = "runestone.smoke.settings-file", TRANSFERS = "runestone.smoke.tab-transfers";
const SECTIONS = ["general", "appearance", "customThemes", "customThemesLegacy", "language", "features", "background"];
const SECTIONS = ["general", "appearance", "customThemes", "customThemesLegacy", "language", "features", "background", "terminal"];
const readJson = (key, fallback) => { try { return JSON.parse(localStorage.getItem(key)) ?? fallback; } catch { return fallback; } };
const settingsFile = () => readJson(SETTINGS_FILE, null);
const snapshot = () => {
@@ -224,6 +227,21 @@ function installMock(options, commands) {
broadcast("settings-changed", change);
return change;
};
// The terminal sessions of this page (src-tauri/src/pty.rs). The count of each page is in localStorage, so `pty_running`
// in a Settings page sees the shells of the main page. A page that unloads takes its count with it.
const PTY_COUNTS = "runestone.smoke.pty-sessions";
const channels = new Map();
const countSessions = () => {
const counts = readJson(PTY_COUNTS, {});
if (channels.size) counts[pageId] = channels.size; else delete counts[pageId];
localStorage.setItem(PTY_COUNTS, JSON.stringify(counts));
};
addEventListener("pagehide", () => { channels.clear(); countSessions(); });
const pty = {
channels,
output: (id, text) => channels.get(id)?.onmessage(new TextEncoder().encode(text).buffer),
exit: (id, code) => channels.get(id)?.onmessage({ exit: code }),
};
const offers = () => {
const list = readJson(TRANSFERS, {});
for (const [id, offer] of Object.entries(list)) if (Date.now() - offer.created >= (offer.taker ? 240000 : 120000)) delete list[id];
@@ -237,6 +255,27 @@ function installMock(options, commands) {
settings_read: () => snapshot(),
// src-tauri/src/features.rs: no old plugin package of a native feature is installed.
features_legacy: () => [],
// src-tauri/src/pty.rs: one shell. Tests of the terminal replace `pty_profiles` to show more profiles.
pty_profiles: () => [{ id: "powershell", title: "PowerShell", kind: "powershell" }],
pty_open: async ({ id, page, channel }) => {
if (!channel || typeof channel.onmessage !== "function") throw "pty_open needs an output channel";
if (typeof page !== "string" || !page) throw "Invalid terminal page ID";
if (channels.has(id)) throw "terminal already exists";
channels.set(id, channel);
countSessions();
const data = new TextEncoder().encode("READY 🪨\r\n\x1b[6n");
// Split the emoji between two messages, as a real shell can.
channel.onmessage(data.slice(0, 8).buffer);
channel.onmessage(data.slice(8).buffer);
await new Promise(resolve => setTimeout(resolve, 50));
return null;
},
pty_write: ({ id }) => { if (!channels.has(id)) throw "terminal is not open"; return null; },
pty_resize: ({ id }) => { if (!channels.has(id)) throw "terminal is not open"; return null; },
pty_close: ({ id }) => { channels.delete(id); countSessions(); return null; },
pty_running: () => Object.values(readJson(PTY_COUNTS, {})).reduce((sum, count) => sum + count, 0),
pty_new_window: () => null,
pty_dictation: () => null,
// The editor asks for the Git line of the cursor while the Git feature is on. Tests of Git replace it.
git_blame: () => null,
// src-tauri/src/backgrounds.rs: the host has no background folder. Tests of the Background folder replace these.
@@ -277,7 +316,7 @@ function installMock(options, commands) {
},
};
const test = { state: options.state, calls: [], emit, label: options.label, workspace, settings: section => settingsFile()?.[section], writeSettings };
const test = { state: options.state, calls: [], emit, label: options.label, workspace, pty, settings: section => settingsFile()?.[section], writeSettings };
// Look up the test's handlers first. A test can return a Proxy, so do not copy its keys.
const table = commands ? commands(test) || {} : {};
window.isTauri = true;
+13 -27
View File
@@ -1,44 +1,30 @@
import { readFile } from "node:fs/promises";
import { resolve } from "node:path";
import { pathToFileURL } from "node:url";
import { pluginRepo } from "./index.mjs";
// Installed plugin packages for the smoke tests: the `plugins_*` commands of src-tauri/src/plugins.rs, without plugin code.
/** An installed package of the old Table Formulas plugin. RuneStone now includes the feature and must not load this code. */
export const oldTableFormulasRow = {
manifest: { schemaVersion: 1, id: "runestone.table-formulas", name: "Table Formulas", author: "RuneStone Team", description: "Calculate formulas in Markdown tables.", version: "0.1.3", apiVersion: 1, entry: "main.js", access: "full-app" },
hash: "old-hash", enabled: true, path: "C:\\AppData\\RuneStone\\plugins\\runestone.table-formulas", error: null, removal: false,
hash: "old-hash", enabled: true, path: "C:\AppData\RuneStone\plugins\runestone.table-formulas", error: null, removal: false,
};
/**
* Load the compiled Terminal package through the production Blob module loader.
* `extraRows` adds installed rows without code, for example `oldTableFormulasRow`.
* Serve `rows` as the installed packages. All pages of a context share them through localStorage, and a change sends
* `plugins-changed`. Enable, disable, and remove work. `plugins_load` fails, because the rows have no code.
* Call it after `mockTauri`, because it wraps the IPC mock.
*/
export async function mockFeaturePlugins(surface, extraRows = []) {
// The runner checks the same folder for "@requires plugin:terminal".
const root = pathToFileURL(resolve(process.env.RUNESTONE_TERMINAL_DIST || pluginRepo("RuneStone_Terminal/dist")) + "/");
const packages = [{
manifest: JSON.parse(await readFile(new URL("plugin.json", root), "utf8")),
code: await readFile(new URL("main.js", root), "utf8"),
css: await readFile(new URL("style.css", root), "base64"),
}];
await surface.addInitScript(({ packages, extraRows }) => {
export async function mockInstalledPlugins(surface, rows = []) {
await surface.addInitScript(rows => {
const key = "test.installed-plugins";
const root = "C:\\AppData\\RuneStone\\plugins";
const defaults = [...packages.map(item => ({ manifest: item.manifest, hash: "test-hash", enabled: true, path: root + "\\" + item.manifest.id, error: null, removal: false })), ...extraRows];
const read = () => JSON.parse(localStorage.getItem(key) || JSON.stringify(defaults));
const write = rows => { localStorage.setItem(key, JSON.stringify(rows)); window.__TEST__?.emit("plugins-changed", {}); };
if (!localStorage.getItem(key)) localStorage.setItem(key, JSON.stringify(defaults));
const root = "C:\AppData\RuneStone\plugins";
const read = () => JSON.parse(localStorage.getItem(key) || JSON.stringify(rows));
const write = next => { localStorage.setItem(key, JSON.stringify(next)); window.__TEST__?.emit("plugins-changed", {}); };
if (!localStorage.getItem(key)) localStorage.setItem(key, JSON.stringify(rows));
window.addEventListener("storage", event => { if (event.key === key) window.__TEST__?.emit("plugins-changed", {}); });
const original = window.__TAURI_INTERNALS__.invoke;
window.__TAURI_INTERNALS__.invoke = async (command, args = {}) => {
if (!command.startsWith("plugins_")) return original(command, args);
window.__TEST__?.calls.push({ command, args });
if (command === "plugins_snapshot") return { root, plugins: read() };
if (command === "plugins_load" || command === "plugins_asset") {
const item = packages.find(item => item.manifest.id === args.id);
if (!item) throw new Error(`No code for ${args.id}`);
return command === "plugins_load" ? item.code : item.css;
}
if (command === "plugins_load" || command === "plugins_asset") throw new Error(`No code for ${args.id}`);
if (command === "plugins_set_enabled") { write(read().map(item => item.manifest.id === args.id ? { ...item, enabled: args.enabled } : item)); return; }
if (command === "plugins_prepare_remove") return { token: args.id, plugin: read().find(item => item.manifest.id === args.id) };
if (command === "plugins_remove") { write(read().filter(item => item.manifest.id !== args.token)); return; }
@@ -46,5 +32,5 @@ export async function mockFeaturePlugins(surface, extraRows = []) {
if (["plugins_release", "plugins_cancel", "plugins_reveal"].includes(command)) return;
throw new Error(`Unhandled plugin IPC: ${command}`);
};
}, { packages, extraRows });
}, rows);
}