From 2811a438a005449a559582f75a41fcafe370f3f0 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Sat, 21 Nov 2026 13:38:13 +0800 Subject: [PATCH] fix(editor): skip project-wide background requests in library sources (#4933) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- src/editor/api.ts | 23 ++++++ src/editor/lsp/codeLens.test.ts | 75 ++++++++++++++++++- src/editor/lsp/codeLens.ts | 8 +- src/editor/lsp/foreground.test.ts | 19 +++++ src/editor/lsp/foreground.ts | 28 +++++++ src/editor/lsp/navigation.ts | 3 + src/editor/lsp/serverCodeLens.test.ts | 23 +++++- src/editor/lsp/serverCodeLens.ts | 12 ++- src/editor/navigation/implementationGutter.ts | 56 ++++++++++++-- src/editor/navigation/lineMarkers.test.ts | 40 ++++++++++ 10 files changed, 269 insertions(+), 18 deletions(-) create mode 100644 src/editor/lsp/foreground.test.ts create mode 100644 src/editor/lsp/foreground.ts diff --git a/src/editor/api.ts b/src/editor/api.ts index a259f5586..98eb0975a 100644 --- a/src/editor/api.ts +++ b/src/editor/api.ts @@ -34,6 +34,9 @@ import type { HunkKind } from "@/bindings"; import type { LineEnding } from "@/platform/ipc"; import { create } from "zustand"; import { maybeEditorService, type EditorInput } from "@/workbench/contributions"; +import { isSameOrInside } from "@/platform/paths"; +import { useProject } from "@/platform/project"; +import { rootOfPath } from "@/platform/projectRoots"; import { cornerInset } from "@/editor/core/cm/cornerInset"; export { iconAreaSource, mapLineStart, type IconAreaSource } from "@/editor/core/cm/iconArea"; @@ -790,6 +793,26 @@ export function isLibraryPath(path: string): boolean { return false; } +/** + * A document outside the project's own code: a server's virtual document (a library class), a + * file under the library roots or in a `node_modules` folder (the library roots list only direct + * dependencies, and a package manager's store holds the real paths), in a folder marked Excluded + * (a virtual environment, build output, a `vendor` copy the user marked; the innermost mark wins, + * so a source folder inside stays the project's), or outside the open project's folders (the stubs + * a language server ships, a standard library it resolves elsewhere). Background features skip + * what needs a search over the whole project here (usage counts, inheritor markers, server + * lenses): a library symbol is referenced everywhere, so each such request makes the server + * analyse every file, and an explicit Find Usages or Go to Implementation still answers. + */ +export function isLibrarySource(ctx: Pick): boolean { + if (ctx.virtual || isLibraryPath(ctx.path) || /(^|[\\/])node_modules[\\/]/.test(ctx.path)) return true; + const project = useProject.getState().project; + if (!project) return false; + const folders = project.workspace ? project.workspace.projects : [project.root]; + if (!folders.some((root) => isSameOrInside(ctx.path, root))) return true; + return rootOfPath(ctx.path)?.kind === "excluded"; +} + // --- documents shown outside editor tabs --------------------------------------- /** diff --git a/src/editor/lsp/codeLens.test.ts b/src/editor/lsp/codeLens.test.ts index c457d0f91..7b5b721ae 100644 --- a/src/editor/lsp/codeLens.test.ts +++ b/src/editor/lsp/codeLens.test.ts @@ -2,7 +2,16 @@ 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, viewShown } from "@/editor/api"; +import { + _addEditor, + _emitEditorEvent, + _removeEditor, + codeLenses, + documentSynced, + setLibraryRoots, + viewShown, + type EditorDocContext, +} from "@/editor/api"; const ipc = vi.hoisted(() => ({ docOutline: vi.fn(), @@ -27,6 +36,7 @@ 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[] = []; @@ -43,11 +53,11 @@ function deferred() { return { promise, resolve }; } -function editor(count = 1, sync?: () => Promise) { +function editor(count = 1, sync?: () => Promise, docCtx: EditorDocContext = ctx) { const view = new EditorView({ state: EditorState.create({ doc: Array.from({ length: count }, (_, i) => `fn f${i}() {}`).join("\n"), - extensions: [lspDoc.of(ctx), usagesLensExtension(), ...(sync ? [documentSynced.of(sync)] : [])], + extensions: [lspDoc.of(docCtx), usagesLensExtension(), ...(sync ? [documentSynced.of(sync)] : [])], }), parent: document.body, }); @@ -157,6 +167,65 @@ describe("background usage counts", () => { 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(); diff --git a/src/editor/lsp/codeLens.ts b/src/editor/lsp/codeLens.ts index fe863077d..63ee66d1f 100644 --- a/src/editor/lsp/codeLens.ts +++ b/src/editor/lsp/codeLens.ts @@ -7,13 +7,13 @@ * panel runs (including the plugin indexers' anchors), scoped to what the * server analyses: opening candidate files or the libraries for every count * would trigger expensive server analysis, so only an explicit Find Usages - * widens the server's scope, and a widened search can find more. Beside each - * count, the declaration's last author from VCS blame (`authorLens`). + * widens the server's scope, and a widened search can find more. Library + * sources get no counts (`isLibrarySource`). Beside each count, the declaration's last author from VCS blame (`authorLens`). */ import { Channel } from "@tauri-apps/api/core"; import { EditorSelection, MapMode, StateEffect, StateField, type Extension, type Text } from "@codemirror/state"; import { EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view"; -import { codeLenses, onEditorEvent, shownAgain, type CodeLens } from "@/editor/api"; +import { codeLenses, isLibrarySource, onEditorEvent, shownAgain, type CodeLens } from "@/editor/api"; import { onNavigationProvidersChanged } from "@/editor/navigationProviders"; import { executeAction } from "@/platform/actions"; import { commands, nextRequestId, onIdeEvent, type OutlineItem, type RequestId, type SymbolKind } from "@/platform/ipc"; @@ -214,7 +214,7 @@ class UsagesLensPlugin { const doc = docOf(view); if (!doc) return; const gen = this.generation; - const usagesWanted = usagesEnabled(); + const usagesWanted = usagesEnabled() && !isLibrarySource(doc); const usages = usagesWanted && !usagesBackoff.active(doc.doc); const authors = authorEnabled() && !doc.virtual; if (!usagesWanted && !authors) { diff --git a/src/editor/lsp/foreground.test.ts b/src/editor/lsp/foreground.test.ts new file mode 100644 index 000000000..846aeba78 --- /dev/null +++ b/src/editor/lsp/foreground.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from "vitest"; +import { isNavigating, navigationStarted, onNavigation } from "./foreground"; + +describe("navigation before background requests", () => { + it("reports the first navigation starting and the last one finishing", () => { + const seen: boolean[] = []; + const off = onNavigation((n) => seen.push(n)); + const a = navigationStarted(); + const b = navigationStarted(); + expect(isNavigating()).toBe(true); + a(); + a(); + expect(isNavigating()).toBe(true); + b(); + expect(isNavigating()).toBe(false); + expect(seen).toEqual([true, false]); + off(); + }); +}); diff --git a/src/editor/lsp/foreground.ts b/src/editor/lsp/foreground.ts new file mode 100644 index 000000000..3a2ddad39 --- /dev/null +++ b/src/editor/lsp/foreground.ts @@ -0,0 +1,28 @@ +/** + * Explicit navigation (Go to Declaration, Implementation, …) goes before background requests: + * the gutter markers cancel what they asked and wait until the navigation is done, so the + * server answers the user's request first. + */ +let running = 0; +const listeners = new Set<(navigating: boolean) => void>(); + +export function isNavigating(): boolean { + return running > 0; +} + +/** Subscribes to navigation starting (`true`) and the last one finishing (`false`). */ +export function onNavigation(listener: (navigating: boolean) => void): () => void { + listeners.add(listener); + return () => listeners.delete(listener); +} + +/** Marks a navigation as running; call the returned function once it is done. */ +export function navigationStarted(): () => void { + if (running++ === 0) for (const l of listeners) l(true); + let done = false; + return () => { + if (done) return; + done = true; + if (--running === 0) for (const l of listeners) l(false); + }; +} diff --git a/src/editor/lsp/navigation.ts b/src/editor/lsp/navigation.ts index 7c3ecad7d..b1e772c30 100644 --- a/src/editor/lsp/navigation.ts +++ b/src/editor/lsp/navigation.ts @@ -82,6 +82,7 @@ import { textReference, } from "./links"; import { featureBackoff } from "./availability"; +import { navigationStarted } from "./foreground"; import { requestHover, showPhpConstructDocumentation } from "./hover"; import { declarationSummary, renderCode } from "./markdown"; import { enclosingType } from "@/editor/navigation/lineMarkers"; @@ -353,9 +354,11 @@ export async function gotoTargets(view: EditorView, kind: GotoKind, at?: number) // can take as long as the server's answer. const done = showPendingHint(view, tx`Finding navigation target…`); pendingGestureHints.set(view, done); + const navigated = navigationStarted(); try { await gotoResolved(view, kind, at ?? view.state.selection.main.head, superseded, done); } finally { + navigated(); done(); if (pendingGestureHints.get(view) === done) pendingGestureHints.delete(view); } diff --git a/src/editor/lsp/serverCodeLens.test.ts b/src/editor/lsp/serverCodeLens.test.ts index e4d6e3d9d..c679a71f7 100644 --- a/src/editor/lsp/serverCodeLens.test.ts +++ b/src/editor/lsp/serverCodeLens.test.ts @@ -1,7 +1,7 @@ import { afterEach, expect, it, vi } from "vitest"; import { EditorState } from "@codemirror/state"; import { EditorView } from "@codemirror/view"; -import { codeLenses } from "@/editor/api"; +import { codeLenses, setLibraryRoots } from "@/editor/api"; const ipc = vi.hoisted(() => ({ lspCodeLens: vi.fn(), lspExecuteCommand: vi.fn(async () => ({ status: "ok", data: null })), @@ -41,6 +41,27 @@ it("renders LSP and plugin lens commands in the shared facet and invokes their c expect(ipc.lspExecuteCommand).toHaveBeenCalledWith(1, command); }); +it("asks nothing in library sources, where resolving a lens searches the whole project", async () => { + vi.useFakeTimers(); + const off = setLibraryRoots("test", ["/venv/site-packages"]); + try { + for (const ctx of [ + { doc: 1, path: "/venv/site-packages/m/a.ts", language: "typescript", uiMode: null, readOnly: true }, + { doc: 2, path: "jdt://contents/A.class", language: "java", uiMode: null, readOnly: true, virtual: true }, + ]) { + const view = new EditorView({ + state: EditorState.create({ doc: "x", extensions: serverCodeLenses(ctx) }), + parent: document.body, + }); + views.push(view); + } + await vi.advanceTimersByTimeAsync(400); + expect(ipc.lspCodeLens).not.toHaveBeenCalled(); + } finally { + off(); + } +}); + it("keeps mapped lenses across edits instead of clearing them (#2710)", async () => { vi.useFakeTimers(); ipc.lspCodeLens.mockResolvedValue({ diff --git a/src/editor/lsp/serverCodeLens.ts b/src/editor/lsp/serverCodeLens.ts index 18a6120d1..b0ca3e2d8 100644 --- a/src/editor/lsp/serverCodeLens.ts +++ b/src/editor/lsp/serverCodeLens.ts @@ -1,7 +1,14 @@ /** Language-server and plugin lenses in the shared editor code-vision renderer. */ import { MapMode, StateEffect, StateField, type Extension } from "@codemirror/state"; import { ViewPlugin, type ViewUpdate } from "@codemirror/view"; -import { codeLenses, shownAgain, whenSynced, type CodeLens, type EditorDocContext } from "@/editor/api"; +import { + codeLenses, + isLibrarySource, + shownAgain, + whenSynced, + type CodeLens, + type EditorDocContext, +} from "@/editor/api"; import { call, commands } from "@/platform/ipc"; import { onNavigationProvidersChanged } from "@/editor/navigationProviders"; import { posToOffset } from "./positions"; @@ -68,7 +75,8 @@ export function serverCodeLenses(ctx: EditorDocContext): Extension { const gen = this.generation; const text = view.state.doc; this.enabled = editorPrefs().inlay.codeVision; - if (!this.enabled) { + // Resolving a server's lenses counts references / implementations over the whole project. + if (!this.enabled || isLibrarySource(ctx)) { if (view.state.field(field).length) view.dispatch({ effects: set.of([]) }); return; } diff --git a/src/editor/navigation/implementationGutter.ts b/src/editor/navigation/implementationGutter.ts index a0fe00bb7..456d20001 100644 --- a/src/editor/navigation/implementationGutter.ts +++ b/src/editor/navigation/implementationGutter.ts @@ -13,13 +13,15 @@ * The cache outlives the editor view (switching tabs remounts it) until other * files change or a language server settles: on some servers (jdtls) every * implementation search walks the whole workspace, so asking again is costly. + * Library sources ask no inheritors from the server (`isLibrarySource`). */ import { RangeSet, StateEffect, StateField, type Extension, type Text } from "@codemirror/state"; import { EditorView, GutterMarker, ViewPlugin, type ViewUpdate } from "@codemirror/view"; import { iconAreaSource, mapLineStart } from "@/editor/core/cm/iconArea"; -import { shownAgain, type EditorDocContext } from "@/editor/api"; +import { isLibrarySource, shownAgain, type EditorDocContext } from "@/editor/api"; import { docOf, debounce, isUnavailable, lspRequest } from "@/editor/lsp/lsp"; import { featureBackoff, onServerSettled } from "@/editor/lsp/availability"; +import { isNavigating, onNavigation } from "@/editor/lsp/foreground"; import { readManyFileLines, withDocument } from "@/editor/lsp/files"; import { locationItems, navigateTo, pinToFind } from "@/editor/lsp/navigation"; import { openPopup } from "@/editor/lsp/popupStore"; @@ -122,6 +124,14 @@ function watchChanges() { forgetInheritanceGraph(); for (const plugin of live) plugin.refreshSoon(); }); + // Go to Declaration and the like go first: in-flight marker requests are cancelled and + // asked again once the navigation is done. + onNavigation((navigating) => { + for (const plugin of live) { + if (navigating) plugin.yieldToNavigation(); + else plugin.resumeAfterNavigation(); + } + }); } /** The cache for `doc` at `path`: kept while its text and other files are unchanged. */ @@ -641,6 +651,8 @@ class MarkersPlugin { private refresh = debounce(() => void this.run(), DEBOUNCE_MS); private generation = 0; private skipped = false; + /** A pass was cancelled or held back by a navigation: run again once it is done. */ + private yielded = false; private request: RequestId | null = null; private offSettings: () => void; @@ -657,6 +669,19 @@ class MarkersPlugin { this.refresh(); } + yieldToNavigation() { + if (this.request === null) return; + this.generation++; + this.cancelRequest(); + this.yielded = true; + } + + resumeAfterNavigation() { + if (!this.yielded) return; + this.yielded = false; + this.refresh(); + } + update(u: ViewUpdate) { if (u.docChanged) { // Other documents' markers may depend on this one. @@ -687,6 +712,10 @@ class MarkersPlugin { if (this.skipped) return; const ctx = docOf(view); if (!ctx) return; + if (isNavigating()) { + this.yielded = true; + return; + } const gen = ++this.generation; this.cancelRequest(); const groups = enabledGroups(editorPrefs()); @@ -701,12 +730,10 @@ class MarkersPlugin { if (!entry.outline) { const items = await lspRequest(() => commands.docOutline(ctx.doc)); if (stale()) return; - entry.outline = { - items, - candidates: markerCandidates(items, (l) => (l < text.lines ? text.line(l + 1).text : ""), { - implicitInterfaces: ctx.language === "go", - }), - }; + const candidates = markerCandidates(items, (l) => (l < text.lines ? text.line(l + 1).text : ""), { + implicitInterfaces: ctx.language === "go", + }); + entry.outline = { items, candidates: isLibrarySource(ctx) ? libraryCandidates(candidates) : candidates }; } const { candidates, items } = entry.outline; const { from, to } = view.viewport; @@ -735,8 +762,21 @@ class MarkersPlugin { } } +/** + * In a library every method's overriders would be searched for across the whole project, + * one search per visible method: only its classes and interfaces get ↓ markers. + */ +export function libraryCandidates(candidates: readonly MarkerCandidate[]): MarkerCandidate[] { + return candidates.map((c) => (c.method && c.inheritable ? { ...c, inheritable: false } : c)); +} + /** LSP access for one pass: this document's outline as known, others' opened on demand, each asked once. */ -function markerDeps(ctx: EditorDocContext, items: OutlineItem[], request: RequestId, cache: MarkerCache): MarkerDeps { +export function markerDeps( + ctx: EditorDocContext, + items: OutlineItem[], + request: RequestId, + cache: MarkerCache, +): MarkerDeps { const supertypes = new Map>(); const subtypes = new Map>(); const outlines = new Map>([[ctx.path, Promise.resolve(items)]]); diff --git a/src/editor/navigation/lineMarkers.test.ts b/src/editor/navigation/lineMarkers.test.ts index 6c9417470..1247abad9 100644 --- a/src/editor/navigation/lineMarkers.test.ts +++ b/src/editor/navigation/lineMarkers.test.ts @@ -29,13 +29,16 @@ import { emptyCache, enabledGroups, fillMarkers, + libraryCandidates, markerBatches, + markerDeps, markersOf, noteOtherChanges, openMarkerTargets, type MarkerDeps, } from "./implementationGutter"; import { importBindings } from "./inheritanceGraph"; +import { setLibraryRoots } from "@/editor/api"; const ALL = enabledGroups({ showGutterIcons: true, gutterIconsDisabled: [] }); @@ -489,6 +492,43 @@ describe("settings", () => { }); }); +describe("library sources", () => { + const shapeImpls = { + [`${SHAPE_PATH}:0`]: [loc("/p/Circle.java", 0, 13), loc("/p/Square.java", 0, 13)], + [`${SHAPE_PATH}:1`]: [loc("/p/Circle.java", 2, 18), loc("/p/Square.java", 1, 18)], + }; + + it("ask for the inheritors of types only, not one project-wide search per method", async () => { + const { deps, calls } = server(shapeImpls, {}); + const candidates = libraryCandidates(markerCandidates(SHAPE_OUTLINE, lines(SHAPE))); + const cache = emptyCache(); + await fillMarkers(SHAPE_PATH, candidates, ALL, deps(SHAPE_PATH), cache); + expect(calls.implementations).toEqual([[{ line: 0, col: 17 }]]); + expect(cachedMarkers(candidates, ALL, cache).map((m) => [m.line, m.kind, m.tooltip])).toEqual([ + [0, "implemented", "Is implemented by Circle, Square"], + ]); + }); + + it("still ask the server for inheritors and subtypes", async () => { + const off = setLibraryRoots("test", ["/venv/site-packages"]); + try { + const library = { + doc: 1, + path: "/venv/site-packages/m/a.py", + language: "python", + uiMode: null, + readOnly: true, + }; + const deps = markerDeps(library, [], 1, emptyCache()); + // No server in tests: unavailable. + await expect(deps.implementations([{ line: 0, col: 4 }])).rejects.toMatchObject({ kind: "unavailable" }); + expect(deps.supers.subtypes).toBeDefined(); + } finally { + off(); + } + }); +}); + describe("clicking a marker", () => { beforeEach(() => { nav.navigateTo.mockClear();