Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/ephemlets/src/panel.ts

Raw
import {
	type ExtensionContext,
	getMarkdownTheme,
	type Theme,
} from "@earendil-works/pi-coding-agent";
import {
	type Color,
	getOsc8LinkAtColumn,
	Input,
	Markdown,
	matchesKey,
	type OverlayHandle,
	type OverlayOptions,
	stripTerminalSequences,
	type TUI,
	type TuiMouseEvent,
	type TuiMouseEventResult,
	truncateToWidth,
	visibleWidth,
	wrapTextWithAnsi,
} from "@earendil-works/pi-tui";
import { type IconSet, Look, Palette } from "./look.ts";
import {
	deliveryOf,
	type EphemletStore,
	isChecked,
	isSingle,
	needsAnswer,
	optionsOf,
} from "./store.ts";
import type { Ephemlet, Field } from "./types.ts";

/** A fake cursor drawn over whitespace, as pi-tui's Input renders it. */
const FAKE_CURSOR_SPACE = /(\x1b_pi:fc\x07)\s(\x1b_pi:\/fc\x07)/;
/** Same-width non-whitespace stand-in, restored to a space after wrapping. */
const CURSOR_CELL = "\u{F8FF}";

export function panelGeometry(
	columns: number,
	rows: number,
): { width: number; height: number; anchor: "top-right" | "top-left" } {
	// Terminal cells are approximately twice as tall as wide.
	const landscape = columns >= rows * 2;
	return {
		width: Math.max(
			1,
			Math.min(
				columns,
				landscape ? Math.max(32, Math.floor(columns * 0.45)) : columns,
			),
		),
		height: Math.max(
			1,
			Math.min(rows, landscape ? rows - 4 : Math.floor(rows * 0.48)),
		),
		anchor: landscape ? "top-right" : "top-left",
	};
}

type ItemRef = { field: string; item: string };
/** A clickable cell range; rows without ranges are not interactive. */
type Target = { from: number; to: number; ref: ItemRef };
type Line = { text: string; targets?: Target[] };
const same = (a: ItemRef | undefined, b: ItemRef | undefined) =>
	a?.field === b?.field && a?.item === b?.item;
const plain = (text: string) => text.replace(/\p{Cc}/gu, " ");

type PanelActions = {
	changed(): void;
	close(id: string): void;
	save(id: string): void;
	hide(): void;
	answered(id: string, fieldId: string): void;
};

/** Appends segments while tracking their columns for hit testing. */
class RowBuilder {
	text = "";
	width = 0;
	readonly targets: Target[] = [];
	add(text: string, ref?: ItemRef): this {
		const from = this.width;
		this.text += text;
		this.width += visibleWidth(text);
		if (ref) this.targets.push({ from, to: this.width, ref });
		return this;
	}
	/** Fills the rest of the row with the row background. */
	fill(width: number, paint: (text: string) => string): string {
		return this.text + paint(" ".repeat(Math.max(0, width - this.width)));
	}
}

export class EphemletPanel {
	focused = false;
	private markdown:
		| { id: string; revision: number; component: Markdown }
		| undefined;
	private linkGesture = false;
	/** Pinned "N needs you" row shown while open questions are scrolled out of view. */
	private marker: { y: number; target: ItemRef } | undefined;
	/** Body rows actually visible; one less than contentHeight while the marker shows. */
	private viewHeight = 1;
	private focus: ItemRef | undefined;
	private hover: ItemRef | undefined;
	/** Inline editor for a text field; keys go to it until enter or escape. */
	private editing: { ref: ItemRef; input: Input } | undefined;
	private lines: Line[] = [];
	private scroll = 0;
	private contentHeight = 1;
	private totalLines = 0;
	private disposed = false;
	private saveRange: [number, number] = [0, 0];
	private deleteRange: [number, number] = [0, 0];
	private pagesRange: [number, number] = [0, 0];
	private renderedLines: string[] = [];
	private readonly renderedFrames = new Map<
		string,
		{
			revision: number;
			answerRevision: number;
			width: number;
			height: number;
			lines: string[];
		}
	>();

	constructor(
		private readonly store: EphemletStore,
		readonly tui: TUI,
		private readonly theme: Theme,
		private readonly actions: PanelActions,
		private readonly look: () => Look,
	) {}

	geometry(): ReturnType<typeof panelGeometry> {
		return panelGeometry(this.tui.terminal.columns, this.tui.terminal.rows);
	}

	refresh(): void {
		if (this.disposed) return;
		for (const id of this.renderedFrames.keys()) {
			if (!this.store.records.has(id)) this.renderedFrames.delete(id);
		}
		this.invalidate();
		this.tui.requestRender();
	}

	private body(
		record: Ephemlet | undefined,
		look: Look,
		width: number,
	): Line[] {
		if (!record) return [];
		if (
			this.markdown?.id !== record.id ||
			this.markdown.revision !== record.revision
		) {
			// A new revision from the agent starts at the top so its context is visible.
			if (this.markdown?.id === record.id) this.scroll = 0;
			this.markdown = {
				id: record.id,
				revision: record.revision,
				component: new Markdown(record.source, 1, 1, getMarkdownTheme(), {
					bgColor: (text) => this.theme.bg("customMessageBg", text),
				}),
			};
		}
		const lines: Line[] = this.markdown.component
			.render(width)
			.map((text) => ({ text }));
		for (const field of record.fields)
			lines.push(...this.field(record, field, look, width));
		if (record.fields.length) lines.push({ text: this.blank(look, width) });
		return lines;
	}

	private blank(look: Look, width: number): string {
		return look.on(look.surface)(" ".repeat(width));
	}

	/** Banded header, then one row per option; confirm renders as Yes/No segments. */
	private field(
		record: Ephemlet,
		field: Field,
		look: Look,
		width: number,
	): Line[] {
		const lines: Line[] = [];
		const needs = needsAnswer(record, field);
		const delivery = deliveryOf(field);
		const waiting = this.store.waiting.get(record.id)?.has(field.id) ?? false;
		if (field.label || needs || delivery !== "ambient" || waiting) {
			// "now" answers interrupt the agent, so their band is tinted and labelled before you click.
			const band = look.on(
				delivery === "now" || waiting ? look.urgentBand : look.band,
			);
			const row = new RowBuilder().add(band(" "));
			if (field.label)
				row.add(band(plain(field.label), look.text, { bold: true }));
			if (needs)
				row
					.add(band(field.label ? "  " : ""))
					.add(
						look.on(look.accent)(" needs you ", look.onAccent, { bold: true }),
					);
			const chip = waiting
				? band(`${look.icon("waiting")} agent waiting `, look.accent, {
						bold: true,
					})
				: delivery === "now"
					? band(`${look.icon("now")} instant `, look.warn, { bold: true })
					: delivery === "next"
						? band(`${look.icon("next")} next turn `, look.muted)
						: "";
			const gap = width - row.width - visibleWidth(chip);
			lines.push({
				text:
					gap >= 1
						? row.text + band(" ".repeat(gap)) + chip
						: truncateToWidth(row.fill(width, band), width, ""),
			});
		}
		if (field.type === "text") {
			const surface = look.on(look.surface);
			const ref = { field: field.id, item: "text" };
			const editor =
				this.editing && same(this.editing.ref, ref) && this.editing.input;
			const focused = !!editor || same(this.focus, ref);
			const bg = focused
				? look.focus
				: same(this.hover, ref) && look.hover
					? look.hover
					: look.pill;
			const answer = record.texts[field.id];
			const fg =
				focused && look.focusText
					? look.focusText
					: !editor && answer === undefined
						? look.muted
						: look.text;
			// Render the editor unscrolled, then wrap it like the read-only answer.
			const body = editor
				? (editor.render(
						Math.max(
							visibleWidth(editor.getValue()),
							visibleWidth(field.placeholder ?? ""),
						) + 2,
					)[0] ?? "")
				: plain(answer ?? field.placeholder ?? "Type an answer");
			const inner = Math.max(1, width - 4);
			const paint = look.on(bg);
			// Wrapping drops whitespace at row breaks; shield the fake cursor cell so it survives.
			const shielded = body.replace(FAKE_CURSOR_SPACE, `$1${CURSOR_CELL}$2`);
			for (const row of wrapTextWithAnsi(
				`${look.icon("edit")} ${shielded}`,
				inner,
			)) {
				const fitted = truncateToWidth(row, inner, "").replace(
					CURSOR_CELL,
					" ",
				);
				lines.push({
					text:
						surface(" ") +
						paint(
							` ${fitted}${" ".repeat(Math.max(0, inner - visibleWidth(fitted)))} `,
							fg,
						) +
						surface(" "),
					targets: [{ from: 0, to: width, ref }],
				});
			}
			lines.push({ text: this.blank(look, width) });
			return lines;
		}
		if (field.type === "confirm") {
			const surface = look.on(look.surface);
			const row = new RowBuilder().add(surface(" "));
			for (const option of optionsOf(field)) {
				const ref = { field: field.id, item: option.id };
				const selected = isChecked(record, field, option);
				const focused = same(this.focus, ref);
				const bg = selected
					? option.id === "yes"
						? look.ok
						: look.accent
					: focused
						? look.focus
						: same(this.hover, ref) && look.hover
							? look.hover
							: look.pill;
				const fg = selected
					? look.onAccent
					: focused
						? (look.focusText ?? look.text)
						: bg === look.muted
							? look.onAccent
							: look.text;
				row.add(
					look.on(bg)(` ${plain(option.label)} `, fg, { bold: selected }),
					ref,
				);
				row.add(surface(" "));
			}
			lines.push({ text: row.fill(width, surface), targets: row.targets });
			return lines;
		}
		const single = isSingle(field);
		for (const option of optionsOf(field)) {
			const ref = { field: field.id, item: option.id };
			const checked = isChecked(record, field, option);
			const focused = same(this.focus, ref);
			const bg = focused
				? look.focus
				: same(this.hover, ref) && look.hover
					? look.hover
					: look.surface;
			const paint = look.on(bg);
			const byUser = record.answers[field.id]?.[option.id] !== undefined;
			// Unticking an item the agent had checked is a veto, not just "not done".
			const vetoed =
				field.type === "checklist" && option.checked === true && !checked;
			const text = focused && look.focusText ? look.focusText : look.text;
			const iconColor: Color =
				focused && look.focusText
					? look.focusText
					: checked
						? single
							? look.accent
							: look.ok
						: look.muted;
			const row = new RowBuilder()
				.add(paint(" "))
				.add(
					paint(
						look.icon(
							single
								? checked
									? "radioOn"
									: "radioOff"
								: checked
									? "checkOn"
									: "checkOff",
						),
						iconColor,
					),
				)
				.add(paint(" "))
				.add(
					paint(
						plain(option.label),
						vetoed && !look.focusText ? look.muted : text,
						{
							strikethrough: vetoed,
						},
					),
				);
			if (field.type === "checklist" && byUser)
				row.add(
					paint(
						"  · you",
						focused && look.focusText ? look.focusText : look.muted,
					),
				);
			const full = truncateToWidth(row.fill(width, paint), width, "");
			lines.push({ text: full, targets: [{ from: 0, to: width, ref }] });
		}
		lines.push({ text: this.blank(look, width) });
		return lines;
	}

	private moveFocus(delta: number): void {
		// Wrapped answers repeat their target on every row; focus moves per answer.
		const items = this.lines
			.flatMap((line) => (line.targets ?? []).map((target) => target.ref))
			.filter(
				(item, index, all) =>
					all.findIndex((other) => same(other, item)) === index,
			);
		if (!items.length) return;
		const index = items.findIndex((item) => same(item, this.focus));
		// The first tab goes straight to an open question, if any.
		const open = index < 0 && delta > 0 ? this.openQuestion() : undefined;
		this.reveal(
			open ??
				items[
					index < 0
						? delta > 0
							? 0
							: items.length - 1
						: (index + delta + items.length) % items.length
				],
		);
	}

	private openQuestion(): ItemRef | undefined {
		const id = this.store.selected;
		const record = id ? this.store.records.get(id) : undefined;
		const field = record?.fields.find((f) => needsAnswer(record, f));
		const option = field && optionsOf(field)[0];
		return field && option ? { field: field.id, item: option.id } : undefined;
	}

	/** Focuses an answer row and scrolls it, with its field header, into view. */
	private reveal(ref: ItemRef | undefined): void {
		this.focus = ref;
		const row = this.lines.findIndex((line) =>
			line.targets?.some((target) => same(target.ref, ref)),
		);
		if (row >= 0 && row < this.scroll) this.scroll = Math.max(0, row - 1);
		else if (row >= this.scroll + this.viewHeight)
			this.scroll = row - this.viewHeight + 1;
		this.tui.requestRender();
	}

	private toggle(ref: ItemRef): void {
		const id = this.store.selected;
		if (!id) return;
		const field = this.store.records
			.get(id)
			?.fields.find((candidate) => candidate.id === ref.field);
		if (field?.type === "text") {
			if (!same(this.editing?.ref, ref))
				this.edit(id, field.id, field.placeholder, ref);
			return;
		}
		if (this.store.toggle(id, ref.field, ref.item))
			this.actions.answered(id, ref.field);
		this.focus = ref;
		this.tui.requestRender();
	}

	private edit(
		id: string,
		fieldId: string,
		placeholder: string | undefined,
		ref: ItemRef,
	): void {
		const input = new Input({
			prompt: "",
			...(placeholder
				? {
						placeholder,
						placeholderStyle: (text: string) => this.theme.fg("muted", text),
					}
				: {}),
		});
		input.setValue(this.store.get(id).texts[fieldId] ?? "");
		input.focused = true;
		input.onSubmit = (value) => {
			this.editing = undefined;
			if (this.store.setText(id, fieldId, value))
				this.actions.answered(id, fieldId);
			this.tui.requestRender();
		};
		input.onEscape = () => {
			this.editing = undefined;
			this.tui.requestRender();
		};
		this.editing = { ref, input };
		this.focus = ref;
		this.tui.requestRender();
	}

	switch(delta: number): void {
		const ids = [...this.store.records.keys()];
		if (!ids.length) return;
		const current = this.store.selected ? ids.indexOf(this.store.selected) : 0;
		this.store.view(
			ids[(current + delta + ids.length) % ids.length] ?? null,
			true,
		);
		this.scroll = 0;
		this.focus = undefined;
		this.editing = undefined;
		this.actions.changed();
	}

	handleInput(data: string): void {
		if (this.editing) {
			this.editing.input.handleInput(data);
			this.tui.requestRender();
			return;
		}
		const id = this.store.selected;
		if (matchesKey(data, "escape") || matchesKey(data, "alt+e")) {
			this.actions.hide();
			return;
		}
		if (matchesKey(data, "alt+left")) {
			this.switch(-1);
			return;
		}
		if (matchesKey(data, "alt+right")) {
			this.switch(1);
			return;
		}
		if (id && matchesKey(data, "ctrl+s")) {
			this.actions.save(id);
			return;
		}
		if (id && matchesKey(data, "ctrl+w")) {
			this.actions.close(id);
			return;
		}
		if (matchesKey(data, "tab") || matchesKey(data, "shift+tab")) {
			this.moveFocus(matchesKey(data, "tab") ? 1 : -1);
			return;
		}
		if (
			this.focus &&
			(matchesKey(data, "space") || matchesKey(data, "enter"))
		) {
			this.toggle(this.focus);
			return;
		}
		if (matchesKey(data, "up") || matchesKey(data, "pageUp"))
			this.scrollBy(matchesKey(data, "up") ? -1 : -this.viewHeight);
		else if (matchesKey(data, "down") || matchesKey(data, "pageDown"))
			this.scrollBy(matchesKey(data, "down") ? 1 : this.viewHeight);
	}

	private scrollBy(delta: number): void {
		this.scroll = Math.max(
			0,
			Math.min(
				Math.max(0, this.totalLines - this.viewHeight),
				this.scroll + delta,
			),
		);
		this.tui.requestRender();
	}

	/** True when Pi's renderer must own OSC 8 activation and text selection. */
	private isLinkEvent(event: TuiMouseEvent): boolean {
		const line = this.renderedLines[event.y];
		return (
			line !== undefined && getOsc8LinkAtColumn(line, event.x) !== undefined
		);
	}

	private targetAt(event: TuiMouseEvent): ItemRef | undefined {
		if (event.y < 1 || event.y > this.viewHeight) return undefined;
		return this.lines[this.scroll + event.y - 1]?.targets?.find(
			(target) => event.x >= target.from && event.x < target.to,
		)?.ref;
	}

	getView(id: string):
		| {
				available: true;
				plainText: string;
				width: number;
				height: number;
				revision: number;
				stale: boolean;
				truncated: boolean;
		  }
		| { available: false; reason: string } {
		const frame = this.renderedFrames.get(id);
		if (!frame) return { available: false, reason: "Never rendered" };
		const record = this.store.records.get(id);
		if (!record) return { available: false, reason: "Ephemlet unavailable" };
		let truncated = false;
		let bytes = 0;
		const lines: string[] = [];
		for (const line of frame.lines.slice(0, 40)) {
			const plainLine = stripTerminalSequences(line).trimEnd();
			let bounded = plainLine;
			if (visibleWidth(plainLine) > 200) {
				truncated = true;
				bounded = truncateToWidth(plainLine, 200, "");
			}
			const remaining = 24 * 1024 - bytes;
			if (remaining <= 0) {
				truncated = true;
				break;
			}
			const buffer = Buffer.from(bounded);
			let end = Math.min(buffer.length, remaining);
			while (end > 0 && end < buffer.length) {
				const next = buffer[end];
				if (next === undefined || (next & 0xc0) !== 0x80) break;
				end--;
			}
			const value = buffer.subarray(0, end).toString("utf8");
			if (value !== bounded) truncated = true;
			bytes += Buffer.byteLength(value);
			lines.push(value);
		}
		if (frame.lines.length > lines.length) truncated = true;
		return {
			available: true,
			plainText: lines.join("\n"),
			width: Math.min(200, frame.width),
			height: Math.min(40, frame.height),
			revision: frame.revision,
			stale:
				frame.revision !== record.revision ||
				frame.answerRevision !== record.answerRevision,
			truncated,
		};
	}

	private rememberFrame(
		lines: string[],
		width: number,
		record: Ephemlet | undefined,
	): string[] {
		this.renderedLines = lines;
		if (record)
			this.renderedFrames.set(record.id, {
				revision: record.revision,
				answerRevision: record.answerRevision,
				width,
				height: lines.length,
				lines: [...lines],
			});
		return lines;
	}

	handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
		if (this.disposed) return { handled: true };
		if (event.type === "move") {
			const hover = this.targetAt(event);
			if (same(hover, this.hover)) return { handled: true };
			this.hover = hover;
			return { handled: true, render: true };
		}
		if (event.type === "press") this.linkGesture = false;
		// Returning undefined keeps the complete OSC 8 gesture with Pi's renderer.
		// It needs press/release/drag to distinguish opening from text selection.
		if (
			this.linkGesture ||
			(event.button === "left" &&
				["press", "release", "click"].includes(event.type) &&
				this.isLinkEvent(event))
		) {
			if (event.type === "press") this.linkGesture = true;
			if (event.type === "release") this.linkGesture = false;
			return undefined;
		}
		const activate =
			event.button === "left" &&
			(event.type === "press" || event.type === "click");
		if (event.y === 0 && event.type === "click" && event.button === "left") {
			const id = this.store.selected;
			const inside = (range: [number, number]) =>
				event.x >= range[0] && event.x < range[1];
			if (id && inside(this.deleteRange)) this.actions.close(id);
			else if (id && inside(this.saveRange)) this.actions.save(id);
			else if (inside(this.pagesRange))
				this.switch(
					event.x < (this.pagesRange[0] + this.pagesRange[1]) / 2 ? -1 : 1,
				);
			return { handled: true, focus: true, render: true };
		}
		if (
			this.marker &&
			event.y === this.marker.y &&
			event.type === "click" &&
			event.button === "left"
		) {
			this.reveal(this.marker.target);
			return { handled: true, focus: true, render: true };
		}
		const target =
			event.type === "click" && event.button === "left"
				? this.targetAt(event)
				: undefined;
		// Clicking anywhere else abandons an unsubmitted edit.
		if (
			event.type === "click" &&
			this.editing &&
			!same(target, this.editing.ref)
		)
			this.editing = undefined;
		if (target) {
			this.toggle(target);
			return { handled: true, focus: true, render: true };
		}
		if (event.type === "wheel") {
			this.scrollBy(event.wheelDelta ?? 0);
			return { handled: true, render: true };
		}
		return { handled: true, focus: activate, render: false };
	}

	private header(
		record: Ephemlet | undefined,
		look: Look,
		width: number,
	): string {
		const band = look.on(look.band);
		const left = new RowBuilder()
			.add(band(" "))
			.add(
				band(plain(record?.title ?? "Ephemlets"), look.text, { bold: true }),
			);
		const checklist = record?.fields.flatMap((field) =>
			field.type === "checklist"
				? optionsOf(field).map((option) => isChecked(record, field, option))
				: [],
		);
		if (checklist?.length) {
			const done = checklist.filter(Boolean).length;
			const cells = 8;
			const filled = Math.round((done / checklist.length) * cells);
			left.add(band("  "));
			for (let i = 0; i < cells; i++)
				left.add(look.on(i < filled ? look.ok : look.track)(" "));
			left.add(band(` ${done}/${checklist.length}`, look.muted));
		}
		const right = new RowBuilder();
		if (record?.fields.length && record.answerRevision > 0) {
			const [name, label, color] =
				record.seenRevision === record.answerRevision
					? (["read", "read", look.ok] as const)
					: (this.store.sent.get(record.id) ?? 0) >= record.answerRevision
						? (["sent", "sent", look.muted] as const)
						: (["unread", "unread", look.warn] as const);
			right.add(band(`${look.icon(name)} ${label}  `, color));
		}
		const saveAt = right.width;
		right.add(band(look.icon("save"), look.muted));
		right.add(band(" "));
		const deleteAt = right.width;
		right.add(band(look.icon("delete"), look.muted));
		right.add(band("  "));
		const pagesAt = right.width;
		const ids = [...this.store.records.keys()];
		const index = Math.max(0, ids.indexOf(record?.id ?? ""));
		right.add(
			ids.length <= 8
				? ids
						.map((_, i) =>
							band(
								i === index ? "●" : "○",
								i === index ? look.accent : look.muted,
							),
						)
						.join("")
				: band(`${index + 1}/${ids.length}`, look.muted),
		);
		const pagesEnd = right.width;
		right.add(band(" "));
		const gap = width - left.width - right.width;
		if (gap < 1) {
			this.saveRange = this.deleteRange = this.pagesRange = [0, 0];
			return truncateToWidth(left.fill(width, band), width, "");
		}
		const offset = left.width + gap;
		this.saveRange = [offset + saveAt, offset + saveAt + 1];
		this.deleteRange = [offset + deleteAt, offset + deleteAt + 1];
		this.pagesRange = [offset + pagesAt, offset + pagesEnd];
		return left.text + band(" ".repeat(gap)) + right.text;
	}

	render(width: number): string[] {
		if (this.disposed) return [];
		const height = this.geometry().height;
		const id = this.store.selected;
		const record = id ? this.store.records.get(id) : undefined;
		if (width < 4 || height < 4) {
			this.contentHeight = 0;
			this.saveRange = this.deleteRange = this.pagesRange = [0, 0];
			return this.rememberFrame(
				[truncateToWidth("Ephemlets: enlarge terminal", width, "")],
				width,
				record,
			);
		}
		const look = this.look();
		this.contentHeight = height - 2;
		const body = this.body(record, look, width);
		this.lines = body;
		this.totalLines = body.length;
		this.scroll = Math.max(
			0,
			// Uses last frame's visible height so the marker row cannot hide the final lines.
			Math.min(
				this.scroll,
				Math.max(
					0,
					body.length - Math.min(this.viewHeight, this.contentHeight),
				),
			),
		);
		const band = look.on(look.band);
		const lines = [this.header(record, look, width)];
		const firstRow = (field: string) =>
			body.findIndex((line) =>
				line.targets?.some((target) => target.ref.field === field),
			);
		const hidden = (view: number) =>
			(record?.fields ?? []).filter((field) => {
				if (!record || !needsAnswer(record, field)) return false;
				const row = firstRow(field.id);
				return row < this.scroll || row >= this.scroll + view;
			});
		let missing = hidden(this.contentHeight);
		this.viewHeight = this.contentHeight;
		if (missing.length && this.contentHeight > 1) {
			this.viewHeight = this.contentHeight - 1;
			missing = hidden(this.viewHeight);
		}
		for (let i = 0; i < this.viewHeight; i++)
			lines.push(body[this.scroll + i]?.text ?? this.blank(look, width));
		const open = missing[0];
		const option = open && optionsOf(open)[0];
		this.marker = undefined;
		if (open && option) {
			const arrow = firstRow(open.id) < this.scroll ? "↑" : "↓";
			const surface = look.on(look.surface);
			const row = new RowBuilder().add(surface(" ")).add(
				look.on(look.accent)(
					` ${arrow} ${missing.length} needs you `,
					look.onAccent,
					{
						bold: true,
					},
				),
			);
			lines.push(row.fill(width, surface));
			this.marker = {
				y: this.viewHeight + 1,
				target: { field: open.id, item: option.id },
			};
		} else if (this.viewHeight < this.contentHeight)
			lines.push(this.blank(look, width));
		const hint = this.editing
			? " enter submit · esc cancel"
			: record?.fields.length
				? " tab move · space select · ^s save · esc close"
				: " ↑↓ scroll · alt+←/→ switch · ^s save · esc close";
		lines.push(
			band(truncateToWidth(hint, width, "").padEnd(width), look.muted),
		);
		return this.rememberFrame(lines, width, record);
	}

	invalidate(): void {
		this.markdown?.component.invalidate();
	}

	dispose(): void {
		if (this.disposed) return;
		this.disposed = true;
		this.linkGesture = false;
		this.markdown = undefined;
		this.lines = [];
		this.renderedFrames.clear();
		this.renderedLines = [];
	}
}

export class PanelHost {
	private panel: EphemletPanel | undefined;
	private handle: OverlayHandle | undefined;
	private tui: TUI | undefined;
	private theme: Theme | undefined;
	private palette: Palette | undefined;
	private ui: ExtensionContext["ui"] | undefined;
	private registered = false;
	constructor(
		private readonly store: EphemletStore,
		private readonly context: () => ExtensionContext,
		private readonly actions: PanelActions,
		private readonly icons: () => IconSet = () => "nerd",
	) {}

	refresh(focus = false): void {
		const ctx = this.context();
		if (ctx.mode !== "tui") return;
		if (!this.store.records.size) {
			this.clearPanel();
			if (this.registered) ctx.ui.setWidget("ephemlets-host", undefined);
			this.registered = false;
			return;
		}
		if (!this.registered) this.register(ctx);
		if (!this.tui || !this.theme) return;
		if (this.store.visible) this.ensurePanel(focus);
		else if (this.panel) {
			this.handle?.setHidden(true);
			this.panel.refresh();
		}
		this.tui.requestRender();
	}

	getView(id: string): ReturnType<EphemletPanel["getView"]> {
		return (
			this.panel?.getView(id) ?? {
				available: false,
				reason: "Never rendered",
			}
		);
	}

	private look(theme: Theme): Look {
		return new Look(theme, this.palette, this.icons());
	}

	private indicator(theme: Theme, width: number): string[] {
		if (!this.store.records.size) return [];
		let needs = 0;
		for (const record of this.store.records.values())
			for (const field of record.fields)
				if (needsAnswer(record, field)) needs++;
		const look = this.look(theme);
		const fg = (text: string, color: Color) => theme.style(text, { fg: color });
		const line = [
			fg(` ${look.icon("bell")}`, needs ? look.accent : look.muted),
			fg(` Ephemlets ${this.store.records.size}`, look.muted),
			needs
				? fg(" ", look.muted) +
					theme.style(` ${needs} needs you `, {
						fg: look.onAccent,
						bg: look.accent,
						bold: true,
					})
				: "",
			fg(` · alt+e ${this.store.visible ? "collapse" : "expand"}`, look.muted),
		].join("");
		return [truncateToWidth(line, Math.max(1, width), "")];
	}

	private register(ctx: ExtensionContext): void {
		this.registered = true;
		this.ui = ctx.ui;
		try {
			ctx.ui.setWidget(
				"ephemlets-host",
				(tui, theme) => {
					this.tui = tui;
					this.theme = theme;
					this.palette?.dispose();
					this.palette = new Palette(tui, () => {
						this.panel?.invalidate();
						tui.requestRender();
					});
					if (this.store.visible) this.ensurePanel(false);
					return {
						render: (width: number) => this.indicator(theme, width),
						invalidate: () => this.panel?.invalidate(),
						dispose: () => {
							this.clearPanel();
							this.palette?.dispose();
							this.palette = undefined;
							this.tui = undefined;
							this.theme = undefined;
							this.registered = false;
						},
					};
				},
				{ placement: "aboveEditor" },
			);
		} catch (error) {
			this.clearPanel();
			this.registered = false;
			ctx.ui.notify(`Ephemlet panel: ${String(error)}`, "error");
		}
	}

	private ensurePanel(focus: boolean): void {
		const { tui, theme } = this;
		if (!tui || !theme) return;
		if (!this.panel) {
			const panel = new EphemletPanel(
				this.store,
				tui,
				theme,
				this.actions,
				() => this.look(theme),
			);
			this.panel = panel;
			const options: OverlayOptions = {
				get width() {
					return panel.geometry().width;
				},
				get maxHeight() {
					return panel.geometry().height;
				},
				get anchor() {
					return panel.geometry().anchor;
				},
				nonCapturing: true,
			};
			this.handle = tui.showOverlay(panel, options);
		}
		this.handle?.setHidden(false);
		this.panel.refresh();
		if (focus) this.handle?.focus();
	}

	private clearPanel(): void {
		this.handle?.hide();
		this.panel?.dispose();
		this.panel = undefined;
		this.handle = undefined;
	}

	dispose(): void {
		this.clearPanel();
		this.palette?.dispose();
		this.palette = undefined;
		if (this.registered) this.ui?.setWidget("ephemlets-host", undefined);
		this.registered = false;
		this.tui = undefined;
		this.theme = undefined;
		this.ui = undefined;
	}
}