Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/loop/src/widget.ts

Raw
import type { Theme } from "@earendil-works/pi-coding-agent";
import {
	type OverlayHandle,
	sliceByColumn,
	type TUI,
	truncateToWidth,
	visibleWidth,
} from "@earendil-works/pi-tui";
import {
	AFTERGLOW_MS,
	type Companion,
	createCompanion,
	H,
} from "./companion.ts";
import type { LoopSnapshot } from "./controller.ts";
import { gateLabel } from "./gates.ts";
import { ICON } from "./icons.ts";
import { createKitten } from "./kitten.ts";
import { createProgress } from "./progress.ts";

const DISPLAY_SCALE = 1.5;
const PORTRAIT_WIDTH = 48;
const PORTRAIT_ROWS = Math.ceil((H * DISPLAY_SCALE) / 2);
const BOTTOM_CLEARANCE = 9;

const budget = (used: number, limit: number | null) =>
	limit === null ? `${used}` : `${used}/${limit}`;

/** Inline status owns the passive portrait, its handle, and animation lifetime. */
export function createLoopWidget(
	tui: TUI,
	theme: Theme,
	state: () => {
		run: LoopSnapshot | null;
		baseline: boolean;
		agentRunning: boolean;
		vixen: boolean;
	},
	kitten = false,
): Companion {
	// Select before construction: the SFW path never instantiates the vixen.
	const createAnimation = kitten ? createKitten : createCompanion;
	const progress = createProgress(tui, theme, state);
	let companion: Companion | undefined;
	let overlay: OverlayHandle | undefined;
	let picture: string[] = [];
	let pictureWidth = 0;
	let pictureHeight = 0;
	let disposed = false;
	const portrait = {
		render: () => picture,
		invalidate() {},
	};
	const remove = () => {
		overlay?.hide();
		overlay = undefined;
		companion?.dispose();
		companion = undefined;
		picture = [];
	};
	return {
		render(width) {
			if (disposed) return [];
			const current = state();
			const run = current.run;
			const detail = progress.render(width);
			// Reserve editor/footer clearance below the full enlarged camera.
			const fits =
				tui.terminal.columns >= 60 &&
				tui.terminal.rows >= PORTRAIT_ROWS + BOTTOM_CLEARANCE;
			if (
				!run ||
				!current.vixen ||
				!fits ||
				width < 1 ||
				run.status === "stopped" ||
				(run.status === "succeeded" &&
					Date.now() - run.updatedAt > AFTERGLOW_MS)
			) {
				remove();
			} else {
				companion ??= createAnimation(
					tui,
					theme,
					() => {
						const live = state().run ?? run;
						const index = live.lastPass?.failedIndex;
						const result =
							index == null ? undefined : live.lastPass?.results[index];
						const gate = index == null ? undefined : live.gates[index];
						return {
							...live,
							failed:
								result && gate
									? { gate: gateLabel(gate), at: result.endedAt }
									: null,
						};
					},
					Date.now,
					DISPLAY_SCALE,
				);
				// Scale pixels before half-block packing; omit the standalone caption.
				const frame = companion.render(PORTRAIT_WIDTH).slice(0, PORTRAIT_ROWS);
				let left = PORTRAIT_WIDTH;
				let right = 0;
				let top = frame.length;
				let bottom = 0;
				for (const [row, line] of frame.entries()) {
					// Empty raster cells are literal spaces, never styled pixels.
					const leading = line.match(/^ */u)?.[0].length ?? 0;
					const end = visibleWidth(line);
					if (end <= leading) continue;
					left = Math.min(left, leading);
					right = Math.max(right, end);
					top = Math.min(top, row);
					bottom = row + 1;
				}
				picture = frame
					.slice(top, bottom)
					.map((line) => sliceByColumn(line, left, right - left));
				const columns = right - left;
				if (picture.length && columns > 0) {
					if (
						!overlay ||
						columns !== pictureWidth ||
						picture.length !== pictureHeight
					) {
						overlay?.hide();
						pictureWidth = columns;
						pictureHeight = picture.length;
						overlay = tui.showOverlay(portrait, {
							nonCapturing: true,
							anchor: "bottom-right",
							width: columns,
							maxHeight: PORTRAIT_ROWS,
							margin: { bottom: BOTTOM_CLEARANCE, right: 1 },
						});
					}
				} else remove();
			}
			if (!run || width < 1) return [];
			const facts = `${ICON.gate} ${budget(run.attempts, run.budgets.attempts)}  ${ICON.turn} ${budget(run.turns, run.budgets.turns)}`;
			const headingWidth = width - visibleWidth(facts) - 3;
			const heading =
				headingWidth >= 20
					? `${truncateToWidth(detail[0] ?? "", headingWidth)} · ${theme.fg("dim", facts)}`
					: truncateToWidth(`${facts} · ${detail[0] ?? ""}`, width);
			return [heading, ...detail.slice(1)]
				.slice(0, 3)
				.map((line) => truncateToWidth(line, width));
		},
		invalidate() {
			progress.invalidate();
			companion?.invalidate();
			if (!disposed) tui.requestRender();
		},
		dispose() {
			disposed = true;
			progress.dispose();
			remove();
		},
	};
}