repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by admin
extensions/lsp/__tests__/result.test.ts
Rawimport { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
import { afterEach, expect, it, vi } from "vitest";
import type { Client } from "../src/client.ts";
import { normalize } from "../src/result.ts";
import {
fromPosition,
LspFailure,
target,
toPosition,
within,
} from "../src/source.ts";
let temp: string | undefined;
afterEach(async () => {
if (temp) await rm(temp, { recursive: true, force: true });
});
async function fixture() {
temp = await mkdtemp(join(tmpdir(), "pi-lsp-result-"));
const file = join(temp, "unicode.go");
await writeFile(file, "😀Hello\r\n");
const client = {
root: temp,
encoding: "utf-16",
remember: vi.fn(async () => undefined),
} as unknown as Client;
const location = {
uri: pathToFileURL(file).href,
range: { start: { line: 0, character: 2 }, end: { line: 0, character: 7 } },
};
return { file, client, location };
}
it("bounds root discovery, reports nested ambiguity, permits ordinary dot-prefixed descendants", async () => {
temp = await mkdtemp(join(tmpdir(), "pi-lsp-roots-"));
const nested = join(temp, "..generated");
await mkdir(nested);
await writeFile(join(temp, "go.work"), "go 1.24\n");
await writeFile(join(nested, "go.mod"), "module fixture\n");
const file = join(nested, "main.go");
await writeFile(file, "package fixture\n");
expect(within(temp, file)).toBe(true);
expect(within(nested, join(temp, "outside.go"))).toBe(false);
await expect(target(temp, file)).rejects.toMatchObject({
status: "ambiguous",
});
await expect(target(temp, file, nested)).resolves.toEqual({
file,
root: nested,
});
await writeFile(join(temp, "outside.go"), "package outside\n");
await expect(target(nested, join(temp, "outside.go"))).rejects.toMatchObject({
status: "invalid_input",
});
});
it("converts scalar columns for all negotiated encodings", () => {
for (const [encoding, units] of [
["utf-16", 2],
["utf-8", 4],
["utf-32", 1],
] as const) {
expect(toPosition("😀Hello", 1, 2, encoding)).toEqual({
line: 0,
character: units,
});
expect(
fromPosition("😀Hello", { line: 0, character: units }, encoding),
).toEqual({ line: 1, column: 2 });
}
});
it("preserves empty lines, CRLF, bare carriage returns and Unicode boundaries", () => {
for (const [text, line, column] of [
["", 1, 1],
["first\n", 2, 1],
["first\r\n😀value\r\n", 2, 2],
["first\n\nlast", 3, 5],
["bare\rcarriage", 1, 6],
] as const) {
for (const encoding of ["utf-8", "utf-16", "utf-32"] as const) {
const position = toPosition(text, line, column, encoding);
expect(fromPosition(text, position, encoding)).toEqual({ line, column });
}
}
expect(toPosition("a\r\n😀b\r\n", 2, 3, "utf-16")).toEqual({
line: 1,
character: 3,
});
expect(
fromPosition("a\r\n😀b\r\n", { line: 1, character: 3 }, "utf-16"),
).toEqual({ line: 2, column: 3 });
expect(() => toPosition("a\r\n", 1, 3, "utf-16")).toThrow();
expect(() =>
fromPosition("a\r\n", { line: 0, character: 2 }, "utf-16"),
).toThrow();
expect(() => toPosition("first\n", 3, 1, "utf-16")).toThrow();
expect(() => toPosition("😀", 1, 3, "utf-16")).toThrow();
});
it("normalizes readable UTF-16 locations without claiming revision correspondence", async () => {
const { file, client, location } = await fixture();
const output = await normalize(
client,
"definition",
file,
location,
10,
2048,
new AbortController().signal,
);
expect(output.items).toEqual([
{
file,
range: { start: { line: 1, column: 2 }, end: { line: 1, column: 7 } },
snippet: "😀Hello",
},
]);
expect(output.sourceRevision).toBe("not_server_revision_verified");
expect(output.workspaceFreshness).toBe("unknown");
});
it("keeps repeated/mixed-file locations correct and observes edits on the next query", async () => {
const { file, client, location } = await fixture();
const other = join(client.root, "other.go");
await writeFile(other, "Other\n");
const second = {
uri: pathToFileURL(other).href,
range: { start: { line: 0, character: 0 }, end: { line: 0, character: 5 } },
};
const signal = new AbortController().signal;
const output = await normalize(
client,
"references",
file,
[location, location, second, location],
10,
8192,
signal,
);
expect(output.items).toEqual([
{
file,
range: { start: { line: 1, column: 2 }, end: { line: 1, column: 7 } },
snippet: "😀Hello",
},
{
file,
range: { start: { line: 1, column: 2 }, end: { line: 1, column: 7 } },
snippet: "😀Hello",
},
{
file: other,
range: { start: { line: 1, column: 1 }, end: { line: 1, column: 6 } },
snippet: "Other",
},
{
file,
range: { start: { line: 1, column: 2 }, end: { line: 1, column: 7 } },
snippet: "😀Hello",
},
]);
await writeFile(file, "😀Again\r\n");
const updated = await normalize(
client,
"references",
file,
[location, location],
10,
8192,
signal,
);
expect(updated.items).toEqual([
{
file,
range: { start: { line: 1, column: 2 }, end: { line: 1, column: 7 } },
snippet: "😀Again",
},
{
file,
range: { start: { line: 1, column: 2 }, end: { line: 1, column: 7 } },
snippet: "😀Again",
},
]);
});
it("rejects cancellation after a repeated readable hit, never returning partial success", async () => {
const { file, client, location } = await fixture();
const controller = new AbortController();
const reason = new LspFailure(
"cancelled",
"cancelled during repeated location",
);
let remembered = 0;
client.remember = vi.fn(async () => {
if (++remembered === 2) controller.abort(reason);
});
await expect(
normalize(
client,
"references",
file,
[location, location, location],
10,
8192,
controller.signal,
),
).rejects.toBe(reason);
expect(remembered).toBe(2);
});
it("rejects malformed scalar-boundary coordinates on readable source", async () => {
const { file, client, location } = await fixture();
location.range.start.character = 1;
await expect(
normalize(
client,
"definition",
file,
location,
10,
2048,
new AbortController().signal,
),
).rejects.toMatchObject({ status: "server_failure" });
});
it("cancellation during retrieval stops remaining result normalization", async () => {
const { file, client, location } = await fixture();
const controller = new AbortController();
const reason = new Error("cancel retrieval");
// The asynchronous stat/open path yields before result materialization.
const work = normalize(
client,
"references",
file,
Array.from({ length: 100 }, () => location),
100,
32768,
controller.signal,
);
queueMicrotask(() => controller.abort(reason));
await expect(work).rejects.toBe(reason);
expect(client.remember).not.toHaveBeenCalled();
});
it.each([
["references", 20],
["references", 19],
["workspace_symbols", 20],
["workspace_symbols", 19],
] as const)(
"preserves exact UTF-8 byte-boundary admission/order for %s (max_results=%i)",
async (operation, maxResults) => {
const { file, client, location } = await fixture();
const snippet = '😀Hello "世界" \\ end';
await writeFile(file, `${snippet}\r\n`);
const names = Array.from(
{ length: 20 },
(_, i) => `世界😀${"x".repeat(40)}${i}`,
);
const raw = names.map((name, i) =>
operation === "references"
? {
...location,
range: {
start: { line: 0, character: 2 + (i % 5) },
end: { line: 0, character: 3 + (i % 5) },
},
}
: {
name,
kind: 12,
containerName: "Scope\\Folder",
location: { uri: location.uri },
},
);
const expected = names.map((name, i) =>
operation === "references"
? {
file,
range: {
start: { line: 1, column: 2 + (i % 5) },
end: { line: 1, column: 3 + (i % 5) },
},
snippet,
}
: {
name,
kind: 12,
qualifiedName: `Scope\\Folder.${name}`,
file,
range: null,
locationUnresolved: true,
},
);
const signal = new AbortController().signal;
const complete = await normalize(
client,
operation,
file,
raw,
20,
32768,
signal,
);
expect(complete.items).toEqual(expected);
expect(complete.toolTruncated).toBe(false);
for (const retained of [12, 13]) {
const exact = Buffer.byteLength(
JSON.stringify({
...complete,
toolTruncated: raw.length > maxResults,
items: expected.slice(0, retained),
}),
);
expect(exact).toBeGreaterThanOrEqual(2048);
for (const delta of [-1, 0, 1]) {
const budget = exact + delta;
const output = await normalize(
client,
operation,
file,
raw,
maxResults,
budget,
signal,
);
expect(output.items).toEqual(
expected.slice(0, delta < 0 ? retained - 1 : retained),
);
expect(output.toolTruncated).toBe(true);
expect(Buffer.byteLength(JSON.stringify(output))).toBeLessThanOrEqual(
budget,
);
}
}
},
);
it("bounds hover bytes, result count, rejects malformed protocol values", async () => {
const { file, client, location } = await fixture();
const signal = new AbortController().signal;
const hover = await normalize(
client,
"hover",
file,
{ contents: "😀".repeat(10000) },
1,
2048,
signal,
);
expect(Buffer.byteLength(JSON.stringify(hover))).toBeLessThanOrEqual(2048);
expect(hover.toolTruncated).toBe(true);
const refs = await normalize(
client,
"references",
file,
[location, location],
1,
2048,
signal,
);
expect(refs.items).toHaveLength(1);
expect(refs.toolTruncated).toBe(true);
await expect(
normalize(client, "definition", file, {}, 1, 2048, signal),
).rejects.toMatchObject({ status: "server_failure" });
expect(
(await normalize(client, "hover", file, null, 1, 2048, signal)).status,
).toBe("no_result");
});
it("call candidates and edges never lose attribution silently when location exceeds output budget", async () => {
const { file, client, location } = await fixture();
let directory = client.root;
for (let i = 0; i < 30; i++) {
directory = join(directory, "x".repeat(80));
await mkdir(directory);
}
const longFile = join(directory, "source.go");
await writeFile(longFile, "😀Hello\n");
const item = {
name: "Hello",
kind: 12,
uri: pathToFileURL(longFile).href,
range: location.range,
selectionRange: location.range,
data: { opaque: 1 },
};
for (const raw of [
{ phase: "ambiguous", candidates: [{ item, selection: "opaque" }] },
{
phase: "relationships",
item,
relationships: [{ from: item, fromRanges: [location.range] }],
},
]) {
const output = await normalize(
client,
"incoming_calls",
file,
raw,
10,
2048,
new AbortController().signal,
);
expect(output.items).toEqual([]);
expect(output.toolTruncated).toBe(true);
expect(Buffer.byteLength(JSON.stringify(output))).toBeLessThanOrEqual(2048);
}
});