repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/masks/__tests__/harness.test.ts

Raw
File outline
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { afterEach, describe, expect, it } from "vitest";
import { createTestSession, type TestSession } from "../../../test/harness";
import { __test } from "../index.ts";

let root: string | undefined;
let t: TestSession | undefined;

function extensionPath(): string {
	return fileURLToPath(new URL("../index.ts", import.meta.url));
}

function writeSettings(settings: Record<string, unknown>): string {
	root = mkdtempSync(join(tmpdir(), "masks-test-"));
	const agentDir = join(root, ".test-home", ".pi", "agent");
	mkdirSync(agentDir, { recursive: true });
	writeFileSync(join(agentDir, "settings.json"), JSON.stringify(settings));
	return root;
}

function writePrompt(name: string, content: string): void {
	if (!root) throw new Error("missing test root");
	const promptsDir = join(root, "prompts");
	mkdirSync(promptsDir, { recursive: true });
	writeFileSync(join(promptsDir, `${name}.md`), content);
}

function extension() {
	if (!t) throw new Error("missing test session");
	return t.session.extensionRunner.extensions[0];
}

function context() {
	if (!t) throw new Error("missing test session");
	return t.session.extensionRunner.createCommandContext();
}

afterEach(() => {
	t?.dispose();
	t = undefined;
	if (root) rmSync(root, { recursive: true, force: true });
	root = undefined;
});

describe("masks pi-test-harness", () => {
	it("switches complete masks from direct shortcut, picker, and command", async () => {
		const cwd = writeSettings({
			masks: {
				pickerShortcut: "alt+m",
				items: [
					{
						name: "low",
						model: "openai/gpt-4o",
						thinkingLevel: "low",
						shortcut: "alt+1",
					},
					{
						name: "high",
						model: "openai/gpt-4o",
						thinkingLevel: "high",
						shortcut: "alt+2",
					},
					{
						name: "missing",
						model: "absent/nope",
						thinkingLevel: "max",
						shortcut: "alt+3",
					},
				],
			},
		});
		t = await createTestSession({
			cwd,
			extensions: [extensionPath()],
			mockUI: { select: 1 },
		});

		const model = context().modelRegistry.find("openai", "gpt-4o");
		if (!model) throw new Error("missing harness model");
		model.reasoning = true;

		expect([...extension().commands.keys()]).toEqual(["masks"]);
		expect([...extension().shortcuts.keys()]).toEqual([
			"alt+m",
			"alt+1",
			"alt+2",
			"alt+3",
		]);

		await extension().shortcuts.get("alt+1").handler(context());
		expect(t.session.model.provider).toBe("openai");
		expect(t.session.model.id).toBe("gpt-4o");
		expect(t.session.thinkingLevel).toBe("low");

		await extension().shortcuts.get("alt+m").handler(context());
		expect(t.session.thinkingLevel).toBe("high");
		expect(t.events.uiCallsFor("select")[0].args).toEqual([
			"Masks",
			[
				"low  openai/gpt-4o:low",
				"high  openai/gpt-4o:high",
				"missing  absent/nope:max",
			],
		]);

		await extension().commands.get("masks").handler("low", context());
		expect(t.session.thinkingLevel).toBe("low");

		await extension().shortcuts.get("alt+3").handler(context());
		expect(t.session.thinkingLevel).toBe("low");
		expect(t.events.uiCallsFor("notify").at(-1)?.args).toEqual([
			'Mask "missing": model absent/nope not found',
			"error",
		]);
	});

	it("applies prompt frontmatter for one agent run, then restores", async () => {
		const cwd = writeSettings({
			masks: {
				items: [
					{
						name: "focused",
						model: "openai/gpt-4o",
						thinkingLevel: "high",
					},
				],
			},
		});
		writePrompt(
			"review",
			"---\ndescription: Review changes\nmask: focused\n---\nReview it.",
		);
		t = await createTestSession({ cwd, extensions: [extensionPath()] });
		const model = context().modelRegistry.find("openai", "gpt-4o");
		if (!model) throw new Error("missing harness model");
		model.reasoning = true;

		const inputHandler = extension().handlers.get("input")[0];
		const beforeHandler = extension().handlers.get("before_agent_start")[0];
		const endHandler = extension().handlers.get("agent_end")[0];
		expect(
			await inputHandler(
				{ type: "input", text: "/review", source: "interactive" },
				context(),
			),
		).toEqual({ action: "continue" });

		await beforeHandler(
			{
				type: "before_agent_start",
				prompt: "Review it.",
				images: undefined,
				systemPrompt: "",
				systemPromptOptions: {},
			},
			context(),
		);
		expect(t.session.thinkingLevel).toBe("high");

		await endHandler({ type: "agent_end", messages: [] }, context());
		expect(t.session.model.provider).toBe("openai");
		expect(t.session.model.id).toBe("gpt-4o");
		expect(t.session.thinkingLevel).toBe("off");
	});

	it("rejects masked prompt templates queued mid-run", async () => {
		const cwd = writeSettings({
			masks: {
				items: [
					{
						name: "focused",
						model: "openai/gpt-4o",
						thinkingLevel: "high",
					},
				],
			},
		});
		writePrompt("review", "---\nmask: focused\n---\nReview it.");
		t = await createTestSession({ cwd, extensions: [extensionPath()] });
		const busyContext = { ...context(), isIdle: () => false };
		const result = await extension().handlers.get("input")[0](
			{
				type: "input",
				text: "/review later",
				source: "interactive",
				streamingBehavior: "followUp",
			},
			busyContext,
		);

		expect(result).toEqual({ action: "handled" });
		expect(t.events.uiCallsFor("notify").at(-1)?.args).toEqual([
			"Prompt /review: masked prompts cannot be queued mid-run",
			"warning",
		]);
	});

	it("fuzzy-matches non-prefix mask queries", () => {
		const parsed = __test.parseMasksSettings({
			items: [
				{
					name: "terra",
					model: "openai-codex/gpt-5.6-terra",
					thinkingLevel: "medium",
				},
				{
					name: "sol-xhigh",
					model: "openai-codex/gpt-5.6-sol",
					thinkingLevel: "xhigh",
				},
			],
		});

		expect(
			__test.fuzzyMasks(parsed.config.items, "sxh").map((mask) => mask.name),
		).toEqual(["sol-xhigh"]);
	});

	it("equips the fuzzy picker's selected result", async () => {
		const parsed = __test.parseMasksSettings({
			items: [
				{
					name: "terra",
					model: "openai-codex/gpt-5.6-terra",
					thinkingLevel: "medium",
				},
				{
					name: "sol-xhigh",
					model: "openai-codex/gpt-5.6-sol",
					thinkingLevel: "xhigh",
				},
			],
		});
		const selected = await __test.chooseFuzzyMask(parsed.config.items, {
			ui: {
				custom: async (factory: any) => {
					let result: string | undefined;
					const component = await factory(
						{ requestRender() {} },
						{
							bold: (text: string) => text,
							fg: (_color: string, text: string) => text,
						},
						{
							matches: (data: string, action: string) =>
								action === "tui.select.confirm" && data === "\r",
						},
						(value: string | undefined) => {
							result = value;
						},
					);
					for (const key of ["s", "x", "h", "\r"]) component.handleInput(key);
					return result;
				},
			},
		} as any);

		expect(selected?.name).toBe("sol-xhigh");
	});

	it("validates schema while preserving usable picker entries", () => {
		const parsed = __test.parseMasksSettings({
			pickerShortcut: "alt+m",
			items: [
				{
					name: "a",
					model: "provider/a",
					thinkingLevel: "high",
					shortcut: "alt+1",
				},
				{
					name: "a",
					model: "provider/b",
					thinkingLevel: "low",
				},
				{
					name: "b",
					model: "provider/b",
					thinkingLevel: "low",
					shortcut: "alt+1",
				},
				{ name: "bad", model: "missing-provider", thinkingLevel: "huge" },
			],
		});

		expect(parsed.config).toEqual({
			pickerShortcut: "alt+m",
			items: [
				{
					name: "a",
					model: "provider/a",
					thinkingLevel: "high",
					shortcut: "alt+1",
				},
				{
					name: "b",
					model: "provider/b",
					thinkingLevel: "low",
					shortcut: undefined,
				},
			],
		});
		expect(parsed.errors).toEqual([
			'masks.items[1].name duplicates "a"',
			'masks.items[2].shortcut duplicates "alt+1"',
			"masks.items[3].model must be provider/model",
			"masks.items[3].thinkingLevel is invalid",
		]);
	});

	it("keeps a model id containing slashes", () => {
		expect(__test.splitModelRef("provider/org/model")).toEqual([
			"provider",
			"org/model",
		]);
	});
});