Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/pipi/__tests__/render.test.ts

Raw
import { fauxAssistantMessage } from "@earendil-works/pi-ai";
import { initTheme, keyHint, Theme } from "@earendil-works/pi-coding-agent";
import {
	Box,
	stripTerminalSequences,
	visibleWidth,
} from "@earendil-works/pi-tui";
import xterm from "@xterm/headless";
import { describe, expect, it } from "vitest";
import {
	collapsedPreview,
	renderTask,
	renderTaskCall,
	safe,
} from "../render.ts";
import type { TaskResult } from "../runtime.ts";

const result: TaskResult = {
	outputMode: "structured",
	outcome: "completed",
	output: { answer: "界".repeat(100) },
	assistantMessage: null,
	sessionId: "native-id",
	sessionFile: "/tmp/native/session.jsonl",
	durationMs: 1234,
	turns: 3,
	usage: {
		input: 10,
		output: 5,
		cacheRead: 0,
		cacheWrite: 0,
		totalTokens: 15,
		cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
	},
	requested: { tools: ["read"] },
	effective: {
		cwd: "/tmp/project",
		model: "faux/test",
		thinkingLevel: "off",
		tools: ["read"],
		excludedTools: ["hidden_probe", "界".repeat(80)],
		extensions: [],
	},
	diagnostics: [],
};
describe("native pipi renderer", () => {
	for (const name of ["dark", "light"] as const) {
		it(`renders collapsed, expanded, streaming and error states at small widths in ${name}`, async () => {
			initTheme(name, false);
			const ink = name === "dark" ? "#dddddd" : "#222222";
			const roles = {
				text: ink,
				thinkingXhigh: ink,
				success: "#439343",
				warning: "#b89826",
				error: "#c84949",
				dim: ink,
				muted: ink,
				toolTitle: ink,
			};
			const theme = new Theme(
				roles as ConstructorParameters<typeof Theme>[0],
				{
					selectedBg: name === "dark" ? "#000000" : "#ffffff",
					toolPendingBg: "#213141",
					toolSuccessBg: "#314151",
					toolErrorBg: "#415161",
				} as ConstructorParameters<typeof Theme>[1],
				"truecolor",
				{ name, appearance: name },
			);
			const callArgs = {
				prompt:
					"Read-only UI demonstration. " +
					"界 evidence ".repeat(40) +
					"\nFull second line retained.",
			};
			const collapsedCall = renderTaskCall(callArgs, false, theme);
			for (const width of [0, 1, 2, 8, 20, 80, 160]) {
				const rows = collapsedCall.render(width);
				expect(rows.length).toBe(width > 0 ? 1 : 0);
				expect(rows.every((line) => visibleWidth(line) <= width)).toBe(true);
			}
			for (const [state, color] of [
				["toolPendingBg", 0x213141],
				["toolSuccessBg", 0x314151],
				["toolErrorBg", 0x415161],
			] as const) {
				for (const width of [3, 8, 40]) {
					const box = new Box(1, 0, (line) => theme.bg(state, line));
					box.addChild(collapsedCall);
					const line = box.render(width)[0] ?? "";
					const terminal = new xterm.Terminal({
						cols: width + 1,
						rows: 2,
						allowProposedApi: true,
					});
					try {
						await new Promise<void>((resolve) => terminal.write(line, resolve));
						const row = terminal.buffer.active.getLine(0);
						for (let column = 0; column < width; column++) {
							expect(
								row?.getCell(column)?.getBgColor(),
								`${state} width=${width} column=${column}`,
							).toBe(color);
						}
					} finally {
						terminal.dispose();
					}
				}
			}
			const beyondCutoff = renderTaskCall(
				{ prompt: "a".repeat(121) + "AFTER_120" },
				false,
				theme,
			)
				.render(200)
				.join("");
			expect(beyondCutoff).toContain("AFTER_120");
			const narrowCall = stripTerminalSequences(
				collapsedCall.render(40).join(""),
			);
			expect(narrowCall).toMatch(/^π² · child · .*…$/u);
			expect(collapsedCall.render(160).join("")).not.toContain(
				"Full second line",
			);
			const fullCall = stripTerminalSequences(
				renderTaskCall(callArgs, true, theme).render(2000).join("\n"),
			);
			expect(
				fullCall
					.split("\n")
					.map((line) => line.trimEnd())
					.join("\n"),
			).toContain(
				callArgs.prompt
					.split("\n")
					.map((line) => line.trimEnd())
					.join("\n"),
			);
			expect(
				stripTerminalSequences(
					renderTaskCall({ prompt: "Short", agent: "reviewer" }, false, theme)
						.render(80)
						.join(""),
				),
			).toBe("π² · reviewer · Short");
			for (const expanded of [false, true])
				for (const width of [1, 2, 8, 20, 80]) {
					const lines = renderTask(result, expanded, theme).render(width);
					expect(lines.length).toBeGreaterThan(0);
					expect(lines.every((line) => visibleWidth(line) <= width)).toBe(true);
				}
			const hint = stripTerminalSequences(
				keyHint("app.tools.expand", "to expand"),
			);
			for (const outcome of ["completed", "aborted", "error"] as const) {
				const rows = renderTask({ ...result, outcome }, false, theme).render(
					120,
				);
				expect(rows).toHaveLength(3);
				expect(stripTerminalSequences(rows[2] ?? "")).toBe(hint);
			}
			for (const progress of [
				undefined,
				{ phase: "running", preview: "" },
				{ phase: "answering", preview: "Short" },
				{ phase: "answering", preview: "Long text\n".repeat(20) },
			]) {
				const rows = renderTask(undefined, false, theme, progress).render(120);
				expect(rows).toHaveLength(3);
				expect(stripTerminalSequences(rows[2] ?? "")).toBe(hint);
				expect(rows.map(stripTerminalSequences)).not.toContain("running");
			}
			const expanded = renderTask(result, true, theme).render(120).join("\n");
			expect(expanded).toContain("$0.0000 estimated");
			expect(
				renderTask(
					{
						...result,
						usage: {
							...result.usage,
							cost: { ...result.usage.cost, totalFromProvider: true },
						},
					},
					false,
					theme,
				)
					.render(120)
					.join("\n"),
			).toContain("$0.0000 billed");
			expect(expanded).toContain(
				"Inherited tools excluded: hidden_probe (hidden)",
			);
			expect(expanded).not.toContain("Diagnostics");
			expect(
				renderTask(result, false, theme).render(120).join("\n"),
			).not.toContain("hidden_probe");
			for (const text of ["", "Partial answer"]) {
				for (const outputMode of ["message", "structured"] as const) {
					const message = fauxAssistantMessage(text, {
						stopReason: "error",
						errorMessage:
							"Provider\u001b]52;c;clipboard-payload\u0007 failure\u0000",
					});
					const failed: TaskResult = {
						...result,
						outcome: "error",
						outputMode,
						output:
							outputMode === "message"
								? JSON.parse(JSON.stringify(message))
								: { answer: 42 },
						assistantMessage: outputMode === "structured" ? message : null,
					};
					const rendered = renderTask(failed, true, theme)
						.render(120)
						.join("\n");
					expect(rendered).toContain("error");
					expect(rendered).toContain("Provider failure");
					expect(rendered).not.toContain("clipboard-payload");
					expect(rendered).not.toContain("\u0000");
					if (text && outputMode === "message")
						expect(rendered).toContain(text);
					if (outputMode === "structured") expect(rendered).toContain("42");
					expect(
						renderTask(failed, false, theme).render(120).join("\n"),
					).not.toContain("Provider failure");
					for (const width of [1, 2, 8, 20]) {
						expect(
							renderTask(failed, true, theme)
								.render(width)
								.every((line) => visibleWidth(line) <= width),
						).toBe(true);
					}
					expect(message.errorMessage).toContain("clipboard-payload");
				}
			}
			const applicationData = { role: "assistant", answer: "ok" };
			const structured = renderTask(
				{ ...result, output: applicationData },
				true,
				theme,
			)
				.render(80)
				.join("\n");
			expect(structured).toContain("answer");
			expect(structured).toContain("ok");
			const progress = {
				phase: "answering",
				preview: "streaming\u001b]52;c;secret\u0007\u001b[31mtext",
			};
			const lines = renderTask(undefined, true, theme, progress).render(80);
			expect(lines.join("\n")).toContain("streamingtext");
			expect(lines.join("")).not.toContain("secret");
			const toolProgress = {
				phase: "tool",
				preview: "",
				tool: { name: "read", args: '{"path":"界/source.ts"}' },
			};
			for (const expanded of [false, true]) {
				for (const width of [1, 2, 8, 20, 80]) {
					const rows = renderTask(
						undefined,
						expanded,
						theme,
						toolProgress,
					).render(width);
					expect(rows.every((line) => visibleWidth(line) <= width)).toBe(true);
				}
				const rendered = renderTask(undefined, expanded, theme, toolProgress)
					.render(80)
					.join("\n");
				expect(rendered).toContain("tool: read");
				if (expanded) expect(rendered).toContain("界/source.ts");
				else expect(rendered).not.toContain("界/source.ts");
			}
			expect(
				renderTask(undefined, false, theme, progress).render(80).join("\n"),
			).not.toContain("streamingtext");
		});
	}
	it("uses host key hints when available and falls back for Pi 1.4", () => {
		const hostHint = "ctrl+e expand";
		expect(
			stripTerminalSequences(
				collapsedPreview(["first"], 80, {
					keyHint: () => hostHint,
				})[2] ?? "",
			),
		).toBe(hostHint);
		expect(
			stripTerminalSequences(collapsedPreview(["first"], 80)[2] ?? ""),
		).toBe(stripTerminalSequences(keyHint("app.tools.expand", "to expand")));
	});
	it("strips terminal controls and bounds previews without altering machine output", () => {
		expect(safe("hello\u001b[31mred\u001b[0m\u0000")).toBe("hellored");
		expect(safe("a".repeat(20000)).length).toBe(12000);
		expect(result.output).toEqual({ answer: "界".repeat(100) });
	});
});