Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/session-rename/__tests__/settings.test.ts

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

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

const ENV = "PI_SESSION_RENAME_IDLE_DELAY_MS";

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

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

	async function start(input: Case) {
		root = mkdtempSync(path.join(tmpdir(), "pi-ext-session-rename-settings-"));
		session = await createPiSession({
			cwd: root,
			extensionPaths: [extensionPath()],
			env: { [ENV]: input.env },
		});
		const write = (dir: string, value: unknown) => {
			mkdirSync(dir, { recursive: true });
			writeFileSync(
				path.join(dir, "settings.json"),
				JSON.stringify({ "session-rename": { idleDelayMs: value } }),
			);
		};
		if ("user" in input) write(session.agentDir, input.user);
		if ("project" in input) write(path.join(session.cwd, ".pi"), input.project);
		if (input.untrusted)
			session.session.settingsManager.setProjectTrusted(false);

		const runner = session.session.extensionRunner;
		// scheduleRename needs a session file; the fixture session is in-memory.
		vi.spyOn(session.session.sessionManager, "getSessionFile").mockReturnValue(
			path.join(root, "session.jsonl"),
		);
		// Recording UI context so notify warnings are observable (hasUI true).
		const notifyCalls: { args: [string, string | undefined] }[] = [];
		runner.setUIContext(
			{
				notify: (message: string, type?: string) =>
					notifyCalls.push({ args: [message, type] }),
				setStatus: () => {},
			} as never,
			"tui",
		);

		const notify = notifyCalls.length;
		await runner.emit({ type: "session_start", reason: "startup" });
		const warnings = notifyCalls
			.slice(notify)
			.filter((call) => call.args[1] === "warning")
			.map((call) => call.args[0]);
		const setTimeoutSpy = vi.spyOn(globalThis, "setTimeout");
		await session.session.prompt("Probe the configured rename delay.");
		const delays = setTimeoutSpy.mock.calls.map((call) => call[1]);
		setTimeoutSpy.mockRestore();
		return { delays, warnings };
	}

	it.each([
		["default unchanged", {}, 10_000],
		["user value", { user: 2_500 }, 2_500],
		["zero allowed", { user: 0 }, 0],
		["env over settings", { user: 2_500, project: 3_000, env: "4000" }, 4_000],
		["trusted project over user", { user: 2_500, project: 3_000 }, 3_000],
		[
			"untrusted project ignored",
			{ user: 2_500, project: 3_000, untrusted: true },
			2_500,
		],
	] satisfies [string, Case, number][])(
		"%s",
		async (_name, input, expected) => {
			const { delays, warnings } = await start(input);
			expect(delays).toContain(expected);
			expect(warnings).toEqual([]);
		},
	);

	it.each([
		[
			"string project",
			{ user: 2_500, project: "3000" },
			"Invalid session-rename.idleDelayMs from project settings",
		],
		[
			"negative user",
			{ user: -1 },
			"Invalid session-rename.idleDelayMs from user settings: expected an integer from 0 to 2147483647",
		],
		[
			"fractional project",
			{ user: 2_500, project: 1.5 },
			"Invalid session-rename.idleDelayMs from project settings: expected an integer from 0 to 2147483647",
		],
		[
			"non-numeric env",
			{ user: 2_500, env: "soon" },
			`Invalid session-rename.idleDelayMs from environment variable ${ENV}`,
		],
	] satisfies [string, Case, string][])(
		"rejects %s without falling through",
		async (_name, input, error) => {
			const { delays, warnings } = await start(input);
			expect(delays).toContain(10_000);
			expect(delays).not.toContain(2_500);
			expect(warnings).toEqual([`${error}; using 10000 ms`]);
		},
	);
});