PEP-257: строка статуса tmux — отдельным запросом в фоне, кадр pane её не ждёт

Красные проверки: все тесты кадра терминала в CI ждали первый кадр, tmux-сервер
после этого пропадал. Запрос размера pane снова прежний (один display-message),
строка статуса читается отдельно, с таймаутом, раз в секунду и без ожидания;
сбой — кадр без строки и одно предупреждение в журнал.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
peppa-bot 2026-11-24 13:33:00 +00:00
parent a330ca575c
commit a6f38e439c
2 changed files with 72 additions and 21 deletions

View File

@ -8,6 +8,10 @@ import type { Db } from "@peppa/db";
import * as tmux from "./tmux.ts";
export const TERMINAL_POLL_MS = 250;
/** PEP-257: how often the tmux status line is re-read (its clock changes once a minute). */
const STATUS_EVERY_MS = 1000;
const STATUS_RETRY_MS = 30_000;
const STATUS_FIRST_WAIT_MS = 500;
/** Lines of pane scrollback sent in the first frame. */
export const TERMINAL_HISTORY_LINES = 1000;
export const TERMINAL_MAX_KEYS_BYTES = 1024;
@ -141,6 +145,37 @@ export class TerminalFeed {
}
}
/**
* PEP-257: the tmux status lines, refreshed in the background once per STATUS_EVERY_MS — the
* pane's picture never waits for them (the first poll gives them a short head start). A failed
* or slow query leaves the picture without them and is retried after STATUS_RETRY_MS.
*/
private bar: tmux.StatusLines = { top: false, lines: [] };
private barAt = -Infinity;
private barCols = 0;
private barJob: Promise<void> | null = null;
private barWarned = false;
private statusBar(cols: number): Promise<tmux.StatusLines> | tmux.StatusLines {
const now = Date.now();
if (!this.barJob && (now - this.barAt >= STATUS_EVERY_MS || cols !== this.barCols)) {
this.barAt = now;
this.barCols = cols;
this.barJob = tmux.statusLines(this.pane, cols).then(
(b) => void (this.bar = b),
(e: unknown) => {
// Once per feed: the reason is in the service log, the picture just goes on without the bar.
if (!this.barWarned) console.warn(`terminal ${this.name}: tmux status line unavailable: ${(e as Error).message}`);
this.barWarned = true;
this.bar = { top: false, lines: [] };
this.barAt = now + STATUS_RETRY_MS - STATUS_EVERY_MS;
},
).finally(() => (this.barJob = null));
if (this.polls === 1) return Promise.race([this.barJob, new Promise((r) => setTimeout(r, STATUS_FIRST_WAIT_MS))]).then(() => this.bar);
}
return this.bar;
}
private async tick() {
if (!this.listeners.size) return;
this.polls++;
@ -150,9 +185,10 @@ export class TerminalFeed {
const pane = await tmux.paneInfo(this.pane);
const body = fit(this.lines(await tmux.capturePaneAnsi(this.pane, 0, pane.rows - 1)), pane.rows);
// PEP-257: the status lines are part of the picture, like in a terminal attached to tmux.
const status = pane.status.lines.map((l) => this.mask(l));
screen = pane.status.top ? [...status, ...body] : [...body, ...status];
info = { ...pane, rows: pane.rows + status.length, cursorY: pane.cursorY + (pane.status.top ? status.length : 0) };
const bar = await this.statusBar(pane.cols);
const status = bar.lines.map((l) => this.mask(l));
screen = bar.top ? [...status, ...body] : [...body, ...status];
info = { ...pane, rows: pane.rows + status.length, cursorY: pane.cursorY + (bar.top ? status.length : 0) };
} catch (e) {
if (await tmux.hasSession(this.pane)) throw e;
const all = [...this.listeners];

View File

@ -189,30 +189,45 @@ export interface PaneInfo {
cursorVisible: boolean;
/** Lines in the pane's scrollback; grows when lines scroll off the top (PEP-9). */
historySize: number;
/**
* PEP-257: the tmux status lines as an attached client would see them (empty — `status off`),
* already rendered to SGR on the window width; `top` — `status-position top`.
*/
status: { top: boolean; lines: string[] };
}
/** Size, cursor and scrollback length of the session's active pane. */
export async function paneInfo(p: Pane): Promise<PaneInfo> {
const out = (await tmuxOn(p, ["display-message", "-p", "-t", `=${paneName(p)}:`, "#{pane_width} #{pane_height} #{cursor_x} #{cursor_y} #{cursor_flag} #{history_size}"])).trim();
const [cols, rows, x, y, flag, hist] = out.split(" ").map(Number);
return { cols: cols!, rows: rows!, cursorX: x!, cursorY: y!, cursorVisible: flag === 1, historySize: hist! };
}
/** Status lines tmux can have (`status` on | 2..5). */
const STATUS_MAX = 5;
/** Size, cursor, scrollback length and status line of the session's active pane — one tmux call. */
export async function paneInfo(p: Pane): Promise<PaneInfo> {
/** PEP-257: tmux status lines of a session — rendered to SGR on `cols` cells, and where they go. */
export interface StatusLines {
top: boolean;
lines: string[];
}
/**
* PEP-257: the status lines as an attached client sees them — tmux expands its own
* `status-format[i]` (`#{T:…}`), the `#[…]` styles become SGR on `cols` cells; `status off` —
* none. Separate, time-limited calls: the picture of the pane never waits for them.
*/
export async function statusLines(p: Pane, cols: number, timeoutMs = 2000): Promise<StatusLines> {
const t = `=${paneName(p)}:`;
// display-message escapes newlines and tabs in its output, so each part is its own command.
const parts = ["#{pane_width} #{pane_height} #{cursor_x} #{cursor_y} #{cursor_flag} #{history_size} #{status} #{status-position}", "#{E:status-style}"];
for (let i = 0; i < STATUS_MAX; i++) parts.push(`#{T:status-format[${i}]}`);
const args = parts.flatMap((f, i) => [...(i ? [";"] : []), "display-message", "-p", "-t", t, f]);
const out = (await tmuxOn(p, args)).split("\n");
const [cols, rows, x, y, flag, hist] = out[0]!.trim().split(" ").map(Number);
const [, , , , , , status, position] = out[0]!.trim().split(" ");
const n = status === "on" ? 1 : status === "off" || !status ? 0 : Math.min(Number(status) || 0, STATUS_MAX);
// Laid out on the pane width: that is the width of the web terminal (one pane per agent window).
const lines = Array.from({ length: n }, (_, i) => renderStatusLine(out[2 + i] ?? "", cols!, out[1] ?? ""));
return { cols: cols!, rows: rows!, cursorX: x!, cursorY: y!, cursorVisible: flag === 1, historySize: hist!, status: { top: position === "top", lines } };
const show = (f: string) => runTmux(p, ["display-message", "-p", "-t", t, f], timeoutMs).then((o) => o.replace(/\n$/, ""));
const [status, position] = (await show("#{status} #{status-position}")).trim().split(" ");
const n = status === "on" ? 1 : !status || status === "off" ? 0 : Math.min(Number(status) || 0, STATUS_MAX);
if (!n) return { top: false, lines: [] };
const style = await show("#{E:status-style}");
const lines: string[] = [];
for (let i = 0; i < n; i++) lines.push(renderStatusLine(await show(`#{T:status-format[${i}]}`), cols, style));
return { top: position === "top", lines };
}
async function runTmux(p: Pane, args: string[], timeoutMs: number): Promise<string> {
const host = paneHost(p);
const { stdout } = await runOn(host, [host ? "tmux" : TMUX(), ...SOCKET(), ...args], { timeoutMs });
return stdout;
}
/**