Файли
openidea/src/editor/lsp/codeLens.test.ts
T
l0ng-ai 2811a438a0 fix(editor): skip project-wide background requests in library sources (#4933)
Go to Declaration in a library file could wait 10-20 s behind usage lenses, server code lenses and inheritor markers, which asked references / implementation for every visible library declaration and made the server analyse the whole project.

Usage lenses and server code lenses now skip library sources (library roots, node_modules, excluded folders, virtual documents, files outside the project). Gutter markers stay: in library files ↓ is asked for classes and interfaces only, and in-flight marker requests are cancelled while a navigation gesture runs and asked again afterwards.
2026-11-21 13:38:13 +08:00

491 рядки
20 KiB
TypeScript

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 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());
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/[email protected]/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"]);
});
});