From bd79458f592d12e07a18249ed40b633497bebfbe Mon Sep 17 00:00:00 2001 From: l0ng-ai <24760907+l0ng-ai@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:19:09 +0800 Subject: [PATCH] fix(editor): refresh Java inheritance markers after Maven import --- crates/ide-core/src/event.rs | 2 + crates/ide-lsp/src/jdtls.rs | 14 ++-- crates/ide-lsp/tests/mock_server.rs | 16 +++-- src/bindings.ts | 2 + src/editor/navigation/implementationGutter.ts | 10 ++- src/editor/navigation/lineMarkers.test.ts | 65 +++++++++++++++++++ 6 files changed, 91 insertions(+), 18 deletions(-) diff --git a/crates/ide-core/src/event.rs b/crates/ide-core/src/event.rs index 27dfe81ed..0db29f55a 100644 --- a/crates/ide-core/src/event.rs +++ b/crates/ide-core/src/event.rs @@ -324,6 +324,8 @@ pub enum LspRefreshKind { InlayHints, SemanticTokens, CodeLens, + /// An import or classpath update may have changed inheritance search results. + Inheritance, /// The Dart server published a document's Flutter outline. FlutterOutline, } diff --git a/crates/ide-lsp/src/jdtls.rs b/crates/ide-lsp/src/jdtls.rs index 99abf99fa..57998c7a7 100644 --- a/crates/ide-lsp/src/jdtls.rs +++ b/crates/ide-lsp/src/jdtls.rs @@ -8,6 +8,7 @@ use crate::LspManager; use crate::server::{Running, Server}; use ide_core::error::ErrorKind; +use ide_core::event::LspRefreshKind; use ide_core::{CancellationToken, IdeError, IdeResult, LanguageId}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -646,10 +647,8 @@ impl LspManager { /// jdtls reports `ProjectStatus` when an import or project update ends (a POM /// change, a Maven sync, other Maven profiles), but does not check open documents /// again against the new classpath: their errors would stay until the next edit. - /// Nor does it ask for a semantic tokens refresh: a file outside any project (its - /// import failed, say on an unresolvable parent POM) gets no tokens, and would stay - /// uncoloured after the import is fixed. Generated Maven sources are attached - /// first, so the recheck and the new tokens see them. + /// Open editors may have cached empty tokens or inheritance results during the import. + /// Attach generated Maven sources before refreshing either, so both see the new classpath. pub(crate) fn java_projects_updated(self: &Arc, server: Arc, generation: u64) { let uris: Vec = self .docs @@ -666,10 +665,9 @@ impl LspManager { self.runtime.spawn(async move { let Some(run) = server.running_gen(generation) else { return }; mgr.sync_generated_sources(&server, &run).await; - mgr.sink().emit(ide_core::IdeEvent::LspRefresh { - server: server.id, - kind: ide_core::event::LspRefreshKind::SemanticTokens, - }); + for kind in [LspRefreshKind::SemanticTokens, LspRefreshKind::Inheritance] { + mgr.sink().emit(ide_core::IdeEvent::LspRefresh { server: server.id, kind }); + } for uri in uris { let params = json!({ "command": "java.project.refreshDiagnostics", "arguments": [uri, "thisFile", false] }); diff --git a/crates/ide-lsp/tests/mock_server.rs b/crates/ide-lsp/tests/mock_server.rs index 0696edb12..80d32e988 100644 --- a/crates/ide-lsp/tests/mock_server.rs +++ b/crates/ide-lsp/tests/mock_server.rs @@ -3166,7 +3166,7 @@ async fn open_java_files_are_checked_again_after_a_project_update() { } #[tokio::test(flavor = "multi_thread")] -async fn a_project_update_refreshes_java_semantic_tokens() { +async fn a_project_update_refreshes_java_tokens_and_inheritance() { let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]); let _ = h.open("A.java", "class A { private String name; }"); h.wait_status("jdtls", ServerStatus::Ready).await; @@ -3175,20 +3175,22 @@ async fn a_project_update_refreshes_java_semantic_tokens() { h.events .lock() .iter() - .filter(|e| matches!(e, IdeEvent::LspRefresh { kind: LspRefreshKind::SemanticTokens, .. })) - .count() + .filter_map(|e| match e { + IdeEvent::LspRefresh { kind, .. } => Some(*kind), + _ => None, + }) + .collect::>() }; state .peer() .notify("language/status", json!({ "type": "Message", "message": "Updating project configurations..." })) .unwrap(); tokio::time::sleep(Duration::from_millis(200)).await; - assert_eq!(refreshes(), 0); + assert!(refreshes().is_empty()); - // jdtls answers with no tokens for a file outside any project and sends no - // `workspace/semanticTokens/refresh` once a later import takes it in. + // A later import may add tokens and implementation targets to open editors. state.peer().notify("language/status", json!({ "type": "ProjectStatus", "message": "OK" })).unwrap(); - eventually(|| refreshes() == 1).await; + eventually(|| refreshes() == [LspRefreshKind::SemanticTokens, LspRefreshKind::Inheritance]).await; } #[tokio::test(flavor = "multi_thread")] diff --git a/src/bindings.ts b/src/bindings.ts index bdf410a53..baa23118f 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -9197,6 +9197,8 @@ export type LogcatLine = { }; export type LspRefreshKind = "inlayHints" | "semanticTokens" | "codeLens" | +/** An import or classpath update may have changed inheritance search results. */ +"inheritance" | /** The Dart server published a document's Flutter outline. */ "flutterOutline"; diff --git a/src/editor/navigation/implementationGutter.ts b/src/editor/navigation/implementationGutter.ts index 34eb22143..a25e334ad 100644 --- a/src/editor/navigation/implementationGutter.ts +++ b/src/editor/navigation/implementationGutter.ts @@ -11,7 +11,7 @@ * of the file in batches; results are cached per document text, and markers * follow their lines in between. * The cache outlives the editor view (switching tabs remounts it) until other - * files change or a language server settles: on some servers (jdtls) every + * files change, a language server settles or its classpath changes: on some servers (jdtls) every * implementation search walks the whole workspace, so asking again is costly. * Library sources ask no inheritors from the server (`isLibrarySource`). */ @@ -119,11 +119,15 @@ function watchChanges() { // documents: re-render them instead of waiting for an edit or a settling server. for (const plugin of live) plugin.refreshSoon(); }); - // Answers (outlines too) given while a server was starting or indexing may be incomplete. - onServerSettled(() => { + // Answers (outlines too) given while a server was starting or importing may be incomplete. + const refreshCaches = () => { docMarkers.clear(); forgetInheritanceGraph(); for (const plugin of live) plugin.refreshSoon(); + }; + onServerSettled(refreshCaches); + 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. diff --git a/src/editor/navigation/lineMarkers.test.ts b/src/editor/navigation/lineMarkers.test.ts index 0a0ed8a62..e11ee7d07 100644 --- a/src/editor/navigation/lineMarkers.test.ts +++ b/src/editor/navigation/lineMarkers.test.ts @@ -9,13 +9,25 @@ import { commands, type ClassInheritance, type HierarchyItem, + type IdeEvent, type Location, type OutlineItem, type Pos, type SymbolKind, } from "@/platform/ipc"; +import { setInvokeRoute } from "@/platform/tauriCore"; const nav = vi.hoisted(() => ({ navigateTo: vi.fn(async () => {}), openPopup: vi.fn() })); +const ideListeners = vi.hoisted(() => new Map void>>()); +vi.mock("@/platform/ipc", async (orig) => ({ + ...(await orig()), + onIdeEvent: (type: string, listener: (event: IdeEvent) => void) => { + let listeners = ideListeners.get(type); + if (!listeners) ideListeners.set(type, (listeners = new Set())); + listeners.add(listener); + return () => listeners.delete(listener); + }, +})); vi.mock("@/editor/lsp/navigation", async (orig) => ({ ...(await orig()), navigateTo: nav.navigateTo, @@ -623,6 +635,59 @@ describe("clicking a marker", () => { }); describe("inheritance gutter", () => { + it.each([ + { type: "interface", source: SHAPE, outline: SHAPE_OUTLINE }, + { type: "abstract class", source: BASE, outline: BASE_OUTLINE }, + ])( + "refreshes implementation and override markers when a Java project update finishes ($type)", + async ({ source, outline }) => { + vi.useFakeTimers(); + let indexed = false; + const target = "/p/service/target/generated-sources/example/ServiceImpl.java"; + const queries = vi.fn(async (positions) => + positions.map(({ line }) => (indexed ? [loc(target, line + 2)] : [])), + ); + setInvokeRoute(async (command, args) => { + if (command === "doc_outline") return outline; + if (command === "lsp_type_hierarchy") { + throw { kind: "unavailable", message: "no type hierarchy", data: null }; + } + if (command === "lsp_implementations") return queries((args as { positions: Pos[] }).positions); + return null; + }); + const ctx = { doc: 12, path: `/p/api/${outline[0]!.name}.java`, language: "java", uiMode: null, readOnly: false }; + const view = new EditorView({ + doc: Text.of(source), + extensions: [lspDoc.of(ctx), iconAreaExtension, implementationGutter(ctx)], + parent: document.body, + }); + const kinds = () => + [...view.dom.querySelectorAll('[class*="cm-openidea-lineMarker-"]')].map((el) => el.dataset.kind); + const emit = (event: IdeEvent) => { + for (const listener of ideListeners.get(event.type) ?? []) listener(event); + }; + try { + await vi.advanceTimersByTimeAsync(500); + expect(queries).toHaveBeenCalledTimes(1); + expect(kinds()).toEqual([]); + + indexed = true; + emit({ type: "lspRefresh", server: 1, kind: "semanticTokens" }); + await vi.advanceTimersByTimeAsync(500); + expect(queries).toHaveBeenCalledTimes(1); + + emit({ type: "lspRefresh", server: 1, kind: "inheritance" }); + await vi.advanceTimersByTimeAsync(500); + expect(queries).toHaveBeenCalledTimes(2); + expect(kinds()).toEqual(["implemented", "implemented", "overridden"]); + } finally { + view.destroy(); + setInvokeRoute(null); + vi.useRealTimers(); + } + }, + ); + it.each([ { kind: "overriding", language: "java", declaration: "@SuperBuilder" }, { kind: "overridden", language: "java", declaration: "@Data" },