diff --git a/e2e/inlayRequests.fixture.ts b/e2e/inlayRequests.fixture.ts
new file mode 100644
index 000000000..58c306679
--- /dev/null
+++ b/e2e/inlayRequests.fixture.ts
@@ -0,0 +1,43 @@
+import { EditorView } from "@codemirror/view";
+import { commands, type InlayHint, type Range } from "../src/platform/ipc";
+import { setInvokeRoute } from "../src/platform/tauriCore";
+import { lspDoc } from "../src/editor/lsp/lsp";
+import { inlayExtension } from "../src/editor/lsp/inlay";
+import { lspTheme } from "../src/editor/lsp/theme";
+
+const requests: { range: Range; resolve: (hints: InlayHint[]) => void }[] = [];
+setInvokeRoute(() => null);
+commands.lspInlayHints = async (_doc, range) =>
+ new Promise((resolve) => requests.push({ range, resolve: (data) => resolve({ status: "ok", data }) }));
+
+const view = new EditorView({
+ parent: document.body,
+ doc: Array.from({ length: 2000 }, (_, i) => `let item${i} = value;`).join("\n"),
+ extensions: [
+ EditorView.theme({ "&": { height: "400px" }, ".cm-scroller": { overflow: "auto" } }),
+ lspTheme,
+ lspDoc.of({ doc: 1, path: "demo.rs", language: "rust", uiMode: "Rust", readOnly: false }),
+ inlayExtension(),
+ ],
+});
+
+Object.assign(window, {
+ inlayTest: {
+ count: () => requests.length,
+ resolve(index: number) {
+ const request = requests[index]!;
+ request.resolve([
+ {
+ position: { line: request.range.start.line + 1, col: 4 },
+ label: `hint-${index}`,
+ kind: "type",
+ paddingLeft: false,
+ paddingRight: false,
+ tooltip: null,
+ parts: [],
+ },
+ ]);
+ },
+ destroy: () => view.destroy(),
+ },
+});
diff --git a/e2e/inlayRequests.html b/e2e/inlayRequests.html
new file mode 100644
index 000000000..d8014e572
--- /dev/null
+++ b/e2e/inlayRequests.html
@@ -0,0 +1,9 @@
+
+
+
+
+
+
+
+
+
diff --git a/e2e/inlayRequests.spec.ts b/e2e/inlayRequests.spec.ts
new file mode 100644
index 000000000..04b0d8f79
--- /dev/null
+++ b/e2e/inlayRequests.spec.ts
@@ -0,0 +1,18 @@
+import { expect, test } from "@playwright/test";
+
+type Probe = { count(): number; resolve(index: number): void };
+
+test("scrolling does not let an old viewport response replace current inlay hints", async ({ page }) => {
+ await page.goto("/e2e/inlayRequests.html");
+ const count = () => page.evaluate(() => (window as unknown as { inlayTest: Probe }).inlayTest.count());
+ await expect.poll(count).toBe(1);
+ await page.locator(".cm-scroller").evaluate((el) => {
+ el.scrollTop = 12000;
+ });
+ await expect.poll(count).toBe(2);
+ await page.evaluate(() => (window as unknown as { inlayTest: Probe }).inlayTest.resolve(1));
+ await expect(page.locator(".cm-lsp-inlay")).toHaveText("hint-1");
+ await page.evaluate(() => (window as unknown as { inlayTest: Probe }).inlayTest.resolve(0));
+ await page.waitForTimeout(500);
+ await expect(page.locator(".cm-lsp-inlay")).toHaveText("hint-1");
+});
diff --git a/src/editor/lsp/inlay.ts b/src/editor/lsp/inlay.ts
index 5b8c16a47..5de84bdaa 100644
--- a/src/editor/lsp/inlay.ts
+++ b/src/editor/lsp/inlay.ts
@@ -159,7 +159,8 @@ function shownKind(kind: InlayHint["kind"]): boolean {
const inlayPlugin = ViewPlugin.fromClass(
class {
- private refresh = debounce(() => void this.run(), 400);
+ private generation = 0;
+ private schedule = debounce(() => void this.run(), 400);
private unsubscribe: () => void;
private offReady: () => void;
private offSettled: () => void;
@@ -185,6 +186,10 @@ const inlayPlugin = ViewPlugin.fromClass(
update(u: ViewUpdate) {
if (u.docChanged || u.viewportChanged || (this.skipped && shownAgain(u))) this.refresh();
}
+ private refresh() {
+ this.generation++;
+ this.schedule();
+ }
async run() {
const view = this.view;
this.skipped = !view.dom.isConnected;
@@ -204,12 +209,17 @@ const inlayPlugin = ViewPlugin.fromClass(
return;
}
const state = view.state;
+ const generation = this.generation;
+ const wanted = () => generation === this.generation && view.state.doc === state.doc;
const { from, to } = view.viewport;
const first = state.doc.lineAt(from).from;
const last = state.doc.lineAt(to).to;
try {
- const hints = await lspRequest(() => commands.lspInlayHints(doc.doc, offsetsToRange(state.doc, first, last)));
- if (view.state.doc !== state.doc) return this.refresh();
+ const hints = await lspRequest(
+ () => commands.lspInlayHints(doc.doc, offsetsToRange(state.doc, first, last)),
+ wanted,
+ );
+ if (!wanted()) return;
const fresh = hints.filter((h) => shownKind(h.kind));
// A busy server (indexing, loading a build) can answer with nothing: keep the
// hints shown until it settles, instead of blinking them away and reflowing
@@ -220,11 +230,12 @@ const inlayPlugin = ViewPlugin.fromClass(
effects: setInlays.of(inlayDecorations(view, fresh)),
});
} catch (e) {
- if (isUnavailable(e)) inlayBackoff.mark(doc.doc);
+ if (wanted() && isUnavailable(e)) inlayBackoff.mark(doc.doc);
}
}
destroy() {
- this.refresh.cancel();
+ this.generation++;
+ this.schedule.cancel();
this.unsubscribe();
this.offReady();
this.offSettled();
diff --git a/src/editor/lsp/inlayRequests.test.ts b/src/editor/lsp/inlayRequests.test.ts
new file mode 100644
index 000000000..d32f2e66d
--- /dev/null
+++ b/src/editor/lsp/inlayRequests.test.ts
@@ -0,0 +1,184 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { EditorState } from "@codemirror/state";
+import { EditorView } from "@codemirror/view";
+import { _addEditor, _removeEditor, documentSynced, viewShown } from "@/editor/api";
+import type { InlayHint } from "@/bindings";
+
+const ipc = vi.hoisted(() => ({ lspInlayHints: vi.fn() }));
+vi.mock("@/platform/ipc", async (orig) => {
+ const real = await orig();
+ return { ...real, isTauri: () => true, commands: { ...real.commands, ...ipc } };
+});
+const { inlayExtension } = await import("./inlay");
+const { lspDoc } = await import("./lsp");
+const { useProject } = await import("@/platform/project");
+const { emitLocalIdeEvent } = await import("@/platform/ipc");
+const views: EditorView[] = [];
+const ok = (label: string) => ({
+ status: "ok" as const,
+ data: [
+ {
+ position: { line: 0, col: 5 },
+ label,
+ kind: "type",
+ parts: [],
+ paddingLeft: false,
+ paddingRight: false,
+ tooltip: null,
+ },
+ ] as InlayHint[],
+});
+function deferred() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise((r) => (resolve = r));
+ return { promise, resolve };
+}
+const ctx = { doc: 71, path: "/p/a.rs", language: "rust", uiMode: "Rust", readOnly: false };
+function editor(sync?: () => Promise) {
+ const view = new EditorView({
+ state: EditorState.create({
+ doc: "let x = 1;",
+ extensions: [lspDoc.of(ctx), ...(sync ? [documentSynced.of(sync)] : []), inlayExtension()],
+ }),
+ parent: document.body,
+ });
+ views.push(view);
+ return view;
+}
+const labels = (view: EditorView) => [...view.dom.querySelectorAll(".cm-lsp-inlay")].map((e) => e.textContent);
+beforeEach(() => {
+ vi.useFakeTimers();
+ ipc.lspInlayHints.mockReset().mockResolvedValue(ok("current"));
+ useProject.setState({ settings: { editor: { inlayHints: true } } as never });
+});
+afterEach(() => {
+ views.splice(0).forEach((v) => v.destroy());
+ useProject.setState({ settings: null });
+ vi.useRealTimers();
+});
+describe("inlay request lifetime", () => {
+ it("does not restore hints after they were disabled", async () => {
+ const old = deferred>();
+ ipc.lspInlayHints.mockReturnValueOnce(old.promise);
+ const view = editor();
+ await vi.advanceTimersByTimeAsync(400);
+ useProject.setState({ settings: { editor: { inlayHints: false } } as never });
+ await vi.advanceTimersByTimeAsync(400);
+ old.resolve(ok("stale"));
+ await vi.advanceTimersByTimeAsync(1);
+ expect(labels(view)).toEqual([]);
+ });
+ it("does not overwrite a newer server refresh with an older response", async () => {
+ const old = deferred>();
+ ipc.lspInlayHints.mockReturnValueOnce(old.promise);
+ const view = editor();
+ await vi.advanceTimersByTimeAsync(400);
+ emitLocalIdeEvent({ type: "lspRefresh", kind: "inlayHints", server: 1 });
+ await vi.advanceTimersByTimeAsync(400);
+ expect(labels(view)).toEqual(["current"]);
+ old.resolve(ok("stale"));
+ await vi.advanceTimersByTimeAsync(1);
+ expect(labels(view)).toEqual(["current"]);
+ });
+});
+
+describe("obsolete inlay work", () => {
+ it("invalidates immediately, before the next debounced request starts", async () => {
+ const old = deferred>();
+ ipc.lspInlayHints.mockReturnValueOnce(old.promise);
+ const view = editor();
+ await vi.advanceTimersByTimeAsync(400);
+ emitLocalIdeEvent({ type: "lspRefresh", kind: "inlayHints", server: 1 });
+ old.resolve(ok("stale"));
+ await vi.advanceTimersByTimeAsync(1);
+ expect(labels(view)).toEqual([]);
+ await vi.advanceTimersByTimeAsync(399);
+ expect(labels(view)).toEqual(["current"]);
+ });
+ it("does not dispatch a response into a destroyed editor", async () => {
+ const old = deferred>();
+ ipc.lspInlayHints.mockReturnValueOnce(old.promise);
+ const view = editor();
+ await vi.advanceTimersByTimeAsync(400);
+ view.destroy();
+ views.splice(views.indexOf(view), 1);
+ const dispatch = vi.spyOn(view, "dispatch");
+ old.resolve(ok("stale"));
+ await vi.advanceTimersByTimeAsync(400);
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+ it("does not send obsolete requests after waiting for document synchronization", async () => {
+ const synced = deferred();
+ const view = editor(() => synced.promise);
+ const handle = { view, ctx };
+ _addEditor(handle);
+ try {
+ await vi.advanceTimersByTimeAsync(400);
+ expect(ipc.lspInlayHints).not.toHaveBeenCalled();
+ view.destroy();
+ views.splice(views.indexOf(view), 1);
+ synced.resolve();
+ await vi.advanceTimersByTimeAsync(400);
+ expect(ipc.lspInlayHints).not.toHaveBeenCalled();
+ } finally {
+ _removeEditor(handle);
+ }
+ });
+});
+
+describe("retained editors", () => {
+ it("keeps an in-flight response when the editor is detached then shown again", async () => {
+ const pending = deferred>();
+ ipc.lspInlayHints.mockReturnValueOnce(pending.promise);
+ const view = editor();
+ await vi.advanceTimersByTimeAsync(400);
+ view.dom.remove();
+ pending.resolve(ok("retained"));
+ await vi.advanceTimersByTimeAsync(1);
+ document.body.append(view.dom);
+ view.dispatch({ effects: viewShown.of(null) });
+ await vi.advanceTimersByTimeAsync(400);
+ expect(labels(view)).toEqual(["retained"]);
+ });
+ it("keeps work waiting for document synchronization when detached then shown again", async () => {
+ const synced = deferred();
+ const view = editor(() => synced.promise);
+ const handle = { view, ctx };
+ _addEditor(handle);
+ try {
+ await vi.advanceTimersByTimeAsync(400);
+ expect(ipc.lspInlayHints).not.toHaveBeenCalled();
+ view.dom.remove();
+ synced.resolve();
+ await vi.advanceTimersByTimeAsync(1);
+ document.body.append(view.dom);
+ view.dispatch({ effects: viewShown.of(null) });
+ await vi.advanceTimersByTimeAsync(400);
+ expect(labels(view)).toEqual(["current"]);
+ } finally {
+ _removeEditor(handle);
+ }
+ });
+});
+
+describe("settled refresh request lifetime", () => {
+ it.each([true, false])("rejects old busy answers after a settled refresh (empty=%s)", async (empty) => {
+ const view = editor();
+ await vi.advanceTimersByTimeAsync(400);
+ expect(labels(view)).toEqual(["current"]);
+ const old = deferred>();
+ ipc.lspInlayHints.mockReturnValueOnce(old.promise);
+ emitLocalIdeEvent({ type: "languageServer", server: 91, name: "rust-analyzer", status: "busy", message: null });
+ emitLocalIdeEvent({ type: "lspRefresh", kind: "inlayHints", server: 91 });
+ await vi.advanceTimersByTimeAsync(1600);
+ const settled = empty ? { status: "ok" as const, data: [] } : ok("settled");
+ ipc.lspInlayHints.mockResolvedValue(settled);
+ emitLocalIdeEvent({ type: "languageServer", server: 91, name: "rust-analyzer", status: "ready", message: null });
+ // Settling invalidates immediately, not only after the debounce delay.
+ old.resolve(ok("stale busy"));
+ await vi.advanceTimersByTimeAsync(1);
+ expect(labels(view)).toEqual(["current"]);
+ await vi.advanceTimersByTimeAsync(399);
+ expect(labels(view)).toEqual(empty ? [] : ["settled"]);
+ });
+});