Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/rtk/__tests__/settings.test.ts

Raw
import {
	chmodSync,
	mkdirSync,
	mkdtempSync,
	rmSync,
	writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { createTestSession, type TestSession } from "../../../test/harness";

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

// Rewrites answer after 300ms; the version probe optionally does too.
const FAKE_RTK = `#!/usr/bin/env node
const [, , sub] = process.argv;
const delay = sub === "--version" ? Number(process.env.FAKE_RTK_VERSION_DELAY ?? 0) : 300;
setTimeout(() => {
	console.log(sub === "--version" ? "rtk 0.37.2" : "rtk git status");
}, delay);
`;

type Case = {
	user?: unknown;
	project?: unknown;
	env?: string;
	untrusted?: boolean;
	versionDelay?: number;
};

describe.skipIf(process.platform === "win32")(
	"rtk.rewriteTimeoutMs resolution",
	() => {
		let t: TestSession | undefined;
		let root: string | undefined;
		afterEach(async () => {
			await t?.session.extensionRunner.emit({
				type: "session_shutdown",
				reason: "quit",
			});
			t?.dispose();
			t = undefined;
			if (root) rmSync(root, { recursive: true, force: true });
			root = undefined;
		});

		async function start(input: Case) {
			root = mkdtempSync(path.join(tmpdir(), "pi-ext-rtk-settings-"));
			const bin = path.join(root, "bin");
			mkdirSync(bin);
			writeFileSync(path.join(bin, "rtk"), FAKE_RTK);
			chmodSync(path.join(bin, "rtk"), 0o755);
			const write = (dir: string, value: unknown) => {
				mkdirSync(dir, { recursive: true });
				writeFileSync(
					path.join(dir, "settings.json"),
					JSON.stringify({ rtk: { rewriteTimeoutMs: value } }),
				);
			};
			if ("user" in input)
				write(path.join(root, ".test-home/.pi/agent"), input.user);
			if ("project" in input) write(path.join(root, ".pi"), input.project);
			t = await createTestSession({
				cwd: root,
				extensions: [extensionPath],
				env: {
					PATH: `${bin}${path.delimiter}${process.env.PATH ?? ""}`,
					PI_RTK_REWRITE_TIMEOUT_MS: input.env,
					FAKE_RTK_VERSION_DELAY: input.versionDelay?.toString(),
				},
			});
			if (input.untrusted) t.session.settingsManager.setProjectTrusted(false);
			const runner = t.session.extensionRunner;
			const before = t.events.uiCallsFor("notify").length;
			await runner.emit({ type: "session_start", reason: "startup" });
			const event = {
				type: "tool_call",
				toolName: "bash",
				toolCallId: "1",
				input: { command: "git status" },
			};
			await runner.emitToolCall(event as never);
			const warnings = t.events
				.uiCallsFor("notify")
				.slice(before)
				.filter((call) => call.args[1] === "warning")
				.map((call) => call.args[0]);
			return { rewritten: event.input.command !== "git status", warnings };
		}

		it.each([
			["default waits for rewrite", {}, true],
			["user timeout applied", { user: 100 }, false],
			["env over user", { user: 100, env: "5000" }, true],
			["trusted project over user", { user: 5000, project: 100 }, false],
			[
				"untrusted project ignored",
				{ user: 5000, project: 100, untrusted: true },
				true,
			],
		] satisfies [string, Case, boolean][])(
			"%s",
			async (_name, input, expected) => {
				const { rewritten, warnings } = await start(input);
				expect(rewritten).toBe(expected);
				expect(warnings).toEqual([]);
			},
		);

		it("applies the timeout to the version probe", async () => {
			const { rewritten, warnings } = await start({
				user: 100,
				versionDelay: 300,
			});
			expect(rewritten).toBe(false);
			// A killed probe reports empty output, which rtk treats as an unknown version.
			expect(warnings).toEqual([
				"rtk disabled: too old (unknown); need >= 0.23.0",
			]);
		});

		it.each([
			["string user", { user: "100" }, "user settings"],
			["zero project", { user: 100, project: 0 }, "project settings"],
			["fractional user", { user: 100.5 }, "user settings"],
			[
				"non-numeric env",
				{ user: 100, env: "fast" },
				"environment variable PI_RTK_REWRITE_TIMEOUT_MS",
			],
		] satisfies [string, Case, string][])(
			"rejects %s without falling through",
			async (_name, input, source) => {
				const { rewritten, warnings } = await start(input);
				// The 2000ms default outlasts the 300ms rewrite; a 100ms fallthrough would not.
				expect(rewritten).toBe(true);
				expect(warnings).toEqual([
					`Invalid rtk.rewriteTimeoutMs from ${source}: expected an integer from 1 to 2147483647; using 2000ms`,
				]);
			},
		);
	},
);