repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/decay/ui.ts

Raw
File outline
import type { Theme } from "@earendil-works/pi-coding-agent";
import type { Component, TUI } from "@earendil-works/pi-tui";
import type { RecordChunk } from "./core.js";

const FRAME_MS = 55;
const TRANSFER_MS = 660;
const NORMAL_HEIGHT = 8;
const SHORT_HEIGHT = 4;
const SPIN = ["▖", "▘", "▝", "▗"] as const;

type Recency = "old" | "established" | "recent" | "newest";
type CellColor = Recency | "recurring" | "title" | "text" | "dim";

interface Cell {
	char: string;
	color: CellColor;
}

export interface DisplayTransfer {
	chunk: number;
	kind: Recency;
	recurring: boolean;
	acceptedAt: number;
}

export interface DecayDisplayState {
	model: string;
	inputTokens: number;
	keptTokens: number;
	totalChunks: number;
	phase: "classify" | "merge";
	transfers: DisplayTransfer[];
	startedAt: number;
}

export class DecayComponent implements Component {
	private readonly seenKeys = new Set<string>();
	private readonly timer: ReturnType<typeof setInterval>;
	private disposed = false;

	constructor(
		private readonly tui: TUI,
		private readonly theme: Theme,
		readonly state: DecayDisplayState,
		private readonly now: () => number = Date.now,
	) {
		this.timer = setInterval(() => this.tui.requestRender(), FRAME_MS);
		this.timer.unref?.();
	}

	record(record: RecordChunk): void {
		let recurring = false;
		for (const atom of record.atoms) {
			const key = atom.key.trim().toLowerCase();
			if (this.seenKeys.has(key)) recurring = true;
			this.seenKeys.add(key);
		}
		this.state.transfers.push({
			chunk: record.chunk,
			kind: recencyFor(record.chunk, record.of),
			recurring,
			acceptedAt: this.now(),
		});
		this.tui.requestRender();
	}

	setPhase(phase: DecayDisplayState["phase"]): void {
		this.state.phase = phase;
		this.tui.requestRender();
	}

	invalidate(): void {
		this.tui.requestRender(true);
	}

	render(width: number): string[] {
		return styleFrame(
			renderDecayFrame(width, this.tui.terminal.rows, this.state, this.now()),
			this.theme,
		);
	}

	dispose(): void {
		if (this.disposed) return;
		this.disposed = true;
		clearInterval(this.timer);
	}
}

export function renderDecayFrame(
	viewportWidth: number,
	viewportHeight: number,
	state: DecayDisplayState,
	now: number,
): Cell[][] {
	const width = Math.max(1, viewportWidth);
	const height = viewportHeight < 24 ? SHORT_HEIGHT : NORMAL_HEIGHT;
	const canvas = blankCanvas(width, height);
	if (height === SHORT_HEIGHT) renderShort(canvas, state, now);
	else renderNormal(canvas, state, now);
	return canvas;
}

function renderNormal(
	canvas: Cell[][],
	state: DecayDisplayState,
	now: number,
): void {
	const width = canvas[0].length;
	const elapsedMs = Math.max(0, now - state.startedAt);
	const frame = Math.floor(elapsedMs / FRAME_MS);
	renderBorder(canvas, 0, "╭", "─", "╮");
	renderBorder(canvas, NORMAL_HEIGHT - 1, "╰", "─", "╯");
	for (let row = 1; row < NORMAL_HEIGHT - 1; row++) {
		put(canvas, 0, row, "│", "dim");
		put(canvas, width - 1, row, "│", "dim");
	}

	const phase = phaseLabel(state);
	const header = `DECAY.EXE ${frame % 12 < 6 ? "█" : " "} · ${phase} · ${(elapsedMs / 1_000).toFixed(1)}s · ${modelLabel(state.model)}`;
	put(canvas, 2, 0, header.slice(0, Math.max(0, width - 4)), "title");

	const tailWidth = clamp(Math.round(width * 0.28), 14, 28);
	const separatorX = Math.max(18, width - tailWidth - 1);
	const historyEnd = Math.max(3, separatorX - 1);
	for (const row of [1, 2]) put(canvas, separatorX, row, "║", "recent");

	const decayedTokens = Math.max(0, state.inputTokens - state.keptTokens);
	put(canvas, 2, 1, `HISTORY ${compactTokens(decayedTokens)}`, "dim");
	fillHistory(canvas, 14, historyEnd, 1, 0);
	fillHistory(canvas, 2, historyEnd, 2, 1);
	for (const transfer of state.transfers) {
		const source = sourcePosition(separatorX, transfer.chunk);
		put(canvas, source.x, source.y, " ", "dim");
	}

	put(
		canvas,
		separatorX + 2,
		1,
		`${compactTokens(state.keptTokens)} KEPT`,
		"recent",
	);
	fillTail(canvas, separatorX + 2, width - 2, 2);

	put(canvas, 2, 3, "TRANSFER", "dim");
	const laneStart = Math.min(width - 3, 11);
	const laneEnd = Math.max(laneStart, width - 3);
	put(
		canvas,
		laneStart,
		3,
		"·".repeat(Math.max(0, laneEnd - laneStart)),
		"dim",
	);
	put(canvas, laneEnd, 3, "▶", "recent");
	const latest = state.transfers.at(-1);
	if (latest) {
		const progress = clamp((now - latest.acceptedAt) / TRANSFER_MS, 0, 1);
		if (progress < 1) {
			const x = Math.round(laneStart + (laneEnd - laneStart) * progress);
			put(
				canvas,
				x,
				3,
				SPIN[frame % SPIN.length],
				latest.recurring ? "recurring" : latest.kind,
			);
		}
	} else if (state.phase === "merge") {
		const span = Math.max(1, laneEnd - laneStart);
		put(
			canvas,
			laneStart + (frame % span),
			3,
			SPIN[frame % SPIN.length],
			"recent",
		);
	}

	renderSummary(canvas, 4, state, now);
	renderLegend(canvas, 5);
	renderStatus(canvas, 6, state);
}

function renderShort(
	canvas: Cell[][],
	state: DecayDisplayState,
	now: number,
): void {
	const width = canvas[0].length;
	const elapsedMs = Math.max(0, now - state.startedAt);
	const frame = Math.floor(elapsedMs / FRAME_MS);
	renderBorder(canvas, 0, "╭", "─", "╮");
	renderBorder(canvas, SHORT_HEIGHT - 1, "╰", "─", "╯");
	for (const row of [1, 2]) {
		put(canvas, 0, row, "│", "dim");
		put(canvas, width - 1, row, "│", "dim");
	}
	const header = `DECAY · ${phaseLabel(state)} · ${(elapsedMs / 1_000).toFixed(1)}s · ${modelLabel(state.model)}`;
	put(canvas, 2, 0, header.slice(0, Math.max(0, width - 4)), "title");

	const decayed = compactTokens(
		Math.max(0, state.inputTokens - state.keptTokens),
	);
	const kept = compactTokens(state.keptTokens);
	const prefix = `H${decayed} `;
	const suffix = ` → K${kept}`;
	const historyStart = 2 + prefix.length;
	const historyEnd = Math.max(historyStart, width - suffix.length - 3);
	put(canvas, 2, 1, prefix, "dim");
	fillHistory(canvas, historyStart, historyEnd, 1, 0);
	put(canvas, historyEnd, 1, suffix, "recent");
	const latest = state.transfers.at(-1);
	if (latest) {
		const progress = clamp((now - latest.acceptedAt) / TRANSFER_MS, 0, 1);
		if (progress < 1) {
			const x = Math.round(
				historyStart + (historyEnd - historyStart) * progress,
			);
			put(
				canvas,
				x,
				1,
				SPIN[frame % SPIN.length],
				latest.recurring ? "recurring" : latest.kind,
			);
		}
	}

	put(canvas, 2, 2, "S [", "dim");
	const controls = width >= 48 ? " ↵ queue · Esc cancel" : " ↵ queue";
	const summaryStart = 5;
	const summaryCapacity = Math.max(
		1,
		width - summaryStart - controls.length - 2,
	);
	put(canvas, summaryStart, 2, "·".repeat(summaryCapacity), "dim");
	put(canvas, summaryStart + summaryCapacity, 2, "]", "dim");
	put(canvas, summaryStart + summaryCapacity + 1, 2, controls, "dim");
	landTransfers(canvas, summaryStart, summaryCapacity, 2, state, now);
}

function renderSummary(
	canvas: Cell[][],
	y: number,
	state: DecayDisplayState,
	now: number,
): void {
	const width = canvas[0].length;
	put(canvas, 2, y, "SUMMARY [", "dim");
	const start = 11;
	const capacity = Math.max(1, width - start - 3);
	put(canvas, start, y, "·".repeat(capacity), "dim");
	put(canvas, start + capacity, y, "]", "dim");
	landTransfers(canvas, start, capacity, y, state, now);
}

function landTransfers(
	canvas: Cell[][],
	start: number,
	capacity: number,
	y: number,
	state: DecayDisplayState,
	now: number,
): void {
	const latest = state.transfers.at(-1);
	for (const transfer of state.transfers) {
		const moving =
			transfer === latest && (now - transfer.acceptedAt) / TRANSFER_MS < 1;
		if (moving) continue;
		const index = Math.floor(
			((transfer.chunk - 1) / Math.max(1, state.totalChunks)) * capacity,
		);
		put(
			canvas,
			start + clamp(index, 0, capacity - 1),
			y,
			historyGlyph(transfer.kind),
			transfer.recurring ? "recurring" : transfer.kind,
		);
	}
}

function renderLegend(canvas: Cell[][], y: number): void {
	const width = canvas[0].length;
	const legend =
		width < 68
			? "░ old  ▒ established  ▓ recent  █ newest  ◆ recurring"
			: "LEGEND  ░ old   ▒ established   ▓ recent   █ newest   ◆ recurring";
	put(canvas, 2, y, legend.slice(0, Math.max(0, width - 4)), "dim");
	for (const [glyph, color] of [
		["░", "old"],
		["▒", "established"],
		["▓", "recent"],
		["█", "newest"],
		["◆", "recurring"],
	] as const) {
		const index = legend.indexOf(glyph);
		if (index >= 0) put(canvas, 2 + index, y, glyph, color);
	}
}

function renderStatus(
	canvas: Cell[][],
	y: number,
	state: DecayDisplayState,
): void {
	const width = canvas[0].length;
	const left = `INPUT ${state.inputTokens.toLocaleString("en-US")} · ${modelLabel(state.model)}`;
	const controls = "Enter queues steer · Esc cancels";
	put(canvas, 2, y, left.slice(0, Math.max(0, width - 4)), "text");
	if (width >= controls.length + 4) {
		put(canvas, width - controls.length - 2, y, controls, "dim");
	}
}

function fillHistory(
	canvas: Cell[][],
	start: number,
	end: number,
	y: number,
	row: number,
): void {
	for (let x = start; x < end; x++) {
		const kind = historyCellKind(x - start, Math.max(1, end - start), row);
		const recurring = (x * 17 + row * 31) % 43 === 0;
		put(canvas, x, y, historyGlyph(kind), recurring ? "recurring" : kind);
	}
}

function fillTail(
	canvas: Cell[][],
	start: number,
	end: number,
	y: number,
): void {
	for (let x = start; x < end; x++) {
		put(canvas, x, y, x % 7 === 0 ? "█" : "▓", "recent");
	}
}

function sourcePosition(
	separatorX: number,
	chunk: number,
): { x: number; y: number } {
	const firstStart = 14;
	const firstWidth = Math.max(1, separatorX - 1 - firstStart);
	const secondStart = 2;
	const secondWidth = Math.max(1, separatorX - 1 - secondStart);
	const capacity = firstWidth + secondWidth;
	const index = (chunk * 37) % capacity;
	return index < firstWidth
		? { x: firstStart + index, y: 1 }
		: { x: secondStart + index - firstWidth, y: 2 };
}

function phaseLabel(state: DecayDisplayState): string {
	return state.phase === "classify"
		? `CLASSIFY ${state.transfers.length}/${state.totalChunks}`
		: "MERGE";
}

function recencyFor(chunk: number, total: number): Recency {
	const ratio = chunk / Math.max(1, total);
	if (ratio <= 0.25) return "old";
	if (ratio <= 0.5) return "established";
	if (ratio <= 0.75) return "recent";
	return "newest";
}

function blankCanvas(width: number, height: number): Cell[][] {
	return Array.from({ length: height }, () =>
		Array.from({ length: width }, () => ({ char: " ", color: "dim" })),
	);
}

function renderBorder(
	canvas: Cell[][],
	y: number,
	left: string,
	fill: string,
	right: string,
): void {
	const width = canvas[0].length;
	put(canvas, 0, y, left, "dim");
	put(canvas, 1, y, fill.repeat(Math.max(0, width - 2)), "dim");
	put(canvas, width - 1, y, right, "dim");
}

function put(
	canvas: Cell[][],
	x: number,
	y: number,
	text: string,
	color: CellColor,
): void {
	if (y < 0 || y >= canvas.length) return;
	let column = x;
	for (const char of text) {
		if (column >= 0 && column < canvas[y].length)
			canvas[y][column] = { char, color };
		column++;
	}
}

function historyCellKind(x: number, width: number, row: number): Recency {
	const ratio = x / Math.max(1, width - 1);
	const hash = (x * 37 + row * 61 + x * row * 11) % 101;
	const recency = clamp(ratio + (hash / 100 - 0.5) * 0.54, 0, 1);
	if (recency < 0.25) return "old";
	if (recency < 0.5) return "established";
	if (recency < 0.75) return "recent";
	return "newest";
}

function historyGlyph(kind: Recency): string {
	return { old: "░", established: "▒", recent: "▓", newest: "█" }[kind];
}

function modelLabel(reference: string): string {
	const separator = reference.indexOf("/");
	return separator >= 0 ? reference.slice(separator + 1) : reference;
}

function compactTokens(tokens: number): string {
	return tokens >= 1_000 ? `${Math.round(tokens / 1_000)}K` : String(tokens);
}

function clamp(value: number, minimum: number, maximum: number): number {
	return Math.max(minimum, Math.min(maximum, value));
}

function styleFrame(frame: Cell[][], theme: Theme): string[] {
	const color = (name: CellColor, text: string): string => {
		switch (name) {
			case "title":
				return theme.bold(theme.fg("success", text));
			case "text":
			case "newest":
				return theme.fg("text", text);
			case "recurring":
				return theme.fg("warning", text);
			case "recent":
				return theme.fg("success", text);
			case "established":
				return theme.fg("borderAccent", text);
			case "old":
			case "dim":
				return theme.fg("dim", text);
		}
	};
	return frame.map((row) => {
		let result = "";
		let active = row[0]?.color ?? "dim";
		let text = "";
		for (const cell of row) {
			if (cell.color !== active) {
				result += color(active, text);
				active = cell.color;
				text = "";
			}
			text += cell.char;
		}
		return result + color(active, text);
	});
}

export function plainFrame(frame: Cell[][]): string[] {
	return frame.map((row) => row.map((cell) => cell.char).join(""));
}