From 006405ca110774b178f3cf80ec679f3a098f849f Mon Sep 17 00:00:00 2001 From: tomgor <22257170@qq.com> Date: Fri, 20 Nov 2026 10:12:35 +0800 Subject: [PATCH] fix(remote): restore WSL projects onto a live connection (#4103) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(remote): restore WSL projects onto a live connection A reopened WSL window kept sending commands to a remote host it was no longer connected to. Remember the remote location, and do not drop a connection that a later open or a superseded attempt still needs. Co-authored-by: Cursor * Use ? for the last remote location prefix (clippy::question_mark) * fix(remote): save window session after connecting --------- Co-authored-by: 胡长贵 Co-authored-by: Cursor Co-authored-by: l0ng-ai <24760907+l0ng-ai@users.noreply.github.com> --- src-tauri/src/remote_dev.rs | 184 ++++++++++++++++++++++++++-- src-tauri/src/state.rs | 11 +- src-tauri/src/window_groups.rs | 48 +++++--- src-tauri/src/windows.rs | 100 ++++++++++++++- src/platform/remote.ts | 3 +- src/platform/remoteSettings.test.ts | 33 +++++ 6 files changed, 346 insertions(+), 33 deletions(-) diff --git a/src-tauri/src/remote_dev.rs b/src-tauri/src/remote_dev.rs index 7addd14d2..478f913bb 100644 --- a/src-tauri/src/remote_dev.rs +++ b/src-tauri/src/remote_dev.rs @@ -106,7 +106,12 @@ impl Forward { type Channels = Arc, u64)>>>; #[derive(Default)] -pub struct Connections(Mutex>>); +pub struct Connections { + windows: Mutex>>, + /// The connect attempt allowed to publish for each window. A later connect, or a + /// disconnect, supersedes an attempt that is still starting the server. + attempts: Mutex>, +} impl Connection { /// Commands of a remote window that run on this machine follow this machine's decision about the @@ -143,13 +148,13 @@ impl Connection { impl Connections { pub fn get(&self, window: &str) -> Option> { - self.0.lock().get(window).cloned() + self.windows.lock().get(window).cloned() } /// The window connected to folder `root` of `target`. pub fn window_of(&self, target: &RemoteTarget, root: &str) -> Option { let root = root.trim_end_matches('/'); - self.0 + self.windows .lock() .iter() // A dev container is one project: its folder there is only known once connected. @@ -162,17 +167,131 @@ impl Connections { /// Every connected window. pub fn all(&self) -> Vec<(String, Arc)> { - self.0.lock().iter().map(|(w, c)| (w.clone(), c.clone())).collect() + self.windows.lock().iter().map(|(w, c)| (w.clone(), c.clone())).collect() + } + + /// Starts a connect for `window`. An older attempt can no longer publish. + pub fn begin(&self, window: &str) -> u64 { + self.bump(window) + } + + fn bump(&self, window: &str) -> u64 { + let mut attempts = self.attempts.lock(); + let next = attempts.get(window).copied().unwrap_or(0).wrapping_add(1); + attempts.insert(window.to_owned(), next); + next + } + + /// Installs `connection` when `attempt` is still the one [`begin`] returned for `window`. + /// An older attempt leaves the connection a newer one published. + pub fn publish(&self, window: &str, attempt: u64, connection: Arc) -> bool { + let attempts = self.attempts.lock(); + if attempts.get(window).copied() != Some(attempt) { + return false; + } + if let Some(old) = self.windows.lock().insert(window.to_owned(), connection) { + old.peer.kill(); + old.forwards.lock().clear(); + } + true } pub fn disconnect(&self, window: &str) { - if let Some(c) = self.0.lock().remove(window) { + // Invalidate an attempt that has not published yet, or it would put the + // connection back after this disconnect. + self.bump(window); + if let Some(c) = self.windows.lock().remove(window) { c.peer.kill(); c.forwards.lock().clear(); } } } +/// `ssh://` / `wsl://` / `devcontainer://` location, the same spelling the frontend stores. +pub fn remote_location(target: &RemoteTarget, path: &str) -> String { + let (scheme, name) = match target { + RemoteTarget::Ssh { config } => ("ssh", config.as_str()), + RemoteTarget::Wsl { distro } => ("wsl", distro.as_str()), + RemoteTarget::DevContainer { folder, .. } => ("devcontainer", folder.as_str()), + }; + let config = match target { + RemoteTarget::DevContainer { config, .. } if !config.is_empty() => format!(":{}", encode_uri_component(config)), + _ => String::new(), + }; + let path = if path.starts_with('/') { path.to_owned() } else { format!("/{path}") }; + format!("{scheme}://{}{config}{path}", encode_uri_component(name)) +} + +/// The remote project a `ssh://`, `wsl://` or `devcontainer://` location names. +pub fn parse_remote_location(location: &str) -> Option<(RemoteTarget, String)> { + let (kind, rest) = if let Some(rest) = location.strip_prefix("ssh://") { + ("ssh", rest) + } else if let Some(rest) = location.strip_prefix("wsl://") { + ("wsl", rest) + } else { + ("devcontainer", location.strip_prefix("devcontainer://")?) + }; + let slash = rest.find('/')?; + if slash == 0 { + return None; + } + let authority = &rest[..slash]; + let path = rest[slash..].to_owned(); + let (name, config) = if kind == "devcontainer" { + match authority.split_once(':') { + Some((name, config)) => (name, config), + None => (authority, ""), + } + } else { + (authority, "") + }; + let name = decode_uri_component(name)?; + let config = decode_uri_component(config)?; + if name.is_empty() { + return None; + } + let target = match kind { + "ssh" => RemoteTarget::Ssh { config: name }, + "wsl" => RemoteTarget::Wsl { distro: name }, + _ => RemoteTarget::DevContainer { folder: name, config }, + }; + Some((target, path)) +} + +/// `encodeURIComponent`: the frontend builds locations with it. +fn encode_uri_component(value: &str) -> String { + let mut out = String::new(); + for b in value.bytes() { + match b { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'!' | b'~' | b'*' | b'\'' | b'(' | b')' => { + out.push(b as char) + } + _ => out.push_str(&format!("%{b:02X}")), + } + } + out +} + +fn decode_uri_component(value: &str) -> Option { + let bytes = value.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'%' { + if i + 2 >= bytes.len() { + return None; + } + let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).ok()?; + out.push(u8::from_str_radix(hex, 16).ok()?); + i += 3; + } else { + out.push(bytes[i]); + i += 1; + } + } + String::from_utf8(out).ok() +} + /// Where [`remote_connect`] is (`fraction`: 0..1 of a download / upload). #[derive(Clone, Copy, Debug, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] @@ -512,6 +631,9 @@ pub async fn remote_connect( }); progress(RemoteStage::Connecting, None); let label = AppState::owner_window(window.label()).to_owned(); + // A later connect or a disconnect supersedes this attempt, so it cannot replace + // the connection that one published — or put one back after it was dropped. + let attempt = state.remote_dev.begin(&label); let channels: Channels = Arc::default(); let connection_slot: Arc>> = Arc::default(); let handler = Arc::new(ClientHandler { @@ -613,10 +735,14 @@ pub async fn remote_connect( if let RemoteTarget::DevContainer { folder, config } = &target { forward_configured_ports(&connection, folder, config).await; } - state.remote_dev.disconnect(&label); + if !state.remote_dev.publish(&label, attempt, connection.clone()) { + tracing::debug!("{label}: remote connection superseded"); + connection.peer.kill(); + connection.forwards.lock().clear(); + return Err(IdeError::cancelled()); + } state.host.close_project(&label); state.host.mcp_reports.set_remote(&label, std::path::PathBuf::from(&connection.root)); - state.remote_dev.0.lock().insert(label.clone(), connection.clone()); let weak = Arc::downgrade(&connection); let peer = connection.peer.clone(); let auth_plugins = state.plugins.clone(); @@ -641,6 +767,9 @@ pub async fn remote_connect( sync_plugin_languages(&plugins, &connection, &label).await; sync_plugin_packages(&plugins, &connection, &label).await; }); + if let Err(error) = crate::window_groups::persist(window.app_handle()).await { + tracing::warn!(%error, "cannot save window session after opening remote project"); + } Ok(RemoteProject { target, root, host, server_version: info.version, os: info.os, commands, project }) } @@ -1069,6 +1198,29 @@ async fn invoke_reply(peer: &Peer, call: Invoke, entries_timeout: std::time::Dur mod tests { use super::*; + #[test] + fn remote_locations_round_trip_like_the_frontend() { + let cases = [ + (RemoteTarget::Wsl { distro: "Ubuntu-24.04".into() }, "/home/me/app", "wsl://Ubuntu-24.04/home/me/app"), + (RemoteTarget::Ssh { config: "my box".into() }, "/srv/app", "ssh://my%20box/srv/app"), + ( + RemoteTarget::DevContainer { folder: "/work/app".into(), config: "devcontainer.json".into() }, + "/workspaces/app", + "devcontainer://%2Fwork%2Fapp:devcontainer.json/workspaces/app", + ), + ( + RemoteTarget::DevContainer { folder: "/work/app".into(), config: String::new() }, + "/workspaces/app", + "devcontainer://%2Fwork%2Fapp/workspaces/app", + ), + ]; + for (target, path, location) in cases { + assert_eq!(remote_location(&target, path), location); + assert_eq!(parse_remote_location(location), Some((target, path.to_owned()))); + } + assert!(parse_remote_location(r"\\wsl.localhost\Ubuntu\home\me\app").is_none()); + } + #[test] fn a_command_missing_on_a_server_of_another_version_says_which_versions() { let missing = || IdeError::unavailable("-32601: command web_url is not available remotely"); @@ -1159,6 +1311,24 @@ mod tests { } } + #[tokio::test] + async fn a_later_connect_supersedes_an_earlier_attempt() { + let connections = Connections::default(); + let first = connections.begin("main"); + let second = connections.begin("main"); + let older = Arc::new(connected(RemoteTarget::Wsl { distro: "Ubuntu".into() }, "/home/me/old")); + assert!(!connections.publish("main", first, older.clone())); + assert!(connections.get("main").is_none()); + let newer = Arc::new(connected(RemoteTarget::Wsl { distro: "Ubuntu".into() }, "/home/me/new")); + assert!(connections.publish("main", second, newer.clone())); + assert!(Arc::ptr_eq(&connections.get("main").unwrap(), &newer)); + connections.disconnect("main"); + assert!(connections.get("main").is_none()); + assert!(!connections.publish("main", second, newer.clone())); + older.peer.kill(); + newer.peer.kill(); + } + #[tokio::test] async fn the_server_does_not_decide_trust_for_commands_run_here() { let tmp = tempfile::tempdir().unwrap(); diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rs index aed1777b5..c8063b477 100644 --- a/src-tauri/src/state.rs +++ b/src-tauri/src/state.rs @@ -143,10 +143,11 @@ impl AppState { /// Opens `root` in `window` and records it in the recent projects. pub fn open_project(&self, window: &str, root: &Path) -> IdeResult> { - // A local project replaces a remote one in this window. - self.remote_dev.disconnect(window); let project = self.host.open_project(window, root)?; self.record_project(&project)?; + // Drop the remote connection only once the local project is actually open. + // A failed open leaves the window on the host it is still routing to. + self.remote_dev.disconnect(window); Ok(project) } @@ -166,14 +167,16 @@ impl AppState { /// Opens `window` for editing the loose file `file` (LightEdit); not a recent project. pub fn open_light(&self, window: &str, file: &Path) -> IdeResult> { + let project = self.host.open_light(window, file)?; self.remote_dev.disconnect(window); - self.host.open_light(window, file) + Ok(project) } /// LightEdit without a file (File › New File from a welcome window). pub fn open_light_empty(&self, window: &str) -> IdeResult> { + let project = self.host.open_light_empty(window)?; self.remote_dev.disconnect(window); - self.host.open_light_empty(window) + Ok(project) } /// Called on the event-loop thread (window destruction, the `close_project` diff --git a/src-tauri/src/window_groups.rs b/src-tauri/src/window_groups.rs index 91a8db6b6..10130d1cc 100644 --- a/src-tauri/src/window_groups.rs +++ b/src-tauri/src/window_groups.rs @@ -276,10 +276,18 @@ pub async fn persist(app: &AppHandle) -> IdeResult<()> { } let groups = state.groups.lock().groups().to_vec(); let windows = labels_in_order(app); - let project_of = |label: &str| match host.project(label) { - Ok(p) => (!p.light).then(|| p.root.clone()), - // A restored window may have taken its launch but not finished opening yet. - Err(_) => state.pending(label).and_then(|l| l.project).map(Into::into), + let project_of = |label: &str| { + if let Some(path) = windows::window_project_path(app, label) { + return Some(path); + } + // Taken its launch, not finished opening: keep the remote location or local folder. + state.pending(label).and_then(|launch| { + launch + .remote + .as_ref() + .map(|remote| PathBuf::from(crate::remote_dev::remote_location(&remote.target, &remote.path))) + .or_else(|| launch.project.clone().map(Into::into)) + }) }; let Some(saved) = ide_workspace::window_groups::session(&groups, &windows, project_of) else { return Ok(()); @@ -314,8 +322,13 @@ pub async fn restore(app: &AppHandle, caller: &str) -> IdeResult<()> { } let state = app.state::(); let host = app.state::(); - let project = host.project(caller)?; - if !project.settings.effective().general.reopen_last_project || state.groups_restored.swap(true, Ordering::SeqCst) { + // A remote window has no local project. Leave the flag clear until this window has + // one, so the call that runs once the connection is up can still restore its siblings. + let Some(root) = windows::window_project_path(app, caller) else { + return Ok(()); + }; + let settings = ide_host::ops::project::settings_get(&host.host, caller); + if !settings.general.reopen_last_project || state.groups_restored.swap(true, Ordering::SeqCst) { return Ok(()); } let saved = { @@ -327,30 +340,25 @@ pub async fn restore(app: &AppHandle, caller: &str) -> IdeResult<()> { }; // The caller's own group first (it already shows one of its projects), then every other // group and single window that was open at quit. Missing folders are skipped. - let order = saved - .iter() - .filter(|g| g.projects.contains(&project.root)) - .chain(saved.iter().filter(|g| !g.projects.contains(&project.root))); + let owns = |group: &ide_workspace::window_groups::SavedWindows| { + group.projects.iter().any(|path| windows::same_saved_project(path, &root)) + }; + let order = saved.iter().filter(|group| owns(group)).chain(saved.iter().filter(|group| !owns(group))); for group in order { let mut labels = Vec::new(); let mut selected = None; for path in &group.projects { - let label = if path == &project.root { + let label = if windows::same_saved_project(path, &root) { Some(caller.to_owned()) - } else if path.is_dir() { - let window = match windows::find_project_window(app, path) { - Some(w) => Ok(w), - None => windows::create_restored_window(app, path.clone()), - }; - match window { - Ok(w) => Some(w.label().to_owned()), + } else { + match windows::reopen_saved_window(app, path) { + Ok(Some(w)) => Some(w.label().to_owned()), + Ok(None) => None, Err(e) => { tracing::warn!("cannot reopen {}: {e}", path.display()); None } } - } else { - None }; if let Some(label) = label { if group.projects.get(group.selected) == Some(path) { diff --git a/src-tauri/src/windows.rs b/src-tauri/src/windows.rs index 4c45a1e95..b6fbcde19 100644 --- a/src-tauri/src/windows.rs +++ b/src-tauri/src/windows.rs @@ -211,6 +211,74 @@ pub fn wsl_launch(path: &Path) -> Option { Some(RemoteLaunch { target: RemoteTarget::Wsl { distro: w.distro }, path: w.path }) } +/// A saved project path that is a remote location: `ssh://`, `wsl://`, `devcontainer://`, +/// or a `\\wsl.localhost` share remembered before those locations existed. +pub(crate) fn saved_remote(path: &Path) -> Option { + if let Some(text) = path.to_str() + && let Some((target, root)) = crate::remote_dev::parse_remote_location(text) + { + return Some(RemoteLaunch { target, path: root }); + } + wsl_launch(path) +} + +/// What reopening `path` should launch. A remote location is recognised before any stat, +/// so a WSL share that is down still comes back as a remote project. +pub(crate) fn saved_project_launch(path: &Path) -> Option { + if let Some(remote) = saved_remote(path) { + return Some(Launch { remote: Some(remote), ..Default::default() }); + } + path.is_dir().then(|| Launch { project: Some(path.to_path_buf().into()), ..Default::default() }) +} + +/// The same project, including a WSL share and the `wsl://` location of that folder. +pub(crate) fn same_saved_project(a: &Path, b: &Path) -> bool { + if a == b { + return true; + } + match (saved_remote(a), saved_remote(b)) { + (Some(left), Some(right)) => { + left.target == right.target && left.path.trim_end_matches('/') == right.path.trim_end_matches('/') + } + _ => false, + } +} + +/// The project `label` has open: a remote location (`wsl://` and the rest), else its local root. +pub(crate) fn window_project_path(app: &AppHandle, label: &str) -> Option { + let state = app.try_state::()?; + if let Some(c) = state.remote_dev.get(label) { + return Some(PathBuf::from(crate::remote_dev::remote_location(&c.target, &c.root))); + } + state.project(label).ok().filter(|p| !p.light).map(|p| p.root.clone()) +} + +/// Reopens a project saved at quit. Remote locations become a remote launch; a missing +/// local folder is skipped. An already connected window is focused instead of duplicated. +pub(crate) fn reopen_saved_window(app: &AppHandle, path: &Path) -> IdeResult> { + let Some(launch) = saved_project_launch(path) else { + return Ok(None); + }; + if let Some(remote) = launch.remote.clone() { + let open = app.try_state::().and_then(|s| s.remote_dev.window_of(&remote.target, &remote.path)); + if let Some(w) = open.and_then(|label| app.get_webview_window(&label)) { + return Ok(Some(w)); + } + let title = remote + .path + .trim_end_matches('/') + .rsplit('/') + .next() + .filter(|n| !n.is_empty() && *n != "~") + .map(str::to_owned); + return Ok(Some(create_window_for(app, title, launch, true)?)); + } + if let Some(w) = find_project_window(app, path) { + return Ok(Some(w)); + } + Ok(Some(create_restored_window(app, path.to_path_buf())?)) +} + #[derive(Default)] pub struct WindowsState { pub groups: Mutex, @@ -2446,11 +2514,41 @@ mod tests { let folder = launch_for(share.clone(), true); let remote = RemoteLaunch { target: RemoteTarget::Wsl { distro: "Ubuntu".into() }, path: "/home/me/app".into() }; - assert_eq!((folder.remote, folder.project, folder.files.len()), (Some(remote), None, 0)); + assert_eq!((folder.remote, folder.project, folder.files.len()), (Some(remote.clone()), None, 0)); let file = launch_for(share.join("main.py"), false); assert_eq!((file.remote, file.project, file.files.len()), (None, None, 1)); } + #[test] + fn a_saved_wsl_project_reopens_as_a_remote_launch_without_the_share() { + let remote = + RemoteLaunch { target: RemoteTarget::Wsl { distro: "Ubuntu".into() }, path: "/home/me/app".into() }; + for saved in [r"\\wsl.localhost\Ubuntu\home\me\app", "wsl://Ubuntu/home/me/app", "//wsl$/Ubuntu/home/me/app"] { + let launch = saved_project_launch(Path::new(saved)).expect(saved); + assert_eq!(launch.remote, Some(remote.clone())); + assert!(launch.project.is_none(), "{saved}"); + } + assert!(same_saved_project( + Path::new(r"\\wsl.localhost\Ubuntu\home\me\app"), + Path::new("wsl://Ubuntu/home/me/app/") + )); + let ssh = saved_project_launch(Path::new("ssh://box/srv/app")).unwrap(); + assert_eq!( + ssh.remote, + Some(RemoteLaunch { target: RemoteTarget::Ssh { config: "box".into() }, path: "/srv/app".into() }) + ); + let container = + saved_project_launch(Path::new("devcontainer://%2Fwork%2Fapp:devcontainer.json/workspaces/app")).unwrap(); + assert_eq!( + container.remote, + Some(RemoteLaunch { + target: RemoteTarget::DevContainer { folder: "/work/app".into(), config: "devcontainer.json".into() }, + path: "/workspaces/app".into(), + }) + ); + assert!(saved_project_launch(Path::new("/no/such/local/project-openidea")).is_none()); + } + fn p(s: &str) -> PathBuf { PathBuf::from(s) } diff --git a/src/platform/remote.ts b/src/platform/remote.ts index 258fa2800..c72c50776 100644 --- a/src/platform/remote.ts +++ b/src/platform/remote.ts @@ -226,8 +226,9 @@ export async function connectRemote(target: RemoteTarget, path: string) { }); try { const r = await call(commands.remoteConnect(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 (useRemoteProgress.getState().location !== location) { - await commands.remoteDisconnect().catch(() => {}); throw new IpcError({ kind: "cancelled", message: "Remote connection cancelled" }); } await attachRemote(r, path); diff --git a/src/platform/remoteSettings.test.ts b/src/platform/remoteSettings.test.ts index 4a1371f6f..050574cfc 100644 --- a/src/platform/remoteSettings.test.ts +++ b/src/platform/remoteSettings.test.ts @@ -9,6 +9,8 @@ import { isRemoteWindow, localGlobalSettings, remoteRouting, + useRemote, + useRemoteProgress, } from "./remote"; import { invoke as routedInvoke } from "./tauriCore"; @@ -62,6 +64,7 @@ beforeEach(() => { afterEach(() => { disableRemote(); useProject.setState({ opening: false, settings: null }); + useRemoteProgress.setState({ progress: null, location: null }); }); describe("remote client settings", () => { @@ -205,6 +208,36 @@ describe("remote client settings", () => { await connectRemote({ kind: "ssh", config: "test" }, "/remote"); expect(useProject.getState().settings).toMatchObject({ keymap: "my-map", editor: { tabSize: 2, fontSize: 19 } }); }); + it("does not disconnect a newer connect when an older one finishes", async () => { + disableRemote(); + useRemoteProgress.setState({ progress: null, location: null }); + let releaseFirst: (value: unknown) => void = () => {}; + const first = new Promise((resolve) => { + releaseFirst = resolve; + }); + let connects = 0; + invoke.mockImplementation(async (cmd: string) => { + if (cmd !== "remote_connect") return cmd === "remote_invoke" ? "null" : local; + connects += 1; + const root = connects === 1 ? "/home/me/old" : "/home/me/new"; + const project = { + target: { kind: "wsl", distro: "Ubuntu" }, + root, + host: "Ubuntu", + os: "linux", + commands: [...served], + project: { root, name: "app", displayName: "app", settings: remote }, + }; + return connects === 1 ? first.then(() => project) : project; + }); + const older = connectRemote({ kind: "wsl", distro: "Ubuntu" }, "/home/me/old"); + const newer = connectRemote({ kind: "wsl", distro: "Ubuntu" }, "/home/me/new"); + await newer; + releaseFirst(undefined); + await expect(older).rejects.toMatchObject({ kind: "cancelled" }); + expect(invoke.mock.calls.filter(([cmd]) => cmd === "remote_disconnect")).toHaveLength(0); + expect(useRemote.getState().session?.root).toBe("/home/me/new"); + }); it("overlays the project snapshot used by the settings window", async () => { invoke.mockImplementation(async (cmd: string) => cmd === "remote_invoke" ? JSON.stringify({ root: "/remote", settings: remote }) : local,