M3.6: integrated terminal with PTY sessions and xterm.js sub-tabs

- crates/terminal: portable-pty sessions (ConPTY on Windows) with reader,
  writer and waiter threads, UTF-8 chunking, a 1 MiB output buffer with
  backpressure, a non-blocking input queue, resize, kill and exit codes;
  default shell pwsh -> powershell -> cmd on Windows, $SHELL or /bin/sh.
- Engine: terminal.create/input/resize/close, terminalOutput (capped per
  terminal and per pump, round-robin) and terminalExited through the pump;
  terminals close with the project and on app.quit.
- UI: Terminal tab in the bottom panel (tabs next to Find), xterm.js with
  the fit addon, sub-tabs, copy/paste, a focus rule that leaves plain Ctrl
  keys to the shell, terminal.open (Mod+Shift+T), --lt-terminal-* ANSI
  tokens in both themes (text colours AA) and a 4.5:1 minimum contrast.
- Tests: real-shell crate tests (UTF-8, backpressure), engine and TCP
  control tests, Vitest with a mocked xterm; live check on port 7936;
  docs and parity rows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-18 11:25:30 +02:00
parent 5fa7f0c8b3
commit a8daf269fb
45 changed files with 3935 additions and 49 deletions

View file

@ -0,0 +1,547 @@
/**
* Tests of the integrated terminal (M3.6): the Terminal store (create,
* output before the answer, history cap and replay, ordered input,
* resize, exit, close, project close, untrusted events), the key rules
* (which shortcuts reach Lutra from a terminal, copy and paste), the theme
* mapping, the tool window with its sub-tabs over a mocked xterm, the
* bottom panel's tabs and `terminal.open` through the main layout next to
* Find. The engine is a fake behind the mocked Tauri `invoke` and `listen`.
*/
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
import { createPinia, setActivePinia, type Pinia } from "pinia";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const invoke = vi.hoisted(() => vi.fn());
const listen = vi.hoisted(() => vi.fn());
vi.mock("@tauri-apps/api/core", () => ({ invoke }));
vi.mock("@tauri-apps/api/event", () => ({ listen }));
/** A fake xterm: records writes, theme and focus; tests type through `type`. */
interface FakeTerm {
writes: string[];
focused: number;
disposed: boolean;
theme: unknown;
selection: string;
type: (data: string) => void;
key: (event: KeyboardEvent) => boolean;
}
const terms = vi.hoisted(() => [] as FakeTerm[]);
vi.mock("../../src/components/terminal/xterm", async (importOriginal) => {
const real = await importOriginal<typeof import("../../src/components/terminal/xterm")>();
return {
...real,
createXterm: () => {
let onData: (data: string) => void = () => undefined;
let onKey: (event: KeyboardEvent) => boolean = () => true;
const fake: FakeTerm = {
writes: [],
focused: 0,
disposed: false,
theme: null,
selection: "",
type: (data) => {
onData(data);
},
key: (event) => onKey(event),
};
terms.push(fake);
const term = {
open: () => undefined,
write: (data: string) => void fake.writes.push(data),
focus: () => void (fake.focused += 1),
dispose: () => void (fake.disposed = true),
onData: (cb: (data: string) => void) => {
onData = cb;
return { dispose: () => undefined };
},
hasSelection: () => fake.selection !== "",
getSelection: () => fake.selection,
attachCustomKeyEventHandler: (cb: (event: KeyboardEvent) => boolean) => {
onKey = cb;
},
options: {
set theme(value: unknown) {
fake.theme = value;
},
},
cols: 80,
rows: 24,
};
return { term, fit: () => ({ cols: 120, rows: 30 }) };
},
};
});
import { useCommandsStore } from "../../src/commands/store";
import BottomPanel from "../../src/components/layout/BottomPanel.vue";
import MainLayout from "../../src/components/layout/MainLayout.vue";
import { clipboardAction, shortcutReachesLutra, TERMINAL_ATTRIBUTE } from "../../src/components/terminal/keys";
import TerminalToolWindow from "../../src/components/terminal/TerminalToolWindow.vue";
import { terminalTheme } from "../../src/components/terminal/xterm";
import { HISTORY_CAP, useTerminalStore } from "../../src/stores/terminal";
import { useNotificationsStore } from "../../src/stores/notifications";
import themes from "../theme/themes.json";
/** Every `engine_execute` call, in order. */
let calls: { command: string; params: Record<string, unknown> }[];
/** Engine event callbacks of every subscription. */
let listeners: ((event: { payload: unknown }) => void)[];
/** Next terminal id the fake returns. */
let nextId: number;
/** Events the fake emits before `terminal.create` answers. */
let beforeAnswer: unknown[];
/** Resolvers of `terminal.input` calls held back by a test. */
let heldInputs: (() => void)[];
/** Whether `terminal.input` calls are held back. */
let holdInput: boolean;
/** Error the next `terminal.create` fails with, if any. */
let createError: { code: string; message: string } | null;
let pinia: Pinia;
let mounted: VueWrapper[];
/**
* Sends an engine event to every subscription.
*
* @param payload - the event.
*/
async function emit(payload: unknown): Promise<void> {
for (const listener of [...listeners]) {
listener({ payload });
}
await flushPromises();
}
/** The params of every call of a command. */
function paramsOf(command: string): Record<string, unknown>[] {
return calls.filter((c) => c.command === command).map((c) => c.params);
}
/**
* A key event whose target is `target`.
*
* @param init - the key fields.
* @param target - the element it is dispatched on.
*/
function keyOn(init: KeyboardEventInit, target: Element): KeyboardEvent {
const event = new KeyboardEvent("keydown", { bubbles: true, ...init });
Object.defineProperty(event, "target", { value: target });
return event;
}
beforeEach(() => {
pinia = createPinia();
setActivePinia(pinia);
calls = [];
listeners = [];
nextId = 1;
beforeAnswer = [];
heldInputs = [];
holdInput = false;
createError = null;
mounted = [];
terms.length = 0;
vi.stubGlobal("requestAnimationFrame", (cb: () => void) => {
cb();
return 0;
});
invoke.mockReset();
listen.mockReset();
listen.mockImplementation((_name: string, callback: (event: { payload: unknown }) => void) => {
listeners.push(callback);
return Promise.resolve(() => {
listeners = listeners.filter((l) => l !== callback);
});
});
invoke.mockImplementation((cmd: string, args?: { command: string; params: Record<string, unknown> }) => {
if (cmd === "engine_list_commands") {
return Promise.resolve([
{ id: "terminal.create", label: "New Terminal", params: "", enabled: true, ui: false },
]);
}
if (cmd !== "engine_execute" || !args) {
return Promise.resolve(null);
}
calls.push({ command: args.command, params: args.params });
if (args.command === "terminal.create") {
if (createError) {
return Promise.reject(Object.assign(new Error(createError.code), createError));
}
const terminalId = nextId;
nextId += 1;
for (const event of beforeAnswer) {
for (const listener of [...listeners]) {
listener({ payload: event });
}
}
return Promise.resolve({ terminalId });
}
if (args.command === "terminal.input" && holdInput) {
return new Promise((resolve) => {
heldInputs.push(() => {
resolve(null);
});
});
}
if (args.command === "terminal.close") {
return Promise.resolve({ closed: true });
}
return Promise.resolve(null);
});
});
afterEach(() => {
for (const wrapper of mounted) {
wrapper.unmount();
}
useTerminalStore(pinia).stop();
useCommandsStore(pinia).stop();
vi.unstubAllGlobals();
});
describe("terminal store", () => {
it("creates a terminal and keeps output that arrives before the answer", async () => {
const store = useTerminalStore(pinia);
store.start();
await flushPromises();
beforeAnswer = [{ kind: "terminalOutput", terminalId: 1, data: "PS> " }];
const id = await store.create({ cols: 100, rows: 30 });
expect(id).toBe(1);
expect(paramsOf("terminal.create")).toEqual([{ cols: 100, rows: 30 }]);
expect(store.tabs).toEqual([{ id: 1, title: "Local", exited: false }]);
beforeAnswer = [];
await store.create();
expect(store.tabs.map((t) => t.title)).toEqual(["Local", "Local (2)"]);
expect(store.activeId).toBe(2);
const written: string[] = [];
const { replay } = store.attach(1, (data) => written.push(data));
expect(replay).toBe("PS> ");
await emit({ kind: "terminalOutput", terminalId: 1, data: "ls\r\n" });
await emit({ kind: "terminalOutput", terminalId: 2, data: "other" });
expect(written).toEqual(["ls\r\n"]);
});
it("caps the history from the front and ignores malformed events", async () => {
const store = useTerminalStore(pinia);
store.start();
await flushPromises();
await store.create();
const chunk = "x".repeat(HISTORY_CAP / 4);
for (let i = 0; i < 6; i += 1) {
await emit({ kind: "terminalOutput", terminalId: 1, data: `${String(i)}${chunk}` });
}
await emit({ kind: "terminalOutput", terminalId: "1", data: "bad" });
await emit({ kind: "terminalOutput", terminalId: 1, data: 7 });
await emit({ kind: "terminalExited", terminalId: null, code: 0 });
const { replay } = store.attach(1, () => undefined);
expect(replay.length).toBeLessThanOrEqual(HISTORY_CAP);
expect(replay.startsWith("3")).toBe(true);
expect(replay).not.toContain("bad");
expect(store.tabs[0]?.exited).toBe(false);
});
it("sends input in order, one call at a time", async () => {
const store = useTerminalStore(pinia);
await store.create();
holdInput = true;
store.input(1, "a");
store.input(1, "b");
store.input(1, "c");
await flushPromises();
expect(paramsOf("terminal.input")).toEqual([{ terminalId: 1, data: "a" }]);
heldInputs.shift()?.();
await flushPromises();
expect(paramsOf("terminal.input")).toEqual([
{ terminalId: 1, data: "a" },
{ terminalId: 1, data: "bc" },
]);
heldInputs.shift()?.();
await flushPromises();
store.input(99, "x");
expect(paramsOf("terminal.input")).toHaveLength(2);
});
it("skips repeated sizes and clamps them", async () => {
const store = useTerminalStore(pinia);
await store.create({ cols: 80, rows: 24 });
await store.resize(1, 80, 24);
await store.resize(1, 120.7, 30);
await store.resize(1, 120, 30);
await store.resize(1, 5000, 0);
expect(paramsOf("terminal.resize")).toEqual([
{ terminalId: 1, cols: 120, rows: 30 },
{ terminalId: 1, cols: 1000, rows: 1 },
]);
});
it("marks an ended terminal, then closes tabs and hides with the last one", async () => {
const store = useTerminalStore(pinia);
store.start();
await flushPromises();
await store.open();
await store.create();
expect(store.visible).toBe(true);
await emit({ kind: "terminalExited", terminalId: 1, code: 3 });
expect(store.tabs[0]?.exited).toBe(true);
expect(store.attach(1, () => undefined).replay).toContain("Process exited with code 3");
store.input(1, "x");
await store.close(1);
expect(paramsOf("terminal.close")).toEqual([]);
expect(store.activeId).toBe(2);
await store.close(2);
expect(paramsOf("terminal.close")).toEqual([{ terminalId: 2 }]);
expect(store.visible).toBe(false);
expect(paramsOf("terminal.input")).toEqual([]);
});
it("opens one terminal, reuses it, and makes another with new", async () => {
const store = useTerminalStore(pinia);
await store.open();
await store.open();
expect(store.tabs).toHaveLength(1);
await store.open({ new: true });
expect(store.tabs).toHaveLength(2);
store.activate(1);
expect(store.activeId).toBe(1);
});
it("shows a refused create in place and drops everything on project close", async () => {
const store = useTerminalStore(pinia);
store.start();
await flushPromises();
createError = { code: "failed", message: "no shell" };
await store.open();
expect(store.error).toBe("no shell");
createError = null;
await store.open();
expect(store.error).toBeNull();
await emit({ kind: "projectClosed" });
expect(store.tabs).toEqual([]);
expect(store.visible).toBe(false);
});
it("raises a toast when input is refused", async () => {
const store = useTerminalStore(pinia);
await store.create();
invoke.mockImplementationOnce(() => Promise.reject(Object.assign(new Error("failed"), { code: "failed", message: "not reading" })));
store.input(1, "x");
await flushPromises();
expect(useNotificationsStore(pinia).toasts.map((t) => t.level)).toEqual(["error"]);
});
});
describe("terminal keys", () => {
const inside = document.createElement("div");
inside.setAttribute(TERMINAL_ATTRIBUTE, "");
const textarea = document.createElement("textarea");
inside.appendChild(textarea);
const outside = document.createElement("textarea");
it("lets the shell have plain Ctrl shortcuts while a terminal has the focus", () => {
expect(shortcutReachesLutra(keyOn({ code: "KeyP", ctrlKey: true }, textarea), false)).toBe(false);
expect(shortcutReachesLutra(keyOn({ code: "KeyW", ctrlKey: true }, textarea), false)).toBe(false);
expect(shortcutReachesLutra(keyOn({ code: "KeyP", ctrlKey: true, shiftKey: true }, textarea), false)).toBe(true);
expect(shortcutReachesLutra(keyOn({ code: "KeyF", ctrlKey: true, altKey: true }, textarea), false)).toBe(true);
expect(shortcutReachesLutra(keyOn({ code: "KeyP", ctrlKey: true }, outside), false)).toBe(true);
expect(shortcutReachesLutra(keyOn({ code: "KeyP", metaKey: true }, textarea), true)).toBe(true);
expect(shortcutReachesLutra(keyOn({ code: "KeyR", ctrlKey: true }, textarea), true)).toBe(false);
});
it("copies and pastes with Lutra's keys", () => {
const key = (init: KeyboardEventInit): KeyboardEvent => new KeyboardEvent("keydown", init);
expect(clipboardAction(key({ code: "KeyC", ctrlKey: true }), false, false)).toBeNull();
expect(clipboardAction(key({ code: "KeyC", ctrlKey: true }), true, false)).toBe("copy");
expect(clipboardAction(key({ code: "KeyC", ctrlKey: true, shiftKey: true }), false, false)).toBe("copy");
expect(clipboardAction(key({ code: "KeyV", ctrlKey: true }), false, false)).toBe("paste");
expect(clipboardAction(key({ code: "KeyV", metaKey: true }), false, true)).toBe("paste");
expect(clipboardAction(key({ code: "KeyC", metaKey: true }), false, true)).toBe("copy");
expect(clipboardAction(key({ code: "KeyC", ctrlKey: true }), true, true)).toBeNull();
expect(clipboardAction(new KeyboardEvent("keyup", { code: "KeyV", ctrlKey: true }), false, false)).toBeNull();
});
it("maps every terminal token of both themes onto xterm's theme", () => {
for (const theme of themes) {
const tokens: Record<string, string> = theme.tokens;
const mapped = terminalTheme((name) => tokens[name] ?? "") as Record<string, unknown>;
expect(mapped.background).toBe(tokens["--lt-terminal-bg"]);
expect(mapped.brightMagenta).toBe(tokens["--lt-terminal-ansi-bright-magenta"]);
expect(Object.values(mapped).every((v) => typeof v === "string" && v.startsWith("#"))).toBe(true);
expect(Object.keys(mapped)).toHaveLength(21);
}
expect(terminalTheme(() => "").background).toBeUndefined();
});
});
describe("terminal tool window", () => {
/** Mounts the window with a started store. */
async function mountWindow(): Promise<VueWrapper> {
const store = useTerminalStore(pinia);
store.start();
const wrapper = mount(TerminalToolWindow, { attachTo: document.body, global: { plugins: [pinia] } });
mounted.push(wrapper);
await flushPromises();
return wrapper;
}
it("shows sub-tabs, replays output, types, resizes and closes", async () => {
const store = useTerminalStore(pinia);
const wrapper = await mountWindow();
beforeAnswer = [{ kind: "terminalOutput", terminalId: 1, data: "hello " }];
await store.open();
await flushPromises();
expect(terms).toHaveLength(1);
expect(terms[0]?.writes).toEqual(["hello "]);
expect(terms[0]?.focused).toBeGreaterThan(0);
expect(paramsOf("terminal.resize")).toEqual([{ terminalId: 1, cols: 120, rows: 30 }]);
await emit({ kind: "terminalOutput", terminalId: 1, data: "world" });
expect(terms[0]?.writes).toEqual(["hello ", "world"]);
terms[0]?.type("dir\r");
await flushPromises();
expect(paramsOf("terminal.input")).toEqual([{ terminalId: 1, data: "dir\r" }]);
expect(wrapper.find(`[${TERMINAL_ATTRIBUTE}]`).exists()).toBe(true);
await wrapper.get("[data-test=terminal-new]").trigger("click");
await flushPromises();
const tabs = wrapper.findAll("[data-test=terminal-tab]");
expect(tabs.map((t) => t.text())).toEqual(["Local", "Local (2)"]);
expect(tabs[1]?.attributes("aria-selected")).toBe("true");
await tabs[1]?.trigger("keydown", { key: "ArrowLeft" });
expect(store.activeId).toBe(1);
expect(terms).toHaveLength(2);
await emit({ kind: "terminalExited", terminalId: 2, code: 0 });
expect(wrapper.findAll("[data-test=terminal-tab]")[1]?.text()).toBe("Local (2) (ended)");
await wrapper.findAll("[data-test=terminal-tab-close]")[0]?.trigger("click");
await flushPromises();
expect(paramsOf("terminal.close")).toEqual([{ terminalId: 1 }]);
expect(terms[0]?.disposed).toBe(true);
expect(store.activeId).toBe(2);
});
it("copies the selection and leaves paste to the browser", async () => {
const writeText = vi.fn(() => Promise.resolve());
vi.stubGlobal("navigator", { userAgent: "Windows", platform: "Win32", clipboard: { writeText } });
await mountWindow();
await useTerminalStore(pinia).open();
await flushPromises();
const term = terms[0];
if (!term) throw new Error("no terminal");
term.selection = "copied";
expect(term.key(new KeyboardEvent("keydown", { code: "KeyC", ctrlKey: true }))).toBe(false);
expect(writeText).toHaveBeenCalledWith("copied");
expect(term.key(new KeyboardEvent("keydown", { code: "KeyV", ctrlKey: true }))).toBe(false);
term.selection = "";
expect(term.key(new KeyboardEvent("keydown", { code: "KeyC", ctrlKey: true }))).toBe(true);
});
it("follows theme changes", async () => {
await mountWindow();
await useTerminalStore(pinia).open();
await flushPromises();
const light = themes.find((t) => t.id === "lutra-light");
await emit({ kind: "themeChanged", id: "lutra-light", dark: false, tokens: light?.tokens });
expect((terms[0]?.theme as { background?: string }).background).toBe(light?.tokens["--lt-terminal-bg"]);
});
it("shows a refused terminal as an alert", async () => {
const wrapper = await mountWindow();
createError = { code: "failed", message: "no shell" };
await useTerminalStore(pinia).open();
await flushPromises();
expect(wrapper.get("[data-test=terminal-error]").text()).toContain("no shell");
});
});
describe("bottom panel tabs", () => {
it("shows tabs instead of the title and switches with clicks and arrows", async () => {
const chosen: string[] = [];
const wrapper = mount(BottomPanel, {
attachTo: document.body,
props: {
title: "Find",
tabs: [
{ id: "find", title: "Find" },
{ id: "terminal", title: "Terminal" },
],
active: "find",
"onUpdate:active": (id: string) => {
chosen.push(id);
void wrapper.setProps({ active: id });
},
},
});
mounted.push(wrapper);
expect(wrapper.find(".bottom-panel__title").exists()).toBe(false);
expect(wrapper.get("[data-test=bottom-tab-find]").attributes("aria-selected")).toBe("true");
await wrapper.get("[data-test=bottom-tab-terminal]").trigger("click");
await wrapper.get("[data-test=bottom-tab-terminal]").trigger("keydown", { key: "ArrowRight" });
await flushPromises();
expect(chosen).toEqual(["terminal", "find"]);
expect(document.activeElement).toBe(wrapper.get("[data-test=bottom-tab-find]").element);
});
});
describe("terminal.open", () => {
/** Mounts the main layout with the commands store started. */
async function mountLayout(): Promise<VueWrapper> {
const wrapper = mount(MainLayout, {
attachTo: document.body,
global: { plugins: [pinia], stubs: { ProjectToolWindow: true, StatusBar: true, StructureToolWindow: true } },
});
mounted.push(wrapper);
await useCommandsStore(pinia).start();
await flushPromises();
return wrapper;
}
it("is registered with its own shortcut", async () => {
await mountLayout();
const registered = paramsOf("ui.registerCommands")[0]?.commands as { id: string; defaultShortcut?: string }[];
expect(registered.find((c) => c.id === "terminal.open")?.defaultShortcut).toBe("Mod+Shift+T");
});
it("opens the Terminal tab next to Find, switches and closes tool windows one by one", async () => {
const wrapper = await mountLayout();
window.dispatchEvent(new KeyboardEvent("keydown", { key: "T", code: "KeyT", ctrlKey: true, shiftKey: true, bubbles: true }));
await flushPromises();
expect(wrapper.find("[data-test=terminal-window]").isVisible()).toBe(true);
expect(wrapper.find(".bottom-panel__title").text()).toBe("Terminal");
expect(paramsOf("terminal.create")).toHaveLength(1);
window.dispatchEvent(new KeyboardEvent("keydown", { key: "f", code: "KeyF", ctrlKey: true, altKey: true, bubbles: true }));
await flushPromises();
expect(wrapper.get("[data-test=bottom-tab-find]").attributes("aria-selected")).toBe("true");
expect(wrapper.find("[data-test=terminal-window]").isVisible()).toBe(false);
await wrapper.get("[data-test=bottom-tab-terminal]").trigger("click");
expect(wrapper.find("[data-test=terminal-window]").isVisible()).toBe(true);
await wrapper.get("[data-test=bottom-panel-close]").trigger("click");
expect(wrapper.find("[data-test=terminal-window]").exists()).toBe(false);
expect(wrapper.find(".bottom-panel__title").text()).toBe("Find");
await wrapper.get("[data-test=bottom-panel-close]").trigger("click");
expect(wrapper.find("[data-test=bottom-panel]").exists()).toBe(false);
expect(paramsOf("terminal.close")).toEqual([]);
});
it("leaves plain Ctrl shortcuts to the focused terminal", async () => {
const wrapper = await mountLayout();
await useCommandsStore(pinia).execute("terminal.open");
await flushPromises();
const view = wrapper.get(`[${TERMINAL_ATTRIBUTE}]`).element;
const event = new KeyboardEvent("keydown", { key: "1", code: "Digit1", ctrlKey: true, bubbles: true, cancelable: true });
view.dispatchEvent(event);
expect(event.defaultPrevented).toBe(false);
const palette = new KeyboardEvent("keydown", { key: "P", code: "KeyP", ctrlKey: true, shiftKey: true, bubbles: true, cancelable: true });
view.dispatchEvent(palette);
expect(palette.defaultPrevented).toBe(true);
});
it("opens from an agent's uiCommand", async () => {
const wrapper = await mountLayout();
await emit({ kind: "uiCommand", id: "terminal.open", params: { new: true } });
expect(wrapper.find("[data-test=terminal-window]").exists()).toBe(true);
expect(paramsOf("terminal.create")).toHaveLength(1);
});
});