diff --git a/crates/ide-lsp/src/handler.rs b/crates/ide-lsp/src/handler.rs index 4ea7f175c4..cec5dd4544 100644 --- a/crates/ide-lsp/src/handler.rs +++ b/crates/ide-lsp/src/handler.rs @@ -645,6 +645,11 @@ impl Handler for ClientHandler { { self.show_message(&mgr, &json!({ "type": 1, "message": text.lines().next().unwrap_or(text) })); } + if self.server.name == "jdtls" + && let Some(failure) = crate::jdtls::gradle_sync_failure(text) + { + mgr.report_gradle_sync_failure(failure); + } if self.server.name == "jdtls" && params.get("type").and_then(Value::as_u64) == Some(1) && let Some(failure) = crate::jdtls::logged_build_plan_failure(text) diff --git a/crates/ide-lsp/src/jdtls.rs b/crates/ide-lsp/src/jdtls.rs index f36d42df63..8ceb8f4eb1 100644 --- a/crates/ide-lsp/src/jdtls.rs +++ b/crates/ide-lsp/src/jdtls.rs @@ -1293,7 +1293,66 @@ pub(crate) fn logged_build_plan_failure(message: &str) -> Option<(String, String Some((reason, body)) } +/// How long a failed Gradle sync waits for jdtls' incompatible-JDK message (sent a few ms later). +const GRADLE_JDK_MESSAGE_WAIT: std::time::Duration = std::time::Duration::from_millis(1500); + +/// Buildship's log when a Gradle sync fails ("Synchronize project app failed due to an error +/// connecting to the Gradle build.", then the stack trace), as (project, notification body). +/// jdtls logs it below error level, so without this the import fails silently: every Java file +/// shows unresolved types and nothing says why. The deepest `Caused by` is the build's own error. +pub(crate) fn gradle_sync_failure(message: &str) -> Option<(String, String)> { + let first = message.lines().next()?; + let (_, rest) = first.split_once("Synchronize project ")?; + let (project, _) = rest.split_once(" failed due to ")?; + let cause = message + .lines() + .rev() + .find_map(|l| l.trim_start().strip_prefix("Caused by: ")) + .or_else(|| message.lines().nth(1)) + .map(|l| match l.split_once(": ") { + // `org.gradle.Some.Exception: what happened` → what happened + Some((class, text)) if class.contains('.') && !class.contains(char::is_whitespace) => text, + _ => l, + }) + .map(str::trim) + .filter(|c| !c.is_empty() && !c.starts_with("at ")); + const MAX: usize = 500; + let cause = cause.map(|c| match c.char_indices().nth(MAX) { + Some((end, _)) => format!("{}…", &c[..end]), + None => c.to_owned(), + }); + let body = match cause { + Some(cause) => format!( + "Gradle could not sync {project}. Java code insight may not work until the build syncs. Fix the build, then reload the Gradle project. Cause: {cause}" + ), + None => format!( + "Gradle could not sync {project}. Java code insight may not work until the build syncs. Fix the build, then reload the Gradle project." + ), + }; + Some((project.to_owned(), body)) +} + impl LspManager { + /// A failed Gradle sync of `project` (see [`gradle_sync_failure`]), shown once. jdtls follows + /// a sync that failed on an incompatible JDK with "Can't use Java … to import Gradle project + /// …", which has its own notification with the fix; wait for it so that one is the only one. + pub(crate) fn report_gradle_sync_failure(&self, (project, body): (String, String)) { + let Some(me) = self.me.upgrade() else { return }; + self.runtime.spawn(async move { + tokio::time::sleep(GRADLE_JDK_MESSAGE_WAIT).await; + if me.shown_message_containing(SERVER, &format!(" to import Gradle project {project}")) { + return; + } + if me.first_message(SERVER, &body) { + me.sink().emit(ide_core::IdeEvent::Notify { + level: ide_core::event::NotifyLevel::Error, + title: "Gradle project sync failed".into(), + body: Some(body), + }); + } + }); + } + /// JDT LS aborted its import with `message`: when reserved Windows device names /// below `root` are the cause, say which (once). The walk runs off the RPC thread. pub(crate) fn report_import_failure(&self, root: PathBuf, message: String) { @@ -1402,6 +1461,43 @@ mod tests { ); } + #[test] + fn a_failed_gradle_sync_is_explained_with_its_root_cause() { + let log = "Nov 25, 2026, 2:00:14 PM Synchronize project repro failed due to an error connecting to the Gradle build.\n\ + org.gradle.tooling.BuildActionFailureException: The supplied phased action failed with an exception.\n\ + \tat org.gradle.tooling.internal.consumer.connection.PhasedActionAwareConsumerConnection.doRun(PhasedActionAwareConsumerConnection.java:58)\n\ + Caused by: org.gradle.api.plugins.InvalidPluginException: An exception occurred applying plugin request [id: 'war']\n\ + \tat x\n\ + Caused by: java.lang.IllegalArgumentException: Unable to determine constructor argument #2: missing parameter of type IdeArtifactRegistry, or no service of type IdeArtifactRegistry.\n\ + \tat org.gradle.groovy.scripts.DefaultScript.apply(DefaultScript.java:133)\n\ + \t... 12 more"; + let (project, body) = gradle_sync_failure(log).unwrap(); + assert_eq!(project, "repro"); + assert_eq!( + body, + "Gradle could not sync repro. Java code insight may not work until the build syncs. Fix the build, then reload the Gradle project. \ + Cause: Unable to determine constructor argument #2: missing parameter of type IdeArtifactRegistry, or no service of type IdeArtifactRegistry." + ); + + // Without a `Caused by`, the logged exception's own message. + let (_, body) = gradle_sync_failure( + "Synchronize project app failed due to an error in the referenced Gradle build.\n\ + org.gradle.tooling.BuildException: Could not run build action.\n\tat y", + ) + .unwrap(); + assert!(body.ends_with(" Cause: Could not run build action."), "{body}"); + + // A cause that is a plain sentence keeps its colons. + let (_, body) = gradle_sync_failure( + "Synchronize project app failed due to an error connecting to the Gradle build.\nx\nCaused by: Build failed: see above", + ) + .unwrap(); + assert!(body.ends_with(" Cause: Build failed: see above"), "{body}"); + + assert_eq!(gradle_sync_failure("Synchronizing projects\nCaused by: x.Y: z"), None); + assert_eq!(gradle_sync_failure("Failed to configure some Maven project(s)"), None); + } + #[test] fn source_settings_preserve_java_defaults_and_library_resolution() { let mut cfg = java_config(); diff --git a/crates/ide-lsp/src/lib.rs b/crates/ide-lsp/src/lib.rs index 69646fc8e0..c17eb67f35 100644 --- a/crates/ide-lsp/src/lib.rs +++ b/crates/ide-lsp/src/lib.rs @@ -1218,6 +1218,11 @@ impl LspManager { self.shown_messages.lock().insert((server.to_owned(), text.to_owned())) } + /// Whether `server` has shown a message containing `needle` in this project. + pub(crate) fn shown_message_containing(&self, server: &str, needle: &str) -> bool { + self.shown_messages.lock().iter().any(|(s, text)| s == server && text.contains(needle)) + } + pub(crate) fn apply_edit_hook(&self) -> Option { self.apply_edit_hook.read().clone() } diff --git a/crates/ide-lsp/tests/mock_server.rs b/crates/ide-lsp/tests/mock_server.rs index 9b6e524635..97d2f1dcda 100644 --- a/crates/ide-lsp/tests/mock_server.rs +++ b/crates/ide-lsp/tests/mock_server.rs @@ -7652,6 +7652,58 @@ async fn gradle_incompatible_jdk_log_is_surfaced_once_across_message_channels() assert_eq!(messages, vec![failure, "after"]); } +#[tokio::test(flavor = "multi_thread")] +async fn a_failed_gradle_sync_is_surfaced_once_unless_an_incompatible_jdk_explains_it() { + let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]); + let s = h.launcher.state("jdtls"); + h.open("A.java", "class A {}"); + h.wait_status("jdtls", ServerStatus::Ready).await; + let sync = |project: &str, cause: &str| { + format!( + "Nov 25, 2026, 2:00:14 PM Synchronize project {project} failed due to an error connecting to the Gradle build.\n\ + org.gradle.tooling.BuildActionFailureException: The supplied phased action failed with an exception.\n\ + \tat org.gradle.tooling.internal.consumer.DefaultPhasedBuildActionExecuter.run(DefaultPhasedBuildActionExecuter.java:68)\n\ + Caused by: java.lang.IllegalArgumentException: {cause}\n\ + \tat org.gradle.groovy.scripts.DefaultScript.apply(DefaultScript.java:133)" + ) + }; + // jdtls logs it below error level, and again on every sync. + for _ in 0..2 { + let message = sync("repro", "Unable to determine constructor argument #2"); + s.peer().notify("window/logMessage", json!({ "type": 3, "message": message })).unwrap(); + } + // An incompatible JDK fails the sync too, and jdtls then says so with its own fix. + s.peer() + .notify( + "window/logMessage", + json!({ "type": 3, "message": sync("old", "Unsupported class file major version 71") }), + ) + .unwrap(); + let jdk = "Can't use Java 27.0.1 and Gradle 7.5.1 to import Gradle project old."; + s.peer() + .notify("window/logMessage", json!({ "type": 1, "message": format!("{jdk}\njava.lang.Exception: details") })) + .unwrap(); + let notes = || -> Vec<(String, String)> { + h.events + .lock() + .iter() + .filter_map(|e| match e { + IdeEvent::Notify { title, body: Some(b), .. } => Some((title.clone(), b.clone())), + _ => None, + }) + .collect() + }; + eventually(|| notes().iter().any(|(t, _)| t == "Gradle project sync failed")).await; + tokio::time::sleep(std::time::Duration::from_millis(500)).await; + let notes = notes(); + let synced: Vec<_> = + notes.iter().filter(|(t, _)| t == "Gradle project sync failed").map(|(_, b)| b.as_str()).collect(); + assert_eq!(synced.len(), 1, "{notes:?}"); + assert!(synced[0].starts_with("Gradle could not sync repro. "), "{notes:?}"); + assert!(synced[0].ends_with(" Cause: Unable to determine constructor argument #2"), "{notes:?}"); + assert!(notes.iter().any(|(_, b)| b == jdk), "{notes:?}"); +} + /// Pull Members Up / Push Members Down: the extension's answers, refusals and edits. #[tokio::test(flavor = "multi_thread")] async fn java_hierarchy_refactorings_use_the_extension_commands() { diff --git a/src/platform/locales/text/zh-TW.json b/src/platform/locales/text/zh-TW.json index d50fdd4cb3..59938781fc 100644 --- a/src/platform/locales/text/zh-TW.json +++ b/src/platform/locales/text/zh-TW.json @@ -9245,5 +9245,8 @@ "Unquoted table, column and alias names; ClickHouse names keep their case.": "未加引號的表名、欄名和別名;ClickHouse 的名稱保持原有大小寫。", "Another deployment uses this application context": "另一個部署項已使用此應用上下文", "Show component usages": "顯示元件用法", - "Find where this component is imported and used": "查找此元件被匯入和使用的位置" + "Find where this component is imported and used": "查找此元件被匯入和使用的位置", + "Gradle project sync failed": "Gradle 專案同步失敗", + "Gradle could not sync {project}. Java code insight may not work until the build syncs. Fix the build, then reload the Gradle project. Cause: {cause}": "Gradle 無法同步 {project}。建置同步成功前,Java 程式碼分析可能無法正常運作。請修正建置,然後重新載入 Gradle 專案。原因:{cause}", + "Gradle could not sync {project}. Java code insight may not work until the build syncs. Fix the build, then reload the Gradle project.": "Gradle 無法同步 {project}。建置同步成功前,Java 程式碼分析可能無法正常運作。請修正建置,然後重新載入 Gradle 專案。" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 3480fe3e4c..e77ac4bd60 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -10194,5 +10194,8 @@ "Unquoted table, column and alias names; ClickHouse names keep their case.": "未加引号的表名、列名和别名;ClickHouse 的名称保持原有大小写。", "Another deployment uses this application context": "另一个部署项已使用此应用程序上下文", "Show component usages": "显示组件用法", - "Find where this component is imported and used": "查找此组件被导入和使用的位置" + "Find where this component is imported and used": "查找此组件被导入和使用的位置", + "Gradle project sync failed": "Gradle 项目同步失败", + "Gradle could not sync {project}. Java code insight may not work until the build syncs. Fix the build, then reload the Gradle project. Cause: {cause}": "Gradle 无法同步 {project}。构建同步成功前,Java 代码分析可能无法正常工作。请修复构建,然后重新加载 Gradle 项目。原因:{cause}", + "Gradle could not sync {project}. Java code insight may not work until the build syncs. Fix the build, then reload the Gradle project.": "Gradle 无法同步 {project}。构建同步成功前,Java 代码分析可能无法正常工作。请修复构建,然后重新加载 Gradle 项目。" }