Lutra/ui/tests/editor/assist/completion.test.ts
danny a212a44490 M3.4: completion, hover and signature help from Phpactor
Engine (crates/engine/src/cmd/lsp_assist.rs), on M3.5's pending outcomes:
- lsp.completion {id, position, triggerCharacter?}: items with label,
  kind, detail, Markdown documentation, insertText, textEdit,
  additionalTextEdits, sortText; sorted, capped at 500 (cut lists are
  incomplete), snippets turned into plain text.
- lsp.hover {id, position}: Markdown contents and range.
- lsp.signatureHelp {id, position}: signatures with UTF-16 parameter spans.
- The request is queued after every didChange; the answer is converted
  in the reply callback, off the engine lock. Positions are checked
  against the buffer. Server strings and lists are capped.
- lutra-lsp-fake answers completion and signature help.

Editor (ui/src/components/editor/assist/):
- Completion source with Lutra's triggers (identifiers, $, ->, ?->, ::,
  namespace \; not in strings or comments unless asked), the server's
  ranking as boost, text edits and imports applied in UTF-16 (CRLF too),
  Lucide kind icons.
- Hover documentation (350 ms) and editor.quickDocumentation (Mod+I).
- Signature help on ( and , following the cursor; editor.parameterInfo.
- editor.complete.
- Lutra's own Markdown renderer without HTML (XSS-tested), tokens only.
- Requests wait for the buffer sync to be idle and use runWaiting.
- New dependency @codemirror/autocomplete (MIT, already transitive).

Tests: 6 engine tests against the fake server, 9 unit tests, an ignored
real-Phpactor latency test, 29 Vitest tests; palette and menu tests list
the new UI commands.

Measured with the real Phpactor (Windows 11, debug build, 25 ms tick):
- Completion 61-109 ms while typing (median 76 ms; ~107 ms in the app).
- Hover and signature help ~16 ms median.
- A useful list 2.3 s after opening a file in a 20-class project, ~65 s
  for 2,000 classes (indexing).
- Phpactor 56-71 MB working set, ~6% of one core while typing.

Live-checked in the app on port 7934. Docs: Code completion 0% -> 5%
(est.), feature depth ~4.1% -> ~4.6%, breadth 26/155, architecture, G6,
ui-parity, language-parity, roadmap, README.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 18:38:07 +02:00

285 lines
13 KiB
TypeScript

/**
* Tests of the completion source (M3.4, `assist/completion.ts`): Lutra's
* trigger rules, the query it sends (UTF-16 columns, trigger characters,
* waiting for the buffer sync), local filtering only for complete lists,
* and applying items: text edits, text typed after the request, imports
* as additional edits, CRLF documents and CRLF insert texts.
*/
import { CompletionContext, type Completion, type CompletionResult } from "@codemirror/autocomplete";
import { php } from "@codemirror/lang-php";
import { ensureSyntaxTree } from "@codemirror/language";
import { EditorState, Text } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { afterEach, describe, expect, it } from "vitest";
import {
completionChanges,
completionTrigger,
lspCompletionSource,
toOptions,
} from "../../../src/components/editor/assist/completion";
import { kindIcon } from "../../../src/components/editor/assist/icons";
import { assistExtensions } from "../../../src/components/editor/assist";
import { toCompletionList, type CompletionItem } from "../../../src/components/editor/assist/types";
import { fakeBuffer, fakeTransport } from "./fakes";
/** Views created by a test, destroyed after it. */
let views: EditorView[] = [];
afterEach(() => {
for (const view of views) {
view.destroy();
}
views = [];
});
/** A PHP editor state with the cursor at `|` in `text`. */
function stateAt(text: string): { state: EditorState; pos: number } {
const pos = text.indexOf("|");
const doc = text.slice(0, pos) + text.slice(pos + 1);
const state = EditorState.create({ doc, extensions: [php()], selection: { anchor: pos } });
ensureSyntaxTree(state, state.doc.length, 5000);
return { state, pos };
}
/** A complete item with defaults. */
function item(over: Partial<CompletionItem>): CompletionItem {
return { label: "x", kind: "text", insertText: over.label ?? "x", ...over };
}
/** Applies a plan to a document and returns the text and cursor. */
function applyPlan(doc: string, plan: ReturnType<typeof completionChanges>): { text: string; cursor: number } {
const state = EditorState.create({ doc });
const changes = state.changes(plan.changes);
return { text: changes.apply(state.doc).toString(), cursor: changes.mapPos(plan.mainEnd, 1) };
}
describe("completionTrigger", () => {
it("triggers after member and static access, variables and namespaces", () => {
expect(completionTrigger("$a->", false)).toEqual({ back: 0, character: ">" });
expect(completionTrigger("$a?->", false)).toEqual({ back: 0, character: ">" });
expect(completionTrigger("Foo::", false)).toEqual({ back: 0, character: ":" });
expect(completionTrigger("echo $", false)).toEqual({ back: 1, character: "$" });
expect(completionTrigger("new App\\", false)).toEqual({ back: 0, character: "\\" });
});
it("triggers on identifiers and variables being typed", () => {
expect(completionTrigger("$a->fo", false)).toEqual({ back: 2 });
expect(completionTrigger("echo $na", false)).toEqual({ back: 3 });
expect(completionTrigger("strl", false)).toEqual({ back: 4 });
expect(completionTrigger("$ä", false)).toEqual({ back: 2 });
});
it("does not trigger on numbers, operators or spaces unless asked", () => {
expect(completionTrigger("x = 12", false)).toBeNull();
expect(completionTrigger("x = 1e5", false)).toBeNull();
expect(completionTrigger("a - ", false)).toBeNull();
expect(completionTrigger("a -", false)).toBeNull();
expect(completionTrigger("", false)).toBeNull();
expect(completionTrigger("a - ", true)).toEqual({ back: 0 });
expect(completionTrigger("12", true)).toEqual({ back: 0 });
});
});
describe("toCompletionList", () => {
it("drops malformed items and defaults the rest", () => {
const list = toCompletionList({
incomplete: true,
items: [
{ label: "a", kind: "nonsense" },
{ label: "" },
"junk",
{ label: "b", kind: "class", insertText: "B", textEdit: { range: { start: {}, end: {} }, newText: "x" } },
{ label: "c", additionalTextEdits: [{ range: { start: { line: 0, column: 0 }, end: { line: 0, column: 0 } }, newText: "u" }, null] },
],
});
expect(list.incomplete).toBe(true);
expect(list.items.map((i) => i.label)).toEqual(["a", "b", "c"]);
expect(list.items[0]).toEqual({ label: "a", kind: "text", insertText: "a" });
expect(list.items[1]?.textEdit).toBeUndefined();
expect(list.items[2]?.additionalTextEdits).toHaveLength(1);
expect(toCompletionList(null)).toEqual({ items: [], incomplete: false });
expect(toCompletionList({ items: "no" })).toEqual({ items: [], incomplete: false });
});
});
describe("completionChanges", () => {
it("applies a text edit and the typing since the request", () => {
const doc = "<?php\n$x->fo";
const requestDoc = Text.of(doc.split("\n"));
const requestPos = doc.length;
const format = item({
label: "format",
insertText: "format(",
textEdit: { range: { start: { line: 1, column: 4 }, end: { line: 1, column: 6 } }, newText: "format(" },
});
expect(applyPlan(doc, completionChanges(requestDoc, requestPos, format, 10, 12, doc.length))).toEqual({
text: "<?php\n$x->format(",
cursor: 17,
});
const typedMore = doc + "rm";
expect(applyPlan(typedMore, completionChanges(requestDoc, requestPos, format, 10, 14, typedMore.length))).toEqual({
text: "<?php\n$x->format(",
cursor: 17,
});
});
it("replaces the typed word with insertText without a text edit", () => {
const doc = "<?php\necho $na";
const plan = completionChanges(Text.of(doc.split("\n")), doc.length, item({ label: "$name", insertText: "$name" }), 11, 14, doc.length);
expect(applyPlan(doc, plan)).toEqual({ text: "<?php\necho $name", cursor: 16 });
});
it("adds imports from additional edits and skips overlapping ones", () => {
const doc = "<?php\n\nnew Fm";
const requestDoc = Text.of(doc.split("\n"));
const fmt = item({
label: "Fmt",
insertText: "Fmt",
additionalTextEdits: [
{ range: { start: { line: 0, column: 5 }, end: { line: 0, column: 5 } }, newText: "\nuse App\\Fmt;" },
{ range: { start: { line: 2, column: 4 }, end: { line: 2, column: 6 } }, newText: "clash" },
],
});
const result = applyPlan(doc, completionChanges(requestDoc, doc.length, fmt, 11, 13, doc.length));
expect(result.text).toBe("<?php\nuse App\\Fmt;\n\nnew Fmt");
expect(result.cursor).toBe(result.text.length);
});
it("works on CRLF documents and turns CRLF insert texts into line breaks", () => {
const engineText = "<?php\r\nfunction a() {\r\n $this->ru\r\n}\r\n";
const lines = engineText.split("\r\n");
const requestDoc = Text.of(lines);
const state = EditorState.create({ doc: requestDoc });
const line = state.doc.line(3);
const requestPos = line.to;
const run = item({
label: "run",
textEdit: { range: { start: { line: 2, column: 11 }, end: { line: 2, column: 13 } }, newText: "run(\r\n 1\r\n)" },
});
const plan = completionChanges(requestDoc, requestPos, run, requestPos - 2, requestPos, state.doc.length);
const changes = state.changes(plan.changes);
const after = changes.apply(state.doc);
expect(after.lines).toBe(7);
expect(after.line(3).text).toBe(" $this->run(");
expect(after.line(4).text).toBe(" 1");
expect(after.line(5).text).toBe(")");
expect(after.sliceString(0)).not.toContain("\r");
});
it("clamps edits that point past the document to its last line", () => {
const doc = "<?php\n$a";
const plan = completionChanges(
Text.of(doc.split("\n")),
doc.length,
item({ label: "a", textEdit: { range: { start: { line: 9, column: 0 }, end: { line: 9, column: 99 } }, newText: "$abc" } }),
6,
8,
doc.length,
);
expect(applyPlan(doc, plan).text).toBe("<?php\n$abc");
});
});
describe("lspCompletionSource", () => {
it("asks with UTF-16 columns after the sync is idle and maps the items", async () => {
const transport = fakeTransport({
items: [
{ label: "format", kind: "method", detail: "format(): string", documentation: "**doc**", insertText: "format(" },
{ label: "$value", kind: "variable", insertText: "$value" },
],
incomplete: false,
});
const buffer = fakeBuffer(7);
const { state, pos } = stateAt("<?php\n$\u{1F9A6}->fo|");
const source = lspCompletionSource(buffer, transport);
const result = (await source(new CompletionContext(state, pos, false))) as CompletionResult;
expect(buffer.idleCalls).toBe(1);
expect(transport.calls).toEqual([
{ command: "lsp.completion", params: { id: 7, position: { line: 1, column: 7 } } },
]);
expect(result.from).toBe(pos - 2);
expect(result.validFor).toBeInstanceOf(RegExp);
expect(result.options.map((o) => o.label)).toEqual(["format", "$value"]);
expect(result.options[0]?.detail).toBe("format(): string");
expect(result.options[0]?.type).toBe("method");
expect((result.options[0]?.boost ?? 0) > (result.options[1]?.boost ?? 0)).toBe(true);
const info = result.options[0]?.info;
expect(typeof info).toBe("function");
});
it("sends the trigger character and asks again for incomplete lists", async () => {
const transport = fakeTransport({ items: [{ label: "run", kind: "method", insertText: "run" }], incomplete: true });
const { state, pos } = stateAt("<?php\n$a->|");
const result = (await lspCompletionSource(fakeBuffer(1), transport)(new CompletionContext(state, pos, false))) as CompletionResult;
expect(transport.calls[0]?.params).toMatchObject({ triggerCharacter: ">" });
expect(result.from).toBe(pos);
expect(result.validFor).toBeUndefined();
});
it("stays quiet in comments and strings unless asked", async () => {
const transport = fakeTransport({ items: [{ label: "x", kind: "text", insertText: "x" }], incomplete: false });
const source = lspCompletionSource(fakeBuffer(1), transport);
const comment = stateAt("<?php\n// call fo|");
expect(await source(new CompletionContext(comment.state, comment.pos, false))).toBeNull();
const string = stateAt("<?php\n$s = 'fo|';");
expect(await source(new CompletionContext(string.state, string.pos, false))).toBeNull();
expect(transport.calls).toHaveLength(0);
expect(await source(new CompletionContext(comment.state, comment.pos, true))).not.toBeNull();
});
it("drops the answer when the document moved on or the query failed", async () => {
const { state, pos } = stateAt("<?php\nfo|");
const view = new EditorView({ state });
views.push(view);
const buffer = fakeBuffer(1, () => {
view.dispatch({ changes: { from: pos, insert: "o" } });
});
const transport = fakeTransport({ items: [{ label: "foo", kind: "function", insertText: "foo" }], incomplete: false });
const context = new CompletionContext(state, pos, false, view);
expect(await lspCompletionSource(buffer, transport)(context)).toBeNull();
expect(transport.calls).toHaveLength(0);
const failing = fakeTransport(null, { code: "failed", message: "no PHP language server is running" });
expect(await lspCompletionSource(fakeBuffer(1), failing)(new CompletionContext(state, pos, false))).toBeNull();
});
it("applies an option through the view, with the import", () => {
const doc = "<?php\n\nnew Fm";
const view = new EditorView({ state: EditorState.create({ doc, selection: { anchor: doc.length } }) });
views.push(view);
const [option] = toOptions(
[
item({
label: "Fmt",
kind: "class",
insertText: "Fmt",
additionalTextEdits: [{ range: { start: { line: 0, column: 5 }, end: { line: 0, column: 5 } }, newText: "\nuse App\\Fmt;" }],
}),
],
view.state.doc,
doc.length,
);
const apply = (option as Completion).apply;
expect(typeof apply).toBe("function");
if (typeof apply === "function") {
apply(view, option as Completion, doc.length - 2, doc.length);
}
expect(view.state.doc.toString()).toBe("<?php\nuse App\\Fmt;\n\nnew Fmt");
expect(view.state.selection.main.head).toBe(view.state.doc.length);
});
});
describe("assistExtensions", () => {
it("is only added for PHP files of a buffer", () => {
expect(assistExtensions("a.txt", fakeBuffer(1))).toEqual([]);
expect(assistExtensions("a.php", undefined)).toEqual([]);
expect(assistExtensions("src/A.php", fakeBuffer(1))).not.toEqual([]);
});
it("renders a Lucide icon with the kind's catalog name", () => {
const icon = kindIcon("class");
expect(icon.title).toBe("Class");
expect(icon.querySelector("svg")).not.toBeNull();
expect(kindIcon("nonsense").className).toContain("lt-assist-kind-text");
});
});