Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/loop/__tests__/widget.test.ts

Raw
import type { Theme } from "@earendil-works/pi-coding-agent";
import {
	Input,
	type OverlayHandle,
	sliceByColumn,
	stripTerminalSequences,
	Text,
	TuiAltScreen,
	TuiMainScreen,
	visibleWidth,
} from "@earendil-works/pi-tui";
import { afterEach, describe, expect, it, vi } from "vitest";
import { createCompanion, H } from "../src/companion.ts";
import type { LoopSnapshot } from "../src/controller.ts";
import { ICON } from "../src/icons.ts";
import { createLoopWidget } from "../src/widget.ts";
import { MemoryTerminal } from "./terminal.ts";

const themes = await import(
	new URL(
		"./modes/interactive/theme/theme.js",
		import.meta.resolve("@earendil-works/pi-coding-agent"),
	).href
);
const plain = (lines: string[]) => stripTerminalSequences(lines.join("\n"));
const snapshot = (): LoopSnapshot => ({
	id: "widget",
	goal: "Done",
	gates: [{ name: "silent", command: "unused" }],
	cwd: ".",
	budgets: { minutes: null, turns: 30, attempts: 10 },
	status: "active",
	reason: "",
	turns: 6,
	attempts: 3,
	createdAt: 0,
	updatedAt: 0,
	deadline: null,
	lastPass: null,
	runningGate: 0,
	runningSince: 0,
	liveOutput: null,
	pending: true,
	pendingAudit: 0,
	storageError: null,
});
afterEach(() => vi.useRealTimers());

describe("passive corner portrait with compact inline status", () => {
	for (const Renderer of [TuiAltScreen, TuiMainScreen]) {
		it.each([false, true])(
			`${Renderer.name}: preserves editor input, inline rows and foreign capturing overlay (kitten=%s)`,
			(kitten) => {
				vi.useFakeTimers();
				vi.setSystemTime(0);
				const terminal = new MemoryTerminal();
				const tui = new Renderer(terminal);
				const theme: Theme = themes.getThemeByName("dark");
				const current = {
					run: snapshot(),
					baseline: true,
					agentRunning: false,
					vixen: true,
				};
				const handles: OverlayHandle[] = [];
				const show = tui.showOverlay.bind(tui);
				tui.showOverlay = (component, options) => {
					const handle = show(component, options);
					handles.push(handle);
					return handle;
				};
				// This is the same public factory boundary as ctx.ui.setWidget.
				const factory = (host: typeof tui, appearance: Theme) =>
					createLoopWidget(host, appearance, () => current, kitten);
				const widget = factory(tui, theme);
				const editor = new Input();
				tui.addChild(new Text("transcript\n".repeat(20), 0, 0));
				tui.addChild(widget);
				tui.addChild(editor);
				tui.setFocus(editor);
				tui.start();
				let foreign: OverlayHandle | undefined;
				try {
					tui.renderNow();
					const on = widget.render(120);
					expect(on).toHaveLength(3);
					expect(plain(on)).not.toMatch(/[▀▄]/u);
					expect(plain(on)).toContain("Baseline · silent [1/1]");
					expect(plain(on)).toContain("no output yet");
					expect(plain(on)).toContain("Esc / /loop pause");
					expect(plain(on).split(ICON.gate)).toHaveLength(2);
					expect(plain(on).split(ICON.turn)).toHaveLength(2);
					const portrait = handles.at(-1)!;
					expect(portrait.isFocused()).toBe(false);
					expect(portrait.getBounds()!.row + portrait.getBounds()!.height).toBe(
						terminal.rows - 9,
					);
					expect(portrait.getBounds()!.height).toBeLessThanOrEqual(23);
					expect(portrait.getBounds()!.height).toBeGreaterThan(H / 2);
					expect(portrait.getBounds()!.height).toBeGreaterThan(0);
					const bounds = portrait.getBounds()!;
					expect(bounds.width).toBeGreaterThan(0);
					expect(bounds.width).toBeLessThanOrEqual(48);
					expect(bounds.col + bounds.width).toBe(terminal.columns - 1);
					terminal.input("a");
					expect(editor.getValue()).toBe("a");
					const dialog = new Input();
					foreign = show(dialog, { width: 20 });
					terminal.input("b");
					expect(dialog.getValue()).toBe("b");
					current.vixen = false;
					tui.renderNow();
					expect(widget.render(120)).toEqual(on);
					expect(portrait.getBounds()).toBeUndefined();
					expect(foreign.isFocused()).toBe(true);
					terminal.input("c");
					expect(dialog.getValue()).toBe("bc");
					// Progress continues with the portrait timer gone.
					vi.advanceTimersByTime(1_000);
					tui.renderNow();
					expect(plain(widget.render(120))).toContain("00:01 elapsed");
					current.vixen = true;
					tui.renderNow();
					expect(foreign.isFocused()).toBe(true);
					expect(handles.at(-1)!.getBounds()).toBeDefined();
					foreign.hide();
					terminal.input("d");
					expect(editor.getValue()).toBe("ad");
					widget.dispose();
					expect(tui.hasOverlay()).toBe(false);
				} finally {
					foreign?.hide();
					widget.dispose();
					tui.stop();
				}
				expect(vi.getTimerCount()).toBe(0);
			},
		);
	}

	it("renders enlarged raster cells with tight outer crop and unchanged camera", () => {
		vi.useFakeTimers();
		vi.setSystemTime(0);
		const terminal = new MemoryTerminal();
		const tui = new TuiAltScreen(terminal);
		const theme: Theme = themes.getThemeByName("light");
		const run = snapshot();
		let picture: string[] = [];
		let handle: OverlayHandle | undefined;
		const show = tui.showOverlay.bind(tui);
		tui.showOverlay = (component, options) => {
			const render = component.render.bind(component);
			component.render = (width) => (picture = render(width));
			handle = show(component, options);
			return handle;
		};
		const widget = createLoopWidget(tui, theme, () => ({
			run,
			baseline: true,
			agentRunning: false,
			vixen: true,
		}));
		const original = createCompanion(
			tui,
			theme,
			() => ({
				...run,
				failed: null,
			}),
			Date.now,
			1.5,
		);
		tui.addChild(widget);
		tui.start();
		try {
			const frame = original.render(48).slice(0, 23);
			tui.renderNow();
			const cells = frame.map(stripTerminalSequences);
			const top = cells.findIndex((line) => line.trim());
			const left = Math.min(
				...cells
					.filter((line) => line.trim())
					.map((line) => line.search(/\S/u)),
			);
			const right = Math.max(...cells.map((line) => line.trimEnd().length));
			const bottom = cells.findLastIndex((line) => line.trim()) + 1;
			expect(picture).toEqual(
				frame
					.slice(top, bottom)
					.map((line) => sliceByColumn(line, left, right - left)),
			);
			expect(handle!.getBounds()!.width).toBe(right - left);
			expect(handle!.getBounds()!.width).toBeLessThan(48);
			expect(handle!.getBounds()!.row + picture.length).toBe(terminal.rows - 9);
			expect(handle!.getBounds()!.col + right - left).toBe(
				terminal.columns - 1,
			);
			expect(picture.length).toBe(bottom - top);
			expect(plain(picture)).toMatch(/[▀▄]/u);
			// Actual native compositor output includes the portrait, never its caption/counters.
			const screen = plain(tui.getScreenLines());
			expect(screen).toMatch(/[▀▄]/u);
			expect(screen.split(ICON.gate)).toHaveLength(2);
			expect(screen.split(ICON.turn)).toHaveLength(2);
		} finally {
			widget.dispose();
			original.dispose();
			tui.stop();
		}
	});

	it("enlarges painted pixels on both axes before packing half-blocks and fits supplied widths", () => {
		vi.useFakeTimers();
		vi.setSystemTime(0);
		const tui = new TuiAltScreen(new MemoryTerminal());
		const theme: Theme = themes.getThemeByName("dark");
		// Expose each styled cell's two painted halves without decoding ANSI colors.
		const style = vi
			.spyOn(theme, "style")
			.mockImplementation((text, options) =>
				text === "▀" && options?.bg ? "█" : text,
			);
		const run = { ...snapshot(), failed: null };
		const original = createCompanion(tui, theme, () => run);
		const enlarged = createCompanion(tui, theme, () => run, Date.now, 1.5);
		const pixels = (lines: string[], width: number) =>
			lines.flatMap((line) => {
				const cells = stripTerminalSequences(line).padEnd(width, " ");
				return [
					Array.from(cells, (cell) => cell === "▀" || cell === "█"),
					Array.from(cells, (cell) => cell === "▄" || cell === "█"),
				];
			});
		try {
			const source = pixels(original.render(32).slice(0, 15), 32);
			const scaled = pixels(enlarged.render(48).slice(0, 23), 48);
			for (let y = 0; y < 45; y++) {
				for (let x = 0; x < 48; x++) {
					expect(scaled[y]![x]).toBe(
						source[Math.floor(y / 1.5)]![Math.floor(x / 1.5)],
					);
				}
			}
			for (const width of [1, 31, 47, 48, 49]) {
				const lines = enlarged.render(width);
				expect(lines).toHaveLength(24);
				expect(lines.every((line) => visibleWidth(line) <= width)).toBe(true);
			}
		} finally {
			original.dispose();
			enlarged.dispose();
			style.mockRestore();
		}
	});

	it.each([false, true])(
		"owns animation timers independently of gate progress, including invisible states (kitten=%s)",
		(kitten) => {
			vi.useFakeTimers();
			vi.setSystemTime(0);
			const terminal = new MemoryTerminal();
			const tui = new TuiAltScreen(terminal);
			// Disable host scheduling to count only the widget's two independent clocks.
			tui.stop();
			const current: {
				run: LoopSnapshot | null;
				baseline: boolean;
				agentRunning: boolean;
				vixen: boolean;
			} = { run: snapshot(), baseline: true, agentRunning: false, vixen: true };
			const widget = createLoopWidget(
				tui,
				themes.getThemeByName("dark"),
				() => current,
				kitten,
			);
			try {
				widget.render(120);
				expect(vi.getTimerCount()).toBe(2);
				current.vixen = false;
				widget.render(120);
				expect(tui.hasOverlay()).toBe(false);
				expect(vi.getTimerCount()).toBe(1);
				current.run!.pending = false;
				current.vixen = true;
				for (const hidden of [
					"small",
					"stopped",
					"expired",
					"reset",
				] as const) {
					current.run = snapshot();
					current.run.pending = false;
					widget.render(120);
					expect(vi.getTimerCount()).toBe(1);
					if (hidden === "small") terminal.rows = 31;
					if (hidden === "stopped") current.run.status = "stopped";
					if (hidden === "expired") {
						current.run.status = "succeeded";
						current.run.updatedAt = -40_001;
					}
					if (hidden === "reset") current.run = null;
					widget.render(120);
					expect(tui.hasOverlay()).toBe(false);
					expect(vi.getTimerCount()).toBe(0);
					terminal.rows = 40;
				}
				current.run = snapshot();
				widget.render(120);
				expect(vi.getTimerCount()).toBe(2);
			} finally {
				widget.dispose();
			}
			expect(vi.getTimerCount()).toBe(0);
			expect(tui.hasOverlay()).toBe(false);
		},
	);

	it.each([false, true])(
		"hides rather than downscales on resize; removes handles and timers on stop, afterglow and reset (kitten=%s)",
		(kitten) => {
			vi.useFakeTimers();
			vi.setSystemTime(0);
			const terminal = new MemoryTerminal();
			const tui = new TuiAltScreen(terminal);
			const theme: Theme = themes.getThemeByName("dark");
			const current: {
				run: LoopSnapshot | null;
				baseline: boolean;
				agentRunning: boolean;
				vixen: boolean;
			} = { run: snapshot(), baseline: true, agentRunning: false, vixen: true };
			const widget = createLoopWidget(tui, theme, () => current, kitten);
			tui.addChild(widget);
			tui.start();
			try {
				for (const [width, rows] of [
					[120, 40],
					[59, 40],
					[120, 31],
					[60, 32],
					[59, 31],
					[60, 31],
					[20, 10],
					[1, 5],
					[200, 50],
				]) {
					terminal.columns = width!;
					terminal.rows = rows!;
					terminal.resize();
					tui.renderNow();
					const on = widget.render(width!);
					expect(on.length).toBeLessThanOrEqual(3);
					expect(on.every((line) => visibleWidth(line) <= width!)).toBe(true);
					expect(tui.hasOverlay()).toBe(width! >= 60 && rows! >= 32);
					current.vixen = false;
					tui.renderNow();
					expect(widget.render(width!)).toEqual(on);
					current.vixen = true;
				}
				current.run!.pending = false;
				for (const status of ["stopped", "succeeded"] as const) {
					current.run!.status = status;
					current.run!.updatedAt = Date.now();
					tui.renderNow();
					expect(tui.hasOverlay()).toBe(status === "succeeded");
					vi.advanceTimersByTime(40_100);
					tui.renderNow();
					expect(tui.hasOverlay()).toBe(false);
				}
				current.run!.status = "active";
				tui.renderNow();
				expect(tui.hasOverlay()).toBe(true);
				current.run = null;
				tui.renderNow();
				expect(widget.render(120)).toEqual([]);
				expect(tui.hasOverlay()).toBe(false);
			} finally {
				widget.dispose();
				tui.stop();
			}
			expect(vi.getTimerCount()).toBe(0);
		},
	);
});