repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/footer/index.ts

Raw
File outline
/**
 * Footer renderer extension.
 *
 * Listens for "footer:segment" events from producer extensions and renders
 * a 4-line footer with stable height:
 *   line 0 = workspace zone (cwd, branch, PR, runtime, session name)
 *   line 1-2 = llm zone (model, thinking, context, tokens, cost, timing) — flow layout
 *   line 3 = extension statuses via ctx.ui.setStatus()
 *
 * Producers use semantic zones ("workspace" | "llm"). Footer decides row mapping.
 * Publishes a process-global capability flag so producers can choose footer
 * segments over ctx.ui.setStatus() fallbacks without ping events.
 * Uses setFooter() — the single footer owner. Producers are decoupled.
 *
 * /footer or ctrl+alt+f toggles visibility by swapping between
 * the real footer and a zero-height stub via setFooter().
 */

import type {
	ExtensionAPI,
	ExtensionContext,
	Theme,
	ThemeColor,
} from "@earendil-works/pi-coding-agent";
import { Key, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
import { renderBlocksBar } from "./progress";

// ── Constants ─────────────────────────────────────────────────────

const FOOTER_KEY = Symbol.for("@bugabinga/pi-ext-footer");
const SEPARATOR_COLOR = "borderMuted" as ThemeColor;
const DEFAULT_SEGMENT_COLOR = "muted" as ThemeColor;
const STATUS_COLOR = "dim" as ThemeColor;
const BAR_WIDTH = 10;
const RETRY_MOUNT_MS = 50;

// ── Types ─────────────────────────────────────────────────────────

type FooterGlobal = {
	version: 1;
	loaded: boolean;
};
type FooterGlobalStore = typeof globalThis & {
	[FOOTER_KEY]?: FooterGlobal;
};

type FooterZone = "workspace" | "llm";

type Segment = {
	id: string;
	text: string;
	variants?: string[];
	icon?: string;
	color?: ThemeColor;
	bar?: number;
	suffix?: string;
	zone: FooterZone;
	order?: number;
};

type SegmentUpdate = Segment | { id: string; text: undefined };

// ── Pure helpers ──────────────────────────────────────────────────

/** Pad line with side margins, truncating to fit terminal width. */
function padLine(line: string, width: number): string {
	if (width <= 1) return truncateToWidth(line, width);
	const contentWidth = width - 2;
	return ` ${truncateToWidth(line, contentWidth)} `;
}

/** Collapse whitespace and strip terminal/control characters for single-line display. */
function sanitizeDisplayText(text: string): string {
	return text
		.replace(
			/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g,
			"",
		)
		.replace(/[\x00-\x1F\x7F-\x9F]/g, " ")
		.replace(/ +/g, " ")
		.trim();
}

/** Zero-height footer stub for hidden mode. */
const HIDDEN_FOOTER = {
	dispose: () => {},
	invalidate() {},
	render(): string[] {
		return [];
	},
};

// ── Extension ─────────────────────────────────────────────────────

export default function footerExtension(pi: ExtensionAPI) {
	const state: FooterGlobal = { version: 1, loaded: true };
	(globalThis as FooterGlobalStore)[FOOTER_KEY] = state;

	const segments = new Map<string, Segment>();
	let requestRender: (() => void) | undefined;
	let renderScheduled = false;
	let hidden = false;
	let currentCtx: ExtensionContext | undefined;

	// ── Segment handling ──────────────────────────────────────────

	function handleSegment(data: unknown) {
		const payload = data as SegmentUpdate;
		if (!payload?.id) return;

		if (!("text" in payload) || payload.text === undefined) {
			segments.delete(payload.id);
		} else {
			segments.set(payload.id, payload as Segment);
		}
		scheduleRender();
	}

	pi.events.on("footer:segment", handleSegment);

	// ── Coalesced render scheduling ───────────────────────────────

	function scheduleRender() {
		if (renderScheduled) return;
		if (!requestRender) {
			if (segments.size > 0) setTimeout(() => scheduleRender(), RETRY_MOUNT_MS);
			return;
		}
		renderScheduled = true;
		queueMicrotask(() => {
			renderScheduled = false;
			requestRender?.();
		});
	}

	// ── Segment queries ───────────────────────────────────────────

	function getZoneSegments(zone: FooterZone): Segment[] {
		return Array.from(segments.values())
			.filter((s) => s.zone === zone)
			.sort((a, b) => (a.order ?? 50) - (b.order ?? 50));
	}

	// ── Segment rendering ─────────────────────────────────────────

	function renderSegmentText(seg: Segment, theme: Theme, text: string): string {
		const color = seg.color ?? DEFAULT_SEGMENT_COLOR;
		const safeIcon = seg.icon ? sanitizeDisplayText(seg.icon) : "";
		const safeText = sanitizeDisplayText(text);
		const safeSuffix = seg.suffix ? sanitizeDisplayText(seg.suffix) : "";
		const parts: string[] = [];

		if (safeIcon) parts.push(theme.fg(color, safeIcon));
		if (safeText) parts.push(theme.fg(color, safeText));

		if (seg.bar !== undefined) {
			const bar = renderBlocksBar(seg.bar, BAR_WIDTH, theme, color);
			const suffix = safeSuffix ? theme.fg(color, safeSuffix) : "";
			parts.push(bar + suffix);
		} else if (safeSuffix) {
			parts.push(theme.fg(color, safeSuffix));
		}

		return parts.join(" ");
	}

	function renderSegment(
		seg: Segment,
		theme: Theme,
		width = Number.POSITIVE_INFINITY,
	): string {
		const variants = [seg.text, ...(seg.variants ?? [])].filter(Boolean);
		for (const text of variants) {
			const rendered = renderSegmentText(seg, theme, text);
			if (visibleWidth(rendered) <= width) return rendered;
		}
		return renderSegmentText(seg, theme, variants.at(-1) ?? "");
	}

	function joinSegments(
		segs: Segment[],
		sep: string,
		theme: Theme,
		width = Number.POSITIVE_INFINITY,
	): string {
		return segs.map((s) => renderSegment(s, theme, width)).join(sep);
	}

	// ── Zone rendering ────────────────────────────────────────────

	function safeSessionName(
		ctx: ExtensionContext | undefined,
	): string | undefined {
		try {
			return ctx?.sessionManager.getSessionName();
		} catch {
			return undefined;
		}
	}

	function renderWorkspaceLine(
		theme: Theme,
		width: number,
		ctx: ExtensionContext | undefined,
	): string {
		const segs = getZoneSegments("workspace");
		const name = safeSessionName(ctx);
		if (name) {
			segs.push({
				id: "session-name",
				text: name,
				icon: "󰑕",
				color: "accent" as ThemeColor,
				zone: "workspace",
				order: 0.5,
			});
			segs.sort((a, b) => (a.order ?? 50) - (b.order ?? 50));
		}
		if (segs.length === 0) return "";
		const sep = theme.fg(SEPARATOR_COLOR, " | ");
		return truncateToWidth(joinSegments(segs, sep, theme, width), width);
	}

	/** Flow layout: fill line 1, overflow to line 2, truncate line 2. */
	function renderLlmLines(theme: Theme, width: number): [string, string] {
		const segs = getZoneSegments("llm");
		if (segs.length === 0) return ["", ""];

		const sep = theme.fg(SEPARATOR_COLOR, " | ");
		const rendered = segs.map((s) => renderSegment(s, theme, width));

		let line1 = "";
		let line1Width = 0;
		let overflowIndex = -1;

		for (const [i, segment] of rendered.entries()) {
			const segWidth = visibleWidth(segment);
			const prefixWidth = line1Width > 0 ? visibleWidth(sep) : 0;

			if (line1Width + prefixWidth + segWidth <= width) {
				line1 += (line1Width > 0 ? sep : "") + segment;
				line1Width += prefixWidth + segWidth;
			} else {
				overflowIndex = i;
				break;
			}
		}

		if (overflowIndex === -1) return [line1, ""];

		const line2 = truncateToWidth(
			rendered.slice(overflowIndex).join(sep),
			width,
		);
		return [line1, line2];
	}

	function renderStatusLine(
		theme: Theme,
		statuses: ReadonlyMap<string, string>,
	): string {
		if (statuses.size === 0) return "";
		const parts = Array.from(statuses.entries())
			.sort(([a], [b]) => a.localeCompare(b))
			.map(([, t]) => sanitizeDisplayText(t))
			.join(" · ");
		return theme.fg(STATUS_COLOR, parts);
	}

	function renderFooterLines(
		theme: Theme,
		width: number,
		ctx: ExtensionContext | undefined,
		statuses: ReadonlyMap<string, string>,
	): string[] {
		const contentWidth = Math.max(0, width - 2);
		const workspaceLine = renderWorkspaceLine(theme, contentWidth, ctx);
		const [llmLine1, llmLine2] = renderLlmLines(theme, contentWidth);
		const statusLine = renderStatusLine(theme, statuses);

		return [
			padLine(workspaceLine, width),
			padLine(llmLine1, width),
			padLine(llmLine2, width),
			padLine(statusLine, width),
		];
	}

	// ── Mounting ──────────────────────────────────────────────────

	function mountFooter() {
		if (!currentCtx) return;

		if (hidden) {
			requestRender = undefined;
			currentCtx.ui.setFooter((tui) => {
				tui.requestRender(true);
				return HIDDEN_FOOTER;
			});
			return;
		}

		currentCtx.ui.setFooter((tui, theme, footerData) => {
			requestRender = () => tui.requestRender();
			const unsubBranch = footerData.onBranchChange(() => scheduleRender());

			return {
				dispose: () => {
					unsubBranch();
					requestRender = undefined;
				},
				invalidate() {},
				render(width: number): string[] {
					try {
						return renderFooterLines(
							theme,
							width,
							currentCtx,
							footerData.getExtensionStatuses(),
						);
					} catch {
						return [];
					}
				},
			};
		});

		setTimeout(() => scheduleRender(), 0);
	}

	// ── Toggle ────────────────────────────────────────────────────

	function toggleVisibility(ctx: ExtensionContext) {
		hidden = !hidden;
		currentCtx = ctx;
		ctx.ui.notify(hidden ? "Footer hidden" : "Footer visible", "info");
		mountFooter();
	}

	pi.registerCommand("footer", {
		description: "Toggle footer visibility",
		handler: async (_args, ctx) => toggleVisibility(ctx),
	});

	pi.registerShortcut(Key.ctrlAlt("f"), {
		description: "Toggle footer visibility",
		handler: async (ctx) => toggleVisibility(ctx),
	});

	// ── Lifecycle ─────────────────────────────────────────────────

	pi.on("session_start", async (_event, ctx) => {
		if (!ctx.hasUI) return;
		currentCtx = ctx;
		mountFooter();
	});

	pi.on("session_shutdown", async (event) => {
		if (event.reason === "quit" || event.reason === "reload")
			state.loaded = false;
		segments.clear();
		requestRender = undefined;
		currentCtx = undefined;
	});
}