repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/mode/__tests__/unit.test.ts

Raw
File outline
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import type { Theme } from "@earendil-works/pi-coding-agent";
import type { Component, TUI } from "@earendil-works/pi-tui";
import { describe, expect, it } from "vitest";
import modeExtension, { __modeTest } from "../index.ts";

function mockTheme(
	overrides: {
		fg?: (color: string, text: string) => string;
		bg?: (color: string, text: string) => string;
		bold?: (text: string) => string;
		italic?: (text: string) => string;
		underline?: (text: string) => string;
		inverse?: (text: string) => string;
		strikethrough?: (text: string) => string;
	} = {},
) {
	const identity = (text: string) => text;
	const passthrough = (_color: string, text: string) => text;
	return {
		fg: overrides.fg ?? passthrough,
		bg: overrides.bg ?? passthrough,
		bold: overrides.bold ?? identity,
		italic: overrides.italic ?? identity,
		underline: overrides.underline ?? identity,
		inverse: overrides.inverse ?? identity,
		strikethrough: overrides.strikethrough ?? identity,
	};
}

type WidgetFactory = (
	tui: TUI,
	theme: Theme,
) => Component & {
	dispose?(): void;
};

function expectFactory(value: WidgetFactory | undefined): WidgetFactory {
	expect(value).toBeDefined();
	if (!value) throw new Error("expected widget factory");
	return value;
}

describe("mode pure helpers", () => {
	it("parses valid mode markdown", () => {
		const mode = __modeTest.parseModeMarkdown(
			"plan",
			`---\ndescription: Read-only planning\naccent: warning\nmodel: openai/gpt-5.2-codex\nthinking: high\ntools: [read, grep]\nreminder: Stay read-only.\n---\n\n# Plan\n\nBody.\n`,
		);
		expect(mode).toEqual({
			id: "plan",
			description: "Read-only planning",
			accent: "warning",
			model: "openai/gpt-5.2-codex",
			thinking: "high",
			tools: ["read", "grep"],
			reminder: "Stay read-only.",
			body: "# Plan\n\nBody.\n",
		});
	});

	it("splits frontmatter variants", () => {
		expect(__modeTest.frontmatterSplit("body")).toEqual({
			frontmatter: "",
			body: "body",
		});
		expect(__modeTest.frontmatterSplit("---\nmissing close")).toEqual({
			frontmatter: "",
			body: "---\nmissing close",
		});
		expect(__modeTest.frontmatterSplit("---\na: 1\n---\nbody")).toEqual({
			frontmatter: "a: 1",
			body: "body",
		});
	});

	it("allows empty body, empty frontmatter, and unknown keys", () => {
		expect(
			__modeTest.parseModeMarkdown("empty", "---\nunknown: ok\n---\n"),
		).toEqual({
			id: "empty",
			body: "",
		});
	});

	it("rejects invalid frontmatter and field types", () => {
		expect(() =>
			__modeTest.parseModeMarkdown("bad", "---\n[1]\n---\nbody"),
		).toThrow("mode bad: frontmatter must be a mapping");
		expect(() =>
			__modeTest.parseModeMarkdown("bad", "---\ndescription: 1\n---\nbody"),
		).toThrow("mode bad: description must be a string");
		expect(() =>
			__modeTest.parseModeMarkdown("bad", "---\nmodel: 1\n---\nbody"),
		).toThrow("mode bad: model must be a string");
		expect(() =>
			__modeTest.parseModeMarkdown("bad", "---\nreminder: 1\n---\nbody"),
		).toThrow("mode bad: reminder must be a string");
		expect(() =>
			__modeTest.parseModeMarkdown("bad", "---\ntools: read\n---\nbody"),
		).toThrow("mode bad: tools must be an array of strings");
		expect(() =>
			__modeTest.parseModeMarkdown("bad", "---\ntools: [read, 1]\n---\nbody"),
		).toThrow("mode bad: tools must be an array of strings");
		expect(() =>
			__modeTest.parseModeMarkdown("bad", "---\nthinking: huge\n---\nbody"),
		).toThrow(
			"mode bad: thinking must be one of off, minimal, low, medium, high, xhigh",
		);
		expect(() =>
			__modeTest.parseModeMarkdown("bad", "---\nthinking: 1\n---\nbody"),
		).toThrow(
			"mode bad: thinking must be one of off, minimal, low, medium, high, xhigh",
		);
		expect(() =>
			__modeTest.parseModeMarkdown("bad", "---\naccent: hotpink\n---\nbody"),
		).toThrow(
			`mode bad: accent must be one of ${__modeTest.ACCENT_COLORS.join(", ")}`,
		);
		expect(() =>
			__modeTest.parseModeMarkdown("bad", "---\naccent: 1\n---\nbody"),
		).toThrow(
			`mode bad: accent must be one of ${__modeTest.ACCENT_COLORS.join(", ")}`,
		);
	});

	it("validates ids", () => {
		expect(__modeTest.isValidModeId("plan_1-build")).toBe(true);
		expect(__modeTest.isValidModeId("../plan")).toBe(false);
		expect(__modeTest.isValidModeId("plan mode")).toBe(false);
	});

	it("splits model ref at first slash", () => {
		expect(__modeTest.parseModelRef("openai/gpt-5.2/codex")).toEqual({
			provider: "openai",
			modelId: "gpt-5.2/codex",
		});
		expect(__modeTest.parseModelRef("missing-slash")).toBeUndefined();
		expect(__modeTest.parseModelRef("provider/")).toBeUndefined();
	});

	it("renders active prompt addition", () => {
		const text = __modeTest.modePromptAddition({
			id: "plan",
			body: "# Body\n",
			reminder: "Stay read-only.",
		});
		expect(text).toContain("# Body");
		expect(text).toContain("<mode_kernel>");
		expect(text).toContain("active_mode: plan");
		expect(text).toContain(
			"<mode_reminder>\nStay read-only.\n</mode_reminder>",
		);
		expect(text.indexOf("# Body")).toBeLessThan(text.indexOf("<mode_kernel>"));
		expect(
			__modeTest.modePromptAddition({ id: "plain", body: "# Body\n" }),
		).not.toContain("<mode_reminder>");
		const withRuntimeFields = __modeTest.modePromptAddition({
			id: "plan",
			body: "body",
			tools: ["read"],
			model: "openai/gpt",
			thinking: "high",
		});
		expect(withRuntimeFields).not.toContain("tools:");
		expect(withRuntimeFields).not.toContain("model: openai/gpt");
		expect(withRuntimeFields).not.toContain("thinking: high");
	});

	it("renders normal neutralizer", () => {
		expect(__modeTest.normalPromptAddition()).toBe(
			`<mode_kernel>\nactive_mode: normal\nactive mode is runtime state, not conversation state\nprevious mode prompts are inactive unless repeated here\n</mode_kernel>`,
		);
	});

	it("keeps malformed model refs unresolved", () => {
		expect(__modeTest.parseModelRef("/model")).toBeUndefined();
		expect(__modeTest.parseModelRef("provider/")).toBeUndefined();
		expect(__modeTest.parseModelRef("provider/model/name")).toEqual({
			provider: "provider",
			modelId: "model/name",
		});
	});

	it("loads mode files and reports invalid files", async () => {
		const agentDir = mkdtempSync(path.join(tmpdir(), "mode-unit-"));
		try {
			const modesDir = path.join(agentDir, "modes");
			mkdirSync(modesDir);
			writeFileSync(path.join(modesDir, "plan.md"), "# Plan\n", "utf8");
			writeFileSync(path.join(modesDir, "notes.txt"), "skip", "utf8");
			writeFileSync(path.join(modesDir, "bad id.md"), "# Bad\n", "utf8");
			writeFileSync(
				path.join(modesDir, "bad-yaml.md"),
				"---\n[\n---\n",
				"utf8",
			);
			writeFileSync(
				path.join(modesDir, "bad-field.md"),
				"---\ndescription: 1\n---\n",
				"utf8",
			);

			const loaded = await __modeTest.loadModes(agentDir);

			expect([...loaded.modes.keys()]).toEqual(["plan"]);
			expect(loaded.warnings).toEqual(
				expect.arrayContaining([
					"ignored invalid mode id: bad id.md",
					"mode bad-field: description must be a string",
				]),
			);
			expect(
				loaded.warnings.some((warning) => warning.includes("bad-yaml")),
			).toBe(true);
		} finally {
			rmSync(agentDir, { recursive: true, force: true });
		}
	});

	it("returns no modes when the mode directory is absent", async () => {
		const agentDir = mkdtempSync(path.join(tmpdir(), "mode-unit-"));
		try {
			const loaded = await __modeTest.loadModes(agentDir);
			expect(loaded.modes.size).toBe(0);
			expect(loaded.warnings).toEqual([]);
		} finally {
			rmSync(agentDir, { recursive: true, force: true });
		}
	});

	it("throws non-missing mode directory read errors", async () => {
		const agentDir = mkdtempSync(path.join(tmpdir(), "mode-unit-"));
		try {
			writeFileSync(path.join(agentDir, "modes"), "not a dir", "utf8");
			await expect(__modeTest.loadModes(agentDir)).rejects.toThrow();
		} finally {
			rmSync(agentDir, { recursive: true, force: true });
		}
	});
});

describe("mode widget factory", () => {
	it("returns undefined for null to clear widget", () => {
		expect(__modeTest.buildWidget(null)).toBeUndefined();
	});

	it("returns a component factory for a mode", () => {
		const factory = __modeTest.buildWidget({
			id: "plan",
			body: "body",
			accent: "warning",
		});
		expect(typeof factory).toBe("function");
	});

	it("applies theme color and bold to banner", () => {
		const factory = expectFactory(
			__modeTest.buildWidget({
				id: "plan",
				body: "body",
				accent: "warning",
			}),
		);
		const calls: Array<[string, string]> = [];
		const theme = mockTheme({
			fg: (color, text) => {
				calls.push(["fg", color]);
				return text;
			},
			bold: (text) => text,
		});
		const component = factory({} as never, theme as never);
		component.render(80);
		expect(calls).toContainEqual(["fg", "warning"]);
	});

	it("defaults accent to accent color", () => {
		const factory = expectFactory(
			__modeTest.buildWidget({ id: "plan", body: "body" }),
		);
		const calls: string[] = [];
		const theme = mockTheme({
			fg: (color) => {
				calls.push(color);
				return "";
			},
			bold: (text) => text,
		});
		factory({} as never, theme as never).render(80);
		expect(calls).toContain("accent");
	});

	it("includes description and meta when present", () => {
		const factory = expectFactory(
			__modeTest.buildWidget({
				id: "plan",
				body: "body",
				description: "Read-only planning",
				tools: ["read", "grep"],
				model: "openai/gpt-5.2-codex",
				thinking: "high",
			}),
		);
		const theme = mockTheme();
		const lines = factory({} as never, theme as never).render(120);
		const flat = lines.join("\n");
		expect(lines).toHaveLength(1);
		expect(flat).toContain("MODE: plan");
		expect(flat).toContain("Read-only planning");
		expect(flat).toContain("tools: read,grep");
		expect(flat).toContain("model: openai/gpt-5.2-codex");
		expect(flat).toContain("thinking: high");
		expect(factory({} as never, theme as never).render(40)).toHaveLength(1);
	});

	it("omits description and meta when absent", () => {
		const factory = expectFactory(
			__modeTest.buildWidget({ id: "plan", body: "body" }),
		);
		const theme = mockTheme();
		const flat = factory({} as never, theme as never)
			.render(120)
			.join("\n");
		expect(flat).toContain("MODE: plan");
		expect(flat).not.toContain("tools:");
		expect(flat).not.toContain("model:");
		expect(flat).not.toContain("thinking:");
	});
});

describe("mode picker", () => {
	it("fuzzy filters typed input and selects", () => {
		const selected: Array<string | undefined> = [];
		const picker = __modeTest.createModePicker(
			[
				{ value: "off", label: "off", description: "Turn mode off" },
				{ value: "plan", label: "plan", description: "Read-only" },
				{ value: "plain", label: "plain", description: "Build" },
			],
			mockTheme() as never,
			(value) => selected.push(value),
			() => undefined,
		);
		expect(picker.render(80).join("\n")).toContain("Turn mode off");
		picker.handleInput?.("p");
		picker.handleInput?.("l");
		picker.handleInput?.("a");
		picker.handleInput?.("i");
		picker.handleInput?.("\r");
		expect(selected).toEqual(["plain"]);
	});
});

describe("mode runtime event handlers", () => {
	it("session_shutdown with no UI does not throw", () => {
		const events = new Map<string, (...args: unknown[]) => unknown>();
		modeExtension({
			events: { emit: () => undefined },
			getAllTools: () => [],
			getThinkingLevel: () => "medium",
			on: (name: string, handler: (...args: unknown[]) => unknown) =>
				events.set(name, handler),
			registerCommand: () => undefined,
			registerShortcut: () => undefined,
			setActiveTools: () => undefined,
			setModel: async () => true,
			setThinkingLevel: () => undefined,
		} as never);
		expect(() =>
			events.get("session_shutdown")?.({}, { hasUI: false } as never),
		).not.toThrow();
	});

	it("session_start resets in-memory state and clears widget", async () => {
		const events = new Map<string, (...args: unknown[]) => unknown>();
		const commands = new Map<
			string,
			{ handler: (args: string, ctx: unknown) => Promise<void> }
		>();
		const widgets: unknown[] = [];
		const ctx = {
			hasUI: true,
			model: undefined,
			modelRegistry: { find: () => undefined },
			ui: {
				notify: () => undefined,
				setEditorText: () => undefined,
				setStatus: () => undefined,
				setWidget: (...args: unknown[]) => widgets.push(args),
				theme: { fg: (_color: string, text: string) => text },
			},
		};
		modeExtension({
			events: { emit: () => undefined },
			getAllTools: () => [],
			getThinkingLevel: () => "medium",
			on: (name: string, handler: (...args: unknown[]) => unknown) =>
				events.set(name, handler),
			registerCommand: (
				name: string,
				command: { handler: (args: string, ctx: unknown) => Promise<void> },
			) => commands.set(name, command),
			registerShortcut: () => undefined,
			setActiveTools: () => undefined,
			setModel: async () => true,
			setThinkingLevel: () => undefined,
		} as never);
		await events.get("session_start")?.({ reason: "startup" }, ctx);
		expect(widgets).toEqual([["mode", undefined]]);
		const beforeAgent = events.get("before_agent_start")?.(
			{ systemPrompt: "BASE" },
			ctx,
		);
		expect(beforeAgent).toBeUndefined();
	});
});