Files
LLeMbas/src/lembas/web/static/js/terminal.js
T
Jaroslav Beneš 131a4083f8 The terminal learns where one command ends, and can be dragged wider
"The last command and its output" was not something the panel could honestly
offer. sendToChat took the last forty rows of the screen buffer, hard-wrapped at
the terminal's width with no way to tell a wrap from a newline -- its own comment
said so. So bash and zsh are given the OSC 133 markers VS Code and WezTerm use,
and Copy, Send and an Auto toggle are built on those.

The integration is written by the PTY command string itself, with printf. sshd
runs that string through $SHELL -c, so it can case on the shell's own name and
needs no probe, no second channel and no writable home. Passing it through the
environment does not work -- every distribution ships AcceptEnv LANG LC_*, so
anything else is dropped silently -- and feeding `source ...` in as keystrokes
races a slow .zshrc, echoes into the scrollback and lands in shell history.

Nothing needs hiding, which is the point of choosing it: the setup runs before
the shell exists and never writes to the PTY's input side, so there is nothing
to echo and no fan-out gate to build.

Two things were wrong in the first version and both were found by running it
against real shells rather than the fake one. bash: the DEBUG trap fires before
every simple command *including each one inside PROMPT_COMMAND*, so $? read from
there is whatever ran a moment ago -- every command reported success. The status
is captured in the trap now, which also removes the two-entry PROMPT_COMMAND
dance entirely. zsh: $ZDOTDIR is already ours by the time .zshenv runs, so the
shims were sourcing themselves and none of the user's configuration loaded; the
original is passed on the exec line.

Parsing is server-side. The `behind` path resets the terminal and replays a
truncated scrollback, so a client parser routinely sees a finish with no start;
two tabs share one shell and can disagree; and what comes out of this ends up
inside a prompt, so deriving it here leaves nothing to disbelieve. The bytes are
fanned out unchanged -- xterm consumes an OSC it has no handler for.

Output is bounded head and tail, 48KB and 16KB: a build that fails ten megabytes
in has the invocation at the top and the error at the bottom. Carriage returns
collapse to the last state of each line, which is the difference between a
usable prompt and two megabytes of spinner. The fence is sized to its content,
because output containing three backticks would otherwise break out and read as
prose.

Any shell that is not bash or zsh starts exactly as it did before. The buttons
then scrape the screen and say so, and Auto is disabled rather than degraded:
forty arbitrary lines on every message is worse than nothing.

Also a generic [data-resize] handle, keyboard included, persisted the way the
theme is. The inspector and sidebar can have it whenever they want it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-02 17:28:38 +02:00

448 lines
16 KiB
JavaScript

/*
The terminal panel.
Loaded only on a chat that can actually open a shell -- see the head and
scripts blocks in chat/index.html -- because xterm is nearly three times the
size of everything else vendored here. The Terminal object itself is built on
the first *open* rather than on load, so even here nothing is parsed for
somebody who never presses the button.
Three things about xterm that are easy to get wrong, and cost an afternoon
each:
* `fit()` measures `offsetWidth`, which is 0 inside a `[hidden]` ancestor, so
fitting while closed silently does nothing and leaves an 80-column terminal
in a 34rem panel. Everything below is arranged so a fit only ever happens
after the panel is visible.
* A window `resize` event does not fire when the sidebar is toggled or a panel
opens beside this one, which is by far the commonest way the panel changes
size. Hence the ResizeObserver.
* xterm does not read CSS variables. The theme is built from the computed
style at open time and rebuilt when the theme changes, or switching to
`shire` leaves a black rectangle in a light interface.
*/
(function () {
"use strict";
var panel = null;
var term = null;
var fit = null;
var socket = null;
var screen = null;
var messageEl = null;
var observer = null;
var closedOnPurpose = false;
/* Whether this shell tells us where commands begin and end -- "live",
"loading" or "none". Everything the three buttons do keys off it. */
var integration = "loading";
var autoSend = false;
var lastCommand = null;
function say(text, isError) {
if (!messageEl) return;
messageEl.textContent = text;
messageEl.classList.toggle("terminal__message--error", !!isError);
}
/* --- Theme -------------------------------------------------------------- */
/* The sixteen ANSI slots, in the order xterm names them. A shell chooses
these itself -- `ls --color`, a git diff, htop's meters -- so without them
the panel rendered a foreign palette inside the application, and switching
to Shire left dark-theme colours on parchment. */
var ANSI = [
"black", "red", "green", "yellow", "blue", "magenta", "cyan", "white",
"brightBlack", "brightRed", "brightGreen", "brightYellow",
"brightBlue", "brightMagenta", "brightCyan", "brightWhite"
];
function readTheme() {
var style = getComputedStyle(document.documentElement);
function token(name, fallback) {
return (style.getPropertyValue(name) || "").trim() || fallback;
}
var theme = {
background: token("--code-bg", "#0C0F13"),
foreground: token("--ink", "#E4E8EC"),
cursor: token("--accent", "#8FB3CC"),
cursorAccent: token("--code-bg", "#0C0F13"),
selectionBackground: token("--accent-soft", "rgba(143, 179, 204, 0.3)")
};
/* camelCase to --kebab-case: brightBlack -> --ansi-bright-black. A slot
with no token is left off the object entirely rather than set to
undefined, which xterm treats as a colour and renders as black. */
ANSI.forEach(function (name) {
var value = token(
"--ansi-" + name.replace(/[A-Z]/g, function (c) { return "-" + c.toLowerCase(); }),
""
);
if (value) theme[name] = value;
});
return theme;
}
/* --- Sizing ------------------------------------------------------------- */
function visible() {
return panel && !panel.hasAttribute("hidden") && panel.offsetWidth > 0;
}
function refit() {
if (!term || !fit || !visible()) return;
try {
fit.fit();
} catch (error) {
return;
}
send({ t: "resize", cols: term.cols, rows: term.rows });
}
/* --- The socket --------------------------------------------------------- */
function send(payload) {
if (socket && socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify(payload));
}
}
function connect() {
if (socket) return;
closedOnPurpose = false;
var base = location.protocol === "https:" ? "wss://" : "ws://";
var url =
base + location.host + panel.dataset.url +
"?cols=" + (term.cols || 80) + "&rows=" + (term.rows || 24);
say("Connecting…");
socket = new WebSocket(url);
socket.binaryType = "arraybuffer";
socket.onmessage = function (event) {
if (typeof event.data === "string") return control(event.data);
/* Written straight through as bytes. xterm's decoder is stateful across
calls, so a multi-byte character split across two frames still lands
correctly -- which is exactly why the server never decodes either. */
term.write(new Uint8Array(event.data));
};
socket.onclose = function () {
socket = null;
if (!closedOnPurpose) say("Disconnected. Close and reopen to reconnect.");
};
socket.onerror = function () {
/* A failed handshake gives the page nothing: no status, no reason. So
this is a guess, and it names the likeliest cause rather than
pretending to know. */
say("Could not connect. If this instance is behind a proxy, it may not " +
"be passing WebSocket upgrades through.", true);
};
}
function control(raw) {
var payload;
try {
payload = JSON.parse(raw);
} catch (error) {
return;
}
if (payload.t === "ready") {
say(payload.shared
? "Connected. This shell is also open in another tab, and they share a size."
: "Connected.");
if (payload.dir) {
var where = panel.querySelector("[data-terminal-where]");
if (where) where.textContent = payload.dir;
}
integration = payload.integration || "none";
showLast(payload.last);
applyIntegration();
/* The server may have opened the shell at a size chosen by whoever got
here first, so ask for ours now that there is something to ask. */
refit();
term.focus();
return;
}
if (payload.t === "command") {
/* A command finished. Tens of bytes, not the output: a 64KB text frame
would compete with PTY bytes on the one path that has to stay quick,
and the buttons fetch what they need when they are pressed. */
if (integration !== "live") { integration = "live"; applyIntegration(); }
showLast(payload.command);
if (autoSend) {
capture(true).then(function (text) { intoComposer(text, true); });
}
return;
}
if (payload.t === "behind") {
/* This window stopped reading and was disconnected so the others kept
up. Reconnecting costs nothing: the scrollback is the state. */
say(payload.message || "Reconnecting…");
closedOnPurpose = true;
if (socket) socket.close();
socket = null;
term.reset();
connect();
return;
}
if (payload.t === "closed" || payload.t === "error") {
say(payload.message || "This terminal closed.", payload.t === "error");
closedOnPurpose = true;
/* Deliberately no reconnect. A new shell has lost the working directory,
the environment and the half-typed command, and quietly substituting
one is worse than saying the connection went. */
}
}
/* --- Building it -------------------------------------------------------- */
function build() {
if (term) return true;
if (typeof Terminal === "undefined" || typeof FitAddon === "undefined") {
say("The terminal could not be loaded.", true);
return false;
}
var style = getComputedStyle(document.documentElement);
term = new Terminal({
allowProposedApi: true,
convertEol: false,
cursorBlink: true,
fontFamily: style.getPropertyValue("--font-mono").trim() || "monospace",
/* xterm wants a number, so the token has to be a plain pixel value and
is parsed back out here. Reading it rather than repeating 13 is what
keeps it adjustable in one place with everything else. */
fontSize: parseFloat(style.getPropertyValue("--terminal-font-size")) || 13,
scrollback: 5000,
theme: readTheme()
});
/* The module namespace is the UMD global, so the class is a property of
it. `new FitAddon()` is the mistake that reads correctly. */
fit = new FitAddon.FitAddon();
term.loadAddon(fit);
term.open(screen);
term.onData(function (data) {
if (socket && socket.readyState === WebSocket.OPEN) {
socket.send(new TextEncoder().encode(data));
}
});
/* Ctrl+C is interrupt here, which is correct and will still surprise
somebody. Copy and paste are the shifted pair, as in every terminal. */
term.attachCustomKeyEventHandler(function (event) {
if (!event.ctrlKey || !event.shiftKey || event.type !== "keydown") return true;
var key = event.key.toLowerCase();
if (key === "c") {
var selection = term.getSelection();
if (selection) navigator.clipboard.writeText(selection);
return false;
}
if (key === "v") {
navigator.clipboard.readText().then(function (text) {
if (socket && socket.readyState === WebSocket.OPEN) {
socket.send(new TextEncoder().encode(text));
}
});
return false;
}
return true;
});
/* The panel changes size when the sidebar is toggled or the window is
resized, and only the second of those fires a `resize` event. */
if (window.ResizeObserver) {
observer = new ResizeObserver(function () {
refit();
});
observer.observe(panel);
}
return true;
}
function open() {
if (!build()) return;
/* Next frame: the panel has just had `hidden` removed and has no measured
width yet, so fitting now would be the silent no-op this file exists to
avoid. */
requestAnimationFrame(function () {
refit();
connect();
term.focus();
});
}
/* --- Handing a command to the chat --------------------------------------
Three buttons over one idea: the last command, its output, and where it
ran. The server renders the block, so the text a model eventually reads
exists in exactly one place -- and the screen buffer could not produce it
anyway, holding as it does what is *on screen*, hard-wrapped at the
terminal's width with no way to tell a wrap from a newline. */
function applyIntegration() {
if (!panel) return;
var auto = panel.querySelector("[data-terminal-auto]");
if (!auto) return;
var usable = integration === "live";
auto.disabled = !usable;
auto.title = usable
? "Attach every command you run to your next message"
: "This shell did not load LLeMbas's command markers, so there is no way " +
"to tell where one command's output ends.";
if (!usable && autoSend) setAuto(false);
}
function showLast(command) {
lastCommand = command || null;
var slot = panel && panel.querySelector("[data-terminal-last]");
if (!slot) return;
// textContent, always: this is a command line off somebody's machine.
slot.textContent = lastCommand ? lastCommand.summary : "";
}
function setAuto(on) {
autoSend = !!on;
var button = panel.querySelector("[data-terminal-auto]");
if (button) {
button.setAttribute("aria-pressed", autoSend ? "true" : "false");
button.classList.toggle("is-active", autoSend);
}
say(autoSend
? "Every command you run will be attached to your next message."
: "Commands are no longer attached automatically.");
}
/* A selection always wins, in every state. People rely on it, and it is the
only way to send part of something. */
function selected() {
var text = term ? term.getSelection() : "";
return text && text.trim() ? text : "";
}
function scraped() {
var lines = [];
var buffer = term.buffer.active;
var last = buffer.baseY + buffer.cursorY;
for (var y = Math.max(0, last - 40); y <= last; y++) {
var line = buffer.getLine(y);
if (line) lines.push(line.translateToString(true));
}
return lines.join("\n").replace(/\n+$/, "");
}
/* Fetches the rendered block, or falls back to the screen. `quiet` is the
auto path, which must not narrate every command it collects. */
function capture(quiet) {
var chosen = selected();
if (chosen && !quiet) return Promise.resolve("```\n" + chosen + "\n```\n");
if (integration !== "live") {
if (quiet) return Promise.resolve("");
var text = scraped();
if (!text.trim()) {
say("Nothing to send: select some output first.");
return Promise.resolve("");
}
/* Said plainly rather than dressed up. Without markers this is the last
forty rows as they appeared, wraps and all, and pretending otherwise
would put a precise-looking block in front of a model that is not. */
say("Copied the last of the screen, as it appeared. This shell does not " +
"mark where commands begin.");
return Promise.resolve("```\n" + text + "\n```\n");
}
return fetch(panel.dataset.url.replace(/\/ws$/, "/last"), { credentials: "same-origin" })
.then(function (response) { return response.json(); })
.then(function (body) {
if (!body.ok) {
if (!quiet) say(body.message || "Nothing to send yet.");
return "";
}
return body.text + "\n";
})
.catch(function () {
if (!quiet) say("Could not read the last command.", true);
return "";
});
}
function intoComposer(text, quiet) {
if (!text) return;
var input = document.querySelector("[data-composer-input]");
if (!input) return;
input.value = input.value ? input.value.replace(/\s*$/, "\n\n") + text : text;
if (window.lembas && window.lembas.autosize) window.lembas.autosize(input);
/* Auto-send never steals focus: it fires while somebody is typing in the
terminal, and yanking the caret out of a shell mid-command is the sort
of thing that gets a feature switched off for good. */
if (!quiet) input.focus();
}
function sendToChat() {
if (!term) return;
capture(false).then(function (text) {
if (!text) return;
intoComposer(text, false);
/* Into the composer, never sent. What a machine printed is exactly the
sort of text somebody should read before a model does, and the box is
where that happens. */
if (integration === "live") say("Put into the message box. It is not sent yet.");
});
}
function copyToClipboard() {
if (!term) return;
capture(false).then(function (text) {
if (!text) return;
if (window.lembas && window.lembas.copyText) {
window.lembas.copyText(text);
say("Copied.");
}
});
}
/* --- Wiring ------------------------------------------------------------- */
function start() {
panel = document.querySelector("[data-terminal]");
if (!panel) return;
screen = panel.querySelector("[data-terminal-screen]");
messageEl = panel.querySelector("[data-terminal-message]");
panel.addEventListener("lembas:toggle", function (event) {
if (event.detail && event.detail.open) open();
/* Closing leaves the Terminal object and the socket alone. `write()` is
internally queued, so disposing mid-output drops it, and keeping the
object is what makes reopening instant. The session on the far side
outlives this panel by design. */
});
panel.addEventListener("click", function (event) {
if (event.target.closest("[data-terminal-send]")) {
event.preventDefault();
return sendToChat();
}
if (event.target.closest("[data-terminal-copy]")) {
event.preventDefault();
return copyToClipboard();
}
if (event.target.closest("[data-terminal-auto]")) {
event.preventDefault();
return setAuto(!autoSend);
}
});
/* xterm holds colours as values, not as variables, so a theme change has
to be pushed into it. */
document.addEventListener("lembas:theme", function () {
if (term) term.options.theme = readTheme();
});
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", start);
} else {
start();
}
})();