Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/lsp/__tests__/navigation.test.ts

Raw
import { chmod, mkdir, readFile, rm, 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";
import type { Query } from "../src/tool.ts";

let pi: PiSession | undefined;
afterEach(async () => {
	await pi?.dispose();
	pi = undefined;
	vi.restoreAllMocks();
});
async function installPeer(bin: string, script: string) {
	await mkdir(bin, { recursive: true });
	if (process.platform === "win32") {
		const packageDir = join(bin, "node_modules/typescript-language-server");
		await mkdir(packageDir, { recursive: true });
		await writeFile(
			join(packageDir, "package.json"),
			JSON.stringify({ name: "typescript-language-server", bin: "peer.mjs" }),
		);
		await writeFile(join(packageDir, "peer.mjs"), script);
		await writeFile(
			join(bin, "typescript-language-server.cmd"),
			"@echo off\r\n",
		);
	} else {
		const executable = join(bin, "typescript-language-server");
		await writeFile(executable, `#!${process.execPath}\n${script}`);
		await chmod(executable, 0o755);
	}
}

async function setup(mode: string) {
	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, mode, ".ts");
	const bin = join(pi.cwd, "bin");
	await installPeer(bin, await readFile(config.args[0] as string, "utf8"));
	process.env["PATH"] = bin;
	await writeFile(join(pi.cwd, "tsconfig.json"), "{}\n");
	await writeFile(join(pi.cwd, "main.ts"), "// fixture\nvar Value = 1\n");
	await writeFile(join(pi.cwd, "other.ts"), "// fixture\nvar Other = 1\n");
	return {
		root: pi.cwd,
		run: (input: Query) =>
			nativeQuery(pi as PiSession, { timeout_ms: 3000, ...input }),
	};
}
const calls: Query = {
	operation: "incoming_calls",
	file: "main.ts",
	line: 2,
	column: 5,
};
it("native ambiguous calls preserve opaque metadata; reject changed source, root, executable, expired and replaced session tokens", async () => {
	const { run, root } = await setup("ambiguous");
	const prepared = await run(calls);
	expect(prepared.status).toBe("ambiguous");
	const candidates = prepared.items as { selection: string; name: string }[];
	expect(candidates.map((c) => c.name)).toEqual(["Value", "Other"]);
	const selection = candidates[1]?.selection;
	if (!selection) throw new Error("Missing selection");
	const selected = await run({ ...calls, selection });
	expect(selected.status).toBe("ok");
	const outgoing = await run({
		...calls,
		operation: "outgoing_calls",
		selection,
	});
	expect(outgoing.status).toBe("ok");
	expect(outgoing.items).toEqual([
		expect.objectContaining({
			callSites: [expect.objectContaining({ file: join(root, "main.ts") })],
		}),
	]);
	expect((await run({ ...calls, column: 6, selection })).status).toBe(
		"stale_selection",
	);
	const next = await run(calls);
	const token = (next.items[0] as { selection: string }).selection;
	await writeFile(join(root, "other.ts"), "// fixture\nvar Other = 2\n");
	expect((await run({ ...calls, selection: token })).status).toBe(
		"stale_selection",
	);
	const fresh = await run(calls);
	const expires = (fresh.items[0] as { selection: string }).selection;
	const now = Date.now();
	const clock = vi.spyOn(Date, "now").mockReturnValue(now + 300001);
	expect((await run({ ...calls, selection: expires })).status).toBe(
		"stale_selection",
	);
	clock.mockRestore();
	const reload = await run(calls);
	const old = (reload.items[0] as { selection: string }).selection;
	await pi?.session.reload();
	expect((await run({ ...calls, selection: old })).status).toBe(
		"stale_selection",
	);
});
it.each([
	"document_symbols",
	"workspace_symbols",
	"incoming_calls",
	"outgoing_calls",
] as const)(
	"native unsupported %s never substitutes text approximations",
	async (operation) => {
		const { run } = await setup("unsupported");
		expect(
			(
				await run({
					...calls,
					operation,
					query: "Value",
					server: "typescript-language-server",
				})
			).status,
		).toBe("unsupported");
	},
);
it.each(["document_symbols", "workspace_symbols", "incoming_calls"] as const)(
	"native malformed %s fails rather than fabricating absence",
	async (operation) => {
		const { run } = await setup("malformed");
		expect(
			(
				await run({
					...calls,
					operation,
					query: "Value",
					server: "typescript-language-server",
				})
			).status,
		).toBe("server_failure");
	},
);
it("native flat symbols and workspace resolution retain qualification, bounds and unknown completeness", async () => {
	const { run } = await setup("flat");
	const doc = await run({
		operation: "document_symbols",
		file: "main.ts",
		max_results: 1,
	});
	expect(doc.status).toBe("ok");
	expect(doc.items).toEqual([
		expect.objectContaining({ qualifiedName: "Fixture.Value" }),
	]);
	const work = await run({
		operation: "workspace_symbols",
		query: "Value",
		server: "typescript-language-server",
	});
	expect(work.status).toBe("ok");
	expect(work.serverCompleteness).toBe("unknown");
	expect(work.items).toEqual([
		expect.objectContaining({
			range: { start: { line: 2, column: 5 }, end: { line: 2, column: 10 } },
		}),
	]);
	expect(
		(await run({ operation: "workspace_symbols", query: "Value" })).status,
	).toBe("ambiguous");
	expect((await run({ operation: "document_symbols" })).status).toBe(
		"invalid_input",
	);
});
it.each(["prepare-empty", "calls-empty"])(
	"native %s keeps target absence distinct from successful empty relationships",
	async (mode) => {
		const { run } = await setup(mode);
		const result = await run(calls);
		expect(result.status).toBe(mode === "prepare-empty" ? "no_result" : "ok");
		expect(result.items).toEqual([]);
	},
);

it("cross-directory ambiguous candidates remain selectable without edits", async () => {
	const { run, root } = await setup("ambiguous-cross");
	await mkdir(join(root, "nested"));
	await writeFile(join(root, "nested/other.ts"), "// fixture\nvar Other = 1\n");
	const result = await run(calls);
	expect(result.status).toBe("ambiguous");
	const selection = (result.items[1] as { selection: string }).selection;
	expect((await run({ ...calls, selection })).status).toBe("ok");
	const outgoing = await run({
		...calls,
		operation: "outgoing_calls",
		selection,
	});
	expect(outgoing.status).toBe("ok");
	expect(outgoing.items).toEqual([
		expect.objectContaining({
			callSites: [
				expect.objectContaining({ file: join(root, "nested/other.ts") }),
			],
		}),
	]);
});
it.each(["root", "executable"] as const)(
	"rejects selection after %s identity changes",
	async (change) => {
		const { run, root } = await setup("ambiguous");
		const prepared = await run(calls);
		const selection = (prepared.items[0] as { selection: string }).selection;
		if (change === "root") {
			await mkdir(join(root, "nested"));
			await writeFile(join(root, "nested/tsconfig.json"), "{}\n");
			await writeFile(
				join(root, "nested/main.ts"),
				"// fixture\nvar Value = 1\n",
			);
			expect(
				(
					await run({
						...calls,
						file: "nested/main.ts",
						workspace: join(root, "nested"),
						selection,
					})
				).status,
			).toBe("stale_selection");
		} else {
			const bin = join(root, "alternate");
			const script = await readFile(join(root, "peer-ambiguous.mjs"), "utf8");
			await installPeer(bin, script);
			process.env["PATH"] = bin;
			expect((await run({ ...calls, selection })).status).toBe(
				"stale_selection",
			);
		}
	},
);

it.each([
	[".ts", "typescript-language-server"],
	[".cpp", "clangd"],
] as const)(
	"missing %s server names actual executable without fallback",
	async (suffix, server) => {
		const { run, root } = await setup("normal");
		process.env["PATH"] = "";
		await writeFile(join(root, "source" + suffix), "void source() {}\n");
		const result = await run({
			operation: "hover",
			file: "source" + suffix,
			line: 1,
			column: 1,
			workspace: root,
		});
		expect(result.status).toBe("missing_tool");
		expect(result.server).toBe(server);
		expect(result.message).toContain(server);
	},
);

it.each(["document_symbols", "incoming_calls", "outgoing_calls"] as const)(
	"native deadline rejects late %s success",
	async (operation) => {
		const { run } = await setup("delay");
		expect(
			(await run({ operation: "hover", file: "main.ts", line: 2, column: 5 }))
				.status,
		).toBe("ok");
		const result = await run({ ...calls, operation, timeout_ms: 100 });
		expect(result.status).toBe("timeout");
		expect(result.interruptedPartialResponse).toBe(true);
	},
);

it("deleted candidate sources visibly invalidate selections without killing reusable server", async () => {
	const { run, root } = await setup("ambiguous-cross");
	await mkdir(join(root, "nested"));
	await writeFile(join(root, "nested/other.ts"), "// fixture\nvar Other = 1\n");
	const prepared = await run(calls);
	const selection = (prepared.items[1] as { selection: string }).selection;
	await rm(join(root, "nested/other.ts"));
	expect((await run({ ...calls, selection })).status).toBe("stale_selection");
	expect(
		(await run({ operation: "hover", file: "main.ts", line: 2, column: 5 }))
			.status,
	).toBe("ok");
	expect(
		(await readFile(join(root, ".peer-processes.jsonl"), "utf8"))
			.trim()
			.split("\n"),
	).toHaveLength(1);
});