sidebar.rs

   1mod thread_switcher;
   2
   3use acp_thread::ThreadStatus;
   4use action_log::DiffStats;
   5use agent_client_protocol::{self as acp};
   6use agent_settings::AgentSettings;
   7use agent_ui::thread_metadata_store::{ArchivedGitWorktree, ThreadMetadata, ThreadMetadataStore};
   8use agent_ui::threads_archive_view::{
   9    ThreadsArchiveView, ThreadsArchiveViewEvent, format_history_entry_timestamp,
  10};
  11use agent_ui::{AcpThreadImportOnboarding, ThreadImportModal};
  12use agent_ui::{
  13    Agent, AgentPanel, AgentPanelEvent, DEFAULT_THREAD_TITLE, NewThread, RemoveSelectedThread,
  14};
  15use chrono::{DateTime, Utc};
  16use editor::Editor;
  17use feature_flags::{AgentV2FeatureFlag, FeatureFlagViewExt as _};
  18use git::repository::{AskPassDelegate, CommitOptions, ResetMode};
  19use gpui::{
  20    Action as _, AnyElement, App, AsyncWindowContext, Context, Entity, FocusHandle, Focusable,
  21    KeyContext, ListState, Pixels, PromptLevel, Render, SharedString, WeakEntity, Window,
  22    WindowHandle, linear_color_stop, linear_gradient, list, prelude::*, px,
  23};
  24use menu::{
  25    Cancel, Confirm, SelectChild, SelectFirst, SelectLast, SelectNext, SelectParent, SelectPrevious,
  26};
  27use project::git_store;
  28use project::{AgentId, AgentRegistryStore, Event as ProjectEvent, linked_worktree_short_name};
  29use recent_projects::sidebar_recent_projects::SidebarRecentProjects;
  30use remote::RemoteConnectionOptions;
  31use ui::utils::platform_title_bar_height;
  32
  33use serde::{Deserialize, Serialize};
  34use settings::Settings as _;
  35use std::collections::{HashMap, HashSet};
  36use std::mem;
  37use std::path::PathBuf;
  38use std::rc::Rc;
  39use theme::ActiveTheme;
  40use ui::{
  41    AgentThreadStatus, CommonAnimationExt, ContextMenu, Divider, HighlightedLabel, KeyBinding,
  42    PopoverMenu, PopoverMenuHandle, Tab, ThreadItem, ThreadItemWorktreeInfo, TintColor, Tooltip,
  43    WithScrollbar, prelude::*,
  44};
  45use util::ResultExt as _;
  46use util::path_list::{PathList, SerializedPathList};
  47use workspace::{
  48    AddFolderToProject, CloseWindow, FocusWorkspaceSidebar, MultiWorkspace, MultiWorkspaceEvent,
  49    Open, Sidebar as WorkspaceSidebar, SidebarSide, ToggleWorkspaceSidebar, Workspace, WorkspaceId,
  50    sidebar_side_context_menu,
  51};
  52
  53use zed_actions::OpenRecent;
  54use zed_actions::editor::{MoveDown, MoveUp};
  55
  56use zed_actions::agents_sidebar::{FocusSidebarFilter, ToggleThreadSwitcher};
  57
  58use crate::thread_switcher::{ThreadSwitcher, ThreadSwitcherEntry, ThreadSwitcherEvent};
  59
  60use crate::project_group_builder::ProjectGroupBuilder;
  61
  62mod project_group_builder;
  63
  64#[cfg(test)]
  65mod sidebar_tests;
  66
  67gpui::actions!(
  68    agents_sidebar,
  69    [
  70        /// Creates a new thread in the currently selected or active project group.
  71        NewThreadInGroup,
  72        /// Toggles between the thread list and the archive view.
  73        ToggleArchive,
  74    ]
  75);
  76
  77gpui::actions!(
  78    dev,
  79    [
  80        /// Dumps multi-workspace state (projects, worktrees, active threads) into a new buffer.
  81        DumpWorkspaceInfo,
  82    ]
  83);
  84
  85const DEFAULT_WIDTH: Pixels = px(300.0);
  86const MIN_WIDTH: Pixels = px(200.0);
  87const MAX_WIDTH: Pixels = px(800.0);
  88const DEFAULT_THREADS_SHOWN: usize = 5;
  89
  90#[derive(Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
  91enum SerializedSidebarView {
  92    #[default]
  93    ThreadList,
  94    Archive,
  95}
  96
  97#[derive(Default, Serialize, Deserialize)]
  98struct SerializedSidebar {
  99    #[serde(default)]
 100    width: Option<f32>,
 101    #[serde(default)]
 102    collapsed_groups: Vec<SerializedPathList>,
 103    #[serde(default)]
 104    expanded_groups: Vec<(SerializedPathList, usize)>,
 105    #[serde(default)]
 106    active_view: SerializedSidebarView,
 107}
 108
 109#[derive(Debug, Default)]
 110enum SidebarView {
 111    #[default]
 112    ThreadList,
 113    Archive(Entity<ThreadsArchiveView>),
 114}
 115
 116#[derive(Clone, Debug)]
 117enum ActiveEntry {
 118    Thread {
 119        session_id: acp::SessionId,
 120        workspace: Entity<Workspace>,
 121    },
 122    Draft(Entity<Workspace>),
 123}
 124
 125impl ActiveEntry {
 126    fn workspace(&self) -> &Entity<Workspace> {
 127        match self {
 128            ActiveEntry::Thread { workspace, .. } => workspace,
 129            ActiveEntry::Draft(workspace) => workspace,
 130        }
 131    }
 132
 133    fn is_active_thread(&self, session_id: &acp::SessionId) -> bool {
 134        matches!(self, ActiveEntry::Thread { session_id: id, .. } if id == session_id)
 135    }
 136
 137    fn matches_entry(&self, entry: &ListEntry) -> bool {
 138        match (self, entry) {
 139            (ActiveEntry::Thread { session_id, .. }, ListEntry::Thread(thread)) => {
 140                thread.metadata.session_id == *session_id
 141            }
 142            (
 143                ActiveEntry::Draft(workspace),
 144                ListEntry::NewThread {
 145                    workspace: entry_workspace,
 146                    ..
 147                },
 148            ) => workspace == entry_workspace,
 149            _ => false,
 150        }
 151    }
 152}
 153
 154#[derive(Clone, Debug)]
 155struct ActiveThreadInfo {
 156    session_id: acp::SessionId,
 157    title: SharedString,
 158    status: AgentThreadStatus,
 159    icon: IconName,
 160    icon_from_external_svg: Option<SharedString>,
 161    is_background: bool,
 162    is_title_generating: bool,
 163    diff_stats: DiffStats,
 164}
 165
 166#[derive(Clone)]
 167enum ThreadEntryWorkspace {
 168    Open(Entity<Workspace>),
 169    Closed(PathList),
 170}
 171
 172#[derive(Clone)]
 173struct WorktreeInfo {
 174    name: SharedString,
 175    full_path: SharedString,
 176    highlight_positions: Vec<usize>,
 177}
 178
 179#[derive(Clone)]
 180struct ThreadEntry {
 181    metadata: ThreadMetadata,
 182    icon: IconName,
 183    icon_from_external_svg: Option<SharedString>,
 184    status: AgentThreadStatus,
 185    workspace: ThreadEntryWorkspace,
 186    is_live: bool,
 187    is_background: bool,
 188    is_title_generating: bool,
 189    highlight_positions: Vec<usize>,
 190    worktrees: Vec<WorktreeInfo>,
 191    diff_stats: DiffStats,
 192}
 193
 194impl ThreadEntry {
 195    /// Updates this thread entry with active thread information.
 196    ///
 197    /// The existing [`ThreadEntry`] was likely deserialized from the database
 198    /// but if we have a correspond thread already loaded we want to apply the
 199    /// live information.
 200    fn apply_active_info(&mut self, info: &ActiveThreadInfo) {
 201        self.metadata.title = info.title.clone();
 202        self.status = info.status;
 203        self.icon = info.icon;
 204        self.icon_from_external_svg = info.icon_from_external_svg.clone();
 205        self.is_live = true;
 206        self.is_background = info.is_background;
 207        self.is_title_generating = info.is_title_generating;
 208        self.diff_stats = info.diff_stats;
 209    }
 210}
 211
 212#[derive(Clone)]
 213enum ListEntry {
 214    ProjectHeader {
 215        path_list: PathList,
 216        label: SharedString,
 217        workspace: Entity<Workspace>,
 218        highlight_positions: Vec<usize>,
 219        has_running_threads: bool,
 220        waiting_thread_count: usize,
 221        is_active: bool,
 222    },
 223    Thread(ThreadEntry),
 224    ViewMore {
 225        path_list: PathList,
 226        is_fully_expanded: bool,
 227    },
 228    NewThread {
 229        path_list: PathList,
 230        workspace: Entity<Workspace>,
 231        worktrees: Vec<WorktreeInfo>,
 232    },
 233}
 234
 235#[cfg(test)]
 236impl ListEntry {
 237    fn workspace(&self) -> Option<Entity<Workspace>> {
 238        match self {
 239            ListEntry::ProjectHeader { workspace, .. } => Some(workspace.clone()),
 240            ListEntry::Thread(thread_entry) => match &thread_entry.workspace {
 241                ThreadEntryWorkspace::Open(workspace) => Some(workspace.clone()),
 242                ThreadEntryWorkspace::Closed(_) => None,
 243            },
 244            ListEntry::ViewMore { .. } => None,
 245            ListEntry::NewThread { workspace, .. } => Some(workspace.clone()),
 246        }
 247    }
 248
 249    fn session_id(&self) -> Option<&acp::SessionId> {
 250        match self {
 251            ListEntry::Thread(thread_entry) => Some(&thread_entry.metadata.session_id),
 252            _ => None,
 253        }
 254    }
 255}
 256
 257impl From<ThreadEntry> for ListEntry {
 258    fn from(thread: ThreadEntry) -> Self {
 259        ListEntry::Thread(thread)
 260    }
 261}
 262
 263#[derive(Default)]
 264struct SidebarContents {
 265    entries: Vec<ListEntry>,
 266    notified_threads: HashSet<acp::SessionId>,
 267    project_header_indices: Vec<usize>,
 268    has_open_projects: bool,
 269}
 270
 271impl SidebarContents {
 272    fn is_thread_notified(&self, session_id: &acp::SessionId) -> bool {
 273        self.notified_threads.contains(session_id)
 274    }
 275}
 276
 277fn fuzzy_match_positions(query: &str, candidate: &str) -> Option<Vec<usize>> {
 278    let mut positions = Vec::new();
 279    let mut query_chars = query.chars().peekable();
 280
 281    for (byte_idx, candidate_char) in candidate.char_indices() {
 282        if let Some(&query_char) = query_chars.peek() {
 283            if candidate_char.eq_ignore_ascii_case(&query_char) {
 284                positions.push(byte_idx);
 285                query_chars.next();
 286            }
 287        } else {
 288            break;
 289        }
 290    }
 291
 292    if query_chars.peek().is_none() {
 293        Some(positions)
 294    } else {
 295        None
 296    }
 297}
 298
 299// TODO: The mapping from workspace root paths to git repositories needs a
 300// unified approach across the codebase: this function, `AgentPanel::classify_worktrees`,
 301// thread persistence (which PathList is saved to the database), and thread
 302// querying (which PathList is used to read threads back). All of these need
 303// to agree on how repos are resolved for a given workspace, especially in
 304// multi-root and nested-repo configurations.
 305fn root_repository_snapshots(
 306    workspace: &Entity<Workspace>,
 307    cx: &App,
 308) -> impl Iterator<Item = project::git_store::RepositorySnapshot> {
 309    let path_list = workspace_path_list(workspace, cx);
 310    let project = workspace.read(cx).project().read(cx);
 311    project.repositories(cx).values().filter_map(move |repo| {
 312        let snapshot = repo.read(cx).snapshot();
 313        let is_root = path_list
 314            .paths()
 315            .iter()
 316            .any(|p| p.as_path() == snapshot.work_directory_abs_path.as_ref());
 317        is_root.then_some(snapshot)
 318    })
 319}
 320
 321fn workspace_path_list(workspace: &Entity<Workspace>, cx: &App) -> PathList {
 322    PathList::new(&workspace.read(cx).root_paths(cx))
 323}
 324
 325/// Derives worktree display info from a thread's stored path list.
 326///
 327/// For each path in the thread's `folder_paths` that canonicalizes to a
 328/// different path (i.e. it's a git worktree), produces a [`WorktreeInfo`]
 329/// with the short worktree name and full path.
 330fn worktree_info_from_thread_paths(
 331    folder_paths: &PathList,
 332    project_groups: &ProjectGroupBuilder,
 333) -> Vec<WorktreeInfo> {
 334    folder_paths
 335        .paths()
 336        .iter()
 337        .filter_map(|path| {
 338            let canonical = project_groups.canonicalize_path(path);
 339            if canonical != path.as_path() {
 340                Some(WorktreeInfo {
 341                    name: linked_worktree_short_name(canonical, path).unwrap_or_default(),
 342                    full_path: SharedString::from(path.display().to_string()),
 343                    highlight_positions: Vec::new(),
 344                })
 345            } else {
 346                None
 347            }
 348        })
 349        .collect()
 350}
 351
 352/// The sidebar re-derives its entire entry list from scratch on every
 353/// change via `update_entries` → `rebuild_contents`. Avoid adding
 354/// incremental or inter-event coordination state — if something can
 355/// be computed from the current world state, compute it in the rebuild.
 356pub struct Sidebar {
 357    multi_workspace: WeakEntity<MultiWorkspace>,
 358    width: Pixels,
 359    focus_handle: FocusHandle,
 360    filter_editor: Entity<Editor>,
 361    list_state: ListState,
 362    contents: SidebarContents,
 363    /// The index of the list item that currently has the keyboard focus
 364    ///
 365    /// Note: This is NOT the same as the active item.
 366    selection: Option<usize>,
 367    /// Tracks which sidebar entry is currently active (highlighted).
 368    active_entry: Option<ActiveEntry>,
 369    hovered_thread_index: Option<usize>,
 370    collapsed_groups: HashSet<PathList>,
 371    expanded_groups: HashMap<PathList, usize>,
 372    /// Updated only in response to explicit user actions (clicking a
 373    /// thread, confirming in the thread switcher, etc.) — never from
 374    /// background data changes. Used to sort the thread switcher popup.
 375    thread_last_accessed: HashMap<acp::SessionId, DateTime<Utc>>,
 376    /// Updated when the user presses a key to send or queue a message.
 377    /// Used for sorting threads in the sidebar and as a secondary sort
 378    /// key in the thread switcher.
 379    thread_last_message_sent_or_queued: HashMap<acp::SessionId, DateTime<Utc>>,
 380    thread_switcher: Option<Entity<ThreadSwitcher>>,
 381    _thread_switcher_subscriptions: Vec<gpui::Subscription>,
 382    view: SidebarView,
 383    recent_projects_popover_handle: PopoverMenuHandle<SidebarRecentProjects>,
 384    project_header_menu_ix: Option<usize>,
 385    _subscriptions: Vec<gpui::Subscription>,
 386    _draft_observation: Option<gpui::Subscription>,
 387}
 388
 389fn find_main_repo_in_workspaces(
 390    workspaces: &[Entity<Workspace>],
 391    main_repo_path: &std::path::Path,
 392    cx: &App,
 393) -> Option<Entity<git_store::Repository>> {
 394    workspaces.iter().find_map(|workspace| {
 395        let project = workspace.read(cx).project().clone();
 396        project
 397            .read(cx)
 398            .repositories(cx)
 399            .values()
 400            .find_map(|repo_entity| {
 401                let repo = repo_entity.read(cx);
 402                (repo.is_main_worktree() && *repo.work_directory_abs_path == *main_repo_path)
 403                    .then(|| repo_entity.clone())
 404            })
 405    })
 406}
 407
 408impl Sidebar {
 409    pub fn new(
 410        multi_workspace: Entity<MultiWorkspace>,
 411        window: &mut Window,
 412        cx: &mut Context<Self>,
 413    ) -> Self {
 414        let focus_handle = cx.focus_handle();
 415        cx.on_focus_in(&focus_handle, window, Self::focus_in)
 416            .detach();
 417
 418        let filter_editor = cx.new(|cx| {
 419            let mut editor = Editor::single_line(window, cx);
 420            editor.set_use_modal_editing(true);
 421            editor.set_placeholder_text("Search…", window, cx);
 422            editor
 423        });
 424
 425        cx.subscribe_in(
 426            &multi_workspace,
 427            window,
 428            |this, _multi_workspace, event: &MultiWorkspaceEvent, window, cx| match event {
 429                MultiWorkspaceEvent::ActiveWorkspaceChanged => {
 430                    this.observe_draft_editor(cx);
 431                    this.update_entries(cx);
 432                }
 433                MultiWorkspaceEvent::WorkspaceAdded(workspace) => {
 434                    this.subscribe_to_workspace(workspace, window, cx);
 435                    this.update_entries(cx);
 436                }
 437                MultiWorkspaceEvent::WorkspaceRemoved(_) => {
 438                    this.update_entries(cx);
 439                }
 440            },
 441        )
 442        .detach();
 443
 444        cx.subscribe(&filter_editor, |this: &mut Self, _, event, cx| {
 445            if let editor::EditorEvent::BufferEdited = event {
 446                let query = this.filter_editor.read(cx).text(cx);
 447                if !query.is_empty() {
 448                    this.selection.take();
 449                }
 450                this.update_entries(cx);
 451                if !query.is_empty() {
 452                    this.select_first_entry();
 453                }
 454            }
 455        })
 456        .detach();
 457
 458        cx.observe(&ThreadMetadataStore::global(cx), |this, _store, cx| {
 459            this.update_entries(cx);
 460        })
 461        .detach();
 462
 463        cx.observe_flag::<AgentV2FeatureFlag, _>(window, |_is_enabled, this, _window, cx| {
 464            this.update_entries(cx);
 465        })
 466        .detach();
 467
 468        let workspaces = multi_workspace.read(cx).workspaces().to_vec();
 469        cx.defer_in(window, move |this, window, cx| {
 470            for workspace in &workspaces {
 471                this.subscribe_to_workspace(workspace, window, cx);
 472            }
 473            this.update_entries(cx);
 474        });
 475
 476        Self {
 477            multi_workspace: multi_workspace.downgrade(),
 478            width: DEFAULT_WIDTH,
 479            focus_handle,
 480            filter_editor,
 481            list_state: ListState::new(0, gpui::ListAlignment::Top, px(1000.)),
 482            contents: SidebarContents::default(),
 483            selection: None,
 484            active_entry: None,
 485            hovered_thread_index: None,
 486            collapsed_groups: HashSet::new(),
 487            expanded_groups: HashMap::new(),
 488            thread_last_accessed: HashMap::new(),
 489            thread_last_message_sent_or_queued: HashMap::new(),
 490            thread_switcher: None,
 491            _thread_switcher_subscriptions: Vec::new(),
 492            view: SidebarView::default(),
 493            recent_projects_popover_handle: PopoverMenuHandle::default(),
 494            project_header_menu_ix: None,
 495            _subscriptions: Vec::new(),
 496            _draft_observation: None,
 497        }
 498    }
 499
 500    fn serialize(&mut self, cx: &mut Context<Self>) {
 501        cx.emit(workspace::SidebarEvent::SerializeNeeded);
 502    }
 503
 504    fn active_entry_workspace(&self) -> Option<&Entity<Workspace>> {
 505        self.active_entry.as_ref().map(|entry| entry.workspace())
 506    }
 507
 508    fn is_active_workspace(&self, workspace: &Entity<Workspace>, cx: &App) -> bool {
 509        self.multi_workspace
 510            .upgrade()
 511            .map_or(false, |mw| mw.read(cx).workspace() == workspace)
 512    }
 513
 514    fn subscribe_to_workspace(
 515        &mut self,
 516        workspace: &Entity<Workspace>,
 517        window: &mut Window,
 518        cx: &mut Context<Self>,
 519    ) {
 520        let project = workspace.read(cx).project().clone();
 521        cx.subscribe_in(
 522            &project,
 523            window,
 524            |this, _project, event, _window, cx| match event {
 525                ProjectEvent::WorktreeAdded(_)
 526                | ProjectEvent::WorktreeRemoved(_)
 527                | ProjectEvent::WorktreeOrderChanged => {
 528                    this.update_entries(cx);
 529                }
 530                _ => {}
 531            },
 532        )
 533        .detach();
 534
 535        let git_store = workspace.read(cx).project().read(cx).git_store().clone();
 536        cx.subscribe_in(
 537            &git_store,
 538            window,
 539            |this, _, event: &project::git_store::GitStoreEvent, _window, cx| {
 540                if matches!(
 541                    event,
 542                    project::git_store::GitStoreEvent::RepositoryUpdated(
 543                        _,
 544                        project::git_store::RepositoryEvent::GitWorktreeListChanged,
 545                        _,
 546                    )
 547                ) {
 548                    this.update_entries(cx);
 549                }
 550            },
 551        )
 552        .detach();
 553
 554        cx.subscribe_in(
 555            workspace,
 556            window,
 557            |this, _workspace, event: &workspace::Event, window, cx| {
 558                if let workspace::Event::PanelAdded(view) = event {
 559                    if let Ok(agent_panel) = view.clone().downcast::<AgentPanel>() {
 560                        this.subscribe_to_agent_panel(&agent_panel, window, cx);
 561                    }
 562                }
 563            },
 564        )
 565        .detach();
 566
 567        self.observe_docks(workspace, cx);
 568
 569        if let Some(agent_panel) = workspace.read(cx).panel::<AgentPanel>(cx) {
 570            self.subscribe_to_agent_panel(&agent_panel, window, cx);
 571            self.observe_draft_editor(cx);
 572        }
 573    }
 574
 575    fn subscribe_to_agent_panel(
 576        &mut self,
 577        agent_panel: &Entity<AgentPanel>,
 578        window: &mut Window,
 579        cx: &mut Context<Self>,
 580    ) {
 581        cx.subscribe_in(
 582            agent_panel,
 583            window,
 584            |this, agent_panel, event: &AgentPanelEvent, _window, cx| match event {
 585                AgentPanelEvent::ActiveViewChanged => {
 586                    let is_new_draft = agent_panel
 587                        .read(cx)
 588                        .active_conversation_view()
 589                        .is_some_and(|cv| cv.read(cx).parent_id(cx).is_none());
 590                    if is_new_draft {
 591                        if let Some(active_workspace) = this
 592                            .multi_workspace
 593                            .upgrade()
 594                            .map(|mw| mw.read(cx).workspace().clone())
 595                        {
 596                            this.active_entry = Some(ActiveEntry::Draft(active_workspace));
 597                        }
 598                    }
 599                    this.observe_draft_editor(cx);
 600                    this.update_entries(cx);
 601                }
 602                AgentPanelEvent::ThreadFocused | AgentPanelEvent::BackgroundThreadChanged => {
 603                    this.update_entries(cx);
 604                }
 605                AgentPanelEvent::MessageSentOrQueued { session_id } => {
 606                    this.record_thread_message_sent(session_id);
 607                    this.update_entries(cx);
 608                }
 609            },
 610        )
 611        .detach();
 612    }
 613
 614    fn observe_docks(&mut self, workspace: &Entity<Workspace>, cx: &mut Context<Self>) {
 615        let docks: Vec<_> = workspace
 616            .read(cx)
 617            .all_docks()
 618            .into_iter()
 619            .cloned()
 620            .collect();
 621        let workspace = workspace.downgrade();
 622        for dock in docks {
 623            let workspace = workspace.clone();
 624            cx.observe(&dock, move |this, _dock, cx| {
 625                let Some(workspace) = workspace.upgrade() else {
 626                    return;
 627                };
 628                if !this.is_active_workspace(&workspace, cx) {
 629                    return;
 630                }
 631
 632                cx.notify();
 633            })
 634            .detach();
 635        }
 636    }
 637
 638    fn observe_draft_editor(&mut self, cx: &mut Context<Self>) {
 639        self._draft_observation = self
 640            .multi_workspace
 641            .upgrade()
 642            .and_then(|mw| {
 643                let ws = mw.read(cx).workspace();
 644                ws.read(cx).panel::<AgentPanel>(cx)
 645            })
 646            .and_then(|panel| {
 647                let cv = panel.read(cx).active_conversation_view()?;
 648                let tv = cv.read(cx).active_thread()?;
 649                Some(tv.read(cx).message_editor.clone())
 650            })
 651            .map(|editor| {
 652                cx.observe(&editor, |_this, _editor, cx| {
 653                    cx.notify();
 654                })
 655            });
 656    }
 657
 658    fn active_draft_text(&self, cx: &App) -> Option<SharedString> {
 659        let mw = self.multi_workspace.upgrade()?;
 660        let workspace = mw.read(cx).workspace();
 661        let panel = workspace.read(cx).panel::<AgentPanel>(cx)?;
 662        let conversation_view = panel.read(cx).active_conversation_view()?;
 663        let thread_view = conversation_view.read(cx).active_thread()?;
 664        let raw = thread_view.read(cx).message_editor.read(cx).text(cx);
 665        let cleaned = Self::clean_mention_links(&raw);
 666        let mut text: String = cleaned.split_whitespace().collect::<Vec<_>>().join(" ");
 667        if text.is_empty() {
 668            None
 669        } else {
 670            const MAX_CHARS: usize = 250;
 671            if let Some((truncate_at, _)) = text.char_indices().nth(MAX_CHARS) {
 672                text.truncate(truncate_at);
 673            }
 674            Some(text.into())
 675        }
 676    }
 677
 678    fn clean_mention_links(input: &str) -> String {
 679        let mut result = String::with_capacity(input.len());
 680        let mut remaining = input;
 681
 682        while let Some(start) = remaining.find("[@") {
 683            result.push_str(&remaining[..start]);
 684            let after_bracket = &remaining[start + 1..]; // skip '['
 685            if let Some(close_bracket) = after_bracket.find("](") {
 686                let mention = &after_bracket[..close_bracket]; // "@something"
 687                let after_link_start = &after_bracket[close_bracket + 2..]; // after "]("
 688                if let Some(close_paren) = after_link_start.find(')') {
 689                    result.push_str(mention);
 690                    remaining = &after_link_start[close_paren + 1..];
 691                    continue;
 692                }
 693            }
 694            // Couldn't parse full link syntax — emit the literal "[@" and move on.
 695            result.push_str("[@");
 696            remaining = &remaining[start + 2..];
 697        }
 698        result.push_str(remaining);
 699        result
 700    }
 701
 702    /// Rebuilds the sidebar contents from current workspace and thread state.
 703    ///
 704    /// Uses [`ProjectGroupBuilder`] to group workspaces by their main git
 705    /// repository, then populates thread entries from the metadata store and
 706    /// merges live thread info from active agent panels.
 707    ///
 708    /// Aim for a single forward pass over workspaces and threads plus an
 709    /// O(T log T) sort. Avoid adding extra scans over the data.
 710    ///
 711    /// Properties:
 712    ///
 713    /// - Should always show every workspace in the multiworkspace
 714    ///     - If you have no threads, and two workspaces for the worktree and the main workspace, make sure at least one is shown
 715    /// - Should always show every thread, associated with each workspace in the multiworkspace
 716    /// - After every build_contents, our "active" state should exactly match the current workspace's, current agent panel's current thread.
 717    fn rebuild_contents(&mut self, cx: &App) {
 718        let Some(multi_workspace) = self.multi_workspace.upgrade() else {
 719            return;
 720        };
 721        let mw = multi_workspace.read(cx);
 722        let workspaces = mw.workspaces().to_vec();
 723        let active_workspace = mw.workspaces().get(mw.active_workspace_index()).cloned();
 724
 725        let agent_server_store = workspaces
 726            .first()
 727            .map(|ws| ws.read(cx).project().read(cx).agent_server_store().clone());
 728
 729        let query = self.filter_editor.read(cx).text(cx);
 730
 731        // Derive active_entry from the active workspace's agent panel.
 732        // Draft is checked first because a conversation can have a session_id
 733        // before any messages are sent. However, a thread that's still loading
 734        // also appears as a "draft" (no messages yet), so when we already have
 735        // an eager Thread write for this workspace we preserve it. A session_id
 736        // on a non-draft is a positive Thread signal. The remaining case
 737        // (conversation exists, not draft, no session_id) is a genuine
 738        // mid-load — keep the previous value.
 739        if let Some(active_ws) = &active_workspace {
 740            if let Some(panel) = active_ws.read(cx).panel::<AgentPanel>(cx) {
 741                if panel.read(cx).active_thread_is_draft(cx)
 742                    || panel.read(cx).active_conversation_view().is_none()
 743                {
 744                    let preserving_thread =
 745                        matches!(&self.active_entry, Some(ActiveEntry::Thread { .. }))
 746                            && self.active_entry_workspace() == Some(active_ws);
 747                    if !preserving_thread {
 748                        self.active_entry = Some(ActiveEntry::Draft(active_ws.clone()));
 749                    }
 750                } else if let Some(session_id) = panel
 751                    .read(cx)
 752                    .active_conversation_view()
 753                    .and_then(|cv| cv.read(cx).parent_id(cx))
 754                {
 755                    self.active_entry = Some(ActiveEntry::Thread {
 756                        session_id,
 757                        workspace: active_ws.clone(),
 758                    });
 759                }
 760                // else: conversation exists, not a draft, but no session_id
 761                // yet — thread is mid-load. Keep previous value.
 762            }
 763        }
 764
 765        let previous = mem::take(&mut self.contents);
 766
 767        let old_statuses: HashMap<acp::SessionId, AgentThreadStatus> = previous
 768            .entries
 769            .iter()
 770            .filter_map(|entry| match entry {
 771                ListEntry::Thread(thread) if thread.is_live => {
 772                    Some((thread.metadata.session_id.clone(), thread.status))
 773                }
 774                _ => None,
 775            })
 776            .collect();
 777
 778        let mut entries = Vec::new();
 779        let mut notified_threads = previous.notified_threads;
 780        let mut current_session_ids: HashSet<acp::SessionId> = HashSet::new();
 781        let mut project_header_indices: Vec<usize> = Vec::new();
 782
 783        // Use ProjectGroupBuilder to canonically group workspaces by their
 784        // main git repository. This replaces the manual absorbed-workspace
 785        // detection that was here before.
 786        let project_groups = ProjectGroupBuilder::from_multiworkspace(mw, cx);
 787
 788        let has_open_projects = workspaces
 789            .iter()
 790            .any(|ws| !workspace_path_list(ws, cx).paths().is_empty());
 791
 792        let resolve_agent_icon = |agent_id: &AgentId| -> (IconName, Option<SharedString>) {
 793            let agent = Agent::from(agent_id.clone());
 794            let icon = match agent {
 795                Agent::NativeAgent => IconName::ZedAgent,
 796                Agent::Custom { .. } => IconName::Terminal,
 797            };
 798            let icon_from_external_svg = agent_server_store
 799                .as_ref()
 800                .and_then(|store| store.read(cx).agent_icon(&agent_id));
 801            (icon, icon_from_external_svg)
 802        };
 803
 804        for (group_name, group) in project_groups.groups() {
 805            let path_list = group_name.path_list().clone();
 806            if path_list.paths().is_empty() {
 807                continue;
 808            }
 809
 810            let label = group_name.display_name();
 811
 812            let is_collapsed = self.collapsed_groups.contains(&path_list);
 813            let should_load_threads = !is_collapsed || !query.is_empty();
 814
 815            let is_active = active_workspace
 816                .as_ref()
 817                .is_some_and(|active| group.workspaces.contains(active));
 818
 819            // Pick a representative workspace for the group: prefer the active
 820            // workspace if it belongs to this group, otherwise use the main
 821            // repo workspace (not a linked worktree).
 822            let representative_workspace = active_workspace
 823                .as_ref()
 824                .filter(|_| is_active)
 825                .unwrap_or_else(|| group.main_workspace(cx));
 826
 827            // Collect live thread infos from all workspaces in this group.
 828            let live_infos: Vec<_> = group
 829                .workspaces
 830                .iter()
 831                .flat_map(|ws| all_thread_infos_for_workspace(ws, cx))
 832                .collect();
 833
 834            let mut threads: Vec<ThreadEntry> = Vec::new();
 835            let mut threadless_workspaces: Vec<(Entity<Workspace>, Vec<WorktreeInfo>)> = Vec::new();
 836            let mut has_running_threads = false;
 837            let mut waiting_thread_count: usize = 0;
 838
 839            if should_load_threads {
 840                let mut seen_session_ids: HashSet<acp::SessionId> = HashSet::new();
 841                let thread_store = ThreadMetadataStore::global(cx);
 842
 843                // Load threads from each workspace in the group.
 844                for workspace in &group.workspaces {
 845                    let ws_path_list = workspace_path_list(workspace, cx);
 846                    let mut workspace_rows = thread_store
 847                        .read(cx)
 848                        .entries_for_path(&ws_path_list)
 849                        .cloned()
 850                        .peekable();
 851                    if workspace_rows.peek().is_none() {
 852                        let worktrees =
 853                            worktree_info_from_thread_paths(&ws_path_list, &project_groups);
 854                        threadless_workspaces.push((workspace.clone(), worktrees));
 855                    }
 856                    for row in workspace_rows {
 857                        if !seen_session_ids.insert(row.session_id.clone()) {
 858                            continue;
 859                        }
 860                        let (icon, icon_from_external_svg) = resolve_agent_icon(&row.agent_id);
 861                        let worktrees =
 862                            worktree_info_from_thread_paths(&row.folder_paths, &project_groups);
 863                        threads.push(ThreadEntry {
 864                            metadata: row,
 865                            icon,
 866                            icon_from_external_svg,
 867                            status: AgentThreadStatus::default(),
 868                            workspace: ThreadEntryWorkspace::Open(workspace.clone()),
 869                            is_live: false,
 870                            is_background: false,
 871                            is_title_generating: false,
 872                            highlight_positions: Vec::new(),
 873                            worktrees,
 874                            diff_stats: DiffStats::default(),
 875                        });
 876                    }
 877                }
 878
 879                // Load threads from linked git worktrees whose
 880                // canonical paths belong to this group.
 881                let linked_worktree_queries = group
 882                    .workspaces
 883                    .iter()
 884                    .flat_map(|ws| root_repository_snapshots(ws, cx))
 885                    .filter(|snapshot| !snapshot.is_linked_worktree())
 886                    .flat_map(|snapshot| {
 887                        snapshot
 888                            .linked_worktrees()
 889                            .iter()
 890                            .filter(|wt| {
 891                                project_groups.group_owns_worktree(group, &path_list, &wt.path)
 892                            })
 893                            .map(|wt| PathList::new(std::slice::from_ref(&wt.path)))
 894                            .collect::<Vec<_>>()
 895                    });
 896
 897                for worktree_path_list in linked_worktree_queries {
 898                    for row in thread_store
 899                        .read(cx)
 900                        .entries_for_path(&worktree_path_list)
 901                        .cloned()
 902                    {
 903                        if !seen_session_ids.insert(row.session_id.clone()) {
 904                            continue;
 905                        }
 906                        let (icon, icon_from_external_svg) = resolve_agent_icon(&row.agent_id);
 907                        let worktrees =
 908                            worktree_info_from_thread_paths(&row.folder_paths, &project_groups);
 909                        threads.push(ThreadEntry {
 910                            metadata: row,
 911                            icon,
 912                            icon_from_external_svg,
 913                            status: AgentThreadStatus::default(),
 914                            workspace: ThreadEntryWorkspace::Closed(worktree_path_list.clone()),
 915                            is_live: false,
 916                            is_background: false,
 917                            is_title_generating: false,
 918                            highlight_positions: Vec::new(),
 919                            worktrees,
 920                            diff_stats: DiffStats::default(),
 921                        });
 922                    }
 923                }
 924
 925                // Build a lookup from live_infos and compute running/waiting
 926                // counts in a single pass.
 927                let mut live_info_by_session: HashMap<&acp::SessionId, &ActiveThreadInfo> =
 928                    HashMap::new();
 929                for info in &live_infos {
 930                    live_info_by_session.insert(&info.session_id, info);
 931                    if info.status == AgentThreadStatus::Running {
 932                        has_running_threads = true;
 933                    }
 934                    if info.status == AgentThreadStatus::WaitingForConfirmation {
 935                        waiting_thread_count += 1;
 936                    }
 937                }
 938
 939                // Merge live info into threads and update notification state
 940                // in a single pass.
 941                for thread in &mut threads {
 942                    if let Some(info) = live_info_by_session.get(&thread.metadata.session_id) {
 943                        thread.apply_active_info(info);
 944                    }
 945
 946                    let session_id = &thread.metadata.session_id;
 947
 948                    let is_thread_workspace_active = match &thread.workspace {
 949                        ThreadEntryWorkspace::Open(thread_workspace) => active_workspace
 950                            .as_ref()
 951                            .is_some_and(|active| active == thread_workspace),
 952                        ThreadEntryWorkspace::Closed(_) => false,
 953                    };
 954
 955                    if thread.status == AgentThreadStatus::Completed
 956                        && !is_thread_workspace_active
 957                        && old_statuses.get(session_id) == Some(&AgentThreadStatus::Running)
 958                    {
 959                        notified_threads.insert(session_id.clone());
 960                    }
 961
 962                    if is_thread_workspace_active && !thread.is_background {
 963                        notified_threads.remove(session_id);
 964                    }
 965                }
 966
 967                threads.sort_by(|a, b| {
 968                    let a_time = self
 969                        .thread_last_message_sent_or_queued
 970                        .get(&a.metadata.session_id)
 971                        .copied()
 972                        .or(a.metadata.created_at)
 973                        .or(Some(a.metadata.updated_at));
 974                    let b_time = self
 975                        .thread_last_message_sent_or_queued
 976                        .get(&b.metadata.session_id)
 977                        .copied()
 978                        .or(b.metadata.created_at)
 979                        .or(Some(b.metadata.updated_at));
 980                    b_time.cmp(&a_time)
 981                });
 982            } else {
 983                for info in live_infos {
 984                    if info.status == AgentThreadStatus::Running {
 985                        has_running_threads = true;
 986                    }
 987                    if info.status == AgentThreadStatus::WaitingForConfirmation {
 988                        waiting_thread_count += 1;
 989                    }
 990                }
 991            }
 992
 993            if !query.is_empty() {
 994                let workspace_highlight_positions =
 995                    fuzzy_match_positions(&query, &label).unwrap_or_default();
 996                let workspace_matched = !workspace_highlight_positions.is_empty();
 997
 998                let mut matched_threads: Vec<ThreadEntry> = Vec::new();
 999                for mut thread in threads {
1000                    let title: &str = &thread.metadata.title;
1001                    if let Some(positions) = fuzzy_match_positions(&query, title) {
1002                        thread.highlight_positions = positions;
1003                    }
1004                    let mut worktree_matched = false;
1005                    for worktree in &mut thread.worktrees {
1006                        if let Some(positions) = fuzzy_match_positions(&query, &worktree.name) {
1007                            worktree.highlight_positions = positions;
1008                            worktree_matched = true;
1009                        }
1010                    }
1011                    if workspace_matched
1012                        || !thread.highlight_positions.is_empty()
1013                        || worktree_matched
1014                    {
1015                        matched_threads.push(thread);
1016                    }
1017                }
1018
1019                if matched_threads.is_empty() && !workspace_matched {
1020                    continue;
1021                }
1022
1023                project_header_indices.push(entries.len());
1024                entries.push(ListEntry::ProjectHeader {
1025                    path_list: path_list.clone(),
1026                    label,
1027                    workspace: representative_workspace.clone(),
1028                    highlight_positions: workspace_highlight_positions,
1029                    has_running_threads,
1030                    waiting_thread_count,
1031                    is_active,
1032                });
1033
1034                for thread in matched_threads {
1035                    current_session_ids.insert(thread.metadata.session_id.clone());
1036                    entries.push(thread.into());
1037                }
1038            } else {
1039                let is_draft_for_workspace = is_active
1040                    && matches!(&self.active_entry, Some(ActiveEntry::Draft(_)))
1041                    && self.active_entry_workspace() == Some(representative_workspace);
1042
1043                project_header_indices.push(entries.len());
1044                entries.push(ListEntry::ProjectHeader {
1045                    path_list: path_list.clone(),
1046                    label,
1047                    workspace: representative_workspace.clone(),
1048                    highlight_positions: Vec::new(),
1049                    has_running_threads,
1050                    waiting_thread_count,
1051                    is_active,
1052                });
1053
1054                if is_collapsed {
1055                    continue;
1056                }
1057
1058                // Emit "New Thread" entries for threadless workspaces
1059                // and active drafts, right after the header.
1060                for (workspace, worktrees) in &threadless_workspaces {
1061                    entries.push(ListEntry::NewThread {
1062                        path_list: path_list.clone(),
1063                        workspace: workspace.clone(),
1064                        worktrees: worktrees.clone(),
1065                    });
1066                }
1067                if is_draft_for_workspace
1068                    && !threadless_workspaces
1069                        .iter()
1070                        .any(|(ws, _)| ws == representative_workspace)
1071                {
1072                    let ws_path_list = workspace_path_list(representative_workspace, cx);
1073                    let worktrees = worktree_info_from_thread_paths(&ws_path_list, &project_groups);
1074                    entries.push(ListEntry::NewThread {
1075                        path_list: path_list.clone(),
1076                        workspace: representative_workspace.clone(),
1077                        worktrees,
1078                    });
1079                }
1080
1081                let total = threads.len();
1082
1083                let extra_batches = self.expanded_groups.get(&path_list).copied().unwrap_or(0);
1084                let threads_to_show =
1085                    DEFAULT_THREADS_SHOWN + (extra_batches * DEFAULT_THREADS_SHOWN);
1086                let count = threads_to_show.min(total);
1087
1088                let mut promoted_threads: HashSet<acp::SessionId> = HashSet::new();
1089
1090                // Build visible entries in a single pass. Threads within
1091                // the cutoff are always shown. Threads beyond it are shown
1092                // only if they should be promoted (running, waiting, or
1093                // focused)
1094                for (index, thread) in threads.into_iter().enumerate() {
1095                    let is_hidden = index >= count;
1096
1097                    let session_id = &thread.metadata.session_id;
1098                    if is_hidden {
1099                        let is_promoted = thread.status == AgentThreadStatus::Running
1100                            || thread.status == AgentThreadStatus::WaitingForConfirmation
1101                            || notified_threads.contains(session_id)
1102                            || self.active_entry.as_ref().is_some_and(|active| {
1103                                active.matches_entry(&ListEntry::Thread(thread.clone()))
1104                            });
1105                        if is_promoted {
1106                            promoted_threads.insert(session_id.clone());
1107                        }
1108                        if !promoted_threads.contains(session_id) {
1109                            continue;
1110                        }
1111                    }
1112
1113                    current_session_ids.insert(session_id.clone());
1114                    entries.push(thread.into());
1115                }
1116
1117                let visible = count + promoted_threads.len();
1118                let is_fully_expanded = visible >= total;
1119
1120                if total > DEFAULT_THREADS_SHOWN {
1121                    entries.push(ListEntry::ViewMore {
1122                        path_list: path_list.clone(),
1123                        is_fully_expanded,
1124                    });
1125                }
1126            }
1127        }
1128
1129        // Prune stale notifications using the session IDs we collected during
1130        // the build pass (no extra scan needed).
1131        notified_threads.retain(|id| current_session_ids.contains(id));
1132
1133        self.thread_last_accessed
1134            .retain(|id, _| current_session_ids.contains(id));
1135        self.thread_last_message_sent_or_queued
1136            .retain(|id, _| current_session_ids.contains(id));
1137
1138        self.contents = SidebarContents {
1139            entries,
1140            notified_threads,
1141            project_header_indices,
1142            has_open_projects,
1143        };
1144    }
1145
1146    /// Rebuilds the sidebar's visible entries from already-cached state.
1147    fn update_entries(&mut self, cx: &mut Context<Self>) {
1148        let Some(multi_workspace) = self.multi_workspace.upgrade() else {
1149            return;
1150        };
1151        if !multi_workspace.read(cx).multi_workspace_enabled(cx) {
1152            return;
1153        }
1154
1155        let had_notifications = self.has_notifications(cx);
1156        let scroll_position = self.list_state.logical_scroll_top();
1157
1158        self.rebuild_contents(cx);
1159
1160        self.list_state.reset(self.contents.entries.len());
1161        self.list_state.scroll_to(scroll_position);
1162
1163        if had_notifications != self.has_notifications(cx) {
1164            multi_workspace.update(cx, |_, cx| {
1165                cx.notify();
1166            });
1167        }
1168
1169        cx.notify();
1170    }
1171
1172    fn select_first_entry(&mut self) {
1173        self.selection = self
1174            .contents
1175            .entries
1176            .iter()
1177            .position(|entry| matches!(entry, ListEntry::Thread(_)))
1178            .or_else(|| {
1179                if self.contents.entries.is_empty() {
1180                    None
1181                } else {
1182                    Some(0)
1183                }
1184            });
1185    }
1186
1187    fn render_list_entry(
1188        &mut self,
1189        ix: usize,
1190        window: &mut Window,
1191        cx: &mut Context<Self>,
1192    ) -> AnyElement {
1193        let Some(entry) = self.contents.entries.get(ix) else {
1194            return div().into_any_element();
1195        };
1196        let is_focused = self.focus_handle.is_focused(window);
1197        // is_selected means the keyboard selector is here.
1198        let is_selected = is_focused && self.selection == Some(ix);
1199
1200        let is_group_header_after_first =
1201            ix > 0 && matches!(entry, ListEntry::ProjectHeader { .. });
1202
1203        let is_active = self
1204            .active_entry
1205            .as_ref()
1206            .is_some_and(|active| active.matches_entry(entry));
1207
1208        let rendered = match entry {
1209            ListEntry::ProjectHeader {
1210                path_list,
1211                label,
1212                workspace,
1213                highlight_positions,
1214                has_running_threads,
1215                waiting_thread_count,
1216                is_active: is_active_group,
1217            } => self.render_project_header(
1218                ix,
1219                false,
1220                path_list,
1221                label,
1222                workspace,
1223                highlight_positions,
1224                *has_running_threads,
1225                *waiting_thread_count,
1226                *is_active_group,
1227                is_selected,
1228                cx,
1229            ),
1230            ListEntry::Thread(thread) => self.render_thread(ix, thread, is_active, is_selected, cx),
1231            ListEntry::ViewMore {
1232                path_list,
1233                is_fully_expanded,
1234            } => self.render_view_more(ix, path_list, *is_fully_expanded, is_selected, cx),
1235            ListEntry::NewThread {
1236                path_list,
1237                workspace,
1238                worktrees,
1239            } => self.render_new_thread(
1240                ix,
1241                path_list,
1242                workspace,
1243                is_active,
1244                worktrees,
1245                is_selected,
1246                cx,
1247            ),
1248        };
1249
1250        if is_group_header_after_first {
1251            v_flex()
1252                .w_full()
1253                .border_t_1()
1254                .border_color(cx.theme().colors().border.opacity(0.5))
1255                .child(rendered)
1256                .into_any_element()
1257        } else {
1258            rendered
1259        }
1260    }
1261
1262    fn render_remote_project_icon(
1263        &self,
1264        ix: usize,
1265        workspace: &Entity<Workspace>,
1266        cx: &mut Context<Self>,
1267    ) -> Option<AnyElement> {
1268        let project = workspace.read(cx).project().read(cx);
1269        let remote_connection_options = project.remote_connection_options(cx)?;
1270
1271        let remote_icon_per_type = match remote_connection_options {
1272            RemoteConnectionOptions::Wsl(_) => IconName::Linux,
1273            RemoteConnectionOptions::Docker(_) => IconName::Box,
1274            _ => IconName::Server,
1275        };
1276
1277        Some(
1278            div()
1279                .id(format!("remote-project-icon-{}", ix))
1280                .child(
1281                    Icon::new(remote_icon_per_type)
1282                        .size(IconSize::XSmall)
1283                        .color(Color::Muted),
1284                )
1285                .tooltip(Tooltip::text("Remote Project"))
1286                .into_any_element(),
1287        )
1288    }
1289
1290    fn render_project_header(
1291        &self,
1292        ix: usize,
1293        is_sticky: bool,
1294        path_list: &PathList,
1295        label: &SharedString,
1296        workspace: &Entity<Workspace>,
1297        highlight_positions: &[usize],
1298        has_running_threads: bool,
1299        waiting_thread_count: usize,
1300        is_active: bool,
1301        is_selected: bool,
1302        cx: &mut Context<Self>,
1303    ) -> AnyElement {
1304        let id_prefix = if is_sticky { "sticky-" } else { "" };
1305        let id = SharedString::from(format!("{id_prefix}project-header-{ix}"));
1306        let disclosure_id = SharedString::from(format!("disclosure-{ix}"));
1307        let group_name = SharedString::from(format!("{id_prefix}header-group-{ix}"));
1308
1309        let is_collapsed = self.collapsed_groups.contains(path_list);
1310        let (disclosure_icon, disclosure_tooltip) = if is_collapsed {
1311            (IconName::ChevronRight, "Expand Project")
1312        } else {
1313            (IconName::ChevronDown, "Collapse Project")
1314        };
1315
1316        let has_new_thread_entry = self
1317            .contents
1318            .entries
1319            .get(ix + 1)
1320            .is_some_and(|entry| matches!(entry, ListEntry::NewThread { .. }));
1321        let show_new_thread_button = !has_new_thread_entry && !self.has_filter_query(cx);
1322
1323        let workspace_for_remove = workspace.clone();
1324        let workspace_for_menu = workspace.clone();
1325        let workspace_for_open = workspace.clone();
1326
1327        let path_list_for_toggle = path_list.clone();
1328        let path_list_for_collapse = path_list.clone();
1329        let view_more_expanded = self.expanded_groups.contains_key(path_list);
1330
1331        let label = if highlight_positions.is_empty() {
1332            Label::new(label.clone())
1333                .color(Color::Muted)
1334                .into_any_element()
1335        } else {
1336            HighlightedLabel::new(label.clone(), highlight_positions.to_vec())
1337                .color(Color::Muted)
1338                .into_any_element()
1339        };
1340
1341        let color = cx.theme().colors();
1342        let hover_color = color
1343            .element_active
1344            .blend(color.element_background.opacity(0.2));
1345
1346        h_flex()
1347            .id(id)
1348            .group(&group_name)
1349            .h(Tab::content_height(cx))
1350            .w_full()
1351            .pl(px(5.))
1352            .pr_1p5()
1353            .border_1()
1354            .map(|this| {
1355                if is_selected {
1356                    this.border_color(color.border_focused)
1357                } else {
1358                    this.border_color(gpui::transparent_black())
1359                }
1360            })
1361            .justify_between()
1362            .hover(|s| s.bg(hover_color))
1363            .child(
1364                h_flex()
1365                    .when(!is_active, |this| this.cursor_pointer())
1366                    .relative()
1367                    .min_w_0()
1368                    .w_full()
1369                    .gap(px(5.))
1370                    .child(
1371                        IconButton::new(disclosure_id, disclosure_icon)
1372                            .shape(ui::IconButtonShape::Square)
1373                            .icon_size(IconSize::Small)
1374                            .icon_color(Color::Custom(cx.theme().colors().icon_muted.opacity(0.5)))
1375                            .tooltip(Tooltip::text(disclosure_tooltip))
1376                            .on_click(cx.listener(move |this, _, window, cx| {
1377                                this.selection = None;
1378                                this.toggle_collapse(&path_list_for_toggle, window, cx);
1379                            })),
1380                    )
1381                    .child(label)
1382                    .when_some(
1383                        self.render_remote_project_icon(ix, workspace, cx),
1384                        |this, icon| this.child(icon),
1385                    )
1386                    .when(is_collapsed, |this| {
1387                        this.when(has_running_threads, |this| {
1388                            this.child(
1389                                Icon::new(IconName::LoadCircle)
1390                                    .size(IconSize::XSmall)
1391                                    .color(Color::Muted)
1392                                    .with_rotate_animation(2),
1393                            )
1394                        })
1395                        .when(waiting_thread_count > 0, |this| {
1396                            let tooltip_text = if waiting_thread_count == 1 {
1397                                "1 thread is waiting for confirmation".to_string()
1398                            } else {
1399                                format!(
1400                                    "{waiting_thread_count} threads are waiting for confirmation",
1401                                )
1402                            };
1403                            this.child(
1404                                div()
1405                                    .id(format!("{id_prefix}waiting-indicator-{ix}"))
1406                                    .child(
1407                                        Icon::new(IconName::Warning)
1408                                            .size(IconSize::XSmall)
1409                                            .color(Color::Warning),
1410                                    )
1411                                    .tooltip(Tooltip::text(tooltip_text)),
1412                            )
1413                        })
1414                    }),
1415            )
1416            .child({
1417                let workspace_for_new_thread = workspace.clone();
1418                let path_list_for_new_thread = path_list.clone();
1419
1420                h_flex()
1421                    .when(self.project_header_menu_ix != Some(ix), |this| {
1422                        this.visible_on_hover(group_name)
1423                    })
1424                    .on_mouse_down(gpui::MouseButton::Left, |_, _, cx| {
1425                        cx.stop_propagation();
1426                    })
1427                    .child(self.render_project_header_menu(
1428                        ix,
1429                        id_prefix,
1430                        &workspace_for_menu,
1431                        &workspace_for_remove,
1432                        cx,
1433                    ))
1434                    .when(view_more_expanded && !is_collapsed, |this| {
1435                        this.child(
1436                            IconButton::new(
1437                                SharedString::from(format!(
1438                                    "{id_prefix}project-header-collapse-{ix}",
1439                                )),
1440                                IconName::ListCollapse,
1441                            )
1442                            .icon_size(IconSize::Small)
1443                            .icon_color(Color::Muted)
1444                            .tooltip(Tooltip::text("Collapse Displayed Threads"))
1445                            .on_click(cx.listener({
1446                                let path_list_for_collapse = path_list_for_collapse.clone();
1447                                move |this, _, _window, cx| {
1448                                    this.selection = None;
1449                                    this.expanded_groups.remove(&path_list_for_collapse);
1450                                    this.serialize(cx);
1451                                    this.update_entries(cx);
1452                                }
1453                            })),
1454                        )
1455                    })
1456                    .when(show_new_thread_button, |this| {
1457                        this.child(
1458                            IconButton::new(
1459                                SharedString::from(format!(
1460                                    "{id_prefix}project-header-new-thread-{ix}",
1461                                )),
1462                                IconName::Plus,
1463                            )
1464                            .icon_size(IconSize::Small)
1465                            .icon_color(Color::Muted)
1466                            .tooltip(Tooltip::text("New Thread"))
1467                            .on_click(cx.listener({
1468                                let workspace_for_new_thread = workspace_for_new_thread.clone();
1469                                let path_list_for_new_thread = path_list_for_new_thread.clone();
1470                                move |this, _, window, cx| {
1471                                    // Uncollapse the group if collapsed so
1472                                    // the new-thread entry becomes visible.
1473                                    this.collapsed_groups.remove(&path_list_for_new_thread);
1474                                    this.selection = None;
1475                                    this.create_new_thread(&workspace_for_new_thread, window, cx);
1476                                }
1477                            })),
1478                        )
1479                    })
1480            })
1481            .when(!is_active, |this| {
1482                this.tooltip(Tooltip::text("Activate Workspace"))
1483                    .on_click(cx.listener({
1484                        move |this, _, window, cx| {
1485                            this.active_entry =
1486                                Some(ActiveEntry::Draft(workspace_for_open.clone()));
1487                            if let Some(multi_workspace) = this.multi_workspace.upgrade() {
1488                                multi_workspace.update(cx, |multi_workspace, cx| {
1489                                    multi_workspace.activate(
1490                                        workspace_for_open.clone(),
1491                                        window,
1492                                        cx,
1493                                    );
1494                                });
1495                            }
1496                            if AgentPanel::is_visible(&workspace_for_open, cx) {
1497                                workspace_for_open.update(cx, |workspace, cx| {
1498                                    workspace.focus_panel::<AgentPanel>(window, cx);
1499                                });
1500                            }
1501                        }
1502                    }))
1503            })
1504            .into_any_element()
1505    }
1506
1507    fn render_project_header_menu(
1508        &self,
1509        ix: usize,
1510        id_prefix: &str,
1511        workspace: &Entity<Workspace>,
1512        workspace_for_remove: &Entity<Workspace>,
1513        cx: &mut Context<Self>,
1514    ) -> impl IntoElement {
1515        let workspace_for_menu = workspace.clone();
1516        let workspace_for_remove = workspace_for_remove.clone();
1517        let multi_workspace = self.multi_workspace.clone();
1518        let this = cx.weak_entity();
1519
1520        PopoverMenu::new(format!("{id_prefix}project-header-menu-{ix}"))
1521            .on_open(Rc::new({
1522                let this = this.clone();
1523                move |_window, cx| {
1524                    this.update(cx, |sidebar, cx| {
1525                        sidebar.project_header_menu_ix = Some(ix);
1526                        cx.notify();
1527                    })
1528                    .ok();
1529                }
1530            }))
1531            .menu(move |window, cx| {
1532                let workspace = workspace_for_menu.clone();
1533                let workspace_for_remove = workspace_for_remove.clone();
1534                let multi_workspace = multi_workspace.clone();
1535
1536                let menu = ContextMenu::build_persistent(window, cx, move |menu, _window, cx| {
1537                    let worktrees: Vec<_> = workspace
1538                        .read(cx)
1539                        .visible_worktrees(cx)
1540                        .map(|worktree| {
1541                            let worktree_read = worktree.read(cx);
1542                            let id = worktree_read.id();
1543                            let name: SharedString =
1544                                worktree_read.root_name().as_unix_str().to_string().into();
1545                            (id, name)
1546                        })
1547                        .collect();
1548
1549                    let worktree_count = worktrees.len();
1550
1551                    let mut menu = menu
1552                        .header("Project Folders")
1553                        .end_slot_action(Box::new(menu::EndSlot));
1554
1555                    for (worktree_id, name) in &worktrees {
1556                        let worktree_id = *worktree_id;
1557                        let workspace_for_worktree = workspace.clone();
1558                        let workspace_for_remove_worktree = workspace_for_remove.clone();
1559                        let multi_workspace_for_worktree = multi_workspace.clone();
1560
1561                        let remove_handler = move |window: &mut Window, cx: &mut App| {
1562                            if worktree_count <= 1 {
1563                                if let Some(mw) = multi_workspace_for_worktree.upgrade() {
1564                                    let ws = workspace_for_remove_worktree.clone();
1565                                    mw.update(cx, |multi_workspace, cx| {
1566                                        multi_workspace.remove(&ws, window, cx);
1567                                    });
1568                                }
1569                            } else {
1570                                workspace_for_worktree.update(cx, |workspace, cx| {
1571                                    workspace.project().update(cx, |project, cx| {
1572                                        project.remove_worktree(worktree_id, cx);
1573                                    });
1574                                });
1575                            }
1576                        };
1577
1578                        menu = menu.entry_with_end_slot_on_hover(
1579                            name.clone(),
1580                            None,
1581                            |_, _| {},
1582                            IconName::Close,
1583                            "Remove Folder".into(),
1584                            remove_handler,
1585                        );
1586                    }
1587
1588                    let workspace_for_add = workspace.clone();
1589                    let multi_workspace_for_add = multi_workspace.clone();
1590                    let menu = menu.separator().entry(
1591                        "Add Folder to Project",
1592                        Some(Box::new(AddFolderToProject)),
1593                        move |window, cx| {
1594                            if let Some(mw) = multi_workspace_for_add.upgrade() {
1595                                mw.update(cx, |mw, cx| {
1596                                    mw.activate(workspace_for_add.clone(), window, cx);
1597                                });
1598                            }
1599                            workspace_for_add.update(cx, |workspace, cx| {
1600                                workspace.add_folder_to_project(&AddFolderToProject, window, cx);
1601                            });
1602                        },
1603                    );
1604
1605                    let workspace_count = multi_workspace
1606                        .upgrade()
1607                        .map_or(0, |mw| mw.read(cx).workspaces().len());
1608                    let menu = if workspace_count > 1 {
1609                        let workspace_for_move = workspace.clone();
1610                        let multi_workspace_for_move = multi_workspace.clone();
1611                        menu.entry(
1612                            "Move to New Window",
1613                            Some(Box::new(
1614                                zed_actions::agents_sidebar::MoveWorkspaceToNewWindow,
1615                            )),
1616                            move |window, cx| {
1617                                if let Some(mw) = multi_workspace_for_move.upgrade() {
1618                                    mw.update(cx, |multi_workspace, cx| {
1619                                        multi_workspace.move_workspace_to_new_window(
1620                                            &workspace_for_move,
1621                                            window,
1622                                            cx,
1623                                        );
1624                                    });
1625                                }
1626                            },
1627                        )
1628                    } else {
1629                        menu
1630                    };
1631
1632                    let workspace_for_remove = workspace_for_remove.clone();
1633                    let multi_workspace_for_remove = multi_workspace.clone();
1634                    menu.separator()
1635                        .entry("Remove Project", None, move |window, cx| {
1636                            if let Some(mw) = multi_workspace_for_remove.upgrade() {
1637                                let ws = workspace_for_remove.clone();
1638                                mw.update(cx, |multi_workspace, cx| {
1639                                    multi_workspace.remove(&ws, window, cx);
1640                                });
1641                            }
1642                        })
1643                });
1644
1645                let this = this.clone();
1646                window
1647                    .subscribe(&menu, cx, move |_, _: &gpui::DismissEvent, _window, cx| {
1648                        this.update(cx, |sidebar, cx| {
1649                            sidebar.project_header_menu_ix = None;
1650                            cx.notify();
1651                        })
1652                        .ok();
1653                    })
1654                    .detach();
1655
1656                Some(menu)
1657            })
1658            .trigger(
1659                IconButton::new(
1660                    SharedString::from(format!("{id_prefix}-ellipsis-menu-{ix}")),
1661                    IconName::Ellipsis,
1662                )
1663                .selected_style(ButtonStyle::Tinted(TintColor::Accent))
1664                .icon_size(IconSize::Small)
1665                .icon_color(Color::Muted),
1666            )
1667            .anchor(gpui::Corner::TopRight)
1668            .offset(gpui::Point {
1669                x: px(0.),
1670                y: px(1.),
1671            })
1672    }
1673
1674    fn render_sticky_header(
1675        &self,
1676        window: &mut Window,
1677        cx: &mut Context<Self>,
1678    ) -> Option<AnyElement> {
1679        let scroll_top = self.list_state.logical_scroll_top();
1680
1681        let &header_idx = self
1682            .contents
1683            .project_header_indices
1684            .iter()
1685            .rev()
1686            .find(|&&idx| idx <= scroll_top.item_ix)?;
1687
1688        let needs_sticky = header_idx < scroll_top.item_ix
1689            || (header_idx == scroll_top.item_ix && scroll_top.offset_in_item > px(0.));
1690
1691        if !needs_sticky {
1692            return None;
1693        }
1694
1695        let ListEntry::ProjectHeader {
1696            path_list,
1697            label,
1698            workspace,
1699            highlight_positions,
1700            has_running_threads,
1701            waiting_thread_count,
1702            is_active,
1703        } = self.contents.entries.get(header_idx)?
1704        else {
1705            return None;
1706        };
1707
1708        let is_focused = self.focus_handle.is_focused(window);
1709        let is_selected = is_focused && self.selection == Some(header_idx);
1710
1711        let header_element = self.render_project_header(
1712            header_idx,
1713            true,
1714            &path_list,
1715            &label,
1716            workspace,
1717            &highlight_positions,
1718            *has_running_threads,
1719            *waiting_thread_count,
1720            *is_active,
1721            is_selected,
1722            cx,
1723        );
1724
1725        let top_offset = self
1726            .contents
1727            .project_header_indices
1728            .iter()
1729            .find(|&&idx| idx > header_idx)
1730            .and_then(|&next_idx| {
1731                let bounds = self.list_state.bounds_for_item(next_idx)?;
1732                let viewport = self.list_state.viewport_bounds();
1733                let y_in_viewport = bounds.origin.y - viewport.origin.y;
1734                let header_height = bounds.size.height;
1735                (y_in_viewport < header_height).then_some(y_in_viewport - header_height)
1736            })
1737            .unwrap_or(px(0.));
1738
1739        let color = cx.theme().colors();
1740        let background = color
1741            .title_bar_background
1742            .blend(color.panel_background.opacity(0.2));
1743
1744        let element = v_flex()
1745            .absolute()
1746            .top(top_offset)
1747            .left_0()
1748            .w_full()
1749            .bg(background)
1750            .border_b_1()
1751            .border_color(color.border.opacity(0.5))
1752            .child(header_element)
1753            .shadow_xs()
1754            .into_any_element();
1755
1756        Some(element)
1757    }
1758
1759    fn toggle_collapse(
1760        &mut self,
1761        path_list: &PathList,
1762        _window: &mut Window,
1763        cx: &mut Context<Self>,
1764    ) {
1765        if self.collapsed_groups.contains(path_list) {
1766            self.collapsed_groups.remove(path_list);
1767        } else {
1768            self.collapsed_groups.insert(path_list.clone());
1769        }
1770        self.serialize(cx);
1771        self.update_entries(cx);
1772    }
1773
1774    fn dispatch_context(&self, window: &Window, cx: &Context<Self>) -> KeyContext {
1775        let mut dispatch_context = KeyContext::new_with_defaults();
1776        dispatch_context.add("ThreadsSidebar");
1777        dispatch_context.add("menu");
1778
1779        let identifier = if self.filter_editor.focus_handle(cx).is_focused(window) {
1780            "searching"
1781        } else {
1782            "not_searching"
1783        };
1784
1785        dispatch_context.add(identifier);
1786        dispatch_context
1787    }
1788
1789    fn focus_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1790        if !self.focus_handle.is_focused(window) {
1791            return;
1792        }
1793
1794        if let SidebarView::Archive(archive) = &self.view {
1795            let has_selection = archive.read(cx).has_selection();
1796            if !has_selection {
1797                archive.update(cx, |view, cx| view.focus_filter_editor(window, cx));
1798            }
1799        } else if self.selection.is_none() {
1800            self.filter_editor.focus_handle(cx).focus(window, cx);
1801        }
1802    }
1803
1804    fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
1805        if self.reset_filter_editor_text(window, cx) {
1806            self.update_entries(cx);
1807        } else {
1808            self.selection = None;
1809            self.filter_editor.focus_handle(cx).focus(window, cx);
1810            cx.notify();
1811        }
1812    }
1813
1814    fn focus_sidebar_filter(
1815        &mut self,
1816        _: &FocusSidebarFilter,
1817        window: &mut Window,
1818        cx: &mut Context<Self>,
1819    ) {
1820        self.selection = None;
1821        if let SidebarView::Archive(archive) = &self.view {
1822            archive.update(cx, |view, cx| {
1823                view.clear_selection();
1824                view.focus_filter_editor(window, cx);
1825            });
1826        } else {
1827            self.filter_editor.focus_handle(cx).focus(window, cx);
1828        }
1829
1830        // When vim mode is active, the editor defaults to normal mode which
1831        // blocks text input. Switch to insert mode so the user can type
1832        // immediately.
1833        if vim_mode_setting::VimModeSetting::get_global(cx).0 {
1834            if let Ok(action) = cx.build_action("vim::SwitchToInsertMode", None) {
1835                window.dispatch_action(action, cx);
1836            }
1837        }
1838
1839        cx.notify();
1840    }
1841
1842    fn reset_filter_editor_text(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
1843        self.filter_editor.update(cx, |editor, cx| {
1844            if editor.buffer().read(cx).len(cx).0 > 0 {
1845                editor.set_text("", window, cx);
1846                true
1847            } else {
1848                false
1849            }
1850        })
1851    }
1852
1853    fn has_filter_query(&self, cx: &App) -> bool {
1854        !self.filter_editor.read(cx).text(cx).is_empty()
1855    }
1856
1857    fn editor_move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
1858        self.select_next(&SelectNext, window, cx);
1859        if self.selection.is_some() {
1860            self.focus_handle.focus(window, cx);
1861        }
1862    }
1863
1864    fn editor_move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
1865        self.select_previous(&SelectPrevious, window, cx);
1866        if self.selection.is_some() {
1867            self.focus_handle.focus(window, cx);
1868        }
1869    }
1870
1871    fn editor_confirm(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1872        if self.selection.is_none() {
1873            self.select_next(&SelectNext, window, cx);
1874        }
1875        if self.selection.is_some() {
1876            self.focus_handle.focus(window, cx);
1877        }
1878    }
1879
1880    fn select_next(&mut self, _: &SelectNext, _window: &mut Window, cx: &mut Context<Self>) {
1881        let next = match self.selection {
1882            Some(ix) if ix + 1 < self.contents.entries.len() => ix + 1,
1883            Some(_) if !self.contents.entries.is_empty() => 0,
1884            None if !self.contents.entries.is_empty() => 0,
1885            _ => return,
1886        };
1887        self.selection = Some(next);
1888        self.list_state.scroll_to_reveal_item(next);
1889        cx.notify();
1890    }
1891
1892    fn select_previous(&mut self, _: &SelectPrevious, window: &mut Window, cx: &mut Context<Self>) {
1893        match self.selection {
1894            Some(0) => {
1895                self.selection = None;
1896                self.filter_editor.focus_handle(cx).focus(window, cx);
1897                cx.notify();
1898            }
1899            Some(ix) => {
1900                self.selection = Some(ix - 1);
1901                self.list_state.scroll_to_reveal_item(ix - 1);
1902                cx.notify();
1903            }
1904            None if !self.contents.entries.is_empty() => {
1905                let last = self.contents.entries.len() - 1;
1906                self.selection = Some(last);
1907                self.list_state.scroll_to_reveal_item(last);
1908                cx.notify();
1909            }
1910            None => {}
1911        }
1912    }
1913
1914    fn select_first(&mut self, _: &SelectFirst, _window: &mut Window, cx: &mut Context<Self>) {
1915        if !self.contents.entries.is_empty() {
1916            self.selection = Some(0);
1917            self.list_state.scroll_to_reveal_item(0);
1918            cx.notify();
1919        }
1920    }
1921
1922    fn select_last(&mut self, _: &SelectLast, _window: &mut Window, cx: &mut Context<Self>) {
1923        if let Some(last) = self.contents.entries.len().checked_sub(1) {
1924            self.selection = Some(last);
1925            self.list_state.scroll_to_reveal_item(last);
1926            cx.notify();
1927        }
1928    }
1929
1930    fn confirm(&mut self, _: &Confirm, window: &mut Window, cx: &mut Context<Self>) {
1931        let Some(ix) = self.selection else { return };
1932        let Some(entry) = self.contents.entries.get(ix) else {
1933            return;
1934        };
1935
1936        match entry {
1937            ListEntry::ProjectHeader { path_list, .. } => {
1938                let path_list = path_list.clone();
1939                self.toggle_collapse(&path_list, window, cx);
1940            }
1941            ListEntry::Thread(thread) => {
1942                let metadata = thread.metadata.clone();
1943                match &thread.workspace {
1944                    ThreadEntryWorkspace::Open(workspace) => {
1945                        let workspace = workspace.clone();
1946                        self.activate_thread(metadata, &workspace, window, cx);
1947                    }
1948                    ThreadEntryWorkspace::Closed(path_list) => {
1949                        self.open_workspace_and_activate_thread(
1950                            metadata,
1951                            path_list.clone(),
1952                            window,
1953                            cx,
1954                        );
1955                    }
1956                }
1957            }
1958            ListEntry::ViewMore {
1959                path_list,
1960                is_fully_expanded,
1961                ..
1962            } => {
1963                let path_list = path_list.clone();
1964                if *is_fully_expanded {
1965                    self.expanded_groups.remove(&path_list);
1966                } else {
1967                    let current = self.expanded_groups.get(&path_list).copied().unwrap_or(0);
1968                    self.expanded_groups.insert(path_list, current + 1);
1969                }
1970                self.serialize(cx);
1971                self.update_entries(cx);
1972            }
1973            ListEntry::NewThread { workspace, .. } => {
1974                let workspace = workspace.clone();
1975                self.create_new_thread(&workspace, window, cx);
1976            }
1977        }
1978    }
1979
1980    fn find_workspace_across_windows(
1981        &self,
1982        cx: &App,
1983        predicate: impl Fn(&Entity<Workspace>, &App) -> bool,
1984    ) -> Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> {
1985        cx.windows()
1986            .into_iter()
1987            .filter_map(|window| window.downcast::<MultiWorkspace>())
1988            .find_map(|window| {
1989                let workspace = window.read(cx).ok().and_then(|multi_workspace| {
1990                    multi_workspace
1991                        .workspaces()
1992                        .iter()
1993                        .find(|workspace| predicate(workspace, cx))
1994                        .cloned()
1995                })?;
1996                Some((window, workspace))
1997            })
1998    }
1999
2000    fn find_workspace_in_current_window(
2001        &self,
2002        cx: &App,
2003        predicate: impl Fn(&Entity<Workspace>, &App) -> bool,
2004    ) -> Option<Entity<Workspace>> {
2005        self.multi_workspace.upgrade().and_then(|multi_workspace| {
2006            multi_workspace
2007                .read(cx)
2008                .workspaces()
2009                .iter()
2010                .find(|workspace| predicate(workspace, cx))
2011                .cloned()
2012        })
2013    }
2014
2015    fn load_agent_thread_in_workspace(
2016        workspace: &Entity<Workspace>,
2017        metadata: &ThreadMetadata,
2018        focus: bool,
2019        window: &mut Window,
2020        cx: &mut App,
2021    ) {
2022        workspace.update(cx, |workspace, cx| {
2023            workspace.reveal_panel::<AgentPanel>(window, cx);
2024        });
2025
2026        if let Some(agent_panel) = workspace.read(cx).panel::<AgentPanel>(cx) {
2027            agent_panel.update(cx, |panel, cx| {
2028                panel.load_agent_thread(
2029                    Agent::from(metadata.agent_id.clone()),
2030                    metadata.session_id.clone(),
2031                    Some(metadata.folder_paths.clone()),
2032                    Some(metadata.title.clone()),
2033                    focus,
2034                    window,
2035                    cx,
2036                );
2037            });
2038        }
2039    }
2040
2041    fn activate_thread_locally(
2042        &mut self,
2043        metadata: &ThreadMetadata,
2044        workspace: &Entity<Workspace>,
2045        window: &mut Window,
2046        cx: &mut Context<Self>,
2047    ) {
2048        let Some(multi_workspace) = self.multi_workspace.upgrade() else {
2049            return;
2050        };
2051
2052        // Set active_entry eagerly so the sidebar highlight updates
2053        // immediately, rather than waiting for a deferred AgentPanel
2054        // event which can race with ActiveWorkspaceChanged clearing it.
2055        self.active_entry = Some(ActiveEntry::Thread {
2056            session_id: metadata.session_id.clone(),
2057            workspace: workspace.clone(),
2058        });
2059        self.record_thread_access(&metadata.session_id);
2060
2061        multi_workspace.update(cx, |multi_workspace, cx| {
2062            multi_workspace.activate(workspace.clone(), window, cx);
2063        });
2064
2065        Self::load_agent_thread_in_workspace(workspace, metadata, true, window, cx);
2066
2067        self.update_entries(cx);
2068    }
2069
2070    fn activate_thread_in_other_window(
2071        &self,
2072        metadata: ThreadMetadata,
2073        workspace: Entity<Workspace>,
2074        target_window: WindowHandle<MultiWorkspace>,
2075        cx: &mut Context<Self>,
2076    ) {
2077        let target_session_id = metadata.session_id.clone();
2078        let workspace_for_entry = workspace.clone();
2079
2080        let activated = target_window
2081            .update(cx, |multi_workspace, window, cx| {
2082                window.activate_window();
2083                multi_workspace.activate(workspace.clone(), window, cx);
2084                Self::load_agent_thread_in_workspace(&workspace, &metadata, true, window, cx);
2085            })
2086            .log_err()
2087            .is_some();
2088
2089        if activated {
2090            if let Some(target_sidebar) = target_window
2091                .read(cx)
2092                .ok()
2093                .and_then(|multi_workspace| {
2094                    multi_workspace.sidebar().map(|sidebar| sidebar.to_any())
2095                })
2096                .and_then(|sidebar| sidebar.downcast::<Self>().ok())
2097            {
2098                target_sidebar.update(cx, |sidebar, cx| {
2099                    sidebar.active_entry = Some(ActiveEntry::Thread {
2100                        session_id: target_session_id.clone(),
2101                        workspace: workspace_for_entry.clone(),
2102                    });
2103                    sidebar.record_thread_access(&target_session_id);
2104                    sidebar.update_entries(cx);
2105                });
2106            }
2107        }
2108    }
2109
2110    fn activate_thread(
2111        &mut self,
2112        metadata: ThreadMetadata,
2113        workspace: &Entity<Workspace>,
2114        window: &mut Window,
2115        cx: &mut Context<Self>,
2116    ) {
2117        if self
2118            .find_workspace_in_current_window(cx, |candidate, _| candidate == workspace)
2119            .is_some()
2120        {
2121            self.activate_thread_locally(&metadata, &workspace, window, cx);
2122            return;
2123        }
2124
2125        let Some((target_window, workspace)) =
2126            self.find_workspace_across_windows(cx, |candidate, _| candidate == workspace)
2127        else {
2128            return;
2129        };
2130
2131        self.activate_thread_in_other_window(metadata, workspace, target_window, cx);
2132    }
2133
2134    fn open_workspace_and_activate_thread(
2135        &mut self,
2136        metadata: ThreadMetadata,
2137        path_list: PathList,
2138        window: &mut Window,
2139        cx: &mut Context<Self>,
2140    ) {
2141        let Some(multi_workspace) = self.multi_workspace.upgrade() else {
2142            return;
2143        };
2144
2145        let paths: Vec<std::path::PathBuf> =
2146            path_list.paths().iter().map(|p| p.to_path_buf()).collect();
2147
2148        let open_task = multi_workspace.update(cx, |mw, cx| {
2149            mw.open_project(paths, workspace::OpenMode::Activate, window, cx)
2150        });
2151
2152        cx.spawn_in(window, async move |this, cx| {
2153            let workspace = open_task.await?;
2154
2155            this.update_in(cx, |this, window, cx| {
2156                this.activate_thread(metadata, &workspace, window, cx);
2157            })?;
2158            anyhow::Ok(())
2159        })
2160        .detach_and_log_err(cx);
2161    }
2162
2163    fn find_current_workspace_for_path_list(
2164        &self,
2165        path_list: &PathList,
2166        cx: &App,
2167    ) -> Option<Entity<Workspace>> {
2168        self.find_workspace_in_current_window(cx, |workspace, cx| {
2169            workspace_path_list(workspace, cx).paths() == path_list.paths()
2170        })
2171    }
2172
2173    fn find_open_workspace_for_path_list(
2174        &self,
2175        path_list: &PathList,
2176        cx: &App,
2177    ) -> Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> {
2178        self.find_workspace_across_windows(cx, |workspace, cx| {
2179            workspace_path_list(workspace, cx).paths() == path_list.paths()
2180        })
2181    }
2182
2183    fn activate_archived_thread(
2184        &mut self,
2185        metadata: ThreadMetadata,
2186        window: &mut Window,
2187        cx: &mut Context<Self>,
2188    ) {
2189        ThreadMetadataStore::global(cx)
2190            .update(cx, |store, cx| store.unarchive(&metadata.session_id, cx));
2191
2192        if metadata.folder_paths.paths().is_empty() {
2193            self.activate_unarchived_thread_in_workspace(&metadata, window, cx);
2194            return;
2195        }
2196
2197        // Check all paths for archived worktrees that may need restoration
2198        // before opening the workspace.
2199        let paths = metadata.folder_paths.paths().to_vec();
2200        self.maybe_restore_git_worktrees(paths, metadata, window, cx);
2201    }
2202
2203    fn activate_unarchived_thread_in_workspace(
2204        &mut self,
2205        metadata: &ThreadMetadata,
2206        window: &mut Window,
2207        cx: &mut Context<Self>,
2208    ) {
2209        if !metadata.folder_paths.paths().is_empty() {
2210            let path_list = metadata.folder_paths.clone();
2211            if let Some(workspace) = self.find_current_workspace_for_path_list(&path_list, cx) {
2212                self.activate_thread_locally(metadata, &workspace, window, cx);
2213            } else if let Some((target_window, workspace)) =
2214                self.find_open_workspace_for_path_list(&path_list, cx)
2215            {
2216                self.activate_thread_in_other_window(
2217                    metadata.clone(),
2218                    workspace,
2219                    target_window,
2220                    cx,
2221                );
2222            } else {
2223                self.open_workspace_and_activate_thread(metadata.clone(), path_list, window, cx);
2224            }
2225            return;
2226        }
2227
2228        let active_workspace = self.multi_workspace.upgrade().and_then(|w| {
2229            w.read(cx)
2230                .workspaces()
2231                .get(w.read(cx).active_workspace_index())
2232                .cloned()
2233        });
2234
2235        if let Some(workspace) = active_workspace {
2236            self.activate_thread_locally(metadata, &workspace, window, cx);
2237        }
2238    }
2239
2240    fn maybe_restore_git_worktrees(
2241        &mut self,
2242        paths: Vec<std::path::PathBuf>,
2243        metadata: ThreadMetadata,
2244        window: &mut Window,
2245        cx: &mut Context<Self>,
2246    ) {
2247        let Some(multi_workspace) = self.multi_workspace.upgrade() else {
2248            return;
2249        };
2250        let workspaces = multi_workspace.read(cx).workspaces().to_vec();
2251
2252        cx.spawn_in(window, async move |this, cx| {
2253            let store = cx.update(|_window, cx| ThreadMetadataStore::global(cx))?;
2254            let mut final_paths = Vec::with_capacity(paths.len());
2255
2256            for path in &paths {
2257                let path_str = path.to_string_lossy().to_string();
2258                let archived_worktree = store
2259                    .update(cx, |store, cx| {
2260                        store.get_archived_worktree_by_path(path_str, cx)
2261                    })
2262                    .await?;
2263
2264                match archived_worktree {
2265                    None => {
2266                        // No archived worktree record — keep the original path.
2267                        final_paths.push(path.clone());
2268                    }
2269                    Some(row) => {
2270                        // Restore from WIP commit.
2271                        let restored_path =
2272                            Self::restore_archived_worktree(&row, &workspaces, cx).await?;
2273                        final_paths.push(restored_path);
2274
2275                        // Clean up the archived worktree record and ref.
2276                        Self::maybe_cleanup_archived_worktree(&row, &store, &workspaces, cx).await;
2277                    }
2278                }
2279            }
2280
2281            let mut updated_metadata = metadata;
2282            updated_metadata.folder_paths = PathList::new(&final_paths);
2283
2284            this.update_in(cx, |this, window, cx| {
2285                this.activate_unarchived_thread_in_workspace(&updated_metadata, window, cx);
2286            })?;
2287
2288            anyhow::Ok(())
2289        })
2290        .detach_and_log_err(cx);
2291    }
2292
2293    async fn restore_archived_worktree(
2294        row: &ArchivedGitWorktree,
2295        workspaces: &[Entity<Workspace>],
2296        cx: &mut AsyncWindowContext,
2297    ) -> anyhow::Result<PathBuf> {
2298        let commit_hash = row.commit_hash.clone();
2299
2300        // Find the main repo entity.
2301        let main_repo = cx.update(|_window, cx| {
2302            find_main_repo_in_workspaces(workspaces, &row.main_repo_path, cx)
2303        })?;
2304
2305        let Some(main_repo) = main_repo else {
2306            // Main repo not found — fall back to fresh worktree.
2307            return Self::create_fresh_worktree(row, workspaces, cx).await;
2308        };
2309
2310        // Check if the original worktree path is already in use.
2311        let worktree_path = &row.worktree_path;
2312        let fs = cx.update(|_window, cx| <dyn fs::Fs>::global(cx))?;
2313        let already_exists = fs.metadata(worktree_path).await?.is_some();
2314
2315        let final_worktree_path = if !already_exists {
2316            worktree_path.clone()
2317        } else if row.restored {
2318            // Another thread already restored this worktree — reuse it.
2319            worktree_path.clone()
2320        } else {
2321            // Collision — use a different path. Generate a name based on
2322            // the archived worktree ID to keep it deterministic.
2323            let new_name = format!(
2324                "{}-restored-{}",
2325                row.branch_name.as_deref().unwrap_or("worktree"),
2326                row.id
2327            );
2328            let path = main_repo.update(cx, |repo, _cx| {
2329                let setting = git_store::worktrees_directory_for_repo(
2330                    &repo.snapshot().original_repo_abs_path,
2331                    git::repository::DEFAULT_WORKTREE_DIRECTORY,
2332                )
2333                .ok()
2334                .map(|p| p.to_string_lossy().to_string())
2335                .unwrap_or_default();
2336                repo.path_for_new_linked_worktree(&new_name, &setting)
2337            })?;
2338            path
2339        };
2340
2341        // We need to create the worktree if it doesn't already exist at
2342        // the final path (which may differ from the original due to a
2343        // collision). If another thread already restored it (row.restored),
2344        // we skip creation.
2345        let final_path_exists = if final_worktree_path == *worktree_path {
2346            already_exists
2347        } else {
2348            fs.metadata(&final_worktree_path).await?.is_some()
2349        };
2350
2351        if !final_path_exists && !row.restored {
2352            // Create the worktree in detached HEAD mode at the WIP commit.
2353            let create_receiver = main_repo.update(cx, |repo, _cx| {
2354                repo.create_worktree_detached(final_worktree_path.clone(), commit_hash)
2355            });
2356            match create_receiver.await {
2357                Ok(Ok(())) => {}
2358                Ok(Err(err)) => {
2359                    log::error!("Failed to create worktree: {err}");
2360                    return Self::create_fresh_worktree(row, workspaces, cx).await;
2361                }
2362                Err(_) => {
2363                    anyhow::bail!("Worktree creation was canceled");
2364                }
2365            }
2366
2367            // Tell the project about the new worktree and wait for it
2368            // to finish scanning so the GitStore creates a Repository.
2369            let project = cx.update(|_window, cx| {
2370                workspaces.iter().find_map(|workspace| {
2371                    let project = workspace.read(cx).project().clone();
2372                    let has_main_repo = project.read(cx).repositories(cx).values().any(|repo| {
2373                        let repo = repo.read(cx);
2374                        repo.is_main_worktree()
2375                            && *repo.work_directory_abs_path == *row.main_repo_path
2376                    });
2377                    has_main_repo.then_some(project)
2378                })
2379            })?;
2380
2381            if let Some(project) = project {
2382                let path_for_register = final_worktree_path.clone();
2383                let worktree_result = project
2384                    .update(cx, |project, cx| {
2385                        project.find_or_create_worktree(path_for_register, true, cx)
2386                    })
2387                    .await;
2388                if let Ok((worktree, _)) = worktree_result {
2389                    let scan_complete = cx.update(|_window, cx| {
2390                        worktree
2391                            .read(cx)
2392                            .as_local()
2393                            .map(project::LocalWorktree::scan_complete)
2394                    })?;
2395                    if let Some(future) = scan_complete {
2396                        future.await;
2397                    }
2398                }
2399            }
2400
2401            // Find the new worktree's repo entity.
2402            let worktree_repo = cx.update(|_window, cx| {
2403                workspaces.iter().find_map(|workspace| {
2404                    let project = workspace.read(cx).project().clone();
2405                    project
2406                        .read(cx)
2407                        .repositories(cx)
2408                        .values()
2409                        .find_map(|repo_entity| {
2410                            let snapshot = repo_entity.read(cx).snapshot();
2411                            (*snapshot.work_directory_abs_path == *final_worktree_path)
2412                                .then(|| repo_entity.clone())
2413                        })
2414                })
2415            })?;
2416
2417            if let Some(worktree_repo) = worktree_repo {
2418                // Reset HEAD~ to undo the WIP commit (mixed reset puts
2419                // changes back as unstaged).
2420                let reset_receiver = worktree_repo.update(cx, |repo, cx| {
2421                    repo.reset("HEAD~".to_string(), ResetMode::Mixed, cx)
2422                });
2423                match reset_receiver.await {
2424                    Ok(Ok(())) => {}
2425                    Ok(Err(err)) => {
2426                        log::warn!("Failed to reset WIP commit: {err}");
2427                    }
2428                    Err(_) => {
2429                        log::warn!("Reset was canceled");
2430                    }
2431                }
2432
2433                // Try to put the worktree back on its original branch.
2434                if let Some(original_branch) = &row.branch_name {
2435                    // First try switching to the branch — this works when
2436                    // the branch still exists and its tip matches HEAD.
2437                    let switch_receiver = worktree_repo
2438                        .update(cx, |repo, _cx| repo.change_branch(original_branch.clone()));
2439                    let switch_ok = matches!(switch_receiver.await, Ok(Ok(())));
2440
2441                    if !switch_ok {
2442                        // Branch doesn't exist or can't be checked out from
2443                        // our current HEAD — create a new branch here.
2444                        let create_receiver = worktree_repo.update(cx, |repo, _cx| {
2445                            repo.create_branch(original_branch.clone(), None)
2446                        });
2447                        if let Ok(result) = create_receiver.await {
2448                            result.log_err();
2449                        }
2450                    }
2451                }
2452            }
2453
2454            // Mark the archived worktree as restored in the database.
2455            let store = cx.update(|_window, cx| ThreadMetadataStore::global(cx))?;
2456            store
2457                .update(cx, |store, cx| {
2458                    store.update_archived_worktree_restored(
2459                        row.id,
2460                        final_worktree_path.to_string_lossy().to_string(),
2461                        row.branch_name.clone(),
2462                        cx,
2463                    )
2464                })
2465                .await?;
2466        }
2467
2468        Ok(final_worktree_path)
2469    }
2470
2471    async fn create_fresh_worktree(
2472        row: &ArchivedGitWorktree,
2473        workspaces: &[Entity<Workspace>],
2474        cx: &mut AsyncWindowContext,
2475    ) -> anyhow::Result<PathBuf> {
2476        // Find the main repo entity.
2477        let main_repo = cx.update(|_window, cx| {
2478            find_main_repo_in_workspaces(workspaces, &row.main_repo_path, cx)
2479        })?;
2480
2481        let Some(main_repo) = main_repo else {
2482            // Can't find the main repo — fall back to the original path.
2483            return Ok(row.worktree_path.clone());
2484        };
2485
2486        // Generate a new branch name for the fresh worktree.
2487        let branch_name = format!("restored-{}", row.id);
2488        let worktree_path = main_repo.update(cx, |repo, _cx| {
2489            repo.path_for_new_linked_worktree(
2490                &branch_name,
2491                git::repository::DEFAULT_WORKTREE_DIRECTORY,
2492            )
2493        })?;
2494
2495        // Create the fresh worktree.
2496        let create_receiver = main_repo.update(cx, |repo, _cx| {
2497            repo.create_worktree(branch_name, worktree_path.clone(), None)
2498        });
2499        match create_receiver.await {
2500            Ok(Ok(())) => {}
2501            Ok(Err(err)) => {
2502                log::error!("Failed to create fresh worktree: {err}");
2503                return Ok(row.worktree_path.clone());
2504            }
2505            Err(_) => {
2506                anyhow::bail!("Fresh worktree creation was canceled");
2507            }
2508        }
2509
2510        log::warn!(
2511            "Unable to restore the original git worktree. Created a fresh worktree instead."
2512        );
2513
2514        Ok(worktree_path)
2515    }
2516
2517    async fn maybe_cleanup_archived_worktree(
2518        row: &ArchivedGitWorktree,
2519        store: &Entity<ThreadMetadataStore>,
2520        workspaces: &[Entity<Workspace>],
2521        cx: &mut AsyncWindowContext,
2522    ) {
2523        // Delete the git ref from the main repo.
2524        let Ok(main_repo) = cx.update(|_window, cx| {
2525            find_main_repo_in_workspaces(workspaces, &row.main_repo_path, cx)
2526        }) else {
2527            return;
2528        };
2529
2530        if let Some(main_repo) = main_repo {
2531            let ref_name = format!("refs/archived-worktrees/{}", row.id);
2532            let receiver = main_repo.update(cx, |repo, _cx| repo.delete_ref(ref_name));
2533            if let Ok(result) = receiver.await {
2534                result.log_err();
2535            }
2536        }
2537
2538        // Delete the archived worktree record.
2539        store
2540            .update(cx, |store, cx| store.delete_archived_worktree(row.id, cx))
2541            .await
2542            .log_err();
2543    }
2544
2545    fn expand_selected_entry(
2546        &mut self,
2547        _: &SelectChild,
2548        _window: &mut Window,
2549        cx: &mut Context<Self>,
2550    ) {
2551        let Some(ix) = self.selection else { return };
2552
2553        match self.contents.entries.get(ix) {
2554            Some(ListEntry::ProjectHeader { path_list, .. }) => {
2555                if self.collapsed_groups.contains(path_list) {
2556                    let path_list = path_list.clone();
2557                    self.collapsed_groups.remove(&path_list);
2558                    self.update_entries(cx);
2559                } else if ix + 1 < self.contents.entries.len() {
2560                    self.selection = Some(ix + 1);
2561                    self.list_state.scroll_to_reveal_item(ix + 1);
2562                    cx.notify();
2563                }
2564            }
2565            _ => {}
2566        }
2567    }
2568
2569    fn collapse_selected_entry(
2570        &mut self,
2571        _: &SelectParent,
2572        _window: &mut Window,
2573        cx: &mut Context<Self>,
2574    ) {
2575        let Some(ix) = self.selection else { return };
2576
2577        match self.contents.entries.get(ix) {
2578            Some(ListEntry::ProjectHeader { path_list, .. }) => {
2579                if !self.collapsed_groups.contains(path_list) {
2580                    let path_list = path_list.clone();
2581                    self.collapsed_groups.insert(path_list);
2582                    self.update_entries(cx);
2583                }
2584            }
2585            Some(
2586                ListEntry::Thread(_) | ListEntry::ViewMore { .. } | ListEntry::NewThread { .. },
2587            ) => {
2588                for i in (0..ix).rev() {
2589                    if let Some(ListEntry::ProjectHeader { path_list, .. }) =
2590                        self.contents.entries.get(i)
2591                    {
2592                        let path_list = path_list.clone();
2593                        self.selection = Some(i);
2594                        self.collapsed_groups.insert(path_list);
2595                        self.update_entries(cx);
2596                        break;
2597                    }
2598                }
2599            }
2600            None => {}
2601        }
2602    }
2603
2604    fn toggle_selected_fold(
2605        &mut self,
2606        _: &editor::actions::ToggleFold,
2607        _window: &mut Window,
2608        cx: &mut Context<Self>,
2609    ) {
2610        let Some(ix) = self.selection else { return };
2611
2612        // Find the group header for the current selection.
2613        let header_ix = match self.contents.entries.get(ix) {
2614            Some(ListEntry::ProjectHeader { .. }) => Some(ix),
2615            Some(
2616                ListEntry::Thread(_) | ListEntry::ViewMore { .. } | ListEntry::NewThread { .. },
2617            ) => (0..ix).rev().find(|&i| {
2618                matches!(
2619                    self.contents.entries.get(i),
2620                    Some(ListEntry::ProjectHeader { .. })
2621                )
2622            }),
2623            None => None,
2624        };
2625
2626        if let Some(header_ix) = header_ix {
2627            if let Some(ListEntry::ProjectHeader { path_list, .. }) =
2628                self.contents.entries.get(header_ix)
2629            {
2630                let path_list = path_list.clone();
2631                if self.collapsed_groups.contains(&path_list) {
2632                    self.collapsed_groups.remove(&path_list);
2633                } else {
2634                    self.selection = Some(header_ix);
2635                    self.collapsed_groups.insert(path_list);
2636                }
2637                self.update_entries(cx);
2638            }
2639        }
2640    }
2641
2642    fn fold_all(
2643        &mut self,
2644        _: &editor::actions::FoldAll,
2645        _window: &mut Window,
2646        cx: &mut Context<Self>,
2647    ) {
2648        for entry in &self.contents.entries {
2649            if let ListEntry::ProjectHeader { path_list, .. } = entry {
2650                self.collapsed_groups.insert(path_list.clone());
2651            }
2652        }
2653        self.update_entries(cx);
2654    }
2655
2656    fn unfold_all(
2657        &mut self,
2658        _: &editor::actions::UnfoldAll,
2659        _window: &mut Window,
2660        cx: &mut Context<Self>,
2661    ) {
2662        self.collapsed_groups.clear();
2663        self.update_entries(cx);
2664    }
2665
2666    fn stop_thread(&mut self, session_id: &acp::SessionId, cx: &mut Context<Self>) {
2667        let Some(multi_workspace) = self.multi_workspace.upgrade() else {
2668            return;
2669        };
2670
2671        let workspaces = multi_workspace.read(cx).workspaces().to_vec();
2672        for workspace in workspaces {
2673            if let Some(agent_panel) = workspace.read(cx).panel::<AgentPanel>(cx) {
2674                let cancelled =
2675                    agent_panel.update(cx, |panel, cx| panel.cancel_thread(session_id, cx));
2676                if cancelled {
2677                    return;
2678                }
2679            }
2680        }
2681    }
2682
2683    fn archive_thread(
2684        &mut self,
2685        session_id: &acp::SessionId,
2686        window: &mut Window,
2687        cx: &mut Context<Self>,
2688    ) {
2689        ThreadMetadataStore::global(cx).update(cx, |store, cx| store.archive(session_id, cx));
2690
2691        // If we're archiving the currently focused thread, move focus to the
2692        // nearest thread within the same project group. We never cross group
2693        // boundaries — if the group has no other threads, clear focus and open
2694        // a blank new thread in the panel instead.
2695        if self
2696            .active_entry
2697            .as_ref()
2698            .is_some_and(|e| e.is_active_thread(session_id))
2699        {
2700            let current_pos = self.contents.entries.iter().position(|entry| {
2701                matches!(entry, ListEntry::Thread(t) if &t.metadata.session_id == session_id)
2702            });
2703
2704            // Find the workspace that owns this thread's project group by
2705            // walking backwards to the nearest ProjectHeader. We must use
2706            // *this* workspace (not the active workspace) because the user
2707            // might be archiving a thread in a non-active group.
2708            let group_workspace = current_pos.and_then(|pos| {
2709                self.contents.entries[..pos]
2710                    .iter()
2711                    .rev()
2712                    .find_map(|e| match e {
2713                        ListEntry::ProjectHeader { workspace, .. } => Some(workspace.clone()),
2714                        _ => None,
2715                    })
2716            });
2717
2718            let next_thread = current_pos.and_then(|pos| {
2719                let group_start = self.contents.entries[..pos]
2720                    .iter()
2721                    .rposition(|e| matches!(e, ListEntry::ProjectHeader { .. }))
2722                    .map_or(0, |i| i + 1);
2723                let group_end = self.contents.entries[pos + 1..]
2724                    .iter()
2725                    .position(|e| matches!(e, ListEntry::ProjectHeader { .. }))
2726                    .map_or(self.contents.entries.len(), |i| pos + 1 + i);
2727
2728                let above = self.contents.entries[group_start..pos]
2729                    .iter()
2730                    .rev()
2731                    .find_map(|entry| {
2732                        if let ListEntry::Thread(t) = entry {
2733                            Some(t)
2734                        } else {
2735                            None
2736                        }
2737                    });
2738
2739                above.or_else(|| {
2740                    self.contents.entries[pos + 1..group_end]
2741                        .iter()
2742                        .find_map(|entry| {
2743                            if let ListEntry::Thread(t) = entry {
2744                                Some(t)
2745                            } else {
2746                                None
2747                            }
2748                        })
2749                })
2750            });
2751
2752            if let Some(next) = next_thread {
2753                let next_metadata = next.metadata.clone();
2754                // Use the thread's own workspace when it has one open (e.g. an absorbed
2755                // linked worktree thread that appears under the main workspace's header
2756                // but belongs to its own workspace). Loading into the wrong panel binds
2757                // the thread to the wrong project, which corrupts its stored folder_paths
2758                // when metadata is saved via ThreadMetadata::from_thread.
2759                let target_workspace = match &next.workspace {
2760                    ThreadEntryWorkspace::Open(ws) => Some(ws.clone()),
2761                    ThreadEntryWorkspace::Closed(_) => group_workspace,
2762                };
2763                if let Some(ref ws) = target_workspace {
2764                    self.active_entry = Some(ActiveEntry::Thread {
2765                        session_id: next_metadata.session_id.clone(),
2766                        workspace: ws.clone(),
2767                    });
2768                }
2769                self.record_thread_access(&next_metadata.session_id);
2770
2771                if let Some(workspace) = target_workspace {
2772                    if let Some(agent_panel) = workspace.read(cx).panel::<AgentPanel>(cx) {
2773                        agent_panel.update(cx, |panel, cx| {
2774                            panel.load_agent_thread(
2775                                Agent::from(next_metadata.agent_id.clone()),
2776                                next_metadata.session_id.clone(),
2777                                Some(next_metadata.folder_paths.clone()),
2778                                Some(next_metadata.title.clone()),
2779                                true,
2780                                window,
2781                                cx,
2782                            );
2783                        });
2784                    }
2785                }
2786            } else {
2787                if let Some(workspace) = &group_workspace {
2788                    self.active_entry = Some(ActiveEntry::Draft(workspace.clone()));
2789                    if let Some(agent_panel) = workspace.read(cx).panel::<AgentPanel>(cx) {
2790                        agent_panel.update(cx, |panel, cx| {
2791                            panel.new_thread(&NewThread, window, cx);
2792                        });
2793                    }
2794                }
2795            }
2796        }
2797
2798        // Capture metadata before archiving in case we need to cancel.
2799        let thread_metadata = self.contents.entries.iter().find_map(|entry| {
2800            if let ListEntry::Thread(t) = entry {
2801                if &t.metadata.session_id == session_id {
2802                    return Some(t.metadata.clone());
2803                }
2804            }
2805            None
2806        });
2807        self.maybe_delete_git_worktree_for_archived_thread(session_id, thread_metadata, window, cx);
2808    }
2809
2810    /// If the thread being archived is associated with a linked git worktree,
2811    /// link it to an archived worktree record. If this is the last thread on
2812    /// that worktree, create a WIP commit, anchor it with a git ref, and
2813    /// delete the worktree.
2814    fn maybe_delete_git_worktree_for_archived_thread(
2815        &self,
2816        session_id: &acp::SessionId,
2817        thread_metadata: Option<ThreadMetadata>,
2818        window: &mut Window,
2819        cx: &mut Context<Self>,
2820    ) {
2821        let folder_paths = self.contents.entries.iter().find_map(|entry| {
2822            if let ListEntry::Thread(t) = entry {
2823                if &t.metadata.session_id == session_id {
2824                    return Some(match &t.workspace {
2825                        ThreadEntryWorkspace::Open(ws) => workspace_path_list(ws, cx),
2826                        ThreadEntryWorkspace::Closed(path_list) => path_list.clone(),
2827                    });
2828                }
2829            }
2830            None
2831        });
2832
2833        let Some(folder_paths) = folder_paths else {
2834            return;
2835        };
2836
2837        if folder_paths.paths().len() != 1 {
2838            return;
2839        }
2840
2841        let worktree_path = folder_paths.paths()[0].clone();
2842
2843        let Some(multi_workspace) = self.multi_workspace.upgrade() else {
2844            return;
2845        };
2846        let workspaces = multi_workspace.read(cx).workspaces().to_vec();
2847
2848        let worktree_info = workspaces.iter().find_map(|workspace| {
2849            let project = workspace.read(cx).project().clone();
2850            project
2851                .read(cx)
2852                .repositories(cx)
2853                .values()
2854                .find_map(|repo_entity| {
2855                    let snapshot = repo_entity.read(cx).snapshot();
2856                    if snapshot.is_linked_worktree()
2857                        && *snapshot.work_directory_abs_path == *worktree_path
2858                    {
2859                        let branch_name = snapshot.branch.as_ref().map(|b| b.name().to_string());
2860                        let main_repo_path = snapshot.original_repo_abs_path;
2861                        Some((repo_entity.clone(), branch_name, main_repo_path))
2862                    } else {
2863                        None
2864                    }
2865                })
2866        });
2867
2868        let Some((worktree_repo, branch_name, main_repo_path)) = worktree_info else {
2869            return;
2870        };
2871
2872        let store_entity = ThreadMetadataStore::global(cx);
2873        let is_last_thread = !store_entity
2874            .read(cx)
2875            .entries_for_path(&folder_paths)
2876            .any(|entry| &entry.session_id != session_id);
2877
2878        let main_repo = find_main_repo_in_workspaces(&workspaces, &main_repo_path, cx);
2879
2880        let fs = <dyn fs::Fs>::global(cx);
2881        let worktree_path_str = worktree_path.to_string_lossy().to_string();
2882        let main_repo_path_str = main_repo_path.to_string_lossy().to_string();
2883        let branch_name_clone = branch_name;
2884
2885        cx.spawn_in(window, async move |_this, cx| {
2886            if !is_last_thread {
2887                return anyhow::Ok(());
2888            }
2889
2890            let store = cx.update(|_window, cx| ThreadMetadataStore::global(cx))?;
2891
2892            // Helper: unarchive the thread so it reappears in the sidebar.
2893            let unarchive = |cx: &mut AsyncWindowContext| {
2894                if let Some(metadata) = &thread_metadata {
2895                    store.update(cx, |store, cx| {
2896                        store.unarchive(&metadata.session_id, cx);
2897                    });
2898                }
2899            };
2900
2901            // Helper: undo the WIP commit on the worktree.
2902            let undo_wip_commit = |cx: &mut AsyncWindowContext| {
2903                let reset_receiver = worktree_repo.update(cx, |repo, cx| {
2904                    repo.reset("HEAD~".to_string(), ResetMode::Mixed, cx)
2905                });
2906                async move {
2907                    match reset_receiver.await {
2908                        Ok(Ok(())) => {}
2909                        Ok(Err(err)) => log::error!("Failed to undo WIP commit: {err}"),
2910                        Err(_) => log::error!("WIP commit undo was canceled"),
2911                    }
2912                }
2913            };
2914
2915            // === Last thread: WIP commit, ref creation, and worktree deletion ===
2916
2917            // Stage all files including untracked.
2918            let stage_result =
2919                worktree_repo.update(cx, |repo, _cx| repo.stage_all_including_untracked());
2920            let stage_ok = match stage_result.await {
2921                Ok(Ok(())) => true,
2922                Ok(Err(err)) => {
2923                    log::error!("Failed to stage worktree files: {err}");
2924                    false
2925                }
2926                Err(_) => {
2927                    log::error!("Stage operation was canceled");
2928                    false
2929                }
2930            };
2931
2932            let commit_ok = if stage_ok {
2933                let askpass = AskPassDelegate::new(cx, |_, _, _| {});
2934                let commit_result = worktree_repo.update(cx, |repo, cx| {
2935                    repo.commit(
2936                        "WIP".into(),
2937                        None,
2938                        CommitOptions {
2939                            allow_empty: true,
2940                            ..Default::default()
2941                        },
2942                        askpass,
2943                        cx,
2944                    )
2945                });
2946                match commit_result.await {
2947                    Ok(Ok(())) => true,
2948                    Ok(Err(err)) => {
2949                        log::error!("Failed to create WIP commit: {err}");
2950                        false
2951                    }
2952                    Err(_) => {
2953                        log::error!("WIP commit was canceled");
2954                        false
2955                    }
2956                }
2957            } else {
2958                false
2959            };
2960
2961            if !commit_ok {
2962                // Show a prompt asking the user what to do.
2963                let answer = cx.prompt(
2964                    PromptLevel::Warning,
2965                    "Failed to save worktree state",
2966                    Some(
2967                        "Could not create a WIP commit for this worktree. \
2968                         If you proceed, the worktree will be deleted and \
2969                         unarchiving this thread later will not restore the \
2970                         filesystem to its previous state.\n\n\
2971                         Cancel to keep the worktree on disk so you can \
2972                         resolve the issue manually.",
2973                    ),
2974                    &["Delete Anyway", "Cancel"],
2975                );
2976
2977                match answer.await {
2978                    Ok(0) => {
2979                        // "Delete Anyway" — proceed to worktree deletion
2980                        // without a WIP commit or DB record.
2981                    }
2982                    _ => {
2983                        // "Cancel" — undo the archive so the thread
2984                        // reappears in the sidebar.
2985                        unarchive(cx);
2986                        return anyhow::Ok(());
2987                    }
2988                }
2989            } else {
2990                // Commit succeeded — get hash, create archived worktree row, create ref.
2991                let head_sha_result = worktree_repo.update(cx, |repo, _cx| repo.head_sha());
2992                let commit_hash = match head_sha_result.await {
2993                    Ok(Ok(Some(sha))) => sha,
2994                    sha_result => {
2995                        let reason = match &sha_result {
2996                            Ok(Ok(None)) => "HEAD SHA is None".into(),
2997                            Ok(Err(err)) => format!("Failed to get HEAD SHA: {err}"),
2998                            Err(_) => "HEAD SHA operation was canceled".into(),
2999                            Ok(Ok(Some(_))) => unreachable!(),
3000                        };
3001                        log::error!("{reason} after WIP commit; attempting to undo");
3002                        undo_wip_commit(cx).await;
3003                        unarchive(cx);
3004                        cx.prompt(
3005                            PromptLevel::Warning,
3006                            "Failed to archive worktree",
3007                            Some(
3008                                "Could not read the commit hash after creating \
3009                                 the WIP commit. The commit has been undone and \
3010                                 the thread has been restored to the sidebar.",
3011                            ),
3012                            &["OK"],
3013                        )
3014                        .await
3015                        .ok();
3016                        return anyhow::Ok(());
3017                    }
3018                };
3019
3020                let row_id_result = store
3021                    .update(cx, |store, cx| {
3022                        store.create_archived_worktree(
3023                            worktree_path_str,
3024                            main_repo_path_str,
3025                            branch_name_clone,
3026                            commit_hash.clone(),
3027                            cx,
3028                        )
3029                    })
3030                    .await;
3031
3032                match row_id_result {
3033                    Ok(row_id) => {
3034                        // Create a git ref on the main repo (non-fatal if
3035                        // this fails — the commit hash is in the DB).
3036                        if let Some(main_repo) = &main_repo {
3037                            let ref_name = format!("refs/archived-worktrees/{row_id}");
3038                            let ref_result = main_repo
3039                                .update(cx, |repo, _cx| repo.update_ref(ref_name, commit_hash));
3040                            match ref_result.await {
3041                                Ok(Ok(())) => {}
3042                                Ok(Err(err)) => {
3043                                    log::warn!("Failed to create archive ref: {err}")
3044                                }
3045                                Err(_) => log::warn!("Archive ref creation was canceled"),
3046                            }
3047                        }
3048                    }
3049                    Err(err) => {
3050                        log::error!("Failed to create archived worktree record: {err}");
3051                        undo_wip_commit(cx).await;
3052                        unarchive(cx);
3053                        cx.prompt(
3054                            PromptLevel::Warning,
3055                            "Failed to archive worktree",
3056                            Some(
3057                                "Could not save the archived worktree record. \
3058                                 The WIP commit has been undone and the thread \
3059                                 has been restored to the sidebar.",
3060                            ),
3061                            &["OK"],
3062                        )
3063                        .await
3064                        .ok();
3065                        return anyhow::Ok(());
3066                    }
3067                }
3068            }
3069
3070            // Delete the worktree directory.
3071            let timestamp = std::time::SystemTime::now()
3072                .duration_since(std::time::UNIX_EPOCH)
3073                .unwrap_or_default()
3074                .as_nanos();
3075            let temp_path = std::env::temp_dir().join(format!("zed-removing-worktree-{timestamp}"));
3076
3077            if let Err(err) = fs
3078                .rename(
3079                    &worktree_path,
3080                    &temp_path,
3081                    fs::RenameOptions {
3082                        overwrite: false,
3083                        ..Default::default()
3084                    },
3085                )
3086                .await
3087            {
3088                log::error!("Failed to move worktree to temp dir: {err}");
3089                return anyhow::Ok(());
3090            }
3091
3092            if let Some(main_repo) = &main_repo {
3093                let receiver =
3094                    main_repo.update(cx, |repo, _cx| repo.remove_worktree(worktree_path, true));
3095                if let Ok(result) = receiver.await {
3096                    result.log_err();
3097                }
3098            }
3099
3100            fs.remove_dir(
3101                &temp_path,
3102                fs::RemoveOptions {
3103                    recursive: true,
3104                    ignore_if_not_exists: true,
3105                },
3106            )
3107            .await
3108            .log_err();
3109
3110            anyhow::Ok(())
3111        })
3112        .detach_and_log_err(cx);
3113    }
3114
3115    fn remove_selected_thread(
3116        &mut self,
3117        _: &RemoveSelectedThread,
3118        window: &mut Window,
3119        cx: &mut Context<Self>,
3120    ) {
3121        let Some(ix) = self.selection else {
3122            return;
3123        };
3124        let Some(ListEntry::Thread(thread)) = self.contents.entries.get(ix) else {
3125            return;
3126        };
3127        match thread.status {
3128            AgentThreadStatus::Running | AgentThreadStatus::WaitingForConfirmation => return,
3129            AgentThreadStatus::Completed | AgentThreadStatus::Error => {}
3130        }
3131
3132        let session_id = thread.metadata.session_id.clone();
3133        self.archive_thread(&session_id, window, cx)
3134    }
3135
3136    fn record_thread_access(&mut self, session_id: &acp::SessionId) {
3137        self.thread_last_accessed
3138            .insert(session_id.clone(), Utc::now());
3139    }
3140
3141    fn record_thread_message_sent(&mut self, session_id: &acp::SessionId) {
3142        self.thread_last_message_sent_or_queued
3143            .insert(session_id.clone(), Utc::now());
3144    }
3145
3146    fn mru_threads_for_switcher(&self, _cx: &App) -> Vec<ThreadSwitcherEntry> {
3147        let mut current_header_label: Option<SharedString> = None;
3148        let mut current_header_workspace: Option<Entity<Workspace>> = None;
3149        let mut entries: Vec<ThreadSwitcherEntry> = self
3150            .contents
3151            .entries
3152            .iter()
3153            .filter_map(|entry| match entry {
3154                ListEntry::ProjectHeader {
3155                    label, workspace, ..
3156                } => {
3157                    current_header_label = Some(label.clone());
3158                    current_header_workspace = Some(workspace.clone());
3159                    None
3160                }
3161                ListEntry::Thread(thread) => {
3162                    let workspace = match &thread.workspace {
3163                        ThreadEntryWorkspace::Open(workspace) => workspace.clone(),
3164                        ThreadEntryWorkspace::Closed(_) => {
3165                            current_header_workspace.as_ref()?.clone()
3166                        }
3167                    };
3168                    let notified = self
3169                        .contents
3170                        .is_thread_notified(&thread.metadata.session_id);
3171                    let timestamp: SharedString = format_history_entry_timestamp(
3172                        self.thread_last_message_sent_or_queued
3173                            .get(&thread.metadata.session_id)
3174                            .copied()
3175                            .or(thread.metadata.created_at)
3176                            .unwrap_or(thread.metadata.updated_at),
3177                    )
3178                    .into();
3179                    Some(ThreadSwitcherEntry {
3180                        session_id: thread.metadata.session_id.clone(),
3181                        title: thread.metadata.title.clone(),
3182                        icon: thread.icon,
3183                        icon_from_external_svg: thread.icon_from_external_svg.clone(),
3184                        status: thread.status,
3185                        metadata: thread.metadata.clone(),
3186                        workspace,
3187                        project_name: current_header_label.clone(),
3188                        worktrees: thread
3189                            .worktrees
3190                            .iter()
3191                            .map(|wt| ThreadItemWorktreeInfo {
3192                                name: wt.name.clone(),
3193                                full_path: wt.full_path.clone(),
3194                                highlight_positions: Vec::new(),
3195                            })
3196                            .collect(),
3197                        diff_stats: thread.diff_stats,
3198                        is_title_generating: thread.is_title_generating,
3199                        notified,
3200                        timestamp,
3201                    })
3202                }
3203                _ => None,
3204            })
3205            .collect();
3206
3207        entries.sort_by(|a, b| {
3208            let a_accessed = self.thread_last_accessed.get(&a.session_id);
3209            let b_accessed = self.thread_last_accessed.get(&b.session_id);
3210
3211            match (a_accessed, b_accessed) {
3212                (Some(a_time), Some(b_time)) => b_time.cmp(a_time),
3213                (Some(_), None) => std::cmp::Ordering::Less,
3214                (None, Some(_)) => std::cmp::Ordering::Greater,
3215                (None, None) => {
3216                    let a_sent = self.thread_last_message_sent_or_queued.get(&a.session_id);
3217                    let b_sent = self.thread_last_message_sent_or_queued.get(&b.session_id);
3218
3219                    match (a_sent, b_sent) {
3220                        (Some(a_time), Some(b_time)) => b_time.cmp(a_time),
3221                        (Some(_), None) => std::cmp::Ordering::Less,
3222                        (None, Some(_)) => std::cmp::Ordering::Greater,
3223                        (None, None) => {
3224                            let a_time = a.metadata.created_at.or(Some(a.metadata.updated_at));
3225                            let b_time = b.metadata.created_at.or(Some(b.metadata.updated_at));
3226                            b_time.cmp(&a_time)
3227                        }
3228                    }
3229                }
3230            }
3231        });
3232
3233        entries
3234    }
3235
3236    fn dismiss_thread_switcher(&mut self, cx: &mut Context<Self>) {
3237        self.thread_switcher = None;
3238        self._thread_switcher_subscriptions.clear();
3239        if let Some(mw) = self.multi_workspace.upgrade() {
3240            mw.update(cx, |mw, cx| {
3241                mw.set_sidebar_overlay(None, cx);
3242            });
3243        }
3244    }
3245
3246    fn on_toggle_thread_switcher(
3247        &mut self,
3248        action: &ToggleThreadSwitcher,
3249        window: &mut Window,
3250        cx: &mut Context<Self>,
3251    ) {
3252        self.toggle_thread_switcher_impl(action.select_last, window, cx);
3253    }
3254
3255    fn toggle_thread_switcher_impl(
3256        &mut self,
3257        select_last: bool,
3258        window: &mut Window,
3259        cx: &mut Context<Self>,
3260    ) {
3261        if let Some(thread_switcher) = &self.thread_switcher {
3262            thread_switcher.update(cx, |switcher, cx| {
3263                if select_last {
3264                    switcher.select_last(cx);
3265                } else {
3266                    switcher.cycle_selection(cx);
3267                }
3268            });
3269            return;
3270        }
3271
3272        let entries = self.mru_threads_for_switcher(cx);
3273        if entries.len() < 2 {
3274            return;
3275        }
3276
3277        let weak_multi_workspace = self.multi_workspace.clone();
3278
3279        let original_metadata = match &self.active_entry {
3280            Some(ActiveEntry::Thread { session_id, .. }) => entries
3281                .iter()
3282                .find(|e| &e.session_id == session_id)
3283                .map(|e| e.metadata.clone()),
3284            _ => None,
3285        };
3286        let original_workspace = self
3287            .multi_workspace
3288            .upgrade()
3289            .map(|mw| mw.read(cx).workspace().clone());
3290
3291        let thread_switcher = cx.new(|cx| ThreadSwitcher::new(entries, select_last, window, cx));
3292
3293        let mut subscriptions = Vec::new();
3294
3295        subscriptions.push(cx.subscribe_in(&thread_switcher, window, {
3296            let thread_switcher = thread_switcher.clone();
3297            move |this, _emitter, event: &ThreadSwitcherEvent, window, cx| match event {
3298                ThreadSwitcherEvent::Preview {
3299                    metadata,
3300                    workspace,
3301                } => {
3302                    if let Some(mw) = weak_multi_workspace.upgrade() {
3303                        mw.update(cx, |mw, cx| {
3304                            mw.activate(workspace.clone(), window, cx);
3305                        });
3306                    }
3307                    this.active_entry = Some(ActiveEntry::Thread {
3308                        session_id: metadata.session_id.clone(),
3309                        workspace: workspace.clone(),
3310                    });
3311                    this.update_entries(cx);
3312                    Self::load_agent_thread_in_workspace(workspace, metadata, false, window, cx);
3313                    let focus = thread_switcher.focus_handle(cx);
3314                    window.focus(&focus, cx);
3315                }
3316                ThreadSwitcherEvent::Confirmed {
3317                    metadata,
3318                    workspace,
3319                } => {
3320                    if let Some(mw) = weak_multi_workspace.upgrade() {
3321                        mw.update(cx, |mw, cx| {
3322                            mw.activate(workspace.clone(), window, cx);
3323                        });
3324                    }
3325                    this.record_thread_access(&metadata.session_id);
3326                    this.active_entry = Some(ActiveEntry::Thread {
3327                        session_id: metadata.session_id.clone(),
3328                        workspace: workspace.clone(),
3329                    });
3330                    this.update_entries(cx);
3331                    Self::load_agent_thread_in_workspace(workspace, metadata, false, window, cx);
3332                    this.dismiss_thread_switcher(cx);
3333                    workspace.update(cx, |workspace, cx| {
3334                        workspace.focus_panel::<AgentPanel>(window, cx);
3335                    });
3336                }
3337                ThreadSwitcherEvent::Dismissed => {
3338                    if let Some(mw) = weak_multi_workspace.upgrade() {
3339                        if let Some(original_ws) = &original_workspace {
3340                            mw.update(cx, |mw, cx| {
3341                                mw.activate(original_ws.clone(), window, cx);
3342                            });
3343                        }
3344                    }
3345                    if let Some(metadata) = &original_metadata {
3346                        if let Some(original_ws) = &original_workspace {
3347                            this.active_entry = Some(ActiveEntry::Thread {
3348                                session_id: metadata.session_id.clone(),
3349                                workspace: original_ws.clone(),
3350                            });
3351                        }
3352                        this.update_entries(cx);
3353                        if let Some(original_ws) = &original_workspace {
3354                            Self::load_agent_thread_in_workspace(
3355                                original_ws,
3356                                metadata,
3357                                false,
3358                                window,
3359                                cx,
3360                            );
3361                        }
3362                    }
3363                    this.dismiss_thread_switcher(cx);
3364                }
3365            }
3366        }));
3367
3368        subscriptions.push(cx.subscribe_in(
3369            &thread_switcher,
3370            window,
3371            |this, _emitter, _event: &gpui::DismissEvent, _window, cx| {
3372                this.dismiss_thread_switcher(cx);
3373            },
3374        ));
3375
3376        let focus = thread_switcher.focus_handle(cx);
3377        let overlay_view = gpui::AnyView::from(thread_switcher.clone());
3378
3379        // Replay the initial preview that was emitted during construction
3380        // before subscriptions were wired up.
3381        let initial_preview = thread_switcher
3382            .read(cx)
3383            .selected_entry()
3384            .map(|entry| (entry.metadata.clone(), entry.workspace.clone()));
3385
3386        self.thread_switcher = Some(thread_switcher);
3387        self._thread_switcher_subscriptions = subscriptions;
3388        if let Some(mw) = self.multi_workspace.upgrade() {
3389            mw.update(cx, |mw, cx| {
3390                mw.set_sidebar_overlay(Some(overlay_view), cx);
3391            });
3392        }
3393
3394        if let Some((metadata, workspace)) = initial_preview {
3395            if let Some(mw) = self.multi_workspace.upgrade() {
3396                mw.update(cx, |mw, cx| {
3397                    mw.activate(workspace.clone(), window, cx);
3398                });
3399            }
3400            self.active_entry = Some(ActiveEntry::Thread {
3401                session_id: metadata.session_id.clone(),
3402                workspace: workspace.clone(),
3403            });
3404            self.update_entries(cx);
3405            Self::load_agent_thread_in_workspace(&workspace, &metadata, false, window, cx);
3406        }
3407
3408        window.focus(&focus, cx);
3409    }
3410
3411    fn render_thread(
3412        &self,
3413        ix: usize,
3414        thread: &ThreadEntry,
3415        is_active: bool,
3416        is_focused: bool,
3417        cx: &mut Context<Self>,
3418    ) -> AnyElement {
3419        let has_notification = self
3420            .contents
3421            .is_thread_notified(&thread.metadata.session_id);
3422
3423        let title: SharedString = thread.metadata.title.clone();
3424        let metadata = thread.metadata.clone();
3425        let thread_workspace = thread.workspace.clone();
3426
3427        let is_hovered = self.hovered_thread_index == Some(ix);
3428        let is_selected = is_active;
3429        let is_running = matches!(
3430            thread.status,
3431            AgentThreadStatus::Running | AgentThreadStatus::WaitingForConfirmation
3432        );
3433
3434        let session_id_for_delete = thread.metadata.session_id.clone();
3435        let focus_handle = self.focus_handle.clone();
3436
3437        let id = SharedString::from(format!("thread-entry-{}", ix));
3438
3439        let color = cx.theme().colors();
3440        let sidebar_bg = color
3441            .title_bar_background
3442            .blend(color.panel_background.opacity(0.32));
3443
3444        let timestamp = format_history_entry_timestamp(
3445            self.thread_last_message_sent_or_queued
3446                .get(&thread.metadata.session_id)
3447                .copied()
3448                .or(thread.metadata.created_at)
3449                .unwrap_or(thread.metadata.updated_at),
3450        );
3451
3452        ThreadItem::new(id, title)
3453            .base_bg(sidebar_bg)
3454            .icon(thread.icon)
3455            .status(thread.status)
3456            .when_some(thread.icon_from_external_svg.clone(), |this, svg| {
3457                this.custom_icon_from_external_svg(svg)
3458            })
3459            .worktrees(
3460                thread
3461                    .worktrees
3462                    .iter()
3463                    .map(|wt| ThreadItemWorktreeInfo {
3464                        name: wt.name.clone(),
3465                        full_path: wt.full_path.clone(),
3466                        highlight_positions: wt.highlight_positions.clone(),
3467                    })
3468                    .collect(),
3469            )
3470            .timestamp(timestamp)
3471            .highlight_positions(thread.highlight_positions.to_vec())
3472            .title_generating(thread.is_title_generating)
3473            .notified(has_notification)
3474            .when(thread.diff_stats.lines_added > 0, |this| {
3475                this.added(thread.diff_stats.lines_added as usize)
3476            })
3477            .when(thread.diff_stats.lines_removed > 0, |this| {
3478                this.removed(thread.diff_stats.lines_removed as usize)
3479            })
3480            .selected(is_selected)
3481            .focused(is_focused)
3482            .hovered(is_hovered)
3483            .on_hover(cx.listener(move |this, is_hovered: &bool, _window, cx| {
3484                if *is_hovered {
3485                    this.hovered_thread_index = Some(ix);
3486                } else if this.hovered_thread_index == Some(ix) {
3487                    this.hovered_thread_index = None;
3488                }
3489                cx.notify();
3490            }))
3491            .when(is_hovered && is_running, |this| {
3492                this.action_slot(
3493                    IconButton::new("stop-thread", IconName::Stop)
3494                        .icon_size(IconSize::Small)
3495                        .icon_color(Color::Error)
3496                        .style(ButtonStyle::Tinted(TintColor::Error))
3497                        .tooltip(Tooltip::text("Stop Generation"))
3498                        .on_click({
3499                            let session_id = session_id_for_delete.clone();
3500                            cx.listener(move |this, _, _window, cx| {
3501                                this.stop_thread(&session_id, cx);
3502                            })
3503                        }),
3504                )
3505            })
3506            .when(is_hovered && !is_running, |this| {
3507                this.action_slot(
3508                    IconButton::new("archive-thread", IconName::Archive)
3509                        .icon_size(IconSize::Small)
3510                        .icon_color(Color::Muted)
3511                        .tooltip({
3512                            let focus_handle = focus_handle.clone();
3513                            move |_window, cx| {
3514                                Tooltip::for_action_in(
3515                                    "Archive Thread",
3516                                    &RemoveSelectedThread,
3517                                    &focus_handle,
3518                                    cx,
3519                                )
3520                            }
3521                        })
3522                        .on_click({
3523                            let session_id = session_id_for_delete.clone();
3524                            cx.listener(move |this, _, window, cx| {
3525                                this.archive_thread(&session_id, window, cx);
3526                            })
3527                        }),
3528                )
3529            })
3530            .on_click({
3531                cx.listener(move |this, _, window, cx| {
3532                    this.selection = None;
3533                    match &thread_workspace {
3534                        ThreadEntryWorkspace::Open(workspace) => {
3535                            this.activate_thread(metadata.clone(), workspace, window, cx);
3536                        }
3537                        ThreadEntryWorkspace::Closed(path_list) => {
3538                            this.open_workspace_and_activate_thread(
3539                                metadata.clone(),
3540                                path_list.clone(),
3541                                window,
3542                                cx,
3543                            );
3544                        }
3545                    }
3546                })
3547            })
3548            .into_any_element()
3549    }
3550
3551    fn render_filter_input(&self, cx: &mut Context<Self>) -> impl IntoElement {
3552        div()
3553            .min_w_0()
3554            .flex_1()
3555            .capture_action(
3556                cx.listener(|this, _: &editor::actions::Newline, window, cx| {
3557                    this.editor_confirm(window, cx);
3558                }),
3559            )
3560            .child(self.filter_editor.clone())
3561    }
3562
3563    fn render_recent_projects_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
3564        let multi_workspace = self.multi_workspace.upgrade();
3565
3566        let workspace = multi_workspace
3567            .as_ref()
3568            .map(|mw| mw.read(cx).workspace().downgrade());
3569
3570        let focus_handle = workspace
3571            .as_ref()
3572            .and_then(|ws| ws.upgrade())
3573            .map(|w| w.read(cx).focus_handle(cx))
3574            .unwrap_or_else(|| cx.focus_handle());
3575
3576        let sibling_workspace_ids: HashSet<WorkspaceId> = multi_workspace
3577            .as_ref()
3578            .map(|mw| {
3579                mw.read(cx)
3580                    .workspaces()
3581                    .iter()
3582                    .filter_map(|ws| ws.read(cx).database_id())
3583                    .collect()
3584            })
3585            .unwrap_or_default();
3586
3587        let popover_handle = self.recent_projects_popover_handle.clone();
3588
3589        PopoverMenu::new("sidebar-recent-projects-menu")
3590            .with_handle(popover_handle)
3591            .menu(move |window, cx| {
3592                workspace.as_ref().map(|ws| {
3593                    SidebarRecentProjects::popover(
3594                        ws.clone(),
3595                        sibling_workspace_ids.clone(),
3596                        focus_handle.clone(),
3597                        window,
3598                        cx,
3599                    )
3600                })
3601            })
3602            .trigger_with_tooltip(
3603                IconButton::new("open-project", IconName::OpenFolder)
3604                    .icon_size(IconSize::Small)
3605                    .selected_style(ButtonStyle::Tinted(TintColor::Accent)),
3606                |_window, cx| {
3607                    Tooltip::for_action(
3608                        "Add Project",
3609                        &OpenRecent {
3610                            create_new_window: false,
3611                        },
3612                        cx,
3613                    )
3614                },
3615            )
3616            .offset(gpui::Point {
3617                x: px(-2.0),
3618                y: px(-2.0),
3619            })
3620            .anchor(gpui::Corner::BottomRight)
3621    }
3622
3623    fn render_view_more(
3624        &self,
3625        ix: usize,
3626        path_list: &PathList,
3627        is_fully_expanded: bool,
3628        is_selected: bool,
3629        cx: &mut Context<Self>,
3630    ) -> AnyElement {
3631        let path_list = path_list.clone();
3632        let id = SharedString::from(format!("view-more-{}", ix));
3633
3634        let label: SharedString = if is_fully_expanded {
3635            "Collapse".into()
3636        } else {
3637            "View More".into()
3638        };
3639
3640        ThreadItem::new(id, label)
3641            .focused(is_selected)
3642            .icon_visible(false)
3643            .title_label_color(Color::Muted)
3644            .on_click(cx.listener(move |this, _, _window, cx| {
3645                this.selection = None;
3646                if is_fully_expanded {
3647                    this.expanded_groups.remove(&path_list);
3648                } else {
3649                    let current = this.expanded_groups.get(&path_list).copied().unwrap_or(0);
3650                    this.expanded_groups.insert(path_list.clone(), current + 1);
3651                }
3652                this.serialize(cx);
3653                this.update_entries(cx);
3654            }))
3655            .into_any_element()
3656    }
3657
3658    fn new_thread_in_group(
3659        &mut self,
3660        _: &NewThreadInGroup,
3661        window: &mut Window,
3662        cx: &mut Context<Self>,
3663    ) {
3664        // If there is a keyboard selection, walk backwards through
3665        // `project_header_indices` to find the header that owns the selected
3666        // row. Otherwise fall back to the active workspace.
3667        let workspace = if let Some(selected_ix) = self.selection {
3668            self.contents
3669                .project_header_indices
3670                .iter()
3671                .rev()
3672                .find(|&&header_ix| header_ix <= selected_ix)
3673                .and_then(|&header_ix| match &self.contents.entries[header_ix] {
3674                    ListEntry::ProjectHeader { workspace, .. } => Some(workspace.clone()),
3675                    _ => None,
3676                })
3677        } else {
3678            // Use the currently active workspace.
3679            self.multi_workspace
3680                .upgrade()
3681                .map(|mw| mw.read(cx).workspace().clone())
3682        };
3683
3684        let Some(workspace) = workspace else {
3685            return;
3686        };
3687
3688        self.create_new_thread(&workspace, window, cx);
3689    }
3690
3691    fn create_new_thread(
3692        &mut self,
3693        workspace: &Entity<Workspace>,
3694        window: &mut Window,
3695        cx: &mut Context<Self>,
3696    ) {
3697        let Some(multi_workspace) = self.multi_workspace.upgrade() else {
3698            return;
3699        };
3700
3701        self.active_entry = Some(ActiveEntry::Draft(workspace.clone()));
3702
3703        multi_workspace.update(cx, |multi_workspace, cx| {
3704            multi_workspace.activate(workspace.clone(), window, cx);
3705        });
3706
3707        workspace.update(cx, |workspace, cx| {
3708            if let Some(agent_panel) = workspace.panel::<AgentPanel>(cx) {
3709                agent_panel.update(cx, |panel, cx| {
3710                    panel.new_thread(&NewThread, window, cx);
3711                });
3712            }
3713            workspace.focus_panel::<AgentPanel>(window, cx);
3714        });
3715    }
3716
3717    fn render_new_thread(
3718        &self,
3719        ix: usize,
3720        _path_list: &PathList,
3721        workspace: &Entity<Workspace>,
3722        is_active: bool,
3723        worktrees: &[WorktreeInfo],
3724        is_selected: bool,
3725        cx: &mut Context<Self>,
3726    ) -> AnyElement {
3727        let label: SharedString = if is_active {
3728            self.active_draft_text(cx)
3729                .unwrap_or_else(|| DEFAULT_THREAD_TITLE.into())
3730        } else {
3731            DEFAULT_THREAD_TITLE.into()
3732        };
3733
3734        let workspace = workspace.clone();
3735        let id = SharedString::from(format!("new-thread-btn-{}", ix));
3736
3737        let thread_item = ThreadItem::new(id, label)
3738            .icon(IconName::Plus)
3739            .icon_color(Color::Custom(cx.theme().colors().icon_muted.opacity(0.8)))
3740            .worktrees(
3741                worktrees
3742                    .iter()
3743                    .map(|wt| ThreadItemWorktreeInfo {
3744                        name: wt.name.clone(),
3745                        full_path: wt.full_path.clone(),
3746                        highlight_positions: wt.highlight_positions.clone(),
3747                    })
3748                    .collect(),
3749            )
3750            .selected(is_active)
3751            .focused(is_selected)
3752            .when(!is_active, |this| {
3753                this.on_click(cx.listener(move |this, _, window, cx| {
3754                    this.selection = None;
3755                    this.create_new_thread(&workspace, window, cx);
3756                }))
3757            });
3758
3759        if is_active {
3760            div()
3761                .on_mouse_down(gpui::MouseButton::Left, |_, _, cx| {
3762                    cx.stop_propagation();
3763                })
3764                .child(thread_item)
3765                .into_any_element()
3766        } else {
3767            thread_item.into_any_element()
3768        }
3769    }
3770
3771    fn render_no_results(&self, cx: &mut Context<Self>) -> impl IntoElement {
3772        let has_query = self.has_filter_query(cx);
3773        let message = if has_query {
3774            "No threads match your search."
3775        } else {
3776            "No threads yet"
3777        };
3778
3779        v_flex()
3780            .id("sidebar-no-results")
3781            .p_4()
3782            .size_full()
3783            .items_center()
3784            .justify_center()
3785            .child(
3786                Label::new(message)
3787                    .size(LabelSize::Small)
3788                    .color(Color::Muted),
3789            )
3790    }
3791
3792    fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
3793        v_flex()
3794            .id("sidebar-empty-state")
3795            .p_4()
3796            .size_full()
3797            .items_center()
3798            .justify_center()
3799            .gap_1()
3800            .track_focus(&self.focus_handle(cx))
3801            .child(
3802                Button::new("open_project", "Open Project")
3803                    .full_width()
3804                    .key_binding(KeyBinding::for_action(&workspace::Open::default(), cx))
3805                    .on_click(|_, window, cx| {
3806                        window.dispatch_action(
3807                            Open {
3808                                create_new_window: false,
3809                            }
3810                            .boxed_clone(),
3811                            cx,
3812                        );
3813                    }),
3814            )
3815            .child(
3816                h_flex()
3817                    .w_1_2()
3818                    .gap_2()
3819                    .child(Divider::horizontal().color(ui::DividerColor::Border))
3820                    .child(Label::new("or").size(LabelSize::XSmall).color(Color::Muted))
3821                    .child(Divider::horizontal().color(ui::DividerColor::Border)),
3822            )
3823            .child(
3824                Button::new("clone_repo", "Clone Repository")
3825                    .full_width()
3826                    .on_click(|_, window, cx| {
3827                        window.dispatch_action(git::Clone.boxed_clone(), cx);
3828                    }),
3829            )
3830    }
3831
3832    fn render_sidebar_header(
3833        &self,
3834        no_open_projects: bool,
3835        window: &Window,
3836        cx: &mut Context<Self>,
3837    ) -> impl IntoElement {
3838        let has_query = self.has_filter_query(cx);
3839        let sidebar_on_left = self.side(cx) == SidebarSide::Left;
3840        let sidebar_on_right = self.side(cx) == SidebarSide::Right;
3841        let not_fullscreen = !window.is_fullscreen();
3842        let traffic_lights = cfg!(target_os = "macos") && not_fullscreen && sidebar_on_left;
3843        let left_window_controls = !cfg!(target_os = "macos") && not_fullscreen && sidebar_on_left;
3844        let right_window_controls =
3845            !cfg!(target_os = "macos") && not_fullscreen && sidebar_on_right;
3846        let header_height = platform_title_bar_height(window);
3847
3848        h_flex()
3849            .h(header_height)
3850            .mt_px()
3851            .pb_px()
3852            .when(left_window_controls, |this| {
3853                this.children(Self::render_left_window_controls(window, cx))
3854            })
3855            .map(|this| {
3856                if traffic_lights {
3857                    this.pl(px(ui::utils::TRAFFIC_LIGHT_PADDING))
3858                } else if !left_window_controls {
3859                    this.pl_1p5()
3860                } else {
3861                    this
3862                }
3863            })
3864            .when(!right_window_controls, |this| this.pr_1p5())
3865            .gap_1()
3866            .when(!no_open_projects, |this| {
3867                this.border_b_1()
3868                    .border_color(cx.theme().colors().border)
3869                    .when(traffic_lights, |this| {
3870                        this.child(Divider::vertical().color(ui::DividerColor::Border))
3871                    })
3872                    .child(
3873                        div().ml_1().child(
3874                            Icon::new(IconName::MagnifyingGlass)
3875                                .size(IconSize::Small)
3876                                .color(Color::Muted),
3877                        ),
3878                    )
3879                    .child(self.render_filter_input(cx))
3880                    .child(
3881                        h_flex()
3882                            .gap_1()
3883                            .when(
3884                                self.selection.is_some()
3885                                    && !self.filter_editor.focus_handle(cx).is_focused(window),
3886                                |this| this.child(KeyBinding::for_action(&FocusSidebarFilter, cx)),
3887                            )
3888                            .when(has_query, |this| {
3889                                this.child(
3890                                    IconButton::new("clear_filter", IconName::Close)
3891                                        .icon_size(IconSize::Small)
3892                                        .tooltip(Tooltip::text("Clear Search"))
3893                                        .on_click(cx.listener(|this, _, window, cx| {
3894                                            this.reset_filter_editor_text(window, cx);
3895                                            this.update_entries(cx);
3896                                        })),
3897                                )
3898                            }),
3899                    )
3900            })
3901            .when(right_window_controls, |this| {
3902                this.children(Self::render_right_window_controls(window, cx))
3903            })
3904    }
3905
3906    fn render_left_window_controls(window: &Window, cx: &mut App) -> Option<AnyElement> {
3907        platform_title_bar::render_left_window_controls(
3908            cx.button_layout(),
3909            Box::new(CloseWindow),
3910            window,
3911        )
3912    }
3913
3914    fn render_right_window_controls(window: &Window, cx: &mut App) -> Option<AnyElement> {
3915        platform_title_bar::render_right_window_controls(
3916            cx.button_layout(),
3917            Box::new(CloseWindow),
3918            window,
3919        )
3920    }
3921
3922    fn render_sidebar_toggle_button(&self, _cx: &mut Context<Self>) -> impl IntoElement {
3923        let on_right = AgentSettings::get_global(_cx).sidebar_side() == SidebarSide::Right;
3924
3925        sidebar_side_context_menu("sidebar-toggle-menu", _cx)
3926            .anchor(if on_right {
3927                gpui::Corner::BottomRight
3928            } else {
3929                gpui::Corner::BottomLeft
3930            })
3931            .attach(if on_right {
3932                gpui::Corner::TopRight
3933            } else {
3934                gpui::Corner::TopLeft
3935            })
3936            .trigger(move |_is_active, _window, _cx| {
3937                let icon = if on_right {
3938                    IconName::ThreadsSidebarRightOpen
3939                } else {
3940                    IconName::ThreadsSidebarLeftOpen
3941                };
3942                IconButton::new("sidebar-close-toggle", icon)
3943                    .icon_size(IconSize::Small)
3944                    .tooltip(Tooltip::element(move |_window, cx| {
3945                        v_flex()
3946                            .gap_1()
3947                            .child(
3948                                h_flex()
3949                                    .gap_2()
3950                                    .justify_between()
3951                                    .child(Label::new("Toggle Sidebar"))
3952                                    .child(KeyBinding::for_action(&ToggleWorkspaceSidebar, cx)),
3953                            )
3954                            .child(
3955                                h_flex()
3956                                    .pt_1()
3957                                    .gap_2()
3958                                    .border_t_1()
3959                                    .border_color(cx.theme().colors().border_variant)
3960                                    .justify_between()
3961                                    .child(Label::new("Focus Sidebar"))
3962                                    .child(KeyBinding::for_action(&FocusWorkspaceSidebar, cx)),
3963                            )
3964                            .into_any_element()
3965                    }))
3966                    .on_click(|_, window, cx| {
3967                        if let Some(multi_workspace) = window.root::<MultiWorkspace>().flatten() {
3968                            multi_workspace.update(cx, |multi_workspace, cx| {
3969                                multi_workspace.close_sidebar(window, cx);
3970                            });
3971                        }
3972                    })
3973            })
3974    }
3975
3976    fn render_sidebar_bottom_bar(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
3977        let is_archive = matches!(self.view, SidebarView::Archive(..));
3978        let show_import_button = is_archive && !self.should_render_acp_import_onboarding(cx);
3979        let on_right = self.side(cx) == SidebarSide::Right;
3980
3981        let action_buttons = h_flex()
3982            .gap_1()
3983            .when(on_right, |this| this.flex_row_reverse())
3984            .when(show_import_button, |this| {
3985                this.child(
3986                    IconButton::new("thread-import", IconName::ThreadImport)
3987                        .icon_size(IconSize::Small)
3988                        .tooltip(Tooltip::text("Import ACP Threads"))
3989                        .on_click(cx.listener(|this, _, window, cx| {
3990                            this.show_archive(window, cx);
3991                            this.show_thread_import_modal(window, cx);
3992                        })),
3993                )
3994            })
3995            .child(
3996                IconButton::new("archive", IconName::Archive)
3997                    .icon_size(IconSize::Small)
3998                    .toggle_state(is_archive)
3999                    .tooltip(move |_, cx| {
4000                        Tooltip::for_action("Toggle Archived Threads", &ToggleArchive, cx)
4001                    })
4002                    .on_click(cx.listener(|this, _, window, cx| {
4003                        this.toggle_archive(&ToggleArchive, window, cx);
4004                    })),
4005            )
4006            .child(self.render_recent_projects_button(cx));
4007
4008        h_flex()
4009            .p_1()
4010            .gap_1()
4011            .when(on_right, |this| this.flex_row_reverse())
4012            .justify_between()
4013            .border_t_1()
4014            .border_color(cx.theme().colors().border)
4015            .child(self.render_sidebar_toggle_button(cx))
4016            .child(action_buttons)
4017    }
4018
4019    fn active_workspace(&self, cx: &App) -> Option<Entity<Workspace>> {
4020        self.multi_workspace.upgrade().and_then(|w| {
4021            w.read(cx)
4022                .workspaces()
4023                .get(w.read(cx).active_workspace_index())
4024                .cloned()
4025        })
4026    }
4027
4028    fn show_thread_import_modal(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4029        let Some(active_workspace) = self.active_workspace(cx) else {
4030            return;
4031        };
4032
4033        let Some(agent_registry_store) = AgentRegistryStore::try_global(cx) else {
4034            return;
4035        };
4036
4037        let agent_server_store = active_workspace
4038            .read(cx)
4039            .project()
4040            .read(cx)
4041            .agent_server_store()
4042            .clone();
4043
4044        let workspace_handle = active_workspace.downgrade();
4045        let multi_workspace = self.multi_workspace.clone();
4046
4047        active_workspace.update(cx, |workspace, cx| {
4048            workspace.toggle_modal(window, cx, |window, cx| {
4049                ThreadImportModal::new(
4050                    agent_server_store,
4051                    agent_registry_store,
4052                    workspace_handle.clone(),
4053                    multi_workspace.clone(),
4054                    window,
4055                    cx,
4056                )
4057            });
4058        });
4059    }
4060
4061    fn should_render_acp_import_onboarding(&self, cx: &App) -> bool {
4062        let has_external_agents = self
4063            .active_workspace(cx)
4064            .map(|ws| {
4065                ws.read(cx)
4066                    .project()
4067                    .read(cx)
4068                    .agent_server_store()
4069                    .read(cx)
4070                    .has_external_agents()
4071            })
4072            .unwrap_or(false);
4073
4074        has_external_agents && !AcpThreadImportOnboarding::dismissed(cx)
4075    }
4076
4077    fn render_acp_import_onboarding(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
4078        let description =
4079            "Import threads from your ACP agents — whether started in Zed or another client.";
4080
4081        let bg = cx.theme().colors().text_accent;
4082
4083        v_flex()
4084            .min_w_0()
4085            .w_full()
4086            .p_2()
4087            .border_t_1()
4088            .border_color(cx.theme().colors().border)
4089            .bg(linear_gradient(
4090                360.,
4091                linear_color_stop(bg.opacity(0.06), 1.),
4092                linear_color_stop(bg.opacity(0.), 0.),
4093            ))
4094            .child(
4095                h_flex()
4096                    .min_w_0()
4097                    .w_full()
4098                    .gap_1()
4099                    .justify_between()
4100                    .child(Label::new("Looking for ACP threads?"))
4101                    .child(
4102                        IconButton::new("close-onboarding", IconName::Close)
4103                            .icon_size(IconSize::Small)
4104                            .on_click(|_, _window, cx| AcpThreadImportOnboarding::dismiss(cx)),
4105                    ),
4106            )
4107            .child(Label::new(description).color(Color::Muted).mb_2())
4108            .child(
4109                Button::new("import-acp", "Import ACP Threads")
4110                    .full_width()
4111                    .style(ButtonStyle::OutlinedCustom(cx.theme().colors().border))
4112                    .label_size(LabelSize::Small)
4113                    .start_icon(
4114                        Icon::new(IconName::ThreadImport)
4115                            .size(IconSize::Small)
4116                            .color(Color::Muted),
4117                    )
4118                    .on_click(cx.listener(|this, _, window, cx| {
4119                        this.show_archive(window, cx);
4120                        this.show_thread_import_modal(window, cx);
4121                    })),
4122            )
4123    }
4124
4125    fn toggle_archive(&mut self, _: &ToggleArchive, window: &mut Window, cx: &mut Context<Self>) {
4126        match &self.view {
4127            SidebarView::ThreadList => self.show_archive(window, cx),
4128            SidebarView::Archive(_) => self.show_thread_list(window, cx),
4129        }
4130    }
4131
4132    fn show_archive(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4133        let Some(active_workspace) = self.multi_workspace.upgrade().and_then(|w| {
4134            w.read(cx)
4135                .workspaces()
4136                .get(w.read(cx).active_workspace_index())
4137                .cloned()
4138        }) else {
4139            return;
4140        };
4141        let Some(agent_panel) = active_workspace.read(cx).panel::<AgentPanel>(cx) else {
4142            return;
4143        };
4144
4145        let agent_server_store = active_workspace
4146            .read(cx)
4147            .project()
4148            .read(cx)
4149            .agent_server_store()
4150            .downgrade();
4151
4152        let agent_connection_store = agent_panel.read(cx).connection_store().downgrade();
4153
4154        let archive_view = cx.new(|cx| {
4155            ThreadsArchiveView::new(
4156                agent_connection_store.clone(),
4157                agent_server_store.clone(),
4158                window,
4159                cx,
4160            )
4161        });
4162
4163        let subscription = cx.subscribe_in(
4164            &archive_view,
4165            window,
4166            |this, _, event: &ThreadsArchiveViewEvent, window, cx| match event {
4167                ThreadsArchiveViewEvent::Close => {
4168                    this.show_thread_list(window, cx);
4169                }
4170                ThreadsArchiveViewEvent::Unarchive { thread } => {
4171                    this.show_thread_list(window, cx);
4172                    this.activate_archived_thread(thread.clone(), window, cx);
4173                }
4174            },
4175        );
4176
4177        self._subscriptions.push(subscription);
4178        self.view = SidebarView::Archive(archive_view.clone());
4179        archive_view.update(cx, |view, cx| view.focus_filter_editor(window, cx));
4180        self.serialize(cx);
4181        cx.notify();
4182    }
4183
4184    fn show_thread_list(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4185        self.view = SidebarView::ThreadList;
4186        self._subscriptions.clear();
4187        let handle = self.filter_editor.read(cx).focus_handle(cx);
4188        handle.focus(window, cx);
4189        self.serialize(cx);
4190        cx.notify();
4191    }
4192}
4193
4194impl WorkspaceSidebar for Sidebar {
4195    fn width(&self, _cx: &App) -> Pixels {
4196        self.width
4197    }
4198
4199    fn set_width(&mut self, width: Option<Pixels>, cx: &mut Context<Self>) {
4200        self.width = width.unwrap_or(DEFAULT_WIDTH).clamp(MIN_WIDTH, MAX_WIDTH);
4201        cx.notify();
4202    }
4203
4204    fn has_notifications(&self, _cx: &App) -> bool {
4205        !self.contents.notified_threads.is_empty()
4206    }
4207
4208    fn is_threads_list_view_active(&self) -> bool {
4209        matches!(self.view, SidebarView::ThreadList)
4210    }
4211
4212    fn side(&self, cx: &App) -> SidebarSide {
4213        AgentSettings::get_global(cx).sidebar_side()
4214    }
4215
4216    fn prepare_for_focus(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
4217        self.selection = None;
4218        cx.notify();
4219    }
4220
4221    fn toggle_thread_switcher(
4222        &mut self,
4223        select_last: bool,
4224        window: &mut Window,
4225        cx: &mut Context<Self>,
4226    ) {
4227        self.toggle_thread_switcher_impl(select_last, window, cx);
4228    }
4229
4230    fn serialized_state(&self, _cx: &App) -> Option<String> {
4231        let serialized = SerializedSidebar {
4232            width: Some(f32::from(self.width)),
4233            collapsed_groups: self
4234                .collapsed_groups
4235                .iter()
4236                .map(|pl| pl.serialize())
4237                .collect(),
4238            expanded_groups: self
4239                .expanded_groups
4240                .iter()
4241                .map(|(pl, count)| (pl.serialize(), *count))
4242                .collect(),
4243            active_view: match self.view {
4244                SidebarView::ThreadList => SerializedSidebarView::ThreadList,
4245                SidebarView::Archive(_) => SerializedSidebarView::Archive,
4246            },
4247        };
4248        serde_json::to_string(&serialized).ok()
4249    }
4250
4251    fn restore_serialized_state(
4252        &mut self,
4253        state: &str,
4254        window: &mut Window,
4255        cx: &mut Context<Self>,
4256    ) {
4257        if let Some(serialized) = serde_json::from_str::<SerializedSidebar>(state).log_err() {
4258            if let Some(width) = serialized.width {
4259                self.width = px(width).clamp(MIN_WIDTH, MAX_WIDTH);
4260            }
4261            self.collapsed_groups = serialized
4262                .collapsed_groups
4263                .into_iter()
4264                .map(|s| PathList::deserialize(&s))
4265                .collect();
4266            self.expanded_groups = serialized
4267                .expanded_groups
4268                .into_iter()
4269                .map(|(s, count)| (PathList::deserialize(&s), count))
4270                .collect();
4271            if serialized.active_view == SerializedSidebarView::Archive {
4272                cx.defer_in(window, |this, window, cx| {
4273                    this.show_archive(window, cx);
4274                });
4275            }
4276        }
4277        cx.notify();
4278    }
4279}
4280
4281impl gpui::EventEmitter<workspace::SidebarEvent> for Sidebar {}
4282
4283impl Focusable for Sidebar {
4284    fn focus_handle(&self, _cx: &App) -> FocusHandle {
4285        self.focus_handle.clone()
4286    }
4287}
4288
4289impl Render for Sidebar {
4290    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4291        let _titlebar_height = ui::utils::platform_title_bar_height(window);
4292        let ui_font = theme_settings::setup_ui_font(window, cx);
4293        let sticky_header = self.render_sticky_header(window, cx);
4294
4295        let color = cx.theme().colors();
4296        let bg = color
4297            .title_bar_background
4298            .blend(color.panel_background.opacity(0.32));
4299
4300        let no_open_projects = !self.contents.has_open_projects;
4301        let no_search_results = self.contents.entries.is_empty();
4302
4303        v_flex()
4304            .id("workspace-sidebar")
4305            .key_context(self.dispatch_context(window, cx))
4306            .track_focus(&self.focus_handle)
4307            .on_action(cx.listener(Self::select_next))
4308            .on_action(cx.listener(Self::select_previous))
4309            .on_action(cx.listener(Self::editor_move_down))
4310            .on_action(cx.listener(Self::editor_move_up))
4311            .on_action(cx.listener(Self::select_first))
4312            .on_action(cx.listener(Self::select_last))
4313            .on_action(cx.listener(Self::confirm))
4314            .on_action(cx.listener(Self::expand_selected_entry))
4315            .on_action(cx.listener(Self::collapse_selected_entry))
4316            .on_action(cx.listener(Self::toggle_selected_fold))
4317            .on_action(cx.listener(Self::fold_all))
4318            .on_action(cx.listener(Self::unfold_all))
4319            .on_action(cx.listener(Self::cancel))
4320            .on_action(cx.listener(Self::remove_selected_thread))
4321            .on_action(cx.listener(Self::new_thread_in_group))
4322            .on_action(cx.listener(Self::toggle_archive))
4323            .on_action(cx.listener(Self::focus_sidebar_filter))
4324            .on_action(cx.listener(Self::on_toggle_thread_switcher))
4325            .on_action(cx.listener(|this, _: &OpenRecent, window, cx| {
4326                this.recent_projects_popover_handle.toggle(window, cx);
4327            }))
4328            .font(ui_font)
4329            .h_full()
4330            .w(self.width)
4331            .bg(bg)
4332            .when(self.side(cx) == SidebarSide::Left, |el| el.border_r_1())
4333            .when(self.side(cx) == SidebarSide::Right, |el| el.border_l_1())
4334            .border_color(color.border)
4335            .map(|this| match &self.view {
4336                SidebarView::ThreadList => this
4337                    .child(self.render_sidebar_header(no_open_projects, window, cx))
4338                    .map(|this| {
4339                        if no_open_projects {
4340                            this.child(self.render_empty_state(cx))
4341                        } else {
4342                            this.child(
4343                                v_flex()
4344                                    .relative()
4345                                    .flex_1()
4346                                    .overflow_hidden()
4347                                    .child(
4348                                        list(
4349                                            self.list_state.clone(),
4350                                            cx.processor(Self::render_list_entry),
4351                                        )
4352                                        .flex_1()
4353                                        .size_full(),
4354                                    )
4355                                    .when(no_search_results, |this| {
4356                                        this.child(self.render_no_results(cx))
4357                                    })
4358                                    .when_some(sticky_header, |this, header| this.child(header))
4359                                    .vertical_scrollbar_for(&self.list_state, window, cx),
4360                            )
4361                        }
4362                    }),
4363                SidebarView::Archive(archive_view) => this.child(archive_view.clone()),
4364            })
4365            .when(self.should_render_acp_import_onboarding(cx), |this| {
4366                this.child(self.render_acp_import_onboarding(cx))
4367            })
4368            .child(self.render_sidebar_bottom_bar(cx))
4369    }
4370}
4371
4372fn all_thread_infos_for_workspace(
4373    workspace: &Entity<Workspace>,
4374    cx: &App,
4375) -> impl Iterator<Item = ActiveThreadInfo> {
4376    let Some(agent_panel) = workspace.read(cx).panel::<AgentPanel>(cx) else {
4377        return None.into_iter().flatten();
4378    };
4379    let agent_panel = agent_panel.read(cx);
4380
4381    let threads = agent_panel
4382        .parent_threads(cx)
4383        .into_iter()
4384        .map(|thread_view| {
4385            let thread_view_ref = thread_view.read(cx);
4386            let thread = thread_view_ref.thread.read(cx);
4387
4388            let icon = thread_view_ref.agent_icon;
4389            let icon_from_external_svg = thread_view_ref.agent_icon_from_external_svg.clone();
4390            let title = thread
4391                .title()
4392                .unwrap_or_else(|| DEFAULT_THREAD_TITLE.into());
4393            let is_native = thread_view_ref.as_native_thread(cx).is_some();
4394            let is_title_generating = is_native && thread.has_provisional_title();
4395            let session_id = thread.session_id().clone();
4396            let is_background = agent_panel.is_background_thread(&session_id);
4397
4398            let status = if thread.is_waiting_for_confirmation() {
4399                AgentThreadStatus::WaitingForConfirmation
4400            } else if thread.had_error() {
4401                AgentThreadStatus::Error
4402            } else {
4403                match thread.status() {
4404                    ThreadStatus::Generating => AgentThreadStatus::Running,
4405                    ThreadStatus::Idle => AgentThreadStatus::Completed,
4406                }
4407            };
4408
4409            let diff_stats = thread.action_log().read(cx).diff_stats(cx);
4410
4411            ActiveThreadInfo {
4412                session_id,
4413                title,
4414                status,
4415                icon,
4416                icon_from_external_svg,
4417                is_background,
4418                is_title_generating,
4419                diff_stats,
4420            }
4421        });
4422
4423    Some(threads).into_iter().flatten()
4424}
4425
4426pub fn dump_workspace_info(
4427    workspace: &mut Workspace,
4428    _: &DumpWorkspaceInfo,
4429    window: &mut gpui::Window,
4430    cx: &mut gpui::Context<Workspace>,
4431) {
4432    use std::fmt::Write;
4433
4434    let mut output = String::new();
4435    let this_entity = cx.entity();
4436
4437    let multi_workspace = workspace.multi_workspace().and_then(|weak| weak.upgrade());
4438    let workspaces: Vec<gpui::Entity<Workspace>> = match &multi_workspace {
4439        Some(mw) => mw.read(cx).workspaces().to_vec(),
4440        None => vec![this_entity.clone()],
4441    };
4442    let active_index = multi_workspace
4443        .as_ref()
4444        .map(|mw| mw.read(cx).active_workspace_index());
4445
4446    writeln!(output, "MultiWorkspace: {} workspace(s)", workspaces.len()).ok();
4447    if let Some(index) = active_index {
4448        writeln!(output, "Active workspace index: {index}").ok();
4449    }
4450    writeln!(output).ok();
4451
4452    for (index, ws) in workspaces.iter().enumerate() {
4453        let is_active = active_index == Some(index);
4454        writeln!(
4455            output,
4456            "--- Workspace {index}{} ---",
4457            if is_active { " (active)" } else { "" }
4458        )
4459        .ok();
4460
4461        // The action handler is already inside an update on `this_entity`,
4462        // so we must avoid a nested read/update on that same entity.
4463        if *ws == this_entity {
4464            dump_single_workspace(workspace, &mut output, cx);
4465        } else {
4466            ws.read_with(cx, |ws, cx| {
4467                dump_single_workspace(ws, &mut output, cx);
4468            });
4469        }
4470    }
4471
4472    let project = workspace.project().clone();
4473    cx.spawn_in(window, async move |_this, cx| {
4474        let buffer = project
4475            .update(cx, |project, cx| project.create_buffer(None, false, cx))
4476            .await?;
4477
4478        buffer.update(cx, |buffer, cx| {
4479            buffer.set_text(output, cx);
4480        });
4481
4482        let buffer = cx.new(|cx| {
4483            editor::MultiBuffer::singleton(buffer, cx).with_title("Workspace Info".into())
4484        });
4485
4486        _this.update_in(cx, |workspace, window, cx| {
4487            workspace.add_item_to_active_pane(
4488                Box::new(cx.new(|cx| {
4489                    let mut editor =
4490                        editor::Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
4491                    editor.set_read_only(true);
4492                    editor.set_should_serialize(false, cx);
4493                    editor.set_breadcrumb_header("Workspace Info".into());
4494                    editor
4495                })),
4496                None,
4497                true,
4498                window,
4499                cx,
4500            );
4501        })
4502    })
4503    .detach_and_log_err(cx);
4504}
4505
4506fn dump_single_workspace(workspace: &Workspace, output: &mut String, cx: &gpui::App) {
4507    use std::fmt::Write;
4508
4509    let workspace_db_id = workspace.database_id();
4510    match workspace_db_id {
4511        Some(id) => writeln!(output, "Workspace DB ID: {id:?}").ok(),
4512        None => writeln!(output, "Workspace DB ID: (none)").ok(),
4513    };
4514
4515    let project = workspace.project().read(cx);
4516
4517    let repos: Vec<_> = project
4518        .repositories(cx)
4519        .values()
4520        .map(|repo| repo.read(cx).snapshot())
4521        .collect();
4522
4523    writeln!(output, "Worktrees:").ok();
4524    for worktree in project.worktrees(cx) {
4525        let worktree = worktree.read(cx);
4526        let abs_path = worktree.abs_path();
4527        let visible = worktree.is_visible();
4528
4529        let repo_info = repos
4530            .iter()
4531            .find(|snapshot| abs_path.starts_with(&*snapshot.work_directory_abs_path));
4532
4533        let is_linked = repo_info.map(|s| s.is_linked_worktree()).unwrap_or(false);
4534        let original_repo_path = repo_info.map(|s| &s.original_repo_abs_path);
4535        let branch = repo_info.and_then(|s| s.branch.as_ref().map(|b| b.ref_name.clone()));
4536
4537        write!(output, "  - {}", abs_path.display()).ok();
4538        if !visible {
4539            write!(output, " (hidden)").ok();
4540        }
4541        if let Some(branch) = &branch {
4542            write!(output, " [branch: {branch}]").ok();
4543        }
4544        if is_linked {
4545            if let Some(original) = original_repo_path {
4546                write!(output, " [linked worktree -> {}]", original.display()).ok();
4547            } else {
4548                write!(output, " [linked worktree]").ok();
4549            }
4550        }
4551        writeln!(output).ok();
4552    }
4553
4554    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
4555        let panel = panel.read(cx);
4556
4557        let panel_workspace_id = panel.workspace_id();
4558        if panel_workspace_id != workspace_db_id {
4559            writeln!(
4560                output,
4561                "  \u{26a0} workspace ID mismatch! panel has {panel_workspace_id:?}, workspace has {workspace_db_id:?}"
4562            )
4563            .ok();
4564        }
4565
4566        if let Some(thread) = panel.active_agent_thread(cx) {
4567            let thread = thread.read(cx);
4568            let title = thread.title().unwrap_or_else(|| "(untitled)".into());
4569            let session_id = thread.session_id();
4570            let status = match thread.status() {
4571                ThreadStatus::Idle => "idle",
4572                ThreadStatus::Generating => "generating",
4573            };
4574            let entry_count = thread.entries().len();
4575            write!(output, "Active thread: {title} (session: {session_id})").ok();
4576            write!(output, " [{status}, {entry_count} entries").ok();
4577            if thread.is_waiting_for_confirmation() {
4578                write!(output, ", awaiting confirmation").ok();
4579            }
4580            writeln!(output, "]").ok();
4581        } else {
4582            writeln!(output, "Active thread: (none)").ok();
4583        }
4584
4585        let background_threads = panel.background_threads();
4586        if !background_threads.is_empty() {
4587            writeln!(
4588                output,
4589                "Background threads ({}): ",
4590                background_threads.len()
4591            )
4592            .ok();
4593            for (session_id, conversation_view) in background_threads {
4594                if let Some(thread_view) = conversation_view.read(cx).root_thread(cx) {
4595                    let thread = thread_view.read(cx).thread.read(cx);
4596                    let title = thread.title().unwrap_or_else(|| "(untitled)".into());
4597                    let status = match thread.status() {
4598                        ThreadStatus::Idle => "idle",
4599                        ThreadStatus::Generating => "generating",
4600                    };
4601                    let entry_count = thread.entries().len();
4602                    write!(output, "  - {title} (session: {session_id})").ok();
4603                    write!(output, " [{status}, {entry_count} entries").ok();
4604                    if thread.is_waiting_for_confirmation() {
4605                        write!(output, ", awaiting confirmation").ok();
4606                    }
4607                    writeln!(output, "]").ok();
4608                } else {
4609                    writeln!(output, "  - (not connected) (session: {session_id})").ok();
4610                }
4611            }
4612        }
4613    } else {
4614        writeln!(output, "Agent panel: not loaded").ok();
4615    }
4616
4617    writeln!(output).ok();
4618}