The IDE you know, rebuilt in Rust. IntelliJ IDEA–style keymap, tool windows and search-everywhere in a fast native app: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages.
TypeScript code-editorcross-platformdapdatabase-clientdebuggerdesktop-appdeveloper-toolsgithttp-clientideintellijlsprusttauriterminal
fix(editor): share go-to-definition requests per word and let the latest gesture win (#2344)
ntbang0901d881737fb355
diff --git a/src/editor/lsp/configurationNavigation.test.ts b/src/editor/lsp/configurationNavigation.test.tsindex 8a7905701..0e2f422cf 100644--- a/src/editor/lsp/configurationNavigation.test.ts+++ b/src/editor/lsp/configurationNavigation.test.ts@@ -78,11 +78,11 @@ describe("configuration navigation result reuse", () => {expect(lspGoto).toHaveBeenCalledOnce();});- it("reuses results when the same document is shown again", async () => {+ it("keeps separate editors of the same document isolated", async () => {const view = editor();await requestNavigation(view, 10, "definition");await requestNavigation(editor(), 11, "definition");- expect(lspGoto).toHaveBeenCalledOnce();+ expect(lspGoto).toHaveBeenCalledTimes(2);});it("keeps different keys and documents separate", async () => {@@ -93,13 +93,52 @@ describe("configuration navigation result reuse", () => {expect(lspGoto).toHaveBeenCalledTimes(3);});- it.each(["java", "typescript"])("leaves %s native navigation uncached", async (language) => {+ it.each(["java", "typescript"])("shares %s native navigation per word", async (language) => {const view = editor(1, language, "value");await requestNavigation(view, 1, "definition");+ await requestNavigation(view, 3, "definition");+ expect(lspGoto).toHaveBeenCalledExactlyOnceWith(1, { line: 0, col: 1 }, "definition");+ });++ it("discards a native answer that raced an edit and asks again afterwards", async () => {+ let resolve!: (r: Awaited<ReturnType<typeof commands.lspGoto>>) => void;+ lspGoto.mockImplementationOnce(+ () =>+ new Promise((r) => {+ resolve = r;+ }),+ );+ const view = editor(1, "java", "value other");+ const pending = requestNavigation(view, 1, "definition");+ const rejected = expect(pending).rejects.toMatchObject({ kind: "cancelled" });+ await vi.waitFor(() => expect(lspGoto).toHaveBeenCalledOnce());+ view.dispatch({ changes: { from: 11, insert: " x" } });+ resolve({ status: "ok", data: [target] });+ await rejected;+ await requestNavigation(view, 1, "definition");+ expect(lspGoto).toHaveBeenCalledTimes(2);+ });++ it("does not reuse an answer after replacing the editor state with equal text", async () => {+ const view = editor(1, "java", "value");+ await requestNavigation(view, 1, "definition");+ view.setState(+ EditorState.create({+ doc: "value",+ extensions: [lspDoc.of({ doc: 1, path: "/p/1.java", language: "java", uiMode: "Java", readOnly: false })],+ }),+ );await requestNavigation(view, 1, "definition");expect(lspGoto).toHaveBeenCalledTimes(2);});+ it("does not share implementations, whose search streams on its own", async () => {+ const view = editor(1, "java", "value");+ await requestNavigation(view, 1, "implementation");+ await requestNavigation(view, 1, "implementation");+ expect(lspGoto).toHaveBeenCalledTimes(2);+ });+it("does not mix definition with other navigation kinds", async () => {const view = editor();await requestNavigation(view, 10, "definition");diff --git a/src/editor/lsp/configurationNavigation.ts b/src/editor/lsp/configurationNavigation.tsindex cac332369..34a6760b5 100644--- a/src/editor/lsp/configurationNavigation.ts+++ b/src/editor/lsp/configurationNavigation.ts@@ -1,4 +1,7 @@-/** Shared, bounded navigation results for YAML/properties hover and click. */+/**+ * Shared, bounded navigation results per word: the ⌘-hover probe, ⌘-click and ⌘B on one+ * word ask the server once. Each identical request costs a server like jdtls a full search.+ */import type { Text } from "@codemirror/state";import type { EditorView } from "@codemirror/view";import { onEditorEvent } from "@/editor/api";@@ -9,11 +12,13 @@ import { docOf, lspRequest } from "./lsp";import { offsetToPos } from "./positions";// Events provide invalidation; the age limit is a backstop for servers/remote-// file systems which do not report every semantic change. Empty/error responses-// are never retained, since import may still be in progress.+// file systems which do not report every semantic change, and for a request the+// backend never answers (it times out sooner). Empty/error responses are never+// retained, since a server may still be importing or indexing.export const CONFIGURATION_NAVIGATION_MAX_AGE = 30_000;const MAX_ENTRIES = 128;const MAX_LOCATIONS = 4096;+const SHARED_KINDS: ReadonlySet<GotoKind> = new Set(["definition", "declaration", "typeDefinition"]);interface Cached {text: Text;path: string;@@ -23,6 +28,16 @@ interface Cached {pending: Promise<Location[]>;}const results = new Map<string, Cached>();+const editors = new WeakMap<EditorView, number>();+let nextEditor = 0;++function requestKey(view: EditorView, from: number, to: number, kind: GotoKind): string {+ let editor = editors.get(view);+ if (editor === undefined) editors.set(view, (editor = ++nextEditor));+ const doc = docOf(view)!;+ // lspGoto chooses servers in the backend; revision also tracks server lifecycle and routing changes.+ return `${editor}:${doc.doc}:${doc.language}:${revision}:${from}:${to}:${kind}`;+}let revision = 0;export function configurationNavigationRevision(): number {@@ -66,13 +81,13 @@ export function hasConfigurationNavigation(view: EditorView, offset: number): boconst doc = docOf(view);const word = navigationWord(view, offset);if (!doc || !word) return false;- const entry = results.get(`${doc.doc}:${word.from}:${word.to}`);+ const entry = results.get(requestKey(view, word.from, word.to, "definition"));return (!!entry &&entry.size > 0 &&entry.retain &&entry.path === doc.path &&- entry.text.eq(view.state.doc) &&+ entry.text === view.state.doc &&Date.now() - entry.at < CONFIGURATION_NAVIGATION_MAX_AGE);}@@ -80,22 +95,20 @@ export function hasConfigurationNavigation(view: EditorView, offset: number): boexport function requestNavigation(view: EditorView, offset: number, kind: GotoKind): Promise<Location[]> {const doc = docOf(view)!;const word = navigationWord(view, offset);- if (!isConfigurationDocument(view) || kind !== "definition" || !word)+ const config = isConfigurationDocument(view);+ if (!word || !(config ? kind === "definition" : SHARED_KINDS.has(kind)))return lspRequest(() => commands.lspGoto(doc.doc, offsetToPos(view.state.doc, offset), kind));- const key = `${doc.doc}:${word.from}:${word.to}`;+ const key = requestKey(view, word.from, word.to, kind);const text = view.state.doc;const hit = results.get(key);- if (- hit &&- hit.path === doc.path &&- hit.text.eq(text) &&- Date.now() - hit.at < (hit.size ? CONFIGURATION_NAVIGATION_MAX_AGE : 3000)- ) {+ if (hit && hit.path === doc.path && hit.text === text && Date.now() - hit.at < CONFIGURATION_NAVIGATION_MAX_AGE) {results.delete(key);results.set(key, hit);return hit.pending;}const version = revision;+ // Just past a word's end some servers resolve the next token, so the shared answer is asked inside the word.+ const at = config ? word.from : Math.min(offset, word.to - 1);const entry: Cached = {text,path: doc.path,@@ -103,11 +116,11 @@ export function requestNavigation(view: EditorView, offset: number, kind: GotoKisize: 0,retain: true,pending: lspRequest(- () => commands.lspGoto(doc.doc, offsetToPos(text, word.from), kind),- () => revision === version,+ () => commands.lspGoto(doc.doc, offsetToPos(text, at), kind),+ () => revision === version && view.state.doc === text && docOf(view) === doc && view.dom.isConnected,).then((locations) => {- if (revision !== version || !view.state.doc.eq(text))+ if (revision !== version || view.state.doc !== text || docOf(view) !== doc || !view.dom.isConnected)throw new IpcError({ kind: "cancelled", message: "cancelled" });entry.size = locations.length;if ((!locations.length || !entry.retain) && results.get(key) === entry) results.delete(key);diff --git a/src/editor/lsp/hover.ts b/src/editor/lsp/hover.tsindex 6ef7021e4..f69594f39 100644--- a/src/editor/lsp/hover.ts+++ b/src/editor/lsp/hover.ts@@ -22,6 +22,7 @@ import { diagnosticsAt, type PlacedDiagnostic } from "./diagnostics";import { isEmptyMarkup, languageForPath, renderMarkup } from "./markdown";import { selectableText } from "@/ui/selectableText";import { docOf, lspRequest, reportLspError } from "./lsp";+import { requestNavigation } from "./configurationNavigation";import { offsetToPos, rangeToOffsets } from "./positions";import { showHint } from "./hint";import { caretAnchor, focusPopup, openPopup, useLspPopup, type DefinitionTarget, type DocEntry } from "./popupStore";@@ -349,9 +350,12 @@ export async function quickDefinition(view: EditorView, kind: "definition" | "tyconst doc = docOf(view);if (!doc) return;const pos = view.state.selection.main.head;+ const source = view.state.doc;+ const stale = () => !view.dom.isConnected || view.state.doc !== source || docOf(view) !== doc;if (kind === "definition" && showPhpConstructDocumentation(view, pos)) return;try {- const found = await lspRequest(() => commands.lspGoto(doc.doc, offsetToPos(view.state.doc, pos), kind));+ const found = await requestNavigation(view, pos, kind);+ if (stale()) return;const seen = new Set<string>();const locations = found.filter((l) => {const key = `${l.path}:${l.range.start.line}:${l.range.start.col}`;@@ -364,6 +368,7 @@ export async function quickDefinition(view: EditorView, kind: "definition" | "tyconst targets = (await Promise.all(locations.slice(0, MAX_TARGETS).map((l) => definitionTarget(l, doc.uiMode)))).filter((t): t is DefinitionTarget => !!t);+ if (stale()) return;if (!targets.length) {showHint(view, "Cannot read the definition's file");return;@@ -376,6 +381,6 @@ export async function quickDefinition(view: EditorView, kind: "definition" | "tythemeClasses: view.themeClasses,});} catch (e) {- reportLspError(view, e, true);+ if (!stale()) reportLspError(view, e, true);}}diff --git a/src/editor/lsp/navigation.ts b/src/editor/lsp/navigation.tsindex 68183a169..966ba6e70 100644--- a/src/editor/lsp/navigation.ts+++ b/src/editor/lsp/navigation.ts@@ -176,7 +176,7 @@ function nameAt(view: EditorView, offset: number): string | null {* (Java: the project's) while it searches on (the dependencies'), and fills in when it ends.* Closing the chooser cancels the search.*/-function streamedImplementations(view: EditorView, offset: number, onOpen: () => void) {+function streamedImplementations(view: EditorView, offset: number, onOpen: () => void, superseded: () => boolean) {const name = nameAt(view, offset);let current: RequestId | null = null;let finished = false;@@ -190,13 +190,13 @@ function streamedImplementations(view: EditorView, offset: number, onOpen: () =>finished = false;const channel = new Channel<Location[]>();channel.onmessage = (locs) => {- if (finished || opened || current !== request || !locs.length) return;+ if (finished || opened || current !== request || !locs.length || superseded()) return;opened = true;onOpen();first = dedupeLocations(locs);showing = locationItems(first).then((items) => {// All of them arrived meanwhile: shown as usual.- if (finished) {+ if (finished || superseded()) {opened = false;return;}@@ -224,10 +224,10 @@ function streamedImplementations(view: EditorView, offset: number, onOpen: () =>},/** Fills the opened chooser with all of them, after those it shows. */async complete(locs: readonly DeclarationTarget[]) {- if (closed) return;+ if (closed || superseded()) return;const all = dedupeLocations([...first, ...locs]);const items = await locationItems(all);- if (closed) return;+ if (closed || superseded()) return;updatePopup("list", {title: chooserTitle("implementation", name, all.length),items,@@ -253,15 +253,37 @@ const editedAt = new WeakMap<EditorView, number>();* version meanwhile (kotlin-language-server: nothing for ~300 ms after typing).* An empty answer right after an edit is asked again a few times.*/-async function gotoAfterEdits(view: EditorView, request: () => Promise<DeclarationTarget[]>) {+async function gotoAfterEdits(+ view: EditorView,+ request: () => Promise<DeclarationTarget[]>,+ superseded: () => boolean,+) {for (let attempt = 0; ; attempt++) {const locs = await request();- if (locs.length || attempt >= 3 || performance.now() - (editedAt.get(view) ?? -Infinity) > 1500) return locs;+ if (locs.length || attempt >= 3 || superseded() || performance.now() - (editedAt.get(view) ?? -Infinity) > 1500)+ return locs;await new Promise((r) => setTimeout(r, 250));+ if (superseded()) return [];}}+/** The latest go-to gesture per editor; an older one answered later must not navigate or show anything. */+const latestGesture = new WeakMap<EditorView, number>();+const pendingGestureHints = new WeakMap<EditorView, () => void>();+let gestures = 0;+export async function gotoTargets(view: EditorView, kind: GotoKind, at?: number) {+ const gesture = ++gestures;+ latestGesture.set(view, gesture);+ pendingGestureHints.get(view)?.();+ pendingGestureHints.delete(view);+ const source = view.state.doc;+ const context = docOf(view);+ const superseded = () =>+ latestGesture.get(view) !== gesture ||+ !view.dom.isConnected ||+ view.state.doc !== source ||+ docOf(view) !== context;const offset = at ?? view.state.selection.main.head;if (kind === "definition" || kind === "declaration") {const own = contributedAt<ContributedDefinition>(view.state, CONTRIBUTED_DEFINITION, offset);@@ -269,17 +291,20 @@ export async function gotoTargets(view: EditorView, kind: GotoKind, at?: number)if (showPhpConstructDocumentation(view, offset)) return;const before = view.state.doc;const plugin = await contributedNavigation(view, offset).catch(() => null);- if (view.state.doc !== before) return;+ if (view.state.doc !== before || superseded()) return;if (plugin) {if (plugin.targets.length === 1) await navigateTo(plugin.targets[0]!);- else+ else {+ const items = await locationItems(plugin.targets);+ if (superseded()) return;openPopup({kind: "list",anchor: caretAnchor(view, offset),title: tx`Choose Declaration`,- items: await locationItems(plugin.targets),+ items,pin: pinToFind(view.state.sliceDoc(plugin.from, plugin.to), plugin.targets),});+ }return;}}@@ -293,13 +318,15 @@ export async function gotoTargets(view: EditorView, kind: GotoKind, at?: number)let streamed: ReturnType<typeof streamedImplementations> | null = null;try {const done = showPendingHint(view, tx`Finding navigation target…`);- const stream = kind === "implementation" ? streamedImplementations(view, offset, done) : null;+ pendingGestureHints.set(view, done);+ const stream = kind === "implementation" ? streamedImplementations(view, offset, done, superseded) : null;streamed = stream;const request = stream ? () => stream.request(doc.doc, pos) : () => requestNavigation(view, offset, kind);try {- locs = dedupeLocations(await gotoAfterEdits(view, request));+ locs = dedupeLocations(await gotoAfterEdits(view, request, superseded));} finally {done();+ if (pendingGestureHints.get(view) === done) pendingGestureHints.delete(view);}} catch (e) {// The chooser shows the first ones: closing it cancelled the search, or the rest failed.@@ -307,15 +334,21 @@ export async function gotoTargets(view: EditorView, kind: GotoKind, at?: number)await streamed.complete([]);return;}+ if (superseded()) return;if (isCancelled(e) || !declaration) {reportLspError(view, e, true);return;}// Web references and links need no server.- if ((await gotoWebReference(view, doc, pos, offset)) || (await followReferenceAt(view, doc, offset))) return;+ if (+ (await gotoWebReference(view, doc, pos, offset, superseded)) ||+ (await followReferenceAt(view, doc, offset, superseded))+ )+ return;serverDown = isUnavailable(e);// Dumb mode: the server is not ready / failing — answer from the syntax tree.const fb = await gotoFallback(view, doc, pos);+ if (superseded()) return;if (!fb) {reportLspError(view, e, true);return;@@ -327,14 +360,17 @@ export async function gotoTargets(view: EditorView, kind: GotoKind, at?: number)await streamed.complete(locs);return;}+ if (superseded()) return;if (!locs.length) {// The server has no definition here: a link (`href`, `#include`, Markdown) or a file path.if (declaration &&!fromSyntax &&- ((await gotoWebReference(view, doc, pos, offset)) || (await followReferenceAt(view, doc, offset)))+ ((await gotoWebReference(view, doc, pos, offset, superseded)) ||+ (await followReferenceAt(view, doc, offset, superseded))))return;+ if (superseded()) return;// The server only checks this file's syntax: say why instead of just "not found".const reason = serverDown ? null : outsideProjectReason(doc.path);showHint(@@ -349,7 +385,7 @@ export async function gotoTargets(view: EditorView, kind: GotoKind, at?: number)}// IDEA: ⌘B on a declaration shows its usages.if (kind === "definition" && isSelfTarget(locs, doc.path, pos)) {- if (!(await executeAction("find.showUsages"))) showHint(view, "No usages found");+ if (!(await executeAction("find.showUsages")) && !superseded()) showHint(view, "No usages found");return;}if (locs.length === 1) {@@ -357,17 +393,20 @@ export async function gotoTargets(view: EditorView, kind: GotoKind, at?: number)// After the editor applied the navigation's selection (which dismisses hints).if (fromSyntax)setTimeout(() => {+ if (superseded()) return;const target = activeEditor()?.view;if (target) showHint(target, SYNTAX_NOTE, { timeout: 2500 });}, 150);return;}const name = nameAt(view, offset);+ const items = await locationItems(locs);+ if (superseded()) return;openPopup({kind: "list",anchor: caretAnchor(view, offset),title: chooserTitle(kind, name, locs.length, fromSyntax),- items: await locationItems(locs),+ items,pin: pinToFind(name ?? "", locs),});}@@ -381,7 +420,13 @@ const WEB_SIGIL: Record<WebReferenceKind, string> = { class: ".", id: "#", ancho* `var(--x)` to its declarations (no language server resolves these); false* when there is no such reference at `pos`.*/-async function gotoWebReference(view: EditorView, doc: EditorDocContext, pos: Pos, offset: number): Promise<boolean> {+async function gotoWebReference(+ view: EditorView,+ doc: EditorDocContext,+ pos: Pos,+ offset: number,+ superseded: () => boolean,+): Promise<boolean> {if (!WEB_LANGUAGES.has(doc.language) || doc.virtual) return false;let found;try {@@ -391,25 +436,35 @@ async function gotoWebReference(view: EditorView, doc: EditorDocContext, pos: Poconsole.debug("[web] goto", e);return false;}+ if (superseded()) return true;if (!found) return false;const { reference, targets } = found;const label = `${WEB_SIGIL[reference.kind]}${reference.name}`;if (!targets.length) showHint(view, `Cannot find declaration of '${label}'`);else if (targets.length === 1) await navigateTo(targets[0]!);- else+ else {+ const items = await locationItems(targets);+ if (superseded()) return true;openPopup({kind: "list",anchor: caretAnchor(view, offset),title: tx`Choose Declaration of '${label}' (${targets.length} found)`,- items: await locationItems(targets),+ items,pin: pinToFind(label, targets),});+ }return true;}/** Follows the link, URL or file path at `offset`; false when there is none. */-async function followReferenceAt(view: EditorView, doc: EditorDocContext, offset: number): Promise<boolean> {+async function followReferenceAt(+ view: EditorView,+ doc: EditorDocContext,+ offset: number,+ superseded: () => boolean,+): Promise<boolean> {const ref = await referenceAt(view, doc, offset);+ if (superseded()) return true;if (!ref) return false;try {if (ref.kind === "file" && ref.path === doc.path && ref.fragment) {@@ -422,7 +477,7 @@ async function followReferenceAt(view: EditorView, doc: EditorDocContext, offset}await followReference(ref);} catch (e) {- showHint(view, e instanceof Error ? e.message : String(e), { tone: "error" });+ if (!superseded()) showHint(view, e instanceof Error ? e.message : String(e), { tone: "error" });}return true;}diff --git a/src/editor/lsp/navigationMouse.test.ts b/src/editor/lsp/navigationMouse.test.tsindex a02a935b7..d719a3fa5 100644--- a/src/editor/lsp/navigationMouse.test.ts+++ b/src/editor/lsp/navigationMouse.test.ts@@ -25,6 +25,7 @@ vi.mock("@tauri-apps/api/core", async (orig) => ({const { gotoTargets, navigationExtension } = await import("./navigation");const { lspDoc } = await import("./lsp");+const { invalidateConfigurationNavigation } = await import("./configurationNavigation");const { provideEditorService } = await import("@/workbench/contributions");const openFile = vi.fn(async () => {});provideEditorService({ openFile } as never);@@ -35,6 +36,7 @@ let removeAction: () => void;beforeEach(() => {usePlatform.setState({ os: "macos" });resetNavigationModifier();+ invalidateConfigurationNavigation();vi.clearAllMocks();useKeymap.setState({preset: "intellij-macos",diff --git a/src/editor/lsp/navigationPending.test.ts b/src/editor/lsp/navigationPending.test.tsindex b23d90bd4..f07b2ed89 100644--- a/src/editor/lsp/navigationPending.test.ts+++ b/src/editor/lsp/navigationPending.test.ts@@ -27,9 +27,10 @@ vi.mock("@tauri-apps/api/core", async (orig) => ({},}));+const files = await import("./files");const { gotoTargets } = await import("./navigation");const { lspDoc } = await import("./lsp");-const { useLspPopup, closePopup } = await import("./popupStore");+const { useLspPopup, closePopup, openPopup } = await import("./popupStore");const { provideEditorService } = await import("@/workbench/contributions");const openFile = vi.fn(async () => {});provideEditorService({ openFile } as never);@@ -48,6 +49,7 @@ beforeEach(() => {});afterEach(() => {view.destroy();+ vi.restoreAllMocks();vi.useRealTimers();});@@ -143,6 +145,38 @@ describe("Go to Implementation while the search goes on", () => {expect(document.querySelector(".cm-lsp-hint")).toBeNull();});+ it("does not let a superseded implementation search replace a newer popup", async () => {+ const search = slowImplementations();+ const pending = gotoTargets(view, "implementation");+ await vi.waitFor(() => expect(lspGotoImplementation).toHaveBeenCalled());+ search.first([at("/p/Own.java", 3)]);+ await vi.waitFor(() => expect(listPopup()).not.toBeNull());+ lspGoto.mockResolvedValueOnce({ status: "ok", data: [at("/p/New.java", 2)] });+ await gotoTargets(view, "definition");+ openPopup({ kind: "list", anchor: { x: 0, y: 0 }, title: "Newer popup", items: [] });+ search.resolve({ status: "ok", data: [at("/p/Old.java", 8)] });+ await pending;+ expect(listPopup()?.title).toBe("Newer popup");+ });++ it("does not open a superseded chooser after its previews finish loading", async () => {+ let finish!: (files: Map<string, string[]>) => void;+ vi.spyOn(files, "readManyFileLines").mockImplementationOnce(() => new Promise((r) => (finish = r)));+ const search = slowImplementations();+ const pending = gotoTargets(view, "implementation");+ await vi.waitFor(() => expect(lspGotoImplementation).toHaveBeenCalled());+ search.first([at("/p/Own.java", 3)]);+ lspGoto.mockResolvedValueOnce({ status: "ok", data: [at("/p/New.java", 2)] });+ await gotoTargets(view, "definition");+ openPopup({ kind: "list", anchor: { x: 0, y: 0 }, title: "Newer popup", items: [] });+ finish(new Map());+ await vi.advanceTimersByTimeAsync(0);+ expect(listPopup()?.title).toBe("Newer popup");+ search.resolve({ status: "ok", data: [at("/p/Old.java", 8)] });+ await pending;+ expect(listPopup()?.title).toBe("Newer popup");+ });+it("goes to the only implementation when none came first", async () => {const search = slowImplementations();const pending = gotoTargets(view, "implementation");diff --git a/src/editor/lsp/navigationShared.test.ts b/src/editor/lsp/navigationShared.test.tsnew file mode 100644index 000000000..0f4f88bcb--- /dev/null+++ b/src/editor/lsp/navigationShared.test.ts@@ -0,0 +1,277 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { EditorState } from "@codemirror/state";+import { EditorView } from "@codemirror/view";+import type { commands, Location } from "@/platform/ipc";+import { usePlatform } from "@/platform/platformInfo";+import { resetNavigationModifier } from "@/platform/navigationModifier";++type GotoResult = Awaited<ReturnType<typeof commands.lspGoto>>;+const { lspGoto, lspHover, lspDocumentLinks } = vi.hoisted(() => ({+ lspGoto: vi.fn<typeof commands.lspGoto>(),+ lspHover: vi.fn<typeof commands.lspHover>(async () => ({ status: "ok", data: null })),+ lspDocumentLinks: vi.fn<typeof commands.lspDocumentLinks>(async () => ({ status: "ok", data: [] })),+}));+vi.mock("@/platform/ipc", async (orig) => {+ const real = await orig<typeof import("@/platform/ipc")>();+ return { ...real, isTauri: () => true, commands: { ...real.commands, lspGoto, lspHover, lspDocumentLinks } };+});++const { gotoTargets, navigationExtension } = await import("./navigation");+const { lspDoc } = await import("./lsp");+const { quickDefinition } = await import("./hover");+const { invalidateConfigurationNavigation } = await import("./configurationNavigation");+const { closePopup } = await import("./popupStore");+const { provideEditorService } = await import("@/workbench/contributions");+const openFile = vi.fn(async (_path: string, _opts: unknown) => {});+provideEditorService({ openFile } as never);++const loc = (path: string): Location => ({+ path,+ uri: null,+ range: { start: { line: 1, col: 2 }, end: { line: 1, col: 5 } },+});+const ok = (data: Location[]): GotoResult => ({ status: "ok", data });++/** A request the test answers when it wants to, in any order. */+function deferred() {+ let resolve!: (r: GotoResult) => void;+ lspGoto.mockImplementationOnce(() => new Promise((r) => (resolve = r)));+ return (r: GotoResult) => resolve(r);+}++// `word` is where the hover probe asks (the word's start), `inside` another position in that word.+const cases = [+ { language: "java", path: "/p/Main.java", text: "service.run(); other.call();", word: 8, inside: 10, other: 21 },+ { language: "typescript", path: "/p/main.ts", text: "service.run(); other.call();", word: 8, inside: 10, other: 21 },+ {+ language: "yaml",+ path: "/p/app.yaml",+ text: "server:\n port: 8080\n host: x\n",+ word: 10,+ inside: 12,+ other: 23,+ },+];++let view: EditorView;+function editor(c: (typeof cases)[number]) {+ view = new EditorView({+ state: EditorState.create({+ doc: c.text,+ extensions: [+ lspDoc.of({ doc: 1, path: c.path, language: c.language, uiMode: c.language, readOnly: false }),+ navigationExtension(),+ ],+ }),+ parent: document.body,+ });+ return view;+}++function hover(pos: number) {+ vi.spyOn(view, "posAtCoords").mockReturnValue(pos);+ view.contentDOM.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, metaKey: true }));+}++function click(pos: number) {+ vi.spyOn(view, "posAtCoords").mockReturnValue(pos);+ view.contentDOM.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true, metaKey: true }));+}++const settle = () => new Promise((r) => setTimeout(r, 20));++beforeEach(() => {+ usePlatform.setState({ os: "macos" });+ resetNavigationModifier();+ invalidateConfigurationNavigation();+ lspGoto.mockReset().mockResolvedValue(ok([loc("/p/Target.java")]));+ lspHover.mockClear();+ openFile.mockClear();+});+afterEach(() => {+ view.destroy();+ closePopup();+ document.body.replaceChildren();+ resetNavigationModifier();+ vi.useRealTimers();+ vi.restoreAllMocks();+});++describe.each(cases)("shared definition requests in $language", (c) => {+ it("lets a click reuse the hover probe's request for the same word", async () => {+ editor(c);+ hover(c.word);+ await vi.waitFor(() => expect(view.dom.querySelector(".cm-lsp-link")).not.toBeNull());+ click(c.inside);+ await vi.waitFor(() => expect(openFile).toHaveBeenCalledOnce());+ expect(lspGoto).toHaveBeenCalledOnce();+ });++ it("lets a click share a hover probe that is still running", async () => {+ editor(c);+ const finish = deferred();+ hover(c.word);+ await vi.waitFor(() => expect(lspGoto).toHaveBeenCalledOnce());+ click(c.inside);+ await settle();+ finish(ok([loc("/p/Target.java")]));+ await vi.waitFor(() => expect(openFile).toHaveBeenCalledOnce());+ expect(lspGoto).toHaveBeenCalledOnce();+ });++ it("sends one request for rapid clicks on one word and navigates once", async () => {+ editor(c);+ const finish = deferred();+ const clicks = [+ gotoTargets(view, "definition", c.inside),+ gotoTargets(view, "definition", c.word),+ gotoTargets(view, "definition", c.inside),+ ];+ await settle();+ finish(ok([loc("/p/Target.java")]));+ await Promise.all(clicks);+ expect(lspGoto).toHaveBeenCalledOnce();+ expect(openFile).toHaveBeenCalledOnce();+ });++ it("navigates for the latest click even when an earlier one answers later", async () => {+ editor(c);+ const first = deferred();+ const second = deferred();+ const earlier = gotoTargets(view, "definition", c.inside);+ await vi.waitFor(() => expect(lspGoto).toHaveBeenCalledOnce());+ const later = gotoTargets(view, "definition", c.other);+ await vi.waitFor(() => expect(lspGoto).toHaveBeenCalledTimes(2));+ second(ok([loc("/p/Later.java")]));+ await later;+ first(ok([loc("/p/Earlier.java")]));+ await earlier;+ expect(openFile.mock.calls.map(([path]) => path)).toEqual(["/p/Later.java"]);+ });++ it("does not show an older click's hint after a newer one", async () => {+ editor(c);+ const first = deferred();+ const earlier = gotoTargets(view, "definition", c.inside);+ await vi.waitFor(() => expect(lspGoto).toHaveBeenCalledOnce());+ await gotoTargets(view, "definition", c.other);+ first(ok([]));+ await earlier;+ expect(document.querySelector(".cm-lsp-hint")).toBeNull();+ });++ it("does not show progress for an older request after the newer gesture finishes", async () => {+ editor(c);+ const finish = deferred();+ vi.useFakeTimers();+ const earlier = gotoTargets(view, "definition", c.inside);+ await vi.advanceTimersByTimeAsync(0);+ await gotoTargets(view, "definition", c.other);+ await vi.advanceTimersByTimeAsync(300);+ expect(document.querySelector(".cm-lsp-hint")).toBeNull();+ finish(ok([loc("/p/Stale.java")]));+ await earlier;+ expect(openFile).toHaveBeenCalledOnce();+ });++ it("asks again after an edit between hover and click", async () => {+ editor(c);+ hover(c.word);+ await vi.waitFor(() => expect(view.dom.querySelector(".cm-lsp-link")).not.toBeNull());+ view.dispatch({ changes: { from: view.state.doc.length, insert: "\n" } });+ await gotoTargets(view, "definition", c.inside);+ expect(lspGoto).toHaveBeenCalledTimes(2);+ });++ it("does not navigate when the document changes while a request is running", async () => {+ editor(c);+ const finish = deferred();+ const pending = gotoTargets(view, "definition", c.inside);+ await vi.waitFor(() => expect(lspGoto).toHaveBeenCalledOnce());+ view.dispatch({ changes: { from: view.state.doc.length, insert: "\n" } });+ finish(ok([loc("/p/Stale.java")]));+ await pending;+ expect(openFile).not.toHaveBeenCalled();+ });++ it("does not retry an older gesture superseded during its edit backoff", async () => {+ editor(c);+ vi.useFakeTimers();+ view.dispatch({ changes: { from: view.state.doc.length, insert: "\n" } });+ lspGoto.mockResolvedValueOnce(ok([]));+ const earlier = gotoTargets(view, "definition", c.inside);+ await vi.advanceTimersByTimeAsync(0);+ await gotoTargets(view, "definition", c.other);+ await vi.advanceTimersByTimeAsync(250);+ await earlier;+ expect(lspGoto).toHaveBeenCalledTimes(2);+ expect(openFile).toHaveBeenCalledOnce();+ });++ it("does not keep an empty answer", async () => {+ editor(c);+ lspGoto.mockResolvedValueOnce(ok([]));+ await gotoTargets(view, "definition", c.inside);+ await gotoTargets(view, "definition", c.inside);+ expect(lspGoto).toHaveBeenCalledTimes(2);+ expect(openFile).toHaveBeenCalledOnce();+ });++ it("does not keep a failed request", async () => {+ editor(c);+ lspGoto.mockResolvedValueOnce({ status: "error", error: { kind: "protocol", message: "boom" } });+ await gotoTargets(view, "definition", c.inside);+ await gotoTargets(view, "definition", c.inside);+ expect(lspGoto).toHaveBeenCalledTimes(2);+ expect(openFile).toHaveBeenCalledOnce();+ });++ it("re-probes a slow word through the running request", async () => {+ editor(c);+ const finish = deferred();+ vi.useFakeTimers();+ hover(c.word);+ await vi.advanceTimersByTimeAsync(3001);+ hover(c.word);+ await vi.advanceTimersByTimeAsync(0);+ expect(lspGoto).toHaveBeenCalledOnce();+ vi.useRealTimers();+ finish(ok([loc("/p/Target.java")]));+ await vi.waitFor(() => expect(view.dom.querySelector(".cm-lsp-link")).not.toBeNull());+ expect(lspGoto).toHaveBeenCalledOnce();+ });+});++describe("shared request keys", () => {+ const java = cases[0]!;++ it("lets Quick Definition reuse the hover probe's request", async () => {+ editor(java);+ hover(java.word);+ await vi.waitFor(() => expect(view.dom.querySelector(".cm-lsp-link")).not.toBeNull());+ view.dispatch({ selection: { anchor: java.inside } });+ await quickDefinition(view);+ expect(lspGoto).toHaveBeenCalledOnce();+ });++ it("keeps navigation kinds apart", async () => {+ editor(java);+ await gotoTargets(view, "definition", java.inside);+ await gotoTargets(view, "typeDefinition", java.inside);+ await gotoTargets(view, "typeDefinition", java.word);+ expect(lspGoto.mock.calls.map(([, , kind]) => kind)).toEqual(["definition", "typeDefinition"]);+ });++ it("asks a click right after a word's last character from inside the word", async () => {+ editor(java);+ await gotoTargets(view, "definition", java.word + 3);+ expect(lspGoto).toHaveBeenCalledExactlyOnceWith(1, { line: 0, col: java.word + 2 }, "definition");+ });++ it("asks positions outside any word directly", async () => {+ editor(java);+ await gotoTargets(view, "definition", 14);+ await gotoTargets(view, "definition", 14);+ expect(lspGoto).toHaveBeenCalledTimes(2);+ });+});diff --git a/src/editor/lsp/syntaxFallback.test.ts b/src/editor/lsp/syntaxFallback.test.tsindex 05c467752..1ebba79d0 100644--- a/src/editor/lsp/syntaxFallback.test.ts+++ b/src/editor/lsp/syntaxFallback.test.ts@@ -327,6 +327,7 @@ describe("navigation wiring", () => {expect(openFile).toHaveBeenCalledWith(target.path, { selection: target.range.start, focus: true });expect(cmd.syntaxLocals).not.toHaveBeenCalled();expect(cmd.syntaxNodeAt).not.toHaveBeenCalled();+ invalidateConfigurationNavigation();cmd.lspGoto.mockReturnValueOnce(ok([]));await gotoTargets(view, "definition");expect(openFile).toHaveBeenCalledOnce();@@ -803,7 +804,7 @@ describe("modifier-hover navigation recovery", () => {expect(cmd.lspGoto).toHaveBeenCalledTimes(2);});- it("retries a stuck configuration probe without retaining the late response", async () => {+ it("re-probes a stuck configuration lookup through the running request, without retaining its empty answer", async () => {let finish!: (value: Awaited<R<unknown>>) => void;cmd.lspGoto.mockReturnValueOnce(new Promise((resolve) => {@@ -815,16 +816,16 @@ describe("modifier-hover navigation recovery", () => {try {move(view, 1);await vi.advanceTimersByTimeAsync(3001);- cmd.lspGoto.mockReturnValueOnce(ok([target]));move(view, 1);await vi.advanceTimersByTimeAsync(0);- expect(cmd.lspGoto).toHaveBeenCalledTimes(2);+ expect(cmd.lspGoto).toHaveBeenCalledOnce();} finally {vi.useRealTimers();}- await vi.waitFor(() => expect(view.dom.querySelector(".cm-lsp-link")).not.toBeNull());finish({ status: "ok", data: [] });await new Promise((resolve) => setTimeout(resolve, 20));+ expect(view.dom.querySelector(".cm-lsp-link")).toBeNull();+ cmd.lspGoto.mockReturnValueOnce(ok([target]));await gotoTargets(view, "definition", 1);expect(cmd.lspGoto).toHaveBeenCalledTimes(2);expect(openFile).toHaveBeenCalledOnce();@@ -852,7 +853,7 @@ describe("modifier-hover navigation recovery", () => {expect(cmd.lspGoto).toHaveBeenCalledTimes(2);});- it("retries a stuck probe and ignores its eventual response", async () => {+ it("re-probes a stuck word through the running request", async () => {let finish!: (value: Awaited<R<unknown>>) => void;cmd.lspGoto.mockReturnValueOnce(new Promise((resolve) => {@@ -864,17 +865,15 @@ describe("modifier-hover navigation recovery", () => {try {move(view);await vi.advanceTimersByTimeAsync(3001);- cmd.lspGoto.mockReturnValueOnce(ok([target]));move(view);await vi.advanceTimersByTimeAsync(0);- expect(cmd.lspGoto).toHaveBeenCalledTimes(2);+ expect(cmd.lspGoto).toHaveBeenCalledOnce();} finally {vi.useRealTimers();}+ finish(await ok([target]));await vi.waitFor(() => expect(view.dom.querySelector(".cm-lsp-link")?.textContent).toBe("foo"));- finish({ status: "ok", data: [] });- await new Promise((resolve) => setTimeout(resolve, 20));- expect(view.dom.querySelector(".cm-lsp-link")?.textContent).toBe("foo");+ expect(cmd.lspGoto).toHaveBeenCalledOnce();});it("ignores a late probe after moving to a different word", async () => {