/** * The Terminal tool window's state (M3.6): the open terminals (sub-tabs), * their output and the panel's visibility. * * - **Sessions:** `create` runs `terminal.create` (cwd = project root, the * engine's default shell) and adds a tab. Output arrives as * `terminalOutput` events; `terminalExited` marks the tab as ended and * writes a line saying so. Closing a tab runs `terminal.close` for a * running one. The engine closes every terminal with the project, so * `projectClosed` drops the tabs. * - **Output history:** every terminal's output is kept here, at most * {@link HISTORY_CAP} UTF-16 code units per terminal; older output is * dropped from the front (whole event chunks, so an escape sequence may be * cut). A view that mounts (switching tabs, expanding the panel) replays * it, then receives new output through `attach`. Output that arrives * before `terminal.create` answered is kept by id, since events and * command results travel on different channels. * - **Input:** keys go out in order, one `terminal.input` at a time; keys * typed while one is in flight are sent together afterwards. * - **Opening:** `open` (the UI command `terminal.open`) shows the panel, * creates a terminal if none is running (or always with `{new: true}`) * and asks the active view to take the focus. * - **Untrusted input:** event fields are checked; events of unknown shape * are ignored. */ import { defineStore } from "pinia"; import { computed, ref } from "vue"; import { t } from "../i18n"; import { onEngineEvent, run, type EngineEventPayload } from "../ipc"; import { useNotificationsStore } from "./notifications"; /** Most UTF-16 code units of output kept per terminal for replay. */ export const HISTORY_CAP = 512 * 1024; /** Size a terminal starts with before its view measured itself. */ export const DEFAULT_SIZE = { cols: 80, rows: 24 } as const; /** One terminal as the tab strip shows it. */ export interface TerminalTab { /** Engine terminal id. */ id: number; /** Tab label. */ title: string; /** Whether the shell ended. */ exited: boolean; } /** Receives new output of one terminal. */ export type TerminalWriter = (data: string) => void; /** Output kept for one terminal. */ interface History { /** Chunks, oldest first. */ chunks: string[]; /** Total length of `chunks`. */ length: number; } /** Input of one terminal waiting to be sent. */ interface Outbox { /** Text not sent yet. */ pending: string; /** Whether a `terminal.input` is in flight. */ busy: boolean; } /** * The text written into a terminal when its shell ended. * * @param code - the exit code, or null when Lutra closed it. * @returns the line, dimmed, on a line of its own. */ export function exitLine(code: number | null): string { const text = code === null ? t("terminal.exited.closed") : t("terminal.exited.code", { code }); return `\r\n\x1b[2m${text}\x1b[0m\r\n`; } /** The terminal store. */ export const useTerminalStore = defineStore("terminal", () => { const notifications = useNotificationsStore(); /** Whether the Terminal tab is in the bottom panel. */ const visible = ref(false); /** Whether the panel is expanded while the Terminal tab is active. */ const expanded = ref(true); /** Open terminals in tab order. */ const tabs = ref([]); /** The shown terminal, or null without tabs. */ const activeId = ref(null); /** Counts up whenever the active view should take the focus. */ const focusRequest = ref(0); /** The last failed `terminal.create`, shown in the window. */ const error = ref(null); /** Number of terminals created, for the tab labels. */ let created = 0; /** Output per terminal id; not reactive, views read it on mount. */ const history = new Map(); /** Views listening for output, per terminal id. */ const writers = new Map>(); /** Pending input per terminal id. */ const outboxes = new Map(); /** Last size sent per terminal id. */ const sizes = new Map(); /** Terminals that ended before their tab existed, with their exit code. */ const early = new Map(); /** Ends the event subscription; null while stopped. */ let unsubscribe: (() => void) | null = null; /** The active tab, if any. */ const active = computed(() => tabs.value.find((tab) => tab.id === activeId.value) ?? null); /** * Adds output to a terminal's history and hands it to its views. * * @param id - the terminal. * @param data - the text. */ function append(id: number, data: string): void { let kept = history.get(id); if (!kept) { kept = { chunks: [], length: 0 }; history.set(id, kept); } kept.chunks.push(data); kept.length += data.length; while (kept.length > HISTORY_CAP && kept.chunks.length > 1) { kept.length -= kept.chunks.shift()?.length ?? 0; } for (const writer of writers.get(id) ?? []) { writer(data); } } /** * Marks a terminal as ended and writes the exit line. * * @param id - the terminal. * @param code - its exit code, or null. */ function ended(id: number, code: number | null): void { const tab = tabs.value.find((candidate) => candidate.id === id); if (!tab) { early.set(id, code); return; } if (tab.exited) { return; } tab.exited = true; outboxes.delete(id); append(id, exitLine(code)); } /** * Handles engine events: terminal output and exits, and the project * closing. * * @param event - the event; its fields are untrusted. */ function onEvent(event: EngineEventPayload): void { if (event.kind === "terminalOutput") { if (typeof event.terminalId === "number" && typeof event.data === "string" && event.data !== "") { append(event.terminalId, event.data); } } else if (event.kind === "terminalExited") { if (typeof event.terminalId === "number") { ended(event.terminalId, typeof event.code === "number" ? event.code : null); } } else if (event.kind === "projectClosed") { reset(); } } /** Drops every tab and its output; the engine closed the terminals. */ function reset(): void { tabs.value = []; activeId.value = null; visible.value = false; error.value = null; history.clear(); outboxes.clear(); sizes.clear(); early.clear(); } /** * Starts a terminal and shows its tab. * * @param size - the size to start with. * @returns the new terminal's id, or null if the engine refused. */ async function create(size: { cols: number; rows: number } = DEFAULT_SIZE): Promise { const result = await run<{ terminalId?: unknown }>("terminal.create", { cols: size.cols, rows: size.rows }); if (!result.ok) { error.value = result.error.message; return null; } const id = result.value.terminalId; if (typeof id !== "number") { error.value = t("terminal.error.badAnswer"); return null; } error.value = null; created += 1; const title = created === 1 ? t("terminal.tab.first") : t("terminal.tab.numbered", { n: created }); tabs.value.push({ id, title, exited: false }); activeId.value = id; sizes.set(id, `${String(size.cols)}x${String(size.rows)}`); if (early.has(id)) { const code = early.get(id) ?? null; early.delete(id); ended(id, code); } focusRequest.value += 1; return id; } /** * Shows the Terminal tab: the UI command `terminal.open`. Creates a * terminal when none is running, or always with `{new: true}`. * * @param params - the command params; untrusted. */ async function open(params: unknown = {}): Promise { const p = typeof params === "object" && params !== null && !Array.isArray(params) ? (params as Record) : {}; visible.value = true; expanded.value = true; focusRequest.value += 1; const running = tabs.value.filter((tab) => !tab.exited); if (p.new === true || running.length === 0) { await create(); } else if (active.value?.exited !== false) { activeId.value = running[running.length - 1]?.id ?? null; } } /** * Shows a terminal's tab. * * @param id - the terminal. */ function activate(id: number): void { if (tabs.value.some((tab) => tab.id === id)) { activeId.value = id; focusRequest.value += 1; } } /** * Closes a tab, killing its shell if it still runs. Closing the last tab * hides the Terminal tab. * * @param id - the terminal. */ async function close(id: number): Promise { const index = tabs.value.findIndex((tab) => tab.id === id); const tab = tabs.value[index]; if (!tab) { return; } tabs.value.splice(index, 1); history.delete(id); outboxes.delete(id); sizes.delete(id); if (activeId.value === id) { activeId.value = (tabs.value[index] ?? tabs.value[index - 1])?.id ?? null; } if (tabs.value.length === 0) { visible.value = false; } if (!tab.exited) { const result = await run("terminal.close", { terminalId: id }); if (!result.ok) { notifications.notifyError("terminal.close", result.error); } } } /** * Sends keys or pasted text to a terminal, in order. * * @param id - the terminal. * @param data - the text from xterm.js. */ function input(id: number, data: string): void { const tab = tabs.value.find((candidate) => candidate.id === id); if (!tab || tab.exited || data === "") { return; } let box = outboxes.get(id); if (!box) { box = { pending: "", busy: false }; outboxes.set(id, box); } box.pending += data; void flush(id, box); } /** * Sends a terminal's pending input unless a send is in flight, and keeps * sending until nothing is pending. A refused input raises an error toast * unless the terminal ended meanwhile. * * @param id - the terminal. * @param box - its outbox. */ async function flush(id: number, box: Outbox): Promise { if (box.busy) { return; } box.busy = true; while (box.pending !== "" && outboxes.get(id) === box) { const data = box.pending; box.pending = ""; const result = await run("terminal.input", { terminalId: id, data }); if (!result.ok && outboxes.get(id) === box) { notifications.notifyError("terminal.input", result.error); } } box.busy = false; } /** * Tells the engine a terminal's new size; repeated sizes are skipped. * * @param id - the terminal. * @param cols - columns, at least 1. * @param rows - rows, at least 1. */ async function resize(id: number, cols: number, rows: number): Promise { const tab = tabs.value.find((candidate) => candidate.id === id); const c = Math.max(1, Math.min(1000, Math.floor(cols))); const r = Math.max(1, Math.min(1000, Math.floor(rows))); const key = `${String(c)}x${String(r)}`; if (!tab || tab.exited || sizes.get(id) === key || !Number.isFinite(cols) || !Number.isFinite(rows)) { return; } sizes.set(id, key); const result = await run("terminal.resize", { terminalId: id, cols: c, rows: r }); if (!result.ok) { sizes.delete(id); } } /** * Connects a view to a terminal's output. * * @param id - the terminal. * @param writer - receives new output. * @returns the output so far, for the view to replay, and a function * that disconnects the view. */ function attach(id: number, writer: TerminalWriter): { replay: string; detach: () => void } { let set = writers.get(id); if (!set) { set = new Set(); writers.set(id, set); } set.add(writer); const replay = (history.get(id)?.chunks ?? []).join(""); return { replay, detach: () => { set.delete(writer); if (set.size === 0) { writers.delete(id); } }, }; } /** Hides the Terminal tab; terminals keep running. */ function hide(): void { visible.value = false; } /** Starts listening to terminal events. Starting twice is a no-op. */ function start(): void { unsubscribe ??= onEngineEvent(onEvent); } /** Stops listening. */ function stop(): void { unsubscribe?.(); unsubscribe = null; } return { visible, expanded, tabs, activeId, active, focusRequest, error, create, open, activate, close, input, resize, attach, hide, start, stop, }; });