From 035a21520cdb1b3357f2328209163d3ba01a8531 Mon Sep 17 00:00:00 2001 From: Kirill Bulatov Date: Wed, 18 Nov 2026 21:53:23 +0200 Subject: [PATCH] sidebar: Show Delta checkouts as worktrees of their source project MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A Delta checkout is now a worktree of its source project in the agents sidebar, instead of a project of its own with the same name. - Thread rows and the project menus label a checkout after its Delta namespace. - Saved threads and terminals of an open checkout follow it into the source project, and a header of the old per-checkout project is removed once nothing is listed under it. - A project keeps its header while closed threads of another checkout are listed under it, for example after "Add Folder to Project" in one checkout. - "Create New Worktree…" names the repository it creates in when the open checkouts of a project are different repositories, and the default branch is cached per repository. --- crates/sidebar/src/sidebar.rs | 598 ++++++-- crates/sidebar/src/sidebar_tests.rs | 1276 ++++++++++++++++- crates/workspace/src/multi_workspace.rs | 113 +- crates/workspace/src/multi_workspace_tests.rs | 2 + 4 files changed, 1854 insertions(+), 135 deletions(-) diff --git a/crates/sidebar/src/sidebar.rs b/crates/sidebar/src/sidebar.rs index a6f6af5fe64..d561b446211 100644 --- a/crates/sidebar/src/sidebar.rs +++ b/crates/sidebar/src/sidebar.rs @@ -63,6 +63,7 @@ use ui::{ use unicode_segmentation::UnicodeSegmentation as _; use util::ResultExt as _; use util::path_list::PathList; +use util::paths::{PathExt as _, PathStyle}; use workspace::{ CloseWindow, FocusWorkspaceSidebar, MoveProjectDown, MoveProjectUp, MultiWorkspace, MultiWorkspaceEvent, NextProject, NextThread, Open, OpenMode, PreviousProject, PreviousThread, @@ -634,6 +635,13 @@ struct WorkspaceMenuWorktreeLabel { } impl WorkspaceMenuWorktreeLabel { + fn text(&self) -> String { + match &self.secondary_name { + Some(secondary_name) => format!("{}/{secondary_name}", self.primary_name), + None => self.primary_name.to_string(), + } + } + fn render(&self) -> impl IntoElement { h_flex() .min_w_0() @@ -649,14 +657,207 @@ impl WorkspaceMenuWorktreeLabel { } } +fn legacy_delta_main_paths(worktree_paths: &WorktreePaths) -> Option { + let legacy_main_path = |main_path: &PathBuf, folder_path: &PathBuf| { + let clone = worktree_paths.delta_clone(folder_path)?; + let legacy_main_path = + project::repo_identity_path(&clone.path, util::paths::PathStyle::local()); + (legacy_main_path != main_path.as_path()).then(|| legacy_main_path.to_path_buf()) + }; + worktree_paths + .ordered_pairs() + .any(|(main_path, folder_path)| legacy_main_path(main_path, folder_path).is_some()) + .then(|| { + PathList::new( + &worktree_paths + .ordered_pairs() + .map(|(main_path, folder_path)| { + legacy_main_path(main_path, folder_path) + .unwrap_or_else(|| main_path.clone()) + }) + .collect::>(), + ) + }) +} + +fn regroup_unused_legacy_delta_project_groups( + multi_workspace: &Entity, + cx: &mut App, +) { + let thread_store = ThreadMetadataStore::global(cx); + let terminal_store = TerminalThreadMetadataStore::global(cx); + if !thread_store.read(cx).is_loaded() || !terminal_store.read(cx).is_loaded() { + return; + } + let regrouped = { + let multi_workspace = multi_workspace.read(cx); + let thread_store = thread_store.read(cx); + let terminal_store = terminal_store.read(cx); + let mut group_paths_by_legacy_paths = HashMap::>::default(); + let saved_paths = thread_store + .entries() + .filter(|thread| thread.remote_connection.is_none() && !thread.archived) + .map(|thread| &thread.worktree_paths) + .chain( + terminal_store + .entries() + .filter(|terminal| terminal.remote_connection.is_none()) + .map(|terminal| &terminal.worktree_paths), + ) + .filter_map(|worktree_paths| { + Some(( + legacy_delta_main_paths(worktree_paths)?, + worktree_paths.main_worktree_path_list().clone(), + )) + }); + let open_paths = multi_workspace + .workspaces() + .filter(|workspace| workspace.read(cx).project().read(cx).is_local()) + .map(|workspace| { + ( + git_project_group_key(workspace, cx).path_list().clone(), + workspace.read(cx).project_group_key(cx).path_list().clone(), + ) + }) + .filter(|(git_paths, group_paths)| git_paths != group_paths); + for (legacy_paths, group_paths) in saved_paths.chain(open_paths) { + let group_paths_for_legacy_paths = + group_paths_by_legacy_paths.entry(legacy_paths).or_default(); + if !group_paths_for_legacy_paths.contains(&group_paths) { + group_paths_for_legacy_paths.push(group_paths); + } + } + multi_workspace + .project_group_keys() + .into_iter() + .filter(|key| key.host().is_none()) + .filter_map(|key| { + let group_paths = group_paths_by_legacy_paths.get(key.path_list())?; + let is_used = multi_workspace + .workspaces_for_project_group(&key, cx) + .next() + .is_some() + || thread_store + .entries_for_main_worktree_path(key.path_list(), None) + .next() + .is_some() + || terminal_store + .entries_for_main_worktree_path(key.path_list(), None) + .next() + .is_some(); + let mut group_keys = group_paths + .iter() + .map(|group_paths| ProjectGroupKey::new(None, group_paths.clone())) + .collect::>(); + group_keys.sort_by(|a, b| a.path_list().paths().cmp(b.path_list().paths())); + (!is_used).then_some((key, group_keys)) + }) + .collect::>() + }; + if regrouped.is_empty() { + return; + } + multi_workspace.update(cx, |multi_workspace, cx| { + for (legacy_key, group_keys) in regrouped { + multi_workspace.replace_project_group(&legacy_key, group_keys, cx); + } + }); +} + +fn git_project_group_key(workspace: &Entity, cx: &App) -> ProjectGroupKey { + let project = workspace.read(cx).project().read(cx); + ProjectGroupKey::from_worktree_paths( + &project.git_worktree_paths(cx), + project.remote_connection_options(cx).cloned(), + ) +} + +fn worktree_creation_base_workspaces( + project_group_key: &ProjectGroupKey, + active_workspace: Option<&Entity>, + open_workspaces: &[Entity], + cx: &App, +) -> Vec<(Entity, bool)> { + let mut git_project_group_keys = Vec::new(); + let mut base_workspaces = Vec::new(); + if let Some(active_workspace) = + active_workspace.filter(|workspace| open_workspaces.contains(workspace)) + { + git_project_group_keys.push(git_project_group_key(active_workspace, cx)); + base_workspaces.push(active_workspace.clone()); + } else { + for workspace in open_workspaces { + let git_project_group_key = git_project_group_key(workspace, cx); + if !git_project_group_keys.contains(&git_project_group_key) { + git_project_group_keys.push(git_project_group_key); + base_workspaces.push(workspace.clone()); + } + } + } + let names_every_base_workspace = base_workspaces.len() > 1; + base_workspaces + .into_iter() + .zip(git_project_group_keys) + .map(|(base_workspace, git_project_group_key)| { + let is_named = + names_every_base_workspace || git_project_group_key != *project_group_key; + (base_workspace, is_named) + }) + .collect() +} + fn workspace_menu_worktree_labels( workspace: &Entity, cx: &App, ) -> Vec { + worktree_menu_labels(root_worktree_names(workspace, cx)) +} + +fn worktree_menu_labels( + root_worktree_names: Vec, +) -> Vec { + let show_folder_name = root_worktree_names.len() > 1; + root_worktree_names + .into_iter() + .map(|root| match root.worktree_name { + Some(worktree_name) if show_folder_name || root.in_checkout_subfolder => { + WorkspaceMenuWorktreeLabel { + icon: Some(IconName::GitWorktree), + primary_name: root.folder_name, + secondary_name: Some(worktree_name), + } + } + Some(worktree_name) => WorkspaceMenuWorktreeLabel { + icon: Some(IconName::GitWorktree), + primary_name: worktree_name, + secondary_name: None, + }, + None => WorkspaceMenuWorktreeLabel { + icon: None, + primary_name: root.folder_name, + secondary_name: None, + }, + }) + .collect() +} + +struct RootWorktreeName { + folder_name: SharedString, + worktree_name: Option, + in_checkout_subfolder: bool, +} + +struct RootCheckout { + path: PathBuf, + common_dir: PathBuf, + is_linked_worktree: bool, + is_delta_checkout: bool, +} + +fn root_worktree_names(workspace: &Entity, cx: &App) -> Vec { let root_paths = workspace.read(cx).root_paths(cx); - let show_folder_name = root_paths.len() > 1; let project = workspace.read(cx).project().clone(); - let (path_style, repository_snapshots) = { + let (path_style, repository_snapshots, worktree_paths, git_worktree_paths) = { let project = project.read(cx); let path_style = project.path_style(cx); let repository_snapshots = project @@ -664,57 +865,98 @@ fn workspace_menu_worktree_labels( .values() .map(|repo| repo.read(cx).snapshot()) .collect::>(); - (path_style, repository_snapshots) + ( + path_style, + repository_snapshots, + project.worktree_paths(cx), + project.git_worktree_paths(cx), + ) }; root_paths .into_iter() .map(|root_path| { - let root_path = root_path.as_ref(); - let folder_name = path_style - .file_name(root_path) - .map(|name| SharedString::from(name.to_string_lossy().into_owned())) - .unwrap_or_default(); - let repository_snapshot = repository_snapshots + let is_delta_checkout = worktree_paths + .ordered_pairs() + .zip(git_worktree_paths.ordered_pairs()) + .any(|((main_path, folder_path), (git_main_path, _))| { + folder_path.as_path() == root_path.as_ref() && main_path != git_main_path + }); + let checkout = repository_snapshots .iter() - .find(|snapshot| snapshot.work_directory_abs_path.as_ref() == root_path); - - if let Some(snapshot) = repository_snapshot { - let worktree_name = if snapshot.is_linked_worktree() { - project::linked_worktree_short_name( - snapshot.linked_worktree_anchor_path(), - root_path, - snapshot.path_style, - ) - .unwrap_or_else(|| folder_name.clone()) - } else { - "main".into() - }; - - if show_folder_name { - WorkspaceMenuWorktreeLabel { - icon: Some(IconName::GitWorktree), - primary_name: folder_name, - secondary_name: Some(worktree_name), - } - } else { - WorkspaceMenuWorktreeLabel { - icon: Some(IconName::GitWorktree), - primary_name: worktree_name, - secondary_name: None, - } - } - } else { - WorkspaceMenuWorktreeLabel { - icon: None, - primary_name: folder_name, - secondary_name: None, - } - } + .filter(|snapshot| { + path_style.starts_with(&root_path, &snapshot.work_directory_abs_path) + }) + .max_by_key(|snapshot| snapshot.work_directory_abs_path.as_os_str().len()) + .map(|snapshot| RootCheckout { + path: snapshot.work_directory_abs_path.to_path_buf(), + common_dir: snapshot.common_dir_abs_path.to_path_buf(), + is_linked_worktree: snapshot.is_linked_worktree(), + is_delta_checkout, + }); + root_worktree_name(&root_path, checkout.as_ref(), path_style) }) .collect() } +fn root_worktree_name( + root_path: &Path, + checkout: Option<&RootCheckout>, + path_style: PathStyle, +) -> RootWorktreeName { + let folder_name = path_style + .file_name(root_path) + .map(|name| SharedString::from(name.to_string_lossy().into_owned())) + .unwrap_or_default(); + let Some(checkout) = + checkout.filter(|checkout| checkout.path == root_path || checkout.is_delta_checkout) + else { + return RootWorktreeName { + folder_name, + worktree_name: None, + in_checkout_subfolder: false, + }; + }; + let checkout_name = path_style + .file_name(&checkout.path) + .map(|name| SharedString::from(name.to_string_lossy().into_owned())) + .unwrap_or_else(|| folder_name.clone()); + let worktree_name = if checkout.is_delta_checkout { + project::delta_checkout_short_name( + &project::DeltaClone { + path: checkout.common_dir.clone(), + is_linked_worktree: checkout.is_linked_worktree, + checkout_path: Some(checkout.path.clone()), + }, + &checkout.path, + path_style, + ) + .unwrap_or(checkout_name) + } else if checkout.is_linked_worktree { + project::linked_worktree_short_name( + project::repo_identity_path(&checkout.common_dir, path_style), + &checkout.path, + path_style, + ) + .unwrap_or(checkout_name) + } else { + "main".into() + }; + RootWorktreeName { + in_checkout_subfolder: checkout.path != root_path, + folder_name, + worktree_name: Some(worktree_name), + } +} + +fn root_paths_tooltip(root_paths: impl IntoIterator>) -> SharedString { + root_paths + .into_iter() + .map(|root_path| root_path.as_ref().compact().to_string_lossy().into_owned()) + .join("\n") + .into() +} + fn defer_menu_dismissal(menu: &WeakEntity, window: &mut Window, cx: &mut App) { let menu = menu.clone(); window.defer(cx, move |_, cx| { @@ -1123,8 +1365,15 @@ impl Sidebar { !old_paths .ordered_pairs() .any(|(old_main, old_folder)| old_main == *main && old_folder == *folder) + || old_paths.delta_clone(folder) != new_paths.delta_clone(folder) + }) + .map(|(main, folder)| { + ( + main.clone(), + folder.clone(), + new_paths.delta_clone(folder).cloned(), + ) }) - .map(|(m, f)| (m.clone(), f.clone())) .collect(); let new_folder_paths = new_paths.folder_path_list(); @@ -1141,8 +1390,9 @@ impl Sidebar { 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 { + for (main_path, folder_path, clone) in &added_pairs { paths.add_path(main_path, folder_path); + paths.set_delta_clone(folder_path, clone.clone()); } for path in &removed_folder_paths { paths.remove_folder_path(path); @@ -1166,6 +1416,24 @@ impl Sidebar { }); } + fn move_saved_entries_of_open_checkouts( + &mut self, + multi_workspace: &Entity, + cx: &mut Context, + ) { + let projects = multi_workspace + .read(cx) + .workspaces() + .map(|workspace| workspace.read(cx).project().clone()) + .collect::>(); + for project in projects { + let git_worktree_paths = project.read(cx).git_worktree_paths(cx); + if git_worktree_paths != project.read(cx).worktree_paths(cx) { + self.move_entry_paths(&project, &git_worktree_paths, cx); + } + } + } + fn subscribe_to_agent_panel( &mut self, workspace: &Entity, @@ -2077,6 +2345,9 @@ impl Sidebar { return; } + self.move_saved_entries_of_open_checkouts(&multi_workspace, cx); + regroup_unused_legacy_delta_project_groups(&multi_workspace, cx); + let had_notifications = self.has_notifications(cx); let previous_shapes: Vec = self.entry_shapes(multi_workspace.read(cx)).collect(); @@ -2675,29 +2946,38 @@ impl Sidebar { move |mut menu, _window, cx| { menu = menu.header("New Thread In…"); - for (workspace, labels) in open_workspaces + for (workspace_index, (workspace, labels)) in open_workspaces .iter() .cloned() .zip(workspace_labels.iter().cloned()) + .enumerate() { let is_active_workspace = active_workspace.as_ref() == Some(&workspace); + let tooltip = root_paths_tooltip(&workspace.read(cx).root_paths(cx)); menu = menu.custom_entry( move |_window, _cx| { h_flex() .w_full() .gap_2() .justify_between() - .child(h_flex().min_w_0().gap_1().children( - labels.iter().enumerate().map(|(label_ix, label)| { - h_flex() - .gap_1() - .when(label_ix > 0, |this| { - this.child(Label::new("•").alpha(0.25)) - }) - .child(label.render()) - .into_any_element() - }), - )) + .child( + h_flex() + .id(("new-thread-worktree", workspace_index)) + .min_w_0() + .gap_1() + .children(labels.iter().enumerate().map( + |(label_ix, label)| { + h_flex() + .gap_1() + .when(label_ix > 0, |this| { + this.child(Label::new("•").alpha(0.25)) + }) + .child(label.render()) + .into_any_element() + }, + )) + .tooltip(Tooltip::text(tooltip.clone())), + ) .when(is_active_workspace, |this| { this.child( Icon::new(IconName::Check) @@ -2722,23 +3002,44 @@ impl Sidebar { ); } - let base_workspace = active_workspace - .as_ref() - .filter(|workspace| open_workspaces.contains(workspace)) - .cloned() - .or_else(|| open_workspaces.first().cloned()); - - // Only offer worktree creation when the base project can - // actually create one; otherwise the submenu would expand to - // nothing. Mirrors the picker's `creation_blocked_reason`. - let creation_blocked = base_workspace.as_ref().is_none_or(|base_workspace| { - let project = base_workspace.read(cx).project().read(cx); - project.is_via_collab() || project.repositories(cx).is_empty() - }); - - if let Some(base_workspace) = base_workspace.filter(|_| !creation_blocked) { - menu = menu.separator().submenu("Create New Worktree…", { - let this = this.clone(); + let base_workspaces = worktree_creation_base_workspaces( + &key, + active_workspace.as_ref(), + &open_workspaces, + cx, + ); + let mut has_creation_submenu = false; + for (base_workspace, is_named) in base_workspaces { + // Only offer worktree creation when the base project can + // actually create one; otherwise the submenu would expand to + // nothing. Mirrors the picker's `creation_blocked_reason`. + let creation_blocked = { + let project = base_workspace.read(cx).project().read(cx); + project.is_via_collab() || project.repositories(cx).is_empty() + }; + if creation_blocked { + continue; + } + let submenu_label = open_workspaces + .iter() + .position(|workspace| *workspace == base_workspace) + .and_then(|workspace_index| workspace_labels.get(workspace_index)) + .filter(|_| is_named) + .map_or_else( + || "Create New Worktree…".to_string(), + |labels| { + format!( + "Create New Worktree in {}…", + labels.iter().map(|label| label.text()).join(" • ") + ) + }, + ); + if !has_creation_submenu { + menu = menu.separator(); + has_creation_submenu = true; + } + let this = this.clone(); + menu = menu.submenu(submenu_label, { move |mut submenu, _window, submenu_cx| { let project = base_workspace.read(submenu_cx).project().clone(); let project_ref = project.read(submenu_cx); @@ -2752,13 +3053,8 @@ impl Sidebar { .map(|branch| branch.name().to_string()) }); let default_branch = this - .read_with(submenu_cx, |sidebar, _| { - match sidebar.worktree_default_branches.get(&key) { - Some(DefaultBranchCache::Resolved(branch)) => { - branch.clone() - } - _ => None, - } + .read_with(submenu_cx, |sidebar, cx| { + sidebar.worktree_default_branch(&base_workspace, cx) }) .ok() .flatten(); @@ -2805,36 +3101,36 @@ impl Sidebar { .into_any_element() } - // Warms `worktree_default_branches` for every project group with at least one - // open workspace. The git query runs off the menu path so the submenu can read - // the result synchronously when it opens. Worktrees of a repository share the - // same default branch, so any workspace in the group yields the same answer. fn prefetch_worktree_default_branches(&mut self, cx: &mut Context) { let Some(multi_workspace) = self.multi_workspace.upgrade() else { return; }; - let keys: Vec = self - .contents - .entries - .iter() - .filter_map(|entry| match entry { - ListEntry::ProjectHeader { key, .. } => Some(key.clone()), - _ => None, - }) - .collect(); - for key in keys { - if self.worktree_default_branches.contains_key(&key) { - continue; - } - let Some(base) = multi_workspace - .read(cx) - .workspaces_for_project_group(&key, cx) - .next() - .cloned() - else { - continue; - }; - self.prefetch_worktree_default_branch(&key, &base, cx); + let workspaces = multi_workspace + .read(cx) + .workspaces() + .cloned() + .collect::>(); + let mut default_branch_keys = HashSet::new(); + for workspace in workspaces { + let default_branch_key = git_project_group_key(&workspace, cx); + self.prefetch_worktree_default_branch(&default_branch_key, &workspace, cx); + default_branch_keys.insert(default_branch_key); + } + self.worktree_default_branches + .retain(|default_branch_key, _| default_branch_keys.contains(default_branch_key)); + } + + fn worktree_default_branch( + &self, + workspace: &Entity, + cx: &App, + ) -> Option { + match self + .worktree_default_branches + .get(&git_project_group_key(workspace, cx)) + { + Some(DefaultBranchCache::Resolved(branch)) => branch.clone(), + _ => None, } } @@ -3067,6 +3363,9 @@ impl Sidebar { let activate_weak_menu = weak_menu.clone(); let close_weak_menu = weak_menu.clone(); let activate_workspace = workspace.clone(); + let tooltip = root_paths_tooltip( + &workspace.read(menu_cx).root_paths(menu_cx), + ); menu = menu.custom_entry( move |_window, _cx| { @@ -3082,21 +3381,29 @@ impl Sidebar { .w_full() .gap_2() .justify_between() - .child(h_flex().min_w_0().gap_1().children( - workspace_label.iter().enumerate().map( - |(label_ix, label)| { - h_flex() - .gap_1() - .when(label_ix > 0, |this| { - this.child( - Label::new("•").alpha(0.25), - ) - }) - .child(label.render()) - .into_any_element() - }, - ), - )) + .child( + h_flex() + .id(("open-worktree", workspace_index)) + .min_w_0() + .gap_1() + .children( + workspace_label.iter().enumerate().map( + |(label_ix, label)| { + h_flex() + .gap_1() + .when(label_ix > 0, |this| { + this.child( + Label::new("•") + .alpha(0.25), + ) + }) + .child(label.render()) + .into_any_element() + }, + ), + ) + .tooltip(Tooltip::text(tooltip.clone())), + ) .when(is_active_workspace, |this| { this.pr_1().child( Icon::new(IconName::Check) @@ -7894,6 +8201,53 @@ impl WorkspaceSidebar for Sidebar { self.width } + fn retains_project_group( + &self, + old_worktree_paths: &WorktreePaths, + new_git_worktree_paths: &WorktreePaths, + cx: &App, + ) -> bool { + let thread_store = ThreadMetadataStore::global(cx).read(cx); + let terminal_store = TerminalThreadMetadataStore::global(cx).read(cx); + let git_paths = |worktree_paths: &WorktreePaths| { + legacy_delta_main_paths(worktree_paths) + .unwrap_or_else(|| worktree_paths.main_worktree_path_list().clone()) + }; + let old_group_paths = old_worktree_paths.main_worktree_path_list(); + let old_folder_paths = old_worktree_paths.folder_path_list(); + let old_git_paths = old_folder_paths + .ordered_paths() + .map(|old_folder_path| { + new_git_worktree_paths + .ordered_pairs() + .find(|(_, folder_path)| *folder_path == old_folder_path) + .map(|(git_main_path, _)| git_main_path.clone()) + }) + .collect::>>() + .map(|git_main_paths| PathList::new(&git_main_paths)) + .unwrap_or_else(|| git_paths(old_worktree_paths)); + let repository_changed = old_git_paths != *new_git_worktree_paths.main_worktree_path_list(); + let stays_in_old_group = |worktree_paths: &WorktreePaths| { + worktree_paths.folder_path_list() != old_folder_paths + && (!repository_changed || git_paths(worktree_paths) != old_git_paths) + }; + thread_store + .entries_for_main_worktree_path(old_group_paths, None) + .any(|thread| { + stays_in_old_group(&thread.worktree_paths) + && (!thread.is_draft() + || agent_ui::draft_prompt_store::display_label_for_draft( + None, + thread.thread_id, + cx, + ) + .is_some()) + }) + || terminal_store + .entries_for_main_worktree_path(old_group_paths, None) + .any(|terminal| stays_in_old_group(&terminal.worktree_paths)) + } + fn set_width(&mut self, width: Option, cx: &mut Context) { // `None` is the reset gesture, which hands the width back to the setting. self.width_set_by_user = width.is_some(); diff --git a/crates/sidebar/src/sidebar_tests.rs b/crates/sidebar/src/sidebar_tests.rs index bd13c3acabf..e0e5a3397ed 100644 --- a/crates/sidebar/src/sidebar_tests.rs +++ b/crates/sidebar/src/sidebar_tests.rs @@ -294,6 +294,609 @@ async fn test_workspace_menu_uses_bare_repository_worktree_name(cx: &mut TestApp assert_eq!(labels[0].secondary_name, None); } +#[gpui::test] +async fn test_delta_checkout_subfolders_are_named_after_their_checkout(cx: &mut TestAppContext) { + init_test(cx); + let fs = FakeFs::new(cx.executor()); + fs.insert_tree( + util::path!("/repo"), + serde_json::json!({ + ".git": { "HEAD": "ref: refs/heads/main\n" }, + ".delta": { + "clones": { + "a": { + "repo.git": { + "HEAD": "ref: refs/heads/feature\n", + "config": "[core]\n\tbare = false\n", + "worktrees": { + "review": { + "HEAD": "ref: refs/heads/review\n", + "commondir": "../..", + "gitdir": util::path!("/review/repo/.git"), + }, + }, + "delta": { "copy-baseline": "" }, + "objects": { + "info": { + "alternates": format!("{}\n", util::path!("/repo/.git/objects")), + }, + }, + }, + }, + "b": { + "repo.git": { + "HEAD": "ref: refs/heads/feature\n", + "config": "[core]\n\tbare = false\n", + "delta": { "copy-baseline": "" }, + "objects": { + "info": { + "alternates": format!("{}\n", util::path!("/repo/.git/objects")), + }, + }, + }, + }, + }, + "worktrees": { + "a": { + "repo": { + ".git": format!("gitdir: {}\n", util::path!("/repo/.delta/clones/a/repo.git")), + "src": {}, + }, + }, + "review-b": { + "repo": { + ".git": format!("gitdir: {}\n", util::path!("/repo/.delta/clones/b/repo.git")), + "src": {}, + }, + }, + }, + }, + }), + ) + .await; + fs.insert_tree( + util::path!("/review/repo"), + serde_json::json!({ + ".git": format!( + "gitdir: {}\n", + util::path!("/repo/.delta/clones/a/repo.git/worktrees/review") + ), + }), + ) + .await; + cx.update(|cx| ::set_global(fs.clone(), cx)); + for (name, folder_name, minute) in [("a", "a", 2), ("b", "review-b", 1)] { + save_thread_metadata_with_main_paths( + name, + &format!("Thread {name}"), + PathList::new(&[PathBuf::from(util::path!("/repo/.delta/worktrees")) + .join(folder_name) + .join("repo") + .join("src")]), + PathList::new(&[Path::new(util::path!("/repo"))]), + chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 1, 0, minute, 0).unwrap(), + cx, + ); + } + let project_a = project::Project::test( + fs.clone(), + [Path::new(util::path!("/repo/.delta/worktrees/a/repo/src"))], + cx, + ) + .await; + let project_b = project::Project::test( + fs.clone(), + [Path::new(util::path!( + "/repo/.delta/worktrees/review-b/repo/src" + ))], + cx, + ) + .await; + let project_review = + project::Project::test(fs.clone(), [Path::new(util::path!("/review/repo"))], cx).await; + for project in [&project_a, &project_b, &project_review] { + project + .update(cx, |project, cx| project.git_scans_complete(cx)) + .await; + } + + let (multi_workspace, cx) = + cx.add_window_view(|window, cx| MultiWorkspace::test_new(project_a, window, cx)); + let workspace_b = multi_workspace.update_in(cx, |multi_workspace, window, cx| { + multi_workspace.test_add_workspace(project_review, window, cx); + multi_workspace.test_add_workspace(project_b, window, cx) + }); + let sidebar = setup_sidebar(&multi_workspace, cx); + sidebar.update(cx, |sidebar, cx| sidebar.update_entries(cx)); + cx.run_until_parked(); + let mut labels = cx.update(|_window, cx| { + multi_workspace + .read(cx) + .workspaces() + .flat_map(|workspace| workspace_menu_worktree_labels(workspace, cx)) + .map(|label| { + ( + label.primary_name.to_string(), + label.secondary_name.map(|name| name.to_string()), + ) + }) + .collect::>() + }); + labels.sort(); + + assert_eq!( + (labels, visible_entries_as_strings(&sidebar, cx)), + ( + vec![ + ("a/repo/review/repo".to_string(), None), + ("src".to_string(), Some("a".to_string())), + ("src".to_string(), Some("b/repo".to_string())), + ], + vec![ + "v [repo]".to_string(), + " Thread a {a}".to_string(), + " Thread b {b/repo}".to_string(), + ] + ) + ); + + multi_workspace + .update_in(cx, |multi_workspace, window, cx| { + multi_workspace.remove([workspace_b], RemovalIntent::KeepProject, window, cx) + }) + .await + .unwrap(); + sidebar.update(cx, |sidebar, cx| sidebar.update_entries(cx)); + cx.run_until_parked(); + + assert_eq!( + visible_entries_as_strings(&sidebar, cx), + vec!["v [repo]", " Thread a {a}", " Thread b {b/repo}"] + ); +} + +#[gpui::test] +async fn test_project_menu_of_a_group_with_delta_checkouts(cx: &mut TestAppContext) { + init_test(cx); + let fs = FakeFs::new(cx.executor()); + let delta_clone = || { + serde_json::json!({ + "HEAD": "ref: refs/heads/feature\n", + "config": "[core]\n\tbare = false\n", + "delta": { "copy-baseline": "" }, + "objects": { + "info": { + "alternates": format!("{}\n", util::path!("/repo/.git/objects")), + }, + }, + }) + }; + fs.insert_tree( + util::path!("/repo"), + serde_json::json!({ + ".git": { + "HEAD": "ref: refs/heads/main\n", + "worktrees": { + "feature": { + "HEAD": "ref: refs/heads/feature\n", + "commondir": "../..", + "gitdir": util::path!("/worktrees/feature/repo/.git"), + }, + }, + }, + ".delta": { + "clones": { + "a": { "repo.git": delta_clone() }, + "b": { "repo.git": delta_clone() }, + }, + "worktrees": { + "a": { + "repo": { + ".git": format!("gitdir: {}\n", util::path!("/repo/.delta/clones/a/repo.git")), + "src": {}, + }, + }, + "b": { + "repo": { + ".git": format!("gitdir: {}\n", util::path!("/repo/.delta/clones/b/repo.git")), + }, + }, + }, + }, + }), + ) + .await; + fs.insert_tree( + util::path!("/worktrees/feature/repo"), + serde_json::json!({ + ".git": format!("gitdir: {}\n", util::path!("/repo/.git/worktrees/feature")), + "src": {}, + }), + ) + .await; + fs.insert_tree(util::path!("/tools"), serde_json::json!({ "bin": {} })) + .await; + cx.update(|cx| ::set_global(fs.clone(), cx)); + + let checkout_subfolder = PathBuf::from(util::path!("/repo/.delta/worktrees/a/repo/src")); + let root_sets = [ + vec![PathBuf::from(util::path!("/repo/.delta/worktrees/b/repo"))], + vec![checkout_subfolder.clone()], + vec![PathBuf::from(util::path!("/worktrees/feature/repo"))], + vec![ + PathBuf::from(util::path!("/repo")), + PathBuf::from(util::path!("/tools")), + ], + vec![ + PathBuf::from(util::path!("/repo/.delta/worktrees/b/repo")), + PathBuf::from(util::path!("/tools")), + ], + vec![PathBuf::from(util::path!("/worktrees/feature/repo/src"))], + vec![PathBuf::from(util::path!("/repo"))], + ]; + let mut projects = Vec::new(); + for roots in &root_sets { + let project = project::Project::test( + fs.clone(), + roots.iter().map(|root| root.as_path()).collect::>(), + cx, + ) + .await; + project + .update(cx, |project, cx| project.git_scans_complete(cx)) + .await; + projects.push(project); + } + let (multi_workspace, cx) = + cx.add_window_view(|window, cx| MultiWorkspace::test_new(projects[0].clone(), window, cx)); + let sibling_workspace = + multi_workspace.read_with(cx, |multi_workspace, _| multi_workspace.workspace().clone()); + let mut workspaces = vec![sibling_workspace.clone()]; + for project in &projects[1..] { + workspaces.push( + multi_workspace.update_in(cx, |multi_workspace, window, cx| { + multi_workspace.test_add_workspace(project.clone(), window, cx) + }), + ); + } + multi_workspace.update_in(cx, |multi_workspace, window, cx| { + multi_workspace.activate(sibling_workspace.clone(), None, window, cx); + }); + let sidebar = setup_sidebar(&multi_workspace, cx); + + let open_labels = workspaces + .iter() + .map(|workspace| { + cx.update(|_window, cx| { + menu_label_names(&workspace_menu_worktree_labels(workspace, cx)) + }) + }) + .collect::>(); + let expected_labels = vec![ + vec![("b".to_string(), None)], + vec![("src".to_string(), Some("a".to_string()))], + vec![("feature".to_string(), None)], + vec![ + ("repo".to_string(), Some("main".to_string())), + ("tools".to_string(), None), + ], + vec![ + ("repo".to_string(), Some("b".to_string())), + ("tools".to_string(), None), + ], + vec![("src".to_string(), None)], + vec![("main".to_string(), None)], + ]; + assert_eq!(open_labels, expected_labels); + + let project_group_keys = [&workspaces[0], &workspaces[3]] + .map(|workspace| workspace.read_with(cx, |workspace, cx| workspace.project_group_key(cx))); + let group_workspaces = multi_workspace.read_with(cx, |multi_workspace, cx| { + multi_workspace + .workspaces_for_project_group(&project_group_keys[0], cx) + .cloned() + .collect::>() + }); + let mut creation_bases = Vec::new(); + for active_workspace in [&workspaces[0], &workspaces[6], &workspaces[3]] { + creation_bases.push(cx.update(|_, cx| { + let mut bases = worktree_creation_base_workspaces( + &project_group_keys[0], + Some(active_workspace), + &group_workspaces, + cx, + ) + .into_iter() + .map(|(workspace, is_named)| { + ( + git_project_group_key(&workspace, cx) + .path_list() + .paths() + .to_vec(), + is_named, + ) + }) + .collect::>(); + bases.sort(); + bases + })); + } + let source_identity = vec![PathBuf::from(util::path!("/repo"))]; + let clone_identity = |name: &str| { + vec![ + Path::new(util::path!("/repo/.delta/clones")) + .join(name) + .join("repo.git"), + ] + }; + assert_eq!( + creation_bases, + [ + vec![(clone_identity("b"), true)], + vec![(source_identity.clone(), false)], + vec![ + (source_identity, true), + (clone_identity("a"), true), + (clone_identity("b"), true), + ], + ], + "a worktree is created in the active checkout, or offered once per repository of the \ + group; a base other than the group's own repository is named" + ); + + cx.run_until_parked(); + let open_worktree_roots = group_workspaces + .iter() + .map(|workspace| { + workspace.read_with(cx, |workspace, cx| { + workspace + .root_paths(cx) + .iter() + .map(|path| path.to_path_buf()) + .collect::>() + }) + }) + .collect::>(); + let active_roots = active_root_paths(&multi_workspace, cx); + let inactive_worktree_row = open_worktree_roots + .iter() + .position(|roots| *roots != active_roots) + .unwrap(); + let menu_handle = project_menu_handle(&sidebar, &project_group_keys[0], cx); + let is_menu_open_after_open_worktree = + confirm_project_menu_row(&menu_handle, 1 + inactive_worktree_row, cx); + cx.run_until_parked(); + assert_eq!( + ( + is_menu_open_after_open_worktree, + active_root_paths(&multi_workspace, cx), + ), + (false, open_worktree_roots[inactive_worktree_row].clone()), + "Enter on an open worktree's row closes the menu at once and activates that worktree" + ); +} + +#[gpui::test] +async fn test_key_change_keeps_the_group_of_closed_rows_that_stay_listed(cx: &mut TestAppContext) { + init_test(cx); + let fs = FakeFs::new(cx.executor()); + let delta_clone = || { + serde_json::json!({ + "HEAD": "ref: refs/heads/feature\n", + "config": "[core]\n\tbare = false\n", + "delta": { "copy-baseline": "" }, + "objects": { + "info": { + "alternates": format!("{}\n", util::path!("/repo/.git/objects")), + }, + }, + }) + }; + fs.insert_tree( + util::path!("/repo"), + serde_json::json!({ + ".git": { "HEAD": "ref: refs/heads/main\n" }, + ".delta": { + "clones": { + "a": { "repo.git": delta_clone() }, + "b": { "repo.git": delta_clone() }, + }, + "worktrees": { + "a": { + "repo": { + ".git": format!("gitdir: {}\n", util::path!("/repo/.delta/clones/a/repo.git")), + "src": {}, + }, + }, + "b": { + "repo": { + ".git": format!("gitdir: {}\n", util::path!("/repo/.delta/clones/b/repo.git")), + }, + }, + }, + }, + }), + ) + .await; + fs.insert_tree(util::path!("/tools"), serde_json::json!({ "bin": {} })) + .await; + fs.insert_tree(util::path!("/other"), serde_json::json!({ "src": {} })) + .await; + fs.insert_tree( + util::path!("/next"), + serde_json::json!({ ".git": { "HEAD": "ref: refs/heads/main\n" } }), + ) + .await; + cx.update(|cx| ::set_global(fs.clone(), cx)); + + let checkout_a = PathBuf::from(util::path!("/repo/.delta/worktrees/a/repo")); + let checkout_b = PathBuf::from(util::path!("/repo/.delta/worktrees/b/repo")); + let clone_a = PathBuf::from(util::path!("/repo/.delta/clones/a/repo.git")); + let source = PathList::new(&[Path::new(util::path!("/repo"))]); + let saved_at = + |minute| chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 1, 0, minute, 0).unwrap(); + save_thread_metadata_with_worktree_paths( + "own-subfolder", + "Own subfolder", + WorktreePaths::from_path_lists(source.clone(), PathList::new(&[checkout_a.join("src")])) + .unwrap() + .with_delta_clones([( + checkout_a.join("src"), + project::DeltaClone { + path: clone_a.clone(), + is_linked_worktree: false, + checkout_path: Some(checkout_a.clone()), + }, + )]), + saved_at(1), + cx, + ); + let other_draft_id = save_draft_metadata_with_main_paths( + None, + PathList::new(std::slice::from_ref(&checkout_b)), + source.clone(), + saved_at(2), + cx, + ); + let project = project::Project::test(fs.clone(), [checkout_a.as_path()], cx).await; + project + .update(cx, |project, cx| project.git_scans_complete(cx)) + .await; + let other_project = + project::Project::test(fs.clone(), [Path::new(util::path!("/other"))], cx).await; + let (multi_workspace, cx) = + cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx)); + let checkout_workspace = + multi_workspace.read_with(cx, |multi_workspace, _| multi_workspace.workspace().clone()); + multi_workspace.update_in(cx, |multi_workspace, window, cx| { + multi_workspace.test_add_workspace(other_project, window, cx); + multi_workspace.activate(checkout_workspace, None, window, cx); + }); + let sidebar = setup_sidebar(&multi_workspace, cx); + save_thread_metadata_with_main_paths( + "own-root", + "Own root", + PathList::new(std::slice::from_ref(&checkout_a)), + source.clone(), + saved_at(3), + cx, + ); + + let mut entries = Vec::new(); + entries.push(entries_after_folder_change(&sidebar, &project, true, cx).await); + entries.push(entries_after_folder_change(&sidebar, &project, false, cx).await); + + let marker_path = clone_a.join("delta/copy-baseline"); + fs.remove_file(&marker_path, fs::RemoveOptions::default()) + .await + .unwrap(); + entries.push(updated_entries(&sidebar, cx)); + fs.insert_file(&marker_path, Vec::new()).await; + entries.push(updated_entries(&sidebar, cx)); + + let alternates_path = clone_a.join("objects/info/alternates"); + fs.insert_file( + &alternates_path, + format!("{}\n", util::path!("/next/.git/objects")).into_bytes(), + ) + .await; + entries.push(updated_entries(&sidebar, cx)); + fs.insert_file( + &alternates_path, + format!("{}\n", util::path!("/repo/.git/objects")).into_bytes(), + ) + .await; + entries.push(updated_entries(&sidebar, cx)); + + cx.update(|_, cx| { + agent_ui::draft_prompt_store::write( + other_draft_id, + &[acp_v2::ContentBlock::Text(acp_v2::TextContent::new( + "Other draft", + ))], + cx, + ) + }) + .await + .unwrap(); + entries.push(entries_after_folder_change(&sidebar, &project, true, cx).await); + entries.push(entries_after_folder_change(&sidebar, &project, false, cx).await); + + cx.update(|_, cx| agent_ui::draft_prompt_store::delete(other_draft_id, cx)) + .await + .unwrap(); + save_terminal_metadata_with_main_paths( + "Other terminal", + PathList::new(&[checkout_b]), + source, + saved_at(4), + cx, + ); + entries.push(entries_after_folder_change(&sidebar, &project, true, cx).await); + + assert_eq!( + entries, + vec![ + vec!["v [other]", "v [repo, tools]", " Own root {repo:a}"], + vec![ + "v [other]", + "v [repo]", + " Own root {a}", + " Own subfolder {a}" + ], + vec![ + "v [other]", + "v [repo]", + " Own root {repo}", + "v [repo]", + " Own subfolder {a}" + ], + vec![ + "v [other]", + "v [repo]", + " Own root {a}", + " Own subfolder {a}" + ], + vec![ + "v [other]", + "v [next]", + " Own root {a}", + "v [repo]", + " Own subfolder {a}" + ], + vec![ + "v [other]", + "v [repo]", + " Own root {a}", + " Own subfolder {a}" + ], + vec![ + "v [other]", + "v [repo, tools]", + " Own root {repo:a}", + "v [repo]", + " Other draft {b}", + " Own subfolder {a}" + ], + vec![ + "v [other]", + "v [repo]", + " Own root {a}", + " Other draft {b}", + " Own subfolder {a}" + ], + vec![ + "v [other]", + "v [repo, tools]", + " Own root {repo:a}", + "v [repo]", + " Other terminal {b}", + " Own subfolder {a}" + ], + ] + ); +} + fn setup_sidebar( multi_workspace: &Entity, cx: &mut gpui::VisualTestContext, @@ -520,6 +1123,22 @@ fn save_thread_metadata_with_main_paths( main_worktree_paths: PathList, updated_at: DateTime, cx: &mut TestAppContext, +) { + save_thread_metadata_with_worktree_paths( + session_id, + title, + WorktreePaths::from_path_lists(main_worktree_paths, folder_paths).unwrap(), + updated_at, + cx, + ); +} + +fn save_thread_metadata_with_worktree_paths( + session_id: &str, + title: &str, + worktree_paths: WorktreePaths, + updated_at: DateTime, + cx: &mut TestAppContext, ) { let session_id = acp::SessionId::new(Arc::from(session_id)); let title = SharedString::from(title.to_string()); @@ -540,7 +1159,7 @@ fn save_thread_metadata_with_main_paths( updated_at, created_at: None, interacted_at: None, - worktree_paths: WorktreePaths::from_path_lists(main_worktree_paths, folder_paths).unwrap(), + worktree_paths, archived: false, remote_connection: None, }; @@ -13496,6 +14115,407 @@ async fn test_activating_workspace_with_draft_does_not_create_extras(cx: &mut Te }); } +#[gpui::test] +async fn test_unused_legacy_delta_headers_follow_their_threads(cx: &mut TestAppContext) { + init_test(cx); + let fs = FakeFs::new(cx.executor()); + let clone = |name: &str| { + serde_json::json!({ + ".dotfiles.git": { + "HEAD": "ref: refs/heads/feature\n", + "config": "[core]\n\tbare = false\n", + "delta": { "copy-baseline": "" }, + "objects": { + "info": { + "alternates": format!("{}\n", util::path!("/.dotfiles/.git/objects")), + }, + }, + }, + "name": name, + }) + }; + let checkout = |name: &str| { + serde_json::json!({ + ".dotfiles": { + ".git": format!( + "gitdir: {}\n", + PathBuf::from(util::path!("/.dotfiles/.delta/clones")) + .join(name) + .join(".dotfiles.git") + .display() + ), + }, + }) + }; + fs.insert_tree( + util::path!("/.dotfiles"), + serde_json::json!({ + ".git": { "HEAD": "ref: refs/heads/main\n" }, + ".delta": { + "clones": { "one": clone("one"), "two": clone("two"), "three": clone("three") }, + "worktrees": { + "one": checkout("one"), + "two": checkout("two"), + "three": checkout("three"), + }, + }, + }), + ) + .await; + fs.insert_tree(util::path!("/other"), serde_json::json!({ "src": {} })) + .await; + cx.update(|cx| ::set_global(fs.clone(), cx)); + let legacy_key_path = + |name: &str| PathBuf::from(util::path!("/.dotfiles/.delta/clones")).join(name); + let checkout_path = |name: &str| { + PathBuf::from(util::path!("/.dotfiles/.delta/worktrees")) + .join(name) + .join(".dotfiles") + }; + for (session_id, folder_path, main_path, minute) in [ + ("one", checkout_path("one"), legacy_key_path("one"), 3), + ("two", checkout_path("two"), legacy_key_path("two"), 2), + ( + "container", + legacy_key_path("two"), + legacy_key_path("two"), + 1, + ), + ] { + save_thread_metadata_with_main_paths( + session_id, + session_id, + PathList::new(&[folder_path]), + PathList::new(&[main_path]), + chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 1, 0, minute, 0).unwrap(), + cx, + ); + } + let project = project::Project::test(fs.clone(), [Path::new(util::path!("/other"))], cx).await; + let mut open_checkout_projects = Vec::new(); + for name in ["one", "three"] { + let open_checkout_project = + project::Project::test(fs.clone(), [checkout_path(name).as_path()], cx).await; + open_checkout_project + .update(cx, |project, cx| project.git_scans_complete(cx)) + .await; + open_checkout_projects.push(open_checkout_project); + } + let (multi_workspace, cx) = + cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx)); + multi_workspace.update_in(cx, |multi_workspace, window, cx| { + for open_checkout_project in open_checkout_projects { + multi_workspace.test_add_workspace(open_checkout_project, window, cx); + } + multi_workspace.restore_project_groups( + ["one", "two", "three"] + .map(|name| workspace::SerializedProjectGroupState { + key: ProjectGroupKey::new(None, PathList::new(&[legacy_key_path(name)])), + expanded: true, + }) + .into(), + cx, + ); + }); + let sidebar = setup_sidebar(&multi_workspace, cx); + + sidebar.update(cx, |sidebar, cx| sidebar.update_entries(cx)); + cx.run_until_parked(); + + assert_eq!( + visible_entries_as_strings(&sidebar, cx), + vec![ + "v [two]", + " two {.dotfiles}", + " container", + "v [.dotfiles]", + " one {one}", + "v [other]", + ], + "rows of an open checkout join its source and its unused old header goes; \ + rows of a closed checkout stay under their old header" + ); + + multi_workspace + .update_in(cx, |multi_workspace, window, cx| { + multi_workspace.remove_project_group( + &ProjectGroupKey::new(None, PathList::new(&[Path::new(util::path!("/.dotfiles"))])), + window, + cx, + ) + }) + .await + .unwrap(); + sidebar.update(cx, |sidebar, cx| sidebar.update_entries(cx)); + cx.run_until_parked(); + + assert_eq!( + visible_entries_as_strings(&sidebar, cx), + vec!["v [two]", " two {.dotfiles}", " container", "v [other]"] + ); + + let checkout_project = + project::Project::test(fs.clone(), [checkout_path("two").as_path()], cx).await; + checkout_project + .update(cx, |project, cx| project.git_scans_complete(cx)) + .await; + multi_workspace.update_in(cx, |multi_workspace, window, cx| { + multi_workspace.test_add_workspace(checkout_project, window, cx); + multi_workspace.test_add_project_group(workspace::ProjectGroup { + key: ProjectGroupKey::new(None, PathList::new(&[legacy_key_path("one")])), + workspaces: Vec::new(), + expanded: true, + }); + }); + save_terminal_metadata_with_main_paths( + "container terminal", + PathList::new(&[legacy_key_path("one")]), + PathList::new(&[legacy_key_path("one")]), + chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 1, 0, 4, 0).unwrap(), + cx, + ); + let entries_with_loaded_stores = updated_entries(&sidebar, cx); + let mut entries_after_each_load = Vec::new(); + let mut legacy_groups_before_the_stores_load = Vec::new(); + for reload_thread_store in [true, false] { + cx.update(|_window, cx| { + if reload_thread_store { + ThreadMetadataStore::init_global(cx); + } else { + TerminalThreadMetadataStore::init_global(cx); + } + sidebar.update(cx, |sidebar, cx| sidebar.update_entries(cx)); + }); + legacy_groups_before_the_stores_load.push(multi_workspace.read_with( + cx, + |multi_workspace, _| { + ["one", "two"].map(|name| { + multi_workspace + .project_group_keys() + .contains(&ProjectGroupKey::new( + None, + PathList::new(&[legacy_key_path(name)]), + )) + }) + }, + )); + entries_after_each_load.push(updated_entries(&sidebar, cx)); + } + assert_eq!( + ( + legacy_groups_before_the_stores_load, + entries_after_each_load, + ), + ( + vec![[true, true], [true, true]], + vec![ + entries_with_loaded_stores.clone(), + entries_with_loaded_stores + ], + ), + "a store that has not loaded yet is not evidence that a group is unused" + ); +} + +#[gpui::test] +async fn test_delta_checkout_groups_with_its_source(cx: &mut TestAppContext) { + init_test(cx); + let fs = FakeFs::new(cx.executor()); + let source_path = Path::new(util::path!("/repo")); + let next_source_path = Path::new(util::path!("/next")); + let first_clone_path = Path::new(util::path!("/repo/.delta/clones/abc/repo.git")); + let first_checkout_path = Path::new(util::path!("/repo/.delta/worktrees/abc/repo")); + let second_clone_path = Path::new(util::path!("/repo/.delta/clones/def/repo.git")); + let second_checkout_path = Path::new(util::path!("/repo/.delta/worktrees/def/repo")); + let delta_clone = || { + serde_json::json!({ + "HEAD": "ref: refs/heads/feature\n", + "config": "[core]\n\tbare = false\n", + "delta": { "copy-baseline": "" }, + "objects": { + "info": { + "alternates": format!("{}\n", util::path!("/repo/.git/objects")), + }, + }, + }) + }; + fs.insert_tree( + source_path, + serde_json::json!({ + ".git": { "HEAD": "ref: refs/heads/main\n" }, + ".delta": { + "clones": { + "abc": { "repo.git": delta_clone() }, + "def": { "repo.git": delta_clone() }, + }, + "worktrees": { + "abc": { + "repo": { ".git": format!("gitdir: {}\n", first_clone_path.display()) }, + }, + "def": { + "repo": { ".git": format!("gitdir: {}\n", second_clone_path.display()) }, + }, + }, + }, + }), + ) + .await; + fs.insert_tree( + next_source_path, + serde_json::json!({ ".git": { "HEAD": "ref: refs/heads/main\n" } }), + ) + .await; + save_thread_metadata_with_main_paths( + "First", + "First", + PathList::new(&[first_checkout_path]), + PathList::new(&[source_path]), + chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 1, 0, 0, 0).unwrap(), + cx, + ); + let source_project = project::Project::test(fs.clone(), [source_path], cx).await; + let first_project = project::Project::test(fs.clone(), [first_checkout_path], cx).await; + let second_project = project::Project::test(fs.clone(), [second_checkout_path], cx).await; + + let (multi_workspace, cx) = + cx.add_window_view(|window, cx| MultiWorkspace::test_new(source_project, window, cx)); + multi_workspace.update_in(cx, |multi_workspace, window, cx| { + multi_workspace.retain_active_workspace(cx); + multi_workspace.test_add_workspace(first_project, window, cx); + multi_workspace.test_add_workspace(second_project, window, cx); + }); + let sidebar = setup_sidebar(&multi_workspace, cx); + let group_paths = |cx: &mut gpui::VisualTestContext| { + cx.run_until_parked(); + multi_workspace.read_with(cx, |multi_workspace, _| { + multi_workspace + .project_group_keys() + .into_iter() + .map(|key| key.path_list().clone()) + .collect::>() + }) + }; + let first_main_paths = |cx: &mut gpui::VisualTestContext| { + cx.run_until_parked(); + cx.update(|_, cx| { + ThreadMetadataStore::global(cx) + .read(cx) + .entries() + .find(|thread| thread.display_title().as_ref() == "First") + .map(|thread| thread.main_worktree_paths().paths().to_vec()) + }) + }; + + let group_paths_with_source = group_paths(cx); + let entries_with_source = visible_entries_as_strings(&sidebar, cx); + let mut default_branch_cache_paths = sidebar.read_with(cx, |sidebar, _| { + sidebar + .worktree_default_branches + .keys() + .map(|key| key.path_list().paths().to_vec()) + .collect::>() + }); + default_branch_cache_paths.sort(); + let branch_name = |root_path: &Path| { + format!( + "origin/{}", + root_path.to_string_lossy().replace(['/', '\\', ':'], "-") + ) + }; + let default_branches = sidebar.update(cx, |sidebar, cx| { + for repository_path in [source_path, first_clone_path, second_clone_path] { + sidebar.worktree_default_branches.insert( + ProjectGroupKey::new(None, PathList::new(&[repository_path])), + DefaultBranchCache::Resolved(RemoteBranchName::parse(&branch_name( + repository_path, + ))), + ); + } + let mut default_branches = multi_workspace + .read(cx) + .workspaces() + .map(|workspace| { + ( + workspace.read(cx).root_paths(cx)[0].to_path_buf(), + sidebar + .worktree_default_branch(workspace, cx) + .map(|branch| branch.display_name()), + ) + }) + .collect::>(); + default_branches.sort(); + default_branches + }); + let mut menu_labels = cx.update(|_, cx| { + multi_workspace + .read(cx) + .workspaces() + .flat_map(|workspace| workspace_menu_worktree_labels(workspace, cx)) + .map(|label| label.primary_name.to_string()) + .collect::>() + }); + menu_labels.sort(); + + fs.insert_file( + first_clone_path.join("objects/info/alternates"), + format!("{}\n", util::path!("/next/.git/objects")).into_bytes(), + ) + .await; + let group_paths_with_next_source = group_paths(cx); + let first_main_paths_with_next_source = first_main_paths(cx); + fs.remove_file( + &first_clone_path.join("delta/copy-baseline"), + fs::RemoveOptions::default(), + ) + .await + .unwrap(); + + assert_eq!( + ( + group_paths_with_source, + entries_with_source, + default_branch_cache_paths, + default_branches, + menu_labels, + group_paths_with_next_source, + first_main_paths_with_next_source, + group_paths(cx), + first_main_paths(cx), + ), + ( + vec![PathList::new(&[source_path])], + vec!["v [repo]".to_string(), " First {abc}".to_string()], + vec![ + vec![source_path.to_path_buf()], + vec![first_clone_path.to_path_buf()], + vec![second_clone_path.to_path_buf()], + ], + vec![ + (source_path.to_path_buf(), Some(branch_name(source_path))), + ( + first_checkout_path.to_path_buf(), + Some(branch_name(first_clone_path)), + ), + ( + second_checkout_path.to_path_buf(), + Some(branch_name(second_clone_path)), + ), + ], + vec!["abc".to_string(), "def".to_string(), "main".to_string()], + vec![ + PathList::new(&[source_path]), + PathList::new(&[next_source_path]), + ], + Some(vec![next_source_path.to_path_buf()]), + vec![ + PathList::new(&[source_path]), + PathList::new(&[first_clone_path]), + ], + Some(vec![first_clone_path.to_path_buf()]), + ) + ); +} + #[gpui::test] async fn test_non_archive_thread_paths_migrate_on_worktree_add_and_remove(cx: &mut TestAppContext) { // Historical threads (not open in any agent panel) should have their @@ -15783,6 +16803,124 @@ fn test_worktree_info_branch_names_for_linked_worktrees() { ); } +#[test] +fn test_worktree_info_names_only_delta_checkouts_after_their_checkout() { + let worktree_names = |paths: &[(&str, &str, Option<(&str, bool, Option<&str>)>)]| { + let (main_paths, folder_paths) = paths + .iter() + .map(|(main_path, folder_path, _)| { + (PathBuf::from(main_path), PathBuf::from(folder_path)) + }) + .unzip::<_, _, Vec<_>, Vec<_>>(); + let worktree_paths = WorktreePaths::from_path_lists( + PathList::new(&main_paths), + PathList::new(&folder_paths), + ) + .expect("same length") + .with_delta_clones(paths.iter().filter_map(|(_, folder_path, clone)| { + let (clone_path, is_linked_worktree, checkout_path) = clone.as_ref()?; + Some(( + PathBuf::from(folder_path), + project::DeltaClone { + path: PathBuf::from(clone_path), + is_linked_worktree: *is_linked_worktree, + checkout_path: checkout_path.map(PathBuf::from), + }, + )) + })); + worktree_info_from_thread_paths(&worktree_paths, &HashMap::::new()) + .into_iter() + .map(|info| info.worktree_name.unwrap_or_default().to_string()) + .collect::>() + }; + + assert_eq!( + [ + worktree_names(&[ + ( + "/repo_a", + "/storage/worktrees/red/repo_a/src", + Some(( + "/storage/clones/red/repo_a.git", + false, + Some("/storage/worktrees/red/repo_a"), + )), + ), + ( + "/repo_b", + "/storage/worktrees/blue/repo_b/lib", + Some(( + "/storage/clones/blue/repo_b.git", + false, + Some("/storage/worktrees/blue/repo_b"), + )), + ), + ]), + worktree_names(&[( + "/repos/My Project", + "/storage/worktrees/checkout-a/My_Project", + Some(( + "/storage/clones/checkout-a/My_Project.git", + false, + Some("/storage/worktrees/checkout-a/My_Project"), + )), + )]), + worktree_names(&[("/repos/My Project", "/checkouts/review/My_Project", None)]), + worktree_names(&[("/repos/My Project", "/checkouts/review/My Project", None)]), + worktree_names(&[( + "/repo", + "/tmp/review/repo", + Some(("/repo/.delta/clones/abc/repo.git", true, None)), + )]), + worktree_names(&[( + "/repo", + "/tmp/review/repo", + Some(("/repo/.delta/clones/def/repo.git", true, None)), + )]), + worktree_names(&[( + "/repo", + "/worktrees/red/repo/src", + Some(( + "/repo/.delta/clones/abc/repo.git", + true, + Some("/worktrees/red/repo"), + )), + )]), + worktree_names(&[( + "/repo", + "/worktrees/blue/repo/src", + Some(( + "/repo/.delta/clones/abc/repo.git", + true, + Some("/worktrees/blue/repo"), + )), + )]), + worktree_names(&[( + "/repo", + "/home/abc/checkouts/red", + Some(("/repo/.delta/clones/abc/repo.git", false, None)), + )]), + worktree_names(&[( + "/repo", + "/home/abc/checkouts/blue", + Some(("/repo/.delta/clones/abc/repo.git", false, None)), + )]), + ], + [ + vec!["repo_a:red".to_string(), "repo_b:blue".to_string()], + vec!["checkout-a".to_string()], + vec!["My_Project".to_string()], + vec!["review".to_string()], + vec!["abc/repo/review/repo".to_string()], + vec!["def/repo/review/repo".to_string()], + vec!["abc/repo/red/repo".to_string()], + vec!["abc/repo/blue/repo".to_string()], + vec!["abc/repo/red".to_string()], + vec!["abc/repo/blue".to_string()], + ] + ); +} + #[test] fn test_worktree_info_missing_branch_returns_none() { let folder_paths = PathList::new(&[PathBuf::from("/projects/myapp")]); @@ -16815,3 +17953,139 @@ fn header_search_offsets( fullscreen, } } + +fn menu_label_names(labels: &[WorkspaceMenuWorktreeLabel]) -> Vec<(String, Option)> { + labels + .iter() + .map(|label| { + ( + label.primary_name.to_string(), + label.secondary_name.as_ref().map(|name| name.to_string()), + ) + }) + .collect() +} + +fn project_menu_handle( + sidebar: &Entity, + project_group_key: &ProjectGroupKey, + cx: &mut gpui::VisualTestContext, +) -> PopoverMenuHandle { + sidebar + .read_with(cx, |sidebar, _| { + let header_index = sidebar.contents.entries.iter().position(|entry| { + matches!(entry, ListEntry::ProjectHeader { key, .. } if key == project_group_key) + })?; + sidebar + .project_header_menu_handles + .get(&header_index) + .cloned() + }) + .unwrap() +} + +fn simulate_frames(cx: &mut gpui::VisualTestContext) { + for _ in 0..2 { + cx.update(|window, cx| window.simulate_next_frame(cx)); + cx.run_until_parked(); + } +} + +fn active_root_paths( + multi_workspace: &Entity, + cx: &mut gpui::VisualTestContext, +) -> Vec { + multi_workspace.read_with(cx, |multi_workspace, cx| { + multi_workspace + .workspace() + .read(cx) + .root_paths(cx) + .iter() + .map(|root_path| root_path.to_path_buf()) + .collect() + }) +} + +async fn entries_after_folder_change( + sidebar: &Entity, + project: &Entity, + add_tools_folder: bool, + cx: &mut gpui::VisualTestContext, +) -> Vec { + let tools_path = Path::new(util::path!("/tools")); + if add_tools_folder { + project + .update(cx, |project, cx| { + project.find_or_create_worktree(tools_path, true, cx) + }) + .await + .unwrap(); + } else { + project.update(cx, |project, cx| { + let worktree_id = project + .visible_worktrees(cx) + .find(|worktree| worktree.read(cx).abs_path().as_ref() == tools_path) + .map(|worktree| worktree.read(cx).id()); + if let Some(worktree_id) = worktree_id { + project.remove_worktree(worktree_id, cx); + } + }); + } + updated_entries(sidebar, cx) +} + +fn save_terminal_metadata_with_main_paths( + title: &'static str, + folder_paths: PathList, + main_worktree_paths: PathList, + created_at: DateTime, + cx: &mut TestAppContext, +) { + cx.update(|cx| { + TerminalThreadMetadataStore::global(cx).update(cx, |store, cx| { + store.save( + TerminalThreadMetadata { + terminal_id: agent_ui::TerminalId::test_new(), + title: title.into(), + custom_title: None, + created_at, + worktree_paths: WorktreePaths::from_path_lists( + main_worktree_paths, + folder_paths, + ) + .unwrap(), + remote_connection: None, + working_directory: None, + }, + cx, + ); + }); + }); + cx.run_until_parked(); +} + +fn confirm_project_menu_row( + menu_handle: &PopoverMenuHandle, + row: usize, + cx: &mut gpui::VisualTestContext, +) -> bool { + cx.update(|window, cx| { + menu_handle.hide(cx); + menu_handle.show(window, cx); + }); + cx.run_until_parked(); + simulate_frames(cx); + cx.dispatch_action(SelectFirst); + for _ in 0..row { + cx.dispatch_action(SelectNext); + } + cx.update(|window, cx| window.dispatch_action(Box::new(Confirm), cx)); + menu_handle.is_deployed() +} + +fn updated_entries(sidebar: &Entity, cx: &mut gpui::VisualTestContext) -> Vec { + cx.run_until_parked(); + sidebar.update(cx, |sidebar, cx| sidebar.update_entries(cx)); + cx.run_until_parked(); + visible_entries_as_strings(sidebar, cx) +} diff --git a/crates/workspace/src/multi_workspace.rs b/crates/workspace/src/multi_workspace.rs index 01d8e217f00..db8032249ad 100644 --- a/crates/workspace/src/multi_workspace.rs +++ b/crates/workspace/src/multi_workspace.rs @@ -7,7 +7,7 @@ use gpui::{ Window, WindowId, actions, deferred, px, }; pub use project::ProjectGroupKey; -use project::{DisableAiSettings, Project}; +use project::{DisableAiSettings, Project, WorktreePaths}; use remote::RemoteConnectionOptions; use settings::Settings; pub use settings::SidebarSide; @@ -127,6 +127,14 @@ pub trait Sidebar: Focusable + Render + EventEmitter + Sized { fn is_threads_list_view_active(&self) -> bool { true } + fn retains_project_group( + &self, + _old_worktree_paths: &WorktreePaths, + _new_git_worktree_paths: &WorktreePaths, + _cx: &App, + ) -> bool { + false + } /// Makes focus reset back to the search editor upon toggling the sidebar from outside fn prepare_for_focus(&mut self, _window: &mut Window, _cx: &mut Context) {} /// Opens or cycles the thread switcher popup. @@ -173,6 +181,12 @@ pub trait SidebarHandle: 'static + Send + Sync { fn cycle_thread(&self, forward: bool, window: &mut Window, cx: &mut App); fn is_threads_list_view_active(&self, cx: &App) -> bool; + fn retains_project_group( + &self, + old_worktree_paths: &WorktreePaths, + new_git_worktree_paths: &WorktreePaths, + cx: &App, + ) -> bool; fn side(&self, cx: &App) -> SidebarSide; fn serialized_state(&self, cx: &App) -> Option; @@ -253,6 +267,16 @@ impl SidebarHandle for Entity { self.read(cx).is_threads_list_view_active() } + fn retains_project_group( + &self, + old_worktree_paths: &WorktreePaths, + new_git_worktree_paths: &WorktreePaths, + cx: &App, + ) -> bool { + self.read(cx) + .retains_project_group(old_worktree_paths, new_git_worktree_paths, cx) + } + fn side(&self, cx: &App) -> SidebarSide { self.read(cx).side(cx) } @@ -613,7 +637,12 @@ impl MultiWorkspace { .cloned(); let old_key = ProjectGroupKey::from_worktree_paths(old_worktree_paths, host); - this.handle_project_group_key_change(&workspace, &old_key, cx); + this.handle_project_group_key_change( + &workspace, + &old_key, + old_worktree_paths, + cx, + ); } } _ => {} @@ -633,6 +662,7 @@ impl MultiWorkspace { &mut self, workspace: &Entity, old_key: &ProjectGroupKey, + old_worktree_paths: &WorktreePaths, cx: &mut Context, ) { if !self.is_workspace_retained(workspace) { @@ -646,7 +676,13 @@ impl MultiWorkspace { // The Project already emitted WorktreePathsChanged which the // sidebar handles for thread migration. - self.rekey_project_group(old_key, &new_key, cx); + let project = workspace.read(cx).project().read(cx); + let new_git_worktree_paths = project.git_worktree_paths(cx); + let sidebar_retains_old_key = project.is_local() + && self.sidebar.as_ref().is_some_and(|sidebar| { + sidebar.retains_project_group(old_worktree_paths, &new_git_worktree_paths, cx) + }); + self.rekey_project_group(old_key, &new_key, sidebar_retains_old_key, cx); self.serialize(cx); cx.notify(); } @@ -709,6 +745,7 @@ impl MultiWorkspace { &mut self, old_key: &ProjectGroupKey, new_key: &ProjectGroupKey, + sidebar_retains_old_key: bool, cx: &App, ) { if old_key == new_key { @@ -727,6 +764,32 @@ impl MultiWorkspace { return; } + // If another retained workspace still has the old key (e.g. a + // linked worktree workspace), re-create the old group so it + // remains reachable in the sidebar. + let other_workspace_needs_old_key = self + .held + .iter() + .any(|held| held.pinned && held.workspace.read(cx).project_group_key(cx) == *old_key); + if sidebar_retains_old_key && !other_workspace_needs_old_key { + let old_group = self + .project_groups + .iter() + .enumerate() + .find(|(_, group)| group.key == *old_key) + .map(|(index, group)| (index, group.expanded)); + if !new_key_exists && let Some((old_index, expanded)) = old_group { + self.project_groups.insert( + old_index, + ProjectGroupState { + key: new_key.clone(), + expanded, + }, + ); + } + return; + } + if new_key_exists { let active_key = self.workspace().read(cx).project_group_key(cx); if active_key == *new_key { @@ -743,13 +806,6 @@ impl MultiWorkspace { } } - // If another retained workspace still has the old key (e.g. a - // linked worktree workspace), re-create the old group so it - // remains reachable in the sidebar. - let other_workspace_needs_old_key = self - .held - .iter() - .any(|held| held.pinned && held.workspace.read(cx).project_group_key(cx) == *old_key); if other_workspace_needs_old_key { self.ensure_project_group_state(old_key.clone()); } @@ -856,6 +912,31 @@ impl MultiWorkspace { self.project_groups = restored; } + pub fn replace_project_group( + &mut self, + old_key: &ProjectGroupKey, + new_keys: Vec, + cx: &mut Context, + ) { + let Some(mut index) = self + .project_groups + .iter() + .position(|group| group.key == *old_key) + else { + return; + }; + let ProjectGroupState { expanded, .. } = self.project_groups.remove(index); + for key in new_keys { + if self.project_groups.iter().all(|group| group.key != key) { + self.project_groups + .insert(index, ProjectGroupState { key, expanded }); + index += 1; + } + } + self.serialize(cx); + cx.notify(); + } + pub fn project_group_keys(&self) -> Vec { self.project_groups .iter() @@ -1863,9 +1944,17 @@ impl MultiWorkspace { .iter() .map(|workspace| workspace.read(cx).project_group_key(cx)) .collect::>(); + let retained_keys = this + .held + .iter() + .filter(|held| held.pinned && !workspaces.contains(&held.workspace)) + .map(|held| held.workspace.read(cx).project_group_key(cx)) + .collect::>(); - this.project_groups - .retain(|group| !workspace_to_delete_keys.contains(&group.key)); + this.project_groups.retain(|group| { + !workspace_to_delete_keys.contains(&group.key) + || retained_keys.contains(&group.key) + }); cx.emit(MultiWorkspaceEvent::ProjectGroupsChanged); } diff --git a/crates/workspace/src/multi_workspace_tests.rs b/crates/workspace/src/multi_workspace_tests.rs index d60a676228b..48a31d39f68 100644 --- a/crates/workspace/src/multi_workspace_tests.rs +++ b/crates/workspace/src/multi_workspace_tests.rs @@ -1041,6 +1041,7 @@ async fn test_close_workspace_prefers_workspace_in_same_project_group(cx: &mut T let project_a_2 = Project::test(fs.clone(), ["/project-a".as_ref()], cx).await; let project_b = Project::test(fs, ["/project-b".as_ref()], cx).await; let key_a = project_a_1.read_with(cx, |project, cx| project.project_group_key(cx)); + let key_b = project_b.read_with(cx, |project, cx| project.project_group_key(cx)); let (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| { @@ -1094,6 +1095,7 @@ async fn test_close_workspace_prefers_workspace_in_same_project_group(cx: &mut T vec![workspace_a_2], "only the fallback workspace should remain in project group A" ); + assert_eq!(multi_workspace.project_group_keys(), vec![key_b, key_a]); }); }