Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/firefox-bidi/__tests__/settings.test.ts

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

const extensionPath = fileURLToPath(new URL("../index.ts", import.meta.url));

type Case = {
	user?: Record<string, unknown> | undefined;
	project?: Record<string, unknown> | undefined;
	env?: Record<string, string> | undefined;
	flag?: boolean | undefined;
	untrusted?: boolean | undefined;
};

type Notification = {
	message: unknown;
	type?: "info" | "warning" | "error" | undefined;
};

describe("firefox-bidi settings resolution", () => {
	let session: PiSession | undefined;
	let root = "";
	let notifications: Notification[] = [];
	afterEach(async () => {
		await session?.dispose();
		session = undefined;
		notifications = [];
		if (root) rmSync(root, { recursive: true, force: true });
		root = "";
	});

	function recordingUI(): ExtensionUIContext {
		const noop = () => undefined;
		return {
			select: async () => undefined,
			confirm: async () => false,
			input: async () => undefined,
			editor: async () => undefined,
			custom: async () => undefined,
			notify: (message: unknown, type?: "info" | "warning" | "error") =>
				notifications.push({ message, type }),
			onTerminalInput: () => noop,
			setStatus: noop,
			setWorkingMessage: noop,
			setWorkingVisible: noop,
			setWorkingIndicator: noop,
		} as unknown as ExtensionUIContext;
	}

	async function start(input: Case) {
		root = mkdtempSync(path.join(tmpdir(), "pi-ext-firefox-bidi-settings-"));
		if (input.project) {
			const dir = path.join(root, ".pi");
			mkdirSync(dir, { recursive: true });
			writeFileSync(
				path.join(dir, "settings.json"),
				JSON.stringify({ "firefox-bidi": input.project }),
			);
		}
		session = await createPiSession({
			cwd: root,
			extensionPaths: [extensionPath],
			...(input.user ? { userSettings: { "firefox-bidi": input.user } } : {}),
			env: {
				PI_FIREFOX: input.env?.["PI_FIREFOX"],
				FIREFOX_BIN: input.env?.["FIREFOX_BIN"],
			},
		});
		const runner = session.session.extensionRunner;
		const extensions = session.extensions;
		runner.setUIContext(recordingUI());
		if (input.untrusted)
			session.session.settingsManager.setProjectTrusted(false);
		if (input.flag !== undefined) runner.setFlagValue("firefox", input.flag);
		await runner.emit({ type: "session_start", reason: "startup" });
		const warnings = [
			...new Set(
				notifications
					.filter(
						(call) =>
							call.type === "warning" &&
							String(call.message).includes("Invalid"),
					)
					.map((call) => String(call.message)),
			),
		];
		const execute = (frames: { method: string; params?: object }[]) =>
			extensions[0]?.tools
				.get("firefox_bidi")
				?.definition.execute(
					"call",
					{ frames },
					undefined,
					undefined,
					runner.createToolContext("call", undefined),
				);
		return {
			active: session.session.getActiveToolNames().includes("firefox_bidi"),
			warnings,
			execute,
		};
	}

	describe("firefox-bidi.enable", () => {
		it("registers --firefox without a default", async () => {
			await start({});
			const runner = session?.session.extensionRunner;
			expect(runner?.getFlags().get("firefox")?.default).toBeUndefined();
			expect(runner?.getFlagValues().has("firefox")).toBe(false);
		});

		it.each([
			[
				"flag --firefox over env PI_FIREFOX=0",
				{ env: { PI_FIREFOX: "0" }, flag: true },
				true,
			],
			[
				"flag --firefox over project false",
				{ project: { enable: false }, flag: true },
				true,
			],
			["default off", {}, false],
			["user true", { user: { enable: true } }, true],
			[
				"project false over user true",
				{ user: { enable: true }, project: { enable: false } },
				false,
			],
			[
				"env PI_FIREFOX=1 over project false",
				{ project: { enable: false }, env: { PI_FIREFOX: "1" } },
				true,
			],
			[
				"env PI_FIREFOX=0 over user true",
				{ user: { enable: true }, env: { PI_FIREFOX: "0" } },
				false,
			],
			[
				"untrusted project ignored",
				{ user: { enable: true }, project: { enable: 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 env",
				{ user: { enable: true }, env: { PI_FIREFOX: "yes" } },
				"environment variable PI_FIREFOX",
			],
			[
				"string project",
				{ user: { enable: true }, project: { enable: "true" } },
				"project 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).toEqual([
					`firefox-bidi: Invalid firefox-bidi.enable from ${source}`,
				]);
			},
		);
	});

	describe("firefox-bidi.executablePath", () => {
		const bin = (name: string) => `/nonexistent/${name}/firefox`;

		it.each([
			["user", { user: { executablePath: bin("user") } }, "user"],
			[
				"project over user",
				{
					user: { executablePath: bin("user") },
					project: { executablePath: bin("project") },
				},
				"project",
			],
			[
				"env FIREFOX_BIN over project",
				{
					project: { executablePath: bin("project") },
					env: { FIREFOX_BIN: bin("env") },
				},
				"env",
			],
			[
				"untrusted project ignored",
				{
					user: { executablePath: bin("user") },
					project: { executablePath: bin("project") },
					untrusted: true,
				},
				"user",
			],
		] satisfies [string, Case, string][])(
			"%s",
			async (_name, input, expected) => {
				const { execute, warnings } = await start(input);
				expect(warnings).toEqual([]);
				await expect(execute([])).rejects.toThrow(
					`firefox not found: ${bin(expected)}`,
				);
			},
		);

		it.each([
			[
				"empty env",
				{ user: { executablePath: bin("user") }, env: { FIREFOX_BIN: "" } },
				"environment variable FIREFOX_BIN",
			],
			[
				"numeric project",
				{
					user: { executablePath: bin("user") },
					project: { executablePath: 1 },
				},
				"project settings",
			],
		] satisfies [string, Case, string][])(
			"rejects %s without falling through",
			async (_name, input, source) => {
				const { execute, warnings } = await start(input);
				const error = `Invalid firefox-bidi.executablePath from ${source}: expected a non-empty string`;
				expect(warnings).toEqual([`firefox-bidi: ${error}`]);
				await expect(execute([])).rejects.toThrow(error);
			},
		);
	});

	describe("firefox-bidi.screencastDir", () => {
		// resolveScreencastDestinations mutates frames, so each call gets fresh ones.
		const screencast = () => [
			{ method: "browsingContext.startScreencast", params: { context: "x" } },
		];
		const firefox = { executablePath: "/nonexistent/firefox" };

		it.each([
			["user", { user: "user" }, "user"],
			["project over user", { user: "user", project: "project" }, "project"],
			[
				"untrusted project ignored",
				{ user: "user", project: "project", untrusted: true },
				"user",
			],
		] as [
			string,
			{ user: string; project?: string; untrusted?: boolean },
			string,
		][])("%s", async (_name, input, expected) => {
			const casts = mkdtempSync(
				path.join(tmpdir(), "pi-ext-firefox-bidi-casts-"),
			);
			try {
				const { execute } = await start({
					user: { ...firefox, screencastDir: path.join(casts, input.user) },
					project: input.project
						? { screencastDir: path.join(casts, input.project) }
						: undefined,
					untrusted: input.untrusted,
				});
				await expect(execute(screencast())).rejects.toThrow(
					/firefox not found/,
				);
				expect(readdirSync(casts)).toEqual([expected]);
			} finally {
				rmSync(casts, { recursive: true, force: true });
			}
		});

		it("rejects invalid project value without falling through", async () => {
			const { execute } = await start({
				user: { ...firefox, screencastDir: "/nonexistent/casts" },
				project: { screencastDir: 42 },
			});
			await expect(execute(screencast())).rejects.toThrow(
				"Invalid firefox-bidi.screencastDir from project settings: expected a non-empty string",
			);
		});
	});
});