repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/ultra/ui.ts

Raw
File outline
// ultra — live progress sinks (Task 7). TWO surface-specific views over the
// shared `progress.ts` reducer, render + input only, NO orchestration:
//
//   • TOOL sink  (Layer 7a) — a `renderResult(result, opts, theme, ctx)` that
//     folds NOTHING itself: it reads the reducer state off `result.details`
//     (pushed through the SDK `onUpdate` channel by the engine) and draws a
//     collapsed/expanded board. Read-only — no `controls`, no steering, and it
//     NEVER renders per-agent bodies/transcripts. Modeled on `tune`'s tools.
//
//   • COMMAND overlay (Layers 7b/7c) — a `ctx.ui.custom` `Component` that folds
//     the `onProgress` stream itself, renders the board + a focused-agent
//     drill-in transcript (follow-mode + throttle), and is the ONLY surface
//     with per-agent steering/abort. Modeled on `devil/ui.ts`.
//
// Both sinks consume only what `progress.ts` defines; this module never
// constructs an SDK session and never holds orchestration logic.

import type {
	AgentToolResult,
	Theme,
	ToolRenderResultOptions,
} from "@earendil-works/pi-coding-agent";
import {
	getMarkdownTheme,
	keyHint,
	ToolExecutionComponent,
} from "@earendil-works/pi-coding-agent";
import {
	type Component,
	Markdown,
	matchesKey,
	type TUI,
	truncateToWidth,
} from "@earendil-works/pi-tui";
import {
	type AgentControls,
	type AgentStatus,
	initialReducerState,
	type PlannedPhase,
	type ReducerState,
	reduceProgress,
	type TranscriptItem,
	type UltraProgressEvent,
} from "./progress.ts";

// ---------------------------------------------------------------------------
// Shared board helpers (used by both sinks)
// ---------------------------------------------------------------------------

const STATUS_ICON: Record<AgentStatus, string> = {
	queued: "󰅐",
	running: "󰐌",
	done: "󰗠",
	dropped: "󰅙",
};

const PHASE_ICON = {
	"agents-pending": "󰭙",
	"condition-pending": "󰘬",
	skipped: "−",
} as const;

const RESET = /\x1b\[0m/g;

function fitLine(text: string, width: number): string {
	const w = Math.max(1, width);
	const out = truncateToWidth(text, w);
	return text.includes("\x1b") ? out : out.replace(RESET, "");
}

/** `phase N/len` from the reducer's ordered phase plan. */
function phaseCounter(state: ReducerState): string {
	if (state.phases.length === 0) return "";
	const idx = state.phase
		? state.phases.findIndex((phase) => phase.phase === state.phase) + 1
		: 0;
	return `phase ${idx}/${state.phases.length}`;
}

/** One-line aggregate with terminal, active, queued, and later work counts. */
function summaryLine(state: ReducerState): string {
	const parts: string[] = [];
	const pc = phaseCounter(state);
	if (pc) parts.push(pc);
	parts.push(`${state.done}/${state.total} done`);
	if (state.running > 0) parts.push(`${state.running} active`);
	if (state.queued > 0) parts.push(`${state.queued} queued`);
	if (state.later > 0)
		parts.push(`${state.later} later phase${state.later === 1 ? "" : "s"}`);
	if (state.dropped > 0) parts.push(`${state.dropped}✗`);
	return parts.join(" · ");
}

function headerLine(state: ReducerState): string {
	const wallTime =
		state.startedAt === undefined
			? undefined
			: `${elapsed(state.startedAt, state.endedAt)} elapsed`;
	return ["ultra", state.workflowName, wallTime].filter(Boolean).join(" · ");
}

function descriptionLine(state: ReducerState): string | undefined {
	return state.workflowDescription;
}

function compactTokens(tokens: number): string {
	if (tokens < 1000) return String(tokens);
	const value = tokens / 1000;
	return `${value >= 10 ? Math.round(value) : value.toFixed(1).replace(/\.0$/, "")}k`;
}

function elapsed(startedAt: number, endedAt = Date.now()): string {
	const seconds = Math.max(0, Math.floor((endedAt - startedAt) / 1000));
	if (seconds < 60) return `${seconds}s`;
	return `${Math.floor(seconds / 60)}m ${seconds % 60}s`;
}

function agentDetailLines(row: ReducerState["rows"][number]): string[] {
	const details: { label: string; value: string }[] = [];
	const failureModel = row.failure?.model;
	const model = row.tier
		? `${row.tier}${row.model ? ` → ${row.model}` : ""}`
		: (row.model ?? failureModel);
	const thinkingLevel = row.thinkingLevel ?? row.failure?.thinkingLevel;
	const modelValue = [model, thinkingLevel].filter(Boolean).join(" · ");
	if (modelValue) details.push({ label: "model", value: modelValue });
	const usageValue = [
		row.startedAt === undefined
			? undefined
			: elapsed(row.startedAt, row.endedAt),
		row.usage ? `${compactTokens(row.usage.total)} tokens` : undefined,
	]
		.filter(Boolean)
		.join(" · ");
	if (usageValue) details.push({ label: "usage", value: usageValue });
	if (row.failure) {
		details.push({
			label: "failure",
			value: `${row.failure.code}: ${row.failure.message}`,
		});
		details.push({
			label: "retry",
			value: `${row.failure.retryable ? "retryable" : "terminal"} · ${row.failure.attempts} attempt${row.failure.attempts === 1 ? "" : "s"}`,
		});
		if (row.item !== undefined)
			details.push({ label: "item", value: JSON.stringify(row.item) });
		if (row.failure.transcriptTail)
			details.push({ label: "tail", value: row.failure.transcriptTail });
	}
	if (row.action) details.push({ label: "action", value: row.action });
	return details.map(
		(detail, index) =>
			`${index === details.length - 1 ? "└" : "├"} ${detail.label.padEnd(6)} ${detail.value}`,
	);
}

type DisplayRow =
	| { kind: "agent"; row: ReducerState["rows"][number] }
	| { kind: "phase"; phase: PlannedPhase };

function displayRows(state: ReducerState): DisplayRow[] {
	const out: DisplayRow[] = [];
	const seen = new Set<string>();
	for (const phase of state.phases) {
		const rows = state.rows.filter((row) => row.phase === phase.phase);
		if (
			phase.status === "agents-pending" ||
			phase.status === "condition-pending" ||
			phase.status === "skipped" ||
			(phase.status === "done" && rows.length === 0)
		) {
			out.push({ kind: "phase", phase });
			continue;
		}
		for (const row of rows) {
			seen.add(row.agentId);
			out.push({ kind: "agent", row });
		}
	}
	for (const row of state.rows) {
		if (!seen.has(row.agentId)) out.push({ kind: "agent", row });
	}
	return out;
}

function phaseLabel(phase: PlannedPhase): string {
	switch (phase.status) {
		case "agents-pending":
			return `${PHASE_ICON[phase.status]} ${phase.phase} · agents not planned yet`;
		case "condition-pending":
			return `${PHASE_ICON[phase.status]} ${phase.phase} · conditional`;
		case "skipped":
			return `${PHASE_ICON[phase.status]} ${phase.phase} · skipped`;
		case "done":
			return `󰗠 ${phase.phase} · done · no agents`;
		case "resolved":
			return phase.phase;
	}
}

function phaseDetail(phase: PlannedPhase): string | undefined {
	if (phase.status === "agents-pending")
		return "earlier results determine which agents are needed";
	if (phase.status === "condition-pending")
		return "earlier results determine whether this phase runs";
	return undefined;
}

function queuedDetail(state: ReducerState, phase: string): string {
	return state.phase === phase
		? "waiting for concurrency slot"
		: "starts when phase begins";
}

function divider(label: string, width: number): string {
	const w = Math.max(1, width);
	const text = ` ${label} `;
	if (text.length >= w) return fitLine(label, w);
	const left = Math.floor((w - text.length) / 2);
	const right = w - text.length - left;
	return `${"─".repeat(left)}${text}${"─".repeat(right)}`;
}

/** The collapsed expand hint. Guarded: `keyHint` needs an initialised theme. */
function expandHint(): string {
	try {
		return keyHint("app.tools.expand", "to expand");
	} catch {
		return "to expand";
	}
}

// ---------------------------------------------------------------------------
// Layer 7a — TOOL sink: `renderResult` over the reducer state
// ---------------------------------------------------------------------------

/**
 * Pure board renderer for the tool surface. Collapsed = aggregate counts +
 * one-line summary + the expand hint (NEVER any per-agent line or transcript
 * body). Expanded = multiline per-agent identity, model/usage metadata, and latest
 * action, with dropped agents surfaced. The drill-in transcript is the OVERLAY's job, never the tool sink's,
 * so `state.transcripts` is intentionally never read here.
 */
function renderToolBoard(
	state: ReducerState,
	options: ToolRenderResultOptions,
	theme: Theme,
	width: number,
): string[] {
	const w = Math.max(1, width);
	const lines: string[] = [];

	const runMark = options.isPartial ? "⏳ " : "";
	lines.push(theme.fg("accent", fitLine(`${runMark}${headerLine(state)}`, w)));
	lines.push(theme.fg("muted", fitLine(summaryLine(state), w)));
	const description = descriptionLine(state);
	if (description) lines.push(theme.fg("muted", fitLine(description, w)));

	if (!options.expanded) {
		// Collapsed: summary + expand hint only. No bodies, ever.
		lines.push(theme.fg("muted", fitLine(expandHint(), w)));
		return lines.map((l) => fitLine(l, w));
	}

	// Expanded: specification order, including non-agent planning rows.
	for (const display of displayRows(state)) {
		if (display.kind === "phase") {
			lines.push(theme.fg("dim", fitLine(phaseLabel(display.phase), w)));
			const detail = phaseDetail(display.phase);
			if (detail) lines.push(theme.fg("muted", fitLine(`  └ ${detail}`, w)));
			continue;
		}
		const { row } = display;
		const icon = STATUS_ICON[row.status];
		let identity = `${icon} ${row.agentId} · ${row.status}`;
		if (row.status === "queued")
			identity += ` · ${queuedDetail(state, row.phase)}`;
		lines.push(theme.fg("dim", fitLine(identity, w)));
		for (const detail of agentDetailLines(row)) {
			lines.push(theme.fg("muted", fitLine(`  ${detail}`, w)));
		}
	}

	return lines.map((l) => fitLine(l, w));
}

/**
 * A throwaway `Component` that draws the tool-surface board for ONE render.
 * It holds no cache: every `render(width)` recomputes from the snapshot it was
 * built with, so a fresh `renderResult` call (one per `onUpdate`, P2) with fresh
 * `details` always tracks the latest reducer state (no frozen snapshot).
 */
class UltraResultComponent implements Component {
	constructor(
		private readonly state: ReducerState,
		private readonly options: ToolRenderResultOptions,
		private readonly theme: Theme,
	) {}

	render(width: number): string[] {
		return renderToolBoard(this.state, this.options, this.theme, width);
	}

	invalidate(): void {
		// No cached state — nothing to drop.
	}
}

/**
 * Accept `result.details` only when it structurally IS a reducer state. It
 * reaches us over an SDK-controlled channel (structured-cloned per `onUpdate`
 * tick, and re-hydrated from session persistence on resume), so a truthy-but-
 * foreign value can arrive — a resumed/foreign tool result, a payload from
 * another producer, a serialization wrapper. The board reads `state.phases`
 * and `state.rows` unguarded, so anything lacking them falls back to an empty
 * board. This is the single choke point: an uncaught throw in `renderResult`
 * escapes tool-error handling and crashes the whole TUI render loop.
 */
function asReducerState(details: unknown): ReducerState {
	const d = details as Partial<ReducerState> | null | undefined;
	const phaseStatuses: readonly string[] = [
		"resolved",
		"agents-pending",
		"condition-pending",
		"done",
		"skipped",
	];
	const agentStatuses: readonly string[] = [
		"queued",
		"running",
		"done",
		"dropped",
	];
	const phasesValid =
		Array.isArray(d?.phases) &&
		d.phases.every(
			(phase) =>
				typeof phase === "object" &&
				phase !== null &&
				typeof phase.phase === "string" &&
				phaseStatuses.includes(phase.status) &&
				Array.isArray(phase.agentIds) &&
				phase.agentIds.every((agentId: unknown) => typeof agentId === "string"),
		);
	const rowsValid =
		Array.isArray(d?.rows) &&
		d.rows.every(
			(row) =>
				typeof row === "object" &&
				row !== null &&
				typeof row.agentId === "string" &&
				typeof row.phase === "string" &&
				agentStatuses.includes(row.status),
		);
	return d && phasesValid && rowsValid
		? (d as ReducerState)
		: initialReducerState();
}

/**
 * Tool-surface `renderResult`: reads the reducer state off `result.details`
 * (pushed through `onUpdate`) and returns a board `Component`. Read-only — no
 * `controls`, no steering. Assignable to `ToolDefinition.renderResult` (the
 * unused 4th `context` arg is accepted but never read on this surface).
 */
export function renderUltraResult(
	result: AgentToolResult<ReducerState>,
	options: ToolRenderResultOptions,
	theme: Theme,
	_context?: unknown,
): Component {
	return new UltraResultComponent(
		asReducerState(result?.details),
		options,
		theme,
	);
}

// ---------------------------------------------------------------------------
// Layers 7b/7c — COMMAND overlay: board + drill-in transcript + steer/abort
// ---------------------------------------------------------------------------

/**
 * Per-agent controls as the OVERLAY consumes them. Extends the locked
 * `AgentControls` (`{steer, abort}`) with an optional `followUp` for re-prompting
 * an agent that has already finished. The runner binds `followUp` on a finished
 * agent's controls (cross-task contract — see module notes); when absent the
 * follow-up affordance is simply inert.
 */
export interface OverlayAgentControls extends AgentControls {
	followUp?(text: string): Promise<void> | void;
}

/**
 * Minimal host surface the overlay needs. The real `TUI` (passed by
 * `ctx.ui.custom`) satisfies this structurally; tests inject a fake with a
 * `requestRender` spy + a fixed terminal size.
 */
export interface OverlayHost {
	requestRender(): void;
	terminal: { rows: number; columns: number };
}

export interface UltraOverlayOptions {
	host: OverlayHost;
	theme: Theme;
	/** Global `Esc` → run-level abort (the command path's own AbortController). */
	onRunAbort: () => void;
	/** Injectable clock for the render throttle (default `Date.now`). */
	now?: () => number;
	/** Render-throttle window in ms (default 80, matching devil). */
	throttleMs?: number;
	workflowName?: string;
	workflowDescription?: string;
	/** Optional Pi TUI handle; when present, tool transcript rows use Pi's native tool renderer. */
	toolUi?: TUI;
	cwd?: string;
}

const DEFAULT_THROTTLE_MS = 80;

/** Render transcript markdown with Pi's own markdown renderer. */
function transcriptLines(text: string, width: number): string[] {
	if (!text) return [];
	return new Markdown(text, 0, 0, getMarkdownTheme()).render(
		Math.max(1, width),
	);
}

function normalizeToolResult(item: TranscriptItem & { kind: "tool" }) {
	const r = item.result as
		| { content?: unknown; details?: unknown; isError?: boolean }
		| undefined;
	const content = Array.isArray(r?.content)
		? (r.content as Array<{
				type: string;
				text?: string;
				data?: string;
				mimeType?: string;
			}>)
		: item.fallback
			? [{ type: "text", text: item.fallback }]
			: [];
	return {
		content,
		details: r?.details,
		isError: item.isError ?? r?.isError ?? false,
	};
}

/**
 * The `ctx.ui.custom` overlay (command surface only). Folds the `onProgress`
 * stream with the shared reducer, renders the board + a focused-agent drill-in
 * transcript (follow-mode), and exposes per-agent steer/abort + global abort.
 * Render + input only: it holds NO orchestration — the run is driven elsewhere
 * and pushes events in via `handleProgress`.
 */
export class UltraOverlayComponent implements Component {
	private state: ReducerState;
	private focusIndex = 0;
	private followMode = true;
	private scrollOffset = 0;
	private lastMaxScroll = 0;
	private lastRenderAt = Number.NEGATIVE_INFINITY;
	private steerMode = false;
	private steerBuffer = "";
	private steeredFlag = false;

	private readonly host: OverlayHost;
	private readonly theme: Theme;
	private readonly onRunAbort: () => void;
	private readonly now: () => number;
	private readonly throttleMs: number;
	private readonly toolUi: TUI | undefined;
	private readonly cwd: string | undefined;

	constructor(options: UltraOverlayOptions) {
		this.state = initialReducerState({
			workflowName: options.workflowName,
			workflowDescription: options.workflowDescription,
		});
		this.host = options.host;
		this.theme = options.theme;
		this.onRunAbort = options.onRunAbort;
		this.now = options.now ?? Date.now;
		this.throttleMs = options.throttleMs ?? DEFAULT_THROTTLE_MS;
		this.toolUi = options.toolUi;
		this.cwd = options.cwd;
	}

	/** True once the human has submitted a steer this run (enqueue-time taint). */
	get steered(): boolean {
		return this.steeredFlag;
	}

	/** Test/inspection accessor for the folded reducer state. */
	get reducerState(): ReducerState {
		return this.state;
	}

	// ---- progress sink: fold + throttled re-render -----------------------

	handleProgress(event: UltraProgressEvent): void {
		const previousPhase = this.state.phase;
		this.state = reduceProgress(this.state, event);
		if (event.kind === "start" && event.phase !== previousPhase) {
			const nextFocus = this.state.rows.findIndex(
				(row) => row.agentId === event.agentId,
			);
			if (nextFocus >= 0) {
				this.focusIndex = nextFocus;
				this.followMode = true;
				this.scrollOffset = 0;
			}
		}
		if (this.focusIndex >= this.state.rows.length) {
			this.focusIndex = Math.max(0, this.state.rows.length - 1);
		}
		const now = this.now();
		// Terminal events bypass the throttle so the final board is never lost
		// behind the render window.
		const force = event.kind === "end" || event.kind === "phase";
		if (force || now - this.lastRenderAt >= this.throttleMs) {
			this.lastRenderAt = now;
			this.host.requestRender();
		}
	}

	// ---- input ------------------------------------------------------------

	handleInput(data: string): void {
		if (this.steerMode) {
			this.handleSteerInput(data);
			return;
		}
		if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
			this.onRunAbort();
			return;
		}
		if (matchesKey(data, "tab")) {
			this.focusBy(1, true);
		} else if (matchesKey(data, "down")) {
			this.focusBy(1, false);
		} else if (matchesKey(data, "up")) {
			this.focusBy(-1, false);
		} else if (
			matchesKey(data, "pageUp") ||
			matchesKey(data, "alt+up") ||
			matchesKey(data, "ctrl+u")
		) {
			this.scrollBy(-10);
		} else if (
			matchesKey(data, "pageDown") ||
			matchesKey(data, "alt+down") ||
			matchesKey(data, "ctrl+d")
		) {
			this.scrollBy(10);
		} else if (data === "s") {
			this.openSteer();
		} else if (data === "x") {
			this.abortFocused();
		}
	}

	private focusBy(delta: number, wrap: boolean): void {
		const n = this.state.rows.length;
		if (n === 0) return;
		this.focusIndex = wrap
			? (this.focusIndex + delta + n) % n
			: Math.min(n - 1, Math.max(0, this.focusIndex + delta));
		// New agent → re-pin its transcript to newest.
		this.followMode = true;
		this.scrollOffset = 0;
		this.host.requestRender();
	}

	private scrollBy(delta: number): void {
		if (delta < 0) {
			this.followMode = false;
			this.scrollOffset = Math.max(0, this.scrollOffset + delta);
		} else {
			this.scrollOffset += delta;
			if (this.scrollOffset >= this.lastMaxScroll) this.followMode = true;
		}
		this.host.requestRender();
	}

	private focusedRow() {
		return this.state.rows[this.focusIndex];
	}

	private openSteer(): void {
		if (this.state.rows.length === 0) return;
		this.steerMode = true;
		this.steerBuffer = "";
		this.host.requestRender();
	}

	private abortFocused(): void {
		const controls = this.focusedRow()?.controls as
			| OverlayAgentControls
			| undefined;
		if (controls?.abort) void Promise.resolve(controls.abort()).catch(() => {});
	}

	private handleSteerInput(data: string): void {
		if (matchesKey(data, "escape")) {
			// Cancel the buffer back to normal mode — does NOT abort the run.
			this.steerMode = false;
			this.steerBuffer = "";
			this.host.requestRender();
			return;
		}
		if (matchesKey(data, "return") || matchesKey(data, "enter")) {
			this.submitSteer();
			return;
		}
		if (matchesKey(data, "backspace")) {
			this.steerBuffer = this.steerBuffer.slice(0, -1);
			this.host.requestRender();
			return;
		}
		// Accept a single printable character (excludes control bytes + DEL).
		if (data.length === 1) {
			const code = data.charCodeAt(0);
			if (code >= 0x20 && code !== 0x7f) {
				this.steerBuffer += data;
				this.host.requestRender();
			}
		}
	}

	private submitSteer(): void {
		const text = this.steerBuffer;
		const row = this.focusedRow();
		this.steerMode = false;
		this.steerBuffer = "";
		this.host.requestRender();
		if (!row || !text) return;
		const controls = row.controls as OverlayAgentControls | undefined;
		if (row.status === "running") {
			// Taint the run synchronously, at enqueue time (before the steer
			// promise settles) — this is what the test asserts and what v2
			// caching keys off.
			this.steeredFlag = true;
			if (controls?.steer)
				void Promise.resolve(controls.steer(text)).catch(() => {});
		} else {
			// A finished agent is re-prompted as a follow-up, not steered.
			if (controls?.followUp)
				void Promise.resolve(controls.followUp(text)).catch(() => {});
		}
	}

	private transcriptBodyLines(
		agentId: string | undefined,
		width: number,
	): string[] {
		if (!agentId) return [];
		const items = this.state.transcriptItems[agentId];
		if (!items || items.length === 0) {
			return transcriptLines(this.state.transcripts[agentId] ?? "", width);
		}
		const lines: string[] = [];
		let text = "";
		const flushText = () => {
			if (!text) return;
			lines.push(...transcriptLines(text, width));
			text = "";
		};
		for (const item of items) {
			if (item.kind === "text") {
				text += item.text;
				continue;
			}
			flushText();
			if (this.toolUi && this.cwd) {
				const tool = new ToolExecutionComponent(
					item.toolName,
					item.toolCallId ?? `${agentId}-${lines.length}`,
					item.args ?? {},
					undefined,
					undefined,
					this.toolUi,
					this.cwd,
				);
				tool.markExecutionStarted();
				tool.setArgsComplete();
				if (item.result !== undefined)
					tool.updateResult(normalizeToolResult(item));
				lines.push(...tool.render(width));
			} else if (item.fallback) {
				lines.push(...transcriptLines(`> ${item.fallback}`, width));
			}
		}
		flushText();
		return lines;
	}

	// ---- render -----------------------------------------------------------

	render(width: number): string[] {
		const w = Math.max(1, width);
		const state = this.state;
		const lines: string[] = [];

		lines.push(this.theme.fg("accent", fitLine(headerLine(state), w)));
		lines.push(this.theme.fg("muted", fitLine(summaryLine(state), w)));
		const description = descriptionLine(state);
		if (description)
			lines.push(this.theme.fg("muted", fitLine(description, w)));

		const maxLines = Math.max(1, this.host.terminal.rows - 3);
		const fixedAfterRows = 3; // border + transcript title + footer
		const display = displayRows(state);
		const maxWorkRows = Math.min(
			display.length,
			Math.max(0, maxLines - lines.length - fixedAfterRows),
		);
		const focusedId = this.focusedRow()?.agentId;
		const focusedDisplay = display.findIndex(
			(item) => item.kind === "agent" && item.row.agentId === focusedId,
		);
		const rowStart =
			maxWorkRows >= display.length
				? 0
				: Math.min(
						Math.max(0, focusedDisplay - Math.floor(maxWorkRows / 2)),
						Math.max(0, display.length - maxWorkRows),
					);
		for (const item of display.slice(rowStart, rowStart + maxWorkRows)) {
			if (item.kind === "phase") {
				lines.push(
					this.theme.fg("dim", fitLine(`  ${phaseLabel(item.phase)}`, w)),
				);
				const detail = phaseDetail(item.phase);
				if (detail)
					lines.push(this.theme.fg("muted", fitLine(`    └ ${detail}`, w)));
				continue;
			}
			const { row } = item;
			const focused = row.agentId === focusedId;
			const marker = focused ? "▶" : " ";
			const icon = STATUS_ICON[row.status];
			let line = `${marker} ${icon} ${row.agentId} · ${row.status}`;
			if (row.status === "queued")
				line += ` · ${queuedDetail(state, row.phase)}`;
			if (row.action) line += ` · ${row.action}`;
			lines.push(this.theme.fg(focused ? "accent" : "dim", fitLine(line, w)));
		}

		const focusedRow = this.focusedRow();
		lines.push(
			this.theme.fg(
				"border",
				divider(`transcript: ${focusedRow ? focusedRow.agentId : "—"}`, w),
			),
		);

		const body = this.transcriptBodyLines(focusedRow?.agentId, w - 2);

		// Reserve the footer and keep a 3-row terminal safety margin.
		const maxVisible = Math.max(0, maxLines - lines.length - 1);
		const maxScroll = Math.max(0, body.length - maxVisible);
		this.lastMaxScroll = maxScroll;
		if (this.followMode) this.scrollOffset = maxScroll;
		this.scrollOffset = Math.min(Math.max(0, this.scrollOffset), maxScroll);
		for (const l of body.slice(
			this.scrollOffset,
			this.scrollOffset + maxVisible,
		)) {
			lines.push(this.theme.fg("dim", fitLine(`  ${l}`, w)));
		}

		if (this.steerMode) {
			const verb =
				focusedRow && focusedRow.status === "running" ? "steer" : "follow-up";
			lines.push(
				this.theme.fg(
					"warning",
					fitLine(
						`${verb} ${focusedRow?.agentId ?? ""}> ${this.steerBuffer}`,
						w,
					),
				),
			);
		} else {
			const follow = this.followMode ? "follow" : "paused";
			lines.push(
				this.theme.fg(
					"dim",
					fitLine(
						`Tab/↑↓ focus · Alt+↑/↓ scroll (${follow}) · s steer · x abort · Esc quit`,
						w,
					),
				),
			);
		}

		return lines.map((l) => fitLine(l, w));
	}

	invalidate(): void {
		// No cached render state to drop.
	}
}