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 ReducerState,
	reduceProgress,
	type TranscriptItem,
	type UltraProgressEvent,
} from "./progress.ts";

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

const STATUS_ICON: Record<AgentStatus, string> = {
	running: "●",
	done: "✓",
	dropped: "✗",
};

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 list (empty until a phase arrives). */
function phaseCounter(state: ReducerState): string {
	if (state.phases.length === 0) return "";
	const idx = state.phase ? state.phases.indexOf(state.phase) + 1 : 0;
	return `phase ${idx}/${state.phases.length}`;
}

/** One-line aggregate: `phase N/len · done/total done · K✗`. */
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.dropped > 0) parts.push(`${state.dropped}✗`);
	return parts.join(" · ");
}

function headerLine(state: ReducerState): string {
	return ["ultra", state.workflowName, summaryLine(state)]
		.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): string {
	const seconds = Math.max(0, Math.floor((Date.now() - 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 model = row.tier
		? `${row.tier}${row.model ? ` → ${row.model}` : ""}`
		: row.model;
	const modelValue = [model, row.thinkingLevel].filter(Boolean).join(" · ");
	if (modelValue) details.push({ label: "model", value: modelValue });
	const usageValue = [
		row.startedAt === undefined ? undefined : elapsed(row.startedAt),
		row.usage ? `${compactTokens(row.usage.total)} tokens` : undefined,
	]
		.filter(Boolean)
		.join(" · ");
	if (usageValue) details.push({ label: "usage", value: usageValue });
	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}`,
	);
}

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)));
	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: identity first, then an indented metadata/action tree.
	for (const row of state.rows) {
		const icon = STATUS_ICON[row.status];
		lines.push(
			theme.fg("dim", fitLine(`${icon} ${row.agentId} · ${row.status}`, 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;
	return d && Array.isArray(d.phases) && Array.isArray(d.rows)
		? (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";
		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)));
		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 maxAgentRows = Math.min(
			state.rows.length,
			Math.max(0, maxLines - lines.length - fixedAfterRows),
		);
		const rowStart =
			maxAgentRows >= state.rows.length
				? 0
				: Math.min(
						Math.max(0, this.focusIndex - Math.floor(maxAgentRows / 2)),
						Math.max(0, state.rows.length - maxAgentRows),
					);
		state.rows
			.slice(rowStart, rowStart + maxAgentRows)
			.forEach((row, offset) => {
				const i = rowStart + offset;
				const focused = i === this.focusIndex;
				const marker = focused ? "▶" : " ";
				const icon = STATUS_ICON[row.status];
				let line = `${marker} ${icon} ${row.agentId} · ${row.status}`;
				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.
	}
}