A local-first multi-agent app development platform, built on PenguinHarness
/**
* The reusable terminal surface: one xterm attached to one server-side terminal over the
* binary WebSocket stream. Both terminal hosts render this — the standalone `/terminal`
* page and the in-app dock (terminal-dock.tsx) — so attach/restore/resize behaviour is
* identical wherever a terminal appears.
*
* The host decides *which* terminal to show via the `ensure` callback: it receives the
* fitted geometry and returns the terminal to attach (reattaching to a stored id, creating
* a fresh one, honouring URL parameters — whatever that host's policy is). This component
* only knows how to attach to whatever `ensure` resolved.
*
* To restart with a different terminal, remount it (change the React `key`). On a touch
* device the surface also carries the key bar (terminal-keybar.tsx), so both hosts get the
* keys a soft keyboard lacks without either of them knowing about it.
*
* The socket itself is not managed here: terminal-connection.ts owns attaching, the
* heartbeat and reattaching after a link drops, so this file stays about xterm.
*/
import { useEffect, useRef, useState } from "react";
import "@xterm/xterm/css/xterm.css";
// Types only (erased at compile time): the xterm runtime stays behind loadXterm() below.
import type { ITheme, Terminal as XTerminal } from "@xterm/xterm";
import { TerminalOpcode, encodeFrame, encodeResize } from "./terminal-frames";
import { TerminalConnection } from "./terminal-connection";
import { LinkClickTracker, openTerminalLink, positionFromPointer } from "./terminal-links";
import { writeClipboard } from "../../lib/clipboard";
import { TerminalKeyBar, type TerminalControl } from "./terminal-keybar";
import { NO_MODIFIERS, applyModifiers, hasModifier, type TerminalModifiers } from "./terminal-keys";
import { selectionSpan, wordAt, type BufferCell, type WordSpan } from "./terminal-selection";
import { TouchScroll } from "./terminal-touch";
import { useCoarsePointer } from "../../lib/use-coarse-pointer";
import { useTheme } from "../../state/theme";
import { currentPlatform } from "../../lib/shortcuts/platform";
import { keymap } from "../../lib/shortcuts/store";
import { terminalClipboardAction } from "../../lib/shortcuts/terminal-clipboard";
import { terminalKeyAction } from "../../lib/shortcuts/terminal-keys";
import { useAuth } from "../../state/auth";
import { machineForTerminal, terminalUrl } from "../../lib/terminal-machines";
/**
* xterm and its addons load lazily, on the first actual terminal render: their UMD
* bundles touch browser globals (`self`) at import time, so a static import would crash
* any Node context that merely reaches this module through the import graph — which is
* most of the app since the dock mounts in AppLayout (unit tests import pages, pages
* import the toolbar, the toolbar imports the dock…).
*/
function loadXterm() {
return Promise.all([
import("@xterm/xterm"),
import("@xterm/addon-fit"),
import("@xterm/addon-web-links"),
import("@xterm/addon-clipboard"),
]);
}
export interface TerminalInfo {
id: string;
/** Stable per-user display number (assigned at creation, never renumbered). */
seq?: number;
name: string;
cwd: string;
alive: boolean;
/** Last OSC window title the shell set (debounced server-side), if any. */
title?: string | null;
}
/**
* How long the container has to hold still before its size is passed on. Long enough to
* swallow a soft keyboard's animation, short enough that a deliberate drag lands promptly.
*/
const RESIZE_SETTLE_MS = 120;
/**
* `reconnecting` is its own word on purpose: it is the state a mobile link spends most of
* its bad minutes in, and it means something the other three do not — the pty is fine, this
* page's socket is not, and it is being reattached (terminal-connection.ts).
*/
export type TerminalStatus = "connecting" | "ready" | "reconnecting" | "exited" | "error";
/**
* The screen's own palette, one per appearance. Two things matter here.
*
* The surface colours are the app's, not a terminal's: `#121212`/`#ffffff` are the default
* theme's canvas (`themes/github.css` in @adelie/ui) and its neutral ink, and the
* selection matches its `::selection`. A panel docked inside the app that brought its
* own charcoal along read as a foreign window sitting on top of it.
*
* The sixteen ANSI slots are NOT the app's palette and must not be: programs pick them by
* meaning ("red = error"), so they have to stay recognisable, and legible against the
* background they land on — which is why light mode has its own set rather than a dimmed
* copy. These are the values editor terminals converged on; xterm's built-in defaults are
* VGA-bright and unreadable on white.
*/
const DARK_THEME = {
background: "#121212",
foreground: "#f5f5f5",
cursor: "#f5f5f5",
cursorAccent: "#121212",
selectionBackground: "rgba(255, 255, 255, 0.18)",
black: "#000000",
red: "#cd3131",
green: "#0dbc79",
yellow: "#e5e510",
blue: "#2472c8",
magenta: "#bc3fbc",
cyan: "#11a8cd",
white: "#e5e5e5",
brightBlack: "#666666",
brightRed: "#f14c4c",
brightGreen: "#23d18b",
brightYellow: "#f5f543",
brightBlue: "#3b8eea",
brightMagenta: "#d670d6",
brightCyan: "#29b8db",
brightWhite: "#ffffff",
};
const LIGHT_THEME = {
background: "#ffffff",
foreground: "#171717",
cursor: "#171717",
cursorAccent: "#ffffff",
selectionBackground: "rgba(0, 0, 0, 0.12)",
black: "#000000",
red: "#cd3131",
green: "#00bc00",
yellow: "#949800",
blue: "#0451a5",
magenta: "#bc05bc",
cyan: "#0598bc",
white: "#555555",
brightBlack: "#666666",
brightRed: "#cd3131",
brightGreen: "#14ce14",
brightYellow: "#b5ba00",
brightBlue: "#0451a5",
brightMagenta: "#bc05bc",
brightCyan: "#0598bc",
brightWhite: "#a5a5a5",
};
export function terminalTheme(dark: boolean): ITheme {
return dark ? DARK_THEME : LIGHT_THEME;
}
/**
* Every terminal round-trip goes through here, and so is addressed to the machine that holds
* the terminal it names (lib/terminal-machines.ts). `server` is for the one call with no id
* to route by: creating a terminal names its machine before the terminal exists.
*/
async function request(
path: string,
init?: RequestInit,
server?: string | null,
): Promise<Response> {
return fetch(terminalUrl(path, server), {
credentials: "same-origin",
...init,
headers: { "Content-Type": "application/json", ...(init?.headers ?? {}) },
});
}
/**
* A failure the user can act on: the method, the path and the server's own words. A bare
* "Server did not return a terminal" was the opposite — it hid a 404 (a server without the
* terminal API, e.g. an older build the desktop shell attached to) behind wording that
* suggested the terminal itself failed to start.
*/
export class HttpStatusError extends Error {
constructor(
readonly status: number,
message: string,
) {
super(message);
this.name = "HttpStatusError";
}
}
function httpError(
path: string,
init: RequestInit | undefined,
res: Response,
body: string,
): HttpStatusError {
const method = init?.method ?? "GET";
const detail = body.trim() === "" ? res.statusText : body.trim();
return new HttpStatusError(res.status, `${method} ${path} → ${res.status} ${detail}`);
}
/** Any non-ok status is an error, 404 included — use probeJson where absence is expected. */
export async function fetchJson<T>(
path: string,
init?: RequestInit,
server?: string | null,
): Promise<T> {
const res = await request(path, init, server);
if (!res.ok) throw httpError(path, init, res, await res.text());
return (await res.json()) as T;
}
/** Existence probe: 404 means "not there" and answers null; every other failure throws. */
export async function probeJson<T>(
path: string,
init?: RequestInit,
server?: string | null,
): Promise<T | null> {
const res = await request(path, init, server);
if (res.status === 404) return null;
if (!res.ok) throw httpError(path, init, res, await res.text());
return (await res.json()) as T;
}
/**
* Always THIS server's stream. A pty on a machine is named in the id instead of the path —
* `<terminalId>@<machineId>@<userId>` — and this server's platform relays the socket through
* the connection it holds (server: machines/terminal-relay.ts). The user id is what the
* runtime's owner check reads; naming anyone else is refused there.
*/
function streamUrl(id: string, cols: number, rows: number, userId: string): string {
const scheme = location.protocol === "https:" ? "wss:" : "ws:";
const machine = machineForTerminal(id);
const ref = machine === null ? id : `${id}@${machine}@${userId}`;
return `${scheme}//${location.host}/api/terminals/${ref}/stream?cols=${cols}&rows=${rows}`;
}
export interface TerminalViewProps {
/**
* Resolves the terminal to attach, given the geometry the fitted xterm ended up with.
* Runs once per mount; throwing reports status "error" with the message as detail.
*/
ensure: (cols: number, rows: number) => Promise<TerminalInfo>;
onStatus?: (status: TerminalStatus, detail: string) => void;
onInfo?: (info: TerminalInfo) => void;
/** OSC window-title changes, parsed by this client's own xterm from the byte stream. */
onTitle?: (title: string) => void;
/**
* The `terminal.close` shortcut (⌃⌥` / Ctrl+Alt+` by default) pressed inside this terminal. The
* host decides what a close is — the dock tab's confirm-then-kill, the standalone page's
* kill-then-close-window; with no handler the key goes to the shell like any other.
*/
onCloseRequest?: () => void;
className?: string;
}
export function TerminalView({
ensure,
onStatus,
onInfo,
onTitle,
onCloseRequest,
className,
}: TerminalViewProps) {
const hostRef = useRef<HTMLDivElement | null>(null);
// The terminal's OWN appearance setting (light / dark / follow the app, defaulting to
// dark — see TerminalThemeMode), not the app's. It is repainted in place rather than
// remounted: the xterm instance, its scrollback and its WebSocket all outlive a switch
// (the view pool exists to keep exactly those alive). The ref is what lets the
// once-per-mount effect below read the current appearance without depending on it.
const { terminalDark } = useTheme();
const userId = useAuth().user?.userId ?? "";
const darkRef = useRef(terminalDark);
darkRef.current = terminalDark;
const termRef = useRef<XTerminal | null>(null);
// Touch affordances. The bar is the only consumer of all three: the control handle the
// effect publishes once a terminal is live, the sticky modifiers it arms (spent on the
// data path below), and whether xterm holds focus (which way the keyboard cap points).
const coarsePointer = useCoarsePointer();
const control = useRef<TerminalControl | null>(null);
const [modifiers, setModifiers] = useState<TerminalModifiers>(NO_MODIFIERS);
const modifiersRef = useRef(modifiers);
modifiersRef.current = modifiers;
const [focused, setFocused] = useState(false);
// Whether a selection is waiting to be copied. Only the touch key bar reads it: on a
// phone the copy has no key of its own, so the bar's copy cap appears exactly while
// there is something to copy.
const [hasSelection, setHasSelection] = useState(false);
// The touch selection mode, armed by the bar's select cap. A mode rather than a gesture
// because the obvious gesture belongs to the browser — see the touch block in the effect.
const [selectMode, setSelectMode] = useState(false);
const selectModeRef = useRef(selectMode);
selectModeRef.current = selectMode;
/**
* Turning the mode off drops the selection with it — the highlight is what the mode is
* for, and leaving it behind would hide the caps that came with it.
*/
const toggleSelectMode = (): void => {
const next = !selectModeRef.current;
selectModeRef.current = next; // before the re-render: a touch may land in between
setSelectMode(next);
if (!next) termRef.current?.clearSelection();
};
useEffect(() => {
if (termRef.current) termRef.current.options.theme = terminalTheme(terminalDark);
}, [terminalDark]);
// Kept in refs so the (intentionally once-per-mount) effect always calls the latest
// callbacks without re-running when a parent re-renders with a new closure.
const callbacks = useRef({ ensure, onStatus, onInfo, onTitle, onCloseRequest });
callbacks.current = { ensure, onStatus, onInfo, onTitle, onCloseRequest };
useEffect(() => {
const host = hostRef.current;
if (!host) return;
let cancelled = false;
let teardown: (() => void) | null = null;
// Deferred by one macrotask on purpose. StrictMode mounts, unmounts and remounts this
// effect synchronously in development; opening an xterm and disposing it inside that
// window leaves xterm's own queued viewport sync to run against a disposed instance
// ("cannot read properties of undefined (reading 'dimensions')"). Starting a tick later
// means the throwaway mount never opens a terminal at all.
const startTimer = setTimeout(() => {
if (cancelled) return;
void startTerminal(host).then((dispose) => {
// The lazy xterm load can outlive a quick unmount: dispose immediately then.
if (cancelled) dispose();
else teardown = dispose;
});
}, 0);
return () => {
cancelled = true;
clearTimeout(startTimer);
teardown?.();
};
async function startTerminal(container: HTMLDivElement): Promise<() => void> {
const [{ Terminal }, { FitAddon }, { WebLinksAddon }, { ClipboardAddon }] = await loadXterm();
let disposed = false;
let exited = false;
const report = (status: TerminalStatus, detail = ""): void => {
if (!disposed) callbacks.current.onStatus?.(status, detail);
};
/** Resolves clicks on links by position (terminal-links.ts); fed by the providers' hover reports. */
const links = new LinkClickTracker(() => term.cols);
/** One abort for every DOM listener this terminal registers; fired at teardown. */
const listenerAbort = new AbortController();
const term = new Terminal({
allowProposedApi: true,
cursorBlink: true,
fontFamily:
'"JetBrains Mono", "Fira Code", Menlo, Monaco, "DejaVu Sans Mono", Consolas, monospace',
fontSize: 13,
lineHeight: 1.2,
scrollback: 5000,
theme: terminalTheme(darkRef.current),
// OSC 8 hyperlinks — how a program that knows the terminal is capable writes a link.
// The providers only REPORT links here; the click itself is resolved below by
// position, because xterm's own activation cannot survive a redrawing program
// (terminal-links.ts). `activate` stays a no-op so a click never opens twice.
linkHandler: {
activate: () => {},
hover: (_event, text, range) => links.hover(text, range),
leave: () => links.leave(),
},
});
const fit = new FitAddon();
term.loadAddon(fit);
// Same arrangement for URLs found in the output: the addon reports, the tracker
// decides. Its built-in handler would also have opened a blank window first, which
// the desktop shell reads as a link to about:blank.
term.loadAddon(
new WebLinksAddon(() => {}, {
hover: (_event, text, range) => links.hover(text, range),
leave: () => links.leave(),
}),
);
// OSC 52: a program's own copy reaches the system clipboard — what tmux's copy mode
// does on every copy, and what makes a selection inside tmux land where a person
// expects it. WRITE only. The addon's default provider also answers a program's
// request to READ the clipboard, and terminal output is not something to hand the
// clipboard's contents to.
term.loadAddon(
new ClipboardAddon({
readText: () => Promise.resolve(""),
writeText: async (_selection, text) => {
await writeClipboard(text);
},
}),
);
termRef.current = term;
term.open(container);
fit.fit();
// Where a pointer event landed, in the coordinates the link ranges use. The screen
// element is exactly cols × rows cells, so the cell size falls out of its box.
const linkPosition = (event: MouseEvent) => {
const screen = term.element?.querySelector(".xterm-screen");
if (!screen) return null;
const box = screen.getBoundingClientRect();
return positionFromPointer(
{ x: event.clientX, y: event.clientY },
{ left: box.left, top: box.top, width: box.width, height: box.height },
{ cols: term.cols, rows: term.rows, viewportY: term.buffer.active.viewportY },
);
};
const linkTarget = term.element;
if (linkTarget) {
const opts = { signal: listenerAbort.signal };
linkTarget.addEventListener("mousemove", (e) => links.move(linkPosition(e)), opts);
linkTarget.addEventListener(
"mousedown",
(e) => {
if (e.button === 0) links.down(linkPosition(e), e.clientX, e.clientY);
},
opts,
);
linkTarget.addEventListener(
"mouseup",
(e) => {
if (e.button !== 0) return;
const uri = links.up(linkPosition(e), e.clientX, e.clientY);
if (uri !== null) openTerminalLink(uri);
},
opts,
);
}
/**
* Copies the active selection and clears it — the visual ack that the copy happened.
*
* Cleared only once the write landed, though. A failed write that also took the
* selection away leaves the reader worse off than before the keypress, and it is the
* one case the browser could still have rescued: xterm serves the browser's own copy
* event out of this same selection, so keeping it is what lets the native path fire
* after ours declined. (jsdom's `copy-to-clipboard` refuses; a plain-HTTP origin has
* no async clipboard API. Both are real on a LAN address.)
*/
const copySelection = (): void => {
const selection = term.getSelection();
if (!selection) return;
void writeClipboard(selection).then((copied) => {
if (copied && !disposed) term.clearSelection();
});
};
/** Async-clipboard paste (the paths where no native paste event exists). */
const pasteFromClipboard = (): void => {
void navigator.clipboard
?.readText()
.then((text) => text && term.paste(text))
.catch(() => {}); // permission denied / insecure context: nothing to paste
};
/**
* Keys the terminal decides before xterm does. xterm hands this handler its own
* textarea's events and nothing else, so everything here is seen only by the terminal
* that has focus.
*
* 1. Clipboard keys, a fixed platform convention (lib/shortcuts/terminal-clipboard.ts):
* a copy writes the selection here; a paste rides the browser's NATIVE paste event
* into xterm's textarea (no clipboard permission involved), so returning false —
* skip xterm's own key handling, keep the browser default — is the whole
* implementation, and calling the async clipboard API as well would double-paste.
* 2. The keymap (lib/shortcuts/terminal-keys.ts decides). The terminal-scope command
* (`terminal.close`, ⌃⌥` / Ctrl+Alt+` by default) is consumed here so it never
* reaches the shell. Everything else is xterm's: the shell keeps every key xterm would
* send it, even one an app command is bound to (Ctrl+W, tmux's Ctrl+B, and on Linux
* the Ctrl+Alt chords, which xterm sends as Meta), and the chords xterm sends nothing
* for — Ctrl+`, Ctrl+Shift+`, every ⌘ chord, and on Windows the Ctrl+Alt ones it
* leaves to AltGr — are left un-prevented and bubble to the window dispatcher that
* owns them.
*/
const platform = currentPlatform();
term.attachCustomKeyEventHandler((event) => {
if (event.type !== "keydown") return true;
const clipboard = terminalClipboardAction(event, platform, term.hasSelection());
if (clipboard === "copy") {
copySelection();
return false;
}
if (clipboard === "paste") {
return false; // native paste path (see above)
}
const action = terminalKeyAction(event, keymap(), platform, {
canClose: callbacks.current.onCloseRequest !== undefined,
});
switch (action) {
case "shell":
return true;
case "consume":
event.preventDefault();
event.stopPropagation();
return false;
case "close":
event.preventDefault();
event.stopPropagation();
callbacks.current.onCloseRequest?.();
return false;
}
});
/**
* Terminal mouse conventions. All of these step aside when a full-screen app (vim,
* htop) has turned mouse tracking on — the app owns the pointer then, and xterm
* forwards the events as escape codes.
*/
const { signal } = listenerAbort;
const appOwnsMouse = (): boolean => term.modes.mouseTrackingMode !== "none";
// A long press on a touchscreen also raises `contextmenu`, and it is not a right
// click: the finger that meant to select text would paste the clipboard into a live
// shell instead. Touch gets the key bar's paste cap, which says what it does.
let touchPointer = false;
container.addEventListener(
"pointerdown",
(event) => {
touchPointer = event.pointerType === "touch" || event.pointerType === "pen";
},
{ signal },
);
container.addEventListener(
"contextmenu",
(event) => {
event.preventDefault(); // a terminal never shows the page's context menu
if (appOwnsMouse() || touchPointer) return;
// PuTTY-style right click: copy the selection if there is one, else paste.
if (term.hasSelection()) copySelection();
else pasteFromClipboard();
},
{ signal },
);
container.addEventListener(
"mousedown",
(event) => {
// Middle click: paste (the X11 convention; browser autoscroll is useless here).
if (event.button === 1 && !appOwnsMouse()) {
event.preventDefault();
pasteFromClipboard();
}
},
{ signal },
);
/**
* A finger dragging while a program owns the mouse: the wheel it does not have.
*
* xterm turns its own touch scrolling off for exactly these programs, and they are the
* ones that need it most — a TUI on the alternate screen (Claude Code) leaves the
* terminal no scrollback to scroll, draws its transcript itself, and pages it only when
* a wheel reports. So the travel becomes wheel events (terminal-touch.ts for the
* arithmetic), dispatched at xterm's own element so IT encodes them in whatever
* protocol the program asked for — hand-rolled SGR here would be a second encoder to
* keep in step with the first.
*
* A tap is left alone: nothing scrolls until the travel passes the slop, so the
* browser's tap-to-click still reaches a program that answers clicks. Where the mouse
* is free, xterm's own touch handling runs first (on its element, below this one) and
* this stays out of the way entirely.
*/
const touchScroll = new TouchScroll();
/** The height of one row, in pixels: the screen element is exactly rows cells tall. */
const cellHeight = (): number => {
const screen = term.element?.querySelector(".xterm-screen");
if (!screen || term.rows <= 0) return 0;
return screen.getBoundingClientRect().height / term.rows;
};
const wheelLine = (x: number, y: number, down: boolean): void => {
term.element?.dispatchEvent(
new WheelEvent("wheel", {
deltaY: down ? 1 : -1,
// Lines, not pixels: one event is one line, whatever this device's cells measure.
deltaMode: 1,
clientX: x,
clientY: y,
bubbles: true,
cancelable: true,
}),
);
};
container.addEventListener(
"touchstart",
(event) => {
if (!appOwnsMouse() || event.touches.length !== 1) {
touchScroll.end(); // a second finger (pinch) is not a scroll
return;
}
touchScroll.start(event.touches[0]!.clientY);
},
{ signal, passive: true },
);
container.addEventListener(
"touchmove",
(event) => {
const touch = event.touches[0];
if (!touchScroll.started || event.touches.length !== 1 || touch === undefined) return;
const lines = touchScroll.move(touch.clientY, cellHeight());
if (!touchScroll.engaged) return;
// The host carries `touch-none` on a touch device, so there is normally nothing
// left to cancel; this is for the device that reports a fine pointer and is one
// anyway, where the page would otherwise scroll out from under the gesture.
if (event.cancelable) event.preventDefault();
for (let i = Math.abs(lines); i > 0; i--) {
wheelLine(touch.clientX, touch.clientY, lines > 0);
}
},
{ signal, passive: false },
);
container.addEventListener("touchend", () => touchScroll.end(), { signal, passive: true });
container.addEventListener("touchcancel", () => touchScroll.end(), { signal, passive: true });
/**
* Selecting with a finger, in the mode the key bar's select cap turns on.
*
* The selection cannot hang off the gesture a phone reaches for first: a press that
* rests belongs to the browser, which takes it for its own and stops delivering
* touches to the page (measured in Chromium: after a resting press, no touchmove and
* no touchend — only pointer events). So it gets an explicit mode instead, one no
* gesture recognizer competes for: while it is on, a touch down takes the word under
* the finger and the finger's travel extends it. While it is off, every touch here
* behaves exactly as it did before — the scroll stays a scroll.
*/
let pressWord: WordSpan | null = null;
let dragging = false;
/** Where an armed gesture began, until the selection itself is made. */
let touchStartPoint: { x: number; y: number } | null = null;
/** The buffer cell under a client point; a drag may leave the grid, so it is clamped. */
const cellAt = (clientX: number, clientY: number): BufferCell | null => {
const screen = term.element?.querySelector(".xterm-screen");
if (!screen) return null;
const box = screen.getBoundingClientRect();
if (box.width <= 0 || box.height <= 0) return null;
const pos = positionFromPointer(
{
x: Math.min(Math.max(clientX, box.left), box.left + box.width - 1),
y: Math.min(Math.max(clientY, box.top), box.top + box.height - 1),
},
{ left: box.left, top: box.top, width: box.width, height: box.height },
{ cols: term.cols, rows: term.rows, viewportY: term.buffer.active.viewportY },
);
return pos === null ? null : { col: pos.x - 1, row: pos.y - 1 };
};
/** A touch landed here: take the word it landed on. */
const beginSelection = (clientX: number, clientY: number): void => {
const cell = cellAt(clientX, clientY);
const line = cell === null ? undefined : term.buffer.active.getLine(cell.row);
if (cell === null || line === undefined) return;
const word = wordAt(line.translateToString(true), cell.col);
if (word === null) return; // blank line: nothing to take, and nothing to extend from
pressWord = { ...word, row: cell.row };
term.select(word.start, cell.row, word.end - word.start);
};
/** The finger moved with a selection live: extend it from the word to the finger. */
const extendSelection = (clientX: number, clientY: number): void => {
if (pressWord === null) return;
const cell = cellAt(clientX, clientY);
if (cell === null) return;
const span = selectionSpan(pressWord, cell, term.cols);
if (span !== null) term.select(span.col, span.row, span.length);
};
container.addEventListener(
"touchstart",
(event) => {
pressWord = null;
dragging = false;
touchStartPoint = null;
const touch = event.touches[0];
if (!selectModeRef.current || event.touches.length !== 1 || touch === undefined) return;
dragging = true;
// Deliberately nothing else. Making the selection here stops Chromium from
// delivering the rest of the gesture at all — measured: a `term.select()` inside
// the touchstart handler is followed by no touchmove and no touchend, only pointer
// events, so the drag the mode exists for would never arrive. It is made on the
// first movement instead, and at the end when there was none (a tap).
touchStartPoint = { x: touch.clientX, y: touch.clientY };
},
{ signal, capture: true, passive: true },
);
container.addEventListener(
"touchmove",
(event) => {
if (!dragging) return;
const touch = event.touches[0];
if (touch === undefined) return;
// Capture phase, and both calls matter: xterm's viewport would otherwise scroll
// the text out from under the finger that is selecting it.
event.preventDefault();
event.stopPropagation();
// The word the gesture took is the one under where it began, or under the cell it
// has reached when that beginning was blank padding and held nothing to take.
if (pressWord === null) {
const from = touchStartPoint ?? { x: touch.clientX, y: touch.clientY };
touchStartPoint = null;
beginSelection(from.x, from.y);
}
extendSelection(touch.clientX, touch.clientY);
},
{ signal, capture: true, passive: false },
);
const endTouch = (event: TouchEvent): void => {
if (!dragging) return;
dragging = false;
const start = touchStartPoint;
touchStartPoint = null;
if (event.touches.length > 0) {
// A second finger is not the end of the gesture.
pressWord = null;
return;
}
// No movement at all: this was a tap, and the tap itself is what takes the word.
if (pressWord === null && start !== null) beginSelection(start.x, start.y);
const selected = pressWord !== null;
pressWord = null;
if (!selected) {
term.clearSelection(); // a touch that took nothing takes the selection away too
return;
}
selectionMade = true; // see swallowTouchMouse
event.preventDefault();
};
container.addEventListener("touchend", endTouch, { signal, capture: true, passive: false });
container.addEventListener("touchcancel", endTouch, { signal, capture: true, passive: true });
/**
* Chrome renders a touch as mouse events as well (`mousedown`, then `click`), and xterm
* reads a mousedown on its surface as "begin a new selection" — it would replace, or
* drop, the one the finger just made. So a gesture that made a selection swallows them.
* Only those: `sourceCapabilities.firesTouchEvents` is the browser saying the event came
* from a finger (the DOM lib does not type the field, hence the widening below), and a
* real mouse never sets it, so a pointer on a touchscreen laptop is untouched. The next
* press disarms the guard.
*/
let selectionMade = false;
const swallowTouchMouse = (event: MouseEvent): void => {
const fromTouch =
(event as MouseEvent & { sourceCapabilities?: { firesTouchEvents?: boolean } })
.sourceCapabilities?.firesTouchEvents === true;
if (!selectionMade || !fromTouch) return;
event.preventDefault();
event.stopPropagation();
};
container.addEventListener("mousedown", swallowTouchMouse, { signal, capture: true });
container.addEventListener("mouseup", swallowTouchMouse, { signal, capture: true });
container.addEventListener("click", swallowTouchMouse, { signal, capture: true });
container.addEventListener("pointerdown", () => (selectionMade = false), {
signal,
capture: true,
});
// What the key bar's copy cap reads, and what makes it show up at all.
term.onSelectionChange(() => setHasSelection(term.hasSelection()));
// Click-to-focus anywhere in the view, padding included — finishing a selection drag
// also lands here, which is fine: focusing xterm's textarea keeps the selection.
container.addEventListener("mouseup", () => term.focus(), { signal });
container.addEventListener("focusin", () => setFocused(true), { signal });
container.addEventListener("focusout", () => setFocused(false), { signal });
// Size ownership follows the user's attention (see server size-ownership.ts): the pty
// is laid out for the most recent CLAIMING connection, and `update`s from anyone else
// are ignored. Attaching claims; refocusing this view must claim again, or after
// another window attaches this one could never win its geometry back.
container.addEventListener(
"focusin",
() => connection.send(encodeResize(term.cols, term.rows, "claim")),
{ signal },
);
const send = (data: string): void => {
connection.send(encodeFrame(TerminalOpcode.Input, data));
};
term.onData((data) => {
// A sticky Ctrl/Alt armed on the touch key bar composes with the next character the
// soft keyboard produces, then spends itself. Nothing to do when none is armed,
// which is every keystroke on a physical keyboard.
const mods = modifiersRef.current;
if (!hasModifier(mods)) {
send(data);
return;
}
send(applyModifiers(data, mods));
setModifiers(NO_MODIFIERS);
});
// Title changes ride the ordinary byte stream (OSC 0/2); this client's xterm parses
// them, so the host can mirror the live title (e.g. onto the dock's tab strip).
term.onTitleChange((title) => {
if (!disposed) callbacks.current.onTitle?.(title);
});
/**
* One connection, however many sockets that takes (terminal-connection.ts): it owns
* the first attach, the heartbeat and every reattach. This view only says what a
* frame means and what a status looks like.
*/
const connection = new TerminalConnection({
first: async () => {
const terminal = await callbacks.current.ensure(term.cols, term.rows);
callbacks.current.onInfo?.(terminal);
return terminal.id;
},
// A reattach that finds no terminal has nothing to come back to: the shell exited
// and was reaped while this page was away.
recheck: async (id) =>
(await probeJson<TerminalInfo>(`/api/terminals/${encodeURIComponent(id)}`)) !== null,
open: (id, handlers) => {
const ws = new WebSocket(streamUrl(id, term.cols, term.rows, userId));
ws.binaryType = "arraybuffer";
ws.onopen = () => handlers.onOpen();
ws.onmessage = (event) => {
if (event.data instanceof ArrayBuffer) handlers.onMessage(event.data);
};
// `error` is always followed by `close`; handling both would report twice.
ws.onclose = () => handlers.onClose();
return {
send: (bytes) => {
if (ws.readyState === WebSocket.OPEN) ws.send(bytes);
},
close: () => ws.close(),
};
},
onFrame: (frame) => {
switch (frame.opcode) {
// The restore stream is self-contained (reset + clear + repaint + cursor), so
// it is written like any other output; calling term.reset() here would race
// with xterm's parser instead.
case TerminalOpcode.Restore:
case TerminalOpcode.Output:
term.write(frame.text);
break;
case TerminalOpcode.Exit: {
const { exitCode } = JSON.parse(frame.text) as { exitCode: number };
exited = true;
connection.stop(); // an exited pty is not something to reattach to
report("exited", String(exitCode));
break;
}
default:
break;
}
},
onStatus: (status, detail) => {
if (exited) return; // the exit already said what happened to this terminal
report(status, detail);
},
});
connection.start();
// A network that comes back, or a tab that does, is a reason to reattach now instead
// of sitting out the backoff — on a phone both happen all day. Waking also probes a
// socket that merely LOOKS open, which is what a suspended tab usually comes back to.
window.addEventListener("online", () => connection.wake(), { signal });
document.addEventListener(
"visibilitychange",
() => {
if (!document.hidden) connection.wake();
},
{ signal },
);
// Geometry changes are `update`s: this connection claimed the size when it attached
// (?cols/?rows on the stream URL, and again on focusin above); an update only
// applies while this connection still holds ownership.
// Settled, not per pixel. A phone resizes this container constantly — the address bar
// collapses, the soft keyboard opens, the dock is dragged — and each size that reaches
// the pty costs a SIGWINCH and a full repaint from whatever is running, which on a slow
// link is the most expensive thing the terminal can do. So fit on the trailing edge,
// and only tell the server when the GRID actually changed; most pixel changes do not
// move it.
let resizeTimer: ReturnType<typeof setTimeout> | null = null;
let sentCols = term.cols;
let sentRows = term.rows;
const observer = new ResizeObserver(() => {
if (disposed) return;
if (resizeTimer !== null) clearTimeout(resizeTimer);
resizeTimer = setTimeout(() => {
resizeTimer = null;
if (disposed) return;
fit.fit();
if (term.cols === sentCols && term.rows === sentRows) return;
sentCols = term.cols;
sentRows = term.rows;
connection.send(encodeResize(term.cols, term.rows, "update"));
}, RESIZE_SETTLE_MS);
});
observer.observe(container);
term.focus();
// What the touch key bar drives. Published after the terminal is open and dropped on
// dispose, so a bar tap between two attaches is a no-op rather than a throw.
control.current = {
send,
copy: copySelection,
paste: pasteFromClipboard,
focus: () => term.focus(),
blur: () => term.blur(),
applicationCursorKeys: () => term.modes.applicationCursorKeysMode,
};
return () => {
disposed = true;
termRef.current = null;
control.current = null;
listenerAbort.abort();
observer.disconnect();
if (resizeTimer !== null) clearTimeout(resizeTimer);
connection.stop();
term.dispose();
};
}
}, []);
// The className lands on the WRAPPER, not on the xterm host: the host has to be the
// flex child that takes the leftover height, so that the bar's own height comes off the
// terminal's grid instead of pushing the surface past its container.
return (
<div className={`flex flex-col ${className ?? "min-h-0 flex-1 overflow-hidden"}`}>
{/* `touch-none` on a touch device: the drag above is the gesture, and the browser
must not take it for its own (a page scroll, a pull-to-refresh) — which also
stops mid-gesture cancellation, since a taken-over touch stops being cancelable.
xterm's own touch scrolling sets scrollTop itself and is unaffected. */}
<div
ref={hostRef}
className={`min-h-0 flex-1 overflow-hidden ${coarsePointer ? "touch-none" : ""}`}
/>
{coarsePointer && (
<TerminalKeyBar
control={control}
modifiers={modifiers}
onModifiers={setModifiers}
focused={focused}
hasSelection={hasSelection}
selectMode={selectMode}
onToggleSelect={toggleSelectMode}
/>
)}
</div>
);
}