repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/devil/ui.ts

Raw
import type { Theme } from "@earendil-works/pi-coding-agent";
import {
	type Component,
	matchesKey,
	type TUI,
	truncateToWidth,
	visibleWidth,
	wrapTextWithAnsi,
} from "@earendil-works/pi-tui";
import { cleanTranscriptText } from "./helpers";
import type { DebateOutput } from "./types";

export type DebateRole = "devil" | "proposer";

export interface DebateTranscriptEntry {
	role: DebateRole;
	round: number;
	text: string;
	blocking: number;
	final: boolean;
}

export interface DebateLiveState {
	idea: string;
	maxRounds: number;
	status: string;
	currentRound: number;
	blocking: number;
	entries: DebateTranscriptEntry[];
	startedAt: number;
	error?: string;
}

export function createDebateState(
	idea: string,
	maxRounds: number,
): DebateLiveState {
	return {
		idea,
		maxRounds,
		status: "Starting debate...",
		currentRound: 0,
		blocking: 0,
		entries: [],
		startedAt: Date.now(),
	};
}

export function setDebateStatus(
	state: DebateLiveState,
	status: string,
	round: number,
	blocking: number,
) {
	state.status = status;
	state.currentRound = round;
	state.blocking = blocking;
}

export function upsertDebateEntry(
	state: DebateLiveState,
	role: DebateRole,
	round: number,
	blocking: number,
	text: string,
	final: boolean,
) {
	state.currentRound = round;
	state.blocking = blocking;
	const existing = state.entries.find(
		(entry) => entry.role === role && entry.round === round,
	);
	if (existing) {
		existing.blocking = blocking;
		existing.text = text;
		existing.final = final;
		return;
	}
	state.entries.push({ role, round, blocking, text, final });
}

// ── State helpers ───────────────────────────────────────────────────

function padToWidth(line: string, width: number): string {
	const target = Math.max(0, width);
	const truncated = truncateToWidth(line, target);
	return truncated + " ".repeat(Math.max(0, target - visibleWidth(truncated)));
}

function frameLine(
	theme: Theme,
	left: string,
	content: string,
	right: string,
	width: number,
): string {
	if (width <= 0) return "";
	if (width === 1) return truncateToWidth(theme.fg("border", left), width);
	const innerWidth = Math.max(0, width - 2);
	return truncateToWidth(
		theme.fg("border", left) +
			padToWidth(content, innerWidth) +
			theme.fg("border", right),
		width,
	);
}

export function renderDebateTranscript(
	state: DebateLiveState,
	theme: Theme,
	width: number,
	options: { compact: boolean; maxBodyLines: number },
): string[] {
	if (width <= 0) return [""];
	const lines: string[] = [];
	const usableWidth = width;
	const elapsed = Math.floor((Date.now() - state.startedAt) / 1000);
	const blocking =
		state.blocking === 1 ? "1 blocking" : `${state.blocking} blocking`;
	const header = `${state.status} · ${blocking} · ${elapsed}s`;
	lines.push(theme.fg("accent", truncateToWidth(header, usableWidth)));

	if (state.error) {
		lines.push(
			theme.fg("warning", truncateToWidth("⚠ Debate failed", usableWidth)),
		);
		const bodyWidth = Math.max(20, usableWidth - 2);
		for (const line of wrapTextWithAnsi(
			theme.fg("dim", state.error),
			bodyWidth,
		)) {
			lines.push(truncateToWidth(`  ${line}`, usableWidth));
		}
	}

	const entries = options.compact ? state.entries.slice(-2) : state.entries;
	if (entries.length === 0) {
		if (!state.error)
			lines.push(
				theme.fg(
					"dim",
					truncateToWidth("  Waiting for first challenge...", usableWidth),
				),
			);
		return lines.map((line) => truncateToWidth(line, usableWidth));
	}

	for (const entry of entries) {
		const icon = entry.role === "devil" ? "⚑" : "✓";
		const label = entry.role === "devil" ? "Devil" : "Defense";
		const stateLabel = entry.final ? "final" : "streaming…";
		lines.push(
			theme.fg(
				entry.role === "devil" ? "warning" : "success",
				truncateToWidth(
					`${icon} R${entry.round} ${label} · ${stateLabel}`,
					usableWidth,
				),
			),
		);

		const bodyWidth = Math.max(1, usableWidth - 2);
		const body = cleanTranscriptText(entry.text, options.compact ? 700 : 20000);
		const wrapped = wrapTextWithAnsi(theme.fg("dim", body), bodyWidth).slice(
			0,
			options.maxBodyLines,
		);
		for (const line of wrapped)
			lines.push(truncateToWidth(`  ${line}`, usableWidth));
	}

	return lines.map((line) => truncateToWidth(line, usableWidth));
}

export class DebateReviewComponent implements Component {
	private scrollOffset = 0;
	private followMode = true;
	private finished = false;
	private failed = false;
	private disposed = false;
	private lastMaxScroll = 0;
	private cachedBodyWidth?: number;
	private cachedBodyKey?: string;
	private cachedBody?: string[];

	constructor(
		private tui: TUI,
		private theme: Theme,
		private state: DebateLiveState,
		private done: (output: DebateOutput | null) => void,
		private controller: AbortController,
	) {}

	get signal(): AbortSignal {
		return this.controller.signal;
	}

	isActive(): boolean {
		return (
			!this.finished && !this.failed && !this.disposed && !this.signal.aborted
		);
	}

	cancel() {
		this.controller.abort();
		this.finish(null);
	}

	finish(output: DebateOutput | null) {
		if (this.finished || this.disposed) return;
		if (output === null) this.controller.abort();
		this.finished = true;
		this.done(output);
	}

	fail() {
		if (this.finished || this.disposed) return;
		this.failed = true;
		this.invalidate();
		this.tui.requestRender();
	}

	refresh() {
		if (this.finished || this.disposed) return;
		this.tui.requestRender();
	}

	handleInput(data: string): void {
		if (
			matchesKey(data, "escape") ||
			matchesKey(data, "ctrl+c") ||
			data === "q"
		) {
			this.cancel();
			return;
		}
		if (matchesKey(data, "up") || data === "k") {
			this.followMode = false;
			this.scrollOffset = Math.max(0, this.scrollOffset - 1);
			this.refresh();
			return;
		}
		if (matchesKey(data, "down") || data === "j") {
			this.scrollOffset++;
			if (this.scrollOffset >= this.lastMaxScroll) this.followMode = true;
			this.refresh();
			return;
		}
		if (matchesKey(data, "pageUp") || matchesKey(data, "ctrl+u")) {
			this.followMode = false;
			this.scrollOffset = Math.max(0, this.scrollOffset - 10);
			this.refresh();
			return;
		}
		if (matchesKey(data, "pageDown") || matchesKey(data, "ctrl+d")) {
			this.scrollOffset += 10;
			if (this.scrollOffset >= this.lastMaxScroll) this.followMode = true;
			this.refresh();
			return;
		}
		if (data === "g") {
			this.followMode = false;
			this.scrollOffset = 0;
			this.refresh();
			return;
		}
		if (data === "G") {
			this.followMode = true;
			this.scrollOffset = 999999;
			this.refresh();
		}
	}

	private getBody(width: number): string[] {
		const key = [
			this.state.status,
			this.state.currentRound,
			this.state.blocking,
			this.state.entries.length,
			...this.state.entries.map(
				(entry) =>
					`${entry.role}:${entry.round}:${entry.blocking}:${entry.text.length}`,
			),
		].join("|");
		if (
			this.cachedBody &&
			this.cachedBodyWidth === width &&
			this.cachedBodyKey === key
		) {
			return this.cachedBody;
		}
		this.cachedBodyWidth = width;
		this.cachedBodyKey = key;
		this.cachedBody = renderDebateTranscript(this.state, this.theme, width, {
			compact: false,
			maxBodyLines: 1000,
		});
		return this.cachedBody;
	}

	render(width: number): string[] {
		if (width <= 0) return [""];
		const innerWidth = Math.max(0, width - 2);
		const body = this.getBody(innerWidth);
		const maxVisible = Math.max(6, Math.min(24, this.tui.terminal.rows - 8));
		const maxScroll = Math.max(0, body.length - maxVisible);
		this.lastMaxScroll = maxScroll;
		if (this.followMode) this.scrollOffset = maxScroll;
		this.scrollOffset = Math.min(this.scrollOffset, maxScroll);
		const visible = body.slice(
			this.scrollOffset,
			this.scrollOffset + maxVisible,
		);

		const title = " Devil Review ";
		const top =
			this.theme.fg("accent", title) +
			this.theme.fg(
				"border",
				"─".repeat(Math.max(0, innerWidth - visibleWidth(title))),
			);
		const lines = [frameLine(this.theme, "╭", top, "╮", width)];

		for (const line of visible) {
			lines.push(frameLine(this.theme, "│", line, "│", width));
		}

		const scrollInfo =
			body.length > maxVisible
				? `${this.scrollOffset + 1}-${Math.min(this.scrollOffset + maxVisible, body.length)}/${body.length}`
				: `${body.length}L`;
		const follow = this.followMode ? "follow" : "paused";
		const action = this.failed ? "q/Esc close" : "q/Esc cancel";
		const footer = this.theme.fg(
			"dim",
			` ${scrollInfo} · ${follow} · ↑↓/j/k scroll · Pg/C-u/d page · g/G top/end · ${action} `,
		);
		lines.push(
			frameLine(
				this.theme,
				"├",
				this.theme.fg("border", "─".repeat(innerWidth)),
				"┤",
				width,
			),
		);
		lines.push(frameLine(this.theme, "│", footer, "│", width));
		lines.push(
			frameLine(
				this.theme,
				"╰",
				this.theme.fg("border", "─".repeat(innerWidth)),
				"╯",
				width,
			),
		);
		return lines.map((line) => truncateToWidth(line, width));
	}

	invalidate(): void {
		this.cachedBody = undefined;
		this.cachedBodyWidth = undefined;
		this.cachedBodyKey = undefined;
	}

	dispose(): void {
		this.disposed = true;
		this.controller.abort();
	}
}