325 lines
14 KiB
TypeScript
325 lines
14 KiB
TypeScript
"use client";
|
||
// Live runner terminal (PEP-9): xterm.js fed by the tab's live channel (`terminal:<id>`, PEP-225),
|
||
// input over the same channel; without a WebSocket — SSE of /api/runners/<id>/terminal and POST.
|
||
// PEP-257: the font is given to xterm resolved (a CSS variable is not understood when xterm
|
||
// measures its cell — the cell came out wider than the glyphs and got letter-spacing), the cell
|
||
// is re-measured when web fonts arrive. By default the whole grid is scaled to the panel width so
|
||
// all columns of the pane are visible («по ширине»): a CSS scale of the grid xterm drew, because
|
||
// font sizes alone do not fit — browsers round small glyph advances to whole pixels. +/- switch
|
||
// to a fixed font size, unscaled, with scrolling.
|
||
import "@xterm/xterm/css/xterm.css";
|
||
import type { Terminal } from "@xterm/xterm";
|
||
import { ArrowLeftRight, Keyboard, Maximize2, Minimize2, Minus, Plus, RotateCw } from "lucide-react";
|
||
import { useCallback, useEffect, useRef, useState } from "react";
|
||
import { cn } from "@/lib/utils";
|
||
import { liveClient, useLiveMode } from "@/lib/live";
|
||
import { useT } from "@/components/I18n";
|
||
import { m } from "@peppa/shared/i18n";
|
||
|
||
type Status = "connecting" | "live" | "reconnecting" | "ended" | "error";
|
||
const STATUS_TEXT: Record<Status, string> = {
|
||
connecting: m("подключение…"),
|
||
live: m("в эфире"),
|
||
reconnecting: m("переподключение…"),
|
||
ended: m("tmux-сессии нет"),
|
||
error: m("нет доступа к терминалу"),
|
||
};
|
||
const FONT_KEY = "peppa_term_font";
|
||
const FIT_KEY = "peppa_term_fit";
|
||
const FONT_MIN = 7;
|
||
const FONT_MAX = 20;
|
||
/** «По ширине» does not blow a narrow pane up beyond this. */
|
||
const FIT_MAX_SCALE = 1.5;
|
||
/** Horizontal padding of the terminal frame (p-1.5 on both sides + border). */
|
||
const FRAME_PAD = 14;
|
||
/** Keys a phone keyboard lacks. */
|
||
const QUICK_KEYS: Array<[string, string]> = [
|
||
["Esc", "\x1b"],
|
||
["Tab", "\t"],
|
||
["↑", "\x1b[A"],
|
||
["↓", "\x1b[B"],
|
||
["Enter", "\r"],
|
||
["Ctrl-C", "\x03"],
|
||
];
|
||
|
||
function readFit(): boolean {
|
||
try {
|
||
return localStorage.getItem(FIT_KEY) !== "0";
|
||
} catch {
|
||
return true;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* The page's monospace font as real family names: `var(--font-geist-mono)` resolved here,
|
||
* because xterm measures its cell with this string outside CSS (PEP-257).
|
||
*/
|
||
function monoFont(): string {
|
||
const v = getComputedStyle(document.documentElement).getPropertyValue("--font-geist-mono").trim();
|
||
return [v, "ui-monospace", "Menlo", '"DejaVu Sans Mono"', "monospace"].filter(Boolean).join(", ");
|
||
}
|
||
|
||
function readFont(): number {
|
||
try {
|
||
const n = Number(localStorage.getItem(FONT_KEY));
|
||
return n >= FONT_MIN && n <= FONT_MAX ? n : 12;
|
||
} catch {
|
||
return 12;
|
||
}
|
||
}
|
||
|
||
/** `fill`: the terminal takes the height of its parent (the «Сессии» page), not 60vh. */
|
||
export function RunnerTerminal({ sessionId, live, fill = false }: { sessionId: number; live: boolean; fill?: boolean }) {
|
||
const host = useRef<HTMLDivElement>(null);
|
||
const scroller = useRef<HTMLDivElement>(null);
|
||
const term = useRef<Terminal | null>(null);
|
||
const [own, setStatus] = useState<Status>("connecting");
|
||
// The channel dropped: the picture is stale until it is back (a fresh frame comes then).
|
||
const mode = useLiveMode();
|
||
const status: Status = own === "live" && mode !== "live" ? "reconnecting" : own;
|
||
const [input, setInput] = useState(false);
|
||
const [full, setFull] = useState(false);
|
||
const [font, setFont] = useState(12);
|
||
const [fit, setFit] = useState(true);
|
||
/** The panel's width and the size of the grid xterm drew (unscaled): what «по ширине» fits. */
|
||
const [width, setWidth] = useState(0);
|
||
const [grid, setGrid] = useState({ w: 0, h: 0 });
|
||
const family = useRef("monospace");
|
||
const [error, setError] = useState<string | null>(null);
|
||
const [attempt, setAttempt] = useState(0);
|
||
const t = useT();
|
||
const inputRef = useRef(false);
|
||
const queue = useRef<{ keys: string; timer: ReturnType<typeof setTimeout> | null; chain: Promise<void> }>({ keys: "", timer: null, chain: Promise.resolve() });
|
||
const scope = `terminal:${sessionId}`;
|
||
|
||
const post = useCallback(
|
||
(body: { keys?: string; paste?: string }) => {
|
||
const q = queue.current;
|
||
// Strictly one request at a time: the order of keystrokes matters.
|
||
q.chain = q.chain.then(async () => {
|
||
setError(await liveClient().input(scope, body));
|
||
});
|
||
},
|
||
[scope],
|
||
);
|
||
|
||
const sendKeys = useCallback(
|
||
(data: string) => {
|
||
const q = queue.current;
|
||
q.keys += data;
|
||
// Coalesce a burst of keystrokes into one request, keep each under the 1 KB limit.
|
||
if (q.keys.length > 256) {
|
||
if (q.timer) clearTimeout(q.timer);
|
||
q.timer = null;
|
||
post({ keys: q.keys });
|
||
q.keys = "";
|
||
return;
|
||
}
|
||
q.timer ??= setTimeout(() => {
|
||
q.timer = null;
|
||
if (q.keys) post({ keys: q.keys });
|
||
q.keys = "";
|
||
}, 25);
|
||
},
|
||
[post],
|
||
);
|
||
|
||
// xterm instance: created once per mount (xterm touches `window`, so it is imported lazily).
|
||
useEffect(() => {
|
||
let disposed = false;
|
||
let cleanup = () => {};
|
||
setFont(readFont());
|
||
setFit(readFit());
|
||
const font = monoFont();
|
||
family.current = font;
|
||
// Open only when the web font is there: xterm measures the cell once, at open.
|
||
const fonts = document.fonts;
|
||
// i18n-ignore: sample glyphs (Latin and Cyrillic) for the font loader, not a text
|
||
const ready = fonts ? Promise.race([fonts.load(`12px ${font}`, "W Ж").then(() => fonts.ready), new Promise((r) => setTimeout(r, 2000))]) : Promise.resolve();
|
||
void Promise.all([import("@xterm/xterm"), ready]).then(([{ Terminal }]) => {
|
||
if (disposed || !host.current) return;
|
||
const t = new Terminal({
|
||
cols: 120,
|
||
rows: 30,
|
||
fontSize: readFont(),
|
||
fontFamily: font,
|
||
letterSpacing: 0,
|
||
scrollback: 5000,
|
||
disableStdin: true,
|
||
cursorBlink: false,
|
||
allowProposedApi: false,
|
||
theme: { background: "#0b0b0d", foreground: "#e4e4e7", cursor: "#e4e4e7" },
|
||
});
|
||
t.open(host.current);
|
||
const onData = t.onData((d) => inputRef.current && sendKeys(d));
|
||
// xterm cannot know whether the agent turned bracketed paste on inside tmux, so a paste
|
||
// goes as one tmux paste-buffer -p instead of keystrokes (multi-line text stays one prompt).
|
||
const onPaste = (e: ClipboardEvent) => {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
const text = e.clipboardData?.getData("text/plain") ?? "";
|
||
if (inputRef.current && text) post({ paste: text });
|
||
};
|
||
const el = host.current;
|
||
el.addEventListener("paste", onPaste, true);
|
||
// A font (or a Cyrillic subset of it) loaded later: make xterm measure the cell again.
|
||
let flip = false;
|
||
const remeasure = () => {
|
||
flip = !flip;
|
||
t.options.fontFamily = flip ? `${font} ` : font;
|
||
};
|
||
fonts?.addEventListener("loadingdone", remeasure);
|
||
term.current = t;
|
||
cleanup = () => {
|
||
fonts?.removeEventListener("loadingdone", remeasure);
|
||
el.removeEventListener("paste", onPaste, true);
|
||
onData.dispose();
|
||
t.dispose();
|
||
term.current = null;
|
||
};
|
||
setAttempt((n) => n + 1);
|
||
});
|
||
return () => {
|
||
disposed = true;
|
||
cleanup();
|
||
};
|
||
}, [post, sendKeys]);
|
||
|
||
// The stream: (re)subscribed when the terminal is ready or the user asks to reconnect.
|
||
useEffect(() => {
|
||
const t = term.current;
|
||
if (!t || attempt === 0) return;
|
||
setStatus("connecting");
|
||
let stop = () => {};
|
||
stop = liveClient().subscribe(
|
||
scope,
|
||
(e) => {
|
||
if (e.type === "frame") {
|
||
t.reset();
|
||
if (t.cols !== e.cols || t.rows !== e.rows) t.resize(e.cols, e.rows);
|
||
// The pane is usually taller than the panel: show its bottom, where the agent works.
|
||
t.write(e.data, () => scroller.current && (scroller.current.scrollTop = scroller.current.scrollHeight));
|
||
setStatus("live");
|
||
} else if (e.type === "out") t.write(e.data);
|
||
else if (e.type === "end") {
|
||
setStatus("ended");
|
||
queueMicrotask(() => stop());
|
||
} else if (e.type === "error") setStatus("error");
|
||
},
|
||
{ heavy: true },
|
||
);
|
||
return () => stop();
|
||
}, [scope, attempt]);
|
||
|
||
useEffect(() => {
|
||
inputRef.current = input && live;
|
||
const t = term.current;
|
||
if (!t) return;
|
||
t.options.disableStdin = !inputRef.current;
|
||
t.options.cursorBlink = inputRef.current;
|
||
if (inputRef.current) t.focus();
|
||
}, [input, live, attempt]);
|
||
|
||
// The panel's width and the grid's size (layout size: a transform does not change it).
|
||
useEffect(() => {
|
||
const el = scroller.current;
|
||
const g = host.current;
|
||
if (!el || !g || typeof ResizeObserver === "undefined") return;
|
||
const ro = new ResizeObserver(() => {
|
||
setWidth(el.clientWidth);
|
||
setGrid({ w: g.offsetWidth, h: g.offsetHeight });
|
||
});
|
||
ro.observe(el);
|
||
ro.observe(g);
|
||
return () => ro.disconnect();
|
||
}, []);
|
||
|
||
const scale = fit && grid.w && width ? Math.min(FIT_MAX_SCALE, (width - FRAME_PAD) / grid.w) : 1;
|
||
/** The font size the user sees. */
|
||
const size = Math.round(font * scale * 10) / 10;
|
||
|
||
useEffect(() => {
|
||
const t = term.current;
|
||
if (!t || t.options.fontSize === font) return;
|
||
t.options.fontSize = font;
|
||
// Keep the bottom of the pane (where the agent works and the tmux status line is) in view.
|
||
requestAnimationFrame(() => scroller.current && (scroller.current.scrollTop = scroller.current.scrollHeight));
|
||
}, [font, attempt]);
|
||
|
||
useEffect(() => {
|
||
try {
|
||
localStorage.setItem(FONT_KEY, String(font));
|
||
localStorage.setItem(FIT_KEY, fit ? "1" : "0");
|
||
} catch {
|
||
// private mode: the size just is not remembered
|
||
}
|
||
}, [font, fit]);
|
||
|
||
/** +/-: from «по ширине» go on from the size shown now. */
|
||
const zoom = (d: number) => {
|
||
setFit(false);
|
||
setFont(Math.max(FONT_MIN, Math.min(FONT_MAX, Math.round(fit ? size : font) + d)));
|
||
};
|
||
|
||
useEffect(() => {
|
||
if (!full) return;
|
||
const onKey = (e: KeyboardEvent) => e.key === "Escape" && !inputRef.current && setFull(false);
|
||
window.addEventListener("keydown", onKey);
|
||
return () => window.removeEventListener("keydown", onKey);
|
||
}, [full]);
|
||
|
||
const btn = "inline-flex items-center gap-1 rounded-md border bg-card px-2 py-1 text-xs text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-50";
|
||
return (
|
||
<div className={cn("flex min-w-0 flex-col gap-2", fill && "h-full min-h-0", full && "fixed inset-0 z-50 bg-background p-3")} data-terminal-status={status} data-terminal-font={size}>
|
||
<div className="flex flex-wrap items-center gap-1.5">
|
||
<span className={cn("mr-auto flex items-center gap-1.5 font-mono text-[11px]", status === "live" ? "text-ok" : status === "error" ? "text-destructive" : "text-muted-foreground")}>
|
||
<span className={cn("size-1.5 rounded-full bg-current", status === "live" && "animate-pulse")} />
|
||
{t(STATUS_TEXT[status])}
|
||
</span>
|
||
{live && (
|
||
<button type="button" className={cn(btn, input && "border-primary/60 bg-primary/10 text-foreground")} onClick={() => setInput((v) => !v)} aria-pressed={input} title={t("Печатать в терминал агента")}>
|
||
<Keyboard className="size-3.5" />
|
||
{input ? t("Ввод включён") : t("Ввод")}
|
||
</button>
|
||
)}
|
||
<button type="button" className={cn(btn, fit && "border-primary/60 bg-primary/10 text-foreground")} onClick={() => setFit((v) => !v)} aria-pressed={fit} title={t("Все колонки по ширине окна")} data-terminal-fit>
|
||
<ArrowLeftRight className="size-3.5" />
|
||
{t("По ширине")}
|
||
</button>
|
||
<button type="button" className={btn} onClick={() => zoom(-1)} aria-label={t("Мельче")} title={t("Мельче")} data-terminal-zoom="-">
|
||
<Minus className="size-3.5" />
|
||
</button>
|
||
<button type="button" className={btn} onClick={() => zoom(1)} aria-label={t("Крупнее")} title={t("Крупнее")} data-terminal-zoom="+">
|
||
<Plus className="size-3.5" />
|
||
</button>
|
||
{(status === "ended" || status === "error") && (
|
||
<button type="button" className={btn} onClick={() => setAttempt((n) => n + 1)} title={t("Подключиться снова")}>
|
||
<RotateCw className="size-3.5" />
|
||
</button>
|
||
)}
|
||
<button type="button" className={btn} onClick={() => setFull((v) => !v)} aria-label={full ? t("Свернуть") : t("Во весь экран")} title={full ? t("Свернуть") : t("Во весь экран")}>
|
||
{full ? <Minimize2 className="size-3.5" /> : <Maximize2 className="size-3.5" />}
|
||
</button>
|
||
</div>
|
||
<div ref={scroller} data-terminal-scroller className={cn("overflow-auto rounded-lg border bg-[#0b0b0d] p-1.5", full || fill ? "min-h-0 flex-1" : "max-h-[60vh]", input && live && "border-primary/60")}>
|
||
{/* xterm's helper textarea and scrollbar keep offsets of the previous font size for a
|
||
moment and stuck out below the terminal (a blank strip to scroll into) — clip them. */}
|
||
<div style={scale !== 1 ? { width: grid.w * scale, height: grid.h * scale } : undefined} className="w-max overflow-hidden">
|
||
<div ref={host} className="w-max origin-top-left overflow-hidden" style={scale !== 1 ? { transform: `scale(${scale})` } : undefined} />
|
||
</div>
|
||
</div>
|
||
{input && live && (
|
||
<div className="flex flex-wrap gap-1.5">
|
||
{QUICK_KEYS.map(([label, seq]) => (
|
||
<button key={label} type="button" className={cn(btn, "font-mono")} onClick={() => sendKeys(seq)}>
|
||
{label}
|
||
</button>
|
||
))}
|
||
</div>
|
||
)}
|
||
{error && <p className="m-0 text-xs text-destructive">{t.text(error)}</p>}
|
||
{!live && <p className="m-0 text-xs text-muted-foreground">{t("Сессия завершена — только просмотр.")}</p>}
|
||
</div>
|
||
);
|
||
}
|