Files
openidea/src/editor/lsp/codeLens.test.ts
T
Mr0Bread 4b55039e6e fix(editor): refresh usage counts only when a source file changed (#5242)
The usages code lens re-asked the language server for every visible declaration on every fsChanged event, even ones carrying only images or logs. It now recounts only when a changed path can be a file a language server analyses (by the language registry and Settings > File Types), and still recounts when in doubt: unloaded languages or paths without an extension.

Co-authored-by: Mr0Bread <55754540+Mr0Bread@users.noreply.github.com>
2026-11-23 13:36:12 +08:00

576 lines
23 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import type { OutlineItem, References } from "@/platform/ipc";
import {
_addEditor,
_emitEditorEvent,
_removeEditor,
codeLenses,
documentSynced,
setLibraryRoots,
viewShown,
type EditorDocContext,
} from "@/editor/api";
const ipc = vi.hoisted(() => ({
docOutline: vi.fn(),
lspReferences: vi.fn(),
cancelRequest: vi.fn<(id: number) => Promise<void>>(async () => {}),
vcsBlame: vi.fn(),
}));
vi.mock("@/platform/ipc", async (orig) => {
const real = await orig<typeof import("@/platform/ipc")>();
return { ...real, isTauri: () => true, commands: { ...real.commands, ...ipc } };
});
const executeAction = vi.hoisted(() => vi.fn(async () => true));
vi.mock("@/platform/actions", () => ({ executeAction }));
vi.mock("@tauri-apps/api/core", async (orig) => ({
...(await orig<object>()),
Channel: class {
onmessage = () => {};
},
}));
const { lensTargets, usagesLensExtension } = await import("./codeLens");
const { lspDoc } = await import("./lsp");
const { useProject } = await import("@/platform/project");
const { emitLocalIdeEvent } = await import("@/platform/ipc");
const { useProjectRoots } = await import("@/platform/projectRoots");
const { _resetLanguages, loadLanguageInfos } = await import("@/editor/core/cm/languages");
const ctx = { doc: 7, path: "/p/a.rs", language: "rust", uiMode: "Rust", readOnly: false };
const views: EditorView[] = [];
const ok = <T>(data: T) => ({ status: "ok" as const, data });
const refs = (n: number, incomplete: References["incomplete"] = null) =>
ok({
locations: Array.from({ length: n }, () => ({ path: "/p/b.rs", range: item("x", "function", 0).range })),
incomplete,
});
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>((r) => (resolve = r));
return { promise, resolve };
}
function editor(count = 1, sync?: () => Promise<void>, docCtx: EditorDocContext = ctx) {
const view = new EditorView({
state: EditorState.create({
doc: Array.from({ length: count }, (_, i) => `fn f${i}() {}`).join("\n"),
extensions: [lspDoc.of(docCtx), usagesLensExtension(), ...(sync ? [documentSynced.of(sync)] : [])],
}),
parent: document.body,
});
views.push(view);
return view;
}
const titles = (view: EditorView) => view.state.facet(codeLenses).map((l) => l.title);
const settle = () => vi.advanceTimersByTimeAsync(1000);
beforeEach(() => {
vi.useFakeTimers();
ipc.docOutline.mockReset().mockResolvedValue(ok([item("f0", "function", 0)]));
ipc.lspReferences.mockReset().mockResolvedValue(refs(2));
ipc.cancelRequest.mockClear();
executeAction.mockClear();
useProject.setState({
settings: { editor: { inlay: { codeVisionUsages: true, codeVisionAuthor: false } } } as never,
});
});
afterEach(() => {
views.splice(0).forEach((v) => v.destroy());
_resetLanguages();
useProject.setState({ settings: null });
vi.useRealTimers();
});
const item = (name: string, kind: OutlineItem["kind"], line: number, children: OutlineItem[] = []): OutlineItem => {
const r = { start: { line, col: 0 }, end: { line, col: 1 } };
return { name, kind, detail: null, range: r, selection_range: r, children };
};
describe("usages label", () => {
it("is translated", async () => {
const { usagesLabel } = await import("./codeLens");
const { setLocale } = await import("@/platform/i18n");
expect([0, 1, 3].map(usagesLabel)).toEqual(["no usages", "1 usage", "3 usages"]);
await setLocale("zh");
expect([0, 1, 3].map(usagesLabel)).toEqual(["无用法", "1 个用法", "3 个用法"]);
await setLocale("en");
});
});
describe("usages lens targets", () => {
it("skips callbacks and anonymous functions", () => {
const items = [
item("Cart", "class", 0, [
item("count", "method", 1, [item("reduce() callback", "function", 2)]),
item("<function>", "function", 3),
]),
];
expect(lensTargets(items).map((t) => t.name)).toEqual(["Cart", "count"]);
});
});
describe("author hint", () => {
it("toggles the blame annotations on every click", async () => {
ipc.vcsBlame.mockResolvedValue(ok([{ commit: "c1", author: "Ann", timeMs: 1, summary: "init" }]));
useProject.setState({
settings: { editor: { inlay: { codeVisionUsages: false, codeVisionAuthor: true } } } as never,
});
const view = editor();
await settle();
const author = view.state.facet(codeLenses).find((l) => l.kind === "author")!;
expect(author.title).toContain("Ann");
author.run!(view, new MouseEvent("click"));
author.run!(view, new MouseEvent("click"));
expect(executeAction.mock.calls).toEqual([["vcs.annotate"], ["vcs.annotate"]]);
});
});
describe("Code Vision switch", () => {
it("hides usages and author while off and brings back the kinds still chosen", async () => {
ipc.vcsBlame.mockResolvedValue(ok([{ commit: "c1", author: "Ann", timeMs: 1, summary: "init" }]));
const inlay = (codeVision: boolean) =>
useProject.setState({
settings: { editor: { inlay: { codeVision, codeVisionUsages: true, codeVisionAuthor: true } } } as never,
});
inlay(true);
const view = editor();
await settle();
expect(view.state.facet(codeLenses).map((l) => l.kind)).toEqual(["author", "usages"]);
inlay(false);
await settle();
expect(titles(view)).toEqual([]);
inlay(true);
await settle();
expect(view.state.facet(codeLenses).map((l) => l.kind)).toEqual(["author", "usages"]);
});
});
describe("background usage counts", () => {
it("uses the server's existing scope and leaves full searches to the explicit action", async () => {
const view = editor();
await settle();
expect(ipc.lspReferences).toHaveBeenCalledWith(
expect.any(Number),
7,
{ line: 0, col: 0 },
false,
false,
false,
expect.anything(),
);
expect(titles(view)).toEqual(["2 usages"]);
view.state.facet(codeLenses)[0]!.run!(view, new MouseEvent("click"));
expect(executeAction).toHaveBeenCalledWith("find.showUsages");
});
it("counts nothing in library sources, where every count searches the whole project", async () => {
const off = setLibraryRoots("test", ["/venv/lib/site-packages"]);
try {
const library = editor(1, undefined, { ...ctx, path: "/venv/lib/site-packages/m/a.rs" });
const virtual = editor(1, undefined, { ...ctx, doc: 8, path: "jdt://contents/A.class", virtual: true });
await settle();
expect(ipc.lspReferences).not.toHaveBeenCalled();
expect([titles(library), titles(virtual)]).toEqual([[], []]);
} finally {
off();
}
});
it("counts nothing outside the project's own code: a server's stubs, a node_modules package", async () => {
useProject.setState({ project: { root: "/p" } as never });
try {
const stub = editor(1, undefined, { ...ctx, doc: 9, path: "/opt/server/typeshed/stdlib/typing.pyi" });
// A transitive dependency in the package manager's store, inside the project folder.
const store = editor(1, undefined, {
...ctx,
doc: 10,
path: "/p/node_modules/.pnpm/react@18.3.1/node_modules/react/index.d.ts",
});
await settle();
expect(ipc.lspReferences).not.toHaveBeenCalled();
expect([titles(stub), titles(store)]).toEqual([[], []]);
const own = editor();
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(1);
expect(titles(own)).toEqual(["2 usages"]);
} finally {
useProject.setState({ project: null });
}
});
it("counts nothing in a folder marked Excluded, unless a source folder inside it holds the file", async () => {
useProject.setState({ project: { root: "/p" } as never });
useProjectRoots.setState({
root: "/p",
detected: [
{ path: "vendor", kind: "excluded", detectedFrom: null },
{ path: "vendor/own/src", kind: "source", detectedFrom: null },
],
});
try {
const vendored = editor(1, undefined, { ...ctx, doc: 11, path: "/p/vendor/lib/a.rs" });
await settle();
expect(ipc.lspReferences).not.toHaveBeenCalled();
expect(titles(vendored)).toEqual([]);
const own = editor(1, undefined, { ...ctx, doc: 12, path: "/p/vendor/own/src/a.rs" });
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(1);
expect(titles(own)).toEqual(["2 usages"]);
} finally {
useProject.setState({ project: null });
useProjectRoots.setState({ root: null, detected: [] });
}
});
it("allows a full search even when the server's current scope has no usages", async () => {
ipc.lspReferences.mockResolvedValue(refs(0));
const view = editor();
await settle();
expect(titles(view)).toEqual(["no usages"]);
view.state.facet(codeLenses)[0]!.run!(view, new MouseEvent("click"));
expect(executeAction).toHaveBeenCalledWith("find.showUsages");
});
it('leaves out "no usages" when Show “no usages” is off', async () => {
ipc.lspReferences.mockResolvedValue(refs(0));
useProject.setState({
settings: {
editor: { inlay: { codeVisionUsages: true, codeVisionAuthor: false, codeVisionNoUsages: false } },
} as never,
});
const view = editor();
await settle();
expect(titles(view)).toEqual([]);
});
it("does not cache an incomplete count while indexing, and retries on server refresh", async () => {
ipc.lspReferences.mockResolvedValueOnce(refs(0, "indexing"));
const view = editor();
await settle();
expect(titles(view)).toEqual([]);
emitLocalIdeEvent({ type: "lspRefresh", kind: "codeLens", server: 1 });
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(2);
expect(titles(view)).toEqual(["2 usages"]);
});
it("asks again for a count that came back incomplete during a short busy spell", async () => {
// jdtls reports progress for a few milliseconds around many requests: no settle follows it.
ipc.lspReferences.mockResolvedValueOnce(refs(0, "indexing"));
const view = editor();
await settle();
expect(titles(view)).toEqual([]);
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(2);
expect(titles(view)).toEqual(["2 usages"]);
});
it("stops asking again while the server keeps saying it is indexing, until it settles", async () => {
ipc.lspReferences.mockResolvedValue(refs(0, "indexing"));
const view = editor();
for (let i = 0; i < 10; i++) await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(4);
expect(titles(view)).toEqual([]);
ipc.lspReferences.mockResolvedValue(refs(2));
emitLocalIdeEvent({ type: "lspRefresh", kind: "codeLens", server: 1 });
await settle();
expect(titles(view)).toEqual(["2 usages"]);
});
it("keeps the shown lens while the server is busy and corrects the count once it settles", async () => {
const view = editor();
await settle();
expect(titles(view)).toEqual(["2 usages"]);
// Editing while the server is indexing: the re-computed count comes back incomplete.
emitLocalIdeEvent({ type: "languageServer", server: 1, name: "rust-analyzer", status: "busy", message: null });
ipc.lspReferences.mockResolvedValue(refs(0, "indexing"));
view.dispatch({ changes: { from: view.state.doc.length, insert: " " } });
await settle();
await settle();
await settle();
await settle();
// The lens stays on its (mapped) line instead of blinking away and shifting the layout.
expect(titles(view)).toEqual(["2 usages"]);
// Once it settles, a complete answer replaces the stale count.
ipc.lspReferences.mockResolvedValue(refs(0));
emitLocalIdeEvent({ type: "languageServer", server: 1, name: "rust-analyzer", status: "ready", message: null });
await settle();
expect(titles(view)).toEqual(["no usages"]);
});
it("opens usages at the lens's current position after edits above it", async () => {
// The lens anchors on the identifier (`f0` at column 3), as in a real outline.
const decl = item("f0", "function", 0);
decl.selection_range = { start: { line: 0, col: 3 }, end: { line: 0, col: 5 } };
ipc.docOutline.mockResolvedValue(ok([decl]));
const view = editor();
await settle();
expect(titles(view)).toEqual(["2 usages"]);
// Insert a line above the declaration. The lens maps down with its line, and a
// pass with an identical count is suppressed by `sameLenses` — the click must
// still land on the identifier, not where it was when the lens was created.
view.dispatch({ changes: { from: 0, insert: "\n" } });
const declAfter = item("f0", "function", 1);
declAfter.selection_range = { start: { line: 1, col: 3 }, end: { line: 1, col: 5 } };
ipc.docOutline.mockResolvedValue(ok([declAfter]));
await settle();
const lens = view.state.facet(codeLenses).find((l) => l.kind === "usages")!;
expect(lens.pos).toBe(4);
lens.run!(view, new MouseEvent("click"));
expect(view.state.selection.main.head).toBe(4);
});
it("cancels obsolete requests immediately on edits and ignores their late replies", async () => {
const old = deferred<ReturnType<typeof refs>>();
ipc.lspReferences.mockReturnValueOnce(old.promise);
const view = editor();
await settle();
const request = ipc.lspReferences.mock.calls[0]![0];
view.dispatch({ changes: { from: view.state.doc.length, insert: " " } });
expect(ipc.cancelRequest).toHaveBeenCalledWith(request);
await settle();
expect(titles(view)).toEqual(["2 usages"]);
old.resolve(refs(99));
await settle();
expect(titles(view)).toEqual(["2 usages"]);
});
it("retries incomplete counts when indexing ends without a code-lens refresh", async () => {
ipc.lspReferences.mockResolvedValueOnce(refs(0, "indexing"));
const view = editor();
emitLocalIdeEvent({ type: "languageServer", server: 1, name: "rust-analyzer", status: "busy", message: null });
await settle();
expect(titles(view)).toEqual([]);
await settle();
emitLocalIdeEvent({ type: "languageServer", server: 1, name: "rust-analyzer", status: "ready", message: null });
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(2);
expect(titles(view)).toEqual(["2 usages"]);
});
it("does not repeat complete counts when the server finishes other work", async () => {
const view = editor();
emitLocalIdeEvent({ type: "languageServer", server: 1, name: "rust-analyzer", status: "busy", message: null });
await settle();
await settle();
emitLocalIdeEvent({ type: "languageServer", server: 1, name: "rust-analyzer", status: "ready", message: null });
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(1);
expect(titles(view)).toEqual(["2 usages"]);
});
it("cancels all in-flight requests on destroy without starting the next batch", async () => {
const pending = deferred<ReturnType<typeof refs>>();
ipc.docOutline.mockResolvedValue(ok(Array.from({ length: 8 }, (_, i) => item(`f${i}`, "function", i))));
ipc.lspReferences.mockReturnValue(pending.promise);
const view = editor(8);
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(4);
const requests = ipc.lspReferences.mock.calls.map(([id]) => id);
view.destroy();
views.splice(views.indexOf(view), 1);
expect(ipc.cancelRequest.mock.calls.map(([id]) => id)).toEqual(requests);
pending.resolve(refs(1));
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(4);
});
it("cancels pending counts when the feature is disabled", async () => {
const pending = deferred<ReturnType<typeof refs>>();
ipc.lspReferences.mockReturnValue(pending.promise);
const view = editor();
await settle();
useProject.setState({
settings: { editor: { inlay: { codeVisionUsages: false, codeVisionAuthor: false } } } as never,
});
expect(ipc.cancelRequest).toHaveBeenCalledWith(ipc.lspReferences.mock.calls[0]![0]);
pending.resolve(refs(2));
await settle();
expect(titles(view)).toEqual([]);
});
it("does not send obsolete requests after waiting for document synchronization", async () => {
const synced = deferred<void>();
const view = editor(1, () => synced.promise);
const handle = { view, ctx };
_addEditor(handle);
try {
await settle();
expect(ipc.docOutline).not.toHaveBeenCalled();
view.destroy();
views.splice(views.indexOf(view), 1);
synced.resolve();
await settle();
expect(ipc.docOutline).not.toHaveBeenCalled();
expect(ipc.lspReferences).not.toHaveBeenCalled();
expect(ipc.cancelRequest).not.toHaveBeenCalled();
} finally {
_removeEditor(handle);
}
});
});
describe("recounting when the project's documents change", () => {
it("recounts when another document is edited (the call sites)", async () => {
const view = editor();
await settle();
expect(titles(view)).toEqual(["2 usages"]);
_emitEditorEvent({ type: "docChanged", doc: 9, path: "/p/b.rs", baseVersion: 1, version: 2, changes: [] });
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(2);
ipc.lspReferences.mockResolvedValue(refs(5));
_emitEditorEvent({ type: "docChanged", doc: 9, path: "/p/b.rs", baseVersion: 2, version: 3, changes: [] });
await settle();
expect(titles(view)).toEqual(["5 usages"]);
});
it("recounts when a kept tab is shown again after another document changed while hidden", async () => {
const view = editor();
await settle();
expect(titles(view)).toEqual(["2 usages"]);
ipc.lspReferences.mockResolvedValue(refs(5));
// A recently used tab keeps its view, detached from the document, while hidden.
view.dom.remove();
_emitEditorEvent({ type: "docChanged", doc: 9, path: "/p/b.rs", baseVersion: 1, version: 2, changes: [] });
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(1);
document.body.append(view.dom);
view.dispatch({ effects: viewShown.of(null) });
await settle();
expect(titles(view)).toEqual(["5 usages"]);
});
it("recounts when the backend patches another document (a refactoring)", async () => {
const view = editor();
await settle();
expect(titles(view)).toEqual(["2 usages"]);
ipc.lspReferences.mockResolvedValue(refs(3));
emitLocalIdeEvent({ type: "docPatched", doc: 9, baseVersion: 1, version: 2, changes: [] });
await settle();
expect(titles(view)).toEqual(["3 usages"]);
});
it("leaves a backend patch of this document to the document change itself", async () => {
editor();
await settle();
const calls = ipc.lspReferences.mock.calls.length;
emitLocalIdeEvent({ type: "docPatched", doc: 7, baseVersion: 1, version: 2, changes: [] });
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(calls);
});
it("recounts when the plugin document indexes change (an XML statement indexed after its declaration)", async () => {
const view = editor();
await settle();
expect(titles(view)).toEqual(["2 usages"]);
ipc.lspReferences.mockResolvedValue(refs(5));
const { invalidateNavigationProviders } = await import("@/editor/navigationProviders");
invalidateNavigationProviders();
await settle();
expect(titles(view)).toEqual(["5 usages"]);
});
it("recounts when files change on disk or another document closes", async () => {
const view = editor();
await settle();
expect(titles(view)).toEqual(["2 usages"]);
ipc.lspReferences.mockResolvedValue(refs(3));
emitLocalIdeEvent({ type: "fsChanged", created: [], modified: ["/p/b.rs"], removed: [] });
await settle();
expect(titles(view)).toEqual(["3 usages"]);
ipc.lspReferences.mockResolvedValue(refs(4));
_emitEditorEvent({ type: "docClosed", doc: 9, path: "/p/b.rs" });
await settle();
expect(titles(view)).toEqual(["4 usages"]);
});
});
describe("file changes on disk", () => {
const language = (id: string, extensions: string[], languageServers: string[], filenames: string[] = []) =>
({ id, name: id, extensions, filenames, languageServers, uiMode: null }) as never;
const fsChanged = (modified: string[], ignoreRules: string[] = []) =>
emitLocalIdeEvent({ type: "fsChanged", created: [], modified, removed: [], ignoreRules });
async function settledEditors(views: number) {
await loadLanguageInfos({
languages: async () => [
language("rust", ["rs"], ["rust-analyzer"]),
language("log", ["log"], []),
language("dockerfile", [], ["docker-langserver"], ["Dockerfile.*"]),
],
} as never);
ipc.docOutline.mockResolvedValue(ok(Array.from({ length: 60 }, (_, i) => item(`f${i}`, "function", i))));
for (let i = 0; i < views; i++) editor(60);
await settle();
const first = ipc.lspReferences.mock.calls.length;
expect(first).toBe(40 * views);
return first;
}
it.each([1, 4])("asks no new counts for events that no source file caused (%i views)", async (n) => {
const first = await settledEditors(n);
for (let i = 0; i < 10; i++) {
fsChanged(["/p/logo.png"]);
await vi.advanceTimersByTimeAsync(1000);
}
fsChanged([], ["/p"]);
fsChanged(["/p/debug.log", "/p/Cargo.lock"]);
emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [], removed: [] });
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(first);
});
it("recounts once when a source file is among the changed paths", async () => {
const first = await settledEditors(1);
for (let i = 0; i < 5; i++) fsChanged(["/p/logo.png", "/p/b.rs", "/p/debug.log"]);
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(2 * first);
});
it.each([
["a created source file", { created: ["/p/new.rs"], modified: [], removed: [] }],
["a removed source file", { created: [], modified: [], removed: ["/p/old.RS"] }],
["a file the registry matches by name", { created: [], modified: ["/p/Dockerfile.dev"], removed: [] }],
[
"a path without an extension (a folder, or a script found by its first line)",
{ created: [], modified: [], removed: ["/p/src/gen"] },
],
])("recounts for %s", async (_, paths) => {
const first = await settledEditors(1);
emitLocalIdeEvent({ type: "fsChanged", ...paths });
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(2 * first);
});
it("recounts for a file Settings › File Types assigns to a language with a server", async () => {
useProject.setState({
settings: {
editor: { inlay: { codeVisionUsages: true, codeVisionAuthor: false } },
files: { fileTypes: { rust: { patterns: ["*.tpl"] } }, fileTypeOverrides: { "/p/x.log": "rust" } },
} as never,
});
const first = await settledEditors(1);
fsChanged(["/p/page.tpl"]);
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(2 * first);
fsChanged(["/p/x.log"]);
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(3 * first);
});
it("recounts for any path while the languages are not loaded", async () => {
ipc.docOutline.mockResolvedValue(ok(Array.from({ length: 60 }, (_, i) => item(`f${i}`, "function", i))));
editor(60);
await settle();
fsChanged(["/p/logo.png"]);
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(80);
});
});