Make Terminal a native feature

- Move the Terminal plugin into src/lib/features/terminal/ on the host Svelte runtime, with xterm 6.0.0 and addon-fit 0.11.0.
- Buttons, shortcuts, Help rows, and the close guard follow the Terminal switch. The first use loads the module.
- Add Settings → Terminal and the terminal settings section. The first start copies the old runestone.terminal key.
- The 16 ANSI colors come from the --rs-ansi-* tokens.
- Off asks first when a shell runs in any window (pty_running).
- Rust: no pty-data or pty-exit events, an owner check for write, resize, and close, output joined up to 64 KiB or 8 ms, and the sessions of a reloaded page close.
- Remove api.pty, the terminal contribution, TerminalSlot, and the plugin loader of the smoke harness.
- Check only the tested switches in the Background smoke test.
- Update the tests, the menu inventory, the docs, and UI-058.
This commit is contained in:
Knotty Wyvern
2026-10-29 19:02:58 -07:00
parent 53b9cea7f0
commit 833f793244
78 changed files with 2971 additions and 659 deletions
+19 -13
View File
@@ -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; }
+269
View File
@@ -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 }]);
});
+1 -77
View File
@@ -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;
+15 -14
View File
@@ -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);
});
+12 -12
View File
@@ -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();
+2 -1
View File
@@ -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']);
});