Порівняти коміти

..
Автор SHA1 Повідомлення Дата
l0ng-ai 68ab95a631 fix(debugger): report obsolete methods as a completed hot swap
Treat the obsolete-method response and event as a reload warning. Explain why active frames keep the old code and offer Reset Frame for supported, droppable paused frames while preserving real failures and cancelled-build restart requirements.
2026-11-09 18:06:42 +08:00
19 змінених файлів з 20 додано та 552 видалено

No files matched your search

-2
Переглянути файл
@@ -24,10 +24,8 @@ fn tools(host: &Host, window: &str) -> IdeResult<Tools> {
.collect();
// Godot is usually an app bundle / Flatpak outside the search path.
let found = ide_sdk::godot::find(None).map(|p| (ide_sdk::godot::COMMAND.to_owned(), p));
let runtime = ide_sdk::apply::tool_install_environment(&root, &settings);
let work_dir = (!root.as_os_str().is_empty()).then_some(root);
Ok(Tools::new(&data)
.with_runtime(runtime.commands, runtime.env)
.with_custom_paths(custom)
.with_found_paths(found.into_iter().collect())
.with_work_dir(work_dir))
-6
Переглянути файл
@@ -268,12 +268,6 @@ impl Handler for ClientHandler {
"window/showMessage" => self.show_message(&mgr, &params),
"window/logMessage" => {
let text = params.get("message").and_then(Value::as_str).unwrap_or_default();
if self.server.name == "jdtls"
&& text.contains("Can't use Java ")
&& text.contains(" to import Gradle project ")
{
self.show_message(&mgr, &json!({ "type": 1, "message": text.lines().next().unwrap_or(text) }));
}
match params.get("type").and_then(Value::as_u64) {
Some(1) if self.server.name == "jdtls" && text.contains(crate::jdtls::reserved_names::IMPORT_FAILURE) => {
tracing::warn!("[{}] {text}", self.server.name);
-33
Переглянути файл
@@ -5606,39 +5606,6 @@ async fn jdtls_import_failure_names_reserved_device_files_on_windows() {
let _ = std::fs::remove_file(&nul);
}
#[tokio::test(flavor = "multi_thread")]
async fn gradle_incompatible_jdk_log_is_surfaced_once_across_message_channels() {
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 failure = "Can't use Java 27.0.1.0.3 and Gradle 9.7.1 to import Gradle project kotlin-gradle.";
for _ in 0..2 {
s.peer()
.notify(
"window/logMessage",
json!({ "type": 1, "message": format!("{failure}\njava.lang.Exception: details stay in the log") }),
)
.unwrap();
}
eventually(|| h.events.lock().iter().any(|e| matches!(e, IdeEvent::Notify { body: Some(b), .. } if b == failure)))
.await;
s.peer().notify("window/showMessage", json!({ "type": 1, "message": failure })).unwrap();
s.peer().notify("window/logMessage", json!({ "type": 1, "message": "unrelated internal error" })).unwrap();
s.peer().notify("window/showMessage", json!({ "type": 2, "message": "after" })).unwrap();
eventually(|| h.events.lock().iter().any(|e| matches!(e, IdeEvent::Notify { body: Some(b), .. } if b == "after")))
.await;
let events = h.events.lock();
let messages: Vec<_> = events
.iter()
.filter_map(|e| match e {
IdeEvent::Notify { body: Some(body), .. } => Some(body.as_str()),
_ => None,
})
.collect();
assert_eq!(messages, vec![failure, "after"]);
}
/// 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() {
-28
Переглянути файл
@@ -130,34 +130,6 @@ pub(crate) fn goroot(root: &Path, s: &Settings) -> Option<PathBuf> {
.or_else(|| pinned::pinned_install(root, Tool::Go).and_then(|(dir, _)| pinned::goroot_in_install(&dir)))
}
/// Runtime choices for package-manager based IDE tool installs.
#[derive(Default)]
pub struct ToolInstallEnvironment {
pub commands: std::collections::BTreeMap<String, PathBuf>,
pub env: std::collections::BTreeMap<String, String>,
}
/// Uses the same configured / project-pinned SDKs as Run and language servers.
/// Build tags and target OS settings intentionally do not apply to host tools.
pub fn tool_install_environment(root: &Path, s: &Settings) -> ToolInstallEnvironment {
let mut runtime = ToolInstallEnvironment::default();
if let Some(go) = goroot(root, s) {
runtime.commands.insert("go".into(), go.join("bin").join(exe("go")));
runtime.env.insert("GOROOT".into(), go.to_string_lossy().into_owned());
}
if let Some(node) = node_dir(root, s) {
let node = setting_path(root, &s.languages.node.interpreter).unwrap_or_else(|| node.join(exe("node")));
runtime.commands.insert("node".into(), node);
}
if let Some(ruby) = ruby_interpreter(root, s) {
runtime.commands.insert("ruby".into(), ruby);
}
if let Some(python) = python_interpreter(root, s) {
runtime.commands.insert("python".into(), python);
}
runtime
}
/// A JDK setting: a JDK home, its `bin` or its `bin/java`.
fn jdk_setting(root: &Path, value: &str) -> Option<Result<crate::java::Jdk, PathBuf>> {
let p = setting_path(root, value)?;
+1 -23
Переглянути файл
@@ -1,6 +1,6 @@
use crate::apply::{
apply_to_run_configs, configure_server, jdtls_jdk, maven_command, maven_options, project_jdk, python_interpreter,
ruff_configuration, terminal_activation, tool_install_environment, tsdk, without_derived,
ruff_configuration, terminal_activation, tsdk, without_derived,
};
use crate::python::parse_pip_list;
use crate::{bin_dir, exe, venv_of};
@@ -2246,25 +2246,3 @@ fn plugin_interpreter_targets_route_all_php_node_command_families() {
assert_eq!(config.extras.target.as_deref(), Some(""));
}
}
#[test]
fn tool_installs_resolve_project_relative_sdks_and_leave_path_fallback_unconfigured() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let mut s = Settings::default();
let defaults = tool_install_environment(root, &s);
assert!(!defaults.commands.contains_key("go"));
assert!(!defaults.commands.contains_key("node"));
assert!(!defaults.commands.contains_key("python"));
assert!(!defaults.env.contains_key("GOROOT"));
s.languages.go.goroot = "go-sdk".into();
s.languages.node.interpreter = "node-sdk/bin/node".into();
s.languages.python.interpreter = "python-sdk/bin/python3.14".into();
s.languages.ruby.interpreter = "ruby-sdk/bin/ruby".into();
let runtime = tool_install_environment(root, &s);
assert_eq!(runtime.commands["go"], root.join("go-sdk/bin").join(if cfg!(windows) { "go.exe" } else { "go" }));
assert_eq!(runtime.env["GOROOT"], root.join("go-sdk").to_string_lossy());
assert_eq!(runtime.commands["node"], root.join("node-sdk/bin/node"));
assert_eq!(runtime.commands["python"], root.join("python-sdk/bin/python3.14"));
assert_eq!(runtime.commands["ruby"], root.join("ruby-sdk/bin/ruby"));
}
+1 -70
Переглянути файл
@@ -421,7 +421,6 @@ pub fn managed_bundle(app_data: &Path, name: &str) -> Option<PathBuf> {
}
/// Installer and detector over one tools directory.
#[derive(Clone)]
pub struct Tools {
root: PathBuf,
/// Search path for system tools (excludes our own dirs).
@@ -433,8 +432,6 @@ pub struct Tools {
custom: BTreeMap<String, PathBuf>,
/// Executables found outside the search path (app bundles), by command.
found: BTreeMap<String, PathBuf>,
runtime_commands: BTreeMap<String, PathBuf>,
runtime_env: BTreeMap<String, String>,
version_timeout: Duration,
/// The project the tools are used for: tools that install into "the active runtime" (gems) run here,
/// so a version manager picks the project's Ruby.
@@ -459,41 +456,11 @@ impl Tools {
platform,
custom: BTreeMap::new(),
found: BTreeMap::new(),
runtime_commands: BTreeMap::new(),
runtime_env: BTreeMap::new(),
version_timeout: Duration::from_secs(4),
work_dir: None,
}
}
/// Applies the project's SDKs to prerequisite lookup, probes and installer children.
pub fn with_runtime(mut self, commands: BTreeMap<String, PathBuf>, env: BTreeMap<String, String>) -> Self {
self.runtime_commands = commands;
self.runtime_env = env;
self
}
fn for_method(&self, method: Method) -> Self {
let commands: &[&str] = match method {
Method::Go { .. } => &["go"],
Method::Npm { .. } => &["node"],
Method::Gem { .. } | Method::GemActive { .. } => &["ruby"],
Method::PipVenv { .. } | Method::PipUser { .. } | Method::PipTarget { .. } => &["python"],
_ => &[],
};
let mut runtime = self.clone();
runtime.runtime_commands.retain(|name, _| commands.contains(&name.as_str()));
runtime.runtime_env.retain(|name, _| name == "GOROOT" && commands.contains(&"go"));
let dirs: Vec<PathBuf> =
runtime.runtime_commands.values().filter_map(|p| p.parent().map(Path::to_path_buf)).collect();
runtime.system_path =
std::env::join_paths(dirs.iter().cloned().chain(std::env::split_paths(&self.system_path)))
.unwrap_or_else(|_| self.system_path.clone());
runtime.child_path = std::env::join_paths(dirs.iter().cloned().chain(std::env::split_paths(&self.child_path)))
.unwrap_or_else(|_| self.child_path.clone());
runtime
}
/// Reports the executables chosen in settings (command → path) as the tools' location.
pub fn with_custom_paths(mut self, custom: BTreeMap<String, PathBuf>) -> Self {
self.custom = custom;
@@ -526,9 +493,6 @@ impl Tools {
}
fn which(&self, cmd: &str) -> Option<PathBuf> {
if let Some(path) = self.runtime_commands.get(cmd) {
return path.is_file().then(|| path.clone());
}
ide_core::tool_path::find_command(cmd, &self.system_path, &self.root)
}
@@ -538,7 +502,7 @@ impl Tools {
fn command(&self, program: impl AsRef<std::ffi::OsStr>) -> Command {
let mut cmd = Command::new(program);
ide_core::process::prepare(&mut cmd).envs(&self.runtime_env).env("PATH", &self.child_path);
ide_core::process::prepare(&mut cmd).env("PATH", &self.child_path);
cmd
}
@@ -560,9 +524,6 @@ impl Tools {
/// Aliases that only open the Store unless the Store's Python is installed, so they count
/// only when they run.
fn python(&self) -> Option<PathBuf> {
if self.runtime_commands.contains_key("python") {
return self.which("python");
}
if self.platform.os != Os::Windows {
return self.which_any(&["python3", "python"]);
}
@@ -703,13 +664,6 @@ impl Tools {
}
fn info_for(&self, name: &str, usage: Option<&Usage>) -> Option<ToolInfo> {
match registry::find(name) {
Some(spec) => self.for_method(spec.method).info_for_runtime(name, usage),
None => self.info_for_runtime(name, usage),
}
}
fn info_for_runtime(&self, name: &str, usage: Option<&Usage>) -> Option<ToolInfo> {
let spec = registry::find(name);
let languages = usage.map(|u| u.languages.clone()).unwrap_or_default();
let install_hint = usage.and_then(|u| u.install_hint.clone());
@@ -914,19 +868,6 @@ impl Tools {
langs: &[LanguageConfig],
cancel: &CancellationToken,
emit: Emit,
) -> IdeResult<ToolInfo> {
match registry::find(name) {
Some(spec) => self.for_method(spec.method).install_for_runtime(name, langs, cancel, emit),
None => self.install_for_runtime(name, langs, cancel, emit),
}
}
fn install_for_runtime(
&self,
name: &str,
langs: &[LanguageConfig],
cancel: &CancellationToken,
emit: Emit,
) -> IdeResult<ToolInfo> {
let spec = registry::find(name).ok_or_else(|| {
let hint = usages(langs).get(name).and_then(|u| u.install_hint.clone());
@@ -1189,9 +1130,6 @@ impl Tools {
if let Some(uv) = self.which("uv") {
let mut c = self.command(&uv);
c.arg("venv").arg(&venv);
if let Some(python) = self.runtime_commands.get("python") {
c.arg("--python").arg(python);
}
run_streamed(c, cancel, emit)?;
let mut c = self.command(&uv);
c.args(["pip", "install", "--python"]).arg(&python).arg(package);
@@ -1433,13 +1371,6 @@ impl Tools {
/// Removes a tool the IDE installed.
pub fn uninstall(&self, name: &str, langs: &[LanguageConfig]) -> IdeResult<ToolInfo> {
match registry::find(name) {
Some(spec) => self.for_method(spec.method).uninstall_for_runtime(name, langs),
None => self.uninstall_for_runtime(name, langs),
}
}
fn uninstall_for_runtime(&self, name: &str, langs: &[LanguageConfig]) -> IdeResult<ToolInfo> {
let spec = registry::find(name).ok_or_else(|| IdeError::not_found(format!("unknown tool `{name}`")))?;
// Uninstalling mid-install would tear down the directory under the running installer.
if INSTALLING.lock().as_ref().is_some_and(|m| m.contains_key(name)) {
+8 -113
Переглянути файл
@@ -438,15 +438,12 @@ esac"#,
#[test]
fn npm_install_uses_tools_prefix() {
let env = Env::new();
let sdk = env._tmp.path().join("selected-sdk/bin");
fs::create_dir_all(&sdk).unwrap();
let log = env.root.parent().unwrap().join("npm-args.txt");
env.script(
&sdk,
&env.sys,
"npm",
&format!(
r#"node --version >/dev/null || exit 98
echo "$@" > '{log}'
r#"echo "$@" > '{log}'
prefix=""; while [ $# -gt 0 ]; do [ "$1" = "--prefix" ] && prefix="$2"; shift; done
/bin/mkdir -p "$prefix/node_modules/.bin" "$prefix/node_modules/bash-language-server"
printf '#!/bin/sh\necho 5.4.0\n' > "$prefix/node_modules/.bin/bash-language-server"
@@ -456,14 +453,7 @@ echo "added 1 package""#,
log = log.display()
),
);
env.script(&sdk, "node", "exit 0");
env.script(&env.sys, "node", "exit 99");
env.script(&env.sys, "npm", "exit 99");
let tools = env.tools().with_runtime(
BTreeMap::from([("node".into(), sdk.join("node")), ("ruby".into(), env.sys.join("ruby"))]),
BTreeMap::new(),
);
let info = tools.install("bash-language-server", &langs(), &CancellationToken::new(), &|_| {}).unwrap();
let info = env.tools().install("bash-language-server", &langs(), &CancellationToken::new(), &|_| {}).unwrap();
assert_eq!(info.status, ToolStatus::Installed);
assert_eq!(info.version.as_deref(), Some("5.4.0"));
let args = fs::read_to_string(&log).unwrap();
@@ -591,19 +581,14 @@ fn elixir_ls_needs_elixir_and_lists_its_debugger() {
#[test]
fn gem_install_wraps_stubs_with_gem_home() {
let env = Env::new();
let sdk = env._tmp.path().join("selected-sdk/bin");
fs::create_dir_all(&sdk).unwrap();
// `gem install --no-document --install-dir <home> --bindir <bin> solargraph`
env.script(
&sdk,
&env.sys,
"gem",
r#"home="$4"; bin="$6"; /bin/mkdir -p "$home/gems/solargraph-0.50.0" "$bin"
printf '#!/bin/sh\necho "$GEM_HOME"\n' > "$bin/solargraph"; /bin/chmod +x "$bin/solargraph""#,
);
env.script(&sdk, "ruby", "exit 0");
env.script(&env.sys, "ruby", "exit 99");
env.script(&env.sys, "gem", "exit 99");
let tools = env.tools().with_runtime(BTreeMap::from([("ruby".into(), sdk.join("ruby"))]), BTreeMap::new());
let tools = env.tools();
let info = tools.install("solargraph", &langs(), &CancellationToken::new(), &|_| {}).unwrap();
assert_eq!(info.status, ToolStatus::Installed);
assert_eq!(info.version.as_deref(), Some("0.50.0"));
@@ -617,18 +602,16 @@ printf '#!/bin/sh\necho "$GEM_HOME"\n' > "$bin/solargraph"; /bin/chmod +x "$bin/
#[test]
fn ruby_lsp_installs_into_the_project_ruby_not_a_private_gem_home() {
let env = Env::new();
let sdk = env._tmp.path().join("selected-sdk/bin");
fs::create_dir_all(&sdk).unwrap();
let project = env._tmp.path().join("project");
fs::create_dir_all(&project).unwrap();
let marker = env._tmp.path().join("installed");
// Homebrew's Ruby: the gem bindir is not on the search path; only the Ruby knows it.
let bindir = env._tmp.path().join("gems/bin");
fs::create_dir_all(&bindir).unwrap();
env.script(&sdk, "ruby", &format!("echo '{}'", bindir.display()));
env.script(&env.sys, "ruby", &format!("echo '{}'", bindir.display()));
// `gem list --exact ruby-lsp` knows the gem once `gem install ruby-lsp` ran, in the cwd it was given.
env.script(
&sdk,
&env.sys,
"gem",
&format!(
r#"case "$1" in
@@ -640,10 +623,7 @@ esac"#,
b = bindir.display()
),
);
env.script(&env.sys, "ruby", "exit 99");
env.script(&env.sys, "gem", "exit 99");
let tools = env.tools().with_runtime(BTreeMap::from([("ruby".into(), sdk.join("ruby"))]), BTreeMap::new());
let tools = tools.with_work_dir(Some(project.clone()));
let tools = env.tools().with_work_dir(Some(project.clone()));
assert_eq!(find(&tools.list(&langs()), "ruby-lsp").status, ToolStatus::Missing);
let info = tools.install("ruby-lsp", &langs(), &CancellationToken::new(), &|_| {}).unwrap();
assert_eq!(info.status, ToolStatus::OnPath);
@@ -820,88 +800,3 @@ fn python_probes_run_in_an_empty_private_directory() {
let dir = env.root.join(".python-cwd");
assert_eq!(out.trim(), dir.canonicalize().unwrap().to_string_lossy());
}
#[cfg(unix)]
#[test]
fn go_installers_use_selected_sdk_instead_of_broken_mise_shim() {
for spec in registry::TOOLS.iter().filter(|s| matches!(s.method, registry::Method::Go { .. })) {
let env = Env::new();
env.script(&env.sys, "go", "echo 'mise ERROR No version is set for shim: go' >&2; exit 1");
let sdk = env._tmp.path().join("selected go");
let log = env._tmp.path().join("go.log");
env.script(
&sdk.join("bin"),
"go",
&format!(
r#"
[ "$GOROOT" = '{sdk}' ] || exit 99
echo "$@" >> '{log}'
case "$1" in
install) printf '#!/bin/sh\necho 1.2.3\n' > "$GOBIN/{command}"; /bin/chmod +x "$GOBIN/{command}" ;;
version) echo 'mod example.com/tool v1.2.3' ;;
esac
"#,
sdk = sdk.display(),
log = log.display(),
command = spec.commands[0]
),
);
let tools = env.tools().with_runtime(
BTreeMap::from([("go".into(), sdk.join("bin/go"))]),
BTreeMap::from([("GOROOT".into(), sdk.to_string_lossy().into_owned())]),
);
let info = tools.install(spec.name, &langs(), &CancellationToken::new(), &|_| {}).unwrap();
assert_eq!(info.status, ToolStatus::Installed, "{}", spec.name);
assert_eq!(info.version.as_deref(), Some("1.2.3"));
let log = fs::read_to_string(log).unwrap();
assert!(log.contains("install -v ") && log.contains("version -m"), "{log}");
tools.uninstall(spec.name, &langs()).unwrap();
assert!(
env.tools()
.install(spec.name, &langs(), &CancellationToken::new(), &|_| {})
.unwrap_err()
.message
.contains("failed")
);
}
}
#[cfg(unix)]
#[test]
fn selected_python_is_used_for_pip_and_uv_even_with_a_versioned_filename() {
let env = Env::new();
env.script(&env.sys, "python3", "exit 99");
let sdk = env._tmp.path().join("python-sdk");
let pip_log = env._tmp.path().join("pip.log");
env.script(
&sdk,
"python3.14",
&format!(
r#"
echo "$@" >> '{log}'
[ "$1" = "-c" ] && exit 1
while [ $# -gt 0 ]; do
if [ "$1" = "--target" ]; then
/bin/mkdir -p "$2/debugpy" "$2/debugpy-1.2.3.dist-info"
/usr/bin/touch "$2/debugpy/__init__.py"
exit 0
fi
shift
done
exit 1
"#,
log = pip_log.display()
),
);
let tools = env.tools().with_runtime(BTreeMap::from([("python".into(), sdk.join("python3.14"))]), BTreeMap::new());
assert_eq!(tools.python(), Some(sdk.join("python3.14")));
let info = tools.install("debugpy", &langs(), &CancellationToken::new(), &|_| {}).unwrap();
assert_eq!(info.status, ToolStatus::Installed);
assert_eq!(info.version.as_deref(), Some("1.2.3"));
assert!(fs::read_to_string(pip_log).unwrap().contains("-m pip install"));
let log = env._tmp.path().join("uv.log");
env.script(&env.sys, "uv", &format!("echo \"$@\" >> '{}'; exit 1", log.display()));
let _ = tools.install("ruff", &langs(), &CancellationToken::new(), &|_| {});
let args = fs::read_to_string(log).unwrap();
assert!(args.contains(&format!("--python {}", sdk.join("python3.14").display())), "{args}");
}
+1 -11
Переглянути файл
@@ -324,13 +324,6 @@ export interface SetupOptions {
* below its top edge. WebKit positions them `absolute` within `.cm-editor`, so
* a window-wide right bound makes CodeMirror skip the shift left and the
* browser squeezes the box into the space left of the editor's edge.
*
* They are parented to the body (#2310): tooltips are `position: fixed` but
* appended inside the editor by default, whose `.content{isolation:isolate}`
* stacking context paints as one unit below the later bottom toolwindow — so
* completion popups got covered where they overflowed the editor's bottom
* edge. At the body level their z-index (500) sits above panels
* (`--z-panel: 10`) while staying below dialogs (`--z-dialog: 900`).
*/
export function tooltipBounds(view: { scrollDOM: Element; dom: Element }) {
const { top } = view.scrollDOM.getBoundingClientRect();
@@ -343,10 +336,7 @@ export function tooltipBounds(view: { scrollDOM: Element; dom: Element }) {
};
}
const tooltipSpace = tooltips({
parent: typeof document === "undefined" ? undefined : document.body,
tooltipSpace: tooltipBounds,
});
const tooltipSpace = tooltips({ tooltipSpace: tooltipBounds });
export function baseExtensions(o: SetupOptions): Extension {
return [
+1 -2
Переглянути файл
@@ -110,8 +110,7 @@ describe.each([
view = editor();
activateHover(view, 2, 1);
await settle();
// Tooltips are parented to the body (#2310), not to the editor element.
const tooltip = document.querySelector(".cm-tooltip")!;
const tooltip = view.dom.querySelector(".cm-tooltip")!;
tooltip.dispatchEvent(new MouseEvent("mousemove", { bubbles: true }));
expect(pointerTarget()).toBe(tooltip);
key("keydown", mod, { [flag]: true });
+4 -3
Переглянути файл
@@ -23,7 +23,7 @@ import {
type RunConfig,
type SyncProgress,
} from "@/platform/ipc";
import { buildToolRecovery } from "@/platform/buildToolRecovery";
import { downloadJdkActions } from "@/platform/jdk";
import { useBuildModel } from "@/platform/buildModel";
import { useProject } from "@/platform/project";
import { editorService, notifications } from "@/workbench/contributions";
@@ -454,8 +454,9 @@ export async function syncTool(tool: BuildTool, buildDir: string | null = null):
group: "run",
level: "warning",
title: tool === "maven" ? "Maven sync finished with errors" : "Gradle sync failed",
...buildToolRecovery(error),
body: error,
key: `build-sync-${tool}`,
actions: downloadJdkActions(error),
});
} catch (e) {
if (!isCancelled(e))
@@ -463,7 +464,7 @@ export async function syncTool(tool: BuildTool, buildDir: string | null = null):
group: "run",
level: "error",
title: tool === "maven" ? "Cannot reload Maven projects" : "Cannot reload Gradle projects",
...buildToolRecovery(e instanceof Error ? e.message : String(e)),
body: e instanceof Error ? e.message : String(e),
key: `build-sync-${tool}`,
});
} finally {
-22
Переглянути файл
@@ -17,7 +17,6 @@ import { ConsoleView, type ConsoleInput } from "./ConsoleView";
import { buildRows, mnemonics } from "./ConfigChooser";
import { activate } from "./index";
import {
onRunExited,
closeSessionTab,
resetRuns,
runtime,
@@ -323,24 +322,3 @@ describe("plugin test selection launches", () => {
}
});
});
describe("Go SDK recovery", () => {
it.each([
["mise ERROR No version is set for shim: go", "go", 1, true],
["No version is set for shim: go", "shell", 1, false],
["compile error", "go", 1, false],
["No version is set for shim: go", "go", 0, false],
] as const)("offers Go settings for %s (%s, %s)", async (text, kind, code, expected) => {
const notify = vi.fn();
provideNotificationService({ notify });
const session = (await startRun(config("go", { kind })))!;
runtime(session.id)!.console.append({ kind: "stderr", text: text.slice(0, 12) });
runtime(session.id)!.console.append({ kind: "stderr", text: text.slice(12) + "\n" });
const runId = 4321 as NonNullable<RunSession["runId"]>;
useRun.setState((s) => ({ sessions: s.sessions.map((x) => ({ ...x, runId })) }));
onRunExited(runId, code);
await vi.waitFor(() => expect(useRun.getState().sessions[0]!.status).toBe("finished"));
expect(notify).toHaveBeenCalledTimes(expected ? 1 : 0);
if (expected) expect(notify.mock.calls[0]![0].actions[0].label).toBe("Go Settings…");
});
});
+1 -17
Переглянути файл
@@ -27,7 +27,6 @@ import {
prepareJavaLaunch,
} from "@/platform/javaLaunch";
import { downloadJdkActions } from "@/platform/jdk";
import { buildToolRecovery } from "@/platform/buildToolRecovery";
import { useProject } from "@/platform/project";
import { executeAction } from "@/platform/actions";
import { workflowSettings } from "@/platform/workflowSettings";
@@ -931,7 +930,7 @@ export async function startRun(
group: "run",
level: "error",
title: `Error running '${remoteLabel(config)}'`,
...buildToolRecovery(message),
body: message,
});
}
return getSession(sessionId) ?? null;
@@ -1104,21 +1103,6 @@ export function testReportEvents(reports: readonly TestCaseReport[]): TestEvent[
function notifyExit(sessionId: string, code: number | null) {
const session = getSession(sessionId);
if (!session || session.stopped || code === 0 || code === null) return;
if (
session.config.kind === "go" &&
!useProject.getState().settings?.languages?.go?.goroot?.trim() &&
/No version (?:is )?set for (?:shim: )?go/i.test(runtimes.get(sessionId)?.console.text() ?? "")
) {
notifications().notify({
group: "run",
level: "error",
key: `run-exit-${sessionId}`,
title: tx("Choose a Go SDK"),
body: tx("The Go version manager has no SDK selected. Choose an installed SDK in Go settings and run again."),
actions: [{ label: tx("Go Settings…"), run: () => void executeAction("file.settings", "languages.go") }],
});
return;
}
let visible = true;
try {
visible = toolWindowService().isVisible("run");
-47
Переглянути файл
@@ -1,47 +0,0 @@
import { afterEach, expect, it, vi } from "vitest";
const executeAction = vi.hoisted(() => vi.fn());
vi.mock("./actions", async (original) => ({
...(await original<typeof import("./actions")>()),
executeAction,
}));
import { buildToolRecovery } from "./buildToolRecovery";
afterEach(() => vi.clearAllMocks());
it.each([
["cannot start mvn: No such file or directory (os error 2)", "maven"],
["command not found: mvn", "maven"],
["command not found: /opt/apache maven/bin/mvn", "maven"],
["command not found: C:\\Maven\\bin\\mvn.cmd", "maven"],
["cannot start gradle: No such file or directory (os error 2)", "gradle"],
["command not found: gradle", "gradle"],
["command not found: C:\\Gradle\\bin\\gradle.bat", "gradle"],
["command not found: ./gradlew", "gradle"],
])("links missing build tool to its settings: %s", (message, tool) => {
const result = buildToolRecovery(message);
expect(result.body).toContain(`${tool === "maven" ? "Maven" : "Gradle"} could not be started`);
expect(result.body).toContain(message);
expect(result.actions).toHaveLength(1);
result.actions[0]!.run();
expect(executeAction).toHaveBeenCalledWith("file.settings", `build.${tool}`);
});
it("links the reported Gradle import rejection to the Gradle JVM picker and its JDK download", () => {
const message =
"Nov 9, 2026, 3:49:11 PM Can't use Java 27.0.1.0.3 and Gradle 9.7.1 to import Gradle project kotlin-gradle.";
const result = buildToolRecovery(message);
expect(result.body).toContain("Download JDK");
expect(result.actions[0]!.label).toBe("Choose Gradle JVM");
result.actions[0]!.run();
expect(executeAction).toHaveBeenCalledWith("file.settings", "build.gradle");
});
it.each([
"command not found: npm",
"Maven tests failed",
"Gradle build failed",
"cannot start mvn: Permission denied (os error 13)",
])("leaves unrelated failures alone: %s", (message) => {
expect(buildToolRecovery(message)).toEqual({ body: message, actions: [] });
});
-37
Переглянути файл
@@ -1,37 +0,0 @@
import { executeAction } from "./actions";
import { tx } from "./i18n";
import { downloadJdkActions } from "./jdk";
/** Recovery shared by build sync, run configurations and language-server import errors. */
export function buildToolRecovery(message: string) {
const actions = downloadJdkActions(message);
const incompatible = /Can't use Java .* and Gradle .* to import Gradle project/i.test(message);
const missing = /command not found: ([^\r\n]+)|cannot start ([^\r\n]+?): [^\r\n]*\(os error [23]\)/i.exec(message);
const command = (missing?.[1] ?? missing?.[2] ?? "").trim().replace(/^["'`]|["'`]$/g, "");
const namedTool = /(?:^|[/\\])(?:mvn|mvnw|mvnd)(?:\.(?:cmd|bat|exe))?$/i.test(command)
? "maven"
: /(?:^|[/\\])gradlew?(?:\.(?:bat|exe))?$/i.test(command)
? "gradle"
: undefined;
const recoveryTool = incompatible ? "gradle" : namedTool;
if (!recoveryTool) return { body: message, actions };
const label =
recoveryTool === "maven"
? tx("Open Maven Settings")
: incompatible
? tx("Choose Gradle JVM")
: tx("Open Gradle Settings");
actions.push({ label, run: () => void executeAction("file.settings", `build.${recoveryTool}`) });
const hint = incompatible
? tx(
"Choose a JDK compatible with this Gradle version in Gradle JVM. Download JDK is available in the JVM selector.",
)
: recoveryTool === "maven"
? tx(
"Maven could not be started. Configure Maven home in Maven settings, install Maven on PATH, or use a project with a Maven wrapper.",
)
: tx(
"Gradle could not be started. Configure a local installation in Gradle settings, install Gradle on PATH, or use a project with a Gradle wrapper.",
);
return { body: `${hint}\n\n${message}`, actions };
}
+1 -10
Переглянути файл
@@ -19,9 +19,6 @@
"Active frames keep running the old code until they return. New calls use the reloaded code.": "Active frames keep running the old code until they return. New calls use the reloaded code.",
"The bottom frame cannot be reset. Re-enter the method or restart the debug session to run the new code.": "The bottom frame cannot be reset. Re-enter the method or restart the debug session to run the new code.",
"Reset Frame ({0})": "Reset Frame ({0})",
"Choose a Go SDK": "Choose a Go SDK",
"The Go version manager has no SDK selected. Choose an installed SDK in Go settings and run again.": "The Go version manager has no SDK selected. Choose an installed SDK in Go settings and run again.",
"Go Settings…": "Go Settings…",
"Active Editor": "Active Editor",
"Soft-Wrap": "Soft-Wrap",
"The language server Java executable ({path}) cannot run on this machine. Choose a working JDK in {setting}, or set it to Auto.": "The language server Java executable ({path}) cannot run on this machine. Choose a working JDK in {setting}, or set it to Auto.",
@@ -735,11 +732,5 @@
"Select a .NET project": "Select a .NET project",
"Project evaluation failed": "Project evaluation failed",
"dotnet exited with code {0}": "dotnet exited with code {0}",
"Microsoft.Testing.Platform was not found in the restored project.": "Microsoft.Testing.Platform was not found in the restored project.",
"Open Maven Settings": "Open Maven Settings",
"Open Gradle Settings": "Open Gradle Settings",
"Choose Gradle JVM": "Choose Gradle JVM",
"Choose a JDK compatible with this Gradle version in Gradle JVM. Download JDK is available in the JVM selector.": "Choose a JDK compatible with this Gradle version in Gradle JVM. Download JDK is available in the JVM selector.",
"Maven could not be started. Configure Maven home in Maven settings, install Maven on PATH, or use a project with a Maven wrapper.": "Maven could not be started. Configure Maven home in Maven settings, install Maven on PATH, or use a project with a Maven wrapper.",
"Gradle could not be started. Configure a local installation in Gradle settings, install Gradle on PATH, or use a project with a Gradle wrapper.": "Gradle could not be started. Configure a local installation in Gradle settings, install Gradle on PATH, or use a project with a Gradle wrapper."
"Microsoft.Testing.Platform was not found in the restored project.": "Microsoft.Testing.Platform was not found in the restored project."
}
+1 -10
Переглянути файл
@@ -11,9 +11,6 @@
"Active frames keep running the old code until they return. New calls use the reloaded code.": "活动栈帧将继续执行旧代码,直到方法返回。新的调用将使用重新加载的代码。",
"The bottom frame cannot be reset. Re-enter the method or restart the debug session to run the new code.": "无法重置栈底帧。请重新进入该方法或重启调试会话,以执行新代码。",
"Reset Frame ({0})": "重置栈帧({0})",
"Choose a Go SDK": "选择 Go SDK",
"The Go version manager has no SDK selected. Choose an installed SDK in Go settings and run again.": "Go 版本管理器未选择 SDK。请在 Go 设置中选择已安装的 SDK,然后重新运行。",
"Go Settings…": "Go 设置…",
"Active Editor": "活动编辑器",
"The language server Java executable ({path}) cannot run on this machine. Choose a working JDK in {setting}, or set it to Auto.": "语言服务器的 Java 可执行文件({path})无法在此机器上运行。请在 {setting} 中选择可正常运行的 JDK,或设为自动。",
"Input queue is full (4 MiB or 1024 writes); input was not sent.": "输入队列已满(4 MiB 或 1024 次写入);本次输入未发送。",
@@ -7069,11 +7066,5 @@
"Run test": "运行测试",
"Project evaluation failed": "项目求值失败",
"dotnet exited with code {0}": "dotnet 已退出,退出码 {0}",
"Microsoft.Testing.Platform was not found in the restored project.": "还原后的项目中未找到 Microsoft.Testing.Platform。",
"Open Maven Settings": "打开 Maven 设置",
"Open Gradle Settings": "打开 Gradle 设置",
"Choose Gradle JVM": "选择 Gradle JVM",
"Choose a JDK compatible with this Gradle version in Gradle JVM. Download JDK is available in the JVM selector.": "请在 Gradle JVM 中选择与此 Gradle 版本兼容的 JDK。JVM 选择器中提供下载 JDK 选项。",
"Maven could not be started. Configure Maven home in Maven settings, install Maven on PATH, or use a project with a Maven wrapper.": "无法启动 Maven。请在 Maven 设置中配置 Maven 主目录,将 Maven 安装到 PATH,或使用带有 Maven wrapper 的项目。",
"Gradle could not be started. Configure a local installation in Gradle settings, install Gradle on PATH, or use a project with a Gradle wrapper.": "无法启动 Gradle。请在 Gradle 设置中配置本地安装,将 Gradle 安装到 PATH,或使用带有 Gradle wrapper 的项目。"
"Microsoft.Testing.Platform was not found in the restored project.": "还原后的项目中未找到 Microsoft.Testing.Platform。"
}
-22
Переглянути файл
@@ -1,7 +1,6 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen } from "@testing-library/react";
import { emitLocalIdeEvent } from "@/platform/ipc";
import { setLocale } from "@/platform/i18n";
import { registerStatusItem, registerToolWindow, type StatusItemContribution } from "./contributions";
import { orderStatusItems, StatusBar, TaskStatus } from "./StatusBar";
import { orderTitleItems } from "./TitleBar";
@@ -201,27 +200,6 @@ describe("notifications", () => {
uninstall();
});
it.each(["en", "zh"])("adds Gradle JVM recovery before translating backend messages (%s)", async (locale) => {
await setLocale(locale);
const uninstall = installNotifyEvents();
try {
act(() =>
emitLocalIdeEvent({
type: "notify",
level: "error",
title: "jdtls",
body: "Can't use Java 27.0.1.0.3 and Gradle 9.7.1 to import Gradle project kotlin-gradle.",
}),
);
const item = useNotifications.getState().items[0]!;
expect(item.actions?.map((a) => a.label)).toEqual([locale === "zh" ? "选择 Gradle JVM" : "Choose Gradle JVM"]);
expect(item.body).toContain(locale === "zh" ? "下载 JDK" : "Download JDK");
} finally {
uninstall();
await setLocale("en");
}
});
it("the Notifications tool window lists history, marks it read and hides balloons", () => {
const dispose = registerToolWindow({
id: NOTIFICATIONS_TOOL_WINDOW,
-86
Переглянути файл
@@ -1,86 +0,0 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import type { BuildModel, ProjectInfo, RunConfig } from "@/platform/ipc";
const mocks = vi.hoisted(() => ({ sync: vi.fn(), start: vi.fn(), notify: vi.fn() }));
vi.mock("@/platform/ipc", async (original) => {
const real = await original<typeof import("@/platform/ipc")>();
return {
...real,
isTauri: () => true,
commands: {
...real.commands,
buildSync: mocks.sync,
runStart: mocks.start,
runConfigs: async () => ({ status: "ok", data: [] }),
},
};
});
vi.mock("@tauri-apps/api/core", async (original) => ({
...(await original<typeof import("@tauri-apps/api/core")>()),
Channel: class {
onmessage: unknown = null;
},
}));
import { useProject } from "@/platform/project";
import { provideNotificationService } from "@/workbench/contributions";
import { resetBuild, syncTool, useBuild } from "../features/build-tools/store";
import { resetRuns, startRun } from "../features/run/store";
beforeEach(() => {
vi.clearAllMocks();
useProject.setState({ project: { root: "/p", trusted: true } as ProjectInfo });
useBuild.setState({ root: "/p", syncing: {}, model: { maven: null, gradle: [] } });
provideNotificationService({ notify: mocks.notify });
});
afterEach(() => {
resetBuild();
resetRuns();
});
it.each(["maven", "gradle"] as const)("offers settings for %s sync failures, returned or thrown", async (tool) => {
const command = tool === "maven" ? "mvn" : "gradle";
const message = `cannot start ${command}: No such file or directory (os error 2)`;
mocks.sync.mockRejectedValueOnce(new Error(message));
await syncTool(tool);
expect(mocks.notify).toHaveBeenLastCalledWith(
expect.objectContaining({
actions: [expect.objectContaining({ label: `Open ${tool === "maven" ? "Maven" : "Gradle"} Settings` })],
body: expect.stringContaining(message),
}),
);
const model = (tool === "maven"
? { maven: { syncError: message }, gradle: [] }
: { maven: null, gradle: [{ syncError: message }] }) as unknown as BuildModel;
mocks.sync.mockResolvedValueOnce({ status: "ok", data: model });
await syncTool(tool);
expect(mocks.notify).toHaveBeenLastCalledWith(
expect.objectContaining({
actions: [expect.objectContaining({ label: `Open ${tool === "maven" ? "Maven" : "Gradle"} Settings` })],
}),
);
});
it.each(["maven", "gradle"] as const)("offers settings when a %s run cannot start", async (kind) => {
const command = kind === "maven" ? "mvn" : "gradle";
const config: RunConfig = {
id: kind,
name: `${command} test`,
kind,
command,
args: ["test"],
cwd: null,
env: {},
detected: true,
isTest: false,
debugAdapter: null,
};
mocks.start.mockRejectedValueOnce(new Error(`command not found: ${command}`));
await startRun(config, undefined, undefined, { prepared: true, show: false });
expect(mocks.start).toHaveBeenCalledOnce();
expect(mocks.notify).toHaveBeenLastCalledWith(
expect.objectContaining({
actions: [expect.objectContaining({ label: `Open ${kind === "maven" ? "Maven" : "Gradle"} Settings` })],
}),
);
});
+1 -10
Переглянути файл
@@ -2,7 +2,6 @@
import type { ReactNode } from "react";
import { create } from "zustand";
import { call, commands, onIdeEvent } from "@/platform/ipc";
import { buildToolRecovery } from "@/platform/buildToolRecovery";
import { txTemplate } from "@/platform/i18n";
import { useProject } from "@/platform/project";
import type { NotificationService } from "./contributions";
@@ -203,14 +202,6 @@ export function installNotifyEvents(): () => void {
return onIdeEvent(
"notify",
// Backend text may carry values (paths, names); `{name}` catalog templates translate it.
(e) => {
const recovery = e.body ? buildToolRecovery(e.body) : undefined;
void notify({
level: e.level,
title: txTemplate(e.title),
...recovery,
body: recovery ? txTemplate(recovery.body) : undefined,
});
},
(e) => void notify({ level: e.level, title: txTemplate(e.title), body: e.body ? txTemplate(e.body) : undefined }),
);
}