Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/clipboard/__serial__/fixture.test.ts

Raw
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
import { afterEach, describe, expect, it, vi } from "vitest";
import clipboardFixture from "../demo/fixture.ts";

vi.mock("node:fs", () => ({
	chmodSync: vi.fn(),
	mkdirSync: vi.fn(),
	mkdtempSync: vi.fn(),
	rmSync: vi.fn(),
	writeFileSync: vi.fn(),
}));

const environmentKeys = [
	"PATH",
	"WAYLAND_DISPLAY",
	"XDG_SESSION_TYPE",
	"DISPLAY",
	"SSH_CONNECTION",
	"SSH_CLIENT",
	"MOSH_CONNECTION",
	"PI_CLIPBOARD_OSC52",
];
const originalEnvironment = environmentKeys.map(
	(key) => [key, process.env[key]] as const,
);

afterEach(() => {
	vi.unstubAllGlobals();
	vi.resetAllMocks();
	for (const [key, value] of originalEnvironment) {
		if (value === undefined) delete process.env[key];
		else process.env[key] = value;
	}
});

function fixture(platform = "linux") {
	vi.stubGlobal("process", { ...process, platform });
	vi.mocked(mkdtempSync).mockReturnValue(
		join(tmpdir(), "pi-clipboard-fixture-unit"),
	);
	const handlers = new Map<string, (event?: { toolName: string }) => unknown>();
	clipboardFixture({
		on: (name: string, handler: (event?: { toolName: string }) => unknown) =>
			handlers.set(name, handler),
		registerCommand: vi.fn(),
	} as unknown as ExtensionAPI);
	return {
		start: () => handlers.get("session_start")?.(),
		stop: () => handlers.get("session_shutdown")?.(),
		call: (toolName = "clipboard") => handlers.get("tool_call")?.({ toolName }),
	};
}

describe("isolated clipboard fixture", () => {
	it("blocks clipboard calls until setup succeeds and after shutdown", () => {
		const session = fixture();
		expect(session.call()).toMatchObject({ block: true });
		expect(session.call("codemode")).toBeUndefined();
		session.start();
		expect(session.call()).toBeUndefined();
		expect(process.env["DISPLAY"]).toBe("");
		expect(process.env["PI_CLIPBOARD_OSC52"]).toBe("0");
		const path = process.env["PATH"];
		session.start();
		expect(process.env["PATH"]).toBe(path);
		session.stop();
		expect(session.call()).toMatchObject({ block: true });
	});

	it("blocks unsupported platforms without initializing a backend", () => {
		const session = fixture("darwin");
		session.start();
		expect(session.call()).toMatchObject({ block: true });
		expect(mkdtempSync).not.toHaveBeenCalled();
	});

	it("remains blocked when temporary fixture setup fails", () => {
		const session = fixture();
		vi.mocked(mkdtempSync).mockImplementationOnce(() => {
			throw new Error("Fixture setup failed");
		});
		expect(session.start).toThrow("Fixture setup failed");
		expect(session.call()).toMatchObject({ block: true });
	});
});