Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
workspace: Fix local file opens with remote workspaces (#65771)
狐狸fae4b2ea4fb3
diff --git a/crates/agent_ui/src/agent_panel.rs b/crates/agent_ui/src/agent_panel.rsindex c5a19bccc8f..99c659c76ce 100644--- a/crates/agent_ui/src/agent_panel.rs+++ b/crates/agent_ui/src/agent_panel.rs@@ -2431,7 +2431,7 @@ impl AgentPanel {custom_title: terminal.custom_title(cx),created_at: terminal.created_at,worktree_paths: project.worktree_paths(cx),- remote_connection: project.remote_connection_options(cx),+ remote_connection: project.remote_connection_options(cx).cloned(),working_directory: terminal.working_directory.clone(),})}diff --git a/crates/agent_ui/src/terminal_thread_metadata_store.rs b/crates/agent_ui/src/terminal_thread_metadata_store.rsindex 528f2e23e83..06ba365b6ee 100644--- a/crates/agent_ui/src/terminal_thread_metadata_store.rs+++ b/crates/agent_ui/src/terminal_thread_metadata_store.rs@@ -12,7 +12,7 @@ use db::{};use futures::{FutureExt, future::Shared};use gpui::{AppContext as _, Entity, Global, Task};-use remote::{RemoteConnectionOptions, same_remote_connection_identity};+use remote::RemoteConnectionOptions;use ui::{App, Context, SharedString};use util::ResultExt as _;use workspace::PathList;@@ -233,10 +233,8 @@ impl TerminalThreadMetadataStore {.flatten().filter_map(|id| self.terminals.get(id)).filter(move |terminal| {- same_remote_connection_identity(- terminal.remote_connection.as_ref(),- remote_connection,- )+ terminal.remote_connection.as_ref().map(|o| o.identity())+ == remote_connection.map(|o| o.identity())})}@@ -251,10 +249,8 @@ impl TerminalThreadMetadataStore {.flatten().filter_map(|id| self.terminals.get(id)).filter(move |terminal| {- same_remote_connection_identity(- terminal.remote_connection.as_ref(),- remote_connection,- )+ terminal.remote_connection.as_ref().map(|o| o.identity())+ == remote_connection.map(|o| o.identity())})}@@ -266,10 +262,8 @@ impl TerminalThreadMetadataStore {) -> bool {self.entries().any(|terminal| {Some(terminal.terminal_id) != terminal_id- && same_remote_connection_identity(- terminal.remote_connection.as_ref(),- remote_connection,- )+ && terminal.remote_connection.as_ref().map(|o| o.identity())+ == remote_connection.map(|o| o.identity())&& terminal.folder_paths().paths()@@ -316,10 +310,8 @@ impl TerminalThreadMetadataStore {.flatten().filter(|id| {self.terminals.get(id).is_some_and(|terminal| {- same_remote_connection_identity(- terminal.remote_connection.as_ref(),- remote_connection,- )+ terminal.remote_connection.as_ref().map(|o| o.identity())+ == remote_connection.map(|o| o.identity())})}).copied()diff --git a/crates/agent_ui/src/thread_import.rs b/crates/agent_ui/src/thread_import.rsindex 13f31831c25..8a3c81678d4 100644--- a/crates/agent_ui/src/thread_import.rs+++ b/crates/agent_ui/src/thread_import.rs@@ -699,14 +699,14 @@ fn fetch_sessions_for_agent(.read(cx).project().read(cx)- .remote_connection_options(cx);+ .remote_connection_options(cx)+ .cloned();let agent = Agent::from(agent_id.clone());let server = agent.server(<dyn Fs>::global(cx), ThreadStore::global(cx));let entry = store.update(cx, |store, cx| store.request_connection(agent, server, cx));wait_for_connection_tasks.push(entry.read(cx).wait_for_connection().map({let agent_id = agent_id.clone();- let remote_connection = remote_connection.clone();move |result| (agent_id, remote_connection, result)}));}diff --git a/crates/agent_ui/src/thread_metadata_store.rs b/crates/agent_ui/src/thread_metadata_store.rsindex a26f7ed3f8b..3fdb3a9580a 100644--- a/crates/agent_ui/src/thread_metadata_store.rs+++ b/crates/agent_ui/src/thread_metadata_store.rs@@ -23,7 +23,7 @@ use futures::{FutureExt, future::Shared};use gpui::{AppContext as _, Entity, Global, Subscription, Task, TaskExt};pub use project::WorktreePaths;use project::{AgentId, linked_worktree_short_name};-use remote::{RemoteConnectionOptions, same_remote_connection_identity};+use remote::RemoteConnectionOptions;use ui::{App, Context, SharedString, ThreadItemWorktreeInfo, WorktreeKind};use util::{ResultExt as _, paths::PathStyle};use workspace::{PathList, SerializedWorkspaceLocation, WorkspaceDb};@@ -359,7 +359,8 @@ impl ThreadMetadata {&self,remote_connection: Option<&RemoteConnectionOptions>,) -> bool {- same_remote_connection_identity(self.remote_connection.as_ref(), remote_connection)+ self.remote_connection.as_ref().map(|o| o.identity())+ == remote_connection.map(|o| o.identity())}}@@ -989,13 +990,9 @@ impl ThreadMetadataStore {.into_iter().flatten().filter(|id| {- self.threads.get(id).is_some_and(|t| {- !t.archived- && same_remote_connection_identity(- t.remote_connection.as_ref(),- remote_connection,- )- })+ self.threads+ .get(id)+ .is_some_and(|t| !t.archived && t.matches_remote_connection(remote_connection))}).copied().collect();@@ -1318,7 +1315,7 @@ impl ThreadMetadataStore {} else {let project = thread_ref.project().read(cx);let worktree_paths = project.worktree_paths(cx);- let remote_connection = project.remote_connection_options(cx);+ let remote_connection = project.remote_connection_options(cx).cloned();(worktree_paths, remote_connection)};diff --git a/crates/agent_ui/src/thread_worktree_archive.rs b/crates/agent_ui/src/thread_worktree_archive.rsindex a01895ae9b2..006c7f33c9c 100644--- a/crates/agent_ui/src/thread_worktree_archive.rs+++ b/crates/agent_ui/src/thread_worktree_archive.rs@@ -11,7 +11,7 @@ use project::{git_store::{Repository, resolve_git_worktree_to_main_repo, worktrees_directory_for_repo},project_settings::ProjectSettings,};-use remote::{RemoteConnectionOptions, same_remote_connection_identity};+use remote::RemoteConnectionOptions;use settings::Settings;use util::{ResultExt, paths::PathStyle};use workspace::{AppState, MultiWorkspace, Workspace};@@ -117,18 +117,13 @@ pub fn build_root_plan() -> Option<RootPlan> {let path = path.to_path_buf();- let matches_target_connection = |project: &Entity<Project>, cx: &App| {- same_remote_connection_identity(- project.read(cx).remote_connection_options(cx).as_ref(),- remote_connection,- )- };-let affected_projects = workspaces.iter().filter_map(|workspace| {let project = workspace.read(cx).project().clone();- if !matches_target_connection(&project, cx) {+ if project.read(cx).remote_connection_identity(cx)+ != remote_connection.map(|o| o.identity())+ {return None;}let worktree = project@@ -149,7 +144,14 @@ pub fn build_root_plan(let linked_repo = workspaces.iter()- .filter(|workspace| matches_target_connection(workspace.read(cx).project(), cx))+ .filter(|workspace| {+ workspace+ .read(cx)+ .project()+ .read(cx)+ .remote_connection_identity(cx)+ == remote_connection.map(|o| o.identity())+ }).flat_map(|workspace| {workspace.read(cx)@@ -369,13 +371,12 @@ async fn find_or_create_repository(.into_iter().filter_map(|workspace| {let project = workspace.read(cx).project().clone();- let project_connection = project.read(cx).remote_connection_options(cx);- if !same_remote_connection_identity(- project_connection.as_ref(),- remote_connection_owned.as_ref(),- ) {+ if project.read(cx).remote_connection_identity(cx)+ != remote_connection_owned.as_ref().map(|o| o.identity())+ {return None;}+Some((project.read(cx)diff --git a/crates/git_ui/src/git_ui.rs b/crates/git_ui/src/git_ui.rsindex 24d2a50285a..db20f4f2a9d 100644--- a/crates/git_ui/src/git_ui.rs+++ b/crates/git_ui/src/git_ui.rs@@ -153,8 +153,11 @@ pub fn init(cx: &mut App) {let is_remote = !workspace.project().read(cx).is_local();if is_remote {- let connection_options =- workspace.project().read(cx).remote_connection_options(cx);+ let connection_options = workspace+ .project()+ .read(cx)+ .remote_connection_options(cx)+ .cloned();let app_state = workspace.app_state().clone();let workspace_handle = workspace.weak_handle();cx.spawn_in(window, async move |_, cx| {diff --git a/crates/git_ui_core/src/created_worktrees.rs b/crates/git_ui_core/src/created_worktrees.rsindex b026d99a413..003d3c1a549 100644--- a/crates/git_ui_core/src/created_worktrees.rs+++ b/crates/git_ui_core/src/created_worktrees.rs@@ -27,7 +27,7 @@ use anyhow::{Context as _, Result};use db::kvp::KeyValueStore;use gpui::{App, AsyncApp, Entity};use project::git_store::Repository;-use remote::{RemoteConnectionOptions, remote_connection_identity};+use remote::RemoteConnectionOptions;use serde::{Deserialize, Serialize};use util::ResultExt as _;@@ -42,7 +42,7 @@ struct CreatedWorktreeRecord {fn record_key(worktree_path: &Path, remote: Option<&RemoteConnectionOptions>) -> String {let host = match remote {None => "local".to_string(),- Some(options) => remote_connection_identity(options).persistence_key(),+ Some(options) => options.host_key(),};// Paths cannot contain newlines in practice, so this separator is// unambiguous.diff --git a/crates/git_ui_core/src/worktree_picker.rs b/crates/git_ui_core/src/worktree_picker.rsindex d518bee6268..53980722846 100644--- a/crates/git_ui_core/src/worktree_picker.rs+++ b/crates/git_ui_core/src/worktree_picker.rs@@ -678,9 +678,8 @@ impl WorktreePickerDelegate {multi_workspace.read(cx).workspaces_for_project_group(&group_key, cx)- .into_iter().find(|group_workspace| {- *group_workspace != workspace+ *group_workspace != &workspace&& group_workspace.read(cx).project()@@ -688,6 +687,7 @@ impl WorktreePickerDelegate {.visible_worktrees(cx).any(|worktree| worktree.read(cx).abs_path().as_ref() == worktree_path)})+ .cloned()}fn remove_worktree_from_window(diff --git a/crates/git_ui_core/src/worktree_service.rs b/crates/git_ui_core/src/worktree_service.rsindex cc1b230a6bb..cc01351243a 100644--- a/crates/git_ui_core/src/worktree_service.rs+++ b/crates/git_ui_core/src/worktree_service.rs@@ -786,7 +786,7 @@ fn create_worktree_workspace_inner(workspace.capture_state_for_worktree_switch(window, fallback_focused_dock, cx);let workspace_handle = workspace.weak_handle();let window_handle = window.window_handle().downcast::<MultiWorkspace>();- let remote_connection_options = project.read(cx).remote_connection_options(cx);+ let remote_connection_options = project.read(cx).remote_connection_options(cx).cloned();let (git_repos, non_git_paths) = classify_worktrees(project.read(cx), cx);@@ -921,7 +921,7 @@ pub fn handle_switch_worktree(workspace.capture_state_for_worktree_switch(window, fallback_focused_dock, cx);let workspace_handle = workspace.weak_handle();let window_handle = window.window_handle().downcast::<MultiWorkspace>();- let remote_connection_options = project.read(cx).remote_connection_options(cx);+ let remote_connection_options = project.read(cx).remote_connection_options(cx).cloned();let (git_repos, non_git_paths) = classify_worktrees(project.read(cx), cx);diff --git a/crates/project/src/project.rs b/crates/project/src/project.rsindex a1b40aef311..d57040ce5f9 100644--- a/crates/project/src/project.rs+++ b/crates/project/src/project.rs@@ -113,7 +113,7 @@ pub use prettier_store::PrettierStore;use project_settings::{ProjectSettings, SettingsObserver, SettingsObserverEvent};#[cfg(target_os = "windows")]use remote::wsl_path_to_windows_path;-use remote::{RemoteClient, RemoteConnectionOptions, same_remote_connection_identity};+use remote::{RemoteClient, RemoteConnectionIdentity, RemoteConnectionOptions};use rpc::{AnyProtoClient, ErrorCode,proto::{LanguageServerPromptResponse, REMOTE_SERVER_PROJECT_ID},@@ -212,6 +212,12 @@ pub enum OpenedBufferEvent {Err(BufferId, Arc<anyhow::Error>),}+#[derive(Debug, Clone)]+pub enum ProjectHost<'a> {+ Local,+ Remote(&'a RemoteConnectionOptions),+}+/// Semantics-aware entity that is relevant to one or more [`Worktree`] with the files./// `Project` is responsible for tasks, LSP and collab queries, synchronizing worktree states accordingly./// Maps [`Worktree`] entries with its own logic using [`ProjectEntryId`] and [`ProjectPath`] structs.@@ -1505,14 +1511,13 @@ impl Project {.detach();let snippets = SnippetProvider::new(fs.clone(), BTreeSet::from_iter([]), cx);- let (remote_proto, path_style, connection_options) =- remote.read_with(cx, |remote, _| {- (- remote.proto_client(),- remote.path_style(),- remote.connection_options(),- )- });+ let (remote_proto, path_style, remote_host) = remote.read_with(cx, |remote, _| {+ (+ remote.proto_client(),+ remote.path_style(),+ RemoteHostLocation::from(remote.connection_options()),+ )+ });let worktree_store = cx.new(|cx| {WorktreeStore::remote(false,@@ -1528,7 +1533,7 @@ impl Project {if init_worktree_trust {trusted_worktrees::track_worktree_trust(worktree_store.clone(),- Some(RemoteHostLocation::from(connection_options)),+ Some(remote_host),None,Some((remote_proto.clone(), ProjectId(REMOTE_SERVER_PROJECT_ID))),cx,@@ -2414,12 +2419,22 @@ impl Project {}#[inline]- pub fn remote_connection_options(&self, cx: &App) -> Option<RemoteConnectionOptions> {+ pub fn remote_connection_options<'a>(+ &self,+ cx: &'a App,+ ) -> Option<&'a RemoteConnectionOptions> {self.remote_client.as_ref().map(|remote| remote.read(cx).connection_options())}+ pub fn remote_connection_identity<'a>(+ &self,+ cx: &'a App,+ ) -> Option<RemoteConnectionIdentity<'a>> {+ self.remote_connection_options(cx).map(|o| o.identity())+ }+/// Reveals the given path in the system file manager.////// On Windows with a WSL remote connection, this converts the POSIX path@@ -2428,11 +2443,11 @@ impl Project {#[cfg(target_os = "windows")]if let Some(RemoteConnectionOptions::Wsl(wsl_options)) = self.remote_connection_options(cx){- let path = path.to_path_buf();+ let windows_path = wsl_path_to_windows_path(wsl_options, path);cx.spawn(async move |_, cx| {- wsl_path_to_windows_path(&wsl_options, &path)+ windows_path.await- .map(|windows_path| cx.update(|cx| cx.reveal_path(&windows_path)))+ .map(|path| cx.update(|cx| cx.reveal_path(&path)))}).detach_and_log_err(cx);return;@@ -2620,9 +2635,8 @@ impl Project {) -> Option<bool> {paths.iter()- .map(|path| self.visibility_for_path(path, exclude_sub_dirs, cx))+ .filter_map(|path| self.visibility_for_path(path, exclude_sub_dirs, cx)).max()- .flatten()}pub fn visibility_for_path(@@ -2637,10 +2651,8 @@ impl Project {.filter_map(|worktree| {let worktree = worktree.read(cx);let abs_path = worktree.abs_path();- let relative_path = path_style- .strip_prefix(path, abs_path.as_ref())- .ok()- .and_then(|path| RelPath::new(path, path_style).ok())?;+ let relative_path = path_style.strip_prefix(path, abs_path.as_ref()).ok()?;+ let relative_path = RelPath::new(relative_path, path_style).ok()?;// Don't exclude the worktree root itself, only actual subdirectorieslet is_subpath = !relative_path.is_empty();// Gitignored subtrees aren't scanned, so their contents don't@@ -2662,9 +2674,8 @@ impl Project {pub fn visibility_for_subpaths(&self, paths: &[PathBuf], cx: &App) -> Option<bool> {paths.iter()- .map(|path| self.visibility_for_subpath(path, cx))+ .filter_map(|path| self.visibility_for_subpath(path, cx)).max()- .flatten()}fn visibility_for_subpath(&self, path: &Path, cx: &App) -> Option<bool> {@@ -2674,10 +2685,8 @@ impl Project {.filter_map(|worktree| {let worktree = worktree.read(cx);let abs_path = worktree.abs_path();- let relative_path = path_style- .strip_prefix(path, abs_path.as_ref())- .ok()- .and_then(|path| RelPath::new(path, path_style).ok())?;+ let relative_path = path_style.strip_prefix(path, abs_path.as_ref()).ok()?;+ let relative_path = RelPath::new(relative_path, path_style).ok()?;let is_subpath =!relative_path.is_empty() && !worktree.is_path_ignored(&relative_path);is_subpath.then(|| worktree.is_visible())@@ -6857,7 +6866,7 @@ impl ProjectGroupKey {pub fn from_project(project: &Project, cx: &App) -> Self {let paths = project.worktree_paths(cx);- let host = project.remote_connection_options(cx);+ let host = project.remote_connection_options(cx).cloned();Self {paths: paths.main_worktree_path_list().clone(),host,@@ -6904,13 +6913,13 @@ impl ProjectGroupKey {}}- pub fn host(&self) -> Option<RemoteConnectionOptions> {- self.host.clone()+ pub fn host(&self) -> Option<&RemoteConnectionOptions> {+ self.host.as_ref()}- pub fn matches(&self, other: &ProjectGroupKey) -> bool {+ pub fn matches_identity(&self, other: &Self) -> bool {self.paths == other.paths- && same_remote_connection_identity(self.host.as_ref(), other.host.as_ref())+ && self.host.as_ref().map(|o| o.identity()) == other.host.as_ref().map(|o| o.identity())}}diff --git a/crates/project/src/trusted_worktrees.rs b/crates/project/src/trusted_worktrees.rsindex d1f9c97db84..91037b2027b 100644--- a/crates/project/src/trusted_worktrees.rs+++ b/crates/project/src/trusted_worktrees.rs@@ -156,20 +156,20 @@ pub struct RemoteHostLocation {pub host_identifier: SharedString,}-impl From<RemoteConnectionOptions> for RemoteHostLocation {- fn from(options: RemoteConnectionOptions) -> Self {+impl From<&RemoteConnectionOptions> for RemoteHostLocation {+ fn from(options: &RemoteConnectionOptions) -> Self {let (user_name, host_name) = match options {RemoteConnectionOptions::Ssh(ssh) => (- ssh.username.map(SharedString::new),+ ssh.username.as_ref().map(SharedString::new),SharedString::new(ssh.host.to_string()),),RemoteConnectionOptions::Wsl(wsl) => (- wsl.user.map(SharedString::new),- SharedString::new(wsl.distro_name),+ wsl.user.as_ref().map(SharedString::new),+ SharedString::new(&wsl.distro_name),),RemoteConnectionOptions::Docker(docker_connection_options) => (- Some(SharedString::new(docker_connection_options.name)),- SharedString::new(docker_connection_options.container_id),+ Some(SharedString::new(&docker_connection_options.name)),+ SharedString::new(&docker_connection_options.container_id),),#[cfg(feature = "test-support")]RemoteConnectionOptions::Mock(mock) => {diff --git a/crates/recent_projects/src/disconnected_overlay.rs b/crates/recent_projects/src/disconnected_overlay.rsindex e78762eb283..14b5684ed38 100644--- a/crates/recent_projects/src/disconnected_overlay.rs+++ b/crates/recent_projects/src/disconnected_overlay.rs@@ -62,7 +62,8 @@ impl DisconnectedOverlay {}let handle = cx.entity().downgrade();- let remote_connection_options = project.read(cx).remote_connection_options(cx);+ let remote_connection_options =+ project.read(cx).remote_connection_options(cx).cloned();let host = if let Some(remote_connection_options) = remote_connection_options {Host::RemoteServerProject(remote_connection_options,diff --git a/crates/recent_projects/src/recent_projects.rs b/crates/recent_projects/src/recent_projects.rsindex 5578ae93829..38df2653dd6 100644--- a/crates/recent_projects/src/recent_projects.rs+++ b/crates/recent_projects/src/recent_projects.rs@@ -17,7 +17,7 @@ use fs::Fs;#[cfg(target_os = "windows")]mod wsl_picker;-use remote::{RemoteConnectionOptions, same_remote_connection_identity};+use remote::RemoteConnectionOptions;pub use remote_connection::{RemoteConnectionModal, connect, connect_with_modal};pub use remote_connections::{navigate_to_positions, open_remote_project};@@ -246,7 +246,7 @@ fn get_open_folders(workspace: &Workspace, cx: &App) -> Vec<OpenFolderEntry> {path,branch,is_active,- connection_options: connection_options.clone(),+ connection_options: connection_options.cloned(),}}).collect();@@ -1173,7 +1173,7 @@ impl PickerDelegate for RecentProjectsDelegate {.log_err();} else {let path_list = key.path_list().clone();- let host = key.host();+ let host = key.host().cloned();if let Some(task) = handle.update(cx, |multi_workspace, window, cx| {let modal_workspace = multi_workspace.workspace().clone();@@ -1991,7 +1991,7 @@ impl PickerDelegate for RecentProjectsDelegate {fn icon_for_project_group(key: &ProjectGroupKey) -> IconName {let host = key.host();- icon_for_remote_connection(host.as_ref())+ icon_for_remote_connection(host)}pub(crate) fn icon_for_remote_connection(options: Option<&RemoteConnectionOptions>) -> IconName {@@ -2449,7 +2449,7 @@ impl RecentProjectsDelegate {fn is_in_current_window_groups(&self, workspace: &RecentWorkspace) -> bool {self.window_project_groups.iter()- .any(|key| key.matches(&workspace.project_group_key()))+ .any(|key| key.matches_identity(&workspace.project_group_key()))}fn is_open_folder(&self, workspace: &RecentWorkspace) -> bool {@@ -2465,10 +2465,11 @@ impl RecentProjectsDelegate {for workspace_path in workspace.paths.paths() {for open_folder in &self.open_folders {if workspace_path == &open_folder.path- && same_remote_connection_identity(- workspace_host,- open_folder.connection_options.as_ref(),- )+ && workspace_host.map(|o| o.identity())+ == open_folder+ .connection_options+ .as_ref()+ .map(|o| o.identity()){return true;}diff --git a/crates/recent_projects/src/remote_connections.rs b/crates/recent_projects/src/remote_connections.rsindex c6829727d07..72dc75d5d27 100644--- a/crates/recent_projects/src/remote_connections.rs+++ b/crates/recent_projects/src/remote_connections.rs@@ -9,7 +9,7 @@ use editor::Editor;use futures::{FutureExt as _, channel::oneshot, select};use gpui::{AppContext, AsyncApp, PromptLevel, WindowHandle};-use project::trusted_worktrees;+use project::{ProjectHost, trusted_worktrees};use remote::{DockerConnectionOptions, Interactive, RemoteConnection, RemoteConnectionOptions,SshConnectionOptions,@@ -17,10 +17,7 @@ use remote::{pub use settings::SshConnection;use settings::{DevContainerConnection, ExtendingVec, RegisterSetting, Settings, WslConnection};use util::paths::PathWithPosition;-use workspace::{- AppState, MultiWorkspace, OpenOptions, SerializedWorkspaceLocation, Workspace,- find_existing_workspace,-};+use workspace::{AppState, MultiWorkspace, OpenOptions, Workspace, find_existing_workspace};pub use remote_connection::{RemoteClientDelegate, RemoteConnectionModal, RemoteConnectionPrompt, SshConnectionHeader,@@ -45,11 +42,9 @@ impl RemoteSettings {}pub fn fill_connection_options_from_settings(&self, options: &mut SshConnectionOptions) {+ let host = options.host.to_string();for conn in self.ssh_connections() {- if conn.host == options.host.to_string()- && conn.username == options.username- && conn.port == options.port- {+ if conn.host == host && conn.username == options.username && conn.port == options.port {options.nickname = conn.nickname;options.upload_binary_over_ssh = conn.upload_binary_over_ssh.unwrap_or_default();options.args = Some(conn.args);@@ -134,15 +129,17 @@ pub async fn open_remote_project() -> Result<WindowHandle<MultiWorkspace>> {let created_new_window = open_options.requesting_window.is_none();- let (existing, open_visible) = find_existing_workspace(+ let existing = find_existing_workspace(&paths,&open_options,- &SerializedWorkspaceLocation::Remote(connection_options.clone()),+ &ProjectHost::Remote(&connection_options),cx,- )- .await;+ );++ if let Some(existing) = existing {+ let existing_window = existing.window;+ let existing_workspace = existing.workspace;- if let Some((existing_window, existing_workspace)) = existing {let remote_connection = cx.update(|cx| {existing_workspace.read(cx)@@ -164,7 +161,7 @@ pub async fn open_remote_project(workspace.open_paths(resolved_paths,OpenOptions {- visible: Some(open_visible),+ visible: Some(existing.visible),..Default::default()},None,@@ -501,7 +498,7 @@ mod tests {use super::*;use extension::ExtensionHostProxy;use fs::FakeFs;- use gpui::{AppContext, TestAppContext};+ use gpui::{AppContext, Entity, TestAppContext};use http_client::BlockedHttpClient;use node_runtime::NodeRuntime;use project::Project;@@ -593,14 +590,10 @@ mod tests {.unwrap();}- #[gpui::test]- async fn test_find_existing_workspace_does_not_reuse_workspace_from_another_remote(+ async fn init_remote_server(cx: &mut TestAppContext,server_cx: &mut TestAppContext,- ) {- let app_state = init_test(cx);- let executor = cx.executor();-+ ) -> (RemoteConnectionOptions, Entity<HeadlessProject>) {cx.update(|cx| {release_channel::init(semver::Version::new(0, 0, 0), cx);});@@ -630,7 +623,7 @@ mod tests {let languages = Arc::new(language::LanguageRegistry::new(server_cx.executor()));let proxy = Arc::new(ExtensionHostProxy::new());- let _headless = server_cx.new(|cx| {+ let headless = server_cx.new(|cx| {HeadlessProject::new(HeadlessAppState {session: server_session,@@ -648,6 +641,18 @@ mod tests {drop(connect_guard);+ (opts, headless)+ }++ #[gpui::test]+ async fn test_find_existing_workspace_does_not_reuse_workspace_from_another_remote(+ cx: &mut TestAppContext,+ server_cx: &mut TestAppContext,+ ) {+ let app_state = init_test(cx);+ let executor = cx.executor();+ let (opts, _headless) = init_remote_server(cx, server_cx).await;+// First open: create a new window for the remote project.let paths = vec![PathBuf::from(path!("/project"))];let mut async_cx = cx.to_async();@@ -704,38 +709,37 @@ mod tests {.unwrap();let search_paths = vec![PathBuf::from(path!("/project/src/lib.rs"))];- let (found, _) = find_existing_workspace(+ let found = find_existing_workspace(&search_paths,&workspace::OpenOptions::default(),- &SerializedWorkspaceLocation::Remote(other_opts),+ &ProjectHost::Remote(&other_opts),&mut async_cx,- )- .await;+ );+assert!(found.is_none(),"a matching path on another remote must not satisfy the request");// Verify find_existing_workspace discovers the remote workspace.- let (found, _open_visible) = find_existing_workspace(+ let found = find_existing_workspace(&search_paths,&workspace::OpenOptions::default(),- &SerializedWorkspaceLocation::Remote(opts.clone()),+ &ProjectHost::Remote(&opts),&mut async_cx,- )- .await;+ );assert!(found.is_some(),"find_existing_workspace should locate the existing remote workspace");- let (found_window, found_workspace) = found.unwrap();+ let found = found.unwrap();assert_eq!(- found_window, first_window,+ found.window, first_window,"find_existing_workspace should return the same window");assert_eq!(- found_workspace, first_workspace,+ found.workspace, first_workspace,"find_existing_workspace should return the workspace for the requested remote");@@ -767,6 +771,65 @@ mod tests {);}+ #[gpui::test]+ async fn test_local_file_reuses_local_workspace_when_remote_workspace_is_active(+ cx: &mut TestAppContext,+ server_cx: &mut TestAppContext,+ ) {+ let app_state = init_test(cx);+ let (opts, _headless) = init_remote_server(cx, server_cx).await;+ let window = open_remote_project(+ opts,+ vec![PathBuf::from(path!("/project"))],+ app_state.clone(),+ workspace::OpenOptions::default(),+ &mut cx.to_async(),+ )+ .await+ .unwrap();++ app_state+ .fs+ .as_fake()+ .insert_tree(path!("/project"), json!({ "src": { "lib.rs": "" } }))+ .await;+ let local_workspace = window+ .update(cx, |multi_workspace, window, cx| {+ assert!(+ multi_workspace+ .workspace()+ .read(cx)+ .project()+ .read(cx)+ .is_via_remote_server()+ );+ window.activate_window();+ multi_workspace+ .workspaces()+ .find(|workspace| workspace.read(cx).project().read(cx).is_local())+ .cloned()+ .expect("remote connection setup should retain the initial local workspace")+ })+ .unwrap();++ let result = cx+ .update(|cx| {+ workspace::open_paths(+ &[PathBuf::from(path!("/project/src/lib.rs"))],+ app_state,+ workspace::OpenOptions::default(),+ cx,+ )+ })+ .await+ .unwrap();++ assert_eq!(result.window, window);+ assert_eq!(result.workspace, local_workspace);+ assert_eq!(cx.windows().len(), 1);+ assert!(matches!(result.opened_items.as_slice(), [Some(Ok(_))]));+ }+#[gpui::test]async fn test_reopen_existing_remote_root_treats_root_as_directory(cx: &mut TestAppContext,diff --git a/crates/recent_projects/src/sidebar_recent_projects.rs b/crates/recent_projects/src/sidebar_recent_projects.rsindex 006fb7f35d7..0b93ee8aa59 100644--- a/crates/recent_projects/src/sidebar_recent_projects.rs+++ b/crates/recent_projects/src/sidebar_recent_projects.rs@@ -184,7 +184,7 @@ impl PickerDelegate for SidebarRecentProjectsDelegate {&& !self.window_project_groups.iter()- .any(|key| key.matches(&workspace.project_group_key()))+ .any(|key| key.matches_identity(&workspace.project_group_key()))}).map(|(id, workspace)| {let combined_string = workspacediff --git a/crates/remote/src/remote.rs b/crates/remote/src/remote.rsindex 2a8e5160ffe..609da36ac24 100644--- a/crates/remote/src/remote.rs+++ b/crates/remote/src/remote.rs@@ -13,9 +13,7 @@ pub use remote_client::{RemoteClientDelegate, RemoteClientEvent, RemoteConnection, RemoteConnectionOptions, RemoteOs,RemotePlatform, connect, has_active_connection,};-pub use remote_identity::{- RemoteConnectionIdentity, remote_connection_identity, same_remote_connection_identity,-};+pub use remote_identity::RemoteConnectionIdentity;pub use transport::docker::DockerConnectionOptions;pub use transport::ssh::{SshConnectionOptions, SshPortForwardOption};pub use transport::wsl::WslConnectionOptions;diff --git a/crates/remote/src/remote_client.rs b/crates/remote/src/remote_client.rsindex 70c70537e5a..f1f63339a44 100644--- a/crates/remote/src/remote_client.rs+++ b/crates/remote/src/remote_client.rs@@ -1,7 +1,7 @@#[cfg(any(test, feature = "test-support"))]use crate::transport::mock::ConnectGuard;use crate::{- SshConnectionOptions,+ RemoteConnectionIdentity, SshConnectionOptions,command::RemoteCommand,protocol::MessageId,proxy::ProxyLaunchError,@@ -1032,8 +1032,8 @@ impl RemoteClient {self.client.clone().into()}- pub fn connection_options(&self) -> RemoteConnectionOptions {- self.connection_options.clone()+ pub fn connection_options(&self) -> &RemoteConnectionOptions {+ &self.connection_options}pub fn connection(&self) -> Option<Arc<dyn RemoteConnection>> {@@ -1145,7 +1145,7 @@ impl RemoteClient {#[cfg(any(test, feature = "test-support"))]pub fn simulate_disconnect(&self, client_cx: &mut App) -> Task<()> {- let opts = self.connection_options();+ let opts = self.connection_options().clone();client_cx.spawn(async move |cx| {let connection = cx.update_global(|c: &mut ConnectionPool, _| {if let Some(ConnectionPoolEntry::Connected(c)) = c.connections.get(&opts) {@@ -1367,6 +1367,36 @@ pub enum RemoteConnectionOptions {}impl RemoteConnectionOptions {+ pub fn identity(&self) -> RemoteConnectionIdentity<'_> {+ self.into()+ }++ /// The connection key prefix used in created worktree registry.+ pub fn host_key(&self) -> String {+ match self {+ Self::Ssh(options) => format!(+ "ssh:{}@{}:{}",+ options.username.as_deref().unwrap_or_default(),+ options.host.to_string(),+ options+ .port+ .map(|port| port.to_string())+ .unwrap_or_default()+ ),+ Self::Wsl(options) => format!(+ "wsl:{}@{}",+ options.user.as_deref().unwrap_or_default(),+ options.distro_name+ ),+ Self::Docker(options) => format!(+ "docker:{}@{}:{}",+ options.remote_user, options.name, options.container_id+ ),+ #[cfg(any(test, feature = "test-support"))]+ Self::Mock(options) => format!("mock:{}", options.id),+ }+ }+pub fn display_name(&self) -> String {match self {RemoteConnectionOptions::Ssh(opts) => optsdiff --git a/crates/remote/src/remote_identity.rs b/crates/remote/src/remote_identity.rsindex f776bdb7a90..b99bd8b154f 100644--- a/crates/remote/src/remote_identity.rs+++ b/crates/remote/src/remote_identity.rs@@ -1,78 +1,70 @@use crate::RemoteConnectionOptions;+use std::borrow::Cow;-/// A normalized remote identity for matching live remote hosts against-/// persisted remote metadata.-///-/// This mirrors workspace persistence identity semantics rather than full-/// `RemoteConnectionOptions` equality, so runtime-only fields like SSH-/// nicknames or Docker environment overrides do not affect matching.+/// Identifies a remote host for project and workspace matching.#[derive(Debug, Clone, PartialEq, Eq, Hash)]-pub enum RemoteConnectionIdentity {+pub enum RemoteConnectionIdentity<'a> {Ssh {- host: String,- username: Option<String>,+ host: Cow<'a, str>,+ username: Option<Cow<'a, str>>,port: Option<u16>,},Wsl {- distro_name: String,- user: Option<String>,+ distro_name: Cow<'a, str>,+ user: Option<Cow<'a, str>>,},Docker {- container_id: String,- name: String,- remote_user: String,+ container_id: Cow<'a, str>,+ remote_user: Cow<'a, str>,},#[cfg(any(test, feature = "test-support"))]Mock { id: u64 },}-impl RemoteConnectionIdentity {- /// A stable string form of this identity, suitable for use in- /// persistence keys (e.g. database keys scoped to a remote host).- pub fn persistence_key(&self) -> String {+impl RemoteConnectionIdentity<'_> {+ pub fn into_owned(self) -> RemoteConnectionIdentity<'static> {match self {Self::Ssh {host,username,port,- } => format!(- "ssh:{}@{}:{}",- username.as_deref().unwrap_or_default(),- host,- port.map(|port| port.to_string()).unwrap_or_default()- ),- Self::Wsl { distro_name, user } => format!(- "wsl:{}@{}",- user.as_deref().unwrap_or_default(),- distro_name- ),+ } => RemoteConnectionIdentity::Ssh {+ host: Cow::Owned(host.into_owned()),+ username: username.map(|username| Cow::Owned(username.into_owned())),+ port,+ },+ Self::Wsl { distro_name, user } => RemoteConnectionIdentity::Wsl {+ distro_name: Cow::Owned(distro_name.into_owned()),+ user: user.map(|user| Cow::Owned(user.into_owned())),+ },Self::Docker {container_id,- name,remote_user,- } => format!("docker:{remote_user}@{name}:{container_id}"),+ } => RemoteConnectionIdentity::Docker {+ container_id: Cow::Owned(container_id.into_owned()),+ remote_user: Cow::Owned(remote_user.into_owned()),+ },#[cfg(any(test, feature = "test-support"))]- Self::Mock { id } => format!("mock:{id}"),+ Self::Mock { id } => RemoteConnectionIdentity::Mock { id },}}}-impl From<&RemoteConnectionOptions> for RemoteConnectionIdentity {- fn from(options: &RemoteConnectionOptions) -> Self {+impl<'a> From<&'a RemoteConnectionOptions> for RemoteConnectionIdentity<'a> {+ fn from(options: &'a RemoteConnectionOptions) -> Self {match options {RemoteConnectionOptions::Ssh(options) => Self::Ssh {- host: options.host.to_string(),- username: options.username.clone(),+ host: options.host.to_cow(),+ username: options.username.as_deref().map(Cow::Borrowed),port: options.port,},RemoteConnectionOptions::Wsl(options) => Self::Wsl {- distro_name: options.distro_name.clone(),- user: options.user.clone(),+ distro_name: Cow::Borrowed(&options.distro_name),+ user: options.user.as_deref().map(Cow::Borrowed),},RemoteConnectionOptions::Docker(options) => Self::Docker {- container_id: options.container_id.clone(),- name: options.name.clone(),- remote_user: options.remote_user.clone(),+ container_id: Cow::Borrowed(&options.container_id),+ remote_user: Cow::Borrowed(&options.remote_user),},#[cfg(any(test, feature = "test-support"))]RemoteConnectionOptions::Mock(options) => Self::Mock { id: options.id },@@ -80,29 +72,14 @@ impl From<&RemoteConnectionOptions> for RemoteConnectionIdentity {}}-pub fn remote_connection_identity(options: &RemoteConnectionOptions) -> RemoteConnectionIdentity {- options.into()-}--pub fn same_remote_connection_identity(- left: Option<&RemoteConnectionOptions>,- right: Option<&RemoteConnectionOptions>,-) -> bool {- match (left, right) {- (Some(left), Some(right)) => {- remote_connection_identity(left) == remote_connection_identity(right)- }- (None, None) => true,- _ => false,- }-}-#[cfg(test)]mod tests {use std::collections::BTreeMap;- use super::*;- use crate::{DockerConnectionOptions, SshConnectionOptions, WslConnectionOptions};+ use crate::{+ DockerConnectionOptions, RemoteConnectionOptions, SshConnectionOptions,+ WslConnectionOptions,+ };#[test]fn ssh_identity_ignores_non_persisted_runtime_fields() {@@ -129,7 +106,7 @@ mod tests {..Default::default()});- assert!(same_remote_connection_identity(Some(&left), Some(&right),));+ assert_eq!(left.identity(), right.identity());}#[test]@@ -147,7 +124,7 @@ mod tests {..Default::default()});- assert!(!same_remote_connection_identity(Some(&left), Some(&right),));+ assert_ne!(left.identity(), right.identity());}#[test]@@ -161,13 +138,13 @@ mod tests {user: Some("root".to_string()),});- assert!(!same_remote_connection_identity(Some(&left), Some(&right),));+ assert_ne!(left.identity(), right.identity());}#[test]- fn docker_identity_ignores_non_persisted_runtime_fields() {+ fn docker_identity_ignores_display_name_and_runtime_fields() {let left = RemoteConnectionOptions::Docker(DockerConnectionOptions {- name: "zed-dev".to_string(),+ name: "renamed-dev".to_string(),container_id: "container-123".to_string(),remote_user: "anth".to_string(),upload_binary_over_docker_exec: true,@@ -183,17 +160,6 @@ mod tests {remote_env: BTreeMap::new(),});- assert!(same_remote_connection_identity(Some(&left), Some(&right),));- }-- #[test]- fn local_identity_matches_only_local_identity() {- let remote = RemoteConnectionOptions::Wsl(WslConnectionOptions {- distro_name: "Ubuntu".to_string(),- user: Some("anth".to_string()),- });-- assert!(same_remote_connection_identity(None, None));- assert!(!same_remote_connection_identity(None, Some(&remote)));+ assert_eq!(left.identity(), right.identity());}}diff --git a/crates/remote/src/transport/ssh.rs b/crates/remote/src/transport/ssh.rsindex 306ff1da5a6..774fbb7137b 100644--- a/crates/remote/src/transport/ssh.rs+++ b/crates/remote/src/transport/ssh.rs@@ -21,6 +21,7 @@ use semver::Version;pub use settings_content::SshPortForwardOption;use smol::fs;use std::{+ borrow::Cow,fmt::Write as _,net::IpAddr,path::{Path, PathBuf},@@ -74,9 +75,13 @@ impl SshConnectionHost {}pub fn to_string(&self) -> String {+ self.to_cow().into_owned()+ }++ pub fn to_cow(&self) -> Cow<'_, str> {match self {- Self::IpAddr(ip) => ip.to_string(),- Self::Hostname(hostname) => hostname.clone(),+ Self::IpAddr(ip) => Cow::Owned(ip.to_string()),+ Self::Hostname(hostname) => Cow::Borrowed(hostname),}}}diff --git a/crates/repl/src/kernels/mod.rs b/crates/repl/src/kernels/mod.rsindex f7b59d2ef82..4e42eae3edd 100644--- a/crates/repl/src/kernels/mod.rs+++ b/crates/repl/src/kernels/mod.rs@@ -417,7 +417,7 @@ pub fn python_env_kernel_specifications(.remote_connection_options(cx).and_then(|opts| {if let RemoteConnectionOptions::Wsl(wsl) = opts {- Some(wsl.distro_name)+ Some(wsl.distro_name.clone())} else {None}diff --git a/crates/sidebar/src/sidebar.rs b/crates/sidebar/src/sidebar.rsindex 03683bfb6e7..6f01115fe1d 100644--- a/crates/sidebar/src/sidebar.rs+++ b/crates/sidebar/src/sidebar.rs@@ -44,7 +44,7 @@ use project::{AgentId, AgentRegistryStore, Event as ProjectEvent, WorktreeId, repo_identity_path_if_local,};use recent_projects::sidebar_recent_projects::SidebarRecentProjects;-use remote::{RemoteConnectionOptions, same_remote_connection_identity};+use remote::RemoteConnectionOptions;use ui::utils::platform_title_bar_height;use serde::{Deserialize, Serialize};@@ -481,9 +481,10 @@ impl ListEntry {ThreadEntryWorkspace::Open(workspace) => vec![workspace.clone()],ThreadEntryWorkspace::Closed { .. } => Vec::new(),},- ListEntry::ProjectHeader { key, .. } => {- multi_workspace.workspaces_for_project_group(key, cx)- }+ ListEntry::ProjectHeader { key, .. } => multi_workspace+ .workspaces_for_project_group(key, cx)+ .cloned()+ .collect(),}}}@@ -562,6 +563,29 @@ fn workspace_path_list(workspace: &Entity<Workspace>, cx: &App) -> PathList {PathList::new(&workspace.read(cx).root_paths(cx))}+fn find_workspace_for_thread(+ multi_workspace: &MultiWorkspace,+ thread: &ThreadMetadata,+ cx: &App,+) -> Option<Entity<Workspace>> {+ multi_workspace+ .workspaces()+ .find(|workspace| {+ if workspace_path_list(workspace, cx) != *thread.folder_paths() {+ return false;+ }++ thread.matches_remote_connection(+ workspace+ .read(cx)+ .project()+ .read(cx)+ .remote_connection_options(cx),+ )+ })+ .cloned()+}+fn linked_worktree_path_lists_for_workspaces(workspaces: &[Entity<Workspace>],cx: &App,@@ -600,7 +624,7 @@ fn workspace_has_terminal_metadata_except(.remote_connection_options(cx);store.read(cx)- .entries_for_path(&path_list, remote_connection.as_ref())+ .entries_for_path(&path_list, remote_connection).any(|terminal| except_terminal_id != Some(terminal.terminal_id))}@@ -1119,7 +1143,7 @@ impl Sidebar {return;}- let remote_connection = project.read(cx).remote_connection_options(cx);+ let remote_connection = project.read(cx).remote_connection_options(cx).cloned();let apply_path_changes = |paths: &mut WorktreePaths| {for (main_path, folder_path) in &added_pairs {paths.add_path(main_path, folder_path);@@ -1314,7 +1338,7 @@ impl Sidebar {return;};let path_list = project_group_key.path_list().clone();- let host = project_group_key.host();+ let host = project_group_key.host().cloned();let provisional_key = Some(project_group_key.clone());let active_workspace = multi_workspace.read(cx).workspace().clone();let modal_workspace = active_workspace.clone();@@ -1354,7 +1378,7 @@ impl Sidebar {};let path_list = project_group_key.path_list().clone();- let host = project_group_key.host();+ let host = project_group_key.host().cloned();let provisional_key = Some(project_group_key.clone());let active_workspace = multi_workspace.read(cx).workspace().clone();@@ -1541,7 +1565,7 @@ impl Sidebar {};for row in terminal_store.read(cx)- .entries_for_main_worktree_path(group_key.path_list(), group_host.as_ref())+ .entries_for_main_worktree_path(group_key.path_list(), group_host).cloned(){let workspace = resolve_workspace(row.folder_paths());@@ -1549,7 +1573,7 @@ impl Sidebar {}for row in terminal_store.read(cx)- .entries_for_path(group_key.path_list(), group_host.as_ref())+ .entries_for_path(group_key.path_list(), group_host).cloned(){let workspace = resolve_workspace(row.folder_paths());@@ -1562,7 +1586,7 @@ impl Sidebar {}for row in terminal_store.read(cx)- .entries_for_path(&ws_paths, group_host.as_ref())+ .entries_for_path(&ws_paths, group_host).cloned(){push_terminal_metadata(row, ThreadEntryWorkspace::Open(ws.clone()));@@ -1571,7 +1595,7 @@ impl Sidebar {for worktree_path_list in &linked_worktree_path_lists {for row in terminal_store.read(cx)- .entries_for_path(worktree_path_list, group_host.as_ref())+ .entries_for_path(worktree_path_list, group_host).cloned(){push_terminal_metadata(@@ -1650,7 +1674,7 @@ impl Sidebar {// linked worktree the thread was opened in.for row in thread_store.read(cx)- .entries_for_main_worktree_path(group_key.path_list(), group_host.as_ref())+ .entries_for_main_worktree_path(group_key.path_list(), group_host).cloned(){if !seen_thread_ids.insert(row.thread_id) {@@ -1666,7 +1690,7 @@ impl Sidebar {// Load any legacy threads for the main worktrees of this project group.for row in thread_store.read(cx)- .entries_for_path(group_key.path_list(), group_host.as_ref())+ .entries_for_path(group_key.path_list(), group_host).cloned(){if !seen_thread_ids.insert(row.thread_id) {@@ -1694,7 +1718,7 @@ impl Sidebar {}for row in thread_store.read(cx)- .entries_for_path(&ws_paths, group_host.as_ref())+ .entries_for_path(&ws_paths, group_host).cloned(){if !seen_thread_ids.insert(row.thread_id) {@@ -1711,7 +1735,7 @@ impl Sidebar {for worktree_path_list in &linked_worktree_path_lists {for row in thread_store.read(cx)- .entries_for_path(worktree_path_list, group_host.as_ref())+ .entries_for_path(worktree_path_list, group_host).cloned(){if !seen_thread_ids.insert(row.thread_id) {@@ -1857,13 +1881,13 @@ impl Sidebar {let has_stored_thread_rows = !should_load_threads && !has_visible_rows && {let store = ThreadMetadataStore::global(cx).read(cx);store- .entries_for_main_worktree_path(group_key.path_list(), group_host.as_ref())+ .entries_for_main_worktree_path(group_key.path_list(), group_host).any(|metadata| {let workspace = resolve_workspace(metadata.folder_paths());thread_metadata_would_render_sidebar_row(metadata, &workspace, cx)})|| store- .entries_for_path(group_key.path_list(), group_host.as_ref())+ .entries_for_path(group_key.path_list(), group_host).any(|metadata| {let workspace = resolve_workspace(metadata.folder_paths());thread_metadata_would_render_sidebar_row(metadata, &workspace, cx)@@ -1972,8 +1996,8 @@ impl Sidebar {let thread_store = ThreadMetadataStore::global(cx);let store = thread_store.read(cx);let group_thread_ids = store- .entries_for_main_worktree_path(group_key.path_list(), group_host.as_ref())- .chain(store.entries_for_path(group_key.path_list(), group_host.as_ref()))+ .entries_for_main_worktree_path(group_key.path_list(), group_host)+ .chain(store.entries_for_path(group_key.path_list(), group_host)).map(|m| m.thread_id).collect::<HashSet<_>>();current_thread_ids.extend(group_thread_ids.iter());@@ -2419,10 +2443,9 @@ impl Sidebar {.w_full().gap_1().child(label)- .when_some(- self.render_remote_project_icon(ix, host.as_ref()),- |this, icon| this.child(icon),- )+ .when_some(self.render_remote_project_icon(ix, host), |this, icon| {+ this.child(icon)+ }).when(is_collapsed, |this| {this.when(has_running_threads, |this| {this.child(@@ -2584,7 +2607,12 @@ impl Sidebar {let open_workspaces = self.multi_workspace.upgrade()- .map(|mw| mw.read(cx).workspaces_for_project_group(key, cx))+ .map(|mw| {+ mw.read(cx)+ .workspaces_for_project_group(key, cx)+ .cloned()+ .collect::<Vec<_>>()+ }).unwrap_or_default();if open_workspaces.is_empty() {@@ -2806,7 +2834,7 @@ impl Sidebar {let Some(base) = multi_workspace.read(cx).workspaces_for_project_group(&key, cx)- .first()+ .next().cloned()else {continue;@@ -2908,7 +2936,10 @@ impl Sidebar {let open_workspaces = multi_workspace.read_with(cx, |multi_workspace, cx| {- multi_workspace.workspaces_for_project_group(&project_group_key, cx)+ multi_workspace+ .workspaces_for_project_group(&project_group_key, cx)+ .cloned()+ .collect::<Vec<_>>()}).unwrap_or_default();@@ -3009,19 +3040,11 @@ impl Sidebar {return;}this.update(cx, |sidebar, cx| {- if let Some(workspace) =- sidebar.workspace_for_group(&project_group_key, cx)- {- sidebar.activate_workspace(&workspace, window, cx);- } else {- sidebar.open_workspace_for_group(- &project_group_key,- window,- cx,- );- }- sidebar.selection = None;- sidebar.active_entry = None;+ sidebar.activate_or_open_workspace_for_group(+ &project_group_key,+ window,+ cx,+ );}).ok();}@@ -3683,39 +3706,6 @@ impl Sidebar {}}- fn find_workspace_across_windows(- &self,- cx: &App,- predicate: impl Fn(&Entity<Workspace>, &App) -> bool,- ) -> Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> {- cx.windows()- .into_iter()- .filter_map(|window| window.downcast::<MultiWorkspace>())- .find_map(|window| {- let workspace = window.read(cx).ok().and_then(|multi_workspace| {- multi_workspace- .workspaces()- .find(|workspace| predicate(workspace, cx))- .cloned()- })?;- Some((window, workspace))- })- }-- fn find_workspace_in_current_window(- &self,- cx: &App,- predicate: impl Fn(&Entity<Workspace>, &App) -> bool,- ) -> Option<Entity<Workspace>> {- self.multi_workspace.upgrade().and_then(|multi_workspace| {- multi_workspace- .read(cx)- .workspaces()- .find(|workspace| predicate(workspace, cx))- .cloned()- })- }-fn load_agent_thread_in_workspace(workspace: &Entity<Workspace>,metadata: &ThreadMetadata,@@ -4014,7 +4004,6 @@ impl Sidebar {) {let target_session_id = metadata.session_id.clone();let metadata_thread_id = metadata.thread_id;- let workspace_for_entry = workspace.clone();let activated = target_window.update(cx, |multi_workspace, window, cx| {@@ -4038,8 +4027,8 @@ impl Sidebar {sidebar.pending_thread_activation = Some(metadata_thread_id);sidebar.active_entry = Some(ActiveEntry::Thread {thread_id: metadata_thread_id,- session_id: target_session_id.clone(),- workspace: workspace_for_entry.clone(),+ session_id: target_session_id,+ workspace,});sidebar.record_thread_access(&metadata_thread_id);sidebar.update_entries(cx);@@ -4057,20 +4046,35 @@ impl Sidebar {cx: &mut Context<Self>,) {if self- .find_workspace_in_current_window(cx, |candidate, _| candidate == workspace)- .is_some()+ .multi_workspace+ .upgrade()+ .is_some_and(|multi_workspace| {+ multi_workspace+ .read(cx)+ .workspaces()+ .any(|candidate| candidate == workspace)+ }){self.activate_thread_locally(&metadata, &workspace, retain, window, cx);return;}- let Some((target_window, workspace)) =- self.find_workspace_across_windows(cx, |candidate, _| candidate == workspace)+ let Some(target_window) = cx+ .windows()+ .into_iter()+ .filter_map(|window| window.downcast::<MultiWorkspace>())+ .find(|window| {+ window.read(cx).is_ok_and(|multi_workspace| {+ multi_workspace+ .workspaces()+ .any(|candidate| candidate == workspace)+ })+ })else {return;};- self.activate_thread_in_other_window(metadata, workspace, target_window, cx);+ self.activate_thread_in_other_window(metadata, workspace.clone(), target_window, cx);}fn open_workspace_and_activate_thread(@@ -4091,7 +4095,7 @@ impl Sidebar {// reconciliation cannot synthesize an empty fallback draft.self.pending_thread_activation = Some(pending_thread_id);- let host = project_group_key.host();+ let host = project_group_key.host().cloned();let provisional_key = Some(project_group_key.clone());let active_workspace = multi_workspace.read(cx).workspace().clone();let modal_workspace = active_workspace.clone();@@ -4134,44 +4138,19 @@ impl Sidebar {.detach_and_log_err(cx);}- fn find_current_workspace_for_path_list(+ fn find_open_workspace_for_thread(&self,- path_list: &PathList,- remote_connection: Option<&RemoteConnectionOptions>,- cx: &App,- ) -> Option<Entity<Workspace>> {- self.find_workspace_in_current_window(cx, |workspace, cx| {- workspace_path_list(workspace, cx).paths() == path_list.paths()- && same_remote_connection_identity(- workspace- .read(cx)- .project()- .read(cx)- .remote_connection_options(cx)- .as_ref(),- remote_connection,- )- })- }-- fn find_open_workspace_for_path_list(- &self,- path_list: &PathList,- remote_connection: Option<&RemoteConnectionOptions>,+ thread: &ThreadMetadata,cx: &App,) -> Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> {- self.find_workspace_across_windows(cx, |workspace, cx| {- workspace_path_list(workspace, cx).paths() == path_list.paths()- && same_remote_connection_identity(- workspace- .read(cx)- .project()- .read(cx)- .remote_connection_options(cx)- .as_ref(),- remote_connection,- )- })+ cx.windows()+ .into_iter()+ .filter_map(|window| window.downcast::<MultiWorkspace>())+ .find_map(|window| {+ let workspace = find_workspace_for_thread(window.read(cx).ok()?, thread, cx)?;++ Some((window, workspace))+ })}fn open_thread_from_archive(@@ -4198,11 +4177,9 @@ impl Sidebar {self.activate_thread_locally(&metadata, &workspace, false, window, cx);} else {let path_list = metadata.folder_paths().clone();- if let Some((target_window, workspace)) = self.find_open_workspace_for_path_list(- &path_list,- metadata.remote_connection.as_ref(),- cx,- ) {+ if let Some((target_window, workspace)) =+ self.find_open_workspace_for_thread(&metadata, cx)+ {self.activate_thread_in_other_window(metadata, workspace, target_window, cx);} else {let key = ProjectGroupKey::from_worktree_paths(@@ -4238,18 +4215,15 @@ impl Sidebar {.update(cx, |store, cx| store.unarchive(thread_id, cx));}- if let Some(workspace) = this.find_current_workspace_for_path_list(- &path_list,- metadata.remote_connection.as_ref(),- cx,- ) {+ let current_workspace =+ this.multi_workspace.upgrade().and_then(|multi_workspace| {+ find_workspace_for_thread(multi_workspace.read(cx), &metadata, cx)+ });++ if let Some(workspace) = current_workspace {this.activate_thread_locally(&metadata, &workspace, false, window, cx);- } else if let Some((target_window, workspace)) = this- .find_open_workspace_for_path_list(- &path_list,- metadata.remote_connection.as_ref(),- cx,- )+ } else if let Some((target_window, workspace)) =+ this.find_open_workspace_for_thread(&metadata, cx){this.activate_thread_in_other_window(metadata,@@ -4724,7 +4698,7 @@ impl Sidebar {return;};- let host = project_group_key.host();+ let host = project_group_key.host().cloned();let provisional_key = Some(project_group_key.clone());let active_workspace = multi_workspace.read(cx).workspace().clone();let modal_workspace = active_workspace.clone();@@ -5040,7 +5014,7 @@ impl Sidebar {return;};- let host = project_group_key.host();+ let host = project_group_key.host().cloned();let active_workspace = multi_workspace.read(cx).workspace().clone();let modal_workspace = active_workspace.clone();@@ -5944,11 +5918,8 @@ impl Sidebar {ThreadEntryWorkspace::Closed { .. } => {current_header_key.as_ref().and_then(|key| {self.multi_workspace.upgrade().and_then(|mw| {- mw.read(cx).workspace_for_paths(- key.path_list(),- key.host().as_ref(),- cx,- )+ mw.read(cx)+ .workspace_for_paths(key.path_list(), key.host(), cx)})})}@@ -7167,6 +7138,8 @@ impl Sidebar {}}+ /// Return the active workspace when it belongs to the group+ /// Otherwise, return the workspace for project path.fn workspace_for_group(&self, key: &ProjectGroupKey, cx: &App) -> Option<Entity<Workspace>> {let mw = self.multi_workspace.upgrade()?;let mw = mw.read(cx);@@ -7175,10 +7148,11 @@ impl Sidebar {if active_key == *key {Some(active)} else {- mw.workspace_for_paths(key.path_list(), key.host().as_ref(), cx)+ mw.workspace_for_paths(key.path_list(), key.host(), cx)}}+ /// Activates or opens a workspace for the group, preferring its last active one.pub(crate) fn activate_or_open_workspace_for_group(&mut self,key: &ProjectGroupKey,@@ -7256,7 +7230,7 @@ impl Sidebar {if let Some(workspace) = self.multi_workspace.upgrade().and_then(|mw| {mw.read(cx)- .workspace_for_paths(key.path_list(), key.host().as_ref(), cx)+ .workspace_for_paths(key.path_list(), key.host(), cx)}) {multi_workspace.update(cx, |multi_workspace, cx| {multi_workspace.activate(workspace, None, window, cx);diff --git a/crates/sidebar/src/sidebar_tests.rs b/crates/sidebar/src/sidebar_tests.rsindex c3d444c03ab..54332e0caa2 100644--- a/crates/sidebar/src/sidebar_tests.rs+++ b/crates/sidebar/src/sidebar_tests.rs@@ -478,7 +478,7 @@ fn save_thread_metadata() {cx.update(|cx| {let worktree_paths = project.read(cx).worktree_paths(cx);- let remote_connection = project.read(cx).remote_connection_options(cx);+ let remote_connection = project.read(cx).remote_connection_options(cx).cloned();let thread_id = ThreadMetadataStore::global(cx).read(cx).entries()@@ -13428,7 +13428,7 @@ mod property_test {let key = &keys[project_group_index];let ws = mw.workspaces_for_project_group(key, cx)- .first()+ .next().cloned().unwrap_or_else(|| mw.workspace().clone());let project = ws.read(cx).project().clone();@@ -13474,7 +13474,7 @@ mod property_test {interacted_at: None,worktree_paths: project.read(cx).worktree_paths(cx),archived: false,- remote_connection: project.read(cx).remote_connection_options(cx),+ remote_connection: project.read(cx).remote_connection_options(cx).cloned(),});cx.update(|_, cx| {ThreadMetadataStore::global(cx)@@ -13581,7 +13581,7 @@ mod property_test {let keys = mw.project_group_keys();let key = &keys[index];mw.workspaces_for_project_group(key, cx)- .first()+ .next().cloned().unwrap_or_else(|| mw.workspace().clone())});@@ -13651,7 +13651,7 @@ mod property_test {let keys = mw.project_group_keys();let key = &keys[project_group_index];mw.workspaces_for_project_group(key, cx)- .first()+ .next().cloned().unwrap()});@@ -13671,7 +13671,7 @@ mod property_test {let workspace = multi_workspace.read_with(cx, |mw, cx| {let keys = mw.project_group_keys();let key = &keys[project_group_index];- mw.workspaces_for_project_group(key, cx).first().cloned()+ mw.workspaces_for_project_group(key, cx).next().cloned()});let Some(workspace) = workspace else { return };let project = workspace.read_with(cx, |ws, _| ws.project().clone());@@ -13698,7 +13698,7 @@ mod property_test {let workspace = multi_workspace.read_with(cx, |mw, cx| {let keys = mw.project_group_keys();let key = &keys[project_group_index];- mw.workspaces_for_project_group(key, cx).first().cloned()+ mw.workspaces_for_project_group(key, cx).next().cloned()});let Some(workspace) = workspace else { return };let project = workspace.read_with(cx, |ws, _| ws.project().clone());@@ -14323,7 +14323,7 @@ async fn test_remote_project_integration_does_not_briefly_render_as_separate_prolet (main_worktree_paths, remote_connection) = project.read_with(cx, |p, cx| {(p.project_group_key(cx).path_list().clone(),- p.remote_connection_options(cx),+ p.remote_connection_options(cx).cloned(),)});cx.update(|_window, cx| {@@ -15276,7 +15276,7 @@ async fn test_remote_archive_thread_with_active_connection(// the folder at the linked worktree checkout and the main at the// parent repo, so `build_root_plan` targets the linked worktree// specifically and knows which main repo owns it.- let remote_connection = project.read_with(cx, |p, cx| p.remote_connection_options(cx));+ let remote_connection = project.read_with(cx, |p, cx| p.remote_connection_options(cx).cloned());// Record the worktree as Zed-created on the client, keyed by the remote// connection identity, with the creation time of the gitdir on thediff --git a/crates/title_bar/src/title_bar.rs b/crates/title_bar/src/title_bar.rsindex 21411e21f4d..d1e12738ee7 100644--- a/crates/title_bar/src/title_bar.rs+++ b/crates/title_bar/src/title_bar.rs@@ -628,22 +628,16 @@ impl TitleBar {let options = self.project.read(cx).remote_connection_options(cx)?;let host: SharedString = options.display_name().into();- let (nickname, tooltip_title, icon) = match options {- RemoteConnectionOptions::Ssh(options) => (- options.nickname.map(|nick| nick.into()),- "Remote Project",- IconName::Server,- ),- RemoteConnectionOptions::Wsl(_) => (None, "Remote Project", IconName::Linux),+ let (tooltip_title, icon) = match options {+ RemoteConnectionOptions::Ssh(_) => ("Remote Project", IconName::Server),+ RemoteConnectionOptions::Wsl(_) => ("Remote Project", IconName::Linux),RemoteConnectionOptions::Docker(_dev_container_connection) => {- (None, "Dev Container", IconName::Box)+ ("Dev Container", IconName::Box)}#[cfg(any(test, feature = "test-support"))]- RemoteConnectionOptions::Mock(_) => (None, "Mock Remote Project", IconName::Server),+ RemoteConnectionOptions::Mock(_) => ("Mock Remote Project", IconName::Server),};- let nickname = nickname.unwrap_or_else(|| host.clone());-let (indicator_color, meta) = match self.project.read(cx).remote_connection_state(cx)? {remote::ConnectionState::Connecting => (Color::Info, format!("Connecting to: {host}")),remote::ConnectionState::Connected => (Color::Success, format!("Connected to: {host}")),@@ -700,7 +694,7 @@ impl TitleBar {)).into_any_element(),)- .child(Label::new(nickname).size(LabelSize::Small).truncate()),+ .child(Label::new(host).size(LabelSize::Small).truncate()),),move |_window, cx| {Tooltip::with_meta(diff --git a/crates/workspace/src/multi_workspace.rs b/crates/workspace/src/multi_workspace.rsindex 0f47414f4be..12d18436bfc 100644--- a/crates/workspace/src/multi_workspace.rs+++ b/crates/workspace/src/multi_workspace.rs@@ -593,7 +593,8 @@ impl MultiWorkspace {.read(cx).project().read(cx)- .remote_connection_options(cx);+ .remote_connection_options(cx)+ .cloned();let old_key =ProjectGroupKey::from_worktree_paths(old_worktree_paths, host);this.handle_project_group_key_change(&workspace, &old_key, cx);@@ -851,7 +852,10 @@ impl MultiWorkspace {.iter().map(|group| ProjectGroup {key: group.key.clone(),- workspaces: self.workspaces_for_project_group(&group.key, cx),+ workspaces: self+ .workspaces_for_project_group(&group.key, cx)+ .cloned()+ .collect(),expanded: group.expanded,}).collect()@@ -929,17 +933,16 @@ impl MultiWorkspace {true}- pub fn workspaces_for_project_group(- &self,- key: &ProjectGroupKey,- cx: &App,- ) -> Vec<Entity<Workspace>> {+ pub fn workspaces_for_project_group<'a>(+ &'a self,+ key: &'a ProjectGroupKey,+ cx: &'a App,+ ) -> impl Iterator<Item = &'a Entity<Workspace>> {self.held.iter().filter(|held| held.pinned)- .map(|held| held.workspace.clone())- .filter(|workspace| workspace.read(cx).project_group_key(cx) == *key)- .collect()+ .map(|held| &held.workspace)+ .filter(move |workspace| workspace.read(cx).project_group_key(cx) == *key)}pub fn remove_project_group(@@ -961,7 +964,10 @@ impl MultiWorkspace {self.pin(index, group_key.clone(), cx);}- let workspaces = self.workspaces_for_project_group(group_key, cx);+ let workspaces = self+ .workspaces_for_project_group(group_key, cx)+ .cloned()+ .collect::<Vec<_>>();if workspaces.is_empty() {let previous_group_count = self.project_groups.len();self.project_groups.retain(|group| group.key != *group_key);@@ -1035,7 +1041,10 @@ impl MultiWorkspace {let app_state = self.workspace().read(cx).app_state().clone();- let workspaces: Vec<_> = self.workspaces_for_project_group(key, cx);+ let workspaces: Vec<_> = self+ .workspaces_for_project_group(key, cx)+ .cloned()+ .collect();let mut serialization_tasks = Vec::new();for workspace in &workspaces {serialization_tasks.push(workspace.update(cx, |workspace, inner_cx| {@@ -1069,17 +1078,13 @@ impl MultiWorkspace {host: Option<&RemoteConnectionOptions>,cx: &App,) -> Option<Entity<Workspace>> {- for workspace in self.workspaces() {- let root_paths = PathList::new(&workspace.read(cx).root_paths(cx));- let key = workspace.read(cx).project_group_key(cx);- let host_matches = key.host().as_ref() == host;- let paths_match = root_paths == *path_list;- if host_matches && paths_match {- return Some(workspace.clone());- }- }-- None+ self.workspaces()+ .find(|workspace| {+ let workspace = workspace.read(cx);+ workspace.project().read(cx).remote_connection_options(cx) == host+ && PathList::new(&workspace.root_paths(cx)) == *path_list+ })+ .cloned()}/// Finds an existing workspace whose paths match, or creates a new one.@@ -1215,7 +1220,18 @@ impl MultiWorkspace {window: &mut Window,cx: &mut Context<Self>,) -> Task<Result<Entity<Workspace>>> {- if let Some(workspace) = self.workspace_for_paths(&path_list, None, cx) {+ let local_workspace_for_paths = |multi_workspace: &Self, path_list: &PathList, cx: &App| {+ multi_workspace+ .workspaces()+ .find(|workspace| {+ let workspace = workspace.read(cx);+ workspace.project().read(cx).is_local()+ && PathList::new(&workspace.root_paths(cx)) == *path_list+ })+ .cloned()+ };++ if let Some(workspace) = local_workspace_for_paths(self, &path_list, cx) {self.activate(workspace.clone(), source_workspace, window, cx);return Task::ready(Ok(workspace));}@@ -1252,8 +1268,7 @@ impl MultiWorkspace {if let Some(requesting_window) = requesting_window&& let Some(workspace) = requesting_window.update(cx, |multi_workspace, window, cx| {- multi_workspace- .workspace_for_paths(&effective_path_list, None, cx)+ local_workspace_for_paths(multi_workspace, &effective_path_list, cx).inspect(|workspace| {multi_workspace.activate(workspace.clone(),diff --git a/crates/workspace/src/multi_workspace_tests.rs b/crates/workspace/src/multi_workspace_tests.rsindex 8d77cdd492b..d60a676228b 100644--- a/crates/workspace/src/multi_workspace_tests.rs+++ b/crates/workspace/src/multi_workspace_tests.rs@@ -459,6 +459,119 @@ async fn test_open_directory_in_empty_workspace_does_not_open_sidebar(cx: &mut T.unwrap();}+#[gpui::test]+async fn test_local_files_reuse_local_workspace_when_non_local_workspace_is_active(+ cx: &mut TestAppContext,+) {+ init_test(cx);+ let app_state = cx.update(AppState::test);+ app_state+ .fs+ .as_fake()+ .insert_tree(+ path!("/"),+ json!({+ "local": { "inside.txt": "" },+ "outside": { "loose.txt": "" },+ }),+ )+ .await;+ cx.update(|cx| {+ cx.default_global::<ProjectItemRegistry>()+ .build_project_item_for_path_fns+ .push(|_, _, _, _| {+ let build_item: WorkspaceItemBuilder =+ Box::new(|_, _, cx| cx.new(TestItem::new).boxed_clone());+ Some(Task::ready(Ok((None, build_item))))+ });+ });++ let remote_project = Project::test(FakeFs::new(cx.executor()), [], cx).await;+ remote_project.update(cx, |project, _| project.mark_as_collab_for_testing());+ let local_project = Project::test(app_state.fs.clone(), [path!("/local").as_ref()], cx).await;+ let window =+ cx.add_window(|window, cx| MultiWorkspace::test_new(remote_project.clone(), window, cx));+ let (remote_workspace, local_workspace) = window+ .update(cx, |multi_workspace, window, cx| {+ multi_workspace.open_sidebar(cx);+ let remote_workspace = multi_workspace.workspace().clone();+ let local_workspace = multi_workspace.test_add_workspace(local_project, window, cx);+ (remote_workspace, local_workspace)+ })+ .unwrap();++ for (path, wait) in [+ (path!("/outside/loose.txt"), false),+ (path!("/local/inside.txt"), true),+ ] {+ window+ .update(cx, |multi_workspace, window, cx| {+ multi_workspace.activate(remote_workspace.clone(), None, window, cx);+ window.activate_window();+ })+ .unwrap();+ let result = cx+ .update(|cx| {+ open_paths(+ &[PathBuf::from(path)],+ app_state.clone(),+ OpenOptions {+ wait,+ ..Default::default()+ },+ cx,+ )+ })+ .await+ .unwrap();++ assert_eq!(result.window, window, "{path}, wait: {wait}");+ assert_eq!(result.workspace, local_workspace, "{path}, wait: {wait}");+ assert_eq!(cx.windows().len(), 1);+ assert!(matches!(result.opened_items.as_slice(), [Some(Ok(_))]));+ window+ .read_with(cx, |multi_workspace, _| {+ assert_eq!(multi_workspace.workspace(), &local_workspace);+ })+ .unwrap();+ }+}++#[gpui::test]+async fn test_local_workspace_lookup_skips_collab_with_same_paths(cx: &mut TestAppContext) {+ init_test(cx);++ let fs = FakeFs::new(cx.executor());+ fs.insert_tree(path!("/project"), json!({})).await;++ let collab_project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;+ collab_project.update(cx, |project, _| project.mark_as_collab_for_testing());++ let local_project = Project::test(fs, [path!("/project").as_ref()], cx).await;+ let (multi_workspace, cx) = setup_multi_workspace(&[collab_project, local_project], cx);++ let paths = PathList::new(&[PathBuf::from(path!("/project"))]);++ let local_workspace =+ multi_workspace.read_with(cx, |multi_workspace, _| multi_workspace.workspace().clone());+ let workspace = multi_workspace+ .update_in(cx, |multi_workspace, window, cx| {+ multi_workspace.find_or_create_local_workspace(+ paths,+ None,+ None,+ OpenMode::Activate,+ None,+ window,+ cx,+ )+ })+ .await+ .unwrap();++ assert_eq!(workspace, local_workspace);+}+#[gpui::test]async fn test_project_group_keys_duplicate_not_added(cx: &mut TestAppContext) {init_test(cx);@@ -910,7 +1023,8 @@ async fn test_close_workspace_prefers_already_loaded_neighboring_workspace(assert!(multi_workspace.workspaces_for_project_group(&project_c_key, cx)- .is_empty(),+ .next()+ .is_none(),"the unloaded neighboring group C should remain unopened");});@@ -930,14 +1044,14 @@ async fn test_close_workspace_prefers_workspace_in_same_project_group(cx: &mut Tlet (multi_workspace, cx) = setup_multi_workspace(&[project_a_1, project_a_2, project_b], cx);let (workspace_a_1, workspace_a_2) = multi_workspace.read_with(cx, |multi_workspace, cx| {- let mut workspaces = multi_workspace- .workspaces_for_project_group(&key_a, cx)- .into_iter();+ let mut workspaces = multi_workspace.workspaces_for_project_group(&key_a, cx);let first = workspaces.next()+ .cloned().expect("project group A should have a first workspace");let second = workspaces.next()+ .cloned().expect("project group A should have a second workspace");assert!(@@ -973,7 +1087,10 @@ async fn test_close_workspace_prefers_workspace_in_same_project_group(cx: &mut T);assert_eq!(- multi_workspace.workspaces_for_project_group(&key_a, cx),+ multi_workspace+ .workspaces_for_project_group(&key_a, cx)+ .cloned()+ .collect::<Vec<_>>(),vec![workspace_a_2],"only the fallback workspace should remain in project group A");@@ -1637,25 +1754,27 @@ async fn test_nearest_retained_workspace(cx: &mut TestAppContext) {.expect("project group for project-c should exist");let workspace_b = multi_workspace.workspaces_for_project_group(&key_b, cx)- .into_iter().next()+ .cloned().expect("workspace for project-b should exist");let workspace_d = multi_workspace.workspaces_for_project_group(&key_d, cx)- .into_iter().next()+ .cloned().expect("workspace for project-d should exist");let retained_workspaces_a = multi_workspace- .workspaces_for_project_group(&key_a, cx);+ .workspaces_for_project_group(&key_a, cx)+ .collect::<Vec<_>>();assert_eq!(retained_workspaces_a.len(),2,"project group A should retain both workspaces");let workspace_a_1 = retained_workspaces_a- .first()- .expect("project group A should have a retained workspace")- .clone();+ .into_iter()+ .next()+ .cloned()+ .expect("project group A should have a retained workspace");let workspace_a_2 = multi_workspace.last_active_workspace_for_group(&key_a, cx).expect("project group A should have a last active workspace");diff --git a/crates/workspace/src/persistence.rs b/crates/workspace/src/persistence.rsindex 9d15c57ebb4..4c7baadc9e1 100644--- a/crates/workspace/src/persistence.rs+++ b/crates/workspace/src/persistence.rs@@ -30,7 +30,7 @@ use project::{use language::{LanguageName, Toolchain, ToolchainScope};use remote::{DockerConnectionOptions, RemoteConnectionIdentity, RemoteConnectionOptions,- SshConnectionOptions, WslConnectionOptions, remote_connection_identity,+ SshConnectionOptions, WslConnectionOptions,};use serde::{Deserialize, Serialize};use sqlez::{@@ -1500,7 +1500,7 @@ impl WorkspaceDb {log::debug!("Saving workspace at location: {:?}", workspace.location);self.write(move |conn| {conn.with_savepoint("update_worktrees", || {- let remote_connection_id = match workspace.location.clone() {+ let remote_connection_id = match &workspace.location {SerializedWorkspaceLocation::Local => None,SerializedWorkspaceLocation::Remote(connection_options) => {Some(Self::get_or_create_remote_connection_internal(@@ -1693,17 +1693,16 @@ impl WorkspaceDb {&self,options: RemoteConnectionOptions,) -> Result<RemoteConnectionId> {- self.write(move |conn| Self::get_or_create_remote_connection_internal(conn, options))+ self.write(move |conn| Self::get_or_create_remote_connection_internal(conn, &options)).await}fn get_or_create_remote_connection_internal(this: &Connection,- options: RemoteConnectionOptions,+ options: &RemoteConnectionOptions,) -> Result<RemoteConnectionId> {- let identity = remote_connection_identity(&options);let kind;- let user: Option<String>;+ let user: Option<Cow<'_, str>>;let mut host = None;let mut port = None;let mut distro = None;@@ -1712,73 +1711,59 @@ impl WorkspaceDb {let mut use_podman = None;let mut remote_env = None;- match identity {- RemoteConnectionIdentity::Ssh {- host: identity_host,- username,- port: identity_port,- } => {+ match options {+ RemoteConnectionOptions::Ssh(options) => {kind = RemoteConnectionKind::Ssh;- host = Some(identity_host);- port = identity_port;- user = username;+ host = Some(options.host.to_cow());+ port = options.port;+ user = options.username.as_deref().map(Cow::Borrowed);}- RemoteConnectionIdentity::Wsl {- distro_name,- user: identity_user,- } => {+ RemoteConnectionOptions::Wsl(options) => {kind = RemoteConnectionKind::Wsl;- distro = Some(distro_name);- user = identity_user;+ distro = Some(options.distro_name.as_str());+ user = options.user.as_deref().map(Cow::Borrowed);}- RemoteConnectionIdentity::Docker {- container_id: identity_container_id,- name: identity_name,- remote_user,- } => {+ RemoteConnectionOptions::Docker(options) => {kind = RemoteConnectionKind::Docker;- container_id = Some(identity_container_id);- name = Some(identity_name);- user = Some(remote_user);+ container_id = Some(options.container_id.as_str());+ user = Some(Cow::Borrowed(options.remote_user.as_str()));+ name = Some(options.name.as_str());+ use_podman = Some(options.use_podman);+ remote_env = serde_json::to_string(&options.remote_env).ok();}#[cfg(any(test, feature = "test-support"))]- RemoteConnectionIdentity::Mock { id } => {+ RemoteConnectionOptions::Mock(options) => {kind = RemoteConnectionKind::Ssh;- host = Some(format!("mock-{}", id));- user = Some(format!("mock-user-{}", id));+ host = Some(format!("mock-{}", options.id).into());+ user = Some(format!("mock-user-{}", options.id).into());}}- if let RemoteConnectionOptions::Docker(options) = options {- use_podman = Some(options.use_podman);- remote_env = serde_json::to_string(&options.remote_env).ok();- }-Self::get_or_create_remote_connection_query(this,kind,- host,+ host.as_deref(),port,- user,+ user.as_deref(),distro,name,container_id,use_podman,- remote_env,+ remote_env.as_deref(),)}fn get_or_create_remote_connection_query(this: &Connection,kind: RemoteConnectionKind,- host: Option<String>,+ host: Option<&str>,port: Option<u16>,- user: Option<String>,- distro: Option<String>,- name: Option<String>,- container_id: Option<String>,+ user: Option<&str>,+ distro: Option<&str>,+ name: Option<&str>,+ container_id: Option<&str>,use_podman: Option<bool>,- remote_env: Option<String>,+ remote_env: Option<&str>,) -> Result<RemoteConnectionId> {if let Some(id) = this.select_row_bound(sql!(SELECT id@@ -1794,12 +1779,12 @@ impl WorkspaceDb {LIMIT 1))?((kind.serialize(),- host.clone(),+ host,port,- user.clone(),- distro.clone(),- name.clone(),- container_id.clone(),+ user,+ distro,+ name,+ container_id,))? {Ok(RemoteConnectionId(id))} else {@@ -2120,7 +2105,7 @@ impl WorkspaceDb {let target_remote_connection = match &target.location {SerializedWorkspaceLocation::Local => None,SerializedWorkspaceLocation::Remote(connection) => {- Some(remote_connection_identity(connection))+ Some(RemoteConnectionIdentity::from(connection))}};@@ -2134,7 +2119,7 @@ impl WorkspaceDb {let Some(connection_options) = remote_connections.get(&id) else {continue;};- Some(remote_connection_identity(connection_options))+ Some(RemoteConnectionIdentity::from(connection_options))} else {None};@@ -2750,14 +2735,16 @@ async fn resolve_local_workspace_identity(fs: &dyn Fs, paths: &PathList) -> Optifn dedupe_recent_workspaces(workspaces: impl IntoIterator<Item = RecentWorkspace>,) -> Vec<RecentWorkspace> {- let mut indices_by_key: HashMap<(Option<RemoteConnectionIdentity>, Vec<PathBuf>), usize> =- HashMap::default();+ let mut indices_by_key: HashMap<+ (Option<RemoteConnectionIdentity<'static>>, Vec<PathBuf>),+ usize,+ > = HashMap::default();let mut result: Vec<RecentWorkspace> = Vec::new();for workspace in workspaces {let location_identity = match &workspace.location {SerializedWorkspaceLocation::Local => None,SerializedWorkspaceLocation::Remote(connection) => {- Some(remote_connection_identity(connection))+ Some(RemoteConnectionIdentity::from(connection).into_owned())}};let key = (location_identity, workspace.identity_paths.paths().to_vec());diff --git a/crates/workspace/src/persistence/model.rs b/crates/workspace/src/persistence/model.rsindex b56279a8b0c..9483e5a4545 100644--- a/crates/workspace/src/persistence/model.rs+++ b/crates/workspace/src/persistence/model.rs@@ -78,7 +78,7 @@ impl SerializedProjectGroup {pub fn from_group(key: &ProjectGroupKey, expanded: bool) -> Self {Self {path_list: key.path_list().serialize(),- location: match key.host() {+ location: match key.host().cloned() {Some(host) => SerializedWorkspaceLocation::Remote(host),None => SerializedWorkspaceLocation::Local,},diff --git a/crates/workspace/src/workspace.rs b/crates/workspace/src/workspace.rsindex 6ad714e32ab..15d03480089 100644--- a/crates/workspace/src/workspace.rs+++ b/crates/workspace/src/workspace.rs@@ -38,9 +38,7 @@ pub use multi_workspace::{SidebarRenderState, SidebarSide, ToggleWorkspaceSidebar, sidebar_side_context_menu,};pub use path_list::{PathList, SerializedPathList};-pub use remote::{- RemoteConnectionIdentity, remote_connection_identity, same_remote_connection_identity,-};+pub use remote::RemoteConnectionIdentity;pub use toast_layer::{ToastAction, ToastLayer, ToastView};use agent_settings::AgentSettings;@@ -98,7 +96,7 @@ pub use persistence::{use persistence::{SerializedWindowBounds, model::SerializedWorkspace};use postage::stream::Stream;use project::{- DirectoryLister, PathChange, Project, ProjectEntryId, ProjectPath, ResolvedPath,+ DirectoryLister, PathChange, Project, ProjectEntryId, ProjectHost, ProjectPath, ResolvedPath,UpdatedEntriesSet, Worktree, WorktreeId, WorktreeSettings,debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},git_store::{GitStoreEvent, RepositoryEvent},@@ -893,11 +891,10 @@ fn prompt_and_open_paths(create_new_window: bool,cx: &mut App,) {- if let Some(workspace_window) =- workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)- .into_iter()- .next()- {+ let workspace_window =+ workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx).next();++ if let Some(workspace_window) = workspace_window {workspace_window.update(cx, |multi_workspace, window, cx| {let workspace = multi_workspace.workspace().clone();@@ -7013,10 +7010,8 @@ impl Workspace {} else {None};- let remote_name = remote_options- .as_ref()- .map(RemoteConnectionOptions::display_name);- let remote_host = remote_options.as_ref().map(RemoteConnectionOptions::host);+ let remote_name = remote_options.map(|o| o.display_name());+ let remote_host = remote_options.map(|o| o.host());let branch = if needs.branch {project@@ -8003,7 +7998,7 @@ impl Workspace {fn workspace_location(&self, cx: &App) -> WorkspaceLocation {let paths = PathList::new(&self.root_paths(cx));- if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {+ if let Some(connection) = self.project.read(cx).remote_connection_options(cx).cloned() {WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)} else if self.project.read(cx).is_local() {WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)@@ -10591,7 +10586,8 @@ pub async fn apply_restored_multiworkspace_state(resolved_paths.push(path.to_path_buf());}}- let resolved = ProjectGroupKey::new(key.host(), PathList::new(&resolved_paths));+ let resolved =+ ProjectGroupKey::new(key.host().cloned(), PathList::new(&resolved_paths));if !resolved_groups.iter().any(|g| g.key == resolved) {resolved_groups.push(SerializedProjectGroupState {key: resolved,@@ -11033,89 +11029,158 @@ pub fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<M})}-fn workspace_is_at_location(- workspace: &Entity<Workspace>,- location: &SerializedWorkspaceLocation,- cx: &App,-) -> bool {- let WorkspaceLocation::Location(workspace_location, _) =- workspace.read(cx).workspace_location(cx)- else {- return false;- };+pub struct WorkspaceOpenTarget {+ pub window: WindowHandle<MultiWorkspace>,+ pub workspace: Entity<Workspace>,+ pub visible: OpenVisible,+}- match (&workspace_location, location) {- (SerializedWorkspaceLocation::Local, SerializedWorkspaceLocation::Local) => true,+fn matches_remote_location(+ connection: &RemoteConnectionOptions,+ requested: &RemoteConnectionOptions,+) -> bool {+ match (connection, requested) {+ (RemoteConnectionOptions::Ssh(_), RemoteConnectionOptions::Ssh(_)) => {+ connection.identity() == requested.identity()+ }+ (RemoteConnectionOptions::Wsl(connection), RemoteConnectionOptions::Wsl(requested)) => {+ // The WSL username is not consistently populated in the workspace location, so ignore it for now.+ connection.distro_name == requested.distro_name+ }(- SerializedWorkspaceLocation::Remote(workspace_remote),- SerializedWorkspaceLocation::Remote(remote),- ) => match (workspace_remote, remote) {- (RemoteConnectionOptions::Ssh(_), RemoteConnectionOptions::Ssh(_)) => {- same_remote_connection_identity(Some(workspace_remote), Some(remote))+ RemoteConnectionOptions::Docker(connection),+ RemoteConnectionOptions::Docker(requested),+ ) => connection.container_id == requested.container_id,+ #[cfg(any(test, feature = "test-support"))]+ (RemoteConnectionOptions::Mock(connection), RemoteConnectionOptions::Mock(requested)) => {+ connection.id == requested.id+ }+ _ => false,+ }+}++fn matches_requested_host(project: &Project, requested: &ProjectHost<'_>, cx: &App) -> bool {+ match requested {+ ProjectHost::Local => project.is_local(),+ ProjectHost::Remote(requested) => {+ let Some(connection) = project.remote_connection_options(cx) else {+ return false;+ };++ if !matches_remote_location(connection, requested) {+ return false;}- (- RemoteConnectionOptions::Wsl(workspace_remote),- RemoteConnectionOptions::Wsl(remote),- ) => {- // The WSL username is not consistently populated in the workspace location, so ignore it for now.- workspace_remote.distro_name == remote.distro_name++ match (connection, *requested) {+ (+ RemoteConnectionOptions::Ssh(options),+ RemoteConnectionOptions::Ssh(requested_options),+ ) => {+ // SSH arguments can override the host and user.+ // Normalize the args to make None == Some(vec![]) for comparison.+ options.args.as_deref().unwrap_or_default()+ == requested_options.args.as_deref().unwrap_or_default()+ }+ (+ RemoteConnectionOptions::Docker(options),+ RemoteConnectionOptions::Docker(requested_options),+ ) => options.remote_user == requested_options.remote_user,+ _ => true,}- (- RemoteConnectionOptions::Docker(workspace_remote),- RemoteConnectionOptions::Docker(remote),- ) => workspace_remote.container_id == remote.container_id,- #[cfg(any(test, feature = "test-support"))]- (- RemoteConnectionOptions::Mock(workspace_remote),- RemoteConnectionOptions::Mock(remote),- ) => workspace_remote.id == remote.id,- _ => false,- },- _ => false,+ }}}-pub fn workspace_windows_for_location(- serialized_location: &SerializedWorkspaceLocation,- cx: &App,-) -> Vec<WindowHandle<MultiWorkspace>> {+pub fn workspace_windows_for_location<'a>(+ serialized_location: &'a SerializedWorkspaceLocation,+ cx: &'a App,+) -> impl Iterator<Item = WindowHandle<MultiWorkspace>> + 'a {cx.windows().into_iter().filter_map(|window| window.downcast::<MultiWorkspace>())- .filter(|multi_workspace| {+ .filter(move |multi_workspace| {multi_workspace.read(cx).is_ok_and(|multi_workspace| {- multi_workspace- .workspaces()- .any(|workspace| workspace_is_at_location(workspace, serialized_location, cx))+ multi_workspace.workspaces().any(|workspace| {+ let project = workspace.read(cx).project.read(cx);++ match (project.remote_connection_options(cx), serialized_location) {+ (Some(connection), SerializedWorkspaceLocation::Remote(requested)) => {+ matches_remote_location(connection, requested)+ }+ (None, SerializedWorkspaceLocation::Local) => project.is_local(),+ _ => false,+ }+ })})})- .collect()}-pub async fn find_existing_workspace(+fn preferred_target_for_files(host: &ProjectHost<'_>, cx: &App) -> Option<WorkspaceOpenTarget> {+ let target_for_window = |window: WindowHandle<MultiWorkspace>| {+ let multi_workspace = window.read(cx).ok()?;+ let active_workspace = multi_workspace.workspace();+ let matches_host = |workspace: &Entity<Workspace>| {+ matches_requested_host(workspace.read(cx).project.read(cx), host, cx)+ };++ let workspace = if matches_host(active_workspace) {+ active_workspace+ } else {+ multi_workspace+ .workspaces()+ .find(|workspace| *workspace != active_workspace && matches_host(workspace))?+ };++ Some(WorkspaceOpenTarget {+ window,+ workspace: workspace.clone(),+ visible: OpenVisible::None,+ })+ };++ let active_window = cx+ .active_window()+ .and_then(|window| window.downcast::<MultiWorkspace>());++ if let Some(window) = active_window+ && let Some(target) = target_for_window(window)+ {+ Some(target)+ } else {+ cx.windows()+ .into_iter()+ .filter_map(|window| window.downcast::<MultiWorkspace>())+ .filter(|window| Some(*window) != active_window)+ .find_map(target_for_window)+ }+}++pub fn find_existing_workspace(abs_paths: &[PathBuf],open_options: &OpenOptions,- location: &SerializedWorkspaceLocation,+ host: &ProjectHost<'_>,cx: &mut AsyncApp,-) -> (- Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,- OpenVisible,-) {- let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;- let mut open_visible = OpenVisible::All;- let mut best_match = None;+) -> Option<WorkspaceOpenTarget> {+ cx.update(|cx| {+ let mut existing = None;+ let mut best_match = None;- if open_options.workspace_matching != WorkspaceMatching::None {- cx.update(|cx| {- for window in workspace_windows_for_location(location, cx) {+ if open_options.workspace_matching != WorkspaceMatching::None {+ for window in cx+ .windows()+ .into_iter()+ .filter_map(|window| window.downcast::<MultiWorkspace>())+ {if let Ok(multi_workspace) = window.read(cx) {for workspace in multi_workspace.workspaces() {- if !workspace_is_at_location(workspace, location, cx) {+ let workspace_ref = workspace.read(cx);+ let project = workspace_ref.project.read(cx);++ if !matches_requested_host(project, host, cx) {continue;}- let project = workspace.read(cx).project.read(cx);- let m = match open_options.workspace_matching {+ let visibility = match open_options.workspace_matching {WorkspaceMatching::None => None,WorkspaceMatching::MatchExact => {project.visibility_for_paths(abs_paths, true, cx)@@ -11127,63 +11192,60 @@ pub async fn find_existing_workspace(project.visibility_for_paths(abs_paths, false, cx)}};- if m > best_match {- existing = Some((window, workspace.clone()));- best_match = m;++ if visibility > best_match {+ existing = Some(WorkspaceOpenTarget {+ window,+ workspace: workspace.clone(),+ visible: OpenVisible::All,+ });+ best_match = visibility;} else if best_match.is_none()&& open_options.workspace_matching== WorkspaceMatching::MatchSubdirectory{- existing = Some((window, workspace.clone()))+ existing = Some(WorkspaceOpenTarget {+ window,+ workspace: workspace.clone(),+ visible: OpenVisible::All,+ });}}}}- });- let all_paths_are_files = existing- .as_ref()- .and_then(|(_, target_workspace)| {- cx.update(|cx| {- let workspace = target_workspace.read(cx);- let project = workspace.project.read(cx);- let path_style = workspace.path_style(cx);- Some(!abs_paths.iter().any(|path| {- let path = util::paths::SanitizedPath::new(path);- project.worktrees(cx).any(|worktree| {+ let all_paths_are_files = existing.as_ref().is_some_and(|target| {+ let workspace = target.workspace.read(cx);+ let project = workspace.project.read(cx);+ let path_style = workspace.path_style(cx);++ !abs_paths.iter().any(|path| {+ let path = util::paths::SanitizedPath::new(path);++ project+ .worktrees(cx)+ .filter_map(|worktree| {let worktree = worktree.read(cx);let abs_path = worktree.abs_path();- path_style++ let relative_path = path_style.strip_prefix(path.as_ref(), abs_path.as_ref())- .ok()- .and_then(|path| RelPath::new(path, path_style).ok())- .and_then(|rel| worktree.entry_for_path(&rel))- .is_some_and(|e| e.is_dir())+ .ok()?;+ let relative_path = RelPath::new(relative_path, path_style).ok()?;++ worktree.entry_for_path(&relative_path)})- }))+ .any(|entry| entry.is_dir())})- })- .unwrap_or(false);-- if open_options.wait && existing.is_some() && all_paths_are_files {- cx.update(|cx| {- let windows = workspace_windows_for_location(location, cx);- let window = cx- .active_window()- .and_then(|window| window.downcast::<MultiWorkspace>())- .filter(|window| windows.contains(window))- .or_else(|| windows.into_iter().next());- if let Some(window) = window {- if let Ok(multi_workspace) = window.read(cx) {- let active_workspace = multi_workspace.workspace().clone();- existing = Some((window, active_workspace));- open_visible = OpenVisible::None;- }- }});++ if open_options.wait && existing.is_some() && all_paths_are_files {+ existing = preferred_target_for_files(host, cx).or(existing);+ }}- }- (existing, open_visible)++ existing+ })}/// Controls whether to reuse an existing workspace whose worktrees contain the@@ -11374,7 +11436,7 @@ pub fn open_workspace_by_id(pub fn open_paths(abs_paths: &[PathBuf],app_state: Arc<AppState>,- mut open_options: OpenOptions,+ open_options: OpenOptions,cx: &mut App,) -> Task<anyhow::Result<OpenResult>> {let abs_paths = abs_paths.to_vec();@@ -11384,17 +11446,14 @@ pub fn open_paths(.find_map(|p| util::paths::WslPath::from_path(p));cx.spawn(async move |cx| {- let (mut existing, mut open_visible) = find_existing_workspace(- &abs_paths,- &open_options,- &SerializedWorkspaceLocation::Local,- cx,- )- .await;+ let mut reuse_target =+ find_existing_workspace(&abs_paths, &open_options, &ProjectHost::Local, cx);++ let mut creation_window = open_options.requesting_window;// Fallback: if no workspace contains the paths and all paths are files,// prefer an existing local workspace window (active window first).- if open_options.should_reuse_existing_window() && existing.is_none() {+ if open_options.should_reuse_existing_window() && reuse_target.is_none() {let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));let all_metadatas = futures::future::join_all(all_paths).await@@ -11402,24 +11461,9 @@ pub fn open_paths(.filter_map(|result| result.ok().flatten());if all_metadatas.into_iter().all(|file| !file.is_dir) {- cx.update(|cx| {- let windows = workspace_windows_for_location(- &SerializedWorkspaceLocation::Local,- cx,- );- let window = cx- .active_window()- .and_then(|window| window.downcast::<MultiWorkspace>())- .filter(|window| windows.contains(window))- .or_else(|| windows.into_iter().next());- if let Some(window) = window {- if let Ok(multi_workspace) = window.read(cx) {- let active_workspace = multi_workspace.workspace().clone();- existing = Some((window, active_workspace));- open_visible = OpenVisible::None;- }- }- });+ reuse_target = cx+ .update(|cx| preferred_target_for_files(&ProjectHost::Local, cx))+ .or(reuse_target);}}@@ -11431,31 +11475,27 @@ pub fn open_paths(// open_workspace_for_paths reusing an empty window) already chose the// target window, so we must not open the sidebar as a side-effect.if open_options.should_reuse_existing_window()- && existing.is_none()- && open_options.requesting_window.is_none()+ && reuse_target.is_none()+ && creation_window.is_none(){let use_existing_window = open_options.add_dirs_to_sidebar;if use_existing_window {- let target_window = cx.update(|cx| {- let windows = workspace_windows_for_location(- &SerializedWorkspaceLocation::Local,- cx,- );- let window = cx+ creation_window = cx.update(|cx| {+ let active_window = cx.active_window()- .and_then(|window| window.downcast::<MultiWorkspace>())- .filter(|window| windows.contains(window))- .or_else(|| windows.into_iter().next());- window.filter(|window| {- window- .read(cx)- .is_ok_and(|mw| mw.multi_workspace_enabled(cx))- })+ .and_then(|window| window.downcast::<MultiWorkspace>());++ workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)+ .min_by_key(|window| Some(*window) != active_window)+ .filter(|window| {+ window+ .read(cx)+ .is_ok_and(|mw| mw.multi_workspace_enabled(cx))+ })});- if let Some(window) = target_window {- open_options.requesting_window = Some(window);+ if let Some(window) = creation_window {window.update(cx, |multi_workspace, _, cx| {if AgentSettings::get_global(cx).threads_sidebar.auto_open {@@ -11474,8 +11514,12 @@ pub fn open_paths(let open_in_dev_container = open_options.open_in_dev_container;- let result = if let Some((existing, target_workspace)) = existing {- let open_task = existing+ let result = if let Some(WorkspaceOpenTarget {+ window: target_window,+ workspace: target_workspace,+ visible: open_visible,+ }) = reuse_target {+ let open_task = target_window.update(cx, |multi_workspace, window, cx| {window.activate_window();multi_workspace.activate(target_workspace.clone(), None, window, cx);@@ -11497,7 +11541,7 @@ pub fn open_paths(})?.await;- _ = existing.update(cx, |multi_workspace, _, cx| {+ _ = target_window.update(cx, |multi_workspace, _, cx| {let workspace = multi_workspace.workspace().clone();workspace.update(cx, |workspace, cx| {for item in open_task.iter().flatten() {@@ -11508,7 +11552,7 @@ pub fn open_paths(});});- Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })+ Ok(OpenResult { window: target_window, workspace: target_workspace, opened_items: open_task })} else {let init = if open_in_dev_container {Some(Box::new(|workspace: &mut Workspace, _window: &mut Window, _cx: &mut Context<Workspace>| {@@ -11522,7 +11566,7 @@ pub fn open_paths(Workspace::new_local(abs_paths,app_state.clone(),- open_options.requesting_window,+ creation_window,open_options.env,init,open_options.open_mode,diff --git a/crates/zed/src/zed.rs b/crates/zed/src/zed.rsindex 18a70751c19..edeb5d31059 100644--- a/crates/zed/src/zed.rs+++ b/crates/zed/src/zed.rs@@ -2446,7 +2446,7 @@ pub fn open_new_ssh_project_from_project(let Some(ssh_client) = workspace.project().read(cx).remote_client() else {return Task::ready(Err(anyhow::anyhow!("Not an ssh project")));};- let connection_options = ssh_client.read(cx).connection_options();+ let connection_options = ssh_client.read(cx).connection_options().clone();let requesting_window = if create_new_window {None} else {diff --git a/crates/zed/src/zed/open_listener.rs b/crates/zed/src/zed/open_listener.rsindex 0675fddb753..177e9538453 100644--- a/crates/zed/src/zed/open_listener.rs+++ b/crates/zed/src/zed/open_listener.rs@@ -800,9 +800,7 @@ pub(crate) fn open_options_for_behavior(// If reuse flag is passed, open a new workspace in an existing window.let requesting_window = if open_behavior == cli::OpenBehavior::Reuse {- workspace::workspace_windows_for_location(location, cx)- .into_iter()- .next()+ workspace::workspace_windows_for_location(location, cx).next()} else {None};@@ -2044,13 +2042,11 @@ mod tests {let window_to_replace = workspace::find_existing_workspace(&paths,&workspace::OpenOptions::default(),- &workspace::SerializedWorkspaceLocation::Local,+ &project::ProjectHost::Local,&mut cx.to_async(),)- .await- .0.unwrap()- .0;+ .window;let errored_reuse = cx.spawn({