perf(editor): let Alt+Enter and refactorings go before Code Vision usage counts (#6560)

Code Vision usage counts run project-wide searches on the same language server and only gave way to Go to Declaration, so Alt+Enter, Refactor menu actions, Refactor This, code actions by kind and Apply Quick Fix queued behind them on a busy server (jdtls on a large project).

The foreground mark now covers every request the user waits for: those requests mark themselves while they ask the server, and the usage counts and implementation gutter markers cancel in-flight work and resume afterwards. Refactor menu actions show a pending hint while the server is busy.

Refs #6381

Co-authored-by: bertyhell <[email protected]>
Цей коміт міститься в:
Bert Verhelstтаbertyhell authored and GitHub committed 2026-11-28 02:20:06 +08:00
1 джерело cead5f08f7
коміт d31a22b5dd
13 files changed
+253 -45

No files matched your search

+5 -5
Переглянути файл
@@ -40,7 +40,7 @@ vi.mock("@tauri-apps/api/core", async (orig) => ({
}));
const { lensTargets, usagesLensExtension } = await import("./codeLens");
const { navigationStarted } = await import("./foreground");
const { foregroundStarted } = await import("./foreground");
const { lspDoc } = await import("./lsp");
const { useProject } = await import("@/platform/project");
const { emitLocalIdeEvent } = await import("@/platform/ipc");
@@ -472,13 +472,13 @@ describe("background usage counts", () => {
expect(ipc.lspReferences).toHaveBeenCalledTimes(4);
});
it("gives way to Go to Declaration: cancels in-flight counts and asks again once it is done", async () => {
it("gives way to a request the user waits for: cancels in-flight counts and asks again once it is done", async () => {
const pending = deferred<ReturnType<typeof refs>>();
ipc.lspReferences.mockReturnValueOnce(pending.promise);
const view = editor();
await settle();
const request = ipc.lspReferences.mock.calls[0]![0];
const done = navigationStarted();
const done = foregroundStarted();
expect(ipc.cancelRequest).toHaveBeenCalledWith(request);
pending.resolve(refs(99));
await settle();
@@ -489,8 +489,8 @@ describe("background usage counts", () => {
expect(titles(view)).toEqual(["2 usages"]);
});
it("starts no counts while a navigation runs", async () => {
const done = navigationStarted();
it("starts no counts while a request the user waits for runs", async () => {
const done = foregroundStarted();
const view = editor();
await settle();
expect(ipc.lspReferences).not.toHaveBeenCalled();
+9 -8
Переглянути файл
@@ -31,7 +31,7 @@ import { dedupeLocations } from "./navigation";
import { overriddenMethods, overriddenReferences, type OutlineCache } from "./overriddenReferences";
import { posToOffset } from "./positions";
import { featureBackoff, onLspRefresh, onServerSettled } from "./availability";
import { isNavigating, onNavigation } from "./foreground";
import { inForeground, onForeground } from "./foreground";
import { editorPrefs } from "@/platform/editorSettings";
import { authorLabel, authorSummary, authorTooltip, blameFor, onBlameInvalidated } from "./authorLens";
import { tx } from "@/platform/i18n";
@@ -184,7 +184,7 @@ class UsagesLensPlugin {
private offChanges: () => void;
private offNavigation: () => void;
private skipped = false;
/** A pass was cut short or held back by a navigation, and runs once it is done. */
/** A pass was cut short or held back by a foreground request, and runs once it is done. */
private yielded = false;
constructor(private view: EditorView) {
@@ -201,10 +201,11 @@ class UsagesLensPlugin {
this.refresh();
});
this.offBlame = onBlameInvalidated(() => this.refresh());
// Go to Declaration and the like go first: counts search the whole project on the same
// server, so in-flight ones are cancelled and asked again once the navigation is done.
this.offNavigation = onNavigation((navigating) => {
if (navigating) {
// Requests the user waits for go first (Go to Declaration, ⌥↵, a refactoring): counts search
// the whole project on the same server, so in-flight ones are cancelled and asked again once
// the user's request is done.
this.offNavigation = onForeground((foreground) => {
if (foreground) {
if (!this.pending.size) return;
this.cancel();
this.yielded = true;
@@ -271,7 +272,7 @@ class UsagesLensPlugin {
if (this.skipped) return;
const doc = docOf(view);
if (!doc) return;
if (isNavigating()) {
if (inForeground()) {
this.yielded = true;
return;
}
@@ -312,7 +313,7 @@ class UsagesLensPlugin {
// A base file is outlined once per pass, however many of its methods are overridden here.
const outlines: OutlineCache = new Map([[doc.path, Promise.resolve(this.outline.items)]]);
for (let i = 0; i < todo.length && !unavailable; i += CONCURRENCY) {
if (isNavigating()) {
if (inForeground()) {
this.yielded = true;
return;
}
+18 -9
Переглянути файл
@@ -1,19 +1,28 @@
import { describe, expect, it } from "vitest";
import { isNavigating, navigationStarted, onNavigation } from "./foreground";
import { foreground, foregroundStarted, inForeground, onForeground } from "./foreground";
describe("navigation before background requests", () => {
it("reports the first navigation starting and the last one finishing", () => {
describe("requests the user waits for before background requests", () => {
it("reports the first foreground request 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);
const off = onForeground((n) => seen.push(n));
const a = foregroundStarted();
const b = foregroundStarted();
expect(inForeground()).toBe(true);
a();
a();
expect(isNavigating()).toBe(true);
expect(inForeground()).toBe(true);
b();
expect(isNavigating()).toBe(false);
expect(inForeground()).toBe(false);
expect(seen).toEqual([true, false]);
off();
});
it("runs a request in the foreground until it settles, also when it fails", async () => {
let fail!: (e: Error) => void;
const running = foreground(() => new Promise((_, reject) => (fail = reject)));
expect(inForeground()).toBe(true);
fail(new Error("boom"));
await expect(running).rejects.toThrow("boom");
expect(inForeground()).toBe(false);
});
});
+19 -9
Переглянути файл
@@ -1,23 +1,23 @@
/**
* 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.
* Requests the user is waiting for (Go to Declaration, ⌥↵, a refactoring, a quick fix) go before
* background requests: Code Vision usage counts and the gutter markers cancel what they asked and
* wait until the user's request is done, so the server answers it first.
*/
let running = 0;
const listeners = new Set<(navigating: boolean) => void>();
const listeners = new Set<(foreground: boolean) => void>();
export function isNavigating(): boolean {
export function inForeground(): boolean {
return running > 0;
}
/** Subscribes to navigation starting (`true`) and the last one finishing (`false`). */
export function onNavigation(listener: (navigating: boolean) => void): () => void {
/** Subscribes to a foreground request starting (`true`) and the last one finishing (`false`). */
export function onForeground(listener: (foreground: 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 {
/** Marks a request the user waits for as running; call the returned function once it is done. */
export function foregroundStarted(): () => void {
if (running++ === 0) for (const l of listeners) l(true);
let done = false;
return () => {
@@ -26,3 +26,13 @@ export function navigationStarted(): () => void {
if (--running === 0) for (const l of listeners) l(false);
};
}
/** Runs `request` as a foreground request until it settles. */
export async function foreground<T>(request: () => Promise<T>): Promise<T> {
const done = foregroundStarted();
try {
return await request();
} finally {
done();
}
}
+73
Переглянути файл
@@ -43,6 +43,7 @@ const {
INTENTIONS_POPUP_DELAY_MS,
quickFixesAt,
applyKindSilently,
runKindAction,
bulbLine,
changedLines,
indentUnderBrace,
@@ -57,6 +58,7 @@ const { useLspPopup, closePopup } = await import("./popupStore");
const { asyncIntentionProviders, inspectionControlProviders } = await import("@/editor/api");
const { setFileDiagnostics, toLintDiagnostics } = await import("./diagnostics");
const { lspDoc } = await import("./lsp");
const { inForeground } = await import("./foreground");
const views: EditorView[] = [];
afterEach(() => {
@@ -625,3 +627,74 @@ describe("quick fixes for overlapping diagnostics", () => {
expect(runInteractiveCodeAction).toHaveBeenCalledWith(1, preferred);
});
});
// #6381: Code Vision's usage counts search the whole project on the same server; while the user
// waits for code actions they give way (`foreground.ts`), but never for background lookups.
describe("code actions the user waits for go before background requests", () => {
const editor = (doc = "f(1);\n", caret = 0) => {
const view = new EditorView({
state: EditorState.create({
doc,
selection: { anchor: caret },
extensions: [lspDoc.of({ doc: 1, path: "/p/a.ts", language: "typescript", uiMode: null, readOnly: false })],
}),
});
views.push(view);
return view;
};
const held = () => {
let release!: () => void;
lspCodeActions.mockImplementation(
() => new Promise((r) => (release = () => r({ status: "ok", data: [{ ...resolved, edit: null }] }))),
);
return () => release();
};
const tick = () => new Promise((r) => setTimeout(r, 0));
it.each([
["⌥↵", (view: EditorView) => showIntentions(view)],
[
"a code action by kind",
(view: EditorView) => runKindAction(view, "refactor", { none: "Nothing", label: "Refactor" }),
],
])("%s holds background requests back until the server answers", async (_name, run) => {
const release = held();
const view = editor();
const running = run(view);
await tick();
expect(lspCodeActions).toHaveBeenCalled();
expect(inForeground()).toBe(true);
release();
await running;
expect(inForeground()).toBe(false);
});
it("Apply Quick Fix holds background requests back while it looks for the fix", async () => {
const view = editor("f(1);\n", 1);
const problem: Diagnostic = {
range: { start: { line: 0, col: 0 }, end: { line: 0, col: 4 } },
severity: "error",
message: "broken",
source: "ts",
code: null,
};
view.dispatch(setDiagnostics(view.state, toLintDiagnostics(view.state.doc, [problem])));
const release = held();
const running = applyQuickFix(view);
await tick();
expect(inForeground()).toBe(true);
release();
await running;
expect(inForeground()).toBe(false);
});
it("an Actions on Save lookup does not hold them back", async () => {
const release = held();
const running = applyKindSilently(editor(), "source.fixAll");
await tick();
expect(lspCodeActions).toHaveBeenCalled();
expect(inForeground()).toBe(false);
release();
await running;
});
});
+5 -3
Переглянути файл
@@ -39,6 +39,7 @@ import {
} from "./popupStore";
import { editPreviewLines } from "./workspaceEdit";
import { featureBackoff } from "./availability";
import { foreground } from "./foreground";
import { iconNode } from "@/ui/iconNode";
import { editorPrefs } from "@/platform/editorSettings";
import { spellingIntentions } from "./spelling";
@@ -219,7 +220,7 @@ export async function applyQuickFix(view: EditorView) {
try {
for (const p of problems) {
// oxlint-disable-next-line no-await-in-loop -- applies the first available fix, then stops; later fixes are not requested
const fix = (await quickFixesAt(view, p.from, p.to, p.problem))[0];
const fix = (await foreground(() => quickFixesAt(view, p.from, p.to, p.problem)))[0];
if (view.state.doc !== state.doc) return;
if (fix) return applyCodeAction(view, fix);
}
@@ -606,8 +607,9 @@ export async function showIntentions(view: EditorView) {
try {
let failure: unknown = null;
// Like IDEA, only applicable intentions are listed (servers also report disabled refactorings).
// The user waits for this answer: background requests to the same server give way.
const [actions, found] = await Promise.all([
fetchIntentions(view).catch((e: unknown) => {
foreground(() => fetchIntentions(view)).catch((e: unknown) => {
failure = e;
return null;
}),
@@ -660,7 +662,7 @@ export async function runKindAction(
let actions: CodeAction[];
try {
// An empty kind asks for every action (filtered by title only).
actions = await fetchActions(view, kind ? [kind] : [], opts.whole);
actions = await foreground(() => fetchActions(view, kind ? [kind] : [], opts.whole));
} catch (e) {
if (!isCancelled(e) && opts.fallback && (await opts.fallback(isUnavailable(e) ? "notReady" : "error"))) return;
reportLspError(view, e, true);
+2 -2
Переглянути файл
@@ -82,7 +82,7 @@ import {
textReference,
} from "./links";
import { featureBackoff } from "./availability";
import { navigationStarted } from "./foreground";
import { foregroundStarted } from "./foreground";
import { requestHover, showPhpConstructDocumentation } from "./hover";
import { declarationSummary, renderCode } from "./markdown";
import { enclosingType } from "@/editor/navigation/lineMarkers";
@@ -354,7 +354,7 @@ 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();
const navigated = foregroundStarted();
try {
await gotoResolved(view, kind, at ?? view.state.selection.main.head, superseded, done);
} finally {
+6 -6
Переглянути файл
@@ -21,7 +21,7 @@ import { iconAreaSource, mapLineStart } from "@/editor/core/cm/iconArea";
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 { inForeground, onForeground } 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";
@@ -129,11 +129,11 @@ function watchChanges() {
onIdeEvent("lspRefresh", (e) => {
if (e.kind === "inheritance") refreshCaches();
});
// Go to Declaration and the like go first: in-flight marker requests are cancelled and
// asked again once the navigation is done.
onNavigation((navigating) => {
// Requests the user waits for go first (Go to Declaration, ⌥↵, a refactoring): in-flight
// marker requests are cancelled and asked again once the user's request is done.
onForeground((foreground) => {
for (const plugin of live) {
if (navigating) plugin.yieldToNavigation();
if (foreground) plugin.yieldToNavigation();
else plugin.resumeAfterNavigation();
}
});
@@ -766,7 +766,7 @@ class MarkersPlugin {
if (this.skipped) return;
const ctx = docOf(view);
if (!ctx) return;
if (isNavigating()) {
if (inForeground()) {
this.yielded = true;
return;
}
+70
Переглянути файл
@@ -0,0 +1,70 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import type { commands } from "@/platform/ipc";
type QueryResult = Awaited<ReturnType<typeof commands.lspCodeActionQuery>>;
const { lspCodeActionQuery, cancelRequest } = vi.hoisted(() => ({
lspCodeActionQuery: vi.fn<typeof commands.lspCodeActionQuery>(),
cancelRequest: vi.fn<typeof commands.cancelRequest>(async () => {}),
}));
vi.mock("@/platform/ipc", async (orig) => {
const real = await orig<typeof import("@/platform/ipc")>();
return { ...real, isTauri: () => true, commands: { ...real.commands, lspCodeActionQuery, cancelRequest } };
});
const { runRefactoring } = await import("./refactorThis");
const { lspDoc } = await import("@/editor/lsp/lsp");
const hint = () => document.querySelector(".cm-lsp-hint")?.textContent ?? null;
const empty: QueryResult = { status: "ok", data: { actions: [], advertisedKinds: null } };
const cancelled: QueryResult = { status: "error", error: { kind: "cancelled", message: "cancelled" } };
let view: EditorView;
beforeEach(() => {
vi.useFakeTimers();
view = new EditorView({
state: EditorState.create({
doc: "fn main() { run(); }",
selection: { anchor: 13 },
extensions: [lspDoc.of({ doc: 1, path: "/p/main.rs", language: "rust", uiMode: "Rust", readOnly: false })],
}),
parent: document.body,
});
});
afterEach(() => {
view.destroy();
vi.clearAllMocks();
vi.useRealTimers();
});
// #6381: a busy server (jdtls searching usages) can take seconds to list the refactorings.
describe("Refactor menu actions while the server is busy", () => {
it("say they are waiting until the server answers", async () => {
let answer!: (r: QueryResult) => void;
lspCodeActionQuery.mockImplementationOnce(() => new Promise((r) => (answer = r)));
const running = runRefactoring(view, "move");
await vi.advanceTimersByTimeAsync(250);
expect(hint()).toBe("Looking for refactorings…");
answer(empty);
await running;
expect(hint()).not.toBe("Looking for refactorings…");
});
it("keep saying so when pressed again while the first press is waiting", async () => {
const answers: Array<(r: QueryResult) => void> = [];
lspCodeActionQuery.mockImplementation(() => new Promise((r) => answers.push(r)));
const first = runRefactoring(view, "move");
await vi.advanceTimersByTimeAsync(250);
expect(hint()).toBe("Looking for refactorings…");
const second = runRefactoring(view, "move");
// The superseded query comes back cancelled at once.
answers[0]!(cancelled);
await first;
await vi.advanceTimersByTimeAsync(250);
expect(hint()).toBe("Looking for refactorings…");
answers[1]!(empty);
await second;
expect(hint()).not.toBe("Looking for refactorings…");
});
});
+32 -1
Переглянути файл
@@ -55,7 +55,9 @@ vi.mock("@/editor/structure", () => ({
},
}));
const showHint = vi.fn();
vi.mock("@/editor/lsp/hint", () => ({ showHint }));
const pendingDone = vi.fn();
const showPendingHint = vi.fn(() => pendingDone);
vi.mock("@/editor/lsp/hint", () => ({ showHint, showPendingHint }));
const introduceFallback = vi.fn(async () => true);
vi.mock("./introduce", () => ({
introduceFallback,
@@ -75,6 +77,7 @@ const { useLspPopup, closePopup } = await import("@/editor/lsp/popupStore");
const { lspDoc } = await import("@/editor/lsp/lsp");
const { inplaceRenameExtension, inplaceSession } = await import("@/editor/lsp/inplaceRename");
const { temporaryHighlights } = await import("@/editor/lsp/tempHighlight");
const { inForeground } = await import("@/editor/lsp/foreground");
const action = (title: string, kind: string, disabledReason: string | null = null): CodeAction => ({
title,
@@ -261,6 +264,17 @@ describe("Refactor This", () => {
expect(showHint).not.toHaveBeenCalled();
});
it("lets background requests give way while it asks the server", async () => {
let release: (r: Result) => void = () => {};
query = () => new Promise((r) => (release = r));
const running = refactorThis(editor(), vi.fn());
await new Promise((r) => setTimeout(r, 0));
expect(inForeground()).toBe(true);
release(ok({ actions: [action("Inline variable", "refactor.inline")], advertisedKinds: null }));
await running;
expect(inForeground()).toBe(false);
});
it("cancels a superseded query and drops answers after the caret moved", async () => {
let release: (r: Result) => void = () => {};
query = (_request) => new Promise((r) => (release = r)).then((x) => x as Result);
@@ -290,6 +304,23 @@ describe("Refactor This", () => {
});
describe("Refactor menu actions", () => {
// #6381: on a busy server (jdtls searching usages for Code Vision) the answer can take seconds.
it("say they are waiting, and let background requests give way until the server answers", async () => {
let release: (r: Result) => void = () => {};
query = () => new Promise((r) => (release = r));
const v = editor();
const running = runRefactoring(v, "inline");
await new Promise((r) => setTimeout(r, 0));
expect(showPendingHint).toHaveBeenCalledWith(v, "Looking for refactorings…");
expect(inForeground()).toBe(true);
expect(pendingDone).not.toHaveBeenCalled();
release(ok({ actions: [action("Inline variable", "refactor.inline")], advertisedKinds: null }));
await running;
expect(inForeground()).toBe(false);
expect(pendingDone).toHaveBeenCalled();
expect(lspExecuteCodeAction).toHaveBeenCalledOnce();
});
it("apply the single matching action, or offer a choice", async () => {
query = answer([action("Move to a new file", "refactor.move.newFile")]);
await runRefactoring(editor(), "move");
+12 -2
Переглянути файл
@@ -17,7 +17,8 @@ import { whenSynced } from "@/editor/api";
import { structure } from "@/editor/structure";
import { docOf, isUnavailable, lspRequest } from "@/editor/lsp/lsp";
import { offsetToPos, offsetsToRange } from "@/editor/lsp/positions";
import { showHint } from "@/editor/lsp/hint";
import { showHint, showPendingHint } from "@/editor/lsp/hint";
import { foreground } from "@/editor/lsp/foreground";
import { caretAnchor, openPopup, type ListPopupItem } from "@/editor/lsp/popupStore";
import { applyCodeAction } from "@/editor/lsp/intentions";
import { planLocalRename } from "@/editor/lsp/syntaxFallback";
@@ -70,7 +71,8 @@ export type ServerAnswer =
async function askServer(view: EditorView, signal?: AbortSignal, only?: string[]): Promise<ServerAnswer> {
try {
return { status: "ok", query: await queryRefactorActions(view, signal, only) };
// The user waits for this answer: background requests to the same server give way.
return { status: "ok", query: await foreground(() => queryRefactorActions(view, signal, only)) };
} catch (e) {
if (isCancelled(e)) throw e;
if (isUnavailable(e)) return { status: "notReady" };
@@ -181,6 +183,8 @@ export async function unavailableReason(
}
let menuRun: AbortController | null = null;
/** Hides the waiting hint of the run in `menuRun`. */
let menuHint: (() => void) | null = null;
/** A Refactor menu action (Move…, Inline…, Extract Method…): runs it or says why it can't. */
export async function runRefactoring(view: EditorView, id: RefactoringId): Promise<void> {
@@ -218,6 +222,10 @@ export async function runRefactoring(view: EditorView, id: RefactoringId): Promi
menuRun?.abort();
const run = (menuRun = new AbortController());
const state = view.state;
// Nothing else shows until the server answers, which a busy server can take seconds to do.
// The superseded run's hint goes first: the new one is not shown over another hint.
menuHint?.();
const pending = (menuHint = showPendingHint(view, tx("Looking for refactorings…")));
let answer: ServerAnswer;
try {
answer = await askServer(view, run.signal, r.kind ? [requestKind(r.kind, ctx.language)] : undefined);
@@ -225,6 +233,8 @@ export async function runRefactoring(view: EditorView, id: RefactoringId): Promi
if (isCancelled(e)) return;
throw e;
} finally {
pending();
if (menuHint === pending) menuHint = null;
if (menuRun === run) menuRun = null;
}
if (run.signal.aborted || view.state.doc !== state.doc || !view.state.selection.eq(state.selection)) return;
+1
Переглянути файл
@@ -775,6 +775,7 @@
"Writing the heap dump…": "Writing the heap dump…",
"Linking objects…": "Linking objects…",
"Computing…": "Computing…",
"Looking for refactorings…": "Looking for refactorings…",
"Computing dominators…": "Computing dominators…",
"Computing retained sizes…": "Computing retained sizes…",
"Finding paths to GC roots…": "Finding paths to GC roots…",
+1
Переглянути файл
@@ -645,6 +645,7 @@
"Writing the heap dump…": "正在写入堆转储…",
"Linking objects…": "正在关联对象…",
"Computing…": "正在计算…",
"Looking for refactorings…": "正在查找可用的重构…",
"Computing dominators…": "正在计算支配树…",
"Computing retained sizes…": "正在计算保留大小…",
"Finding paths to GC roots…": "正在查找到 GC 根的路径…",