"use client"; // Live runner terminal (PEP-9): xterm.js fed by the tab's live channel (`terminal:`, PEP-225), // input over the same channel; without a WebSocket — SSE of /api/runners//terminal and POST. import "@xterm/xterm/css/xterm.css"; import type { Terminal } from "@xterm/xterm"; import { 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 = { connecting: m("подключение…"), live: m("в эфире"), reconnecting: m("переподключение…"), ended: m("tmux-сессии нет"), error: m("нет доступа к терминалу"), }; const FONT_KEY = "peppa_term_font"; const FONT_MIN = 7; const FONT_MAX = 20; /** 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 readFont(): number { try { const n = Number(localStorage.getItem(FONT_KEY)); return n >= FONT_MIN && n <= FONT_MAX ? n : 12; } catch { return 12; } } export function RunnerTerminal({ sessionId, live }: { sessionId: number; live: boolean }) { const host = useRef(null); const scroller = useRef(null); const term = useRef(null); const [own, setStatus] = useState("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 [error, setError] = useState(null); const [attempt, setAttempt] = useState(0); const t = useT(); const inputRef = useRef(false); const queue = useRef<{ keys: string; timer: ReturnType | null; chain: Promise }>({ 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()); void import("@xterm/xterm").then(({ Terminal }) => { if (disposed || !host.current) return; const t = new Terminal({ cols: 120, rows: 30, fontSize: readFont(), fontFamily: "var(--font-geist-mono), ui-monospace, Menlo, monospace", 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); term.current = t; cleanup = () => { 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]); useEffect(() => { if (term.current) term.current.options.fontSize = font; try { localStorage.setItem(FONT_KEY, String(font)); } catch { // private mode: the size just is not remembered } }, [font]); 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 (
{t(STATUS_TEXT[status])} {live && ( )} {(status === "ended" || status === "error") && ( )}
{input && live && (
{QUICK_KEYS.map(([label, seq]) => ( ))}
)} {error &&

{t.text(error)}

} {!live &&

{t("Сессия завершена — только просмотр.")}

}
); }