Skip to content

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.

fix(lsp): isolate backoff for optional language features

Kartik06d78cf524be
diff --git a/src/editor/lsp/autoImport.ts b/src/editor/lsp/autoImport.ts
index 734c45494..7a8321005 100644
--- a/src/editor/lsp/autoImport.ts
+++ b/src/editor/lsp/autoImport.ts
@@ -9,14 +9,15 @@
import { ViewPlugin, type EditorView, type ViewUpdate } from "@codemirror/view";
import { commands, type CodeAction, type Diagnostic } from "@/platform/ipc";
import { editorPrefs } from "@/platform/editorSettings";
-import { docOf, lspRequest } from "./lsp";
+import { docOf, isUnavailable, lspRequest } from "./lsp";
import { diagnosticsFor, subscribeDiagnostics } from "./diagnostics";
import { applyCodeAction } from "./intentions";
import { offsetsToRange, rangeToOffsets } from "./positions";
-import { serverBackoff } from "./availability";
+import { featureBackoff } from "./availability";
const IDLE_MS = 1500;
const IMPORT_TITLE = /\bimport\b/i;
+const importBackoff = featureBackoff();
/** The single import fix among `actions`, if exactly one exists. */
export function unambiguousImport(actions: readonly CodeAction[]): CodeAction | null {
@@ -65,7 +66,7 @@ const autoImportPlugin = ViewPlugin.fromClass(
const view = this.view;
const doc = docOf(view);
if ((!prefs.addUnambiguous && !prefs.optimizeOnTheFly) || this.running || !doc || doc.readOnly) return;
- if (!view.dom.isConnected || !view.hasFocus || serverBackoff.active(doc.doc)) return;
+ if (!view.dom.isConnected || !view.hasFocus || importBackoff.active(doc.doc)) return;
this.running = true;
try {
const caretLine = view.state.doc.lineAt(view.state.selection.main.head).number - 1;
@@ -75,8 +76,9 @@ const autoImportPlugin = ViewPlugin.fromClass(
this.dirty = false;
await this.optimize(caretLine);
}
- } catch {
+ } catch (e) {
// Servers without these code actions: nothing to do.
+ if (isUnavailable(e)) importBackoff.mark(doc.doc);
} finally {
this.running = false;
}
diff --git a/src/editor/lsp/availability.test.ts b/src/editor/lsp/availability.test.ts
index d408ccf4e..e1c310bda 100644
--- a/src/editor/lsp/availability.test.ts
+++ b/src/editor/lsp/availability.test.ts
@@ -14,7 +14,7 @@ vi.mock("@/platform/ipc", async (orig) => {
};
});
-const { onServerSettled } = await import("./availability");
+const { onServerSettled, featureBackoff, installAvailabilityEvents } = await import("./availability");
const status = (s: string) => {
for (const fn of listeners) fn({ type: "languageServer", server: 1, status: s } as unknown as IdeEvent);
@@ -57,3 +57,43 @@ describe("onServerSettled", () => {
expect(fn).not.toHaveBeenCalled();
});
});
+
+describe("featureBackoff", () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ listeners.clear();
+ });
+
+ it("leaves a document alone until the back-off expires", () => {
+ vi.useFakeTimers();
+ const backoff = featureBackoff(1000);
+ expect(backoff.active(1)).toBe(false);
+ backoff.mark(1);
+ expect(backoff.active(1)).toBe(true);
+ expect(backoff.active(2)).toBe(false);
+ vi.advanceTimersByTime(1001);
+ expect(backoff.active(1)).toBe(false);
+ });
+
+ it("keeps features independent: one feature backing off does not stop another", () => {
+ const inlay = featureBackoff();
+ const completion = featureBackoff();
+ inlay.mark(1);
+ expect(inlay.active(1)).toBe(true);
+ expect(completion.active(1)).toBe(false);
+ });
+
+ it("is cleared for every feature when a server becomes ready", () => {
+ const a = featureBackoff();
+ const b = featureBackoff();
+ const off = installAvailabilityEvents();
+ a.mark(1);
+ b.mark(2);
+ status("starting");
+ expect(a.active(1)).toBe(true);
+ status("ready");
+ expect(a.active(1)).toBe(false);
+ expect(b.active(2)).toBe(false);
+ off();
+ });
+});
diff --git a/src/editor/lsp/availability.ts b/src/editor/lsp/availability.ts
index 0c28cef5a..414a51fcd 100644
--- a/src/editor/lsp/availability.ts
+++ b/src/editor/lsp/availability.ts
@@ -1,29 +1,45 @@
/**
- * Per-document back-off after `unavailable` errors, so background features
- * (completion while typing, lightbulb, inlay hints…) don't hammer the backend
- * for files without a language server. Cleared when any server becomes ready.
+ * Per-document, per-feature back-off after `unavailable` errors, so background
+ * features (completion while typing, lightbulb, inlay hints…) don't hammer the
+ * backend for files without a language server, or for a feature the server
+ * doesn't offer. Each feature owns its back-off: a server lacking one
+ * capability (Godot has no inlay hints, say) must not switch off the others.
+ * All of them are cleared when any server becomes ready.
*/
import { isTauri, onIdeEvent } from "@/platform/ipc";
import type { LspRefreshKind } from "@/bindings";
-const BACKOFF_MS = 15_000;
-const until = new Map<number, number>();
+const DEFAULT_BACKOFF_MS = 15_000;
+const all = new Set<Map<number, number>>();
-export const serverBackoff = {
- mark(doc: number) {
- until.set(doc, Date.now() + BACKOFF_MS);
- },
- active(doc: number): boolean {
- const t = until.get(doc);
- if (t === undefined) return false;
- if (t > Date.now()) return true;
- until.delete(doc);
- return false;
- },
- clear() {
- until.clear();
- },
-};
+export interface FeatureBackoff {
+ /** Stop asking about `doc` for a while. */
+ mark(doc: number): void;
+ /** Whether `doc` is still being left alone. */
+ active(doc: number): boolean;
+}
+
+/** A back-off for one feature; give each feature its own. */
+export function featureBackoff(ms = DEFAULT_BACKOFF_MS): FeatureBackoff {
+ const until = new Map<number, number>();
+ all.add(until);
+ return {
+ mark(doc) {
+ until.set(doc, Date.now() + ms);
+ },
+ active(doc) {
+ const t = until.get(doc);
+ if (t === undefined) return false;
+ if (t > Date.now()) return true;
+ until.delete(doc);
+ return false;
+ },
+ };
+}
+
+function clearBackoffs() {
+ for (const until of all) until.clear();
+}
/**
* Calls `fn` when data of `kind` fetched earlier may be stale: the server asked
@@ -85,6 +101,6 @@ export function onServerSettled(fn: () => void): () => void {
export function installAvailabilityEvents(): () => void {
return onIdeEvent("languageServer", (e) => {
- if (e.status === "ready") serverBackoff.clear();
+ if (e.status === "ready") clearBackoffs();
});
}
diff --git a/src/editor/lsp/codeLens.ts b/src/editor/lsp/codeLens.ts
index e17657938..132672435 100644
--- a/src/editor/lsp/codeLens.ts
+++ b/src/editor/lsp/codeLens.ts
@@ -13,7 +13,7 @@ import { commands, nextRequestId, type OutlineItem, type SymbolKind } from "@/pl
import { useProject } from "@/platform/project";
import { debounce, docOf, isUnavailable, lspRequest } from "./lsp";
import { posToOffset } from "./positions";
-import { onLspRefresh, serverBackoff } from "./availability";
+import { featureBackoff, onLspRefresh } from "./availability";
import { editorPrefs } from "@/platform/editorSettings";
import { authorLabel, authorSummary, authorTooltip, blameFor, onBlameInvalidated } from "./authorLens";
import { tx } from "@/platform/i18n";
@@ -35,6 +35,7 @@ const MAX_PER_PASS = 40;
const CONCURRENCY = 4;
/** Lines above/below the viewport that are counted too, so scrolling feels instant. */
const MARGIN_LINES = 60;
+const usagesBackoff = featureBackoff();
export interface LensTarget {
name: string;
@@ -138,7 +139,7 @@ class UsagesLensPlugin {
const doc = docOf(view);
if (!doc) return;
const gen = ++this.generation;
- const usages = usagesEnabled() && !serverBackoff.active(doc.doc);
+ const usages = usagesEnabled() && !usagesBackoff.active(doc.doc);
const authors = authorEnabled() && !doc.virtual;
if (!usages && !authors) {
if (view.state.field(lensField).length) view.dispatch({ effects: setLenses.of([]) });
@@ -181,7 +182,7 @@ class UsagesLensPlugin {
);
if (gen !== this.generation || view.state.doc !== text) return;
}
- if (unavailable) serverBackoff.mark(doc.doc);
+ if (unavailable) usagesBackoff.mark(doc.doc);
const lines = await blame;
if (gen !== this.generation || view.state.doc !== text) return;
const lenses: CodeLens[] = [];
@@ -202,7 +203,7 @@ class UsagesLensPlugin {
}
if (!sameLenses(view.state.field(lensField), lenses)) view.dispatch({ effects: setLenses.of(lenses) });
} catch (e) {
- if (isUnavailable(e)) serverBackoff.mark(doc.doc);
+ if (isUnavailable(e)) usagesBackoff.mark(doc.doc);
}
}
diff --git a/src/editor/lsp/completion.ts b/src/editor/lsp/completion.ts
index 66d8c5740..083fdbc74 100644
--- a/src/editor/lsp/completion.ts
+++ b/src/editor/lsp/completion.ts
@@ -50,7 +50,7 @@ import { isEmptyMarkup, renderCode, renderMarkup } from "./markdown";
import { selectableText } from "@/ui/selectableText";
import { iconNode } from "./iconMarkup";
import { parameterInfoOrLeave, triggerSignatureHelp } from "./signature";
-import { serverBackoff } from "./availability";
+import { featureBackoff } from "./availability";
import { pathCompletionSource } from "./fileReferences";
import { editorPrefs } from "@/platform/editorSettings";
import { tx } from "@/platform/i18n";
@@ -410,6 +410,9 @@ interface RichCompletion extends Completion {
typeText?: string;
}
+/** Documents the server could not complete in, so typing doesn't ask again until a server is ready. */
+const completionBackoff = featureBackoff();
+
async function lspCompletionSource(ctx: CompletionContext): Promise<CompletionResult | null> {
const doc = ctx.state.facet(lspDoc);
if (!doc || doc.readOnly) return null;
@@ -417,8 +420,7 @@ async function lspCompletionSource(ctx: CompletionContext): Promise<CompletionRe
const trigger = triggerCharacter(ctx.state.sliceDoc(Math.max(0, ctx.pos - 2), ctx.pos));
if (!ctx.explicit && !word && !trigger) return null;
if (!ctx.explicit && word && !trigger && /^\d/.test(word.text)) return null;
- if (serverBackoff.active(doc.doc)) return fallback(ctx);
-
+ if (completionBackoff.active(doc.doc)) return fallback(ctx);
cancelInflight();
const id = nextRequestId();
inflight = id;
@@ -433,7 +435,7 @@ async function lspCompletionSource(ctx: CompletionContext): Promise<CompletionRe
);
} catch (e) {
if (isUnavailable(e)) {
- serverBackoff.mark(doc.doc);
+ completionBackoff.mark(doc.doc);
return fallback(ctx);
}
return null;
diff --git a/src/editor/lsp/inlay.ts b/src/editor/lsp/inlay.ts
index 6fd5be075..49c645c92 100644
--- a/src/editor/lsp/inlay.ts
+++ b/src/editor/lsp/inlay.ts
@@ -15,7 +15,7 @@ import { useProject } from "@/platform/project";
import { editorPrefs } from "@/platform/editorSettings";
import { debounce, docOf, isUnavailable, lspRequest } from "./lsp";
import { offsetsToRange, posToOffset } from "./positions";
-import { onLspRefresh, serverBackoff } from "./availability";
+import { featureBackoff, onLspRefresh } from "./availability";
import { gotoTargets } from "./navigation";
import { tx } from "@/platform/i18n";
@@ -30,6 +30,8 @@ async function setEditorSetting(key: string, value: unknown) {
useProject.setState({ settings: await call(commands.settingsSet("global", `editor.${key}`, JSON.stringify(value))) });
}
+const inlayBackoff = featureBackoff();
+
/** A type hint after an identifier can resolve that identifier's inferred type. */
function typeHintOffset(view: EditorView, at: number): number | null {
if (at <= 0 || at > view.state.doc.length) return null;
@@ -183,7 +185,7 @@ const inlayPlugin = ViewPlugin.fromClass(
if (!view.dom.isConnected) return;
const doc = docOf(view);
if (!doc) return;
- if (!enabled(doc.language) || serverBackoff.active(doc.doc)) {
+ if (!enabled(doc.language) || inlayBackoff.active(doc.doc)) {
if (view.state.field(inlayField).size) view.dispatch({ effects: setInlays.of(Decoration.none) });
return;
}
@@ -203,7 +205,7 @@ const inlayPlugin = ViewPlugin.fromClass(
),
});
} catch (e) {
- if (isUnavailable(e)) serverBackoff.mark(doc.doc);
+ if (isUnavailable(e)) inlayBackoff.mark(doc.doc);
}
}
destroy() {
diff --git a/src/editor/lsp/inlineCompletion.ts b/src/editor/lsp/inlineCompletion.ts
index 0cbad830a..54beafb13 100644
--- a/src/editor/lsp/inlineCompletion.ts
+++ b/src/editor/lsp/inlineCompletion.ts
@@ -27,6 +27,7 @@ import { activeEditor } from "@/editor/api";
import { docOf, isUnavailable, lspRequest } from "./lsp";
import { offsetToPos, rangeToOffsets } from "./positions";
import { showHint } from "./hint";
+import { featureBackoff } from "./availability";
/** A suggestion in document offsets: `text` replaces `[from, to)`. */
export interface Suggestion {
@@ -144,7 +145,7 @@ function enabledFor(language: string): boolean {
return p.enabled && !p.disabledLanguages.includes(language);
}
-const backoff = new Map<number, number>();
+const backoff = featureBackoff(BACKOFF_MS);
let focused: EditorView | null = null;
let inflight: RequestId | null = null;
@@ -159,7 +160,7 @@ export async function requestInline(view: EditorView, automatic: boolean): Promi
const state = view.state;
const sel = state.selection;
if (!doc || sel.ranges.length !== 1 || !sel.main.empty || view.state.readOnly) return false;
- if (automatic && (backoff.get(doc.doc) ?? 0) > Date.now()) return false;
+ if (automatic && backoff.active(doc.doc)) return false;
cancelInflight();
const id = (inflight = nextRequestId());
const caret = sel.main.head;
@@ -173,7 +174,7 @@ export async function requestInline(view: EditorView, automatic: boolean): Promi
view.dispatch({ effects: setGhost.of(suggestions.length ? { items: suggestions, index: 0, caret } : null) });
return suggestions.length > 0;
} catch (e) {
- if (isUnavailable(e)) backoff.set(doc.doc, Date.now() + BACKOFF_MS);
+ if (isUnavailable(e)) backoff.mark(doc.doc);
else if (!isCancelled(e)) console.debug("[lsp] inline completion", e);
if (!automatic && !isCancelled(e)) throw e;
return false;
diff --git a/src/editor/lsp/intentions.ts b/src/editor/lsp/intentions.ts
index a1ab97070..fa39cf0af 100644
--- a/src/editor/lsp/intentions.ts
+++ b/src/editor/lsp/intentions.ts
@@ -18,7 +18,7 @@ import { formatLines } from "./format";
import { pythonMemberIntentions } from "./pythonMembers";
import { caretAnchor, openPopup, type ListPopupItem, type ListPreview } from "./popupStore";
import { editPreviewLines } from "./workspaceEdit";
-import { serverBackoff } from "./availability";
+import { featureBackoff } from "./availability";
import { iconNode } from "./iconMarkup";
import { editorPrefs } from "@/platform/editorSettings";
import { spellingIntentions } from "./spelling";
@@ -27,6 +27,8 @@ import { SPELLING_INSPECTION } from "@/platform/inspections";
import { editInspectionSettings, intentionControls } from "@/platform/inspectionControls";
import { tx } from "@/platform/i18n";
+const codeActionBackoff = featureBackoff();
+
const isQuickFix = (a: CodeAction) => !!a.kind && (a.kind === "quickfix" || a.kind.startsWith("quickfix."));
/** IDEA ordering: quick fixes first, preferred before others, disabled last; stable otherwise. */
@@ -512,14 +514,14 @@ const bulbPlugin = ViewPlugin.fromClass(
const state = this.view.state;
const typoFix = spellingIntentions(this.view).length > 0;
const local = typoFix || contributedIntentions(this.view).length > 0;
- const backoff = serverBackoff.active(doc.doc);
+ const backoff = codeActionBackoff.active(doc.doc);
if (backoff && !local) return;
let actions: CodeAction[] = [];
if (!backoff) {
try {
actions = await fetchIntentions(this.view);
} catch (e) {
- if (isUnavailable(e)) serverBackoff.mark(doc.doc);
+ if (isUnavailable(e)) codeActionBackoff.mark(doc.doc);
if (!local) return;
}
}
diff --git a/src/editor/lsp/navigation.ts b/src/editor/lsp/navigation.ts
index b46b8555d..cede48117 100644
--- a/src/editor/lsp/navigation.ts
+++ b/src/editor/lsp/navigation.ts
@@ -50,7 +50,7 @@ import { showHint } from "./hint";
import { caretAnchor, openPopup, type ListPopupItem } from "./popupStore";
import { identifierAt, readManyFileLines } from "./files";
import { documentLinks, followReference, knownLinks, linkReference, referenceAt, textReference } from "./links";
-import { serverBackoff } from "./availability";
+import { featureBackoff } from "./availability";
import { requestHover } from "./hover";
import { declarationSummary, renderCode } from "./markdown";
import { editorPrefs } from "@/platform/editorSettings";
@@ -60,6 +60,8 @@ import { isNavigationGesture, onNavigationModifier } from "@/platform/navigation
import { create } from "zustand";
import { tx } from "@/platform/i18n";
+const highlightsBackoff = featureBackoff();
+
export async function navigateTo(loc: Location) {
await editorService().openFile(loc.path, {
selection: { line: loc.range.start.line, col: loc.range.start.col },
@@ -573,7 +575,7 @@ async function fetchHighlights(view: EditorView, sticky: boolean) {
);
};
let lspError: unknown = null;
- if (!serverBackoff.active(doc.doc)) {
+ if (!highlightsBackoff.active(doc.doc)) {
try {
const items = await lspRequest(() => commands.lspDocumentHighlights(doc.doc, offsetToPos(state.doc, head)));
if (stale()) return;
@@ -582,7 +584,7 @@ async function fetchHighlights(view: EditorView, sticky: boolean) {
return;
} catch (e) {
if (isCancelled(e)) return;
- if (isUnavailable(e)) serverBackoff.mark(doc.doc);
+ if (isUnavailable(e)) highlightsBackoff.mark(doc.doc);
lspError = e;
}
}
diff --git a/src/editor/lsp/semantic.ts b/src/editor/lsp/semantic.ts
index 2e4451b3c..a1e497b87 100644
--- a/src/editor/lsp/semantic.ts
+++ b/src/editor/lsp/semantic.ts
@@ -14,7 +14,9 @@ import { Decoration, EditorView, ViewPlugin, type DecorationSet, type ViewUpdate
import { commands, type SemanticTokens } from "@/platform/ipc";
import { editorPrefs } from "@/platform/editorSettings";
import { debounce, docOf, isUnavailable, lspRequest } from "./lsp";
-import { onLspRefresh, serverBackoff } from "./availability";
+import { featureBackoff, onLspRefresh } from "./availability";
+
+const semanticBackoff = featureBackoff();
const TYPE_CLASS: Record<string, string> = {
type: "type",
@@ -180,14 +182,14 @@ const semanticPlugin = ViewPlugin.fromClass(
async run() {
const view = this.view;
const doc = docOf(view);
- if (!doc || serverBackoff.active(doc.doc) || !view.dom.isConnected) return;
+ if (!doc || semanticBackoff.active(doc.doc) || !view.dom.isConnected) return;
const state = view.state;
try {
const tokens = await lspRequest(() => commands.lspSemanticTokens(doc.doc));
if (view.state.doc !== state.doc) return this.refresh();
this.decorate(state.doc, tokens);
} catch (e) {
- if (isUnavailable(e)) serverBackoff.mark(doc.doc);
+ if (isUnavailable(e)) semanticBackoff.mark(doc.doc);
}
}
destroy() {
diff --git a/src/editor/navigation/implementationGutter.ts b/src/editor/navigation/implementationGutter.ts
index a4898cbe1..fb59e5d10 100644
--- a/src/editor/navigation/implementationGutter.ts
+++ b/src/editor/navigation/implementationGutter.ts
@@ -14,7 +14,7 @@ import { RangeSet, StateEffect, StateField, type Extension, type Text } from "@c
import { EditorView, GutterMarker, ViewPlugin, gutter, type ViewUpdate } from "@codemirror/view";
import type { EditorDocContext } from "@/editor/api";
import { docOf, debounce, isUnavailable, lspRequest } from "@/editor/lsp/lsp";
-import { onServerSettled, serverBackoff } from "@/editor/lsp/availability";
+import { featureBackoff, onServerSettled } from "@/editor/lsp/availability";
import { readManyFileLines, withDocument } from "@/editor/lsp/files";
import { locationItems, navigateTo, pinToFind } from "@/editor/lsp/navigation";
import { openPopup } from "@/editor/lsp/popupStore";
@@ -49,6 +49,7 @@ import styles from "./LineMarkers.module.css";
const MARGIN_LINES = 60;
const MAX_PER_PASS = 60;
const DEBOUNCE_MS = 500;
+const gutterBackoff = featureBackoff();
/** Settings › Editor › General › Gutter Icons groups that are on. */
export function enabledGroups(prefs: Pick<EditorExtras, "showGutterIcons" | "gutterIconsDisabled">): Set<MarkerGroup> {
@@ -279,7 +280,7 @@ class MarkersPlugin {
const gen = ++this.generation;
this.cancelRequest();
const groups = enabledGroups(editorPrefs());
- if (!groups.size || serverBackoff.active(ctx.doc)) {
+ if (!groups.size || gutterBackoff.active(ctx.doc)) {
if (!groups.size) this.show([]);
return;
}
@@ -310,7 +311,7 @@ class MarkersPlugin {
if (stale()) return;
this.show(place(text, cachedMarkers(candidates, groups, this.cache)));
} catch (e) {
- if (isUnavailable(e)) serverBackoff.mark(ctx.doc);
+ if (isUnavailable(e)) gutterBackoff.mark(ctx.doc);
else if (!isCancelled(e)) console.debug("[lineMarkers]", e);
}
}