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:
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -204,7 +204,10 @@ await runSmoke("features/background", async ({ browser }) => {
|
||||
await migrated.goto(smokeUrl);
|
||||
await waitForChange(migrated, "");
|
||||
assert.deepEqual(await migrated.evaluate(() => window.__TEST__.settings("background")), { source: "folder", seconds: 7, order: "random", paused: false, targets: ["app", "pm-all"], overlay: 0.3, position: "top", size: "contain" });
|
||||
assert.deepEqual(await migrated.evaluate(() => window.__TEST__.settings("features")), { git: true, background: true });
|
||||
// Each feature gets its switch. Background is on, and Git follows its old package (none here).
|
||||
const switches = await migrated.evaluate(() => window.__TEST__.settings("features"));
|
||||
assert.equal(switches.background, true);
|
||||
assert.equal(switches.git, true);
|
||||
assert.equal(await migrated.evaluate(() => window.__TEST__.calls.filter(call => call.command === "background_migrate").length), 1);
|
||||
assert.deepEqual(migrated.errors, []);
|
||||
await migrationContext.close();
|
||||
|
||||
@@ -20,7 +20,7 @@ await runSmoke("features/settings", async ({ browser }) => {
|
||||
const sourceControl = main.locator(".header-left").getByRole("button", { name: "Source control", exact: true });
|
||||
await sourceControl.waitFor();
|
||||
// Without an old package, the migration stores the default of each feature.
|
||||
assert.deepEqual(await main.evaluate(() => window.__TEST__.settings("features")), { git: true, background: true });
|
||||
assert.deepEqual(await main.evaluate(() => window.__TEST__.settings("features")), { git: true, background: true, terminal: true });
|
||||
|
||||
const settings = await openPage(context, { timeout: 10000 });
|
||||
await settings.goto(`${smokeUrl}/?settingsWindow=true`);
|
||||
@@ -33,7 +33,7 @@ await runSmoke("features/settings", async ({ browser }) => {
|
||||
|
||||
await git.click();
|
||||
await sourceControl.waitFor({ state: "detached" });
|
||||
assert.deepEqual(await main.evaluate(() => window.__TEST__.settings("features")), { git: false, background: true });
|
||||
assert.deepEqual(await main.evaluate(() => window.__TEST__.settings("features")), { git: false, background: true, terminal: true });
|
||||
assert.equal(await settings.getByRole("status").innerText(), "Changes saved.");
|
||||
await git.focus();
|
||||
await settings.keyboard.press("Space");
|
||||
|
||||
@@ -0,0 +1,474 @@
|
||||
// The Terminal feature: lazy load, copy and paste, the theme and the --rs-ansi-* colors, splits, maximize, profiles, history pickers,
|
||||
// tasks, run file and run selection, Settings → Terminal, the Off prompt, close and reopen, and the terminal window.
|
||||
// The `pty_*` commands are mocks with channels (tests/smoke/_harness/index.mjs). They do not prove real shell behavior.
|
||||
import assert from "node:assert/strict";
|
||||
import path from "node:path";
|
||||
import { mockTauri, openPage, outputDir, runSmoke, settle, smokeUrl } from "../_harness/index.mjs";
|
||||
|
||||
await runSmoke("features/terminal", async ({ browser }) => {
|
||||
const output = await outputDir("features/terminal");
|
||||
const shot = name => path.join(output, name);
|
||||
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
|
||||
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
await mockTauri(context, {
|
||||
state: { confirm: "Cancel" },
|
||||
commands: test => {
|
||||
const workspace = test.workspace({
|
||||
root: "C:\\smoke-workspace",
|
||||
files: {
|
||||
"notes/welcome.md": "# Working notes\n\nFirst paragraph.\n",
|
||||
"src/hello.py": "print('hello')\n",
|
||||
},
|
||||
});
|
||||
test.files = workspace.files;
|
||||
return {
|
||||
...workspace,
|
||||
pty_profiles: () => [{ 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" }],
|
||||
settings_open_window: () => null,
|
||||
spelling_menu_install: () => null,
|
||||
"plugin:window|is_maximized": () => false,
|
||||
"plugin:window|destroy": () => null,
|
||||
"plugin:dialog|message": args => { test.state.prompts = [...test.state.prompts ?? [], args.message]; return test.state.confirm; },
|
||||
};
|
||||
},
|
||||
});
|
||||
const page = await openPage(context);
|
||||
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(""));
|
||||
const xtermLoaded = target => target.evaluate(() => performance.getEntriesByType("resource").some(entry => /xterm/i.test(entry.name)));
|
||||
const appearance = (target, mode) => target.evaluate(async mode => {
|
||||
const { applyAppearance } = await import("/src/lib/theme/appearance.ts");
|
||||
applyAppearance({ theme: "default", mode });
|
||||
}, mode);
|
||||
|
||||
await page.goto(smokeUrl);
|
||||
await page.getByText("smoke-workspace", { exact: true }).waitFor();
|
||||
// The Terminal button shows from the static catalog. The feature module and xterm load at the first use.
|
||||
assert.equal(await xtermLoaded(page), false, "xterm does not load at start");
|
||||
await click("Terminal");
|
||||
await waitCount("pty_open", 1);
|
||||
const open = await page.evaluate(() => window.__TEST__.calls.find(c => c.command === "pty_open").args);
|
||||
assert.equal(typeof open.page, "string", "Each open sends the page ID");
|
||||
assert.equal(open.cwd, "C:\\smoke-workspace");
|
||||
await page.locator(".xterm-rows > div > span").first().waitFor();
|
||||
assert.equal(await xtermLoaded(page), true);
|
||||
const terminalFont = await page.locator(".xterm-rows > div > span").first().evaluate(element => {
|
||||
const style = getComputedStyle(element);
|
||||
return { family: style.fontFamily, weight: style.fontWeight, size: style.fontSize };
|
||||
});
|
||||
assert.equal(terminalFont.weight, "300");
|
||||
assert.equal(terminalFont.size, "13px");
|
||||
assert.ok(terminalFont.family.startsWith('"Cascadia Mono"'));
|
||||
// The input before the open finished includes the answer of xterm to the cursor position query.
|
||||
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_write" && /\x1b\[\d+;\d+R/.test(c.args.data)));
|
||||
|
||||
// Copy: a drag selects without copy, a right-click copies and clears, Ctrl+C copies a selection, and without one it interrupts.
|
||||
await page.evaluate(() => navigator.clipboard.writeText("before selection"));
|
||||
const beforeSelection = await writes();
|
||||
const firstText = await page.locator(".xterm-rows > div > span").first().boundingBox();
|
||||
await page.mouse.move(firstText.x + 1, firstText.y + firstText.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(firstText.x + firstText.width, firstText.y + firstText.height / 2, { steps: 10 });
|
||||
await page.mouse.up();
|
||||
assert.ok(await page.locator(".xterm-selection > div").count(), "Mouse drag selects terminal output.");
|
||||
assert.equal(await page.evaluate(() => navigator.clipboard.readText()), "before selection", "Selection does not copy output.");
|
||||
assert.equal(await writes(), beforeSelection, "Selection does not send input to the shell.");
|
||||
await page.locator(".term").first().screenshot({ path: shot("terminal-copy-selection.png") });
|
||||
await page.evaluate(() => {
|
||||
window.__TEST__.writeText = navigator.clipboard.writeText.bind(navigator.clipboard);
|
||||
navigator.clipboard.writeText = text => new Promise(resolve => {
|
||||
window.__TEST__.finishCopy = async () => { await window.__TEST__.writeText(text); resolve(); };
|
||||
});
|
||||
});
|
||||
await page.mouse.click(firstText.x + 10, firstText.y + firstText.height / 2, { button: "right" });
|
||||
assert.ok(await page.locator(".xterm-selection > div").count(), "Selection stays until the clipboard write succeeds.");
|
||||
await page.evaluate(() => window.__TEST__.finishCopy());
|
||||
await page.evaluate(() => { navigator.clipboard.writeText = window.__TEST__.writeText; });
|
||||
await page.waitForFunction(async () => (await navigator.clipboard.readText()).includes("READY"));
|
||||
await page.waitForFunction(() => !document.querySelector(".xterm-selection > div"));
|
||||
assert.equal(await writes(), beforeSelection, "Right-click copy does not send input to the shell.");
|
||||
await page.evaluate(() => navigator.clipboard.writeText("empty selection"));
|
||||
await page.mouse.click(firstText.x + 10, firstText.y + firstText.height / 2, { button: "right" });
|
||||
assert.equal(await page.evaluate(() => navigator.clipboard.readText()), "empty selection", "Right-click without selection keeps the clipboard.");
|
||||
await page.mouse.dblclick(firstText.x + 10, firstText.y + firstText.height / 2);
|
||||
await page.evaluate(() => navigator.clipboard.writeText(""));
|
||||
const beforeCopy = await writes();
|
||||
await page.keyboard.press("Control+c");
|
||||
await page.waitForFunction(async () => (await navigator.clipboard.readText()).includes("READY"));
|
||||
assert.equal(await writes(), beforeCopy, "Copy does not send an interrupt to the shell.");
|
||||
const beforeInterrupt = await writes();
|
||||
await page.locator(".xterm-screen").first().click();
|
||||
await page.keyboard.press("Control+c");
|
||||
await page.waitForFunction(before => window.__TEST__.calls.filter(c => c.command === "pty_write").map(c => c.args.data).join("").length > before.length, beforeInterrupt);
|
||||
assert.equal((await writes()).slice(beforeInterrupt.length), "\u0003", "Ctrl+C without selection interrupts the shell.");
|
||||
// A denied clipboard write keeps the selection for another try.
|
||||
await page.mouse.dblclick(firstText.x + 10, firstText.y + firstText.height / 2);
|
||||
await page.evaluate(() => { navigator.clipboard.writeText = () => Promise.reject(new Error("Clipboard denied for smoke test")); });
|
||||
await page.locator(".xterm-screen").first().click({ button: "right" });
|
||||
await page.getByText("Error: Clipboard denied for smoke test", { exact: true }).waitFor();
|
||||
assert.ok(await page.locator(".xterm-selection > div").count(), "Failed copy keeps the selection.");
|
||||
await page.evaluate(() => { navigator.clipboard.writeText = window.__TEST__.writeText; });
|
||||
|
||||
// The 16 ANSI colors come from the --rs-ansi-* tokens. A token change reaches the open terminal.
|
||||
const id = open.id;
|
||||
await page.evaluate(id => window.__TEST__.pty.output(id, "\x1b[31mANSI-RED\x1b[0m \x1b[94mANSI-BLUE\x1b[0m\r\n"), id);
|
||||
const colorOf = text => page.evaluate(text => {
|
||||
const span = [...document.querySelectorAll(".xterm-rows span")].find(node => node.textContent.includes(text));
|
||||
return span && getComputedStyle(span).color;
|
||||
}, text);
|
||||
await page.waitForFunction(() => [...document.querySelectorAll(".xterm-rows span")].some(node => node.textContent.includes("ANSI-RED")));
|
||||
const red = await page.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue("--rs-ansi-red").trim());
|
||||
assert.ok(red, "The theme defines --rs-ansi-red");
|
||||
await page.evaluate(() => {
|
||||
document.documentElement.style.setProperty("--rs-ansi-red", "#12ab34");
|
||||
document.documentElement.style.setProperty("--rs-ansi-bright-blue", "#3456cd");
|
||||
});
|
||||
await page.waitForFunction(() => {
|
||||
const color = text => getComputedStyle([...document.querySelectorAll(".xterm-rows span")].find(node => node.textContent.includes(text))).color;
|
||||
return color("ANSI-RED") === "rgb(18, 171, 52)" && color("ANSI-BLUE") === "rgb(52, 86, 205)";
|
||||
});
|
||||
await page.evaluate(() => { for (const name of ["--rs-ansi-red", "--rs-ansi-bright-blue"]) document.documentElement.style.removeProperty(name); });
|
||||
await page.waitForFunction(() => getComputedStyle([...document.querySelectorAll(".xterm-rows span")].find(node => node.textContent.includes("ANSI-RED"))).color !== "rgb(18, 171, 52)");
|
||||
assert.notEqual(await colorOf("ANSI-RED"), "rgb(18, 171, 52)");
|
||||
|
||||
// Selection colors keep their hue and stay at most 65% opaque, in both themes and at two widths.
|
||||
for (const theme of ["light", "dark"]) {
|
||||
await appearance(page, theme);
|
||||
for (const width of [620, 1440]) {
|
||||
await page.setViewportSize({ width, height: 1000 });
|
||||
await page.locator(".xterm-helper-textarea").first().focus();
|
||||
const text = await (await page.waitForFunction(() => {
|
||||
const node = [...document.querySelectorAll(".xterm-rows > div > span")].find(node => node.textContent.includes("READY"));
|
||||
const rect = node?.getBoundingClientRect();
|
||||
return rect?.width ? { x: rect.x, y: rect.y, width: rect.width, height: rect.height } : null;
|
||||
})).jsonValue();
|
||||
await page.mouse.move(text.x + 1, text.y + text.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(text.x + text.width, text.y + text.height / 2, { steps: 10 });
|
||||
await page.mouse.up();
|
||||
await page.evaluate(() => navigator.clipboard.writeText(""));
|
||||
await page.keyboard.press("Control+Shift+c");
|
||||
await page.waitForFunction(async () => (await navigator.clipboard.readText()).includes("READY"));
|
||||
const selectionColor = await page.locator(".xterm-selection > div").first().evaluate(node => getComputedStyle(node).backgroundColor);
|
||||
const selectionAlpha = Number(selectionColor.match(/rgba\([^,]+,[^,]+,[^,]+,\s*([\d.]+)\)/)?.[1] ?? 1);
|
||||
assert.ok(selectionAlpha > 0 && selectionAlpha <= 0.65, `Terminal selection keeps transparency: ${selectionColor}`);
|
||||
assert.ok(await page.locator(".xterm-rows .xterm-decoration-top").first().evaluate(node => getComputedStyle(node).backgroundColor === "rgba(0, 0, 0, 0)"), "Selected glyph backgrounds stay transparent.");
|
||||
await page.locator(".term").first().screenshot({ path: shot(`terminal-theme-${theme}-${width}.png`) });
|
||||
}
|
||||
}
|
||||
for (const [source, expected] of [["#ff8000", [255, 128, 0, 0.647]], ["rgba(0, 255, 128, 0.35)", [0, 255, 128, 0.35]]]) {
|
||||
await page.evaluate(source => document.documentElement.style.setProperty("--rs-selection", source), source);
|
||||
await page.waitForFunction(expected => {
|
||||
const channels = getComputedStyle(document.querySelector(".xterm-selection > div")).backgroundColor.match(/[\d.]+/g).map(Number);
|
||||
return channels.length === 4 && channels.slice(0, 3).every((channel, index) => Math.abs(channel - expected[index]) <= 2) && Math.abs(channels[3] - expected[3]) < 0.005;
|
||||
}, expected);
|
||||
}
|
||||
await page.evaluate(() => document.documentElement.style.removeProperty("--rs-selection"));
|
||||
|
||||
// The panel surfaces are translucent, the xterm layers are transparent, and the ribbon controls fit at 620 pixels.
|
||||
const surfaces = () => page.evaluate(() => {
|
||||
const alpha = color => {
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = canvas.height = 1;
|
||||
const context = canvas.getContext("2d");
|
||||
context.fillStyle = color;
|
||||
context.fillRect(0, 0, 1, 1);
|
||||
return context.getImageData(0, 0, 1, 1).data[3] / 255;
|
||||
};
|
||||
return Object.fromEntries([".ribbon", ".term", ".xterm", ".xterm-viewport", ".rail", ".pane-label"].map(selector => {
|
||||
const element = document.querySelector(`.dock ${selector}`);
|
||||
if (!element) return [selector, null];
|
||||
const style = getComputedStyle(element);
|
||||
return [selector, { alpha: alpha(style.backgroundColor), opacity: style.opacity }];
|
||||
}));
|
||||
});
|
||||
for (const mode of ["light", "dark"]) {
|
||||
await appearance(page, mode);
|
||||
await settle(page);
|
||||
const colors = await surfaces();
|
||||
// The ribbon and the panes use the translucent surface tokens, so a background image shows through them.
|
||||
assert.ok(colors[".ribbon"].alpha > 0.5 && colors[".ribbon"].alpha < 1, `ribbon ${colors[".ribbon"].alpha}`);
|
||||
assert.ok(colors[".term"].alpha > 0.5 && colors[".term"].alpha < 1, `term ${colors[".term"].alpha}`);
|
||||
assert.equal(colors[".xterm"].alpha, 0);
|
||||
assert.equal(colors[".xterm-viewport"].alpha, 0);
|
||||
assert.equal(colors[".ribbon"].opacity, "1");
|
||||
assert.equal(await page.locator(".bottom").evaluate(element => getComputedStyle(element).backgroundColor), "rgba(0, 0, 0, 0)");
|
||||
for (const width of [620, 1440]) {
|
||||
await page.setViewportSize({ width, height: 800 });
|
||||
await page.locator(".xterm-helper-textarea").first().focus();
|
||||
await settle(page);
|
||||
await page.getByRole("button", { name: "Terminal profiles and tasks", exact: true }).focus();
|
||||
await page.getByRole("tooltip", { name: "Terminal profiles and tasks", exact: true }).waitFor();
|
||||
const ribbonBounds = await page.locator(".dock .ribbon").boundingBox();
|
||||
for (const button of await page.locator(".dock .ribbon button").all()) {
|
||||
const bounds = await button.boundingBox();
|
||||
assert.ok(bounds.x >= ribbonBounds.x && bounds.x + bounds.width <= ribbonBounds.x + ribbonBounds.width + 1);
|
||||
assert.ok(bounds.width >= 28 && bounds.height >= 28);
|
||||
}
|
||||
await page.screenshot({ path: shot(`terminal-translucent-${mode}-${width}.png`) });
|
||||
}
|
||||
}
|
||||
|
||||
// Splits, maximize, hide and show without a close, profiles, and kill.
|
||||
await page.setViewportSize({ width: 1440, height: 1000 });
|
||||
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: shot("terminal-splits.png") });
|
||||
await click("Restore panel");
|
||||
await page.keyboard.press("Control+j");
|
||||
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");
|
||||
const splitProfile = page.getByRole("menuitem", { name: "Split terminal with profile", exact: true });
|
||||
await splitProfile.focus();
|
||||
await page.keyboard.press("ArrowRight");
|
||||
const profileSubmenu = page.getByRole("menu", { name: "Split terminal with profile", exact: true });
|
||||
assert(await profileSubmenu.getByRole("menuitem", { name: "PowerShell", exact: true }).evaluate(node => document.activeElement === node));
|
||||
await page.keyboard.press("ArrowLeft");
|
||||
assert(await splitProfile.evaluate(node => document.activeElement === node));
|
||||
await page.keyboard.press("Escape");
|
||||
assert(await page.getByRole("button", { name: "Terminal profiles and tasks", exact: true }).evaluate(node => document.activeElement === node));
|
||||
await click("Terminal profiles and tasks");
|
||||
await page.screenshot({ path: shot("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 633 and 133 shell integration fills 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__.pty.output(id, data);
|
||||
});
|
||||
await click("More terminal actions");
|
||||
assert(await page.getByRole("menuitem", { name: "Run the active file", exact: true }).isDisabled());
|
||||
assert(await page.getByRole("menuitem", { name: "Run selected text", exact: true }).isDisabled());
|
||||
await page.screenshot({ path: shot("terminal-actions.png") });
|
||||
await menu("Run a recent command… Ctrl+Alt+R");
|
||||
await page.getByRole("dialog").getByRole("option", { 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("option", { name: "C:\\two words" }).click();
|
||||
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_write" && c.args.data.includes('cd /d "C:\\two words"')));
|
||||
|
||||
// Settings → Terminal opens Settings. The page does not load xterm, and its changes reach the open panel.
|
||||
await click("Terminal profiles and tasks");
|
||||
await menu("Terminal settings");
|
||||
await waitCount("settings_open_window", 1);
|
||||
const settings = await openPage(context);
|
||||
await settings.goto(`${smokeUrl}/?settingsWindow=true`);
|
||||
const dialog = settings.getByRole("dialog", { name: "Settings", exact: true });
|
||||
await dialog.getByRole("button", { name: "Terminal", exact: true }).click();
|
||||
await dialog.getByRole("heading", { name: "Terminal", exact: true }).waitFor();
|
||||
assert.equal(await xtermLoaded(settings), false, "Settings → Terminal does not load xterm");
|
||||
const fontSize = dialog.getByLabel("Font size", { exact: true });
|
||||
assert.equal(await fontSize.inputValue(), "13");
|
||||
await fontSize.fill("40");
|
||||
await fontSize.press("Enter");
|
||||
await fontSize.blur();
|
||||
await dialog.getByText("Choose a whole number from 9 to 28.", { exact: true }).waitFor();
|
||||
await fontSize.fill("16");
|
||||
await fontSize.blur();
|
||||
await settings.waitForFunction(() => window.__TEST__.settings("terminal")?.fontSize === 16);
|
||||
await page.waitForFunction(() => getComputedStyle(document.querySelector(".pane.shown .xterm-rows > div > span")).fontSize === "16px");
|
||||
for (const mode of ["light", "dark"]) {
|
||||
await appearance(settings, mode);
|
||||
for (const width of [1152, 360]) {
|
||||
await settings.setViewportSize({ width, height: width === 360 ? 640 : 815 });
|
||||
await settle(settings);
|
||||
assert(await settings.evaluate(() => document.documentElement.scrollWidth <= innerWidth), `No horizontal scroll at ${width} pixels`);
|
||||
await settings.screenshot({ path: shot(`settings-terminal-${mode}-${width}.png`) });
|
||||
}
|
||||
await dialog.getByRole("button", { name: "Default profile", exact: true }).click();
|
||||
const profileMenu = settings.getByRole("menu", { name: "Default terminal profile", exact: true });
|
||||
const current = profileMenu.getByRole("menuitemradio", { name: "PowerShell", exact: true });
|
||||
assert.equal(await current.getAttribute("aria-checked"), "true");
|
||||
assert.equal(await profileMenu.getByRole("menuitemradio", { name: "JavaScript Debug Terminal", exact: true }).count(), 0, "The debug terminal is not a default");
|
||||
const bounds = await profileMenu.boundingBox();
|
||||
assert(bounds.x >= 0 && bounds.x + bounds.width <= 360 && bounds.y >= 0 && bounds.y + bounds.height <= 640);
|
||||
await settings.screenshot({ path: shot(`settings-terminal-profile-${mode}-360.png`) });
|
||||
await settings.keyboard.press("End");
|
||||
assert(await profileMenu.getByRole("menuitemradio", { name: "Git Bash", exact: true }).evaluate(node => document.activeElement === node));
|
||||
await settings.keyboard.press("Escape");
|
||||
assert(await dialog.getByRole("button", { name: "Default profile", exact: true }).evaluate(node => document.activeElement === node));
|
||||
}
|
||||
await settings.setViewportSize({ width: 1152, height: 815 });
|
||||
await dialog.getByRole("button", { name: "Default profile", exact: true }).click();
|
||||
await settings.getByRole("menuitemradio", { name: "Git Bash", exact: true }).click();
|
||||
await dialog.getByRole("switch", { name: "Blink cursor", exact: true }).uncheck();
|
||||
await settings.waitForFunction(() => window.__TEST__.settings("terminal")?.defaultProfile === "git-bash" && window.__TEST__.settings("terminal")?.cursorBlink === false);
|
||||
await page.bringToFront();
|
||||
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");
|
||||
|
||||
// Tasks from .runestone/tasks.json, with the shared picker rows at 360 pixels in both themes.
|
||||
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 a task…");
|
||||
for (const mode of ["light", "dark"]) {
|
||||
await appearance(page, mode);
|
||||
await page.setViewportSize({ width: 360, height: 640 });
|
||||
const row = page.getByRole("option", { name: "Smoke task echo task-ok" });
|
||||
const measurements = await row.evaluate(node => {
|
||||
const css = getComputedStyle(node);
|
||||
const root = getComputedStyle(document.documentElement);
|
||||
return { fontSize: css.fontSize, minHeight: css.minHeight, padding: css.padding, radius: css.borderRadius,
|
||||
tokenFont: root.getPropertyValue("--rs-menu-font-size").trim(), tokenHeight: root.getPropertyValue("--rs-menu-row-height").trim(),
|
||||
tokenRadius: root.getPropertyValue("--rs-control-radius").trim(), tokenPadding: root.getPropertyValue("--rs-menu-row-padding").trim() };
|
||||
});
|
||||
assert.equal(measurements.fontSize, measurements.tokenFont);
|
||||
assert.equal(measurements.minHeight, measurements.tokenHeight);
|
||||
assert.equal(measurements.radius, measurements.tokenRadius);
|
||||
assert.equal(measurements.padding, measurements.tokenPadding);
|
||||
await page.screenshot({ path: shot(`terminal-task-picker-${mode}-360.png`) });
|
||||
}
|
||||
await page.setViewportSize({ width: 1440, height: 1000 });
|
||||
const taskQuery = page.getByRole("combobox", { name: "Run a task", exact: true });
|
||||
await taskQuery.fill("no-such-task");
|
||||
await page.getByText("No entries match the filter.", { exact: true }).waitFor();
|
||||
assert.equal(await page.getByRole("option").count(), 0);
|
||||
await taskQuery.fill("Smoke task");
|
||||
const taskOption = page.getByRole("option", { name: "Smoke task echo task-ok" });
|
||||
assert.equal(await taskQuery.getAttribute("aria-activedescendant"), await taskOption.getAttribute("id"));
|
||||
await taskQuery.press("Enter");
|
||||
await waitCount("pty_open", 6);
|
||||
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_write" && c.args.data.includes("echo task-ok")));
|
||||
|
||||
// Run selected text and run the active file. The editor keeps its selection while the menu takes focus.
|
||||
// The shell owns its control keys, so the test opens the file from a new tab.
|
||||
await click("New tab (Ctrl+T)");
|
||||
await page.getByRole("button", { name: /^Find file/ }).click();
|
||||
await page.getByRole("textbox", { name: "Find a file" }).fill("hello.py");
|
||||
await page.getByRole("dialog").getByRole("button").filter({ hasText: "hello.py" }).first().click();
|
||||
const editor = page.locator(".cm-content").first();
|
||||
await editor.waitFor();
|
||||
const editorFont = await editor.evaluate(element => ({ family: getComputedStyle(element).fontFamily, weight: getComputedStyle(element).fontWeight }));
|
||||
assert.equal(editorFont.weight, terminalFont.weight, "The terminal uses the code font weight");
|
||||
assert.ok(editorFont.family.startsWith(terminalFont.family.split(",")[0]), "The terminal uses the code font");
|
||||
await editor.click();
|
||||
await page.keyboard.press("Control+a");
|
||||
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 the 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+Alt+Shift+`");
|
||||
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 the terminal");
|
||||
assert.equal(await count("pty_close"), 1);
|
||||
|
||||
// Kill down to one session and none, start again, the new and window shortcuts, then close and a fresh reopen.
|
||||
await page.setViewportSize({ width: 880, height: 600 });
|
||||
await page.screenshot({ path: shot("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 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);
|
||||
const opens = await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_open").map(c => c.args.id));
|
||||
await click("Close terminal (end all sessions)");
|
||||
await waitCount("pty_close", opens.length);
|
||||
const closedIds = await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_close").map(c => c.args.id));
|
||||
assert.deepEqual([...closedIds].sort(), [...opens].sort());
|
||||
await page.keyboard.press("Control+j");
|
||||
await waitCount("pty_open", opens.length + 1);
|
||||
const freshId = await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_open").at(-1).args.id);
|
||||
assert.equal(opens.includes(freshId), false);
|
||||
// The new shell takes the focus when it starts. Wait for that before the focus moves to the close button.
|
||||
await page.waitForFunction(id => window.__TEST__.calls.some(c => c.command === "pty_resize" && c.args.id === id), freshId);
|
||||
await appearance(page, "light");
|
||||
await settle(page);
|
||||
await page.getByRole("button", { name: "Close terminal (end all sessions)", exact: true }).focus();
|
||||
await page.getByRole("tooltip", { name: "Close terminal (end all sessions)", exact: true }).waitFor();
|
||||
await page.screenshot({ path: shot("terminal-close-light-narrow-focus.png") });
|
||||
await page.keyboard.press("Enter");
|
||||
await waitCount("pty_close", opens.length + 1);
|
||||
await page.keyboard.press("Control+Shift+Backquote");
|
||||
await waitCount("pty_open", opens.length + 2);
|
||||
assert.equal(await page.locator(".pane.shown").count(), 1);
|
||||
|
||||
// Off asks first while a shell runs. Cancel keeps the shells. OK ends them and removes the controls.
|
||||
await settings.bringToFront();
|
||||
await dialog.getByRole("button", { name: "Features", exact: true }).click();
|
||||
const terminalSwitch = dialog.getByRole("switch", { name: "Terminal", exact: true });
|
||||
await terminalSwitch.click();
|
||||
await settings.waitForFunction(() => window.__TEST__.state.prompts?.length === 1);
|
||||
await settings.waitForFunction(() => document.querySelector("#feature-terminal").checked);
|
||||
assert.deepEqual(await settings.evaluate(() => window.__TEST__.state.prompts), ["Terminal sessions will end.\nTurn off Terminal?"]);
|
||||
assert.equal(await terminalSwitch.isChecked(), true, "Cancel keeps Terminal on");
|
||||
assert.equal(await settings.evaluate(() => window.__TEST__.settings("features").terminal), true);
|
||||
const closesBefore = await count("pty_close");
|
||||
await settings.evaluate(() => { window.__TEST__.state.confirm = "Ok"; });
|
||||
await terminalSwitch.click();
|
||||
await page.waitForFunction(before => window.__TEST__.calls.filter(c => c.command === "pty_close").length > before, closesBefore);
|
||||
assert.equal(await settings.evaluate(() => window.__TEST__.settings("features").terminal), false);
|
||||
await page.getByRole("button", { name: "Terminal", exact: true }).waitFor({ state: "detached" });
|
||||
assert.equal(await dialog.getByRole("button", { name: "Terminal", exact: true }).count(), 0, "Settings → Terminal hides while Terminal is off");
|
||||
for (const mode of ["light", "dark"]) {
|
||||
await appearance(settings, mode);
|
||||
await settings.setViewportSize({ width: 360, height: 640 });
|
||||
await settle(settings);
|
||||
await settings.screenshot({ path: shot(`features-terminal-off-${mode}-360.png`) });
|
||||
}
|
||||
// Without prompts, an Off with no shell needs no question.
|
||||
await terminalSwitch.check();
|
||||
await page.getByRole("button", { name: "Terminal", exact: true }).first().waitFor();
|
||||
await settings.evaluate(() => { window.__TEST__.state.prompts = []; });
|
||||
await terminalSwitch.uncheck();
|
||||
await settings.waitForFunction(() => window.__TEST__.settings("features").terminal === false);
|
||||
assert.deepEqual(await settings.evaluate(() => window.__TEST__.state.prompts), []);
|
||||
await terminalSwitch.check();
|
||||
assert.deepEqual([...page.errors, ...settings.errors], []);
|
||||
await settings.close();
|
||||
|
||||
// The terminal window: one session, no workspace open, the exit code from the channel, and close.
|
||||
await page.goto(`${smokeUrl}/?terminalWindow=C%3A%5Csmoke-workspace`);
|
||||
await page.locator(".xterm").waitFor();
|
||||
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("button", { name: "Maximize panel", exact: true }).count(), 0);
|
||||
await page.screenshot({ path: shot("terminal-window.png") });
|
||||
await page.evaluate(() => window.__TEST__.pty.exit(window.__TEST__.calls.find(c => c.command === "pty_open").args.id, 3));
|
||||
await page.waitForFunction(() => document.querySelector(".xterm-rows")?.textContent.includes("[Process exited with code 3]"));
|
||||
await click("Close terminal window");
|
||||
await waitCount("plugin:window|destroy", 1);
|
||||
assert.equal(await count("pty_close"), 0, "The host removed the exited shell, so the close needs no host call");
|
||||
assert.deepEqual(page.errors, []);
|
||||
console.log("PASS: terminal lazy load, copy, ANSI tokens, selection, splits, profiles, history, Settings → Terminal, tasks, run file, Off prompt, close and reopen, and the terminal window.");
|
||||
}, { timeout: 30000 });
|
||||
@@ -1,10 +1,8 @@
|
||||
// Custom window controls: maximize, restore, minimize, the terminal close guard, the keyboard tooltip, and the header at 1400 and 880 px.
|
||||
// @requires plugin:terminal
|
||||
import assert from "node:assert/strict";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { mockTauri, outputDir, repoRoot, runSmoke, smokeUrl } from "../_harness/index.mjs";
|
||||
import { mockFeaturePlugins } from "../_harness/pluginMocks.mjs";
|
||||
|
||||
await runSmoke("layout/windowControls", async ({ page }) => {
|
||||
const output = await outputDir("layout/windowControls");
|
||||
@@ -20,8 +18,7 @@ await runSmoke("layout/windowControls", async ({ page }) => {
|
||||
"plugin:dialog|message": () => test.state.confirm,
|
||||
}),
|
||||
});
|
||||
// The Terminal button belongs to the terminal plug-in (src/lib/layout/Workbench.svelte:1305).
|
||||
await mockFeaturePlugins(page);
|
||||
// The Terminal button belongs to the Terminal feature, which is on by default (src/lib/features/catalog.ts).
|
||||
const called = command => page.evaluate(command => window.__TEST__.calls.some(call => call.command === command), command);
|
||||
|
||||
const config = JSON.parse(await readFile(path.join(repoRoot, "src-tauri/tauri.conf.json"), "utf8"));
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
// Core workbench: source edits and history, agent refresh and conflicts, persistent terminals, Reading and Mermaid previews, the live Writer, tables and their menus, and narrow layouts.
|
||||
// @requires plugin:terminal
|
||||
import assert from "node:assert/strict";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { chooseView, mockTauri, outputDir, repoRoot, runSmoke, smokeUrl } from "../_harness/index.mjs";
|
||||
import { mockFeaturePlugins } from "../_harness/pluginMocks.mjs";
|
||||
|
||||
await runSmoke("layout/workbench", async ({ page }) => {
|
||||
const output = await outputDir("layout/workbench");
|
||||
@@ -21,33 +19,18 @@ await runSmoke("layout/workbench", async ({ page }) => {
|
||||
},
|
||||
});
|
||||
Object.assign(test, { files: workspace.files, root: workspace.root });
|
||||
// The terminal plug-in opens shells through these commands.
|
||||
const pty = {};
|
||||
for (const command of ["pty_write", "pty_resize", "pty_close"]) pty[command] = () => {};
|
||||
// The Terminal feature opens its shells through the default `pty_*` handlers of the harness.
|
||||
return {
|
||||
...workspace,
|
||||
...pty,
|
||||
workspace_write: args => {
|
||||
if (args.expected !== undefined && workspace.files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
return workspace.workspace_write(args);
|
||||
},
|
||||
workspace_search: () => [],
|
||||
pty_profiles: () => [{ id: "powershell", title: "PowerShell", kind: "powershell" }],
|
||||
pty_open: async args => {
|
||||
const data = new TextEncoder().encode("READY 🪨\r\n\x1b[6n");
|
||||
// A Terminal plugin that uses api.pty passes a channel and gets raw bytes. Released versions listen for events.
|
||||
if (args.channel) setTimeout(() => { args.channel.onmessage(data.slice(0, 8).buffer); args.channel.onmessage(data.slice(8).buffer); }, 0);
|
||||
else {
|
||||
test.emit("pty-data", { id: args.id, data: [...data.slice(0, 8)] });
|
||||
test.emit("pty-data", { id: args.id, data: [...data.slice(8)] });
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
},
|
||||
"plugin:dialog|message": () => "Cancel",
|
||||
};
|
||||
},
|
||||
});
|
||||
await mockFeaturePlugins(page);
|
||||
|
||||
async function quickOpen(name) {
|
||||
await page.keyboard.press("Control+p");
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
// Feature lifecycle: the built-in Table formulas setting and the Terminal plug-in turn off, persist, reopen across windows, and uninstall without restoration.
|
||||
// An old Table Formulas package stays inactive and shows that the feature is built in.
|
||||
// @requires plugin:terminal
|
||||
// Feature lifecycle: the built-in Table formulas setting and the native Terminal feature turn off, persist, and turn on again across windows.
|
||||
// Terminal off asks first while a shell runs, and then ends the shells of each window.
|
||||
// An old Table Formulas package stays inactive, shows that the feature is built in, and uninstalls without restoration.
|
||||
import assert from 'node:assert/strict';
|
||||
import path from 'node:path';
|
||||
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
|
||||
import { mockFeaturePlugins, oldTableFormulasRow } from '../_harness/pluginMocks.mjs';
|
||||
import { mockInstalledPlugins, oldTableFormulasRow } from '../_harness/pluginMocks.mjs';
|
||||
|
||||
await runSmoke('plugins/lifecycle', async ({ browser }) => {
|
||||
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
|
||||
@@ -32,24 +32,12 @@ await runSmoke('plugins/lifecycle', async ({ browser }) => {
|
||||
test.emit('workspace-event', { root: ws.root, kind: 'modify', paths: [rel] });
|
||||
},
|
||||
settings_open_window: () => null,
|
||||
pty_profiles: () => [{ id: 'powershell', title: 'PowerShell', kind: 'powershell' }],
|
||||
pty_open: async ({ id, channel }) => {
|
||||
const data = new TextEncoder().encode('READY 🪨\r\n\x1b[6n');
|
||||
// A Terminal plugin that uses api.pty passes a channel and gets raw bytes. Released versions listen for events.
|
||||
if (channel) setTimeout(() => { channel.onmessage(data.slice(0, 8).buffer); channel.onmessage(data.slice(8).buffer); }, 0);
|
||||
else {
|
||||
test.emit('pty-data', { id, data: [...data.slice(0, 8)] });
|
||||
test.emit('pty-data', { id, data: [...data.slice(8)] });
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
},
|
||||
pty_write: () => null,
|
||||
pty_resize: () => null,
|
||||
pty_close: () => null,
|
||||
// Terminal off asks first while a shell runs (src/lib/layout/SettingsDialog.svelte).
|
||||
'plugin:dialog|message': args => { test.state.prompts = [...test.state.prompts ?? [], args.message]; return 'Ok'; },
|
||||
};
|
||||
},
|
||||
});
|
||||
await mockFeaturePlugins(context, [oldTableFormulasRow]);
|
||||
await mockInstalledPlugins(context, [oldTableFormulasRow]);
|
||||
const output = await outputDir('plugins/lifecycle');
|
||||
const source = '# Formulas\n\n| A | B |\n| --- | --- |\n| 2 | =A2*3 |\n\nAfter.\n';
|
||||
const table = page.locator('.live-writer table');
|
||||
@@ -122,29 +110,38 @@ await runSmoke('plugins/lifecycle', async ({ browser }) => {
|
||||
await oldPackage.getByText('Included with RuneStone', { exact: true }).waitFor();
|
||||
await oldPackage.getByText(/Table Formulas is now built in\. You can remove this old package\./).waitFor();
|
||||
assert(await oldPackage.getByRole('switch').isDisabled(), 'The old package cannot be enabled');
|
||||
assert.equal(await switchFor('Terminal').count(), 0, 'Terminal is a feature, not a plugin');
|
||||
await dialog.getByRole('button', { name: 'Features', exact: true }).click();
|
||||
await switchFor('Terminal').uncheck();
|
||||
await page.waitForFunction(ptyCalled, 'pty_close');
|
||||
await settingsPage.screenshot({ path: path.join(output, 'plugins-settings.png') });
|
||||
const prompts = await settingsPage.evaluate(() => window.__TEST__.state.prompts);
|
||||
assert.deepEqual(prompts, ['Terminal sessions will end.\nTurn off Terminal?'], 'Terminal off asks first while a shell runs');
|
||||
assert.equal(await settingsPage.evaluate(() => window.__TEST__.settings('features').terminal), false);
|
||||
await settingsPage.screenshot({ path: path.join(output, 'features-terminal-off.png') });
|
||||
await closeSettings();
|
||||
assert.equal(await page.getByRole('button', { name: 'Terminal', exact: true }).count(), 0);
|
||||
const opened = await count('pty_open');
|
||||
await page.keyboard.press('Control+j');
|
||||
await page.keyboard.press('Control+Shift+Backquote');
|
||||
assert.equal(await count('pty_open'), opened);
|
||||
await page.reload();
|
||||
await page.getByText('smoke-workspace', { exact: true }).waitFor();
|
||||
assert.equal(await page.getByRole('button', { name: 'Terminal', exact: true }).count(), 0);
|
||||
await settings();
|
||||
await settings('Features');
|
||||
assert(!await switchFor('Terminal').isChecked());
|
||||
assert.equal(await dialog.getByRole('button', { name: 'Terminal', exact: true }).count(), 0, 'Settings → Terminal shows only while Terminal is on');
|
||||
|
||||
const standalone = await openPage(context);
|
||||
await standalone.goto(smokeUrl + '?terminalWindow=C%3A%5Csmoke-workspace');
|
||||
await standalone.getByText(/Install and enable the Terminal plugin/).waitFor();
|
||||
await standalone.getByText('Terminal is off. Turn it on in Settings → Features.', { exact: true }).waitFor();
|
||||
await switchFor('Terminal').check();
|
||||
await standalone.locator('.xterm').waitFor();
|
||||
await standalone.waitForFunction(ptyCalled, 'pty_open');
|
||||
await dialog.getByRole('button', { name: 'Terminal', exact: true }).waitFor();
|
||||
await switchFor('Terminal').uncheck();
|
||||
await standalone.getByText(/Install and enable the Terminal plugin/).waitFor();
|
||||
await standalone.getByText('Terminal is off. Turn it on in Settings → Features.', { exact: true }).waitFor();
|
||||
await standalone.waitForFunction(ptyCalled, 'pty_close');
|
||||
assert.equal((await settingsPage.evaluate(() => window.__TEST__.state.prompts)).length, 1, 'The shell of the terminal window gives a prompt too');
|
||||
page.errors.push(...standalone.errors);
|
||||
await standalone.close();
|
||||
await switchFor('Terminal').check();
|
||||
@@ -156,17 +153,14 @@ await runSmoke('plugins/lifecycle', async ({ browser }) => {
|
||||
await quickOpen('formulas.md');
|
||||
await settings();
|
||||
assert.equal(await dialog.getByRole('heading', { name: 'Bundled plugins' }).count(), 0);
|
||||
for (const name of ['Terminal', 'Table Formulas']) {
|
||||
await idle();
|
||||
await dialog.locator('.card').filter({ has: settingsPage.getByRole('switch', { name, exact: true }) }).getByRole('button', { name: 'Uninstall', exact: true }).click();
|
||||
const confirmation = settingsPage.getByRole('dialog', { name: `Uninstall ${name}?`, exact: true });
|
||||
await confirmation.getByRole('button', { name: 'Uninstall and delete files', exact: true }).click();
|
||||
await confirmation.waitFor({ state: 'hidden' });
|
||||
await switchFor(name).waitFor({ state: 'detached' });
|
||||
}
|
||||
await idle();
|
||||
await dialog.locator('.card').filter({ has: settingsPage.getByRole('switch', { name: 'Table Formulas', exact: true }) }).getByRole('button', { name: 'Uninstall', exact: true }).click();
|
||||
const confirmation = settingsPage.getByRole('dialog', { name: 'Uninstall Table Formulas?', exact: true });
|
||||
await confirmation.getByRole('button', { name: 'Uninstall and delete files', exact: true }).click();
|
||||
await confirmation.waitFor({ state: 'hidden' });
|
||||
await switchFor('Table Formulas').waitFor({ state: 'detached' });
|
||||
await closeSettings();
|
||||
await page.waitForFunction(() => !document.querySelector('.xterm'));
|
||||
assert.equal(await page.getByRole('button', { name: 'Terminal', exact: true }).count(), 0);
|
||||
assert.equal(await page.locator('.xterm').count(), 1, 'The package removal does not touch the Terminal feature');
|
||||
assert.equal(await table.locator('.md-table-formula').innerText(), '8', 'Removing the old package keeps the built-in formulas');
|
||||
await page.reload();
|
||||
await page.getByText('smoke-workspace', { exact: true }).waitFor();
|
||||
@@ -181,5 +175,5 @@ await runSmoke('plugins/lifecycle', async ({ browser }) => {
|
||||
console.log([...page.errors, ...settingsPage.errors]);
|
||||
throw error;
|
||||
}
|
||||
console.log('Plugin smoke passed: formula setting, source preservation, inactive old package, terminal shutdown, persistence, shortcuts, cross-window enable controls, removal, and no automatic restoration.');
|
||||
console.log('Plugin smoke passed: formula setting, source preservation, inactive old package, Terminal off with a prompt, persistence, shortcuts, the terminal window, removal, and no automatic restoration.');
|
||||
});
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
// Table keyboard navigation: arrows, caret positions, entry and exit in all directions, goal columns, line breaks, stable cell sizes, saving, and undo.
|
||||
// @requires plugin:terminal
|
||||
import assert from "node:assert/strict";
|
||||
import { mockTauri, runSmoke, settle, smokeUrl } from "../_harness/index.mjs";
|
||||
import { mockFeaturePlugins } from "../_harness/pluginMocks.mjs";
|
||||
|
||||
await runSmoke("tables/navigation", async ({ page }) => {
|
||||
await mockTauri(page, {
|
||||
@@ -12,7 +10,6 @@ await runSmoke("tables/navigation", async ({ page }) => {
|
||||
return workspace;
|
||||
},
|
||||
});
|
||||
await mockFeaturePlugins(page);
|
||||
// Add a file after the workspace opens, as an external change would.
|
||||
const addFile = (name, text) => page.evaluate(({ name, text }) => {
|
||||
window.__TEST__.files.set(name, text);
|
||||
|
||||
@@ -5,6 +5,7 @@ import { FEATURES, featureEntry, featureOfOwner } from "../../../src/lib/feature
|
||||
import { storedSwitches, switchesFrom } from "../../../src/lib/features/state.ts";
|
||||
import { legacySwitch, migrateFeatures, type LegacyPlugin } from "../../../src/lib/features/migration.ts";
|
||||
import type { BackgroundMigrationHost, BackgroundSettings } from "../../../src/lib/features/backgroundSettings.ts";
|
||||
import type { TerminalMigrationHost } from "../../../src/lib/features/terminalSettings.ts";
|
||||
import { featureErrors, featureRequested, loadFeature } from "../../../src/lib/features/loader.ts";
|
||||
import { FeatureSession } from "../../../src/lib/features/session.ts";
|
||||
import type { FeatureContext, FeatureInstance, FeatureModule } from "../../../src/lib/features/types.ts";
|
||||
@@ -29,12 +30,12 @@ test("each feature keeps the ID of its old plugin package as its owner ID", () =
|
||||
});
|
||||
|
||||
test("switches keep known booleans only, and missing keys take the default", () => {
|
||||
assert.deepEqual(storedSwitches({ git: false, terminal: true, other: "yes" }), { git: false });
|
||||
assert.deepEqual(storedSwitches({ git: false, terminal: "no", csv: true, other: "yes" }), { git: false });
|
||||
assert.deepEqual(storedSwitches(null), {});
|
||||
assert.deepEqual(storedSwitches(["git"]), {});
|
||||
assert.deepEqual(switchesFrom(undefined), { git: true, background: true });
|
||||
assert.deepEqual(switchesFrom({ git: false, background: false }), { git: false, background: false });
|
||||
assert.deepEqual(switchesFrom({ git: "false" }), { git: true, background: true });
|
||||
assert.deepEqual(switchesFrom(undefined), { git: true, background: true, terminal: true });
|
||||
assert.deepEqual(switchesFrom({ git: false, background: false, terminal: false }), { git: false, background: false, terminal: false });
|
||||
assert.deepEqual(switchesFrom({ git: "false" }), { git: true, background: true, terminal: true });
|
||||
});
|
||||
|
||||
test("an installed package gives its state, and without a package the default applies", () => {
|
||||
@@ -57,6 +58,11 @@ function presentBackground(): BackgroundMigrationHost {
|
||||
return { missing: () => false, hasImage: () => false, migrateFolder: async () => { throw new Error("not asked"); }, write: async () => { throw new Error("not asked"); } };
|
||||
}
|
||||
|
||||
/** A terminal host with a section already present. */
|
||||
function presentTerminal(): TerminalMigrationHost {
|
||||
return { missing: () => false, legacy: () => { throw new Error("not asked"); }, write: async () => { throw new Error("not asked"); } };
|
||||
}
|
||||
|
||||
test("the migration asks only for features without a switch, and keeps other keys", async () => {
|
||||
const writes: unknown[] = [];
|
||||
const asked: string[][] = [];
|
||||
@@ -65,10 +71,10 @@ test("the migration asks only for features without a switch, and keeps other key
|
||||
write: async (value: unknown) => { writes.push(value); },
|
||||
legacy: async (ids: string[]) => { asked.push(ids); return packages; },
|
||||
});
|
||||
assert.deepEqual(await migrateFeatures(host({ future: 1, background: false }, [{ id: "runestone.git", installed: true, enabled: false, settings: null }]), presentBackground()), ["git"]);
|
||||
assert.deepEqual(await migrateFeatures(host({ future: 1, background: false, terminal: true }, [{ id: "runestone.git", installed: true, enabled: false, settings: null }]), presentBackground(), presentTerminal()), ["git"]);
|
||||
assert.deepEqual(asked, [["runestone.git"]]);
|
||||
assert.deepEqual(writes, [{ future: 1, background: false, git: false }]);
|
||||
assert.deepEqual(await migrateFeatures(host({ git: true, background: true }, []), presentBackground()), []);
|
||||
assert.deepEqual(writes, [{ future: 1, background: false, terminal: true, git: false }]);
|
||||
assert.deepEqual(await migrateFeatures(host({ git: true, background: true, terminal: true }, []), presentBackground(), presentTerminal()), []);
|
||||
assert.equal(asked.length, 1, "A stored switch needs no package read.");
|
||||
assert.equal(writes.length, 1);
|
||||
});
|
||||
@@ -78,17 +84,17 @@ test("a missing background section asks for the slideshow package and makes the
|
||||
const switches: unknown[] = [];
|
||||
const sections: BackgroundSettings[] = [];
|
||||
const background: BackgroundMigrationHost = { missing: () => true, hasImage: () => true, migrateFolder: async () => true, write: async value => { sections.push(value); } };
|
||||
const host = { read: () => ({ git: true, background: false }), write: async (value: unknown) => { switches.push(value); }, legacy: async (ids: string[]) => { asked.push(ids); return []; } };
|
||||
assert.deepEqual(await migrateFeatures(host, background), []);
|
||||
const host = { read: () => ({ git: true, background: false, terminal: true }), write: async (value: unknown) => { switches.push(value); }, legacy: async (ids: string[]) => { asked.push(ids); return []; } };
|
||||
assert.deepEqual(await migrateFeatures(host, background, presentTerminal()), []);
|
||||
assert.deepEqual(asked, [["runestone.bg-slideshow"]]);
|
||||
assert.deepEqual(switches, [], "Stored switches stay.");
|
||||
assert.equal(sections.length, 1);
|
||||
assert.equal(sections[0].source, "image");
|
||||
// Both migrations together ask once for both packages.
|
||||
asked.length = 0;
|
||||
await migrateFeatures({ ...host, read: () => undefined }, background);
|
||||
assert.deepEqual(asked, [["runestone.git", "runestone.bg-slideshow"]]);
|
||||
assert.deepEqual(switches, [{ git: true, background: true }]);
|
||||
await migrateFeatures({ ...host, read: () => undefined }, background, presentTerminal());
|
||||
assert.deepEqual(asked, [["runestone.git", "runestone.bg-slideshow", "runestone.terminal"]]);
|
||||
assert.deepEqual(switches, [{ git: true, background: true, terminal: true }]);
|
||||
});
|
||||
|
||||
test("a failed package read writes nothing, so the next start tries again", async () => {
|
||||
@@ -97,7 +103,7 @@ test("a failed package read writes nothing, so the next start tries again", asyn
|
||||
console.error = () => {};
|
||||
try {
|
||||
const background: BackgroundMigrationHost = { missing: () => true, hasImage: () => true, migrateFolder: async () => true, write: async value => { writes.push(value); } };
|
||||
const result = await migrateFeatures({ read: () => undefined, write: async value => { writes.push(value); }, legacy: async () => { throw new Error("no host"); } }, background);
|
||||
const result = await migrateFeatures({ read: () => undefined, write: async value => { writes.push(value); }, legacy: async () => { throw new Error("no host"); } }, background, presentTerminal());
|
||||
assert.deepEqual(result, []);
|
||||
assert.deepEqual(writes, []);
|
||||
} finally { console.error = error; }
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
// The Terminal feature: the catalog entry, the shell commands and tasks, the shortcuts, the session lifecycle,
|
||||
// the theme map, the settings section, and the first-start migration of the plugin settings.
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { featureEntry, featureOfOwner } from "../../../src/lib/features/catalog.ts";
|
||||
import { migrateFeatures } from "../../../src/lib/features/migration.ts";
|
||||
import { TERMINAL_KEYS, TERMINAL_SHORTCUTS, terminalShortcut, type TerminalAction } from "../../../src/lib/features/terminalKeys.ts";
|
||||
import { DEFAULT_TERMINAL, migrateTerminal, normalizeTerminal, type TerminalMigrationHost, type TerminalSettings } from "../../../src/lib/features/terminalSettings.ts";
|
||||
import { directoryCommand, fileCommand, parseTasks, pickProfile, quoteShell, remember, type ShellProfile } from "../../../src/lib/features/terminal/model.ts";
|
||||
import { TerminalSessions, type PtyRequest, type PtyTransport } from "../../../src/lib/features/terminal/sessions.ts";
|
||||
import { SELECTION_ALPHA, TERMINAL_TOKENS, terminalColors } from "../../../src/lib/features/terminal/theme.ts";
|
||||
import { ANSI_COLORS } from "../../../src/lib/theme/roles.ts";
|
||||
import { SETTINGS_SECTIONS, LEGACY_KEYS } from "../../../src/lib/settings/store.ts";
|
||||
|
||||
test("Terminal keeps the ID of the Terminal plugin and follows its package", () => {
|
||||
const terminal = featureEntry("terminal");
|
||||
assert.equal(terminal.owner, "runestone.terminal");
|
||||
assert.equal(featureOfOwner("runestone.terminal")?.id, "terminal");
|
||||
assert.equal(terminal.defaultOn, true);
|
||||
assert.equal(terminal.followsPackage, true);
|
||||
assert.deepEqual(terminal.views, []);
|
||||
assert.deepEqual(terminal.commands, []);
|
||||
});
|
||||
|
||||
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.equal(directoryCommand("C:\\two words", "bash"), "cd -- 'C:/two words'");
|
||||
assert.throws(() => quoteShell("C:\\%PATH%", "cmd"), /PowerShell/);
|
||||
assert.throws(() => fileCommand("a\nwhoami.py", "powershell"), /line breaks/);
|
||||
});
|
||||
|
||||
test("run file selects a runner and refuses documents that do not run", () => {
|
||||
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.equal(fileCommand("D:\\tools\\app.exe", "powershell"), "& 'D:\\tools\\app.exe'");
|
||||
assert.equal(fileCommand("D:\\tools\\build.cmd", "cmd"), 'cmd /c "D:\\tools\\build.cmd"');
|
||||
assert.throws(() => fileCommand("notes.md", "powershell"), /cannot run this file type/);
|
||||
assert.throws(() => fileCommand("app.js", "node"), /Node\.js REPL/);
|
||||
});
|
||||
|
||||
test("the tasks file must be valid before the panel offers a task", () => {
|
||||
assert.deepEqual(parseTasks('{"tasks":[{"label":"Test","command":"npm test","profile":"pwsh"}]}'), [{ label: "Test", command: "npm test", profile: "pwsh" }]);
|
||||
for (const text of ["{}", "null", '{"tasks":[null]}', '{"tasks":[{"label":"x","command":" "}]}', '{"tasks":[{"label":"x","command":"echo hi","profile":4}]}']) assert.throws(() => parseTasks(text), text);
|
||||
});
|
||||
|
||||
test("history puts the newest value first, has no duplicates, and keeps 100 values", () => {
|
||||
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("a new terminal takes the default profile, then the first shell that is not Node.js", () => {
|
||||
const profiles: ShellProfile[] = [{ id: "node", title: "JavaScript Debug Terminal", kind: "node" }, { id: "powershell", title: "PowerShell", kind: "powershell" }, { id: "cmd", title: "Command Prompt", kind: "cmd" }];
|
||||
assert.equal(pickProfile(profiles, "cmd")?.id, "cmd");
|
||||
assert.equal(pickProfile(profiles, "")?.id, "powershell");
|
||||
assert.equal(pickProfile(profiles, "missing")?.id, "powershell");
|
||||
assert.equal(pickProfile([profiles[0]], "")?.id, "node");
|
||||
assert.equal(pickProfile([], ""), undefined);
|
||||
});
|
||||
|
||||
/** A key event for a written combination such as "Mod+Shift+`". Mod is Ctrl. */
|
||||
function press(combination: string) {
|
||||
const parts = combination.split("+");
|
||||
const key = parts.pop()!;
|
||||
const has = (name: string) => parts.includes(name);
|
||||
const code = key === "`" ? "Backquote" : /^\d$/.test(key) ? `Digit${key}` : key.length === 1 ? `Key${key.toUpperCase()}` : key;
|
||||
return { ctrlKey: has("Mod") || has("Ctrl"), metaKey: false, altKey: has("Alt"), shiftKey: has("Shift"), code, key: key.length === 1 ? key.toLowerCase() : key };
|
||||
}
|
||||
|
||||
test("physical key shortcuts tell new, split, window, and hide apart", () => {
|
||||
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);
|
||||
assert.equal(terminalShortcut({ ...key, ctrlKey: false, metaKey: true, shiftKey: false }), "toggle", "Cmd works as Ctrl on macOS.");
|
||||
assert.equal(terminalShortcut({ ...key, ctrlKey: false }), null);
|
||||
// Each combination that menus and Help show gives its own action.
|
||||
for (const [action, combination] of Object.entries(TERMINAL_KEYS)) assert.equal(terminalShortcut(press(combination)), action as TerminalAction, combination);
|
||||
assert.ok(TERMINAL_SHORTCUTS.every(row => row.label && row.keys && !/Ctrl/.test(row.keys)), "Help rows use Mod, so macOS shows Cmd.");
|
||||
});
|
||||
|
||||
/** A fake host. `hold()` makes the next open wait for `release()`. */
|
||||
function fakeTransport() {
|
||||
const calls: string[] = [];
|
||||
const outputs = new Map<string, { data: (bytes: Uint8Array) => void; exit: (code: number | null) => void }>();
|
||||
let holding: Promise<void> = Promise.resolve();
|
||||
let release: () => void = () => {};
|
||||
let failClose = false;
|
||||
const transport: PtyTransport = {
|
||||
open: async (request: PtyRequest, data, exit) => {
|
||||
calls.push(`open:${request.id}:${request.profile ?? ""}:${request.directory ?? ""}`);
|
||||
outputs.set(request.id, { data, exit });
|
||||
await holding;
|
||||
},
|
||||
write: async (id, data) => { calls.push(`write:${id}:${data}`); },
|
||||
resize: async (id, cols, rows) => { calls.push(`resize:${id}:${cols}x${rows}`); },
|
||||
close: async id => { calls.push(`close:${id}`); if (failClose) throw new Error("close failed"); },
|
||||
profiles: async () => [{ id: "pwsh", title: "PowerShell 7", kind: "powershell" }],
|
||||
openWindow: async () => { calls.push("window"); },
|
||||
dictation: async () => { calls.push("dictation"); },
|
||||
};
|
||||
return {
|
||||
transport, calls, outputs,
|
||||
hold() { holding = new Promise(resolve => { release = resolve; }); },
|
||||
release: () => release(),
|
||||
failClose(value: boolean) { failClose = value; },
|
||||
};
|
||||
}
|
||||
const text = (bytes: Uint8Array) => new TextDecoder().decode(bytes);
|
||||
const options = (output: string[] = [], exits: (number | null)[] = []) => ({ cwd: "C:\\work", cols: 80, rows: 24, onData: (data: Uint8Array) => output.push(text(data)), onExit: (code: number | null) => exits.push(code) });
|
||||
|
||||
test("sessions deliver their own output, write, resize, and close once", async () => {
|
||||
const host = fakeTransport();
|
||||
const sessions = new TerminalSessions(host.transport);
|
||||
assert.deepEqual(await sessions.profiles(), [{ id: "pwsh", title: "PowerShell 7", kind: "powershell" }]);
|
||||
const output: string[] = [];
|
||||
await sessions.open("a", { ...options(output), profile: "pwsh", directory: "C:\\work\\src" });
|
||||
await sessions.open("b", options());
|
||||
assert.deepEqual(host.calls.slice(0, 2), ["open:a:pwsh:C:\\work\\src", "open:b::"]);
|
||||
host.outputs.get("a")!.data(new TextEncoder().encode("ready"));
|
||||
await sessions.write("a", "dir\r");
|
||||
await sessions.resize("a", 100, 30);
|
||||
assert.deepEqual(output, ["ready"]);
|
||||
assert.deepEqual(host.calls.slice(-2), ["write:a:dir\r", "resize:a:100x30"]);
|
||||
await assert.rejects(sessions.open("a", options()), /already running/);
|
||||
await Promise.all([sessions.close("a"), sessions.close("a")]);
|
||||
assert.equal(host.calls.filter(call => call === "close:a").length, 1);
|
||||
await assert.rejects(sessions.write("a", "x"), /not running/);
|
||||
host.outputs.get("a")!.data(new TextEncoder().encode("late"));
|
||||
assert.deepEqual(output, ["ready"], "A closed pane gets no more output.");
|
||||
await assert.rejects(sessions.open("a", options()), /closed/);
|
||||
await assert.rejects(sessions.write("missing", "x"), /not running/);
|
||||
await sessions.openWindow();
|
||||
await sessions.dictation();
|
||||
assert.deepEqual(host.calls.slice(-2), ["window", "dictation"]);
|
||||
});
|
||||
|
||||
test("a close waits for the start of its shell, and a closed pane cannot start", async () => {
|
||||
const host = fakeTransport();
|
||||
const sessions = new TerminalSessions(host.transport);
|
||||
host.hold();
|
||||
const start = sessions.open("starting", options());
|
||||
const close = sessions.close("starting");
|
||||
assert.equal(sessions.close("starting"), close, "A second close returns the same promise.");
|
||||
await Promise.resolve();
|
||||
assert.deepEqual(host.calls, ["open:starting::"]);
|
||||
host.release();
|
||||
await Promise.all([start, close]);
|
||||
assert.deepEqual(host.calls, ["open:starting::", "close:starting"]);
|
||||
await sessions.close("not-started");
|
||||
await assert.rejects(sessions.open("not-started", options()), /closed/);
|
||||
assert.equal(host.calls.length, 2);
|
||||
});
|
||||
|
||||
test("an exited shell needs no close, and a failed close can be tried again", async () => {
|
||||
const host = fakeTransport();
|
||||
const sessions = new TerminalSessions(host.transport);
|
||||
const exits: (number | null)[] = [];
|
||||
await sessions.open("exits", options([], exits));
|
||||
host.outputs.get("exits")!.exit(3);
|
||||
host.outputs.get("exits")!.exit(4);
|
||||
assert.deepEqual(exits, [3], "The exit reaches the pane one time.");
|
||||
await assert.rejects(sessions.write("exits", "x"), /not running/);
|
||||
await sessions.close("exits");
|
||||
assert.equal(host.calls.includes("close:exits"), false);
|
||||
await sessions.open("writer", options());
|
||||
host.failClose(true);
|
||||
await assert.rejects(sessions.close("writer"), /close failed/);
|
||||
host.failClose(false);
|
||||
await sessions.close("writer");
|
||||
assert.equal(host.calls.filter(call => call === "close:writer").length, 2);
|
||||
});
|
||||
|
||||
test("closeAll stops every shell, also one that is starting, and later calls fail", async () => {
|
||||
const host = fakeTransport();
|
||||
const sessions = new TerminalSessions(host.transport);
|
||||
await sessions.open("one", options());
|
||||
host.hold();
|
||||
const late = sessions.open("late", options());
|
||||
const stopping = sessions.closeAll();
|
||||
assert.equal(sessions.signal.aborted, true);
|
||||
host.release();
|
||||
await late;
|
||||
await stopping;
|
||||
assert.deepEqual(host.calls.filter(call => call.startsWith("close:")).sort(), ["close:late", "close:one"]);
|
||||
await assert.rejects(sessions.open("again", options()), /This feature is off/);
|
||||
await assert.rejects(sessions.profiles(), /This feature is off/);
|
||||
await assert.rejects(sessions.openWindow(), /This feature is off/);
|
||||
});
|
||||
|
||||
test("the terminal colors come from the theme tokens, with the 16 ANSI colors from --rs-ansi-*", () => {
|
||||
const asked: [string, number][] = [];
|
||||
const theme = terminalColors((css, maxAlpha) => { asked.push([css, maxAlpha]); return css; });
|
||||
assert.equal(theme.background, "#00000000", "The panel surface shows through the terminal.");
|
||||
assert.equal(theme.foreground, "var(--rs-text)");
|
||||
assert.equal(theme.cursor, "var(--rs-accent)");
|
||||
assert.equal(theme.cursorAccent, "var(--rs-bg)");
|
||||
assert.equal(theme.selectionBackground, "var(--rs-selection)");
|
||||
assert.deepEqual(asked.find(([css]) => css === "var(--rs-selection)"), ["var(--rs-selection)", SELECTION_ALPHA]);
|
||||
assert.equal(SELECTION_ALPHA, 165);
|
||||
for (const color of ANSI_COLORS) {
|
||||
const bright = `bright${color[0].toUpperCase()}${color.slice(1)}` as keyof typeof theme;
|
||||
assert.equal(theme[color], `var(--rs-ansi-${color})`);
|
||||
assert.equal(theme[bright], `var(--rs-ansi-bright-${color})`);
|
||||
}
|
||||
assert.equal(TERMINAL_TOKENS.filter(item => item.token.startsWith("var(--rs-ansi-")).length, 16);
|
||||
assert.ok(asked.filter(([css]) => css !== "var(--rs-selection)").every(([, alpha]) => alpha === 255), "Only the selection has an alpha cap.");
|
||||
});
|
||||
|
||||
test("the terminal settings section has valid values and its own old key", () => {
|
||||
assert.ok((SETTINGS_SECTIONS as readonly string[]).includes("terminal"));
|
||||
assert.equal(LEGACY_KEYS.terminal, "runestone.terminal");
|
||||
assert.deepEqual(normalizeTerminal(undefined), DEFAULT_TERMINAL);
|
||||
assert.deepEqual(normalizeTerminal(["x"]), DEFAULT_TERMINAL);
|
||||
assert.deepEqual(normalizeTerminal({ defaultProfile: "cmd", fontSize: 40, scrollback: 5, cursorBlink: false, future: 1 }),
|
||||
{ defaultProfile: "cmd", fontSize: 28, scrollback: 100, cursorBlink: false });
|
||||
assert.deepEqual(normalizeTerminal({ defaultProfile: 3, fontSize: 2, scrollback: 250000, cursorBlink: "no" }),
|
||||
{ defaultProfile: "", fontSize: 9, scrollback: 100000, cursorBlink: true });
|
||||
assert.equal(normalizeTerminal({ fontSize: 14.6 }).fontSize, 15);
|
||||
assert.equal(normalizeTerminal({ fontSize: Number.NaN }).fontSize, 13);
|
||||
});
|
||||
|
||||
function terminalHost(missing: boolean, legacy: string | null | (() => never)): TerminalMigrationHost & { written: TerminalSettings[] } {
|
||||
const written: TerminalSettings[] = [];
|
||||
return { written, missing: () => missing, legacy: () => typeof legacy === "function" ? legacy() : legacy, write: async value => { written.push(value); } };
|
||||
}
|
||||
|
||||
test("the first start copies the plugin settings into the terminal section once", async () => {
|
||||
const plugin = JSON.stringify({ defaultProfile: "git-bash", fontSize: 16, scrollback: 2000, cursorBlink: false });
|
||||
const copy = terminalHost(true, plugin);
|
||||
assert.deepEqual(await migrateTerminal(copy), { defaultProfile: "git-bash", fontSize: 16, scrollback: 2000, cursorBlink: false });
|
||||
assert.deepEqual(copy.written, [{ defaultProfile: "git-bash", fontSize: 16, scrollback: 2000, cursorBlink: false }]);
|
||||
const present = terminalHost(false, plugin);
|
||||
assert.equal(await migrateTerminal(present), null);
|
||||
assert.deepEqual(present.written, [], "An existing section stays.");
|
||||
const none = terminalHost(true, null);
|
||||
assert.equal(await migrateTerminal(none), null);
|
||||
assert.deepEqual(none.written, [], "Without the old key, the defaults apply and nothing is written.");
|
||||
const damaged = terminalHost(true, "{not json");
|
||||
assert.deepEqual(await migrateTerminal(damaged), DEFAULT_TERMINAL);
|
||||
const blocked = terminalHost(true, () => { throw new Error("storage is blocked"); });
|
||||
assert.equal(await migrateTerminal(blocked), null);
|
||||
});
|
||||
|
||||
test("the feature migration copies the terminal settings also when the package report fails", async () => {
|
||||
const error = console.error;
|
||||
console.error = () => {};
|
||||
try {
|
||||
const terminal = terminalHost(true, JSON.stringify({ fontSize: 20 }));
|
||||
const background = { missing: () => false, hasImage: () => false, migrateFolder: async () => false, write: async () => {} };
|
||||
const host = { read: () => undefined, write: async () => { throw new Error("not asked"); }, legacy: async () => { throw new Error("no host"); } };
|
||||
assert.deepEqual(await migrateFeatures(host, background, terminal), []);
|
||||
assert.deepEqual(terminal.written, [{ ...DEFAULT_TERMINAL, fontSize: 20 }]);
|
||||
} finally { console.error = error; }
|
||||
});
|
||||
|
||||
test("the terminal switch follows the enabled state of an installed Terminal plugin", async () => {
|
||||
const writes: unknown[] = [];
|
||||
const host = { read: () => ({ git: true, background: true }), write: async (value: unknown) => { writes.push(value); },
|
||||
legacy: async (ids: string[]) => ids.map(id => ({ id, installed: true, enabled: false, settings: null })) };
|
||||
const background = { missing: () => false, hasImage: () => false, migrateFolder: async () => false, write: async () => {} };
|
||||
assert.deepEqual(await migrateFeatures(host, background, terminalHost(false, null)), ["terminal"]);
|
||||
assert.deepEqual(writes, [{ git: true, background: true, terminal: false }]);
|
||||
});
|
||||
@@ -3,7 +3,7 @@ import assert from "node:assert/strict";
|
||||
import { ExternalSession, type SessionServices } from "../../../src/lib/plugins/externalSession.ts";
|
||||
import { ContributionRegistry } from "../../../src/lib/plugins/registry.ts";
|
||||
import { ServiceHub } from "../../../src/lib/plugins/services.ts";
|
||||
import type { FilesTransport, PluginApi, PtyTransport } from "../../../src/lib/plugins/sdk.ts";
|
||||
import type { FilesTransport, PluginApi } from "../../../src/lib/plugins/sdk.ts";
|
||||
|
||||
const base: SessionServices = {
|
||||
workspace: { list: async () => [], read: async () => "", write: async () => {} },
|
||||
@@ -17,82 +17,6 @@ async function start(id: string, services: Partial<SessionServices>) {
|
||||
return { api, session };
|
||||
}
|
||||
|
||||
function fakePty() {
|
||||
const calls: unknown[][] = [];
|
||||
const outputs = new Map<string, { data: (bytes: Uint8Array) => void; exit: (code: number | null) => void }>();
|
||||
let release: (() => void) | undefined;
|
||||
const transport: PtyTransport & { hold(): void } = {
|
||||
hold() { let done!: () => void; const wait = new Promise<void>(resolve => { done = resolve; }); release = done; holding = wait; },
|
||||
open: async (request, data, exit) => { calls.push(["open", request]); outputs.set(request.id, { data, exit }); await holding; },
|
||||
write: async (id, data) => { calls.push(["write", id, data]); },
|
||||
resize: async (id, cols, rows) => { calls.push(["resize", id, cols, rows]); },
|
||||
close: async id => { calls.push(["close", id]); },
|
||||
profiles: async () => [{ id: "pwsh", title: "PowerShell 7", kind: "powershell" }],
|
||||
openWindow: async () => { calls.push(["window"]); },
|
||||
dictation: async () => { calls.push(["dictation"]); },
|
||||
};
|
||||
let holding: Promise<void> = Promise.resolve();
|
||||
return { transport, calls, outputs, release: () => release?.() };
|
||||
}
|
||||
|
||||
test("terminal sessions deliver their own output and close when the plugin stops", async () => {
|
||||
const pty = fakePty();
|
||||
const { api, session } = await start("org.test.terminal", { pty: pty.transport });
|
||||
assert.equal(api.pty!.version, 1);
|
||||
assert.deepEqual(await api.pty!.profiles(), [{ id: "pwsh", title: "PowerShell 7", kind: "powershell" }]);
|
||||
const received: string[] = [];
|
||||
const exits: (number | null)[] = [];
|
||||
const first = await api.pty!.open({ cwd: "C:/work", cols: 80, rows: 24, profile: "pwsh", onData: data => received.push(new TextDecoder().decode(data)), onExit: code => exits.push(code) });
|
||||
const second = await api.pty!.open({ cwd: "C:/work", cols: 80, rows: 24, onData: () => {} });
|
||||
assert.notEqual(first.id, second.id);
|
||||
assert.deepEqual(pty.calls[0], ["open", { id: first.id, cwd: "C:/work", cols: 80, rows: 24, profile: "pwsh" }]);
|
||||
pty.outputs.get(first.id)!.data(new TextEncoder().encode("ready"));
|
||||
await first.write("dir\r");
|
||||
await first.resize(100, 30);
|
||||
assert.deepEqual(received, ["ready"]);
|
||||
assert.deepEqual(pty.calls.slice(-2), [["write", first.id, "dir\r"], ["resize", first.id, 100, 30]]);
|
||||
assert.throws(() => first.resize(0, 30), /positive integers/);
|
||||
// An exited session needs no close at shutdown.
|
||||
pty.outputs.get(first.id)!.exit(0);
|
||||
assert.deepEqual(exits, [0]);
|
||||
await session.stop();
|
||||
assert.deepEqual(pty.calls.filter(call => call[0] === "close"), [["close", second.id]]);
|
||||
pty.outputs.get(second.id)!.data(new TextEncoder().encode("late"));
|
||||
assert.deepEqual(received, ["ready"]);
|
||||
assert.throws(() => api.pty!.open({ cwd: "C:/work", cols: 80, rows: 24, onData: () => {} }), /disabled/);
|
||||
assert.throws(() => api.pty!.openWindow(), /disabled/);
|
||||
assert.throws(() => second.write("x"), /disabled/);
|
||||
// Close stays safe after shutdown and is not repeated.
|
||||
await second.close();
|
||||
assert.equal(pty.calls.filter(call => call[0] === "close").length, 1);
|
||||
});
|
||||
|
||||
test("a terminal session that starts after shutdown is closed", async () => {
|
||||
const pty = fakePty();
|
||||
const { api, session } = await start("org.test.terminal", { pty: pty.transport });
|
||||
pty.transport.hold();
|
||||
const opening = api.pty!.open({ cwd: "C:/work", cols: 80, rows: 24, onData: () => {} });
|
||||
const stopping = session.stop();
|
||||
pty.release();
|
||||
await assert.rejects(opening, /disabled/);
|
||||
await stopping;
|
||||
const id = (pty.calls[0][1] as { id: string }).id;
|
||||
assert.deepEqual(pty.calls.filter(call => call[0] === "close"), [["close", id]]);
|
||||
});
|
||||
|
||||
test("a closed terminal session rejects input and closes once", async () => {
|
||||
const pty = fakePty();
|
||||
const { api } = await start("org.test.terminal", { pty: pty.transport });
|
||||
const output: string[] = [];
|
||||
const terminal = await api.pty!.open({ cwd: "C:/work", cols: 80, rows: 24, onData: data => output.push(String(data.length)) });
|
||||
await Promise.all([terminal.close(), terminal.close()]);
|
||||
assert.equal(pty.calls.filter(call => call[0] === "close").length, 1);
|
||||
assert.throws(() => terminal.write("x"), /closed/);
|
||||
pty.outputs.get(terminal.id)!.data(new Uint8Array([1]));
|
||||
assert.deepEqual(output, []);
|
||||
await assert.rejects(Promise.resolve().then(() => api.pty!.open({ cwd: "C:/work", cols: 80, rows: 24 } as never)), /onData/);
|
||||
});
|
||||
|
||||
test("folder grant calls check shutdown before and after the native request", async () => {
|
||||
const calls: unknown[][] = [];
|
||||
let finish: ((value: unknown) => void) | undefined;
|
||||
|
||||
@@ -5,9 +5,9 @@ import { ExternalSession } from "../../../src/lib/plugins/externalSession.ts";
|
||||
import type { PluginApi } from "../../../src/lib/plugins/sdk.ts";
|
||||
import type { Contributions } from "../../../src/lib/plugins/contracts.ts";
|
||||
|
||||
// A small test-only package. It contributes a feature, as the optional plugins do.
|
||||
const terminal: Contributions["terminal"] = { mount: () => ({ update() {}, command() {}, dispose() {} }), shortcut: () => null };
|
||||
const activate = (api: PluginApi) => { api.contribute("terminal", terminal); };
|
||||
// A small test-only package. It contributes the browser, as the built-in browser module does.
|
||||
const browser: Contributions["browser"] = { mountSettings: () => () => {}, mountBookmarks: () => () => {}, open: async () => false };
|
||||
const activate = (api: PluginApi) => { api.contribute("browser", browser); };
|
||||
|
||||
const services = {
|
||||
workspace: { list: async () => [], read: async () => "", write: async () => {} },
|
||||
@@ -37,23 +37,24 @@ test("optional workspace creation and reads stop when the plugin is disabled", a
|
||||
assert.equal(files.size, 1);
|
||||
});
|
||||
test("core starts without optional features and package contributions end with their session", async () => {
|
||||
assert.equal(pluginHost.get("terminal"), undefined);
|
||||
assert.equal(pluginHost.get("browser"), undefined);
|
||||
const registry = new ContributionRegistry();
|
||||
const session = new ExternalSession("org.test.feature", services, () => {}, () => {}, registry);
|
||||
await session.start({ activate });
|
||||
assert.equal(registry.get("terminal"), terminal);
|
||||
assert.equal(registry.get("browser"), browser);
|
||||
await session.stop();
|
||||
assert.equal(registry.get("terminal"), undefined);
|
||||
assert.equal(registry.get("browser"), undefined);
|
||||
const next = new ExternalSession("org.test.feature", services, () => {}, () => {}, registry);
|
||||
await next.start({ activate });
|
||||
assert.equal(registry.get("terminal"), terminal);
|
||||
assert.equal(registry.get("browser"), browser);
|
||||
await next.stop();
|
||||
assert.equal(registry.get("terminal"), undefined);
|
||||
assert.equal(registry.get("browser"), undefined);
|
||||
});
|
||||
|
||||
test("unknown contribution keys are rejected", () => {
|
||||
const registry = new ContributionRegistry();
|
||||
for (const key of ["tableFormulas", "git"]) assert.throws(() => registry.register("old", key as keyof Contributions, terminal as never), /Unknown plugin contribution/);
|
||||
// `terminal` was a contribution until the Terminal feature became native.
|
||||
for (const key of ["tableFormulas", "git", "terminal"]) assert.throws(() => registry.register("old", key as keyof Contributions, browser as never), /Unknown plugin contribution/);
|
||||
});
|
||||
|
||||
test("package contribution conflicts preserve the first owner and revoke access before cleanup", async () => {
|
||||
@@ -62,13 +63,13 @@ test("package contribution conflicts preserve the first owner and revoke access
|
||||
const second = new ExternalSession("second", services, () => {}, () => {}, registry);
|
||||
let api!: PluginApi;
|
||||
await first.start({ activate(value) { api = value; activate(api); } });
|
||||
const contribution = registry.get("terminal");
|
||||
const contribution = registry.get("browser");
|
||||
await assert.rejects(second.start({ activate }), /already registered/);
|
||||
await second.stop();
|
||||
assert.equal(registry.get("terminal"), contribution);
|
||||
assert.equal(registry.get("browser"), contribution);
|
||||
api.onDispose(() => {
|
||||
assert.equal(registry.get("terminal"), undefined);
|
||||
assert.throws(() => api.contribute("terminal", contribution!), /disabled/);
|
||||
assert.equal(registry.get("browser"), undefined);
|
||||
assert.throws(() => api.contribute("browser", contribution!), /disabled/);
|
||||
});
|
||||
await first.stop();
|
||||
});
|
||||
@@ -82,5 +83,5 @@ test("partial activation and failed cleanup cannot retain feature contributions"
|
||||
throw new Error("Activation failed");
|
||||
} }), /Activation failed/);
|
||||
await assert.rejects(session.stop(), /Cleanup failed/);
|
||||
assert.equal(registry.get("terminal"), undefined);
|
||||
assert.equal(registry.get("browser"), undefined);
|
||||
});
|
||||
|
||||
@@ -15,8 +15,7 @@ import type { ActionMenuItem as HostMenuItem } from "../../../src/lib/ui/actionM
|
||||
import type { MenuOptions as HostMenuOptions } from "../../../src/lib/ui/managedActionMenu.ts";
|
||||
import type { ActionMenuItem, ActionMenuOptions } from "../../../packages/plugin-sdk/src/index.ts";
|
||||
|
||||
// The host menu files must match the copies in the Terminal plugin (scripts/menuSurfaceAudit.mjs), so they keep
|
||||
// their own menu types. `pnpm check` fails when those types and the SDK types differ.
|
||||
// The host menu files keep their own menu types. `pnpm check` fails when those types and the SDK types differ.
|
||||
type Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;
|
||||
const sameMenuTypes: [Same<HostMenuItem, ActionMenuItem>, Same<HostMenuOptions, ActionMenuOptions>] = [true, true];
|
||||
|
||||
@@ -40,15 +39,17 @@ test("feature checks find optional members, and missing members give an update m
|
||||
assert.equal(hasFeature(api, "workspace.readBytes"), true);
|
||||
assert.equal(hasFeature(api, "services"), true);
|
||||
assert.equal(hasFeature(api, "workspace.subscribe"), false);
|
||||
assert.equal(hasFeature(api, "pty"), false);
|
||||
assert.deepEqual(missingFeatures(api, ["pty", "workspace.readBytes", "settings.subscribe"]), ["pty", "settings.subscribe"]);
|
||||
assert.equal(hasFeature(api, "files"), false);
|
||||
assert.deepEqual(missingFeatures(api, ["files", "workspace.readBytes", "settings.subscribe"]), ["files", "settings.subscribe"]);
|
||||
assert.equal(requireFeature(api, "services"), (api as unknown as { services: unknown }).services);
|
||||
assert.throws(() => requireFeature(api, "pty"), (error: unknown) => error instanceof MissingFeatureError
|
||||
&& error.name === "MissingFeatureError" && error.features.length === 1 && error.features[0] === "pty"
|
||||
&& error.message === "This plugin needs the terminal API (api.pty). Update RuneStone to a version that has this feature.");
|
||||
assert.throws(() => requireFeatures(api, ["pty", "files", "workspace.readBytes"]), {
|
||||
message: "This plugin needs the terminal API (api.pty) and the folder grant API (api.files). Update RuneStone to a version that has these features.",
|
||||
assert.throws(() => requireFeature(api, "files"), (error: unknown) => error instanceof MissingFeatureError
|
||||
&& error.name === "MissingFeatureError" && error.features.length === 1 && error.features[0] === "files"
|
||||
&& error.message === "This plugin needs the folder grant API (api.files). Update RuneStone to a version that has this feature.");
|
||||
assert.throws(() => requireFeatures(api, ["files", "backgrounds", "workspace.readBytes"]), {
|
||||
message: "This plugin needs the folder grant API (api.files) and the background API (api.backgrounds). Update RuneStone to a version that has these features.",
|
||||
});
|
||||
// The terminal API (api.pty) left the SDK when Terminal became a native feature.
|
||||
assert.throws(() => hasFeature(api, "pty" as never), TypeError);
|
||||
assert.doesNotThrow(() => requireFeatures(api, ["services", "workspace.readBytes"]));
|
||||
assert.throws(() => hasFeature(api, "workspace.read" as never), TypeError);
|
||||
assert.equal(describeFeature("ui.showActionMenu"), "the shared action menu (api.ui.showActionMenu)");
|
||||
@@ -63,10 +64,9 @@ test("a required function stays bound to its parent object", async () => {
|
||||
});
|
||||
|
||||
test("the current host gives every SDK feature when all services are present", async () => {
|
||||
const pty = { open: async () => {}, write: async () => {}, resize: async () => {}, close: async () => {}, profiles: async () => [], openWindow: async () => {}, dictation: async () => {} };
|
||||
const files = { chooseFolder: async () => null, pictureFolder: async () => ({ id: "g", path: "p", name: "n" }), grants: async () => [], revoke: async () => false, list: async () => [], readBytes: async () => new Uint8Array(), readSidecar: async () => null, writeSidecar: async () => {} };
|
||||
const { api, session } = await hostApi({
|
||||
pty, files, backgrounds: true, serviceHub: new ServiceHub(), openFile: async () => {}, completionTransport: async () => {},
|
||||
files, backgrounds: true, serviceHub: new ServiceHub(), openFile: async () => {}, completionTransport: async () => {},
|
||||
workspace: { ...base.workspace, listMarkdown: async () => [], readMany: async () => [], readBytes: async () => new Uint8Array(), readOptional: async () => null, create: async () => {}, subscribe: () => () => {} },
|
||||
settings: { ...base.settings, subscribe: () => () => {} },
|
||||
}, true);
|
||||
@@ -78,7 +78,7 @@ test("the host without optional services lacks only the features that depend on
|
||||
const { api, session } = await hostApi({});
|
||||
assert.deepEqual(missingFeatures(api, pluginFeatures).sort(), [
|
||||
"backgrounds", "closeView", "completion.transport", "files",
|
||||
"openFile", "pty", "renameDocument", "replaceDocumentWithView", "replaceView", "settings.subscribe",
|
||||
"openFile", "renameDocument", "replaceDocumentWithView", "replaceView", "settings.subscribe",
|
||||
"workspace.create", "workspace.listMarkdown", "workspace.readBytes", "workspace.readMany", "workspace.readOptional", "workspace.subscribe",
|
||||
]);
|
||||
await session.stop();
|
||||
|
||||
@@ -66,5 +66,6 @@ test('Migration keeps renamed theme IDs and a background image data URL', () =>
|
||||
|
||||
test('Every section has one old key', () => {
|
||||
// `runestone.features` and `runestone.background` came after the settings file. Only the browser preview uses them.
|
||||
assert.deepEqual(Object.values(LEGACY_KEYS).sort(), ['runestone.appearance', 'runestone.background', 'runestone.custom-themes', 'runestone.custom-themes.legacy', 'runestone.features', 'runestone.language', 'runestone.settings']);
|
||||
// `runestone.terminal` is the key of the Terminal plugin. The first start of the Terminal feature copies it into the file.
|
||||
assert.deepEqual(Object.values(LEGACY_KEYS).sort(), ['runestone.appearance', 'runestone.background', 'runestone.custom-themes', 'runestone.custom-themes.legacy', 'runestone.features', 'runestone.language', 'runestone.settings', 'runestone.terminal']);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user