Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/lsp/__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 { afterEach, expect, it, vi } from "vitest";
import {
	createPiSession,
	type PiSession,
} from "../../../test/fixture/create-pi-session.ts";
import { nativeQuery } from "../__serial__/native.ts";
import { peer } from "../__serial__/peer.ts";

let pi: PiSession | undefined;

it.each([
	{
		trusted: false,
		user: 30000,
		project: "invalid",
		env: undefined,
		status: "missing_tool",
	},
	{
		trusted: true,
		user: 30000,
		project: "invalid",
		env: undefined,
		status: "invalid_config",
	},
	{
		trusted: true,
		user: "invalid",
		project: 30000,
		env: undefined,
		status: "missing_tool",
	},
	{
		trusted: false,
		user: "invalid",
		project: 30000,
		env: undefined,
		status: "invalid_config",
	},
	{
		trusted: false,
		user: "invalid",
		project: "invalid",
		env: "30000",
		status: "missing_tool",
	},
	{
		trusted: true,
		user: 30000,
		project: 30000,
		env: "",
		status: "invalid_config",
	},
])(
	"resolves timeout sources without invalid-value fallback: %j",
	async ({ trusted, user, project, env, status }) => {
		pi = await createPiSession({
			extensionPaths: [fileURLToPath(new URL("../index.ts", import.meta.url))],
			projectTrusted: trusted,
			userSettings: { lsp: { timeoutMs: user } },
			env: { PI_LSP_DEBUG: "0", PATH: "", PI_LSP_TIMEOUT_MS: env },
		});
		await mkdir(join(pi.cwd, ".pi"), { recursive: true });
		await writeFile(
			join(pi.cwd, ".pi/settings.json"),
			JSON.stringify({ lsp: { timeoutMs: project } }),
		);
		await writeFile(join(pi.cwd, "go.mod"), "module fixture\n");
		await writeFile(join(pi.cwd, "main.go"), "package fixture\n");
		const result = await nativeQuery(pi, {
			operation: "hover",
			file: "main.go",
			line: 1,
			column: 1,
		});
		expect(result.status).toBe(status);
	},
);

it("records only declared lifecycle/query metadata inside fixture debug sandbox", async () => {
	pi = await createPiSession({
		extensionPaths: [fileURLToPath(new URL("../index.ts", import.meta.url))],
		env: { PI_LSP_DEBUG: "1", PATH: "" },
	});
	await pi.session.extensionRunner.emit({
		type: "session_start",
		reason: "startup",
	});
	await writeFile(join(pi.cwd, "go.mod"), "module fixture\n");
	await writeFile(
		join(pi.cwd, "main.go"),
		"package fixture\n// PRIVATE_SOURCE_SENTINEL\n",
	);
	const outcome = await nativeQuery(pi, {
		operation: "hover",
		file: "main.go",
		line: 1,
		column: 1,
	});
	expect(outcome.status).toBe("missing_tool");
	await pi.session.extensionRunner.emit({
		type: "session_shutdown",
		reason: "quit",
	});
	const directory = join(pi.cwd, ".test-state/pi-ext/debug/lsp");
	const records = (
		await Promise.all(
			(
				await readdir(directory)
			).map((name) => readFile(join(directory, name), "utf8")),
		)
	)
		.join("\n")
		.trim()
		.split("\n")
		.filter(Boolean)
		.map((line) => JSON.parse(line));
	expect(records.map((record) => record.event)).toEqual(
		expect.arrayContaining(["session.start", "session.shutdown"]),
	);
	expect(records).toContainEqual(
		expect.objectContaining({ event: "query.finish", ok: false }),
	);
	for (const record of records) {
		expect(["session.start", "session.shutdown", "query.finish"]).toContain(
			record.event,
		);
		expect(Object.keys(record).sort()).toEqual(
			(record.event === "query.finish"
				? ["timestamp", "extension", "pid", "event", "ok"]
				: ["timestamp", "extension", "pid", "event"]
			).sort(),
		);
	}
	expect(JSON.stringify(records)).not.toContain(pi.cwd);
	expect(JSON.stringify(records)).not.toContain("PRIVATE_SOURCE_SENTINEL");
});

it.runIf(process.platform !== "win32")(
	"native Pi tool returns timeout/cancelled envelopes and reaps owned peers",
	async () => {
		pi = await createPiSession({
			extensionPaths: [fileURLToPath(new URL("../index.ts", import.meta.url))],
			env: { PI_LSP_DEBUG: "0", PI_LSP_TIMEOUT_MS: undefined },
		});
		const config = await peer(pi.cwd, "delay");
		const script = config.args[0];
		if (!script) throw new Error("peer script missing");
		const bin = join(pi.cwd, "bin");
		await mkdir(bin);
		await writeFile(
			join(bin, "gopls"),
			`#!${process.execPath}\n${await readFile(script, "utf8")}`,
		);
		await chmod(join(bin, "gopls"), 0o755);
		process.env["PATH"] = bin;
		await writeFile(join(pi.cwd, "go.mod"), "module fixture\n");
		await writeFile(
			join(pi.cwd, "main.go"),
			"package fixture\nvar Value = 1\n",
		);
		const warm = await nativeQuery(pi, {
			operation: "hover",
			file: "main.go",
			line: 2,
			column: 5,
			timeout_ms: 3000,
		});
		expect(warm.status).toBe("ok");
		const state = JSON.parse(warm.hover ?? "{}");
		for (const operation of ["type_definition", "implementations"] as const) {
			const added = await nativeQuery(pi, {
				operation,
				file: "main.go",
				line: 2,
				column: 5,
				timeout_ms: 3000,
			});
			expect(added.status).toBe("ok");
			expect(added.items).toEqual([
				{
					file: join(pi.cwd, "main.go"),
					range: { start: { line: 2, column: 5 }, end: { line: 2, column: 5 } },
					snippet: "var Value = 1",
				},
			]);
		}
		await writeFile(
			join(pi.cwd, "other.go"),
			"package fixture\nvar Other = 1\n",
		);
		for (const operation of ["incoming_calls", "outgoing_calls"] as const) {
			const calls = await nativeQuery(pi, {
				operation,
				file: "main.go",
				line: 2,
				column: 5,
			});
			expect(calls.status).toBe("ok");
			expect(calls.items).toEqual([
				expect.objectContaining({
					file: join(pi.cwd, "other.go"),
					callSites: [
						expect.objectContaining({
							file: join(
								pi.cwd,
								operation === "incoming_calls" ? "other.go" : "main.go",
							),
						}),
					],
				}),
			]);
		}
		const document = await nativeQuery(pi, {
			operation: "document_symbols",
			file: "main.go",
		});
		expect(document.status).toBe("ok");
		expect(document.items).toEqual(
			expect.arrayContaining([
				expect.objectContaining({ qualifiedName: "Fixture.Value" }),
			]),
		);
		const workspace = await nativeQuery(pi, {
			operation: "workspace_symbols",
			server: "gopls",
			query: "Value",
		});
		expect(workspace.status).toBe("ok");
		expect(workspace.items).toEqual([
			expect.objectContaining({
				name: "Value",
				file: join(pi.cwd, "main.go"),
				range: { start: { line: 2, column: 5 }, end: { line: 2, column: 10 } },
			}),
		]);
		const tool = pi.extensions[0]?.tools.get("lsp")?.definition;
		if (!tool) throw new Error("tool missing");
		const ctx = pi.session.extensionRunner.createToolContext(
			"parallel",
			undefined,
		);
		const query = {
			operation: "definition",
			file: "main.go",
			line: 2,
			column: 5,
			timeout_ms: 3000,
		};
		const parallel = await Promise.all([
			tool.execute(
				"parallel-a",
				query,
				new AbortController().signal,
				undefined,
				ctx,
			),
			tool.execute(
				"parallel-b",
				query,
				new AbortController().signal,
				undefined,
				ctx,
			),
		]);
		expect(
			parallel
				.map((result) => (result.details as { status: string }).status)
				.sort(),
		).toEqual(["ok", "resource_limit"]);
		const expired = await nativeQuery(pi, {
			operation: "definition",
			file: "main.go",
			line: 2,
			column: 5,
			timeout_ms: 100,
		});
		expect(expired).toMatchObject({
			status: "timeout",
			interruptedPartialResponse: true,
			sourceRevision: "not_server_revision_verified",
			serverCompleteness: "unknown",
		});
		await vi.waitFor(() => expect(() => process.kill(state.pid, 0)).toThrow(), {
			timeout: 2000,
		});
		const audit = async () =>
			(await readFile(join(ctx.cwd, ".peer-processes.jsonl"), "utf8"))
				.trim()
				.split("\n")
				.map((line) => JSON.parse(line) as { pid: number; mode: string });
		expect(await audit()).toHaveLength(1);
		// Both calls now await the same dead owner's close before replacement acquisition.
		const replacing = await Promise.all([
			tool.execute(
				"replace-a",
				query,
				new AbortController().signal,
				undefined,
				ctx,
			),
			tool.execute(
				"replace-b",
				query,
				new AbortController().signal,
				undefined,
				ctx,
			),
		]);
		expect(
			replacing
				.map((result) => (result.details as { status: string }).status)
				.sort(),
		).toEqual(["ok", "resource_limit"]);
		const replacements = await audit();
		expect(replacements).toHaveLength(2);
		const replacement = replacements[1];
		if (!replacement) throw new Error("replacement peer missing");
		expect(replacement.pid).not.toBe(state.pid);
		expect(() => process.kill(replacement.pid, 0)).not.toThrow();
		const otherConfig = await peer(pi.cwd, "normal");
		const otherScript = otherConfig.args[0];
		if (!otherScript) throw new Error("second executable missing");
		const otherBin = join(pi.cwd, "other-bin");
		await mkdir(otherBin);
		await writeFile(
			join(otherBin, "gopls"),
			`#!${process.execPath}\n${await readFile(otherScript, "utf8")}`,
		);
		await chmod(join(otherBin, "gopls"), 0o755);
		process.env["PATH"] = otherBin;
		const switched = await nativeQuery(pi, {
			operation: "hover",
			file: "main.go",
			line: 2,
			column: 5,
			timeout_ms: 3000,
		});
		expect(switched.status).toBe("ok");
		const switchedState = JSON.parse(switched.hover ?? "{}");
		expect(switchedState.mode).toBe("normal");
		expect(switchedState.pid).not.toBe(replacement.pid);
		expect(await audit()).toHaveLength(3);
		const controller = new AbortController();
		controller.abort();
		const cancelled = await tool.execute(
			"cancel",
			{ operation: "definition", file: "main.go", line: 2, column: 5 },
			controller.signal,
			undefined,
			pi.session.extensionRunner.createToolContext("cancel", controller.signal),
		);
		expect(cancelled.details).toMatchObject({
			status: "cancelled",
			interruptedPartialResponse: true,
		});
		await pi.session.extensionRunner.emit({
			type: "session_shutdown",
			reason: "reload",
		});
		for (const record of await audit())
			expect(() => process.kill(record.pid, 0)).toThrow();
	},
);
afterEach(async () => {
	await pi?.dispose();
	pi = undefined;
});

it("loads in real Pi without starting gopls; missing executable fails explicitly through native tool", async () => {
	pi = await createPiSession({
		extensionPaths: [fileURLToPath(new URL("../index.ts", import.meta.url))],
		env: { PI_LSP_DEBUG: "0", PATH: "" },
	});
	expect(pi.errors).toEqual([]);
	const tool = pi.extensions[0]?.tools.get("lsp")?.definition;
	expect(tool).toBeDefined();
	if (!tool) throw new Error("lsp missing");
	await writeFile(
		join(pi.cwd, "go.mod"),
		"module example.test/fixture\n\ngo 1.24\n",
	);
	await writeFile(join(pi.cwd, "main.go"), "package fixture\nvar Value = 1\n");
	const ctx = pi.session.extensionRunner.createToolContext(
		"contract",
		undefined,
	);
	const result = await tool.execute(
		"missing",
		{ operation: "definition", file: "main.go", line: 2, column: 5 },
		new AbortController().signal,
		undefined,
		ctx,
	);
	expect(result.isError).toBe(true);
	expect(result.details).toMatchObject({ status: "missing_tool" });
});

it("ignores untrusted project settings, rejects invalid user configuration", async () => {
	pi = await createPiSession({
		extensionPaths: [fileURLToPath(new URL("../index.ts", import.meta.url))],
		projectTrusted: false,
		userSettings: { lsp: { timeoutMs: 30000 } },
		env: { PI_LSP_DEBUG: "0", PATH: "", PI_LSP_TIMEOUT_MS: undefined },
	});
	await mkdir(join(pi.cwd, ".pi"), { recursive: true });
	await writeFile(
		join(pi.cwd, ".pi/settings.json"),
		JSON.stringify({ lsp: { timeoutMs: "invalid" } }),
	);
	await writeFile(join(pi.cwd, "go.mod"), "module fixture\n");
	await writeFile(join(pi.cwd, "main.go"), "package fixture\n");
	const tool = pi.extensions[0]?.tools.get("lsp")?.definition;
	if (!tool) throw new Error("lsp missing");
	const ctx = pi.session.extensionRunner.createToolContext(
		"contract",
		undefined,
	);
	const run = () =>
		tool.execute(
			"config",
			{ operation: "hover", file: "main.go", line: 1, column: 1 },
			new AbortController().signal,
			undefined,
			ctx,
		);
	expect((await run()).details).toMatchObject({ status: "missing_tool" });
	process.env["PI_LSP_TIMEOUT_MS"] = "invalid";
	expect((await run()).details).toMatchObject({
		status: "invalid_config",
		server: "unselected",
	});
	const specific = await tool.execute(
		"config-ts",
		{
			operation: "hover",
			file: "file.ts",
			line: 1,
			column: 1,
			server: "typescript-language-server",
		},
		new AbortController().signal,
		undefined,
		ctx,
	);
	expect(specific.details).toMatchObject({
		status: "invalid_config",
		server: "typescript-language-server",
	});
});