Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/fast/__tests__/settings.test.ts

Raw
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { fauxProvider } from "@earendil-works/pi-ai";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
	createPiSession,
	type PiSession,
} from "../../../test/fixture/create-pi-session.ts";

const extensionPath = path.resolve(import.meta.dirname, "../index.ts");

interface UiCall {
	args: unknown[];
}

interface RecordingUi {
	statusCalls: UiCall[];
	notifyCalls: UiCall[];
}

/**
 * Install a recording UI context so `hasUI` is true (the extension sees an
 * interactive UI) and `ctx.ui.setStatus` / `ctx.ui.notify` calls are captured.
 */
function installRecordingUi(session: PiSession): RecordingUi {
	const statusCalls: UiCall[] = [];
	const notifyCalls: UiCall[] = [];
	session.session.extensionRunner.setUIContext(
		{
			setStatus: (...args: unknown[]) => statusCalls.push({ args }),
			notify: (...args: unknown[]) => notifyCalls.push({ args }),
		} as never,
		"print",
	);
	return { statusCalls, notifyCalls };
}

type Case = { user?: unknown; project?: unknown; untrusted?: boolean };

describe("fast.enable resolution", () => {
	let session: PiSession | undefined;
	let root: string | undefined;
	afterEach(async () => {
		await session?.dispose();
		session = undefined;
		if (root) rmSync(root, { recursive: true, force: true });
		root = undefined;
	});

	async function start(input: Case) {
		root = mkdtempSync(path.join(tmpdir(), "pi-ext-fast-settings-"));
		if ("project" in input) {
			mkdirSync(path.join(root, ".pi"), { recursive: true });
			writeFileSync(
				path.join(root, ".pi", "settings.json"),
				JSON.stringify({ fast: { enable: input.project } }),
			);
		}
		session = await createPiSession({
			cwd: root,
			extensionPaths: [extensionPath],
			...("user" in input
				? { userSettings: { fast: { enable: input.user } } }
				: {}),
		});
		if (input.untrusted)
			session.session.settingsManager.setProjectTrusted(false);
		// fast only activates for the openai-codex provider; pin it through a
		// deterministic provider and select its model.
		const faux = fauxProvider({
			provider: "openai-codex",
			models: [{ id: "gpt-5.5", maxTokens: 8_192 }],
		});
		const registry =
			session.session.extensionRunner.createContext().modelRegistry;
		registry.registerProvider(faux.provider);
		await registry.refresh({ allowNetwork: false });
		const current = registry.find("openai-codex", "gpt-5.5");
		if (!current) throw new Error("missing openai-codex test model");
		await session.session.setModel(current);
		const ui = installRecordingUi(session);
		await session.session.extensionRunner.emit({
			type: "session_start",
			reason: "startup",
		});
		await vi.waitFor(() => expect(ui.statusCalls.length).toBeGreaterThan(0));
		const status = ui.statusCalls.at(-1)?.args;
		const warnings = ui.notifyCalls
			.filter((call) => call.args[1] === "warning")
			.map((call) => call.args[0]);
		return { active: status?.[1] !== undefined, warnings };
	}

	it.each([
		["default off", {}, false],
		["user true", { user: true }, true],
		["project false over user true", { user: true, project: false }, false],
		["project true over user false", { user: false, project: true }, true],
		[
			"untrusted project ignored",
			{ user: true, project: false, untrusted: true },
			true,
		],
	] satisfies [string, Case, boolean][])(
		"%s",
		async (_name, input, expected) => {
			const { active, warnings } = await start(input);
			expect(active).toBe(expected);
			expect(warnings).toEqual([]);
		},
	);

	it.each([
		["string project", { user: true, project: "true" }, "project settings"],
		["numeric user", { user: 1 }, "user settings"],
	] satisfies [string, Case, string][])(
		"rejects %s without falling through",
		async (_name, input, source) => {
			const { active, warnings } = await start(input);
			expect(active).toBe(false);
			expect(warnings.at(-1)).toBe(
				`Invalid fast.enable from ${source}; fast mode off`,
			);
		},
	);
});