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:
@@ -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 }]);
|
||||
});
|
||||
Reference in New Issue
Block a user