From 73ad8e3ed01740371df9c1ea579e3f74c4e098d5 Mon Sep 17 00:00:00 2001 From: "Ivan K." <18464660+h4nz4@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:00:35 +0000 Subject: [PATCH] Fix opening `ssh://` links with a drive letter on Windows remotes (#66814) ## Summary Closes #66813 `ssh://host/C:/project` (and `zed://ssh/host/C:/...`) sends `/C:/project` to the remote, because a URL path keeps a `/` before a Windows drive letter. A Windows remote server cannot canonicalize that path (os error 123), so the project fails to open with `DevServerProjectPathDoesNotExist`. This is a follow-up to #66497, which fixed the same leading `/` for local `file://` and `zed://file` links. That fix could not be reused here: it checks the local OS while the URL is parsed, and for SSH the remote's OS is only known after connecting. This change strips the slash in `determine_paths_with_positions`, which runs after the connection and can ask the remote for its path style. Paths on Unix remotes and `/~` paths are left alone. Before (Zed 1.27.0): zed-ssh-drive-letter-error After (this branch, same URL): zed-ssh-drive-letter-fixed ## Testing - Windows 11 Pro with OpenSSH Server, connected to itself over `localhost` (setup in #66813). - Zed 1.27.0: `zed ssh://zed-win-repro/C:/Users//zed-ssh-repro/project` fails with `DevServerProjectPathDoesNotExist path=/C:/...`. - This branch, debug build, with the remote server built from the same commit: the same URL opens the project, and the worktree is `C:\Users\\zed-ssh-repro\project`. - `cargo test -p recent_projects --lib remote_connections`: 6 passed, including the new `test_strip_slash_before_drive_letter`, which covers both path styles and the paths that must stay unchanged. - `cargo clippy -p recent_projects --tests`: no warnings. To test a debug build against a Windows remote: the debug remote server panics outside the checkout ("dev asset loading requires running from within the checkout"), so build it with `cargo build -p remote_server --features util/debug-embed` and set `ZED_COPY_REMOTE_SERVER` to `target/debug/remote-server.exe`. ## Self-review - [x] I've reviewed my diff for quality, security, reliability, and performance. - [x] UI changes follow the [checklist](https://zed.dev/docs/development/ui-checklist). (No UI changes.) - [x] Tests cover the new or changed behavior. Release Notes: - Fixed `ssh://` links with a drive letter (for example `ssh://user@host/C:/project`) failing to open a project on a Windows remote. --- .../recent_projects/src/remote_connections.rs | 241 +++++++++++++++++- crates/remote/src/transport/mock.rs | 45 +++- crates/util/src/paths.rs | 41 +++ crates/workspace/src/workspace.rs | 31 ++- crates/zed/src/zed/open_listener.rs | 18 +- 5 files changed, 348 insertions(+), 28 deletions(-) diff --git a/crates/recent_projects/src/remote_connections.rs b/crates/recent_projects/src/remote_connections.rs index 72dc75d5d27..e060ae376ec 100644 --- a/crates/recent_projects/src/remote_connections.rs +++ b/crates/recent_projects/src/remote_connections.rs @@ -16,7 +16,7 @@ use remote::{ }; pub use settings::SshConnection; use settings::{DevContainerConnection, ExtendingVec, RegisterSetting, Settings, WslConnection}; -use util::paths::PathWithPosition; +use util::paths::{PathStyle, PathWithPosition, url_path_to_path}; use workspace::{AppState, MultiWorkspace, OpenOptions, Workspace, find_existing_workspace}; pub use remote_connection::{ @@ -456,6 +456,7 @@ pub(crate) async fn determine_paths_with_positions( mut paths: Vec, ) -> (Vec, Vec) { let mut paths_with_positions = Vec::::new(); + url_paths_to_paths(&mut paths, remote_connection.path_style()); for path in &mut paths { if let Some(path_str) = path.to_str() { let path_with_position = PathWithPosition::parse_str(&path_str); @@ -472,6 +473,16 @@ pub(crate) async fn determine_paths_with_positions( (paths, paths_with_positions) } +/// `ssh://` URL paths are converted here rather than when the URL is parsed, because the remote's +/// path style is only known once connected. +fn url_paths_to_paths(paths: &mut [PathBuf], path_style: PathStyle) { + for path in paths { + if let Some(url_path) = path.to_str() { + *path = PathBuf::from(url_path_to_path(url_path, path_style)); + } + } +} + async fn path_exists(connection: &Arc, path: &Path) -> bool { let Ok(command) = connection.build_command( Some("test".to_string()), @@ -509,6 +520,234 @@ mod tests { use util::path; use workspace::find_existing_workspace; + // Each remote path style is set explicitly, so the client and remote styles differ on every + // platform the tests run on. + #[gpui::test] + async fn test_determine_paths_with_positions_converts_url_paths_for_remote_path_style( + cx: &mut TestAppContext, + server_cx: &mut TestAppContext, + ) { + init_test(cx); + // As parsed from `ssh://host/C:/`, `ssh://host/C:/project/src/lib.rs` and `ssh://host/a:12`. + let url_paths = ["/C:/", "/C:/project/src/lib.rs", "/a:12"]; + for (path_style, expected_paths) in [ + (PathStyle::Windows, ["C:/", "C:/project/src/lib.rs", "/a"]), + (PathStyle::Unix, ["/C:/", "/C:/project/src/lib.rs", "/a"]), + ] { + let (opts, _server_session, connect_guard) = RemoteClient::fake_server(cx, server_cx); + cx.update(|cx| remote::MockConnection::set_path_style(&opts, path_style, cx)); + drop(connect_guard); + let connection = + remote::connect(opts, Arc::new(remote::MockDelegate), &mut cx.to_async()) + .await + .unwrap(); + + let (paths, paths_with_positions) = determine_paths_with_positions( + &connection, + url_paths.iter().map(PathBuf::from).collect(), + ) + .await; + + let expected_paths = expected_paths.map(PathBuf::from).to_vec(); + assert_eq!(paths, expected_paths, "{path_style:?}"); + assert_eq!( + paths_with_positions + .iter() + .map(|path| (path.path.clone(), path.row)) + .collect::>(), + expected_paths + .into_iter() + .zip([None, None, Some(12)]) + .collect::>(), + "{path_style:?}" + ); + } + } + + // A remote workspace on a Unix host cannot hold a `C:` path, so this needs a Windows host. + #[cfg(target_os = "windows")] + #[gpui::test] + async fn test_drive_letter_url_path_matches_saved_connection_with_other_options( + cx: &mut TestAppContext, + server_cx: &mut TestAppContext, + ) { + let app_state = init_test(cx); + let (opts, _headless) = init_remote_server(cx, server_cx).await; + let host = || SshConnectionOptions { + host: "example.com".to_string().into(), + ..Default::default() + }; + // A saved connection keeps its timeout; options built from a URL leave it unset. + let saved = RemoteConnectionOptions::Ssh(SshConnectionOptions { + connection_timeout: Some(30), + ..host() + }); + cx.update(|cx| remote::MockConnection::report_connection_options(&opts, saved, cx)); + let mut async_cx = cx.to_async(); + let window = open_remote_project( + opts, + vec![PathBuf::from(path!("/project"))], + app_state, + workspace::OpenOptions::default(), + &mut async_cx, + ) + .await + .unwrap(); + cx.executor().run_until_parked(); + + let found = find_existing_workspace( + &[PathBuf::from("/C:/project/src/lib.rs")], + &workspace::OpenOptions::default(), + &ProjectHost::Remote(&RemoteConnectionOptions::Ssh(host())), + &mut async_cx, + ); + + assert_eq!(found.map(|target| target.window), Some(window)); + } + + // A retained workspace on a Windows host matches the requested host, which now answers with a + // Unix path style, as when an SSH alias is repointed. Its style must not leak into the paths + // sent over the fresh connection. It stays connected because the mock disconnect looks the + // connection up by its reported options; no lookup here depends on connection state. + #[gpui::test] + async fn test_url_path_reaches_fresh_connection_unconverted( + cx: &mut TestAppContext, + server_cx: &mut TestAppContext, + ) { + let app_state = init_test(cx); + let (opts, _headless) = init_remote_server(cx, server_cx).await; + let requested_paths = Arc::new(std::sync::Mutex::new(Vec::new())); + cx.update(|cx| { + remote::MockConnection::set_path_style(&opts, PathStyle::Unix, cx); + remote::MockConnection::intercept_messages( + &opts, + cx, + { + let requested_paths = requested_paths.clone(); + move |envelope| { + if let Some(proto::envelope::Payload::AddWorktree(request)) = + envelope.payload.as_mut() + { + // Record the path, then open one the fake server has. + let path = path!("/project/src/lib.rs").to_string(); + let requested = std::mem::replace(&mut request.path, path); + requested_paths.lock().unwrap().push(requested); + } + } + }, + |_| {}, + ); + }); + + let (stale_opts, stale_session, stale_guard) = RemoteClient::fake_server(cx, server_cx); + let ping_handler = server_cx.new(|_| ()); + stale_session.add_request_handler::( + ping_handler.downgrade(), + |_, _, _| async { Ok(proto::Ack {}) }, + ); + cx.update(|cx| { + remote::MockConnection::set_path_style(&stale_opts, PathStyle::Windows, cx); + remote::MockConnection::report_connection_options(&stale_opts, opts.clone(), cx); + }); + drop(stale_guard); + let stale_client = RemoteClient::connect_mock(stale_opts, cx).await; + let stale_project = cx.update(|cx| { + Project::remote( + stale_client.clone(), + app_state.client.clone(), + app_state.node_runtime.clone(), + app_state.user_store.clone(), + app_state.languages.clone(), + app_state.fs.clone(), + false, + cx, + ) + }); + cx.add_window(|window, cx| { + let workspace = cx.new(|cx| { + Workspace::new(None, stale_project.clone(), app_state.clone(), window, cx) + }); + MultiWorkspace::new(workspace, window, cx) + }); + cx.executor().run_until_parked(); + assert_eq!( + stale_project.read_with(cx, |project, cx| project.path_style(cx)), + PathStyle::Windows + ); + + // As parsed from `ssh://host/C:/project/src/lib.rs`, opened with `--new`. + open_remote_project( + opts, + vec![PathBuf::from("/C:/project/src/lib.rs")], + app_state, + workspace::OpenOptions { + workspace_matching: workspace::WorkspaceMatching::None, + ..Default::default() + }, + &mut cx.to_async(), + ) + .await + .unwrap(); + cx.executor().run_until_parked(); + + assert_eq!( + *requested_paths.lock().unwrap(), + vec!["/C:/project/src/lib.rs".to_string()] + ); + } + + // A remote workspace on a Unix host cannot hold a `C:` path, so this needs a Windows host. + #[cfg(target_os = "windows")] + #[gpui::test] + async fn test_drive_letter_url_path_reuses_open_remote_workspace( + cx: &mut TestAppContext, + server_cx: &mut TestAppContext, + ) { + let app_state = init_test(cx); + let (opts, _headless) = init_remote_server(cx, server_cx).await; + let mut async_cx = cx.to_async(); + + let window = open_remote_project( + opts.clone(), + vec![PathBuf::from(path!("/project"))], + app_state.clone(), + workspace::OpenOptions::default(), + &mut async_cx, + ) + .await + .unwrap(); + cx.executor().run_until_parked(); + + // As parsed from `ssh://host/C:/project/src/lib.rs`. + open_remote_project( + opts, + vec![PathBuf::from("/C:/project/src/lib.rs")], + app_state, + workspace::OpenOptions::default(), + &mut async_cx, + ) + .await + .unwrap(); + cx.executor().run_until_parked(); + + assert_eq!( + cx.update(|cx| cx.windows().len()), + 1, + "a drive-letter URL path into the open project should reuse its window" + ); + let opened = window + .read_with(cx, |multi_workspace, cx| { + multi_workspace + .workspace() + .read(cx) + .active_item(cx) + .and_then(|item| item.project_path(cx)) + .map(|project_path| project_path.path.as_unix_str().to_owned()) + }) + .unwrap(); + assert_eq!(opened.as_deref(), Some("src/lib.rs")); + } + #[gpui::test] async fn test_open_remote_project_with_mock_connection( cx: &mut TestAppContext, diff --git a/crates/remote/src/transport/mock.rs b/crates/remote/src/transport/mock.rs index 798cd14e3d5..ccc2d9e2649 100644 --- a/crates/remote/src/transport/mock.rs +++ b/crates/remote/src/transport/mock.rs @@ -70,6 +70,8 @@ pub struct MockRemoteConnection { server_channel: Arc, server_cx: SendableCx, message_interceptors: parking_lot::Mutex>, + path_style: parking_lot::Mutex, + reported_options: parking_lot::Mutex>, pub(crate) proxy_tx: parking_lot::Mutex< Option< mpsc::UnboundedSender<( @@ -141,18 +143,40 @@ impl MockConnection { client_to_server: impl Fn(&mut Envelope) + Send + Sync + 'static, server_to_client: impl Fn(&mut Envelope) + Send + Sync + 'static, ) { + *Self::pending(options, cx).message_interceptors.lock() = Some(MessageInterceptors { + client_to_server: Arc::new(client_to_server), + server_to_client: Arc::new(server_to_client), + }); + } + + /// Makes the connection report `path_style`, as a connection to a host of another OS would. + pub fn set_path_style(options: &RemoteConnectionOptions, path_style: PathStyle, cx: &mut App) { + *Self::pending(options, cx).path_style.lock() = path_style; + } + + /// Makes the connection report `reported` as its options, as a real connection reports the + /// options it was opened with, such as a saved SSH connection. + pub fn report_connection_options( + options: &RemoteConnectionOptions, + reported: RemoteConnectionOptions, + cx: &mut App, + ) { + *Self::pending(options, cx).reported_options.lock() = Some(reported); + } + + fn pending<'a>( + options: &RemoteConnectionOptions, + cx: &'a App, + ) -> &'a Arc { let RemoteConnectionOptions::Mock(options) = options else { - panic!("message interception requires a mock connection"); + panic!("this requires a mock connection"); }; let (_, connection) = cx .global::() .pending .get(&options.id) - .expect("message interceptors must be installed before connecting"); - *connection.message_interceptors.lock() = Some(MessageInterceptors { - client_to_server: Arc::new(client_to_server), - server_to_client: Arc::new(server_to_client), - }); + .expect("the mock connection must be configured before connecting"); + connection } /// Creates a new mock connection pair for testing. @@ -202,6 +226,8 @@ impl MockConnection { server_channel: server_client.clone(), server_cx: SendableCx::new(server_cx), message_interceptors: parking_lot::Mutex::new(None), + path_style: parking_lot::Mutex::new(PathStyle::local()), + reported_options: parking_lot::Mutex::new(None), proxy_tx: Default::default(), }); @@ -286,7 +312,10 @@ impl RemoteConnection for MockRemoteConnection { } fn connection_options(&self) -> RemoteConnectionOptions { - RemoteConnectionOptions::Mock(self.options.clone()) + self.reported_options + .lock() + .clone() + .unwrap_or_else(|| RemoteConnectionOptions::Mock(self.options.clone())) } fn simulate_disconnect(&self, cx: &AsyncApp) { @@ -356,7 +385,7 @@ impl RemoteConnection for MockRemoteConnection { } fn path_style(&self) -> PathStyle { - PathStyle::local() + *self.path_style.lock() } fn remote_platform(&self) -> crate::RemotePlatform { diff --git a/crates/util/src/paths.rs b/crates/util/src/paths.rs index 8029d34cae4..b4a7419b89f 100644 --- a/crates/util/src/paths.rs +++ b/crates/util/src/paths.rs @@ -1589,6 +1589,23 @@ impl UrlExt for url::Url { } } +/// Converts the already-decoded path of a URL into a path on a host with `path_style`. +/// +/// URL paths keep a `/` before a Windows drive letter (`/C:/x`), which Windows cannot open. +/// The `/` is only dropped when what follows is an absolute drive path, so `/a:12` stays the +/// rooted file `/a` at line 12. +/// Unlike [`UrlExt::to_file_path_ext`], this takes a decoded path, not a whole URL, so it also +/// serves URLs whose authority is not a file host, such as `ssh://`. +pub fn url_path_to_path(url_path: &str, path_style: PathStyle) -> &str { + if path_style.is_windows() + && let Some(path) = url_path.strip_prefix('/') + && path_style.is_absolute(Path::new(path)) + { + return path; + } + url_path +} + #[cfg(test)] mod tests { use super::*; @@ -3468,6 +3485,30 @@ mod tests { assert_eq!(WslPath::from_path(&path), None); } + #[test] + fn test_url_path_to_path() { + let windows = |path| url_path_to_path(path, PathStyle::Windows); + assert_eq!(windows("/C:/project/main.rs"), "C:/project/main.rs"); + assert_eq!(windows("/C:/project/main.rs:12"), "C:/project/main.rs:12"); + assert_eq!(windows("/d:\\project"), "d:\\project"); + // Drive roots keep their separator. + assert_eq!(windows("/C:/"), "C:/"); + assert_eq!(windows("/d:\\"), "d:\\"); + // Not a drive path: left as it is. + assert_eq!(windows("/~/project"), "/~/project"); + assert_eq!(windows("/1:/project"), "/1:/project"); + assert_eq!(windows("C:/project"), "C:/project"); + // A rooted file with a row, or a drive without a root, is not an absolute drive path. + assert_eq!(windows("/a:12"), "/a:12"); + assert_eq!(windows("/C:"), "/C:"); + assert_eq!(windows("/C:project"), "/C:project"); + // On a Unix host `/C:/x` is a valid absolute path. + assert_eq!( + url_path_to_path("/C:/project", PathStyle::Unix), + "/C:/project" + ); + } + #[test] fn test_url_to_file_path_ext_posix_basic() { use super::UrlExt; diff --git a/crates/workspace/src/workspace.rs b/crates/workspace/src/workspace.rs index 407784c0001..933733800e7 100644 --- a/crates/workspace/src/workspace.rs +++ b/crates/workspace/src/workspace.rs @@ -11561,6 +11561,27 @@ fn preferred_workspace_target( } } +/// `ssh://` URL paths arrive unconverted, because each remote has its own path style. Every +/// candidate converts its own copy, so the caller's paths reach a fresh connection unchanged. +fn paths_for_candidate<'a>( + abs_paths: &'a [impl AsRef], + host: &ProjectHost<'_>, + path_style: PathStyle, +) -> Vec<&'a Path> { + abs_paths + .iter() + .map(|path| { + let path = path.as_ref(); + match (host, path.to_str()) { + (ProjectHost::Remote(_), Some(url_path)) => { + Path::new(util::paths::url_path_to_path(url_path, path_style)) + } + _ => path, + } + }) + .collect() +} + pub fn find_existing_workspace( abs_paths: &[impl AsRef], open_options: &OpenOptions, @@ -11592,16 +11613,17 @@ pub fn find_existing_workspace( continue; } + let paths = paths_for_candidate(abs_paths, host, project.path_style(cx)); let visibility = match open_options.workspace_matching { WorkspaceMatching::None => None, WorkspaceMatching::MatchExact => { - project.visibility_for_paths(abs_paths, true, cx) + project.visibility_for_paths(&paths, true, cx) } WorkspaceMatching::MatchSubpaths => { - project.visibility_for_subpaths(abs_paths, cx) + project.visibility_for_subpaths(&paths, cx) } WorkspaceMatching::MatchSubdirectory => { - project.visibility_for_paths(abs_paths, false, cx) + project.visibility_for_paths(&paths, false, cx) } }; @@ -11629,8 +11651,9 @@ pub fn find_existing_workspace( let workspace = target.workspace.read(cx); let project = workspace.project.read(cx); let path_style = workspace.path_style(cx); + let paths = paths_for_candidate(abs_paths, host, path_style); - !abs_paths.iter().any(|path| { + !paths.iter().any(|path| { let path = util::paths::SanitizedPath::new(path); project diff --git a/crates/zed/src/zed/open_listener.rs b/crates/zed/src/zed/open_listener.rs index c33f37cc5fb..38360b05867 100644 --- a/crates/zed/src/zed/open_listener.rs +++ b/crates/zed/src/zed/open_listener.rs @@ -21,8 +21,6 @@ use onboarding::show_onboarding_view; use recent_projects::{RemoteSettings, navigate_to_positions, open_remote_project}; use remote::{RemoteConnectionOptions, WslConnectionOptions}; use settings::Settings; -#[cfg(target_os = "windows")] -use std::path::{Component, Prefix}; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::thread; @@ -30,7 +28,7 @@ use std::time::Duration; use ui::SharedString; use util::ResultExt; use util::debug_panic; -use util::paths::PathWithPosition; +use util::paths::{PathStyle, PathWithPosition, url_path_to_path}; use workspace::PathList; use workspace::item::ItemHandle; use workspace::{AppState, MultiWorkspace, OpenOptions, OpenResult, SerializedWorkspaceLocation}; @@ -224,18 +222,8 @@ impl OpenRequest { fn parse_local_file_path(&mut self, file: &str) { if let Some(decoded) = urlencoding::decode(file).log_err() { - // URL paths keep a `/` before a Windows drive letter (`/C:/x`), which Windows cannot open. - #[cfg(target_os = "windows")] - if let Some(path) = decoded.strip_prefix('/') - && matches!( - Path::new(path).components().next(), - Some(Component::Prefix(prefix)) if matches!(prefix.kind(), Prefix::Disk(_)) - ) - { - self.open_paths.push(path.to_owned()); - return; - } - self.open_paths.push(decoded.into_owned()) + self.open_paths + .push(url_path_to_path(&decoded, PathStyle::local()).to_owned()) } }