Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/activity/__tests__/ui.test.ts

Raw
import {
	type ExtensionCommandContext,
	Theme,
} from "@earendil-works/pi-coding-agent";
import {
	type Component,
	CURSOR_MARKER,
	type KeybindingsManager,
	stripTerminalSequences,
	type TUI,
	type TuiMouseEvent,
	visibleWidth,
} from "@earendil-works/pi-tui";
import headless from "@xterm/headless";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { ActivitySnapshot, TimerView } from "../types.js";
import {
	ActivityInspector,
	activityPicker,
	activityWidget,
	formatActivityOption,
	openActivities,
	renderActivityFrame,
	sanitizeActivityText,
	terminalInput,
} from "../ui.js";
import type { TerminalView } from "../view.js";

const terminal: ActivitySnapshot = {
	id: "α",
	kind: "terminal",
	title: "界界界 terminal",
	status: "running",
	notify: false,
	createdAt: 0,
	sequence: 1,
	screen: {
		text: "\u001b[31m界界界\u001b[0m\nnext",
		cols: 20,
		rows: 5,
		cursorX: 0,
		cursorY: 1,
		truncated: false,
	},
};
const plainTheme = {
	fg: (_color: unknown, text: string) => text,
	bold: (text: string) => text,
	getFgAnsi: () => "",
	getBgAnsi: () => "",
} as unknown as Theme;
const inspectors: ActivityInspector[] = [];
const pickers: { dispose(): void }[] = [];
afterEach(() => {
	for (const inspector of inspectors.splice(0)) inspector.dispose();
	for (const picker of pickers.splice(0)) picker.dispose();
	vi.restoreAllMocks();
});

function inspect(
	activity = terminal,
	{
		view,
		hardware = false,
		timer,
		theme = plainTheme,
	}: {
		view?: TerminalView;
		hardware?: boolean;
		timer?: TimerView;
		theme?: Theme;
	} = {},
) {
	const done = vi.fn();
	const write = vi.fn();
	const stop = vi.fn(async () => {
		activity.status = "stopping";
		return { ...activity };
	});
	const requestRender = vi.fn();
	const acknowledge = vi.fn();
	const inspector = new ActivityInspector(
		{
			terminal: { rows: 30 },
			requestRender,
			getShowHardwareCursor: () => hardware,
		} as unknown as TUI,
		theme,
		{ matches: () => false } as unknown as KeybindingsManager,
		done,
		{
			list: () => [activity],
			read: () => activity,
			attention: () => [activity],
			acknowledge,
			write,
			resize: vi.fn(),
			stop,
			subscribe: () => () => {},
			terminalView: () => view,
			timerView: () => timer,
		},
		activity.id,
	);
	inspectors.push(inspector);
	return { inspector, done, write, stop, requestRender, acknowledge };
}

function pick(activities: ActivitySnapshot[]) {
	const done = vi.fn();
	const requestRender = vi.fn();
	const unsubscribe = vi.fn();
	let refresh = () => {};
	const stop = vi.fn(async (id: string) => {
		const activity = activities.find((item) => item.id === id);
		if (!activity) throw new Error("Unknown fixture activity");
		activity.status = "stopping";
		refresh();
		return { ...activity };
	});
	const acknowledged = new Set<string>();
	const acknowledge = vi.fn((id: string) => {
		acknowledged.add(id);
		refresh();
	});
	const component = activityPicker(
		{
			list: () => activities,
			attention: () =>
				activities.filter(
					(activity) =>
						activity.status === "running" ||
						activity.status === "stopping" ||
						(activity.status === "failed" && !acknowledged.has(activity.id)),
				),
			acknowledge,
			stop,
			subscribe: (listener) => {
				refresh = listener;
				return unsubscribe;
			},
		},
		{ terminal: { rows: 30 }, requestRender } as unknown as TUI,
		plainTheme,
		done,
	);
	pickers.push(component);
	return {
		component,
		done,
		requestRender,
		unsubscribe,
		stop,
		acknowledge,
		refresh: () => refresh(),
	};
}

describe("activity picker stopping", () => {
	it("stops only the selected active activity and retains truthful stopping state", async () => {
		const { component, stop, done } = pick([
			{ ...terminal, id: "first", title: "First fixture" },
			{ ...terminal, id: "second", title: "Second fixture" },
		]);
		component.handleInput?.("\x1b[B");
		component.handleInput?.("x");
		expect(stop).toHaveBeenCalledExactlyOnceWith("second");
		expect(component.render(68).join("\n")).toContain("Stopping…");
		expect(done).not.toHaveBeenCalled();
		stop.mockRejectedValueOnce(new Error("Synthetic stop failure"));
		component.handleInput?.("x");
		await vi.waitFor(() =>
			expect(component.render(68).join("\n")).toContain("Stop failed"),
		);
		component.handleInput?.("\x1b");
		expect(done).toHaveBeenCalledWith(undefined);
	});

	it("does not request termination for completed work", () => {
		const { component, stop } = pick([{ ...terminal, status: "completed" }]);
		component.handleInput?.("x");
		expect(stop).not.toHaveBeenCalled();
	});
});

describe("activity picker hiding", () => {
	it("hides the selected failure or all finished work from the widget and labels hidden failures", () => {
		const activities: ActivitySnapshot[] = [
			{ ...terminal, id: "active", title: "Active fixture" },
			{
				...terminal,
				id: "first",
				status: "failed",
				title: "First failure",
				createdAt: 2,
			},
			{
				...terminal,
				id: "second",
				status: "failed",
				title: "Second failure",
				createdAt: 1,
			},
		];
		const { component, acknowledge } = pick(activities);
		const text = () => stripTerminalSequences(component.render(68).join("\n"));
		expect(text()).toContain("d hide · D hide all");
		expect(text()).not.toContain("hidden");
		component.handleInput?.("\x1b[B");
		component.handleInput?.("d");
		expect(acknowledge).toHaveBeenCalledExactlyOnceWith("first");
		expect(text().match(/Failed · hidden/g)).toHaveLength(1);
		component.handleInput?.("D");
		expect(acknowledge.mock.calls.map(([id]) => id)).toEqual([
			"first",
			"first",
			"second",
		]);
		expect(text().match(/Failed · hidden/g)).toHaveLength(2);
	});
});

describe("above-editor activity status", () => {
	it("keeps stopping distinct from stopped and shows each kind's running state", () => {
		for (const [status, label] of [
			["stopping", "Stopping…"],
			["stopped", "Stopped"],
			["completed", "Done"],
			["failed", "Failed"],
		] as const) {
			const lines = activityWidget(
				[{ ...terminal, status, exitCode: status === "failed" ? 7 : 0 }],
				plainTheme,
			).render(120);
			expect(lines.join("\n")).toContain(label);
			if (status === "failed") expect(lines.join("\n")).toContain("exit 7");
		}
		for (const [kind, label] of [
			["process", "Running"],
			["terminal", "Open"],
			["watch", "Watching"],
			["timer", "Waiting"],
		] as const) {
			expect(
				activityWidget([{ ...terminal, kind }], plainTheme)
					.render(120)
					.join("\n"),
			).toContain(label);
		}
	});

	it("prioritizes active work, bounds rows and discloses retained failures and overflow", () => {
		const activities: ActivitySnapshot[] = Array.from(
			{ length: 8 },
			(_, i) => ({
				...terminal,
				id: String(i),
				kind: "process" as const,
				title: `Fixture ${i}`,
				status: i === 6 ? "stopping" : i === 7 ? "failed" : "running",
				createdAt: i,
			}),
		);
		const lines = activityWidget(activities, plainTheme).render(40);
		expect(lines).toHaveLength(5);
		expect(lines[0]).toContain("4 hidden");
		expect(lines[0]).not.toContain("/activities");
		expect(lines[1]).toContain("Stopping… · Fixture 6");
		expect(lines[2]).toContain("Running · Fixture 5");
		expect(lines[0]).toContain("1 failed");
		expect(lines[4]).toContain("Failed · Fixture 7");
	});

	it.each([40, 62])(
		"never lets retained failures hide active work at width %i",
		(width) => {
			const activities: ActivitySnapshot[] = Array.from(
				{ length: 6 },
				(_, i) => ({
					...terminal,
					id: String(i),
					kind: "process",
					createdAt: i,
					status: i < 3 ? "running" : "failed",
					title: i < 3 ? `Active fixture ${i}` : `Past failure ${i}`,
				}),
			);
			const lines = activityWidget(activities, plainTheme).render(width);
			expect(lines).toHaveLength(5);
			expect(
				lines.slice(1, 4).every((line) => /Running · Active/.test(line)),
			).toBe(true);
			expect(lines[4]).toContain("Past failure 5");
			for (const label of ["3 active", "3 failed", "2 hidden"])
				expect(lines[0]).toContain(label);
			expect(lines.every((line) => visibleWidth(line) <= width)).toBe(true);
		},
	);

	it("preserves distinguishing title ends, kind and exit status at constrained width", () => {
		const lines = activityWidget(
			[
				{
					...terminal,
					kind: "process",
					status: "failed",
					exitCode: 7,
					title:
						"Shared build prefix with a long branch name and distinctive tail-Z9",
				},
			],
			plainTheme,
		).render(62);
		expect(lines[0]).toBe(" \u{F0996} Activities · 1 failed");
		expect(lines[1]).toMatch(/^ {3}✕ Failed · Shared/);
		expect(lines[1]).toContain("…");
		expect(lines[1]).toContain("tail-Z9");
		expect(lines[1]).toContain("Process · exit 7");
		expect(visibleWidth(lines[1])).toBeLessThanOrEqual(62);
	});

	it("preserves kind when an elision boundary intersects a wide glyph", () => {
		const job: ActivitySnapshot = {
			...terminal,
			kind: "process",
			title:
				"Unicode 界😀 overflow fixture with deliberately long title for narrow layouts",
		};
		for (let width = 32; width <= 80; width++) {
			const row = activityWidget([job], plainTheme).render(width)[1];
			expect(row).toMatch(/ · Process$/);
			expect(visibleWidth(row)).toBeLessThanOrEqual(width);
		}
	});

	it("keeps retained failures compact, icon-led and out of keyboard focus", () => {
		const widget = activityWidget(
			Array.from({ length: 32 }, (_, i) => ({
				...terminal,
				id: String(i),
				status: "failed",
			})),
			plainTheme,
		);
		const lines = widget.render(100);
		expect(lines).toHaveLength(2);
		expect(lines[0]).toBe(" \u{F0996} Activities · 32 failed · 31 hidden");
		expect(lines[0]).not.toContain("history");
		expect(widget.handleInput).toBeUndefined();
		expect(activityWidget([], plainTheme).render(100)).toEqual([]);
	});

	it("fits every supplied width and never renders output or title control sequences", () => {
		const widget = activityWidget(
			[
				{
					...terminal,
					title: "\x1b[31m界😀\tfirst\nnext\u0085last",
					output: "PRIVATE_STDOUT",
				},
			],
			plainTheme,
		);
		for (let width = 0; width <= 130; width++) {
			for (const line of widget.render(width)) {
				expect(visibleWidth(line)).toBeLessThanOrEqual(width);
				expect(stripTerminalSequences(line)).not.toMatch(
					/[\r\n\t\u0080-\u009f]/,
				);
				expect(line).not.toContain("\x1b[31m");
				expect(line).not.toContain("PRIVATE_STDOUT");
			}
		}
		expect(widget.render(100).join("\n")).toContain("界😀 first next last");
	});
});

describe("ActivityInspector", () => {
	it("hides an inspected finished activity from the widget on close, but not active work", () => {
		const running = inspect({ ...terminal, kind: "process" });
		running.inspector.dispose();
		expect(running.acknowledge).not.toHaveBeenCalled();
		const failed = inspect({ ...terminal, kind: "process", status: "failed" });
		failed.inspector.dispose();
		failed.inspector.dispose();
		expect(failed.acknowledge).toHaveBeenCalledExactlyOnceWith(terminal.id);
	});

	it("marks clipped captions, output tails and narrow stop feedback", () => {
		const job: ActivitySnapshot = {
			...terminal,
			kind: "process",
			title: "Long task name ".repeat(12),
			output: Array.from({ length: 80 }, (_, i) => `entry ${i}`).join("\n"),
		};
		const lines = renderActivityFrame(job, 40, 12);
		const text = stripTerminalSequences(lines.join("\n"));
		expect(stripTerminalSequences(lines[0])).toContain("…╮");
		expect(text).toContain("Showing 7 lines · earlier omitted");
		expect(text).toContain("entry 79");
		expect(text).not.toContain("entry 0");
		expect(lines).toHaveLength(12);
		const failed = renderActivityFrame(
			{ ...job, error: "Signal fixture error" },
			40,
			12,
		);
		expect(stripTerminalSequences(failed.join("\n"))).toContain(
			"Signal fixture error",
		);
		expect(stripTerminalSequences(failed.join("\n"))).toContain(
			"Showing 6 lines · earlier omitted",
		);
		expect(failed).toHaveLength(12);
		expect(
			stripTerminalSequences(
				renderActivityFrame({ ...job, output: "" }, 40, 12, {
					stopFailed: true,
				}).join("\n"),
			),
		).toContain("Stop failed; retry x.");
	});

	it("keeps tall terminal cells intact and both stop-guidance lines readable at 40 columns", () => {
		const lines = renderActivityFrame(terminal, 40, 80, {
			view: {
				lines: Array.from({ length: 60 }, (_, i) => `cell ${i}`),
				truncated: false,
			},
		});
		const text = stripTerminalSequences(lines.join("\n"));
		expect(text).toContain("cell 59");
		expect(text).toContain("keys → app");
		expect(text).toContain("Stop: Ctrl+G → /activities → x");
		expect(text).not.toContain("earlier omitted");
		expect(lines.every((line) => visibleWidth(line) <= 40)).toBe(true);
	});
	it("marks clipped process output without inserting markers into terminal cells", () => {
		const output = `pid=${"1234567890".repeat(8)}`;
		const frame = renderActivityFrame(
			{ ...terminal, kind: "process", output },
			40,
		);
		expect(stripTerminalSequences(frame[3])).toMatch(/…\s*│$/);
		expect(frame.every((line) => visibleWidth(line) <= 40)).toBe(true);
		const cells = renderActivityFrame(terminal, 40, 64, {
			view: { lines: [output], truncated: false },
		});
		expect(stripTerminalSequences(cells[3])).not.toContain("…");
	});
	it.each(["process", "terminal"] as const)(
		"shows elapsed %s time and freezes it at the terminal event",
		(kind) => {
			const now = vi.spyOn(Date, "now").mockReturnValue(12345);
			const job: ActivitySnapshot = { ...terminal, kind, createdAt: 2000 };
			expect(
				stripTerminalSequences(renderActivityFrame(job, 100).join("\n")),
			).toContain("10s elapsed");
			job.status = "completed";
			job.events = [{ type: "exit", time: 12345, sequence: 1 }];
			now.mockReturnValue(54321);
			expect(
				stripTerminalSequences(renderActivityFrame(job, 100).join("\n")),
			).toContain("10s elapsed");
		},
	);

	it("shows attached-terminal input ownership and an available stop path", () => {
		const frame = stripTerminalSequences(
			renderActivityFrame(terminal, 62).join("\n"),
		);
		expect(frame).toContain("keys → app");
		expect(frame).toContain("/activities → x");
	});
	it.each(["process", "watch", "timer"] as const)(
		"offers direct stop and failure recovery for active %s without closing",
		async (kind) => {
			const { inspector, stop, done } = inspect({ ...terminal, kind });
			expect(stripTerminalSequences(inspector.render(62).join("\n"))).toContain(
				"x stop",
			);
			inspector.handleInput("x");
			expect(stop).toHaveBeenCalledExactlyOnceWith(terminal.id);
			expect(stripTerminalSequences(inspector.render(62).join("\n"))).toContain(
				"Stopping…",
			);
			expect(done).not.toHaveBeenCalled();
			stop.mockRejectedValueOnce(new Error("Synthetic stop failure"));
			inspector.handleInput("x");
			await vi.waitFor(() =>
				expect(
					stripTerminalSequences(inspector.render(62).join("\n")),
				).toContain("Stop failed"),
			);
		},
	);

	it("keeps x as application input in an attached terminal and does not stop finished work", () => {
		const attached = inspect({ ...terminal });
		attached.inspector.handleInput("x");
		expect(attached.write).toHaveBeenCalledWith(
			terminal.id,
			"x",
			undefined,
			true,
		);
		expect(attached.stop).not.toHaveBeenCalled();
		const finished = inspect({
			...terminal,
			kind: "process",
			status: "completed",
		});
		finished.inspector.handleInput("x");
		expect(finished.stop).not.toHaveBeenCalled();
		expect(
			stripTerminalSequences(finished.inspector.render(62).join("\n")),
		).not.toContain("x stop");
	});
	it.each([false, true])(
		"paints every border edge consistently despite inherited/application styling: cursor=%s",
		async (cursor) => {
			const theme = new Theme(
				{
					border: 6,
					accent: 5,
					text: 7,
					muted: 8,
					dim: 8,
					success: 2,
					warning: 3,
					error: 1,
					thinkingXhigh: 5,
				} as ConstructorParameters<typeof Theme>[0],
				{ customMessageBg: 4, selectedBg: 4 } as ConstructorParameters<
					typeof Theme
				>[1],
				"256color",
			);
			const { inspector } = inspect(terminal, {
				theme,
				view: {
					lines: ["\x1b[1;7;38;5;1;48;5;2mcolored output\x1b[0m"],
					truncated: false,
					cursor: cursor
						? {
								x: 0,
								y: 0,
								text: "c",
								width: 1,
								style: "\x1b[1;7;38;5;1;48;5;2m",
								inverse: true,
							}
						: undefined,
				},
			});
			inspector.focused = true;
			const lines = inspector.render(60);
			const emulator = new headless.Terminal({
				allowProposedApi: true,
				cols: 60,
				rows: 30,
			});
			try {
				await new Promise<void>((resolve) =>
					emulator.write("\x1b[1;7;45m" + lines.join("\r\n"), resolve),
				);
				for (let row = 0; row < lines.length; row++)
					for (const column of [0, 59]) {
						const cell = emulator.buffer.active.getLine(row)?.getCell(column);
						expect(cell?.getFgColor()).toBe(6);
						expect(cell?.getBgColor()).toBe(4);
						expect(cell?.isInverse()).toBe(0);
						expect(cell?.isBold()).toBe(0);
					}
				const appCell = emulator.buffer.active.getLine(3)?.getCell(2);
				expect(appCell?.getFgColor()).toBe(1);
				expect(appCell?.getBgColor()).toBe(2);
				expect(Boolean(appCell?.isInverse())).toBe(true);
			} finally {
				emulator.dispose();
			}
		},
	);

	it("shows timer countdown and stops its refresh clock on disposal", async () => {
		vi.useFakeTimers();
		vi.setSystemTime(0);
		try {
			const timer: ActivitySnapshot = {
				...terminal,
				kind: "timer",
				title: "Tea",
				screen: undefined,
			};
			const { inspector, requestRender } = inspect(timer, {
				timer: { delayMs: 60000, nextAt: 60000, repeat: false },
			});
			expect(stripTerminalSequences(inspector.render(60).join("\n"))).toContain(
				"1m remaining",
			);
			await vi.advanceTimersByTimeAsync(1100);
			expect(requestRender).toHaveBeenCalled();
			expect(stripTerminalSequences(inspector.render(60).join("\n"))).toContain(
				"59s remaining",
			);
			inspector.dispose();
			expect(vi.getTimerCount()).toBe(0);
		} finally {
			vi.useRealTimers();
		}
	});
	it("closes completed terminals without forwarding Escape to a dead application", () => {
		const { inspector, done, write } = inspect({
			...terminal,
			status: "completed",
		});
		expect(
			inspector.render(40).some((line) => line.includes("Esc close")),
		).toBe(true);
		inspector.handleInput("\x1b");
		expect(done).toHaveBeenCalledOnce();
		expect(write).not.toHaveBeenCalled();
	});

	it("forwards human input and negotiated paste but detaches locally", () => {
		const { inspector, done, write } = inspect();
		inspector.handleInput("\x1b[200~line one\nline two\x1b[201~");
		expect(write).toHaveBeenLastCalledWith(
			terminal.id,
			"line one\nline two",
			true,
			true,
		);
		inspector.handleInput("\x1b");
		expect(write).toHaveBeenLastCalledWith(
			terminal.id,
			"\x1b",
			undefined,
			true,
		);
		inspector.handleInput("\x07");
		expect(write).toHaveBeenCalledTimes(2);
		expect(done).toHaveBeenCalledOnce();
	});

	it.each([
		{ hardware: false, visible: false },
		{ hardware: false, visible: true },
		{ hardware: true, visible: false },
		{ hardware: true, visible: true },
	])(
		"preserves selection and frame resets: hardware=$hardware, visible=$visible",
		({ hardware, visible }) => {
			const view: TerminalView = {
				lines: ["\x1b[0;7m界x    \x1b[0m"],
				truncated: false,
				cursor: visible
					? {
							x: 0,
							y: 0,
							text: "界",
							width: 2,
							style: "\x1b[0;7m",
							inverse: true,
						}
					: undefined,
			};
			const { inspector } = inspect(terminal, { view, hardware });
			inspector.focused = true;
			const lines = inspector.render(40);
			expect(lines[3].includes(CURSOR_MARKER)).toBe(visible);
			expect(lines[3]).toContain("\x1b[0;7m");
			if (visible && !hardware)
				expect(lines[3]).toContain("\x1b[27m界\x1b[0;7m");
			expect(lines[3]).toMatch(/\x1b\[0m *│\x1b\[0m$/);
			expect(stripTerminalSequences(lines[3])).toContain("界x");
			expect(lines.every((line) => visibleWidth(line) <= 40)).toBe(true);
		},
	);

	it("keeps focused wide cursor cells within width without duplication", () => {
		const { inspector } = inspect({
			...terminal,
			screen: {
				...terminal.screen!,
				text: "abcdef界gh",
				cursorX: 6,
				cursorY: 0,
			},
		});
		inspector.focused = true;
		const lines = inspector.render(40);
		expect(lines.every((line) => visibleWidth(line) <= 40)).toBe(true);
		expect(stripTerminalSequences(lines[3])).toContain("abcdef界gh");
		expect(stripTerminalSequences(lines[3]).match(/abcdef界gh/g)).toHaveLength(
			1,
		);
	});
});

describe("activity navigation", () => {
	async function navigate(
		activities: ActivitySnapshot[],
		steps: ((component: Component) => void)[],
		id?: string,
	) {
		const manager = {
			list: () => activities,
			attention: () => activities,
			acknowledge: vi.fn(),
			read: (value: string) => {
				const found = activities.find((activity) => activity.id === value);
				if (!found) throw new Error("Missing activity");
				return found;
			},
			write: vi.fn(),
			resize: vi.fn(),
			stop: vi.fn(),
			subscribe: () => () => {},
			terminalView: () => undefined,
			timerView: () => undefined,
		};
		const tui = {
			terminal: { rows: 30 },
			requestRender: vi.fn(),
			getShowHardwareCursor: () => false,
		} as unknown as TUI;
		const notify = vi.fn();
		const custom = vi.fn(
			(
				factory: (
					tui: TUI,
					theme: Theme,
					kb: KeybindingsManager,
					done: (value: unknown) => void,
				) => Component & { dispose?(): void },
				_options?: unknown,
			) =>
				new Promise((resolve) => {
					const component = factory(
						tui,
						plainTheme,
						{ matches: () => false } as unknown as KeybindingsManager,
						resolve,
					);
					try {
						const step = steps.shift();
						if (!step) throw new Error("Unexpected extra dialog");
						step(component);
					} finally {
						component.dispose?.();
					}
				}),
		);
		await openActivities(
			manager,
			{
				mode: "tui",
				ui: { custom, notify },
			} as unknown as ExtensionCommandContext,
			id,
		);
		expect(notify).not.toHaveBeenCalled();
		expect(steps).toHaveLength(0);
		for (const call of custom.mock.calls) {
			expect(call[1]).toMatchObject({
				overlay: true,
				blocked: { kind: "question", message: expect.any(String) },
			});
		}
		return { manager, custom };
	}

	it.each(["timer", "terminal"] as const)(
		"returns from %s inspection to the same picker selection",
		async (kind) => {
			const activities = [
				{ ...terminal, id: "first", title: "First", kind },
				{ ...terminal, id: "second", title: "Second", kind },
			];
			const { manager, custom } = await navigate(activities, [
				(component) => {
					component.handleInput?.("\x1b[B");
					component.handleInput?.("\r");
				},
				(component) => {
					const text = stripTerminalSequences(component.render(68).join("\n"));
					expect(text).toContain(kind === "timer" ? "Esc back" : "Ctrl+G back");
					component.handleInput?.("\x1b");
					if (kind === "terminal") component.handleInput?.("\x07");
				},
				(component) => {
					const selected = component
						.render(68)
						.map(stripTerminalSequences)
						.find((line) => line.includes("→"));
					expect(selected).toContain("Second");
					component.handleInput?.("\x1b");
				},
			]);
			expect(custom).toHaveBeenCalledTimes(3);
			if (kind === "terminal")
				expect(manager.write).toHaveBeenCalledWith(
					"second",
					"\x1b",
					undefined,
					true,
				);
			else expect(manager.write).not.toHaveBeenCalled();
			expect(
				activities.every((activity) => activity.status === "running"),
			).toBe(true);
		},
	);

	it("closes a directly addressed inspector without opening a picker", async () => {
		const { custom } = await navigate(
			[{ ...terminal, kind: "timer" }],
			[
				(component) => {
					expect(
						stripTerminalSequences(component.render(68).join("\n")),
					).toContain("Esc close");
					component.handleInput?.("\x1b");
				},
			],
			terminal.id,
		);
		expect(custom).toHaveBeenCalledOnce();
	});
});

describe("activity picker", () => {
	it("uses icons and human names while retaining hidden stable IDs", () => {
		const choice = formatActivityOption({
			...terminal,
			id: "activity-private-id",
			status: "completed",
			title: "Editor",
		});
		expect(choice.value).toBe("activity-private-id");
		expect(choice.label).toBe("✓ ▣ Editor");
		expect(choice.description).toBe("Done");
		expect(choice.label).not.toContain(choice.value);
	});

	it("selects duplicate names by ID and puts running work first", () => {
		const { component, done } = pick([
			{ ...terminal, id: "older", status: "completed", title: "Same" },
			{ ...terminal, id: "running", title: "Same" },
			{
				...terminal,
				id: "newer",
				status: "completed",
				title: "Same",
				createdAt: 1,
			},
		]);
		component.render(68);
		component.handleInput?.("\x1b[B");
		component.handleInput?.("\r");
		expect(done).toHaveBeenLastCalledWith("newer");
	});

	it("refreshes status without moving rows and unsubscribes on close", () => {
		const activities = [{ ...terminal }];
		const { component, requestRender, refresh, unsubscribe } = pick(activities);
		expect(stripTerminalSequences(component.render(68).join("\n"))).toContain(
			"Open",
		);
		activities[0].status = "completed";
		refresh();
		expect(requestRender).toHaveBeenCalledOnce();
		expect(stripTerminalSequences(component.render(68).join("\n"))).toContain(
			"Done",
		);
		component.dispose();
		expect(unsubscribe).toHaveBeenCalledOnce();
	});

	it("does not select a record pruned while the picker is open", () => {
		const activities = [{ ...terminal }];
		const { component, done, refresh } = pick(activities);
		component.render(68);
		activities.length = 0;
		refresh();
		expect(stripTerminalSequences(component.render(68).join("\n"))).toContain(
			"No longer available",
		);
		component.handleInput?.("\r");
		expect(done).not.toHaveBeenCalled();
		component.handleInput?.("\x1b");
		expect(done).toHaveBeenCalledWith(undefined);
	});

	it("delegates mouse selection with panel-relative coordinates and ignores hover", () => {
		const { component, done } = pick([
			{ ...terminal, id: "first" },
			{ ...terminal, id: "second" },
		]);
		const lines = component.render(68);
		const event: TuiMouseEvent = {
			type: "move",
			button: "none",
			x: 4,
			y: 3,
			screenX: 4,
			screenY: 3,
			width: 68,
			height: lines.length,
			shift: false,
			alt: false,
			ctrl: false,
		};
		component.handleMouse?.(event);
		expect(done).not.toHaveBeenCalled();
		component.handleMouse?.({ ...event, type: "press", button: "left" });
		component.handleMouse?.({ ...event, type: "click", button: "left" });
		expect(done).toHaveBeenCalledWith("second");
	});

	it.each([1, 12, 30, 68])(
		"fits %i columns without exposing technical identifiers",
		(width) => {
			const { component } = pick([{ ...terminal, id: "activity-hidden" }]);
			const lines = component.render(width);
			expect(lines.every((line) => visibleWidth(line) <= width)).toBe(true);
			expect(stripTerminalSequences(lines.join("\n"))).not.toContain(
				"activity-hidden",
			);
		},
	);
});

describe("activity frames", () => {
	it("shows human status instead of IDs/PIDs and hides raw lifecycle event names", () => {
		const lines = renderActivityFrame(
			{
				...terminal,
				kind: "timer",
				status: "completed",
				title: "Tea",
				id: "activity-hidden",
				pid: 1234,
				events: [
					{ type: "tick", time: 1, sequence: 1 },
					{ type: "exit", time: 1, sequence: 2 },
				],
			},
			68,
			64,
			{ timer: { delayMs: 60000, repeat: false, nextAt: 60000 } },
		);
		const text = stripTerminalSequences(lines.join("\n"));
		expect(text).toContain("◷ Tea");
		expect(text).toContain("✓ Timer · Done");
		expect(text).toContain("1m timer");
		expect(text).not.toMatch(/activity-hidden|1234|tick|exit|completed/);
	});

	it("shows repeating timer interval and next tick", () => {
		vi.spyOn(Date, "now").mockReturnValue(1000);
		const text = stripTerminalSequences(
			renderActivityFrame({ ...terminal, kind: "timer" }, 68, 64, {
				timer: { delayMs: 2000, nextAt: 3000, repeat: true },
			}).join("\n"),
		);
		expect(text).toContain("2s until next tick");
		expect(text).toContain("Repeats every 2s");
	});
	it("bounds height without losing terminal row order", () => {
		const lines = renderActivityFrame(
			{
				...terminal,
				screen: {
					...terminal.screen!,
					text: Array.from({ length: 60 }, (_, i) => `row-${i}`).join("\n"),
					rows: 60,
				},
			},
			80,
			20,
		);
		expect(lines.length).toBeLessThanOrEqual(20);
		expect(lines.join("\n")).toContain("Ctrl+G back");
		expect(stripTerminalSequences(lines[3])).toContain("row-0");
		expect(stripTerminalSequences(lines[4])).toContain("row-1");
	});

	it.each([1, 2, 3, 12, 20])("fits Unicode in %i columns", (width) => {
		expect(
			renderActivityFrame(terminal, width).every(
				(line) => visibleWidth(line) <= width,
			),
		).toBe(true);
	});

	it("removes child escapes and remaining control bytes", () => {
		expect(
			sanitizeActivityText(
				"\u001b]8;;https://bad\u0007link\u001b]8;;\u0007\u0003界",
			),
		).toBe("link�界");
	});
});

describe("terminal input", () => {
	it.each([
		["\x1bOP", "\x1bOP"],
		["\x1b[1;2P", "\x1b[1;2P"],
		["\x1b[15;5~", "\x1b[15;5~"],
		["\x1bb", "\x1bb"],
		["\x08", "\x08"],
		["\x1b[1;5A", "\x1b[1;5A"],
		["\x1b[2~", "\x1b[2~"],
		["\x1b[32;5u", "\x00"],
		["a", "a"],
		[" ", " "],
		["界😀", "界😀"],
		["\x1b[13u", "\r"],
		["\x1b[A", "\x1b[A"],
		["\x03", "\x03"],
	])("translates %j to %j", (input, expected) => {
		expect(terminalInput(input)).toEqual({ text: expected });
	});

	it("keeps paste separate from key input", () => {
		expect(terminalInput("\x1b[200~line one\nline two\x1b[201~")).toEqual({
			text: "line one\nline two",
			paste: true,
		});
	});

	it("reserves Ctrl+G for detachment", () => {
		expect(terminalInput("\x07")).toEqual({ detach: true });
	});
});