peppa/apps/web/components/RunnerTerminal.tsx

235 lines
9.4 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"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.
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<Status, string> = {
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<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 [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());
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 (
<div className={cn("flex flex-col gap-2", full && "fixed inset-0 z-50 bg-background p-3")} data-terminal-status={status}>
<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={btn} onClick={() => setFont((f) => Math.max(FONT_MIN, f - 1))} aria-label={t("Мельче")} title={t("Мельче")}>
<Minus className="size-3.5" />
</button>
<button type="button" className={btn} onClick={() => setFont((f) => Math.min(FONT_MAX, f + 1))} aria-label={t("Крупнее")} title={t("Крупнее")}>
<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} className={cn("overflow-auto rounded-lg border bg-[#0b0b0d] p-1.5", full ? "min-h-0 flex-1" : "max-h-[60vh]", input && live && "border-primary/60")}>
<div ref={host} className="w-max" />
</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>
);
}