Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/clipboard/__tests__/contract.test.ts

Raw
import { chmod, mkdir, readdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { fauxAssistantMessage, fauxToolCall } from "@earendil-works/pi-ai";
import {
	convertToPng,
	copyToClipboard,
	createCodemodeExtension,
	initTheme,
} from "@earendil-works/pi-coding-agent";
import { getNativeClipboard } from "@earendil-works/pi-tui";
import { Value } from "typebox/value";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
	createPiSession,
	type PiSession,
} from "../../../test/fixture/create-pi-session.ts";
import type { ClipboardParams, ClipboardValue } from "../clipboard.ts";
import clipboardExtension from "../index.ts";

vi.mock("@earendil-works/pi-coding-agent", async (original) => {
	const sdk =
		await original<typeof import("@earendil-works/pi-coding-agent")>();
	return {
		...sdk,
		copyToClipboard: vi.fn(),
		convertToPng: vi.fn(sdk.convertToPng),
	};
});
vi.mock("@earendil-works/pi-tui", async (original) => ({
	...(await original<typeof import("@earendil-works/pi-tui")>()),
	getNativeClipboard: vi.fn(),
}));

const PNG = Buffer.from(
	"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aX1cAAAAASUVORK5CYII=",
	"base64",
);
const native = { getText: vi.fn(), getImage: vi.fn(), getFilePaths: vi.fn() };
let fixture: PiSession | undefined;

beforeEach(() => {
	vi.mocked(getNativeClipboard).mockReturnValue(native);
	native.getText.mockResolvedValue("private clipboard\r\n");
	native.getImage.mockResolvedValue(PNG);
	native.getFilePaths.mockResolvedValue(["/private/file.txt"]);
	vi.mocked(copyToClipboard).mockResolvedValue();
});
afterEach(async () => {
	await fixture?.dispose();
	fixture = undefined;
	vi.clearAllMocks();
});

async function start(
	pathLoaded = false,
	env: Record<string, string | undefined> = {},
) {
	initTheme("dark", false);
	fixture = await createPiSession({
		extensionPaths: pathLoaded
			? [fileURLToPath(new URL("../index.ts", import.meta.url))]
			: [],
		extensionFactories: [
			...(pathLoaded ? [] : [clipboardExtension]),
			createCodemodeExtension(),
		],
		userSettings: { defaultTools: ["+codemode"] },
		env: {
			WAYLAND_DISPLAY: undefined,
			XDG_SESSION_TYPE: undefined,
			DISPLAY: undefined,
			PI_CLIPBOARD_DEBUG: "0",
			...env,
		},
	});
	const tool = fixture.extensions
		.flatMap((extension) => [...extension.tools.values()])
		.find((entry) => entry.definition.name === "clipboard")?.definition;
	if (!tool) throw new Error("Clipboard tool missing");
	const invoke = async (
		params: ClipboardParams,
		mode: "tui" | "print" | "rpc" = "print",
		signal?: AbortSignal,
	) =>
		tool.execute("clipboard-test", params, signal, undefined, {
			...fixture!.session.extensionRunner.createToolContext(
				"clipboard-test",
				signal,
			),
			mode,
		});
	return { tool, invoke };
}

function value(
	result: Awaited<ReturnType<Awaited<ReturnType<typeof start>>["invoke"]>>,
): ClipboardValue {
	return result.structuredContent as ClipboardValue;
}

describe("clipboard public contract", () => {
	it("loads through real Pi, supports direct and programmatic calls, and never accesses clipboard at startup", async () => {
		const { tool } = await start(true);
		expect(fixture!.errors).toEqual([]);
		expect(tool.exposure).toBe("direct");
		expect(fixture!.session.getActiveToolNames()).toContain("clipboard");
		expect(fixture!.session.getCallableToolNames()).toContain("clipboard");
		expect(getNativeClipboard).not.toHaveBeenCalled();
		expect(copyToClipboard).not.toHaveBeenCalled();
		expect(tool.annotations).toMatchObject({
			readOnlyHint: false,
			destructiveHint: true,
		});
	});

	it("uses strict action-dependent input schemas", async () => {
		const { tool } = await start();
		for (const params of [
			{ action: "read" },
			{ action: "read", format: "image" },
			{ action: "copy", text: "" },
		])
			expect(Value.Check(tool.parameters, params)).toBe(true);
		for (const params of [
			{ action: "copy" },
			{ action: "read", text: "unexpected" },
			{ action: "copy", text: "x", format: "text" },
			{ action: "read", format: "html" },
			{ action: "watch" },
		])
			expect(Value.Check(tool.parameters, params)).toBe(false);
	});

	it.each(["", "Unicode 界😀\t\r\n\n"])(
		"preserves text and validates structured output: %j",
		async (text) => {
			native.getText.mockResolvedValue(text);
			const { tool, invoke } = await start();
			const result = await invoke({ action: "read" });
			expect(value(result)).toEqual({
				action: "read",
				format: "text",
				text,
				bytes: Buffer.byteLength(text),
			});
			expect(Value.Check(tool.outputSchema!, result.structuredContent)).toBe(
				true,
			);
		},
	);

	it("distinguishes absent content, unavailable backend, and sanitized transfer failures", async () => {
		const { invoke } = await start();
		native.getText.mockResolvedValueOnce(null);
		expect(value(await invoke({ action: "read" }))).toMatchObject({
			text: null,
			bytes: 0,
		});
		native.getText.mockResolvedValueOnce(undefined);
		await expect(invoke({ action: "read" })).rejects.toThrow("unavailable");
		native.getText.mockRejectedValueOnce(new Error("PRIVATE_RAW_ERROR"));
		await expect(invoke({ action: "read" })).rejects.not.toThrow(
			"PRIVATE_RAW_ERROR",
		);
		vi.mocked(getNativeClipboard).mockReturnValueOnce(undefined);
		await expect(invoke({ action: "read" })).rejects.toThrow(
			"OSC 52 copy does not provide clipboard reading",
		);
	});

	it("copies exact text through Pi without returning copied contents", async () => {
		const { tool, invoke } = await start();
		const text = "exact 😀\r\n";
		const result = await invoke({ action: "copy", text }, "tui");
		expect(copyToClipboard).toHaveBeenCalledExactlyOnceWith(text);
		expect(value(result)).toEqual({
			action: "copy",
			bytes: Buffer.byteLength(text),
		});
		expect(JSON.stringify(result)).not.toContain(text);
		expect(Value.Check(tool.outputSchema!, result.structuredContent)).toBe(
			true,
		);
		await invoke({ action: "copy", text: "" }, "tui");
		expect(copyToClipboard).toHaveBeenLastCalledWith("");
	});

	it.each(["print", "rpc"] as const)(
		"blocks %s copying before SDK terminal output",
		async (mode) => {
			const { invoke } = await start();
			await expect(
				invoke({ action: "copy", text: "secret" }, mode),
			).rejects.toThrow("interactive TUI");
			expect(copyToClipboard).not.toHaveBeenCalled();
		},
	);

	it("enforces byte and escaped-output limits without partial results or clipboard writes", async () => {
		const { invoke } = await start();
		native.getText.mockResolvedValueOnce("é".repeat(16385));
		await expect(invoke({ action: "read" })).rejects.toThrow("read limit");
		native.getText.mockResolvedValueOnce("\0".repeat(10000));
		await expect(invoke({ action: "read" })).rejects.toThrow("read limit");
		await expect(
			invoke({ action: "copy", text: "é".repeat(32769) }, "tui"),
		).rejects.toThrow("clipboard unchanged");
		expect(copyToClipboard).not.toHaveBeenCalled();
	});

	it("returns PNG blocks for codemode image() without base64 in text content", async () => {
		const { tool, invoke } = await start();
		const result = await invoke({ action: "read", format: "image" });
		expect(value(result)).toEqual({
			action: "read",
			format: "image",
			image: {
				type: "image",
				mimeType: "image/png",
				data: PNG.toString("base64"),
			},
			bytes: PNG.length,
		});
		expect(
			JSON.stringify(result.content.filter((part) => part.type === "text")),
		).not.toContain(PNG.toString("base64"));
		expect(result.content).toContainEqual({
			type: "image",
			mimeType: "image/png",
			data: PNG.toString("base64"),
		});
		expect(Value.Check(tool.outputSchema!, result.structuredContent)).toBe(
			true,
		);
		native.getImage.mockResolvedValueOnce(null);
		expect(
			value(await invoke({ action: "read", format: "image" })),
		).toMatchObject({ image: null });
		native.getImage.mockResolvedValueOnce(Buffer.alloc(4 * 1024 * 1024 + 1));
		await expect(invoke({ action: "read", format: "image" })).rejects.toThrow(
			"4 MiB",
		);
	});

	it("rejects malformed PNGs instead of laundering them through passthrough", async () => {
		const { invoke } = await start();
		native.getImage.mockResolvedValueOnce(PNG.subarray(0, 24));
		await expect(invoke({ action: "read", format: "image" })).rejects.toThrow(
			"malformed",
		);
		native.getImage.mockResolvedValueOnce(PNG.subarray(0, PNG.length - 12));
		await expect(invoke({ action: "read", format: "image" })).rejects.toThrow(
			"malformed",
		);
		expect(convertToPng).not.toHaveBeenCalled();
	});

	it("rejects PNG decode bombs declared in IHDR before any conversion", async () => {
		const { invoke } = await start();
		const dimensions = Buffer.alloc(8);
		dimensions.writeUInt32BE(65535, 0);
		dimensions.writeUInt32BE(65535, 4);
		const bomb = Buffer.concat([
			PNG.subarray(0, 8),
			Buffer.from([0, 0, 0, 13]),
			Buffer.from("IHDR", "latin1"),
			dimensions,
			Buffer.alloc(4),
			Buffer.from([
				0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
			]),
		]);
		native.getImage.mockResolvedValueOnce(bomb);
		await expect(invoke({ action: "read", format: "image" })).rejects.toThrow(
			"pixel limit",
		);
		expect(convertToPng).not.toHaveBeenCalled();
	});

	it("reports image conversion failure without exposing backend data", async () => {
		const { invoke } = await start();
		native.getImage.mockResolvedValueOnce(Buffer.from("not-png"));
		vi.mocked(convertToPng).mockResolvedValueOnce(null);
		await expect(invoke({ action: "read", format: "image" })).rejects.toThrow(
			"convert",
		);
		expect(convertToPng).toHaveBeenLastCalledWith(
			Buffer.from("not-png").toString("base64"),
			"application/octet-stream",
		);
	});

	it("returns file references without opening files, and rejects unsupported backends", async () => {
		const { tool, invoke } = await start();
		const result = await invoke({ action: "read", format: "files" });
		expect(value(result)).toMatchObject({ files: ["/private/file.txt"] });
		expect(Value.Check(tool.outputSchema!, result.structuredContent)).toBe(
			true,
		);
		native.getFilePaths.mockResolvedValueOnce(
			Array.from({ length: 129 }, () => "/x"),
		);
		await expect(invoke({ action: "read", format: "files" })).rejects.toThrow(
			"limit",
		);
		vi.mocked(getNativeClipboard).mockReturnValueOnce({
			getText: native.getText,
			getImage: native.getImage,
		});
		await expect(invoke({ action: "read", format: "files" })).rejects.toThrow(
			"currently supported on macOS",
		);
	});

	it("honors cancellation before dispatch and after native reads", async () => {
		const { invoke } = await start();
		const controller = new AbortController();
		controller.abort(new Error("PRIVATE_ABORT"));
		await expect(
			invoke({ action: "copy", text: "never" }, "tui", controller.signal),
		).rejects.toThrow("cancelled");
		expect(copyToClipboard).not.toHaveBeenCalled();
		const pending = new AbortController();
		native.getText.mockImplementationOnce(async () => {
			pending.abort();
			return "discard";
		});
		await expect(
			invoke({ action: "read" }, "print", pending.signal),
		).rejects.toThrow("cancelled");
	});

	it("bounds hung native backend reads with a deadline", async () => {
		const { invoke } = await start();
		native.getText.mockImplementationOnce(() => new Promise(() => {}));
		await expect(invoke({ action: "read" })).rejects.toThrow("timed out");
	});

	it("cancels a hung native read promptly on abort", async () => {
		const { invoke } = await start();
		let started = () => {};
		const reading = new Promise<void>((resolve) => {
			started = resolve;
		});
		native.getText.mockImplementationOnce(() => {
			started();
			return new Promise(() => {});
		});
		const controller = new AbortController();
		const pending = invoke({ action: "read" }, "print", controller.signal);
		await reading;
		controller.abort();
		await expect(pending).rejects.toThrow("cancelled");
	});

	it("hides contents in compact rows, reveals expanded text, and tolerates missing details", async () => {
		const { tool, invoke } = await start();
		const result = await invoke({ action: "read" });
		const theme = fixture!.session.extensionRunner.createContext().ui.theme;
		const context = { isError: false, showImages: false } as Parameters<
			NonNullable<typeof tool.renderResult>
		>[3];
		const render = (expanded: boolean) =>
			tool.renderResult!(result, { expanded, isPartial: false }, theme, context)
				.render(100)
				.join("\n");
		expect(render(false)).not.toContain("private clipboard");
		expect(render(false)).toContain("to expand");
		expect(render(true)).toContain("private clipboard");
		expect(() =>
			tool.renderResult!(
				{ content: [], details: undefined },
				{ expanded: false, isPartial: false },
				theme,
				context,
			).render(20),
		).not.toThrow();
	});

	it.each(["text", "image"] as const)(
		"executes direct %s reads through real Pi without codemode",
		async (format) => {
			initTheme("dark", false);
			fixture = await createPiSession({
				extensionFactories: [clipboardExtension],
				// Same isolation as start(): never reach the host's real clipboard tools.
				env: {
					WAYLAND_DISPLAY: undefined,
					XDG_SESSION_TYPE: undefined,
					DISPLAY: undefined,
					PI_CLIPBOARD_DEBUG: "0",
				},
			});
			expect(fixture.session.getActiveToolNames()).toContain("clipboard");
			expect(fixture.session.getCallableToolNames()).not.toContain("codemode");
			fixture.setResponses([
				fauxAssistantMessage(
					fauxToolCall("clipboard", { action: "read", format }),
					{ stopReason: "toolUse" },
				),
				fauxAssistantMessage("done"),
			]);
			await fixture.session.prompt("Read the synthetic clipboard fixture.");
			const result = fixture.session.messages.find(
				(message) =>
					message.role === "toolResult" && message.toolName === "clipboard",
			);
			if (result?.role !== "toolResult")
				throw new Error("Missing direct clipboard result");
			expect(result.isError).toBe(false);
			if (format === "image")
				expect(result.content).toContainEqual({
					type: "image",
					mimeType: "image/png",
					data: PNG.toString("base64"),
				});
			else
				expect(JSON.stringify(result.content)).toContain("private clipboard");
			expect(fixture.errors).toEqual([]);
		},
	);

	it("returns typed clipboard data and image output through real codemode", async () => {
		await start();
		fixture!.setResponses([
			fauxAssistantMessage(
				fauxToolCall("codemode", {
					code: 'const textResult = await tools.clipboard({action:"read"}); text(textResult.text); const picture = await tools.clipboard({action:"read",format:"image"}); if(picture.image) image(picture.image);',
				}),
				{ stopReason: "toolUse" },
			),
			fauxAssistantMessage("done"),
		]);
		await fixture!.session.prompt("Read the synthetic clipboard fixture.");
		const result = fixture!.session.messages.find(
			(message) =>
				message.role === "toolResult" && message.toolName === "codemode",
		);
		expect(result?.role).toBe("toolResult");
		if (result?.role !== "toolResult")
			throw new Error("Missing codemode result");
		expect(result.isError).toBe(false);
		expect(result.content.some((part) => part.type === "image")).toBe(true);
		expect(JSON.stringify(result.content)).toContain("private clipboard");
		expect(fixture!.errors).toEqual([]);
	});

	it("writes only safe lifecycle diagnostics in the isolated test state directory", async () => {
		// Debug selection happens at import time, after the fixture applies env.
		await start(true, { PI_CLIPBOARD_DEBUG: "1" });
		await fixture!.session.extensionRunner.emit({
			type: "session_shutdown",
			reason: "quit",
		});
		const directory = join(
			fixture!.env["XDG_STATE_HOME"]!,
			"pi-ext",
			"debug",
			"clipboard",
		);
		const records = await vi.waitFor(async () => {
			const text = (
				await Promise.all(
					(
						await readdir(directory)
					).map((name) => readFile(join(directory, name), "utf8")),
				)
			).join("\n");
			expect(text).toContain("session.start");
			expect(text).toContain("session.shutdown");
			return text;
		});
		expect(records).not.toContain("private clipboard");
	});
});

// Exercise the real process boundary without touching the OS clipboard.
describe.runIf(process.platform === "linux")(
	"Wayland clipboard command contract",
	() => {
		async function command(body: string) {
			await start(false, {
				WAYLAND_DISPLAY: "fake-wayland",
				DISPLAY: ":stale-x11",
			});
			const bin = join(fixture!.cwd, "bin");
			await mkdir(bin);
			const path = join(bin, "wl-paste");
			await writeFile(path, `#!${process.execPath}\n${body}\n`);
			await chmod(path, 0o755);
			process.env["PATH"] = bin;
			const tool = fixture!.extensions[0]!.tools.get("clipboard")!.definition;
			return (signal?: AbortSignal, format: "text" | "image" = "text") =>
				tool.execute(
					"wayland",
					{ action: "read", format },
					signal,
					undefined,
					fixture!.session.extensionRunner.createToolContext("wayland", signal),
				);
		}
		it("preserves bytes and prefers UTF-8 offers without stale X11 fallback", async () => {
			const call = await command(
				'if(process.argv.includes("--list-types")) process.stdout.write("text/plain;charset=iso-8859-1\\ntext/plain;charset=utf-8\\n"); else { if(!process.argv.includes("text/plain;charset=utf-8")) process.exit(2); process.stdout.write("wayland 界\\r\\n"); }',
			);
			expect(value(await call())).toMatchObject({ text: "wayland 界\r\n" });
			expect(getNativeClipboard).not.toHaveBeenCalled();
		});
		it("recognizes an empty selection, not arbitrary command failures", async () => {
			const call = await command(
				'process.stderr.write("Nothing is copied\\n"); process.exit(1);',
			);
			expect(value(await call())).toMatchObject({ text: null });
			expect(getNativeClipboard).not.toHaveBeenCalled();
		});
		it("reports genuine backend failure without leaking stderr or reading X11", async () => {
			const call = await command(
				'process.stderr.write("PRIVATE_BACKEND_FAILURE"); process.exit(1);',
			);
			await expect(call()).rejects.toThrow("Wayland clipboard read failed");
			expect(getNativeClipboard).not.toHaveBeenCalled();
		});
		it("does not read images as text or touch stale X11", async () => {
			const call = await command(
				'if(process.argv.includes("--list-types")) process.stdout.write("image/png\\n"); else process.exit(2);',
			);
			expect(value(await call())).toMatchObject({ text: null });
			expect(getNativeClipboard).not.toHaveBeenCalled();
		});
		it("normalizes offered image MIME types and returns a PNG block", async () => {
			const call = await command(
				`if(process.argv.includes("--list-types")) process.stdout.write("IMAGE/PNG;source=test\\n"); else process.stdout.write(Buffer.from(${JSON.stringify(PNG.toString("base64"))}, "base64"));`,
			);
			expect(value(await call(undefined, "image"))).toMatchObject({
				image: {
					type: "image",
					mimeType: "image/png",
					data: PNG.toString("base64"),
				},
			});
			expect(getNativeClipboard).not.toHaveBeenCalled();
		});
		it("rejects unsupported text encodings instead of replacing characters", async () => {
			const call = await command(
				'process.stdout.write("text/plain;charset=iso-8859-1\\n");',
			);
			await expect(call()).rejects.toThrow("unsupported encoding");
		});
		it("rejects oversized process output without returning partial text", async () => {
			const call = await command(
				'if(process.argv.includes("--list-types")) process.stdout.write("text/plain\\n"); else process.stdout.write("x".repeat(32769));',
			);
			await expect(call()).rejects.toThrow("read limit");
		});
		it("cancels a pending clipboard command", async () => {
			const call = await command("setTimeout(() => {}, 10000);");
			const controller = new AbortController();
			const pending = call(controller.signal);
			setTimeout(() => controller.abort(), 30);
			await expect(pending).rejects.toThrow("cancelled");
		});
	},
);