repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/activity/ui.ts

Raw
File outline
import type {
	ExtensionCommandContext,
	Theme,
} from "@earendil-works/pi-coding-agent";
import {
	type Component,
	CURSOR_MARKER,
	decodeKittyPrintable,
	type Focusable,
	isKeyRelease,
	type KeybindingsManager,
	matchesKey,
	parseKey,
	renderFakeCursor,
	type SelectItem,
	SelectList,
	sliceByColumn,
	stripTerminalSequences,
	type TUI,
	type TuiMouseEvent,
	truncateToWidth,
	visibleWidth,
} from "@earendil-works/pi-tui";
import type { ActivityManager } from "./runtime.js";
import type { ActivitySnapshot, TimerView } from "./types.js";
import type { TerminalView } from "./view.js";

type ManagerApi = Pick<
	ActivityManager,
	| "list"
	| "read"
	| "write"
	| "resize"
	| "subscribe"
	| "terminalView"
	| "timerView"
>;

type TerminalInput =
	| { detach: true }
	| { text: string; paste?: true }
	| undefined;

const OUTPUT_LIMIT = 16_384;
const OUTPUT_LINES = 48;
const EVENT_LINES = 8;
const REFRESH_MS = 100;
const MIN_COLS = 20;
const MAX_COLS = 200;
const MIN_ROWS = 5;
const MAX_ROWS = 60;

export async function openActivities(
	manager: ManagerApi,
	ctx: ExtensionCommandContext,
	id?: string,
): Promise<void> {
	if (ctx.mode !== "tui") {
		if (ctx.hasUI)
			ctx.ui.notify("Activities require Pi's terminal UI.", "warning");
		return;
	}

	const api: ManagerApi = manager;
	let selectedId = id;
	let previousId: string | undefined;
	try {
		while (true) {
			if (!selectedId) {
				if (api.list().length === 0) {
					ctx.ui.notify("No activities.", "info");
					return;
				}
				selectedId = await ctx.ui.custom<string | undefined>(
					(tui, theme, _keybindings, done) =>
						activityPicker(api, tui, theme, done, previousId),
					{
						overlay: true,
						overlayOptions: { anchor: "center", width: 68, maxHeight: "90%" },
					},
				);
			}
			if (!selectedId) return;
			const inspectedId = selectedId;
			const activity = api.read(inspectedId);
			await ctx.ui.custom<void>(
				(tui, theme, keybindings, done) =>
					new ActivityInspector(
						tui,
						theme,
						keybindings,
						done,
						api,
						inspectedId,
						!id,
					),
				{
					overlay: true,
					overlayOptions: {
						anchor: "center",
						width: activity.kind === "terminal" ? "90%" : 68,
						maxHeight: "90%",
					},
				},
			);
			if (id) return;
			previousId = inspectedId;
			selectedId = undefined;
		}
	} catch (error) {
		ctx.ui.notify(`Activities unavailable: ${errorMessage(error)}`, "error");
	}
}

const KINDS = {
	process: { icon: "⚙", label: "Process", running: "Running" },
	terminal: { icon: "▣", label: "Terminal", running: "Open" },
	watch: { icon: "◎", label: "Watch", running: "Watching" },
	timer: { icon: "◷", label: "Timer", running: "Waiting" },
} as const;
const STATES = {
	running: { icon: "●", label: "Running" },
	stopping: { icon: "◌", label: "Stopping…" },
	completed: { icon: "✓", label: "Done" },
	failed: { icon: "✕", label: "Failed" },
	stopped: { icon: "■", label: "Stopped" },
} as const;
const RESET = "\x1b[0m";

function isActive(activity: ActivitySnapshot): boolean {
	return activity.status === "running" || activity.status === "stopping";
}

function statusLabel(activity: ActivitySnapshot): string {
	return activity.status === "running"
		? KINDS[activity.kind].running
		: STATES[activity.status].label;
}

export function formatActivityOption(activity: ActivitySnapshot): SelectItem {
	return {
		value: activity.id,
		label: `${STATES[activity.status].icon} ${KINDS[activity.kind].icon} ${singleLine(sanitizeActivityText(activity.title))}`,
		description: statusLabel(activity),
	};
}

export function activityPicker(
	manager: Pick<ManagerApi, "list" | "subscribe">,
	tui: TUI,
	theme: Theme,
	done: (id: string | undefined) => void,
	selectedId?: string,
): Component & { dispose(): void } {
	const items = manager
		.list()
		.slice()
		.sort(
			(a, b) =>
				Number(isActive(b)) - Number(isActive(a)) || b.createdAt - a.createdAt,
		)
		.map(formatActivityOption);
	let list: SelectList;
	let visibleRows = 0;
	let listHeight = 0;
	const updateSize = () => {
		const rows = Math.max(
			1,
			Math.min(8, Math.floor(tui.terminal.rows * 0.9) - 6),
		);
		if (rows === visibleRows) return;
		const selected = list?.getSelectedItem()?.value ?? selectedId;
		list = new SelectList(items, rows, {
			selectedPrefix: (text) => theme.fg("accent", text),
			selectedText: (text) => theme.fg("accent", theme.bold(text)),
			description: (text) => theme.fg("muted", text),
			scrollInfo: (text) => theme.fg("dim", text),
			noMatch: (text) => theme.fg("muted", text),
		});
		list.setSelectedIndex(
			Math.max(
				0,
				items.findIndex((item) => item.value === selected),
			),
		);
		list.onSelect = (item) => {
			if (manager.list().some((activity) => activity.id === item.value))
				done(item.value);
		};
		list.onCancel = () => done(undefined);
		visibleRows = rows;
	};
	updateSize();
	const unsubscribe = manager.subscribe(() => tui.requestRender());
	return {
		render(width) {
			// Keep row identities/order stable during mouse gestures; refresh presentation only.
			const current = new Map(
				manager.list().map((activity) => [activity.id, activity]),
			);
			for (const item of items) {
				const activity = current.get(item.value);
				if (activity) Object.assign(item, formatActivityOption(activity));
				else {
					item.label = "○ No longer available";
					item.description = "";
				}
			}
			updateSize();
			const lines = list.render(Math.max(1, width - 4));
			listHeight = lines.length;
			return renderPanel(
				"Activities",
				[
					"",
					...lines.map((line) => ` ${line}`),
					"",
					` ${theme.fg("dim", "↑↓ choose · Enter inspect · Esc close")}`,
				],
				width,
				theme,
			);
		},
		dispose: unsubscribe,
		invalidate() {
			list.invalidate();
		},
		handleInput(data) {
			list.handleInput(data);
			tui.requestRender();
		},
		handleMouse(event: TuiMouseEvent) {
			if (
				event.x < 2 ||
				event.x >= event.width - 2 ||
				event.y < 2 ||
				event.y >= listHeight + 2
			)
				return undefined;
			return list.handleMouse({
				...event,
				x: event.x - 2,
				y: event.y - 2,
				width: Math.max(1, event.width - 4),
				height: listHeight,
			});
		},
	};
}

/** Remove terminal controls before rendering activity-owned text in Pi's TUI. */
export function sanitizeActivityText(text: string): string {
	return stripTerminalSequences(text)
		.replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, "�")
		.slice(-OUTPUT_LIMIT);
}

/** Translate Pi's normalized keyboard input to conservative terminal application bytes. */
export function terminalInput(data: string): TerminalInput {
	if (isKeyRelease(data)) return undefined;
	if (data.startsWith("\x1b[200~") && data.endsWith("\x1b[201~"))
		return { text: data.slice(6, -6), paste: true };
	if (matchesKey(data, "ctrl+g")) return { detach: true };
	// Preserve legacy control/Meta bytes instead of Pi editor aliases (e.g. Alt+B → Alt+Left).
	if (
		/^[\x00-\x1f\x7f]$/.test(data) ||
		/^\x1b[^\x00-\x1f\x7f-\x9f]$/u.test(data)
	)
		return { text: data };
	const key = parseKey(data);
	if (key) {
		const mapped = TERMINAL_KEYS[key];
		if (mapped !== undefined) return { text: mapped };
		const modifiers = key.split("+");
		const base = modifiers.pop() ?? "";
		const modifier =
			1 +
			(modifiers.includes("shift") ? 1 : 0) +
			(modifiers.includes("alt") ? 2 : 0) +
			(modifiers.includes("ctrl") ? 4 : 0);
		const sequence = TERMINAL_KEYS[base];
		if (modifier > 1 && sequence?.startsWith("\x1b[")) {
			const navigation = /^\x1b\[([ABCDHF])$/.exec(sequence);
			if (navigation) return { text: `\x1b[1;${modifier}${navigation[1]}` };
			const editing = /^\x1b\[(\d+)~$/.exec(sequence);
			if (editing) return { text: `\x1b[${editing[1]};${modifier}~` };
		}
		if (modifier > 1 && sequence?.startsWith("\x1bO"))
			return { text: `\x1b[1;${modifier}${sequence.at(-1)}` };
		const control = modifiers.includes("ctrl")
			? (CONTROL_KEYS[base] ??
				(/^[a-z]$/i.test(base)
					? String.fromCharCode(base.toLowerCase().charCodeAt(0) - 96)
					: undefined))
			: undefined;
		const text =
			control ??
			sequence ??
			decodeKittyPrintable(data) ??
			(base.length === 1 ? base : undefined);
		if (text !== undefined)
			return { text: (modifiers.includes("alt") ? "\x1b" : "") + text };
	}
	// Pi's keybinding parser need not name every standard modified function key.
	if (/^\x1b\[(?:1;[2-8][PQRS]|(?:15|17|18|19|20|21|23|24);[2-8]~)$/.test(data))
		return { text: data };
	const printable = decodeKittyPrintable(data);
	if (printable !== undefined) return { text: printable };
	return /^[^\u0000-\u001f\u007f\u001b]+$/u.test(data)
		? { text: data }
		: undefined;
}

const CONTROL_KEYS: Record<string, string> = {
	space: "\x00",
	"@": "\x00",
	"[": "\x1b",
	"\\": "\x1c",
	"]": "\x1d",
	"^": "\x1e",
	_: "\x1f",
	"?": "\x7f",
};

const TERMINAL_KEYS: Record<string, string> = {
	escape: "\u001b",
	enter: "\r",
	return: "\r",
	backspace: "\u007f",
	delete: "\u001b[3~",
	insert: "\u001b[2~",
	f1: "\x1bOP",
	f2: "\x1bOQ",
	f3: "\x1bOR",
	f4: "\x1bOS",
	f5: "\x1b[15~",
	f6: "\x1b[17~",
	f7: "\x1b[18~",
	f8: "\x1b[19~",
	f9: "\x1b[20~",
	f10: "\x1b[21~",
	f11: "\x1b[23~",
	f12: "\x1b[24~",
	up: "\u001b[A",
	down: "\u001b[B",
	right: "\u001b[C",
	left: "\u001b[D",
	home: "\u001b[H",
	end: "\u001b[F",
	pageUp: "\u001b[5~",
	pageDown: "\u001b[6~",
	tab: "\t",
	"shift+tab": "\u001b[Z",
	"ctrl+c": "\u0003",
};

function renderPanel(
	title: string,
	rows: string[],
	width: number,
	theme?: Theme,
): string[] {
	const safeWidth = Math.max(1, width);
	if (safeWidth < 3) return [truncateToWidth(title, safeWidth, "")];
	const inner = safeWidth - 2;
	const background = theme?.getBgAnsi("customMessageBg") ?? "";
	const foreground = theme?.getFgAnsi("text") ?? "";
	const edgeStyle = theme?.getFgAnsi("border") ?? "";
	const edge = (text: string) => RESET + background + edgeStyle + text + RESET;
	const caption = truncateToWidth(` ${title} `, inner, "");
	const heading = theme ? theme.fg("accent", theme.bold(caption)) : caption;
	return [
		edge("╭") +
			background +
			heading +
			edge("─".repeat(Math.max(0, inner - visibleWidth(caption))) + "╮"),
		...rows.map((text) => {
			const body = truncateToWidth(singleLine(text), inner, "");
			return (
				edge("│") +
				background +
				foreground +
				body +
				RESET +
				background +
				" ".repeat(Math.max(0, inner - visibleWidth(body))) +
				edge("│")
			);
		}),
		edge(`╰${"─".repeat(inner)}╯`),
	];
}

function duration(milliseconds: number): string {
	const seconds = Math.max(0, Math.ceil(milliseconds / 1000));
	if (seconds < 60) return `${seconds}s`;
	if (seconds < 3600)
		return `${Math.floor(seconds / 60)}m${seconds % 60 ? ` ${seconds % 60}s` : ""}`;
	return `${Math.floor(seconds / 3600)}h${Math.floor((seconds % 3600) / 60) ? ` ${Math.floor((seconds % 3600) / 60)}m` : ""}`;
}

function timerLines(
	activity: ActivitySnapshot,
	timer: TimerView | undefined,
	theme?: Theme,
): string[] {
	if (!timer)
		return [isActive(activity) ? "Waiting for timer…" : "Timer finished"];
	if (activity.status !== "running")
		return [
			`${duration(timer.delayMs)} ${timer.repeat ? "between ticks" : "timer"}`,
		];
	const remaining = Math.max(0, timer.nextAt - Date.now());
	const filled = Math.round(
		20 * Math.max(0, Math.min(1, 1 - remaining / timer.delayMs)),
	);
	const progress = "━".repeat(filled);
	const rest = "─".repeat(20 - filled);
	return [
		`${duration(remaining)} ${timer.repeat ? "until next tick" : "remaining"}`,
		theme
			? theme.fg("accent", progress) + theme.fg("dim", rest)
			: progress + rest,
		...(timer.repeat ? [`Repeats every ${duration(timer.delayMs)}`] : []),
	];
}

export function renderActivityFrame(
	activity: ActivitySnapshot,
	width: number,
	maxRows = 64,
	{
		view,
		theme,
		timer,
		backToPicker = false,
	}: {
		view?: TerminalView;
		theme?: Theme;
		timer?: TimerView;
		backToPicker?: boolean;
	} = {},
): string[] {
	const kind = KINDS[activity.kind];
	const title = `${kind.icon} ${singleLine(sanitizeActivityText(activity.title))}`;
	const meta = `${STATES[activity.status].icon} ${kind.label} · ${statusLabel(activity)}${activity.status === "failed" && activity.exitCode != null ? ` · exit ${activity.exitCode}` : ""}`;
	const error = activity.error
		? `✕ ${sanitizeActivityText(activity.error)}`
		: view?.truncated
			? "View clipped; resize terminal"
			: "";
	const content =
		activity.kind === "terminal"
			? (view?.lines ?? terminalLines(activity, Math.max(1, width - 2)))
			: activity.kind === "timer"
				? timerLines(activity, timer, theme)
				: outputLines(activity);
	const limit = Math.max(1, maxRows - 5);
	const visible =
		activity.kind === "terminal"
			? content.slice(0, limit)
			: content.slice(-limit).map((line) => ` ${line}`);
	const hint =
		activity.kind === "terminal" && isActive(activity)
			? activity.status === "running"
				? "Ctrl+G back · Esc/Ctrl+C → app"
				: "Ctrl+G back"
			: backToPicker
				? "Esc back"
				: "Esc close";
	return renderPanel(
		title,
		[
			` ${theme ? theme.fg(statusColor(activity), meta) : meta}`,
			` ${theme && error ? theme.fg(activity.error ? "error" : "warning", error) : error}`,
			...visible,
			` ${theme ? theme.fg("dim", hint) : hint}`,
		],
		width,
		theme,
	);
}

function singleLine(text: string): string {
	return text.replace(/[\r\n]+/g, " ");
}

function outputLines(activity: ActivitySnapshot): string[] {
	if (activity.kind === "watch") {
		const changes = (activity.events ?? [])
			.filter((event) => event.type === "change")
			.slice(-EVENT_LINES);
		return changes.length
			? changes.map(
					(event) =>
						`↻ ${sanitizeActivityText(event.text ?? "Change detected")}`,
				)
			: [isActive(activity) ? "Watching for changes…" : "No changes recorded"];
	}
	const output = sanitizeActivityText(activity.output ?? "");
	return output
		? output.split("\n").slice(-OUTPUT_LINES)
		: [isActive(activity) ? "Waiting for output…" : "No output"];
}

function terminalLines(activity: ActivitySnapshot, width: number): string[] {
	const screen = activity.screen;
	if (!screen) return ["(terminal screen unavailable)"];
	const lines = sanitizeActivityText(screen.text).split("\n");
	return lines
		.slice(-Math.min(MAX_ROWS, Math.max(MIN_ROWS, screen.rows)))
		.map((line) => sliceByColumn(line, 0, width, true));
}

export class ActivityInspector implements Component, Focusable {
	focused = false;
	private unsubscribe: (() => void) | undefined;
	private refreshTimer: ReturnType<typeof setTimeout> | undefined;
	private resizeTimer: ReturnType<typeof setTimeout> | undefined;
	private clockTimer: ReturnType<typeof setInterval> | undefined;
	private disposed = false;
	private renderedWidth = 0;

	constructor(
		private readonly tui: TUI,
		private readonly theme: Theme,
		private readonly keybindings: KeybindingsManager,
		private readonly done: () => void,
		private readonly manager: ManagerApi,
		private readonly id: string,
		private readonly backToPicker = false,
	) {
		this.unsubscribe = manager.subscribe(() => this.scheduleRefresh());
		const activity = this.current();
		if (activity?.kind === "timer" && activity.status === "running") {
			this.clockTimer = setInterval(() => {
				if (this.current()?.status !== "running") {
					clearInterval(this.clockTimer);
					this.clockTimer = undefined;
				}
				this.scheduleRefresh();
			}, 1000);
			this.clockTimer.unref?.();
		}
	}

	handleInput(data: string): void {
		const activity = this.current();
		if (!activity) {
			this.done();
			return;
		}
		if (activity.kind !== "terminal" || !isActive(activity)) {
			if (
				this.keybindings.matches(data, "tui.select.cancel") ||
				matchesKey(data, "escape") ||
				matchesKey(data, "ctrl+c") ||
				matchesKey(data, "ctrl+g")
			)
				this.done();
			return;
		}
		const input = terminalInput(data);
		if (input?.detach) {
			this.done();
			return;
		}
		if (input?.text && activity.status === "running") {
			try {
				this.manager.write(this.id, input.text, input.paste, true);
			} catch {
				this.done();
			}
		}
	}

	render(width: number): string[] {
		this.renderedWidth = Math.max(1, width);
		this.scheduleResize();
		const activity = this.current();
		if (!activity)
			return [
				this.theme.fg(
					"warning",
					truncateToWidth("Activity no longer exists", width, ""),
				),
			];
		const height = Math.max(1, Math.floor(this.tui.terminal.rows * 0.9));
		if (width < 22 || height < 11)
			return [
				this.theme.fg(
					"muted",
					truncateToWidth("Activities: enlarge terminal", width, ""),
				),
			];
		const view =
			activity.kind === "terminal"
				? this.manager.terminalView(this.id)
				: undefined;
		const lines = renderActivityFrame(activity, width, height, {
			view,
			theme: this.theme,
			backToPicker: this.backToPicker,
			timer:
				activity.kind === "timer" ? this.manager.timerView(this.id) : undefined,
		});
		const screen = activity.screen;
		if (
			this.focused &&
			activity.status === "running" &&
			screen &&
			!screen.truncated &&
			(!view || view.cursor)
		) {
			const row = (view?.cursor?.y ?? screen.cursorY) + 3;
			const column = (view?.cursor?.x ?? screen.cursorX) + 1;
			if (row < lines.length - 2 && column < width - 1) {
				const line = lines[row];
				const cursor = view?.cursor;
				const cell = cursor?.text ?? (sliceByColumn(line, column, 1) || " ");
				const cellWidth = cursor?.width ?? visibleWidth(cell);
				const style = cursor?.style ?? "";
				const painted = this.tui.getShowHardwareCursor()
					? cell
					: cursor?.inverse
						? `\x1b[27m${cell}`
						: renderFakeCursor(cell);
				lines[row] =
					sliceByColumn(line, 0, column, true) +
					style +
					CURSOR_MARKER +
					painted +
					style +
					sliceByColumn(
						line,
						column + cellWidth,
						width - column - cellWidth,
						true,
					) +
					RESET;
			}
		}
		return lines;
	}

	invalidate(): void {}

	dispose(): void {
		this.disposed = true;
		this.unsubscribe?.();
		if (this.refreshTimer) clearTimeout(this.refreshTimer);
		if (this.resizeTimer) clearTimeout(this.resizeTimer);
		if (this.clockTimer) clearInterval(this.clockTimer);
	}

	private current(): ActivitySnapshot | undefined {
		try {
			return this.manager.read(this.id);
		} catch {
			return undefined;
		}
	}

	private scheduleRefresh(): void {
		if (this.disposed || this.refreshTimer) return;
		this.refreshTimer = setTimeout(() => {
			this.refreshTimer = undefined;
			if (!this.disposed) this.tui.requestRender();
		}, REFRESH_MS);
	}

	private scheduleResize(): void {
		if (this.disposed || this.resizeTimer) return;
		this.resizeTimer = setTimeout(() => {
			this.resizeTimer = undefined;
			const activity = this.current();
			if (
				this.disposed ||
				activity?.kind !== "terminal" ||
				activity.status !== "running" ||
				this.renderedWidth < 22 ||
				this.tui.terminal.rows < 13
			)
				return;
			const cols = clamp(this.renderedWidth - 2, MIN_COLS, MAX_COLS);
			const rows = clamp(
				Math.floor(this.tui.terminal.rows * 0.9) - 6,
				MIN_ROWS,
				MAX_ROWS,
			);
			if (activity.screen?.cols === cols && activity.screen.rows === rows)
				return;
			try {
				this.manager.resize(this.id, cols, rows);
			} catch {
				this.done();
			}
		}, 0);
	}
}

function statusColor(activity: ActivitySnapshot) {
	if (activity.status === "completed") return "success" as const;
	if (activity.status === "failed") return "error" as const;
	if (activity.status === "running") return "accent" as const;
	return "warning" as const;
}

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

function errorMessage(error: unknown): string {
	return error instanceof Error ? error.message : String(error);
}