From 30291971e115ee4331402c2ca495e0688b7a3a65 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Thu, 26 Nov 2026 18:00:44 +0800 Subject: [PATCH] fix(remote): offer to stop another build's backend that keeps a project (#6147) A remote daemon of another build refuses to retire while it has terminals, runs, agent sessions or unsaved changes. After an upgrade left such a daemon (its binary gone, so no build can reconnect to it), the project could not be opened and the error only asked to reconnect with the old build. The refusal now comes back as RemoteBackendBusy and the window asks whether to stop that backend. Agreeing reconnects with `openidea-server --attach --replace`, which sends the old daemon SIGTERM (its own shutdown), kills it after the shutdown timeout if needed, and starts this build's daemon. Works for SSH hosts, WSL and dev containers, and for daemons of earlier builds (found by their --daemon command line). Fixes #6119 --- crates/ide-core/src/error.rs | 2 + crates/ide-host/src/bin/server.rs | 26 ++++--- crates/ide-host/src/daemon.rs | 93 +++++++++++++++++++++++--- crates/ide-host/src/rpc.rs | 4 ++ crates/ide-host/tests/remote_daemon.rs | 56 +++++++++++++++- src-tauri/src/remote_container.rs | 27 +++++--- src-tauri/src/remote_dev.rs | 13 +++- src-tauri/src/remote_wsl.rs | 16 +++-- src/bindings.ts | 6 +- src/features/remote-dev/index.ts | 12 +++- src/platform/locales/text/en.json | 4 +- src/platform/locales/text/zh.json | 4 +- src/platform/remote.ts | 25 ++++++- src/platform/remoteBackendBusy.test.ts | 50 ++++++++++++++ 14 files changed, 297 insertions(+), 41 deletions(-) create mode 100644 src/platform/remoteBackendBusy.test.ts diff --git a/crates/ide-core/src/error.rs b/crates/ide-core/src/error.rs index 2d40a50954..35bc813948 100644 --- a/crates/ide-core/src/error.rs +++ b/crates/ide-core/src/error.rs @@ -46,6 +46,8 @@ pub enum ErrorData { JavaBuildProblems { problems: Vec, }, + /// A remote backend of another OpenIDEA build still serves the project and refused to retire. + RemoteBackendBusy, } /// Git's reported result for each destination ref. A remote with several push URLs can diff --git a/crates/ide-host/src/bin/server.rs b/crates/ide-host/src/bin/server.rs index c10ed7724a..ec6ec8054c 100644 --- a/crates/ide-host/src/bin/server.rs +++ b/crates/ide-host/src/bin/server.rs @@ -46,18 +46,26 @@ fn main() { #[cfg(unix)] if args.first().is_some_and(|a| a == "--attach") { let Some(project_path) = args.get(1).filter(|p| !p.is_empty()) else { - eprintln!("usage: openidea-server --attach "); + eprintln!("usage: openidea-server --attach [--replace]"); std::process::exit(2); }; + // `--replace`: stop another build's backend that still holds the project. + let replace = args.get(2).is_some_and(|a| a == "--replace"); let home = dirs::home_dir().unwrap_or_default(); - let code = - match ide_host::daemon::attach(&base, &home, project_path, std::io::stdin(), std::io::stdout().lock()) { - Ok(()) => 0, - Err(e) => { - eprintln!("{e}"); - 1 - } - }; + let code = match ide_host::daemon::attach( + &base, + &home, + project_path, + replace, + std::io::stdin(), + std::io::stdout().lock(), + ) { + Ok(()) => 0, + Err(e) => { + eprintln!("{e}"); + 1 + } + }; std::process::exit(code); } let mode = match args.as_slice() { diff --git a/crates/ide-host/src/daemon.rs b/crates/ide-host/src/daemon.rs index 2acfded018..461335e87d 100644 --- a/crates/ide-host/src/daemon.rs +++ b/crates/ide-host/src/daemon.rs @@ -121,11 +121,13 @@ fn ensure_private_dir(dir: &Path) -> io::Result<()> { } /// Connects to the daemon for `project_path` (spawning it if needed) and bridges -/// `input` / `output` to its Unix socket. +/// `input` / `output` to its Unix socket. With `replace`, a daemon of another build that +/// refuses to retire is stopped first. pub fn attach( base: &Path, home: &Path, project_path: &str, + replace: bool, input: impl Read + Send + 'static, output: impl Write, ) -> Result<(), String> { @@ -137,11 +139,11 @@ pub fn attach( .map_err(|e| format!("cannot identify openidea-server build: {e}"))?; let hex = hasher.finalize().to_hex(); let build = &hex.as_str()[..16]; - let stream = connect_or_spawn(&exe, &paths, build)?; + let stream = connect_or_spawn(&exe, &paths, build, replace)?; bridge(stream, input, output).map_err(|e| format!("daemon relay failed: {e}")) } -fn connect_or_spawn(exe: &Path, paths: &DaemonPaths, build: &str) -> Result { +fn connect_or_spawn(exe: &Path, paths: &DaemonPaths, build: &str, replace: bool) -> Result { let lock_file = OpenOptions::new() .create(true) .truncate(false) @@ -153,8 +155,11 @@ fn connect_or_spawn(exe: &Path, paths: &DaemonPaths, build: &str) -> Result return Ok(stream), + Ok(None) => {} + Err(e) if replace && e.contains(rpc::OTHER_BUILD_BUSY) => stop_daemon(&paths.socket)?, + Err(e) => return Err(e), } match std::fs::remove_file(&paths.socket) { @@ -232,10 +237,7 @@ fn existing_daemon(paths: &DaemonPaths, build: &str) -> Result Err(io::Error::other( - "Another build of OpenIDEA still has this project open, is running tasks, or has unsaved changes. \ - Reconnect with that build, then stop the remote backend before upgrading.", - )), + BUSY => Err(io::Error::other(rpc::OTHER_BUILD_BUSY)), _ => Err(io::Error::other("unrecognized remote backend response")), } }; @@ -247,6 +249,63 @@ fn existing_daemon(paths: &DaemonPaths, build: &str) -> Result Result<(), String> { + let pids = daemon_pids(socket)?; + if pids.is_empty() { + return Err(format!("cannot find the backend serving {}", socket.display())); + } + let signal = |sig| { + for pid in &pids { + if let Some(pid) = rustix::process::Pid::from_raw(*pid) { + let _ = rustix::process::kill_process(pid, sig); + } + } + }; + let alive = || pids.iter().any(|pid| process_exists(*pid)); + signal(rustix::process::Signal::TERM); + let deadline = Instant::now() + rpc::SHUTDOWN_TIMEOUT; + while alive() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(50)); + } + if alive() { + signal(rustix::process::Signal::KILL); + std::thread::sleep(Duration::from_millis(200)); + } + Ok(()) +} + +/// Whether `pid` still runs: an exited process its parent hasn't reaped yet (a zombie) doesn't. +fn process_exists(pid: i32) -> bool { + if !rustix::process::Pid::from_raw(pid).is_some_and(|pid| rustix::process::test_kill_process(pid).is_ok()) { + return false; + } + Command::new("ps") + .args(["-o", "stat=", "-p", &pid.to_string()]) + .output() + .map_or(true, |out| !String::from_utf8_lossy(&out.stdout).trim_start().starts_with('Z')) +} + +/// Processes started as `openidea-server --daemon `. +fn daemon_pids(socket: &Path) -> Result, String> { + let out = Command::new("ps") + .args(["-axww", "-o", "pid=", "-o", "args="]) + .output() + .map_err(|e| format!("cannot list processes: {e}"))?; + Ok(daemon_pids_in(&String::from_utf8_lossy(&out.stdout), &socket.to_string_lossy())) +} + +fn daemon_pids_in(ps: &str, socket: &str) -> Vec { + ps.lines() + .filter_map(|line| { + let (pid, args) = line.trim_start().split_once(char::is_whitespace)?; + let mut words = args.split_whitespace().skip_while(|w| *w != "--daemon").skip(1); + (words.next() == Some(socket)).then(|| pid.parse().ok()).flatten() + }) + .collect() +} + fn read_log_tail(file: &mut File, offset: u64) -> String { if file.seek(SeekFrom::Start(offset)).is_err() { return String::new(); @@ -480,3 +539,19 @@ fn has_live_work(host: &Host) -> bool { .iter() .any(|project| project.agents.has_live_work() || project.documents.has_unsaved_changes()) } + +#[cfg(test)] +mod tests { + use super::daemon_pids_in; + + #[test] + fn finds_the_daemon_of_a_socket_in_the_process_list() { + let ps = " 1 /sbin/init\n\ + 581660 /root/.openidea/server/0.1.51/634a/openidea-server --daemon /root/.openidea/run/s-de2d.sock 634a\n\ + 141712 /root/.openidea/server/0.1.53/e116/openidea-server --daemon /root/.openidea/run/s-a67f.sock e116\n\ + 582484 /bin/bash --init-file /tmp/openidea-shell-integration-0.1.51/bash/openidea.bashrc -i\n\ + 590000 grep --daemon /root/.openidea/run/s-de2d.sock.bak\n"; + assert_eq!(daemon_pids_in(ps, "/root/.openidea/run/s-de2d.sock"), [581660]); + assert!(daemon_pids_in(ps, "/root/.openidea/run/s-none.sock").is_empty()); + } +} diff --git a/crates/ide-host/src/rpc.rs b/crates/ide-host/src/rpc.rs index 39bf441344..98c84d72f1 100644 --- a/crates/ide-host/src/rpc.rs +++ b/crates/ide-host/src/rpc.rs @@ -32,6 +32,10 @@ use std::sync::{Arc, OnceLock}; /// doesn't know the event would show stale output. pub const PROTOCOL_VERSION: u32 = 4; pub const SESSION_REPLACED: &str = "session_replaced"; +/// What `openidea-server --attach` reports when another build's backend keeps the project +/// (clients match it to offer stopping that backend). +pub const OTHER_BUILD_BUSY: &str = "Another build of OpenIDEA still has this project open, is running tasks, or has \ + unsaved changes. Reconnect with that build, or stop its backend and open the project again."; pub const SHUTDOWN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(90); /// Advertised only by a persistent backend with an editable idle timeout. diff --git a/crates/ide-host/tests/remote_daemon.rs b/crates/ide-host/tests/remote_daemon.rs index f2dc9144c7..55e43bec4b 100644 --- a/crates/ide-host/tests/remote_daemon.rs +++ b/crates/ide-host/tests/remote_daemon.rs @@ -782,7 +782,7 @@ async fn upgraded_build_refuses_live_work_and_then_replaces_idle_backend() { .unwrap() .unwrap(); assert!(!rejected.status.success()); - assert!(String::from_utf8_lossy(&rejected.stderr).contains("Another build of OpenIDEA"), "{rejected:?}"); + assert!(String::from_utf8_lossy(&rejected.stderr).contains(ide_host::rpc::OTHER_BUILD_BUSY), "{rejected:?}"); assert!(previous_build.try_wait().unwrap().is_none(), "the live backend was replaced"); let resumed = old_open().await; assert_eq!(invoke(&resumed, "term_list", json!({})).await.unwrap()[0]["id"], term["id"]); @@ -798,6 +798,60 @@ async fn upgraded_build_refuses_live_work_and_then_replaces_idle_backend() { shutdown(&new).await; } +/// `--attach --replace` stops another build's backend that refuses to retire (#6119). +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn replace_stops_another_builds_busy_backend() { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + use tokio::net::UnixStream; + + const OLD_BUILD: &str = "fedcba9876543210"; + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path().join("h"); + let base = tmp.path().join("s"); + let project = home.join("demo"); + std::fs::create_dir_all(&project).unwrap(); + let guard = DaemonGuard(ide_host::daemon::paths_for(&base, &home, "~/demo").unwrap().socket); + let mut previous_build = tokio::process::Command::new(SERVER) + .arg("--daemon") + .arg(&guard.0) + .arg(OLD_BUILD) + .envs(server_env(&home, &base, 10_800)) + .kill_on_drop(true) + .spawn() + .unwrap(); + until("old backend socket", || guard.0.exists()).await; + let mut stream = 'connect: { + for _ in 0..600 { + match UnixStream::connect(&guard.0).await { + Err(e) if e.kind() == std::io::ErrorKind::ConnectionRefused => { + tokio::time::sleep(Duration::from_millis(15)).await; + } + other => break 'connect other.unwrap(), + } + } + panic!("the old backend never accepted a connection"); + }; + stream.write_all(OLD_BUILD.as_bytes()).await.unwrap(); + assert_eq!(stream.read_u8().await.unwrap(), b'A'); + let (reader, writer) = stream.into_split(); + let old = Peer::connect(reader, writer, Arc::new(Client::default())); + initialize(&old).await; + let term = looping_terminal(&old, &project).await; + old.kill(); + old.closed().await; + + let client = Arc::new(Client::default()); + let args = ["--attach", "~/demo", "--replace"].map(str::to_owned).to_vec(); + let env = server_env(&home, &base, 10_800); + let new = Peer::spawn(SERVER, &args, &home, &env, client, Box::new(|line| eprintln!("{line}"))).unwrap(); + initialize(&new).await; + let old_exit = tokio::time::timeout(Duration::from_secs(15), previous_build.wait()).await.unwrap().unwrap(); + assert!(old_exit.success(), "the old backend did not shut down cleanly: {old_exit:?}"); + until("its terminal stopped", || !pid_alive(term["pid"].as_u64().unwrap() as u32)).await; + assert!(invoke(&new, "term_list", json!({})).await.unwrap().as_array().unwrap().is_empty()); + shutdown(&new).await; +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] #[ignore = "requires a Docker context with Docker Compose and the busybox image"] async fn compose_service_survives_disconnect_and_is_removed_on_stop() { diff --git a/src-tauri/src/remote_container.rs b/src-tauri/src/remote_container.rs index 12f1511eec..0cbfcb6cf1 100644 --- a/src-tauri/src/remote_container.rs +++ b/src-tauri/src/remote_container.rs @@ -164,7 +164,7 @@ async fn install( /// The arguments of `docker` that start the server in the container: in the project folder, told /// that the folder is trusted and that the CLI already ran the lifecycle commands. -fn server_args(up: &Up, bin: &str) -> Vec { +fn server_args(up: &Up, bin: &str, replace: bool) -> Vec { let mut args: Vec = ["exec", "-i", "-u", &up.user, "-w", &up.folder].map(str::to_owned).into(); for var in [ format!("{}={}", ide_host::trust::TRUSTED_ROOT_ENV, up.folder), @@ -173,6 +173,9 @@ fn server_args(up: &Up, bin: &str) -> Vec { args.extend(["-e".to_owned(), var]); } args.extend([up.container.clone(), bin.to_owned(), "--attach".to_owned(), up.folder.clone()]); + if replace { + args.push("--replace".to_owned()); + } args } @@ -183,6 +186,7 @@ pub(crate) async fn connect( state: &crate::state::AppState, folder: &str, config: &str, + replace: bool, handler: Arc, tail: &Tail, progress: &Arc, @@ -215,16 +219,23 @@ pub(crate) async fn connect( let up = up(&cli, &docker, &local, config, tail).await?; let bin = ensure_server(state, &docker, &up, progress).await?; progress(RemoteStage::Starting, None); - let peer = spawn(&docker, &up, &bin, handler, tail)?; + let peer = spawn(&docker, &up, &bin, replace, handler, tail)?; let folder = up.folder.clone(); Ok((peer, folder, Exec::new(docker, up, bin))) } -fn spawn(docker: &Path, up: &Up, bin: &str, handler: Arc, tail: &Tail) -> IdeResult { +fn spawn(docker: &Path, up: &Up, bin: &str, replace: bool, handler: Arc, tail: &Tail) -> IdeResult { let tail = tail.clone(); let program = docker.to_string_lossy(); - Peer::spawn(&program, &server_args(up, bin), &std::env::temp_dir(), &[], handler, Box::new(move |l| tail.push(l))) - .map_err(|e| IdeError::unavailable(format!("cannot start docker: {e}"))) + Peer::spawn( + &program, + &server_args(up, bin, replace), + &std::env::temp_dir(), + &[], + handler, + Box::new(move |l| tail.push(l)), + ) + .map_err(|e| IdeError::unavailable(format!("cannot start docker: {e}"))) } #[cfg(test)] @@ -237,7 +248,7 @@ mod tests { #[test] fn the_server_starts_in_the_folder_trusted_and_without_the_lifecycle() { let up = Up { container: ID.into(), user: "vscode".into(), folder: "/workspaces/my app".into() }; - let args = server_args(&up, "/home/vscode/.openidea/server/1/ab/openidea-server"); + let args = server_args(&up, "/home/vscode/.openidea/server/1/ab/openidea-server", false); assert_eq!( args, [ @@ -374,7 +385,7 @@ echo '{{"outcome":"success","containerId":"{ID}","remoteUser":"vscode","remoteWo let dir = version_dir(&found.home, "0.0.0-test"); let bin = install(&docker, &up, &dir, "b1", &server, &progress).await.unwrap(); assert_eq!(probe(&docker, &up, "0.0.0-test").await.unwrap().installed, std::slice::from_ref(&bin)); - let peer = spawn(&docker, &up, &bin, Arc::new(Silent), &tail).unwrap(); + let peer = spawn(&docker, &up, &bin, false, Arc::new(Silent), &tail).unwrap(); let info: ide_host::rpc::ServerInfo = peer .request("initialize", serde_json::json!({ "version": ide_host::rpc::PROTOCOL_VERSION }), None) .await @@ -446,7 +457,7 @@ echo '{{"outcome":"success","containerId":"{ID}","remoteUser":"vscode","remoteWo let live = || docker_sh(&docker, &up.container, &format!("kill -0 {pid} 2>/dev/null && printf live")); assert_eq!(live(), "live", "the terminal must outlive the window in a dev container"); - let peer = spawn(&docker, &up, &bin, Arc::new(Silent), &Tail::default()).unwrap(); + let peer = spawn(&docker, &up, &bin, false, Arc::new(Silent), &Tail::default()).unwrap(); tokio::time::timeout(Duration::from_secs(30), async { let project: Value = peer.request("invoke", invoke("project_current", json!({})), None).await.unwrap(); assert_eq!(project["root"], up.folder); diff --git a/src-tauri/src/remote_dev.rs b/src-tauri/src/remote_dev.rs index 3b13f3d9ad..8208877257 100644 --- a/src-tauri/src/remote_dev.rs +++ b/src-tauri/src/remote_dev.rs @@ -673,6 +673,7 @@ pub async fn remote_connect( state: State<'_, AppState>, target: RemoteTarget, mut path: String, + replace: bool, on_progress: Channel, ) -> IdeResult { let progress: Arc = Arc::new(move |stage, fraction| { @@ -704,9 +705,10 @@ pub async fn remote_connect( let attach_arg = if path.trim().is_empty() { "~" } else { path.trim() }; let stream = session .exec_stream(&format!( - "{} --attach {} 2>&1", + "{} --attach {}{} 2>&1", ide_ssh::shell::tilde_quote(&bin), ide_ssh::shell::quote(attach_arg), + if replace { " --replace" } else { "" }, )) .await .map_err(|e| IdeError::unavailable(format!("cannot start openidea-server: {e}")))?; @@ -723,12 +725,12 @@ pub async fn remote_connect( let bin = crate::remote_wsl::ensure_server(&state, distro, progress.clone()).await?; progress(RemoteStage::Starting, None); let attach_arg = if path.trim().is_empty() { "~" } else { path.trim() }; - let peer = crate::remote_wsl::spawn(distro, &bin, attach_arg, handler, &tail)?; + let peer = crate::remote_wsl::spawn(distro, &bin, attach_arg, replace, handler, &tail)?; (peer, None, distro.clone(), format!("WSL: {distro}")) } RemoteTarget::DevContainer { folder, config } => { let (peer, root, run) = - crate::remote_container::connect(&state, folder, config, handler, &tail, &progress).await?; + crate::remote_container::connect(&state, folder, config, replace, handler, &tail, &progress).await?; path = root; exec = Some(Arc::new(run)); let name = std::path::Path::new(folder) @@ -740,6 +742,11 @@ pub async fn remote_connect( // A server that dies on start-up says why on stderr (`wsl.exe` prints its own errors too). let with_output = |e: IdeError| match tail.text() { t if t.is_empty() => e, + // Another build's backend holds the project: the window offers to stop it (#6119). + t if t.contains(ide_host::rpc::OTHER_BUILD_BUSY) => IdeError { + data: Some(ide_core::error::ErrorData::RemoteBackendBusy), + ..IdeError::unavailable(ide_host::rpc::OTHER_BUILD_BUSY) + }, t => IdeError::unavailable(format!("{}: {t}", e.message)), }; let info: ServerInfo = peer diff --git a/src-tauri/src/remote_wsl.rs b/src-tauri/src/remote_wsl.rs index 3db7315400..5e4c485cd9 100644 --- a/src-tauri/src/remote_wsl.rs +++ b/src-tauri/src/remote_wsl.rs @@ -187,10 +187,11 @@ pub(crate) fn spawn( distro: &str, bin: &str, project_path: &str, + replace: bool, handler: Arc, tail: &Tail, ) -> IdeResult { - spawn_with(ide_core::wsl::EXE, distro, bin, project_path, handler, tail) + spawn_with(ide_core::wsl::EXE, distro, bin, project_path, replace, handler, tail) } /// [`spawn`] through `launcher` instead of `wsl.exe` (tests put a stand-in there). @@ -199,10 +200,15 @@ fn spawn_with( distro: &str, bin: &str, project_path: &str, + replace: bool, handler: Arc, tail: &Tail, ) -> IdeResult { - let args: Vec = ["-d", checked(distro)?, "--exec", bin, "--attach", project_path].map(str::to_owned).into(); + let mut args: Vec = + ["-d", checked(distro)?, "--exec", bin, "--attach", project_path].map(str::to_owned).into(); + if replace { + args.push("--replace".to_owned()); + } let tail = tail.clone(); Peer::spawn(launcher, &args, &std::env::temp_dir(), &[], handler, Box::new(move |line| tail.push(line))) .map_err(|e| IdeError::unavailable(format!("cannot start wsl.exe: {e}"))) @@ -305,7 +311,8 @@ printf 'Content-Length: %s\r\n\r\n%s' "${{#body}}" "$body" std::fs::write(&launcher, script).unwrap(); std::fs::set_permissions(&launcher, std::fs::Permissions::from_mode(0o755)).unwrap(); let tail = Tail::default(); - let peer = spawn_with(launcher.to_str().unwrap(), distro, bin, project, Arc::new(Silent), &tail).unwrap(); + let peer = + spawn_with(launcher.to_str().unwrap(), distro, bin, project, false, Arc::new(Silent), &tail).unwrap(); let reply: String = peer.request("ping", serde_json::Value::Null, None).await.unwrap_or_else(|e| { panic!("{e:?}; launcher said: {}", tail.text()); }); @@ -314,7 +321,8 @@ printf 'Content-Length: %s\r\n\r\n%s' "${{#body}}" "$body" #[tokio::test] async fn a_bad_distro_name_never_starts_the_launcher() { - let err = spawn_with("does-not-exist", "-d", "/x", "~", Arc::new(Silent), &Tail::default()).err().unwrap(); + let err = + spawn_with("does-not-exist", "-d", "/x", "~", false, Arc::new(Silent), &Tail::default()).err().unwrap(); assert!(err.message.contains("not a valid"), "{}", err.message); } } diff --git a/src/bindings.ts b/src/bindings.ts index 5da54653af..7e0354ee5b 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -1517,7 +1517,7 @@ export const commands = { * dev container, whose project folder is the container's own) in this window (installs / * starts the server as needed). */ - remoteConnect: (target: RemoteTarget, path: string, onProgress: Channel) => typedError(__TAURI_INVOKE("remote_connect", { target, path, onProgress })), + remoteConnect: (target: RemoteTarget, path: string, replace: boolean, onProgress: Channel) => typedError(__TAURI_INVOKE("remote_connect", { target, path, replace, onProgress })), /** The remote session of this window (a settings window: its parent's), if any. */ remoteCurrent: () => __TAURI_INVOKE<{ target: RemoteTarget, @@ -6855,7 +6855,9 @@ report?: PushReport | null } | * jdtls could not set a module up as a Java project: the errors on its build files and * the builds enclosing it (`path: message`, the path relative to the project), nearest first. */ -{ type: "javaBuildProblems"; problems: string[] }; +{ type: "javaBuildProblems"; problems: string[] } | +/** A remote backend of another OpenIDEA build still serves the project and refused to retire. */ +{ type: "remoteBackendBusy" }; export type ErrorKind = "notFound" | "alreadyExists" | "permissionDenied" | "invalidInput" | /** The requested state is stale; the UI must use the current snapshot. */ diff --git a/src/features/remote-dev/index.ts b/src/features/remote-dev/index.ts index 6bc74adc88..c1c148bdbc 100644 --- a/src/features/remote-dev/index.ts +++ b/src/features/remote-dev/index.ts @@ -4,7 +4,7 @@ * to it (platform/remote.ts). */ import { registerActions } from "@/platform/actions"; -import { disconnectRemote, stopRemoteBackend, useRemote } from "@/platform/remote"; +import { disconnectRemote, provideBackendBusyPrompt, stopRemoteBackend, useRemote } from "@/platform/remote"; import { lazyComponent } from "@/ui"; import { maybeEditorService, registerOverlay, registerStatusItem, registerToolWindow } from "@/workbench/contributions"; import { confirm } from "@/workbench/messages"; @@ -57,6 +57,16 @@ function trackPortsWindow(): () => void { export function activate(): () => void { const disposers = [ + provideBackendBusyPrompt(() => + confirm({ + title: tx("Stop Remote Backend"), + message: tx( + "The backend of another OpenIDEA build, for example the one from before an upgrade, still has this project open, so this build can't open it. Stop that backend and open the project? Its terminals, runs and agent sessions end, and changes it hasn't saved are lost.", + ), + ok: tx("Stop Backend and Open"), + icon: "warning", + }), + ), trackPortsWindow(), installReconnect(), installDirenvNotifications(), diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 045d59fa08..8a8a5299ed 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -4071,5 +4071,7 @@ "Granted with grant option": "Granted with grant option", "No privileges are granted on this table.": "No privileges are granted on this table.", "* With grant option: the grantee may grant the privilege to others.": "* With grant option: the grantee may grant the privilege to others.", - "Separate several prefixes with commas: they are tried in order, then the official source.": "Separate several prefixes with commas: they are tried in order, then the official source." + "Separate several prefixes with commas: they are tried in order, then the official source.": "Separate several prefixes with commas: they are tried in order, then the official source.", + "The backend of another OpenIDEA build, for example the one from before an upgrade, still has this project open, so this build can't open it. Stop that backend and open the project? Its terminals, runs and agent sessions end, and changes it hasn't saved are lost.": "The backend of another OpenIDEA build, for example the one from before an upgrade, still has this project open, so this build can't open it. Stop that backend and open the project? Its terminals, runs and agent sessions end, and changes it hasn't saved are lost.", + "Stop Backend and Open": "Stop Backend and Open" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index ede77150c1..db2215b1e7 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -10402,5 +10402,7 @@ "No privileges are granted on this table.": "此表未授予任何权限。", "* With grant option: the grantee may grant the privilege to others.": "* WITH GRANT OPTION:被授权者可以将该权限再授予他人。", "Separate several prefixes with commas: they are tried in order, then the official source.": "多个前缀用逗号分隔:按顺序尝试,最后回退到官方源。", - "Recent Find Usages": "最近的查找用法" + "Recent Find Usages": "最近的查找用法", + "The backend of another OpenIDEA build, for example the one from before an upgrade, still has this project open, so this build can't open it. Stop that backend and open the project? Its terminals, runs and agent sessions end, and changes it hasn't saved are lost.": "另一个 OpenIDEA 版本(例如升级前的版本)的后端仍打开着这个项目,当前版本无法打开它。要停止那个后端并打开项目吗?它的终端、运行和智能体会话会结束,未保存的修改会丢失。", + "Stop Backend and Open": "停止后端并打开" } diff --git a/src/platform/remote.ts b/src/platform/remote.ts index 399c92ff7b..0ef0142b2e 100644 --- a/src/platform/remote.ts +++ b/src/platform/remote.ts @@ -237,6 +237,27 @@ async function attachRemote(r: RemoteProject, path: string): Promise { let connectAttempt = 0; +let backendBusyPrompt: ((target: RemoteTarget) => Promise) | null = null; + +/** Asks whether to stop another build's backend that still holds the project (#6119). */ +export function provideBackendBusyPrompt(value: (target: RemoteTarget) => Promise): () => void { + backendBusyPrompt = value; + return () => { + if (backendBusyPrompt === value) backendBusyPrompt = null; + }; +} + +/** Connects; when another build's backend still holds the project, stops it once the user agrees. */ +async function connectOrReplace(target: RemoteTarget, path: string, onProgress: Channel) { + try { + return await call(commands.remoteConnect(target, path, false, onProgress)); + } catch (e) { + const busy = e instanceof IpcError && e.data?.type === "remoteBackendBusy"; + if (!busy || !backendBusyPrompt || !(await backendBusyPrompt(target))) throw e; + return await call(commands.remoteConnect(target, path, true, onProgress)); + } +} + /** * Opens `path` of `target` (an SSH host or a WSL distribution) in this window. A dev container's * project folder is the one in the container: `path` is then only a label. @@ -256,7 +277,7 @@ export async function connectRemote(target: RemoteTarget, path: string) { location, }); try { - const r = await call(commands.remoteConnect(target, path, onProgress)); + const r = await connectOrReplace(target, path, onProgress); // Another connect replaced this one, or the user cancelled. Disconnecting here // would drop the connection that replacement published. Cancel already disconnects. if (!current()) { @@ -280,7 +301,7 @@ export async function reconnectRemote(): Promise { if (!session) return; useRemote.setState({ reconnecting: true }); try { - const r = await call(commands.remoteConnect(session.target, session.root, new Channel())); + const r = await connectOrReplace(session.target, session.root, new Channel()); useProject.setState({ project: null }); await attachRemote(r, session.root); } finally { diff --git a/src/platform/remoteBackendBusy.test.ts b/src/platform/remoteBackendBusy.test.ts new file mode 100644 index 0000000000..5d2c63805d --- /dev/null +++ b/src/platform/remoteBackendBusy.test.ts @@ -0,0 +1,50 @@ +import { afterEach, expect, it, vi } from "vitest"; +import { commands, type RemoteTarget } from "./ipc"; +import { connectRemote, provideBackendBusyPrompt } from "./remote"; + +vi.mock("@tauri-apps/api/core", async (original) => ({ + ...(await original()), + Channel: class { + onmessage: unknown = null; + }, +})); +vi.mock("./ipc", async (original) => ({ + ...(await original()), + isTauri: () => true, +})); + +const target: RemoteTarget = { kind: "ssh", config: "box" }; +const busy = { + status: "error" as const, + error: { kind: "unavailable" as const, message: "busy", data: { type: "remoteBackendBusy" as const } }, +}; +const stop = { status: "error" as const, error: { kind: "unavailable" as const, message: "second attempt" } }; + +afterEach(() => vi.restoreAllMocks()); + +it("stops another build's backend once the user agrees, then connects again (#6119)", async () => { + const connect = vi.spyOn(commands, "remoteConnect").mockResolvedValueOnce(busy).mockResolvedValueOnce(stop); + const prompt = vi.fn(async () => true); + const dispose = provideBackendBusyPrompt(prompt); + await expect(connectRemote(target, "/srv/app")).rejects.toThrow("second attempt"); + dispose(); + expect(prompt).toHaveBeenCalledOnce(); + expect(connect.mock.calls.map((c) => c[2])).toEqual([false, true]); +}); + +it("keeps the error when the user declines", async () => { + const connect = vi.spyOn(commands, "remoteConnect").mockResolvedValue(busy); + const dispose = provideBackendBusyPrompt(async () => false); + await expect(connectRemote(target, "/srv/app")).rejects.toThrow("busy"); + dispose(); + expect(connect).toHaveBeenCalledOnce(); +}); + +it("doesn't ask about other connection errors", async () => { + vi.spyOn(commands, "remoteConnect").mockResolvedValue(stop); + const prompt = vi.fn(async () => true); + const dispose = provideBackendBusyPrompt(prompt); + await expect(connectRemote(target, "/srv/app")).rejects.toThrow("second attempt"); + dispose(); + expect(prompt).not.toHaveBeenCalled(); +});