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::{SidebarThreadMetadataStore, ThreadMetadata};
   8use agent_ui::threads_archive_view::{
   9    ThreadsArchiveView, ThreadsArchiveViewEvent, format_history_entry_timestamp,
  10};
  11use agent_ui::{
  12    Agent, AgentPanel, AgentPanelEvent, DEFAULT_THREAD_TITLE, NewThread, RemoveSelectedThread,
  13};
  14use chrono::{DateTime, Utc};
  15use editor::Editor;
  16use feature_flags::{AgentV2FeatureFlag, FeatureFlagViewExt as _};
  17use gpui::{
  18    Action as _, AnyElement, App, Context, Entity, FocusHandle, Focusable, KeyContext, ListState,
  19    Pixels, Render, SharedString, WeakEntity, Window, WindowHandle, list, prelude::*, px,
  20};
  21use menu::{
  22    Cancel, Confirm, SelectChild, SelectFirst, SelectLast, SelectNext, SelectParent, SelectPrevious,
  23};
  24use project::{Event as ProjectEvent, linked_worktree_short_name};
  25use recent_projects::sidebar_recent_projects::SidebarRecentProjects;
  26use ui::utils::platform_title_bar_height;
  27
  28use settings::Settings as _;
  29use std::collections::{HashMap, HashSet};
  30use std::mem;
  31use std::rc::Rc;
  32use theme::ActiveTheme;
  33use ui::{
  34    AgentThreadStatus, CommonAnimationExt, ContextMenu, Divider, HighlightedLabel, KeyBinding,
  35    PopoverMenu, PopoverMenuHandle, Tab, ThreadItem, ThreadItemWorktreeInfo, TintColor, Tooltip,
  36    WithScrollbar, prelude::*,
  37};
  38use util::ResultExt as _;
  39use util::path_list::PathList;
  40use workspace::{
  41    AddFolderToProject, FocusWorkspaceSidebar, MultiWorkspace, MultiWorkspaceEvent, Open,
  42    Sidebar as WorkspaceSidebar, SidebarSide, ToggleWorkspaceSidebar, Workspace, WorkspaceId,
  43    sidebar_side_context_menu,
  44};
  45
  46use zed_actions::OpenRecent;
  47use zed_actions::editor::{MoveDown, MoveUp};
  48
  49use zed_actions::agents_sidebar::{
  50    ActivateSelectedWorkspace, FocusSidebarFilter, NewThreadInGroup, RemoveSelected,
  51    RemoveSelectedWorkspace, ShowFewerThreads, ShowMoreThreads, StopSelectedThread, ToggleArchive,
  52    ToggleThreadSwitcher,
  53};
  54
  55use crate::thread_switcher::{ThreadSwitcher, ThreadSwitcherEntry, ThreadSwitcherEvent};
  56
  57use crate::project_group_builder::ProjectGroupBuilder;
  58
  59mod project_group_builder;
  60
  61#[cfg(test)]
  62mod sidebar_tests;
  63
  64const DEFAULT_WIDTH: Pixels = px(300.0);
  65const MIN_WIDTH: Pixels = px(200.0);
  66const MAX_WIDTH: Pixels = px(800.0);
  67const DEFAULT_THREADS_SHOWN: usize = 5;
  68
  69#[derive(Debug, Default)]
  70enum SidebarView {
  71    #[default]
  72    ThreadList,
  73    Archive(Entity<ThreadsArchiveView>),
  74}
  75
  76#[derive(Clone, Debug)]
  77struct ActiveThreadInfo {
  78    session_id: acp::SessionId,
  79    title: SharedString,
  80    status: AgentThreadStatus,
  81    icon: IconName,
  82    icon_from_external_svg: Option<SharedString>,
  83    is_background: bool,
  84    is_title_generating: bool,
  85    diff_stats: DiffStats,
  86}
  87
  88impl From<&ActiveThreadInfo> for acp_thread::AgentSessionInfo {
  89    fn from(info: &ActiveThreadInfo) -> Self {
  90        Self {
  91            session_id: info.session_id.clone(),
  92            work_dirs: None,
  93            title: Some(info.title.clone()),
  94            updated_at: Some(Utc::now()),
  95            created_at: Some(Utc::now()),
  96            meta: None,
  97        }
  98    }
  99}
 100
 101#[derive(Clone)]
 102enum ThreadEntryWorkspace {
 103    Open(Entity<Workspace>),
 104    Closed(PathList),
 105}
 106
 107#[derive(Clone)]
 108struct WorktreeInfo {
 109    name: SharedString,
 110    full_path: SharedString,
 111    highlight_positions: Vec<usize>,
 112}
 113
 114#[derive(Clone)]
 115struct ThreadEntry {
 116    agent: Agent,
 117    session_info: acp_thread::AgentSessionInfo,
 118    icon: IconName,
 119    icon_from_external_svg: Option<SharedString>,
 120    status: AgentThreadStatus,
 121    workspace: ThreadEntryWorkspace,
 122    is_live: bool,
 123    is_background: bool,
 124    is_title_generating: bool,
 125    highlight_positions: Vec<usize>,
 126    worktrees: Vec<WorktreeInfo>,
 127    diff_stats: DiffStats,
 128}
 129
 130impl ThreadEntry {
 131    /// Updates this thread entry with active thread information.
 132    ///
 133    /// The existing [`ThreadEntry`] was likely deserialized from the database
 134    /// but if we have a correspond thread already loaded we want to apply the
 135    /// live information.
 136    fn apply_active_info(&mut self, info: &ActiveThreadInfo) {
 137        self.session_info.title = Some(info.title.clone());
 138        self.status = info.status;
 139        self.icon = info.icon;
 140        self.icon_from_external_svg = info.icon_from_external_svg.clone();
 141        self.is_live = true;
 142        self.is_background = info.is_background;
 143        self.is_title_generating = info.is_title_generating;
 144        self.diff_stats = info.diff_stats;
 145    }
 146}
 147
 148#[derive(Clone)]
 149enum ListEntry {
 150    ProjectHeader {
 151        path_list: PathList,
 152        label: SharedString,
 153        workspace: Entity<Workspace>,
 154        highlight_positions: Vec<usize>,
 155        has_running_threads: bool,
 156        waiting_thread_count: usize,
 157        is_active: bool,
 158    },
 159    Thread(ThreadEntry),
 160    ViewMore {
 161        path_list: PathList,
 162        is_fully_expanded: bool,
 163    },
 164    NewThread {
 165        path_list: PathList,
 166        workspace: Entity<Workspace>,
 167        is_active_draft: bool,
 168    },
 169}
 170
 171#[cfg(test)]
 172impl ListEntry {
 173    fn workspace(&self) -> Option<Entity<Workspace>> {
 174        match self {
 175            ListEntry::ProjectHeader { workspace, .. } => Some(workspace.clone()),
 176            ListEntry::Thread(thread_entry) => match &thread_entry.workspace {
 177                ThreadEntryWorkspace::Open(workspace) => Some(workspace.clone()),
 178                ThreadEntryWorkspace::Closed(_) => None,
 179            },
 180            ListEntry::ViewMore { .. } => None,
 181            ListEntry::NewThread { workspace, .. } => Some(workspace.clone()),
 182        }
 183    }
 184
 185    fn session_id(&self) -> Option<&acp::SessionId> {
 186        match self {
 187            ListEntry::Thread(thread_entry) => Some(&thread_entry.session_info.session_id),
 188            _ => None,
 189        }
 190    }
 191}
 192
 193impl From<ThreadEntry> for ListEntry {
 194    fn from(thread: ThreadEntry) -> Self {
 195        ListEntry::Thread(thread)
 196    }
 197}
 198
 199#[derive(Default)]
 200struct SidebarContents {
 201    entries: Vec<ListEntry>,
 202    notified_threads: HashSet<acp::SessionId>,
 203    project_header_indices: Vec<usize>,
 204    has_open_projects: bool,
 205}
 206
 207impl SidebarContents {
 208    fn is_thread_notified(&self, session_id: &acp::SessionId) -> bool {
 209        self.notified_threads.contains(session_id)
 210    }
 211}
 212
 213fn fuzzy_match_positions(query: &str, candidate: &str) -> Option<Vec<usize>> {
 214    let mut positions = Vec::new();
 215    let mut query_chars = query.chars().peekable();
 216
 217    for (byte_idx, candidate_char) in candidate.char_indices() {
 218        if let Some(&query_char) = query_chars.peek() {
 219            if candidate_char.eq_ignore_ascii_case(&query_char) {
 220                positions.push(byte_idx);
 221                query_chars.next();
 222            }
 223        } else {
 224            break;
 225        }
 226    }
 227
 228    if query_chars.peek().is_none() {
 229        Some(positions)
 230    } else {
 231        None
 232    }
 233}
 234
 235// TODO: The mapping from workspace root paths to git repositories needs a
 236// unified approach across the codebase: this function, `AgentPanel::classify_worktrees`,
 237// thread persistence (which PathList is saved to the database), and thread
 238// querying (which PathList is used to read threads back). All of these need
 239// to agree on how repos are resolved for a given workspace, especially in
 240// multi-root and nested-repo configurations.
 241fn root_repository_snapshots(
 242    workspace: &Entity<Workspace>,
 243    cx: &App,
 244) -> impl Iterator<Item = project::git_store::RepositorySnapshot> {
 245    let path_list = workspace_path_list(workspace, cx);
 246    let project = workspace.read(cx).project().read(cx);
 247    project.repositories(cx).values().filter_map(move |repo| {
 248        let snapshot = repo.read(cx).snapshot();
 249        let is_root = path_list
 250            .paths()
 251            .iter()
 252            .any(|p| p.as_path() == snapshot.work_directory_abs_path.as_ref());
 253        is_root.then_some(snapshot)
 254    })
 255}
 256
 257fn workspace_path_list(workspace: &Entity<Workspace>, cx: &App) -> PathList {
 258    PathList::new(&workspace.read(cx).root_paths(cx))
 259}
 260
 261/// Derives worktree display info from a thread's stored path list.
 262///
 263/// For each path in the thread's `folder_paths` that canonicalizes to a
 264/// different path (i.e. it's a git worktree), produces a [`WorktreeInfo`]
 265/// with the short worktree name and full path.
 266fn worktree_info_from_thread_paths(
 267    folder_paths: &PathList,
 268    project_groups: &ProjectGroupBuilder,
 269) -> Vec<WorktreeInfo> {
 270    folder_paths
 271        .paths()
 272        .iter()
 273        .filter_map(|path| {
 274            let canonical = project_groups.canonicalize_path(path);
 275            if canonical != path.as_path() {
 276                Some(WorktreeInfo {
 277                    name: linked_worktree_short_name(canonical, path).unwrap_or_default(),
 278                    full_path: SharedString::from(path.display().to_string()),
 279                    highlight_positions: Vec::new(),
 280                })
 281            } else {
 282                None
 283            }
 284        })
 285        .collect()
 286}
 287
 288/// The sidebar re-derives its entire entry list from scratch on every
 289/// change via `update_entries` → `rebuild_contents`. Avoid adding
 290/// incremental or inter-event coordination state — if something can
 291/// be computed from the current world state, compute it in the rebuild.
 292pub struct Sidebar {
 293    multi_workspace: WeakEntity<MultiWorkspace>,
 294    width: Pixels,
 295    focus_handle: FocusHandle,
 296    filter_editor: Entity<Editor>,
 297    list_state: ListState,
 298    contents: SidebarContents,
 299    /// The index of the list item that currently has the keyboard focus
 300    ///
 301    /// Note: This is NOT the same as the active item.
 302    selection: Option<usize>,
 303    /// Derived from the active panel's thread in `rebuild_contents`.
 304    /// Only updated when the panel returns `Some` — never cleared by
 305    /// derivation, since the panel may transiently return `None` while
 306    /// loading. User actions may write directly for immediate feedback.
 307    focused_thread: Option<acp::SessionId>,
 308    agent_panel_visible: bool,
 309    active_thread_is_draft: bool,
 310    hovered_thread_index: Option<usize>,
 311    collapsed_groups: HashSet<PathList>,
 312    expanded_groups: HashMap<PathList, usize>,
 313    /// Updated only in response to explicit user actions (clicking a
 314    /// thread, confirming in the thread switcher, etc.) — never from
 315    /// background data changes. Used to sort the thread switcher popup.
 316    thread_last_accessed: HashMap<acp::SessionId, DateTime<Utc>>,
 317    /// Updated when the user presses a key to send or queue a message.
 318    /// Used for sorting threads in the sidebar and as a secondary sort
 319    /// key in the thread switcher.
 320    thread_last_message_sent_or_queued: HashMap<acp::SessionId, DateTime<Utc>>,
 321    thread_switcher: Option<Entity<ThreadSwitcher>>,
 322    _thread_switcher_subscriptions: Vec<gpui::Subscription>,
 323    view: SidebarView,
 324    recent_projects_popover_handle: PopoverMenuHandle<SidebarRecentProjects>,
 325    project_header_menu_ix: Option<usize>,
 326    _subscriptions: Vec<gpui::Subscription>,
 327    _draft_observation: Option<gpui::Subscription>,
 328}
 329
 330impl Sidebar {
 331    pub fn new(
 332        multi_workspace: Entity<MultiWorkspace>,
 333        window: &mut Window,
 334        cx: &mut Context<Self>,
 335    ) -> Self {
 336        let focus_handle = cx.focus_handle();
 337        cx.on_focus_in(&focus_handle, window, Self::focus_in)
 338            .detach();
 339
 340        let filter_editor = cx.new(|cx| {
 341            let mut editor = Editor::single_line(window, cx);
 342            editor.set_use_modal_editing(true);
 343            editor.set_placeholder_text("Search…", window, cx);
 344            editor
 345        });
 346
 347        cx.subscribe_in(
 348            &multi_workspace,
 349            window,
 350            |this, _multi_workspace, event: &MultiWorkspaceEvent, window, cx| match event {
 351                MultiWorkspaceEvent::ActiveWorkspaceChanged => {
 352                    this.observe_draft_editor(cx);
 353                    this.update_entries(cx);
 354                }
 355                MultiWorkspaceEvent::WorkspaceAdded(workspace) => {
 356                    this.subscribe_to_workspace(workspace, window, cx);
 357                    this.update_entries(cx);
 358                }
 359                MultiWorkspaceEvent::WorkspaceRemoved(_) => {
 360                    this.update_entries(cx);
 361                }
 362            },
 363        )
 364        .detach();
 365
 366        cx.subscribe(&filter_editor, |this: &mut Self, _, event, cx| {
 367            if let editor::EditorEvent::BufferEdited = event {
 368                let query = this.filter_editor.read(cx).text(cx);
 369                if !query.is_empty() {
 370                    this.selection.take();
 371                }
 372                this.update_entries(cx);
 373                if !query.is_empty() {
 374                    this.select_first_entry();
 375                }
 376            }
 377        })
 378        .detach();
 379
 380        cx.observe(
 381            &SidebarThreadMetadataStore::global(cx),
 382            |this, _store, cx| {
 383                this.update_entries(cx);
 384            },
 385        )
 386        .detach();
 387
 388        cx.observe_flag::<AgentV2FeatureFlag, _>(window, |_is_enabled, this, _window, cx| {
 389            this.update_entries(cx);
 390        })
 391        .detach();
 392
 393        let workspaces = multi_workspace.read(cx).workspaces().to_vec();
 394        cx.defer_in(window, move |this, window, cx| {
 395            for workspace in &workspaces {
 396                this.subscribe_to_workspace(workspace, window, cx);
 397            }
 398            this.update_entries(cx);
 399        });
 400
 401        Self {
 402            multi_workspace: multi_workspace.downgrade(),
 403            width: DEFAULT_WIDTH,
 404            focus_handle,
 405            filter_editor,
 406            list_state: ListState::new(0, gpui::ListAlignment::Top, px(1000.)),
 407            contents: SidebarContents::default(),
 408            selection: None,
 409            focused_thread: None,
 410            agent_panel_visible: false,
 411            active_thread_is_draft: false,
 412            hovered_thread_index: None,
 413            collapsed_groups: HashSet::new(),
 414            expanded_groups: HashMap::new(),
 415            thread_last_accessed: HashMap::new(),
 416            thread_last_message_sent_or_queued: HashMap::new(),
 417            thread_switcher: None,
 418            _thread_switcher_subscriptions: Vec::new(),
 419            view: SidebarView::default(),
 420            recent_projects_popover_handle: PopoverMenuHandle::default(),
 421            project_header_menu_ix: None,
 422            _subscriptions: Vec::new(),
 423            _draft_observation: None,
 424        }
 425    }
 426
 427    fn is_active_workspace(&self, workspace: &Entity<Workspace>, cx: &App) -> bool {
 428        self.multi_workspace
 429            .upgrade()
 430            .map_or(false, |mw| mw.read(cx).workspace() == workspace)
 431    }
 432
 433    fn subscribe_to_workspace(
 434        &mut self,
 435        workspace: &Entity<Workspace>,
 436        window: &mut Window,
 437        cx: &mut Context<Self>,
 438    ) {
 439        let project = workspace.read(cx).project().clone();
 440        cx.subscribe_in(
 441            &project,
 442            window,
 443            |this, _project, event, _window, cx| match event {
 444                ProjectEvent::WorktreeAdded(_)
 445                | ProjectEvent::WorktreeRemoved(_)
 446                | ProjectEvent::WorktreeOrderChanged => {
 447                    this.update_entries(cx);
 448                }
 449                _ => {}
 450            },
 451        )
 452        .detach();
 453
 454        let git_store = workspace.read(cx).project().read(cx).git_store().clone();
 455        cx.subscribe_in(
 456            &git_store,
 457            window,
 458            |this, _, event: &project::git_store::GitStoreEvent, _window, cx| {
 459                if matches!(
 460                    event,
 461                    project::git_store::GitStoreEvent::RepositoryUpdated(
 462                        _,
 463                        project::git_store::RepositoryEvent::GitWorktreeListChanged,
 464                        _,
 465                    )
 466                ) {
 467                    this.update_entries(cx);
 468                }
 469            },
 470        )
 471        .detach();
 472
 473        cx.subscribe_in(
 474            workspace,
 475            window,
 476            |this, _workspace, event: &workspace::Event, window, cx| {
 477                if let workspace::Event::PanelAdded(view) = event {
 478                    if let Ok(agent_panel) = view.clone().downcast::<AgentPanel>() {
 479                        this.subscribe_to_agent_panel(&agent_panel, window, cx);
 480                    }
 481                }
 482            },
 483        )
 484        .detach();
 485
 486        self.observe_docks(workspace, cx);
 487
 488        if let Some(agent_panel) = workspace.read(cx).panel::<AgentPanel>(cx) {
 489            self.subscribe_to_agent_panel(&agent_panel, window, cx);
 490            if self.is_active_workspace(workspace, cx) {
 491                self.agent_panel_visible = AgentPanel::is_visible(workspace, cx);
 492            }
 493            self.observe_draft_editor(cx);
 494        }
 495    }
 496
 497    fn subscribe_to_agent_panel(
 498        &mut self,
 499        agent_panel: &Entity<AgentPanel>,
 500        window: &mut Window,
 501        cx: &mut Context<Self>,
 502    ) {
 503        cx.subscribe_in(
 504            agent_panel,
 505            window,
 506            |this, agent_panel, event: &AgentPanelEvent, _window, cx| match event {
 507                AgentPanelEvent::ActiveViewChanged => {
 508                    let is_new_draft = agent_panel
 509                        .read(cx)
 510                        .active_conversation_view()
 511                        .is_some_and(|cv| cv.read(cx).parent_id(cx).is_none());
 512                    if is_new_draft {
 513                        this.focused_thread = None;
 514                    }
 515                    this.observe_draft_editor(cx);
 516                    this.update_entries(cx);
 517                }
 518                AgentPanelEvent::ThreadFocused | AgentPanelEvent::BackgroundThreadChanged => {
 519                    this.update_entries(cx);
 520                }
 521                AgentPanelEvent::MessageSentOrQueued { session_id } => {
 522                    this.record_thread_message_sent(session_id);
 523                    this.update_entries(cx);
 524                }
 525            },
 526        )
 527        .detach();
 528    }
 529
 530    fn observe_docks(&mut self, workspace: &Entity<Workspace>, cx: &mut Context<Self>) {
 531        let docks: Vec<_> = workspace
 532            .read(cx)
 533            .all_docks()
 534            .into_iter()
 535            .cloned()
 536            .collect();
 537        let workspace = workspace.downgrade();
 538        for dock in docks {
 539            let workspace = workspace.clone();
 540            cx.observe(&dock, move |this, _dock, cx| {
 541                let Some(workspace) = workspace.upgrade() else {
 542                    return;
 543                };
 544                if !this.is_active_workspace(&workspace, cx) {
 545                    return;
 546                }
 547
 548                let is_visible = AgentPanel::is_visible(&workspace, cx);
 549
 550                if this.agent_panel_visible != is_visible {
 551                    this.agent_panel_visible = is_visible;
 552                    cx.notify();
 553                }
 554            })
 555            .detach();
 556        }
 557    }
 558
 559    fn observe_draft_editor(&mut self, cx: &mut Context<Self>) {
 560        self._draft_observation = self
 561            .multi_workspace
 562            .upgrade()
 563            .and_then(|mw| {
 564                let ws = mw.read(cx).workspace();
 565                ws.read(cx).panel::<AgentPanel>(cx)
 566            })
 567            .and_then(|panel| {
 568                let cv = panel.read(cx).active_conversation_view()?;
 569                let tv = cv.read(cx).active_thread()?;
 570                Some(tv.read(cx).message_editor.clone())
 571            })
 572            .map(|editor| {
 573                cx.observe(&editor, |_this, _editor, cx| {
 574                    cx.notify();
 575                })
 576            });
 577    }
 578
 579    fn active_draft_text(&self, cx: &App) -> Option<SharedString> {
 580        let mw = self.multi_workspace.upgrade()?;
 581        let workspace = mw.read(cx).workspace();
 582        let panel = workspace.read(cx).panel::<AgentPanel>(cx)?;
 583        let conversation_view = panel.read(cx).active_conversation_view()?;
 584        let thread_view = conversation_view.read(cx).active_thread()?;
 585        let raw = thread_view.read(cx).message_editor.read(cx).text(cx);
 586        let cleaned = Self::clean_mention_links(&raw);
 587        let mut text: String = cleaned.split_whitespace().collect::<Vec<_>>().join(" ");
 588        if text.is_empty() {
 589            None
 590        } else {
 591            const MAX_CHARS: usize = 250;
 592            if let Some((truncate_at, _)) = text.char_indices().nth(MAX_CHARS) {
 593                text.truncate(truncate_at);
 594            }
 595            Some(text.into())
 596        }
 597    }
 598
 599    fn clean_mention_links(input: &str) -> String {
 600        let mut result = String::with_capacity(input.len());
 601        let mut remaining = input;
 602
 603        while let Some(start) = remaining.find("[@") {
 604            result.push_str(&remaining[..start]);
 605            let after_bracket = &remaining[start + 1..]; // skip '['
 606            if let Some(close_bracket) = after_bracket.find("](") {
 607                let mention = &after_bracket[..close_bracket]; // "@something"
 608                let after_link_start = &after_bracket[close_bracket + 2..]; // after "]("
 609                if let Some(close_paren) = after_link_start.find(')') {
 610                    result.push_str(mention);
 611                    remaining = &after_link_start[close_paren + 1..];
 612                    continue;
 613                }
 614            }
 615            // Couldn't parse full link syntax — emit the literal "[@" and move on.
 616            result.push_str("[@");
 617            remaining = &remaining[start + 2..];
 618        }
 619        result.push_str(remaining);
 620        result
 621    }
 622
 623    /// Rebuilds the sidebar contents from current workspace and thread state.
 624    ///
 625    /// Uses [`ProjectGroupBuilder`] to group workspaces by their main git
 626    /// repository, then populates thread entries from the metadata store and
 627    /// merges live thread info from active agent panels.
 628    ///
 629    /// Aim for a single forward pass over workspaces and threads plus an
 630    /// O(T log T) sort. Avoid adding extra scans over the data.
 631    ///
 632    /// Properties:
 633    ///
 634    /// - Should always show every workspace in the multiworkspace
 635    ///     - If you have no threads, and two workspaces for the worktree and the main workspace, make sure at least one is shown
 636    /// - Should always show every thread, associated with each workspace in the multiworkspace
 637    /// - After every build_contents, our "active" state should exactly match the current workspace's, current agent panel's current thread.
 638    fn rebuild_contents(&mut self, cx: &App) {
 639        let Some(multi_workspace) = self.multi_workspace.upgrade() else {
 640            return;
 641        };
 642        let mw = multi_workspace.read(cx);
 643        let workspaces = mw.workspaces().to_vec();
 644        let active_workspace = mw.workspaces().get(mw.active_workspace_index()).cloned();
 645
 646        let agent_server_store = workspaces
 647            .first()
 648            .map(|ws| ws.read(cx).project().read(cx).agent_server_store().clone());
 649
 650        let query = self.filter_editor.read(cx).text(cx);
 651
 652        // Re-derive agent_panel_visible from the active workspace so it stays
 653        // correct after workspace switches.
 654        self.agent_panel_visible = active_workspace
 655            .as_ref()
 656            .map_or(false, |ws| AgentPanel::is_visible(ws, cx));
 657
 658        // Derive active_thread_is_draft BEFORE focused_thread so we can
 659        // use it as a guard below.
 660        self.active_thread_is_draft = active_workspace
 661            .as_ref()
 662            .and_then(|ws| ws.read(cx).panel::<AgentPanel>(cx))
 663            .map_or(false, |panel| panel.read(cx).active_thread_is_draft(cx));
 664
 665        // Derive focused_thread from the active workspace's agent panel.
 666        // Only update when the panel gives us a positive signal — if the
 667        // panel returns None (e.g. still loading after a thread activation),
 668        // keep the previous value so eager writes from user actions survive.
 669        let panel_focused = active_workspace
 670            .as_ref()
 671            .and_then(|ws| ws.read(cx).panel::<AgentPanel>(cx))
 672            .and_then(|panel| {
 673                panel
 674                    .read(cx)
 675                    .active_conversation_view()
 676                    .and_then(|cv| cv.read(cx).parent_id(cx))
 677            });
 678        if panel_focused.is_some() && !self.active_thread_is_draft {
 679            self.focused_thread = panel_focused;
 680        }
 681
 682        let previous = mem::take(&mut self.contents);
 683
 684        let old_statuses: HashMap<acp::SessionId, AgentThreadStatus> = previous
 685            .entries
 686            .iter()
 687            .filter_map(|entry| match entry {
 688                ListEntry::Thread(thread) if thread.is_live => {
 689                    Some((thread.session_info.session_id.clone(), thread.status))
 690                }
 691                _ => None,
 692            })
 693            .collect();
 694
 695        let mut entries = Vec::new();
 696        let mut notified_threads = previous.notified_threads;
 697        let mut current_session_ids: HashSet<acp::SessionId> = HashSet::new();
 698        let mut project_header_indices: Vec<usize> = Vec::new();
 699
 700        // Use ProjectGroupBuilder to canonically group workspaces by their
 701        // main git repository. This replaces the manual absorbed-workspace
 702        // detection that was here before.
 703        let project_groups = ProjectGroupBuilder::from_multiworkspace(mw, cx);
 704
 705        let has_open_projects = workspaces
 706            .iter()
 707            .any(|ws| !workspace_path_list(ws, cx).paths().is_empty());
 708
 709        let resolve_agent = |row: &ThreadMetadata| -> (Agent, IconName, Option<SharedString>) {
 710            match &row.agent_id {
 711                None => (Agent::NativeAgent, IconName::ZedAgent, None),
 712                Some(id) => {
 713                    let custom_icon = agent_server_store
 714                        .as_ref()
 715                        .and_then(|store| store.read(cx).agent_icon(id));
 716                    (
 717                        Agent::Custom { id: id.clone() },
 718                        IconName::Terminal,
 719                        custom_icon,
 720                    )
 721                }
 722            }
 723        };
 724
 725        for (group_name, group) in project_groups.groups() {
 726            let path_list = group_name.path_list().clone();
 727            if path_list.paths().is_empty() {
 728                continue;
 729            }
 730
 731            let label = group_name.display_name();
 732
 733            let is_collapsed = self.collapsed_groups.contains(&path_list);
 734            let should_load_threads = !is_collapsed || !query.is_empty();
 735
 736            let is_active = active_workspace
 737                .as_ref()
 738                .is_some_and(|active| group.workspaces.contains(active));
 739
 740            // Pick a representative workspace for the group: prefer the active
 741            // workspace if it belongs to this group, otherwise use the main
 742            // repo workspace (not a linked worktree).
 743            let representative_workspace = active_workspace
 744                .as_ref()
 745                .filter(|_| is_active)
 746                .unwrap_or_else(|| group.main_workspace(cx));
 747
 748            // Collect live thread infos from all workspaces in this group.
 749            let live_infos: Vec<_> = group
 750                .workspaces
 751                .iter()
 752                .flat_map(|ws| all_thread_infos_for_workspace(ws, cx))
 753                .collect();
 754
 755            let mut threads: Vec<ThreadEntry> = Vec::new();
 756            let mut has_running_threads = false;
 757            let mut waiting_thread_count: usize = 0;
 758
 759            if should_load_threads {
 760                let mut seen_session_ids: HashSet<acp::SessionId> = HashSet::new();
 761                let thread_store = SidebarThreadMetadataStore::global(cx);
 762
 763                // Load threads from each workspace in the group.
 764                for workspace in &group.workspaces {
 765                    let ws_path_list = workspace_path_list(workspace, cx);
 766
 767                    for row in thread_store.read(cx).entries_for_path(&ws_path_list) {
 768                        if !seen_session_ids.insert(row.session_id.clone()) {
 769                            continue;
 770                        }
 771                        let (agent, icon, icon_from_external_svg) = resolve_agent(&row);
 772                        let worktrees =
 773                            worktree_info_from_thread_paths(&row.folder_paths, &project_groups);
 774                        threads.push(ThreadEntry {
 775                            agent,
 776                            session_info: acp_thread::AgentSessionInfo {
 777                                session_id: row.session_id.clone(),
 778                                work_dirs: None,
 779                                title: Some(row.title.clone()),
 780                                updated_at: Some(row.updated_at),
 781                                created_at: row.created_at,
 782                                meta: None,
 783                            },
 784                            icon,
 785                            icon_from_external_svg,
 786                            status: AgentThreadStatus::default(),
 787                            workspace: ThreadEntryWorkspace::Open(workspace.clone()),
 788                            is_live: false,
 789                            is_background: false,
 790                            is_title_generating: false,
 791                            highlight_positions: Vec::new(),
 792                            worktrees,
 793                            diff_stats: DiffStats::default(),
 794                        });
 795                    }
 796                }
 797
 798                // Load threads from linked git worktrees
 799                // canonical paths belong to this group.
 800                let linked_worktree_queries = group
 801                    .workspaces
 802                    .iter()
 803                    .flat_map(|ws| root_repository_snapshots(ws, cx))
 804                    .filter(|snapshot| !snapshot.is_linked_worktree())
 805                    .flat_map(|snapshot| {
 806                        snapshot
 807                            .linked_worktrees()
 808                            .iter()
 809                            .filter(|wt| {
 810                                project_groups.group_owns_worktree(group, &path_list, &wt.path)
 811                            })
 812                            .map(|wt| PathList::new(std::slice::from_ref(&wt.path)))
 813                            .collect::<Vec<_>>()
 814                    });
 815
 816                for worktree_path_list in linked_worktree_queries {
 817                    for row in thread_store.read(cx).entries_for_path(&worktree_path_list) {
 818                        if !seen_session_ids.insert(row.session_id.clone()) {
 819                            continue;
 820                        }
 821                        let (agent, icon, icon_from_external_svg) = resolve_agent(&row);
 822                        let worktrees =
 823                            worktree_info_from_thread_paths(&row.folder_paths, &project_groups);
 824                        threads.push(ThreadEntry {
 825                            agent,
 826                            session_info: acp_thread::AgentSessionInfo {
 827                                session_id: row.session_id.clone(),
 828                                work_dirs: None,
 829                                title: Some(row.title.clone()),
 830                                updated_at: Some(row.updated_at),
 831                                created_at: row.created_at,
 832                                meta: None,
 833                            },
 834                            icon,
 835                            icon_from_external_svg,
 836                            status: AgentThreadStatus::default(),
 837                            workspace: ThreadEntryWorkspace::Closed(worktree_path_list.clone()),
 838                            is_live: false,
 839                            is_background: false,
 840                            is_title_generating: false,
 841                            highlight_positions: Vec::new(),
 842                            worktrees,
 843                            diff_stats: DiffStats::default(),
 844                        });
 845                    }
 846                }
 847
 848                // Build a lookup from live_infos and compute running/waiting
 849                // counts in a single pass.
 850                let mut live_info_by_session: HashMap<&acp::SessionId, &ActiveThreadInfo> =
 851                    HashMap::new();
 852                for info in &live_infos {
 853                    live_info_by_session.insert(&info.session_id, info);
 854                    if info.status == AgentThreadStatus::Running {
 855                        has_running_threads = true;
 856                    }
 857                    if info.status == AgentThreadStatus::WaitingForConfirmation {
 858                        waiting_thread_count += 1;
 859                    }
 860                }
 861
 862                // Merge live info into threads and update notification state
 863                // in a single pass.
 864                for thread in &mut threads {
 865                    if let Some(info) = live_info_by_session.get(&thread.session_info.session_id) {
 866                        thread.apply_active_info(info);
 867                    }
 868
 869                    let session_id = &thread.session_info.session_id;
 870
 871                    let is_thread_workspace_active = match &thread.workspace {
 872                        ThreadEntryWorkspace::Open(thread_workspace) => active_workspace
 873                            .as_ref()
 874                            .is_some_and(|active| active == thread_workspace),
 875                        ThreadEntryWorkspace::Closed(_) => false,
 876                    };
 877
 878                    if thread.status == AgentThreadStatus::Completed
 879                        && !is_thread_workspace_active
 880                        && old_statuses.get(session_id) == Some(&AgentThreadStatus::Running)
 881                    {
 882                        notified_threads.insert(session_id.clone());
 883                    }
 884
 885                    if is_thread_workspace_active && !thread.is_background {
 886                        notified_threads.remove(session_id);
 887                    }
 888                }
 889
 890                threads.sort_by(|a, b| {
 891                    let a_time = self
 892                        .thread_last_message_sent_or_queued
 893                        .get(&a.session_info.session_id)
 894                        .copied()
 895                        .or(a.session_info.created_at)
 896                        .or(a.session_info.updated_at);
 897                    let b_time = self
 898                        .thread_last_message_sent_or_queued
 899                        .get(&b.session_info.session_id)
 900                        .copied()
 901                        .or(b.session_info.created_at)
 902                        .or(b.session_info.updated_at);
 903                    b_time.cmp(&a_time)
 904                });
 905            } else {
 906                for info in live_infos {
 907                    if info.status == AgentThreadStatus::Running {
 908                        has_running_threads = true;
 909                    }
 910                    if info.status == AgentThreadStatus::WaitingForConfirmation {
 911                        waiting_thread_count += 1;
 912                    }
 913                }
 914            }
 915
 916            if !query.is_empty() {
 917                let workspace_highlight_positions =
 918                    fuzzy_match_positions(&query, &label).unwrap_or_default();
 919                let workspace_matched = !workspace_highlight_positions.is_empty();
 920
 921                let mut matched_threads: Vec<ThreadEntry> = Vec::new();
 922                for mut thread in threads {
 923                    let title = thread
 924                        .session_info
 925                        .title
 926                        .as_ref()
 927                        .map(|s| s.as_ref())
 928                        .unwrap_or("");
 929                    if let Some(positions) = fuzzy_match_positions(&query, title) {
 930                        thread.highlight_positions = positions;
 931                    }
 932                    let mut worktree_matched = false;
 933                    for worktree in &mut thread.worktrees {
 934                        if let Some(positions) = fuzzy_match_positions(&query, &worktree.name) {
 935                            worktree.highlight_positions = positions;
 936                            worktree_matched = true;
 937                        }
 938                    }
 939                    if workspace_matched
 940                        || !thread.highlight_positions.is_empty()
 941                        || worktree_matched
 942                    {
 943                        matched_threads.push(thread);
 944                    }
 945                }
 946
 947                if matched_threads.is_empty() && !workspace_matched {
 948                    continue;
 949                }
 950
 951                project_header_indices.push(entries.len());
 952                entries.push(ListEntry::ProjectHeader {
 953                    path_list: path_list.clone(),
 954                    label,
 955                    workspace: representative_workspace.clone(),
 956                    highlight_positions: workspace_highlight_positions,
 957                    has_running_threads,
 958                    waiting_thread_count,
 959                    is_active,
 960                });
 961
 962                for thread in matched_threads {
 963                    current_session_ids.insert(thread.session_info.session_id.clone());
 964                    entries.push(thread.into());
 965                }
 966            } else {
 967                let thread_count = threads.len();
 968                let is_draft_for_workspace = self.agent_panel_visible
 969                    && self.active_thread_is_draft
 970                    && self.focused_thread.is_none()
 971                    && is_active;
 972
 973                let show_new_thread_entry = thread_count == 0 || is_draft_for_workspace;
 974
 975                project_header_indices.push(entries.len());
 976                entries.push(ListEntry::ProjectHeader {
 977                    path_list: path_list.clone(),
 978                    label,
 979                    workspace: representative_workspace.clone(),
 980                    highlight_positions: Vec::new(),
 981                    has_running_threads,
 982                    waiting_thread_count,
 983                    is_active,
 984                });
 985
 986                if is_collapsed {
 987                    continue;
 988                }
 989
 990                if show_new_thread_entry {
 991                    entries.push(ListEntry::NewThread {
 992                        path_list: path_list.clone(),
 993                        workspace: representative_workspace.clone(),
 994                        is_active_draft: is_draft_for_workspace,
 995                    });
 996                }
 997
 998                let total = threads.len();
 999
1000                let extra_batches = self.expanded_groups.get(&path_list).copied().unwrap_or(0);
1001                let threads_to_show =
1002                    DEFAULT_THREADS_SHOWN + (extra_batches * DEFAULT_THREADS_SHOWN);
1003                let count = threads_to_show.min(total);
1004
1005                let mut promoted_threads: HashSet<acp::SessionId> = HashSet::new();
1006
1007                // Build visible entries in a single pass. Threads within
1008                // the cutoff are always shown. Threads beyond it are shown
1009                // only if they should be promoted (running, waiting, or
1010                // focused)
1011                for (index, thread) in threads.into_iter().enumerate() {
1012                    let is_hidden = index >= count;
1013
1014                    let session_id = &thread.session_info.session_id;
1015                    if is_hidden {
1016                        let is_promoted = thread.status == AgentThreadStatus::Running
1017                            || thread.status == AgentThreadStatus::WaitingForConfirmation
1018                            || notified_threads.contains(session_id)
1019                            || self
1020                                .focused_thread
1021                                .as_ref()
1022                                .is_some_and(|id| id == session_id);
1023                        if is_promoted {
1024                            promoted_threads.insert(session_id.clone());
1025                        }
1026                        if !promoted_threads.contains(session_id) {
1027                            continue;
1028                        }
1029                    }
1030
1031                    current_session_ids.insert(session_id.clone());
1032                    entries.push(thread.into());
1033                }
1034
1035                let visible = count + promoted_threads.len();
1036                let is_fully_expanded = visible >= total;
1037
1038                if total > DEFAULT_THREADS_SHOWN {
1039                    entries.push(ListEntry::ViewMore {
1040                        path_list: path_list.clone(),
1041                        is_fully_expanded,
1042                    });
1043                }
1044            }
1045        }
1046
1047        // Prune stale notifications using the session IDs we collected during
1048        // the build pass (no extra scan needed).
1049        notified_threads.retain(|id| current_session_ids.contains(id));
1050
1051        self.thread_last_accessed
1052            .retain(|id, _| current_session_ids.contains(id));
1053        self.thread_last_message_sent_or_queued
1054            .retain(|id, _| current_session_ids.contains(id));
1055
1056        self.contents = SidebarContents {
1057            entries,
1058            notified_threads,
1059            project_header_indices,
1060            has_open_projects,
1061        };
1062    }
1063
1064    /// Rebuilds the sidebar's visible entries from already-cached state.
1065    fn update_entries(&mut self, cx: &mut Context<Self>) {
1066        let Some(multi_workspace) = self.multi_workspace.upgrade() else {
1067            return;
1068        };
1069        if !multi_workspace.read(cx).multi_workspace_enabled(cx) {
1070            return;
1071        }
1072
1073        let had_notifications = self.has_notifications(cx);
1074        let scroll_position = self.list_state.logical_scroll_top();
1075
1076        self.rebuild_contents(cx);
1077
1078        self.list_state.reset(self.contents.entries.len());
1079        self.list_state.scroll_to(scroll_position);
1080
1081        if had_notifications != self.has_notifications(cx) {
1082            multi_workspace.update(cx, |_, cx| {
1083                cx.notify();
1084            });
1085        }
1086
1087        cx.notify();
1088    }
1089
1090    fn select_first_entry(&mut self) {
1091        self.selection = self
1092            .contents
1093            .entries
1094            .iter()
1095            .position(|entry| matches!(entry, ListEntry::Thread(_)))
1096            .or_else(|| {
1097                if self.contents.entries.is_empty() {
1098                    None
1099                } else {
1100                    Some(0)
1101                }
1102            });
1103    }
1104
1105    fn render_list_entry(
1106        &mut self,
1107        ix: usize,
1108        window: &mut Window,
1109        cx: &mut Context<Self>,
1110    ) -> AnyElement {
1111        let Some(entry) = self.contents.entries.get(ix) else {
1112            return div().into_any_element();
1113        };
1114        let is_focused = self.focus_handle.is_focused(window);
1115        // is_selected means the keyboard selector is here.
1116        let is_selected = is_focused && self.selection == Some(ix);
1117
1118        let is_group_header_after_first =
1119            ix > 0 && matches!(entry, ListEntry::ProjectHeader { .. });
1120
1121        let rendered = match entry {
1122            ListEntry::ProjectHeader {
1123                path_list,
1124                label,
1125                workspace,
1126                highlight_positions,
1127                has_running_threads,
1128                waiting_thread_count,
1129                is_active,
1130            } => self.render_project_header(
1131                ix,
1132                false,
1133                path_list,
1134                label,
1135                workspace,
1136                highlight_positions,
1137                *has_running_threads,
1138                *waiting_thread_count,
1139                *is_active,
1140                is_selected,
1141                cx,
1142            ),
1143            ListEntry::Thread(thread) => self.render_thread(ix, thread, is_selected, cx),
1144            ListEntry::ViewMore {
1145                path_list,
1146                is_fully_expanded,
1147            } => self.render_view_more(ix, path_list, *is_fully_expanded, is_selected, cx),
1148            ListEntry::NewThread {
1149                path_list,
1150                workspace,
1151                is_active_draft,
1152            } => {
1153                self.render_new_thread(ix, path_list, workspace, *is_active_draft, is_selected, cx)
1154            }
1155        };
1156
1157        if is_group_header_after_first {
1158            v_flex()
1159                .w_full()
1160                .border_t_1()
1161                .border_color(cx.theme().colors().border.opacity(0.5))
1162                .child(rendered)
1163                .into_any_element()
1164        } else {
1165            rendered
1166        }
1167    }
1168
1169    fn render_project_header(
1170        &self,
1171        ix: usize,
1172        is_sticky: bool,
1173        path_list: &PathList,
1174        label: &SharedString,
1175        workspace: &Entity<Workspace>,
1176        highlight_positions: &[usize],
1177        has_running_threads: bool,
1178        waiting_thread_count: usize,
1179        is_active: bool,
1180        is_selected: bool,
1181        cx: &mut Context<Self>,
1182    ) -> AnyElement {
1183        let id_prefix = if is_sticky { "sticky-" } else { "" };
1184        let id = SharedString::from(format!("{id_prefix}project-header-{ix}"));
1185        let group_name = SharedString::from(format!("{id_prefix}header-group-{ix}"));
1186
1187        let is_collapsed = self.collapsed_groups.contains(path_list);
1188        let disclosure_icon = if is_collapsed {
1189            IconName::ChevronRight
1190        } else {
1191            IconName::ChevronDown
1192        };
1193
1194        let has_new_thread_entry = self
1195            .contents
1196            .entries
1197            .get(ix + 1)
1198            .is_some_and(|entry| matches!(entry, ListEntry::NewThread { .. }));
1199        let show_new_thread_button = !has_new_thread_entry && !self.has_filter_query(cx);
1200
1201        let workspace_for_remove = workspace.clone();
1202        let workspace_for_menu = workspace.clone();
1203        let workspace_for_open = workspace.clone();
1204
1205        let path_list_for_toggle = path_list.clone();
1206        let path_list_for_collapse = path_list.clone();
1207        let view_more_expanded = self.expanded_groups.contains_key(path_list);
1208
1209        let label = if highlight_positions.is_empty() {
1210            Label::new(label.clone())
1211                .color(Color::Muted)
1212                .into_any_element()
1213        } else {
1214            HighlightedLabel::new(label.clone(), highlight_positions.to_vec())
1215                .color(Color::Muted)
1216                .into_any_element()
1217        };
1218
1219        let color = cx.theme().colors();
1220        let hover_color = color
1221            .element_active
1222            .blend(color.element_background.opacity(0.2));
1223
1224        h_flex()
1225            .id(id)
1226            .group(&group_name)
1227            .h(Tab::content_height(cx))
1228            .w_full()
1229            .pl_1p5()
1230            .pr_1()
1231            .border_1()
1232            .map(|this| {
1233                if is_selected {
1234                    this.border_color(color.border_focused)
1235                } else {
1236                    this.border_color(gpui::transparent_black())
1237                }
1238            })
1239            .justify_between()
1240            .hover(|s| s.bg(hover_color))
1241            .child(
1242                h_flex()
1243                    .relative()
1244                    .min_w_0()
1245                    .w_full()
1246                    .gap_1p5()
1247                    .child(
1248                        h_flex().size_4().flex_none().justify_center().child(
1249                            Icon::new(disclosure_icon)
1250                                .size(IconSize::Small)
1251                                .color(Color::Custom(cx.theme().colors().icon_muted.opacity(0.5))),
1252                        ),
1253                    )
1254                    .child(label)
1255                    .when(is_collapsed, |this| {
1256                        this.when(has_running_threads, |this| {
1257                            this.child(
1258                                Icon::new(IconName::LoadCircle)
1259                                    .size(IconSize::XSmall)
1260                                    .color(Color::Muted)
1261                                    .with_rotate_animation(2),
1262                            )
1263                        })
1264                        .when(waiting_thread_count > 0, |this| {
1265                            let tooltip_text = if waiting_thread_count == 1 {
1266                                "1 thread is waiting for confirmation".to_string()
1267                            } else {
1268                                format!(
1269                                    "{waiting_thread_count} threads are waiting for confirmation",
1270                                )
1271                            };
1272                            this.child(
1273                                div()
1274                                    .id(format!("{id_prefix}waiting-indicator-{ix}"))
1275                                    .child(
1276                                        Icon::new(IconName::Warning)
1277                                            .size(IconSize::XSmall)
1278                                            .color(Color::Warning),
1279                                    )
1280                                    .tooltip(Tooltip::text(tooltip_text)),
1281                            )
1282                        })
1283                    }),
1284            )
1285            .child({
1286                let workspace_for_new_thread = workspace.clone();
1287                let path_list_for_new_thread = path_list.clone();
1288
1289                h_flex()
1290                    .when(self.project_header_menu_ix != Some(ix), |this| {
1291                        this.visible_on_hover(group_name)
1292                    })
1293                    .on_mouse_down(gpui::MouseButton::Left, |_, _, cx| {
1294                        cx.stop_propagation();
1295                    })
1296                    .child(self.render_project_header_menu(
1297                        ix,
1298                        id_prefix,
1299                        &workspace_for_menu,
1300                        &workspace_for_remove,
1301                        cx,
1302                    ))
1303                    .when(view_more_expanded && !is_collapsed, |this| {
1304                        this.child(
1305                            IconButton::new(
1306                                SharedString::from(format!(
1307                                    "{id_prefix}project-header-collapse-{ix}",
1308                                )),
1309                                IconName::ListCollapse,
1310                            )
1311                            .icon_size(IconSize::Small)
1312                            .icon_color(Color::Muted)
1313                            .tooltip(Tooltip::text("Collapse Displayed Threads"))
1314                            .on_click(cx.listener({
1315                                let path_list_for_collapse = path_list_for_collapse.clone();
1316                                move |this, _, _window, cx| {
1317                                    this.selection = None;
1318                                    this.expanded_groups.remove(&path_list_for_collapse);
1319                                    this.update_entries(cx);
1320                                }
1321                            })),
1322                        )
1323                    })
1324                    .when(!is_active, |this| {
1325                        this.child(
1326                            IconButton::new(
1327                                SharedString::from(format!(
1328                                    "{id_prefix}project-header-open-workspace-{ix}",
1329                                )),
1330                                IconName::Focus,
1331                            )
1332                            .icon_size(IconSize::Small)
1333                            .icon_color(Color::Muted)
1334                            .tooltip(Tooltip::text("Activate Workspace"))
1335                            .on_click(cx.listener({
1336                                move |this, _, window, cx| {
1337                                    this.focused_thread = None;
1338                                    if let Some(multi_workspace) = this.multi_workspace.upgrade() {
1339                                        multi_workspace.update(cx, |multi_workspace, cx| {
1340                                            multi_workspace
1341                                                .activate(workspace_for_open.clone(), cx);
1342                                        });
1343                                    }
1344                                    if AgentPanel::is_visible(&workspace_for_open, cx) {
1345                                        workspace_for_open.update(cx, |workspace, cx| {
1346                                            workspace.focus_panel::<AgentPanel>(window, cx);
1347                                        });
1348                                    }
1349                                }
1350                            })),
1351                        )
1352                    })
1353                    .when(show_new_thread_button, |this| {
1354                        this.child(
1355                            IconButton::new(
1356                                SharedString::from(format!(
1357                                    "{id_prefix}project-header-new-thread-{ix}",
1358                                )),
1359                                IconName::Plus,
1360                            )
1361                            .icon_size(IconSize::Small)
1362                            .icon_color(Color::Muted)
1363                            .tooltip(Tooltip::text("New Thread"))
1364                            .on_click(cx.listener({
1365                                let workspace_for_new_thread = workspace_for_new_thread.clone();
1366                                let path_list_for_new_thread = path_list_for_new_thread.clone();
1367                                move |this, _, window, cx| {
1368                                    // Uncollapse the group if collapsed so
1369                                    // the new-thread entry becomes visible.
1370                                    this.collapsed_groups.remove(&path_list_for_new_thread);
1371                                    this.selection = None;
1372                                    this.create_new_thread(&workspace_for_new_thread, window, cx);
1373                                }
1374                            })),
1375                        )
1376                    })
1377            })
1378            .on_click(cx.listener(move |this, _, window, cx| {
1379                this.selection = None;
1380                this.toggle_collapse(&path_list_for_toggle, window, cx);
1381            }))
1382            .into_any_element()
1383    }
1384
1385    fn render_project_header_menu(
1386        &self,
1387        ix: usize,
1388        id_prefix: &str,
1389        workspace: &Entity<Workspace>,
1390        workspace_for_remove: &Entity<Workspace>,
1391        cx: &mut Context<Self>,
1392    ) -> impl IntoElement {
1393        let workspace_for_menu = workspace.clone();
1394        let workspace_for_remove = workspace_for_remove.clone();
1395        let multi_workspace = self.multi_workspace.clone();
1396        let this = cx.weak_entity();
1397
1398        PopoverMenu::new(format!("{id_prefix}project-header-menu-{ix}"))
1399            .on_open(Rc::new({
1400                let this = this.clone();
1401                move |_window, cx| {
1402                    this.update(cx, |sidebar, cx| {
1403                        sidebar.project_header_menu_ix = Some(ix);
1404                        cx.notify();
1405                    })
1406                    .ok();
1407                }
1408            }))
1409            .menu(move |window, cx| {
1410                let workspace = workspace_for_menu.clone();
1411                let workspace_for_remove = workspace_for_remove.clone();
1412                let multi_workspace = multi_workspace.clone();
1413
1414                let menu = ContextMenu::build_persistent(window, cx, move |menu, _window, cx| {
1415                    let worktrees: Vec<_> = workspace
1416                        .read(cx)
1417                        .visible_worktrees(cx)
1418                        .map(|worktree| {
1419                            let worktree_read = worktree.read(cx);
1420                            let id = worktree_read.id();
1421                            let name: SharedString =
1422                                worktree_read.root_name().as_unix_str().to_string().into();
1423                            (id, name)
1424                        })
1425                        .collect();
1426
1427                    let worktree_count = worktrees.len();
1428
1429                    let mut menu = menu
1430                        .header("Project Folders")
1431                        .end_slot_action(Box::new(menu::EndSlot));
1432
1433                    for (worktree_id, name) in &worktrees {
1434                        let worktree_id = *worktree_id;
1435                        let workspace_for_worktree = workspace.clone();
1436                        let workspace_for_remove_worktree = workspace_for_remove.clone();
1437                        let multi_workspace_for_worktree = multi_workspace.clone();
1438
1439                        let remove_handler = move |window: &mut Window, cx: &mut App| {
1440                            if worktree_count <= 1 {
1441                                if let Some(mw) = multi_workspace_for_worktree.upgrade() {
1442                                    let ws = workspace_for_remove_worktree.clone();
1443                                    mw.update(cx, |multi_workspace, cx| {
1444                                        if let Some(index) = multi_workspace
1445                                            .workspaces()
1446                                            .iter()
1447                                            .position(|w| *w == ws)
1448                                        {
1449                                            multi_workspace.remove_workspace(index, window, cx);
1450                                        }
1451                                    });
1452                                }
1453                            } else {
1454                                workspace_for_worktree.update(cx, |workspace, cx| {
1455                                    workspace.project().update(cx, |project, cx| {
1456                                        project.remove_worktree(worktree_id, cx);
1457                                    });
1458                                });
1459                            }
1460                        };
1461
1462                        menu = menu.entry_with_end_slot_on_hover(
1463                            name.clone(),
1464                            None,
1465                            |_, _| {},
1466                            IconName::Close,
1467                            "Remove Folder".into(),
1468                            remove_handler,
1469                        );
1470                    }
1471
1472                    let workspace_for_add = workspace.clone();
1473                    let multi_workspace_for_add = multi_workspace.clone();
1474                    let menu = menu.separator().entry(
1475                        "Add Folder to Project",
1476                        Some(Box::new(AddFolderToProject)),
1477                        move |window, cx| {
1478                            if let Some(mw) = multi_workspace_for_add.upgrade() {
1479                                mw.update(cx, |mw, cx| {
1480                                    mw.activate(workspace_for_add.clone(), cx);
1481                                });
1482                            }
1483                            workspace_for_add.update(cx, |workspace, cx| {
1484                                workspace.add_folder_to_project(&AddFolderToProject, window, cx);
1485                            });
1486                        },
1487                    );
1488
1489                    let workspace_count = multi_workspace
1490                        .upgrade()
1491                        .map_or(0, |mw| mw.read(cx).workspaces().len());
1492                    let menu = if workspace_count > 1 {
1493                        let workspace_for_move = workspace.clone();
1494                        let multi_workspace_for_move = multi_workspace.clone();
1495                        menu.entry(
1496                            "Move to New Window",
1497                            Some(Box::new(
1498                                zed_actions::agents_sidebar::MoveWorkspaceToNewWindow,
1499                            )),
1500                            move |window, cx| {
1501                                if let Some(mw) = multi_workspace_for_move.upgrade() {
1502                                    mw.update(cx, |multi_workspace, cx| {
1503                                        if let Some(index) = multi_workspace
1504                                            .workspaces()
1505                                            .iter()
1506                                            .position(|w| *w == workspace_for_move)
1507                                        {
1508                                            multi_workspace
1509                                                .move_workspace_to_new_window(index, window, cx);
1510                                        }
1511                                    });
1512                                }
1513                            },
1514                        )
1515                    } else {
1516                        menu
1517                    };
1518
1519                    let workspace_for_remove = workspace_for_remove.clone();
1520                    let multi_workspace_for_remove = multi_workspace.clone();
1521                    menu.separator()
1522                        .entry("Remove Project", None, move |window, cx| {
1523                            if let Some(mw) = multi_workspace_for_remove.upgrade() {
1524                                let ws = workspace_for_remove.clone();
1525                                mw.update(cx, |multi_workspace, cx| {
1526                                    if let Some(index) =
1527                                        multi_workspace.workspaces().iter().position(|w| *w == ws)
1528                                    {
1529                                        multi_workspace.remove_workspace(index, window, cx);
1530                                    }
1531                                });
1532                            }
1533                        })
1534                });
1535
1536                let this = this.clone();
1537                window
1538                    .subscribe(&menu, cx, move |_, _: &gpui::DismissEvent, _window, cx| {
1539                        this.update(cx, |sidebar, cx| {
1540                            sidebar.project_header_menu_ix = None;
1541                            cx.notify();
1542                        })
1543                        .ok();
1544                    })
1545                    .detach();
1546
1547                Some(menu)
1548            })
1549            .trigger(
1550                IconButton::new(
1551                    SharedString::from(format!("{id_prefix}-ellipsis-menu-{ix}")),
1552                    IconName::Ellipsis,
1553                )
1554                .selected_style(ButtonStyle::Tinted(TintColor::Accent))
1555                .icon_size(IconSize::Small)
1556                .icon_color(Color::Muted),
1557            )
1558            .anchor(gpui::Corner::TopRight)
1559            .offset(gpui::Point {
1560                x: px(0.),
1561                y: px(1.),
1562            })
1563    }
1564
1565    fn render_sticky_header(
1566        &self,
1567        window: &mut Window,
1568        cx: &mut Context<Self>,
1569    ) -> Option<AnyElement> {
1570        let scroll_top = self.list_state.logical_scroll_top();
1571
1572        let &header_idx = self
1573            .contents
1574            .project_header_indices
1575            .iter()
1576            .rev()
1577            .find(|&&idx| idx <= scroll_top.item_ix)?;
1578
1579        let needs_sticky = header_idx < scroll_top.item_ix
1580            || (header_idx == scroll_top.item_ix && scroll_top.offset_in_item > px(0.));
1581
1582        if !needs_sticky {
1583            return None;
1584        }
1585
1586        let ListEntry::ProjectHeader {
1587            path_list,
1588            label,
1589            workspace,
1590            highlight_positions,
1591            has_running_threads,
1592            waiting_thread_count,
1593            is_active,
1594        } = self.contents.entries.get(header_idx)?
1595        else {
1596            return None;
1597        };
1598
1599        let is_focused = self.focus_handle.is_focused(window);
1600        let is_selected = is_focused && self.selection == Some(header_idx);
1601
1602        let header_element = self.render_project_header(
1603            header_idx,
1604            true,
1605            &path_list,
1606            &label,
1607            workspace,
1608            &highlight_positions,
1609            *has_running_threads,
1610            *waiting_thread_count,
1611            *is_active,
1612            is_selected,
1613            cx,
1614        );
1615
1616        let top_offset = self
1617            .contents
1618            .project_header_indices
1619            .iter()
1620            .find(|&&idx| idx > header_idx)
1621            .and_then(|&next_idx| {
1622                let bounds = self.list_state.bounds_for_item(next_idx)?;
1623                let viewport = self.list_state.viewport_bounds();
1624                let y_in_viewport = bounds.origin.y - viewport.origin.y;
1625                let header_height = bounds.size.height;
1626                (y_in_viewport < header_height).then_some(y_in_viewport - header_height)
1627            })
1628            .unwrap_or(px(0.));
1629
1630        let color = cx.theme().colors();
1631        let background = color
1632            .title_bar_background
1633            .blend(color.panel_background.opacity(0.2));
1634
1635        let element = v_flex()
1636            .absolute()
1637            .top(top_offset)
1638            .left_0()
1639            .w_full()
1640            .bg(background)
1641            .border_b_1()
1642            .border_color(color.border.opacity(0.5))
1643            .child(header_element)
1644            .shadow_xs()
1645            .into_any_element();
1646
1647        Some(element)
1648    }
1649
1650    fn toggle_collapse(
1651        &mut self,
1652        path_list: &PathList,
1653        _window: &mut Window,
1654        cx: &mut Context<Self>,
1655    ) {
1656        if self.collapsed_groups.contains(path_list) {
1657            self.collapsed_groups.remove(path_list);
1658        } else {
1659            self.collapsed_groups.insert(path_list.clone());
1660        }
1661        self.update_entries(cx);
1662    }
1663
1664    fn dispatch_context(&self, window: &Window, cx: &Context<Self>) -> KeyContext {
1665        let mut dispatch_context = KeyContext::new_with_defaults();
1666        dispatch_context.add("ThreadsSidebar");
1667        dispatch_context.add("menu");
1668
1669        let identifier = if self.filter_editor.focus_handle(cx).is_focused(window) {
1670            "searching"
1671        } else {
1672            "not_searching"
1673        };
1674
1675        dispatch_context.add(identifier);
1676        dispatch_context
1677    }
1678
1679    fn focus_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1680        if !self.focus_handle.is_focused(window) {
1681            return;
1682        }
1683
1684        if let SidebarView::Archive(archive) = &self.view {
1685            let has_selection = archive.read(cx).has_selection();
1686            if !has_selection {
1687                archive.update(cx, |view, cx| view.focus_filter_editor(window, cx));
1688            }
1689        } else if self.selection.is_none() {
1690            self.filter_editor.focus_handle(cx).focus(window, cx);
1691        }
1692    }
1693
1694    fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
1695        if self.reset_filter_editor_text(window, cx) {
1696            self.update_entries(cx);
1697        } else {
1698            self.selection = None;
1699            self.filter_editor.focus_handle(cx).focus(window, cx);
1700            cx.notify();
1701        }
1702    }
1703
1704    fn focus_sidebar_filter(
1705        &mut self,
1706        _: &FocusSidebarFilter,
1707        window: &mut Window,
1708        cx: &mut Context<Self>,
1709    ) {
1710        self.selection = None;
1711        if let SidebarView::Archive(archive) = &self.view {
1712            archive.update(cx, |view, cx| {
1713                view.clear_selection();
1714                view.focus_filter_editor(window, cx);
1715            });
1716        } else {
1717            self.filter_editor.focus_handle(cx).focus(window, cx);
1718        }
1719
1720        // When vim mode is active, the editor defaults to normal mode which
1721        // blocks text input. Switch to insert mode so the user can type
1722        // immediately.
1723        if vim_mode_setting::VimModeSetting::get_global(cx).0 {
1724            if let Ok(action) = cx.build_action("vim::SwitchToInsertMode", None) {
1725                window.dispatch_action(action, cx);
1726            }
1727        }
1728
1729        cx.notify();
1730    }
1731
1732    fn reset_filter_editor_text(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
1733        self.filter_editor.update(cx, |editor, cx| {
1734            if editor.buffer().read(cx).len(cx).0 > 0 {
1735                editor.set_text("", window, cx);
1736                true
1737            } else {
1738                false
1739            }
1740        })
1741    }
1742
1743    fn has_filter_query(&self, cx: &App) -> bool {
1744        !self.filter_editor.read(cx).text(cx).is_empty()
1745    }
1746
1747    fn editor_move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
1748        self.select_next(&SelectNext, window, cx);
1749        if self.selection.is_some() {
1750            self.focus_handle.focus(window, cx);
1751        }
1752    }
1753
1754    fn editor_move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
1755        self.select_previous(&SelectPrevious, window, cx);
1756        if self.selection.is_some() {
1757            self.focus_handle.focus(window, cx);
1758        }
1759    }
1760
1761    fn editor_confirm(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1762        if self.selection.is_none() {
1763            self.select_next(&SelectNext, window, cx);
1764        }
1765        if self.selection.is_some() {
1766            self.focus_handle.focus(window, cx);
1767        }
1768    }
1769
1770    fn select_next(&mut self, _: &SelectNext, _window: &mut Window, cx: &mut Context<Self>) {
1771        let next = match self.selection {
1772            Some(ix) if ix + 1 < self.contents.entries.len() => ix + 1,
1773            Some(_) if !self.contents.entries.is_empty() => 0,
1774            None if !self.contents.entries.is_empty() => 0,
1775            _ => return,
1776        };
1777        self.selection = Some(next);
1778        self.list_state.scroll_to_reveal_item(next);
1779        cx.notify();
1780    }
1781
1782    fn select_previous(&mut self, _: &SelectPrevious, window: &mut Window, cx: &mut Context<Self>) {
1783        match self.selection {
1784            Some(0) => {
1785                self.selection = None;
1786                self.filter_editor.focus_handle(cx).focus(window, cx);
1787                cx.notify();
1788            }
1789            Some(ix) => {
1790                self.selection = Some(ix - 1);
1791                self.list_state.scroll_to_reveal_item(ix - 1);
1792                cx.notify();
1793            }
1794            None if !self.contents.entries.is_empty() => {
1795                let last = self.contents.entries.len() - 1;
1796                self.selection = Some(last);
1797                self.list_state.scroll_to_reveal_item(last);
1798                cx.notify();
1799            }
1800            None => {}
1801        }
1802    }
1803
1804    fn select_first(&mut self, _: &SelectFirst, _window: &mut Window, cx: &mut Context<Self>) {
1805        if !self.contents.entries.is_empty() {
1806            self.selection = Some(0);
1807            self.list_state.scroll_to_reveal_item(0);
1808            cx.notify();
1809        }
1810    }
1811
1812    fn select_last(&mut self, _: &SelectLast, _window: &mut Window, cx: &mut Context<Self>) {
1813        if let Some(last) = self.contents.entries.len().checked_sub(1) {
1814            self.selection = Some(last);
1815            self.list_state.scroll_to_reveal_item(last);
1816            cx.notify();
1817        }
1818    }
1819
1820    fn confirm(&mut self, _: &Confirm, window: &mut Window, cx: &mut Context<Self>) {
1821        let Some(ix) = self.selection else { return };
1822        let Some(entry) = self.contents.entries.get(ix) else {
1823            return;
1824        };
1825
1826        match entry {
1827            ListEntry::ProjectHeader { path_list, .. } => {
1828                let path_list = path_list.clone();
1829                self.toggle_collapse(&path_list, window, cx);
1830            }
1831            ListEntry::Thread(thread) => {
1832                let session_info = thread.session_info.clone();
1833                match &thread.workspace {
1834                    ThreadEntryWorkspace::Open(workspace) => {
1835                        let workspace = workspace.clone();
1836                        self.activate_thread(
1837                            thread.agent.clone(),
1838                            session_info,
1839                            &workspace,
1840                            window,
1841                            cx,
1842                        );
1843                    }
1844                    ThreadEntryWorkspace::Closed(path_list) => {
1845                        self.open_workspace_and_activate_thread(
1846                            thread.agent.clone(),
1847                            session_info,
1848                            path_list.clone(),
1849                            window,
1850                            cx,
1851                        );
1852                    }
1853                }
1854            }
1855            ListEntry::ViewMore {
1856                path_list,
1857                is_fully_expanded,
1858                ..
1859            } => {
1860                let path_list = path_list.clone();
1861                if *is_fully_expanded {
1862                    self.expanded_groups.remove(&path_list);
1863                } else {
1864                    let current = self.expanded_groups.get(&path_list).copied().unwrap_or(0);
1865                    self.expanded_groups.insert(path_list, current + 1);
1866                }
1867                self.update_entries(cx);
1868            }
1869            ListEntry::NewThread { workspace, .. } => {
1870                let workspace = workspace.clone();
1871                self.create_new_thread(&workspace, window, cx);
1872            }
1873        }
1874    }
1875
1876    fn find_workspace_across_windows(
1877        &self,
1878        cx: &App,
1879        predicate: impl Fn(&Entity<Workspace>, &App) -> bool,
1880    ) -> Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> {
1881        cx.windows()
1882            .into_iter()
1883            .filter_map(|window| window.downcast::<MultiWorkspace>())
1884            .find_map(|window| {
1885                let workspace = window.read(cx).ok().and_then(|multi_workspace| {
1886                    multi_workspace
1887                        .workspaces()
1888                        .iter()
1889                        .find(|workspace| predicate(workspace, cx))
1890                        .cloned()
1891                })?;
1892                Some((window, workspace))
1893            })
1894    }
1895
1896    fn find_workspace_in_current_window(
1897        &self,
1898        cx: &App,
1899        predicate: impl Fn(&Entity<Workspace>, &App) -> bool,
1900    ) -> Option<Entity<Workspace>> {
1901        self.multi_workspace.upgrade().and_then(|multi_workspace| {
1902            multi_workspace
1903                .read(cx)
1904                .workspaces()
1905                .iter()
1906                .find(|workspace| predicate(workspace, cx))
1907                .cloned()
1908        })
1909    }
1910
1911    fn load_agent_thread_in_workspace(
1912        workspace: &Entity<Workspace>,
1913        agent: Agent,
1914        session_info: acp_thread::AgentSessionInfo,
1915        focus: bool,
1916        window: &mut Window,
1917        cx: &mut App,
1918    ) {
1919        workspace.update(cx, |workspace, cx| {
1920            workspace.open_panel::<AgentPanel>(window, cx);
1921        });
1922
1923        if let Some(agent_panel) = workspace.read(cx).panel::<AgentPanel>(cx) {
1924            agent_panel.update(cx, |panel, cx| {
1925                panel.load_agent_thread(
1926                    agent,
1927                    session_info.session_id,
1928                    session_info.work_dirs,
1929                    session_info.title,
1930                    focus,
1931                    window,
1932                    cx,
1933                );
1934            });
1935        }
1936    }
1937
1938    fn activate_thread_locally(
1939        &mut self,
1940        agent: Agent,
1941        session_info: acp_thread::AgentSessionInfo,
1942        workspace: &Entity<Workspace>,
1943        window: &mut Window,
1944        cx: &mut Context<Self>,
1945    ) {
1946        let Some(multi_workspace) = self.multi_workspace.upgrade() else {
1947            return;
1948        };
1949
1950        // Set focused_thread eagerly so the sidebar highlight updates
1951        // immediately, rather than waiting for a deferred AgentPanel
1952        // event which can race with ActiveWorkspaceChanged clearing it.
1953        self.focused_thread = Some(session_info.session_id.clone());
1954        self.record_thread_access(&session_info.session_id);
1955
1956        multi_workspace.update(cx, |multi_workspace, cx| {
1957            multi_workspace.activate(workspace.clone(), cx);
1958        });
1959
1960        Self::load_agent_thread_in_workspace(workspace, agent, session_info, true, window, cx);
1961
1962        self.update_entries(cx);
1963    }
1964
1965    fn activate_thread_in_other_window(
1966        &self,
1967        agent: Agent,
1968        session_info: acp_thread::AgentSessionInfo,
1969        workspace: Entity<Workspace>,
1970        target_window: WindowHandle<MultiWorkspace>,
1971        cx: &mut Context<Self>,
1972    ) {
1973        let target_session_id = session_info.session_id.clone();
1974
1975        let activated = target_window
1976            .update(cx, |multi_workspace, window, cx| {
1977                window.activate_window();
1978                multi_workspace.activate(workspace.clone(), cx);
1979                Self::load_agent_thread_in_workspace(
1980                    &workspace,
1981                    agent,
1982                    session_info,
1983                    true,
1984                    window,
1985                    cx,
1986                );
1987            })
1988            .log_err()
1989            .is_some();
1990
1991        if activated {
1992            if let Some(target_sidebar) = target_window
1993                .read(cx)
1994                .ok()
1995                .and_then(|multi_workspace| {
1996                    multi_workspace.sidebar().map(|sidebar| sidebar.to_any())
1997                })
1998                .and_then(|sidebar| sidebar.downcast::<Self>().ok())
1999            {
2000                target_sidebar.update(cx, |sidebar, cx| {
2001                    sidebar.focused_thread = Some(target_session_id.clone());
2002                    sidebar.record_thread_access(&target_session_id);
2003                    sidebar.update_entries(cx);
2004                });
2005            }
2006        }
2007    }
2008
2009    fn activate_thread(
2010        &mut self,
2011        agent: Agent,
2012        session_info: acp_thread::AgentSessionInfo,
2013        workspace: &Entity<Workspace>,
2014        window: &mut Window,
2015        cx: &mut Context<Self>,
2016    ) {
2017        if self
2018            .find_workspace_in_current_window(cx, |candidate, _| candidate == workspace)
2019            .is_some()
2020        {
2021            self.activate_thread_locally(agent, session_info, &workspace, window, cx);
2022            return;
2023        }
2024
2025        let Some((target_window, workspace)) =
2026            self.find_workspace_across_windows(cx, |candidate, _| candidate == workspace)
2027        else {
2028            return;
2029        };
2030
2031        self.activate_thread_in_other_window(agent, session_info, workspace, target_window, cx);
2032    }
2033
2034    fn open_workspace_and_activate_thread(
2035        &mut self,
2036        agent: Agent,
2037        session_info: acp_thread::AgentSessionInfo,
2038        path_list: PathList,
2039        window: &mut Window,
2040        cx: &mut Context<Self>,
2041    ) {
2042        let Some(multi_workspace) = self.multi_workspace.upgrade() else {
2043            return;
2044        };
2045
2046        let paths: Vec<std::path::PathBuf> =
2047            path_list.paths().iter().map(|p| p.to_path_buf()).collect();
2048
2049        let open_task = multi_workspace.update(cx, |mw, cx| mw.open_project(paths, window, cx));
2050
2051        cx.spawn_in(window, async move |this, cx| {
2052            let workspace = open_task.await?;
2053
2054            this.update_in(cx, |this, window, cx| {
2055                this.activate_thread(agent, session_info, &workspace, window, cx);
2056            })?;
2057            anyhow::Ok(())
2058        })
2059        .detach_and_log_err(cx);
2060    }
2061
2062    fn find_current_workspace_for_path_list(
2063        &self,
2064        path_list: &PathList,
2065        cx: &App,
2066    ) -> Option<Entity<Workspace>> {
2067        self.find_workspace_in_current_window(cx, |workspace, cx| {
2068            workspace_path_list(workspace, cx).paths() == path_list.paths()
2069        })
2070    }
2071
2072    fn find_open_workspace_for_path_list(
2073        &self,
2074        path_list: &PathList,
2075        cx: &App,
2076    ) -> Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> {
2077        self.find_workspace_across_windows(cx, |workspace, cx| {
2078            workspace_path_list(workspace, cx).paths() == path_list.paths()
2079        })
2080    }
2081
2082    fn activate_archived_thread(
2083        &mut self,
2084        agent: Agent,
2085        session_info: acp_thread::AgentSessionInfo,
2086        window: &mut Window,
2087        cx: &mut Context<Self>,
2088    ) {
2089        // Eagerly save thread metadata so that the sidebar is updated immediately
2090        SidebarThreadMetadataStore::global(cx).update(cx, |store, cx| {
2091            store.save(
2092                ThreadMetadata::from_session_info(agent.id(), &session_info),
2093                cx,
2094            )
2095        });
2096
2097        if let Some(path_list) = &session_info.work_dirs {
2098            if let Some(workspace) = self.find_current_workspace_for_path_list(path_list, cx) {
2099                self.activate_thread_locally(agent, session_info, &workspace, window, cx);
2100            } else if let Some((target_window, workspace)) =
2101                self.find_open_workspace_for_path_list(path_list, cx)
2102            {
2103                self.activate_thread_in_other_window(
2104                    agent,
2105                    session_info,
2106                    workspace,
2107                    target_window,
2108                    cx,
2109                );
2110            } else {
2111                let path_list = path_list.clone();
2112                self.open_workspace_and_activate_thread(agent, session_info, path_list, window, cx);
2113            }
2114            return;
2115        }
2116
2117        let active_workspace = self.multi_workspace.upgrade().and_then(|w| {
2118            w.read(cx)
2119                .workspaces()
2120                .get(w.read(cx).active_workspace_index())
2121                .cloned()
2122        });
2123
2124        if let Some(workspace) = active_workspace {
2125            self.activate_thread_locally(agent, session_info, &workspace, window, cx);
2126        }
2127    }
2128
2129    fn expand_selected_entry(
2130        &mut self,
2131        _: &SelectChild,
2132        _window: &mut Window,
2133        cx: &mut Context<Self>,
2134    ) {
2135        let Some(ix) = self.selection else { return };
2136
2137        match self.contents.entries.get(ix) {
2138            Some(ListEntry::ProjectHeader { path_list, .. }) => {
2139                if self.collapsed_groups.contains(path_list) {
2140                    let path_list = path_list.clone();
2141                    self.collapsed_groups.remove(&path_list);
2142                    self.update_entries(cx);
2143                } else if ix + 1 < self.contents.entries.len() {
2144                    self.selection = Some(ix + 1);
2145                    self.list_state.scroll_to_reveal_item(ix + 1);
2146                    cx.notify();
2147                }
2148            }
2149            _ => {}
2150        }
2151    }
2152
2153    fn collapse_selected_entry(
2154        &mut self,
2155        _: &SelectParent,
2156        _window: &mut Window,
2157        cx: &mut Context<Self>,
2158    ) {
2159        let Some(ix) = self.selection else { return };
2160
2161        match self.contents.entries.get(ix) {
2162            Some(ListEntry::ProjectHeader { path_list, .. }) => {
2163                if !self.collapsed_groups.contains(path_list) {
2164                    let path_list = path_list.clone();
2165                    self.collapsed_groups.insert(path_list);
2166                    self.update_entries(cx);
2167                }
2168            }
2169            Some(
2170                ListEntry::Thread(_) | ListEntry::ViewMore { .. } | ListEntry::NewThread { .. },
2171            ) => {
2172                for i in (0..ix).rev() {
2173                    if let Some(ListEntry::ProjectHeader { path_list, .. }) =
2174                        self.contents.entries.get(i)
2175                    {
2176                        let path_list = path_list.clone();
2177                        self.selection = Some(i);
2178                        self.collapsed_groups.insert(path_list);
2179                        self.update_entries(cx);
2180                        break;
2181                    }
2182                }
2183            }
2184            None => {}
2185        }
2186    }
2187
2188    fn toggle_selected_fold(
2189        &mut self,
2190        _: &editor::actions::ToggleFold,
2191        _window: &mut Window,
2192        cx: &mut Context<Self>,
2193    ) {
2194        let Some(ix) = self.selection else { return };
2195
2196        // Find the group header for the current selection.
2197        let header_ix = match self.contents.entries.get(ix) {
2198            Some(ListEntry::ProjectHeader { .. }) => Some(ix),
2199            Some(
2200                ListEntry::Thread(_) | ListEntry::ViewMore { .. } | ListEntry::NewThread { .. },
2201            ) => (0..ix).rev().find(|&i| {
2202                matches!(
2203                    self.contents.entries.get(i),
2204                    Some(ListEntry::ProjectHeader { .. })
2205                )
2206            }),
2207            None => None,
2208        };
2209
2210        if let Some(header_ix) = header_ix {
2211            if let Some(ListEntry::ProjectHeader { path_list, .. }) =
2212                self.contents.entries.get(header_ix)
2213            {
2214                let path_list = path_list.clone();
2215                if self.collapsed_groups.contains(&path_list) {
2216                    self.collapsed_groups.remove(&path_list);
2217                } else {
2218                    self.selection = Some(header_ix);
2219                    self.collapsed_groups.insert(path_list);
2220                }
2221                self.update_entries(cx);
2222            }
2223        }
2224    }
2225
2226    fn fold_all(
2227        &mut self,
2228        _: &editor::actions::FoldAll,
2229        _window: &mut Window,
2230        cx: &mut Context<Self>,
2231    ) {
2232        for entry in &self.contents.entries {
2233            if let ListEntry::ProjectHeader { path_list, .. } = entry {
2234                self.collapsed_groups.insert(path_list.clone());
2235            }
2236        }
2237        self.update_entries(cx);
2238    }
2239
2240    fn unfold_all(
2241        &mut self,
2242        _: &editor::actions::UnfoldAll,
2243        _window: &mut Window,
2244        cx: &mut Context<Self>,
2245    ) {
2246        self.collapsed_groups.clear();
2247        self.update_entries(cx);
2248    }
2249
2250    fn stop_thread(&mut self, session_id: &acp::SessionId, cx: &mut Context<Self>) {
2251        let Some(multi_workspace) = self.multi_workspace.upgrade() else {
2252            return;
2253        };
2254
2255        let workspaces = multi_workspace.read(cx).workspaces().to_vec();
2256        for workspace in workspaces {
2257            if let Some(agent_panel) = workspace.read(cx).panel::<AgentPanel>(cx) {
2258                let cancelled =
2259                    agent_panel.update(cx, |panel, cx| panel.cancel_thread(session_id, cx));
2260                if cancelled {
2261                    return;
2262                }
2263            }
2264        }
2265    }
2266
2267    fn archive_thread(
2268        &mut self,
2269        session_id: &acp::SessionId,
2270        window: &mut Window,
2271        cx: &mut Context<Self>,
2272    ) {
2273        // If we're archiving the currently focused thread, move focus to the
2274        // nearest thread within the same project group. We never cross group
2275        // boundaries — if the group has no other threads, clear focus and open
2276        // a blank new thread in the panel instead.
2277        if self.focused_thread.as_ref() == Some(session_id) {
2278            let current_pos = self.contents.entries.iter().position(|entry| {
2279                matches!(entry, ListEntry::Thread(t) if &t.session_info.session_id == session_id)
2280            });
2281
2282            // Find the workspace that owns this thread's project group by
2283            // walking backwards to the nearest ProjectHeader. We must use
2284            // *this* workspace (not the active workspace) because the user
2285            // might be archiving a thread in a non-active group.
2286            let group_workspace = current_pos.and_then(|pos| {
2287                self.contents.entries[..pos]
2288                    .iter()
2289                    .rev()
2290                    .find_map(|e| match e {
2291                        ListEntry::ProjectHeader { workspace, .. } => Some(workspace.clone()),
2292                        _ => None,
2293                    })
2294            });
2295
2296            let next_thread = current_pos.and_then(|pos| {
2297                let group_start = self.contents.entries[..pos]
2298                    .iter()
2299                    .rposition(|e| matches!(e, ListEntry::ProjectHeader { .. }))
2300                    .map_or(0, |i| i + 1);
2301                let group_end = self.contents.entries[pos + 1..]
2302                    .iter()
2303                    .position(|e| matches!(e, ListEntry::ProjectHeader { .. }))
2304                    .map_or(self.contents.entries.len(), |i| pos + 1 + i);
2305
2306                let above = self.contents.entries[group_start..pos]
2307                    .iter()
2308                    .rev()
2309                    .find_map(|entry| {
2310                        if let ListEntry::Thread(t) = entry {
2311                            Some(t)
2312                        } else {
2313                            None
2314                        }
2315                    });
2316
2317                above.or_else(|| {
2318                    self.contents.entries[pos + 1..group_end]
2319                        .iter()
2320                        .find_map(|entry| {
2321                            if let ListEntry::Thread(t) = entry {
2322                                Some(t)
2323                            } else {
2324                                None
2325                            }
2326                        })
2327                })
2328            });
2329
2330            if let Some(next) = next_thread {
2331                let next_session_id = next.session_info.session_id.clone();
2332                let next_agent = next.agent.clone();
2333                let next_work_dirs = next.session_info.work_dirs.clone();
2334                let next_title = next.session_info.title.clone();
2335                // Use the thread's own workspace when it has one open (e.g. an absorbed
2336                // linked worktree thread that appears under the main workspace's header
2337                // but belongs to its own workspace). Loading into the wrong panel binds
2338                // the thread to the wrong project, which corrupts its stored folder_paths
2339                // when metadata is saved via ThreadMetadata::from_thread.
2340                let target_workspace = match &next.workspace {
2341                    ThreadEntryWorkspace::Open(ws) => Some(ws.clone()),
2342                    ThreadEntryWorkspace::Closed(_) => group_workspace,
2343                };
2344                self.focused_thread = Some(next_session_id.clone());
2345                self.record_thread_access(&next_session_id);
2346
2347                if let Some(workspace) = target_workspace {
2348                    if let Some(agent_panel) = workspace.read(cx).panel::<AgentPanel>(cx) {
2349                        agent_panel.update(cx, |panel, cx| {
2350                            panel.load_agent_thread(
2351                                next_agent,
2352                                next_session_id,
2353                                next_work_dirs,
2354                                next_title,
2355                                true,
2356                                window,
2357                                cx,
2358                            );
2359                        });
2360                    }
2361                }
2362            } else {
2363                self.focused_thread = None;
2364                if let Some(workspace) = &group_workspace {
2365                    if let Some(agent_panel) = workspace.read(cx).panel::<AgentPanel>(cx) {
2366                        agent_panel.update(cx, |panel, cx| {
2367                            panel.new_thread(&NewThread, window, cx);
2368                        });
2369                    }
2370                }
2371            }
2372        }
2373
2374        SidebarThreadMetadataStore::global(cx)
2375            .update(cx, |store, cx| store.delete(session_id.clone(), cx));
2376    }
2377
2378    fn remove_selected_thread(
2379        &mut self,
2380        _: &RemoveSelectedThread,
2381        window: &mut Window,
2382        cx: &mut Context<Self>,
2383    ) {
2384        let Some(ix) = self.selection else {
2385            return;
2386        };
2387        let Some(ListEntry::Thread(thread)) = self.contents.entries.get(ix) else {
2388            return;
2389        };
2390        if thread.agent != Agent::NativeAgent {
2391            return;
2392        }
2393        let session_id = thread.session_info.session_id.clone();
2394        self.archive_thread(&session_id, window, cx);
2395    }
2396
2397    fn remove_selected_workspace(
2398        &mut self,
2399        _: &RemoveSelectedWorkspace,
2400        window: &mut Window,
2401        cx: &mut Context<Self>,
2402    ) {
2403        let Some(ix) = self.selection else {
2404            return;
2405        };
2406        let Some(ListEntry::ProjectHeader { workspace, .. }) = self.contents.entries.get(ix) else {
2407            return;
2408        };
2409        let workspace = workspace.clone();
2410        if let Some(multi_workspace) = self.multi_workspace.upgrade() {
2411            multi_workspace.update(cx, |multi_workspace, cx| {
2412                if let Some(index) = multi_workspace
2413                    .workspaces()
2414                    .iter()
2415                    .position(|w| *w == workspace)
2416                {
2417                    multi_workspace.remove_workspace(index, window, cx);
2418                }
2419            });
2420        }
2421    }
2422
2423    fn remove_selected(&mut self, _: &RemoveSelected, window: &mut Window, cx: &mut Context<Self>) {
2424        let Some(ix) = self.selection else {
2425            return;
2426        };
2427        match self.contents.entries.get(ix) {
2428            Some(ListEntry::Thread(_)) => {
2429                self.remove_selected_thread(&RemoveSelectedThread, window, cx);
2430            }
2431            Some(ListEntry::ProjectHeader { .. }) => {
2432                self.remove_selected_workspace(&RemoveSelectedWorkspace, window, cx);
2433            }
2434            _ => {}
2435        }
2436    }
2437
2438    fn stop_selected_thread(
2439        &mut self,
2440        _: &StopSelectedThread,
2441        _window: &mut Window,
2442        cx: &mut Context<Self>,
2443    ) {
2444        let Some(ix) = self.selection else {
2445            return;
2446        };
2447        let Some(ListEntry::Thread(thread)) = self.contents.entries.get(ix) else {
2448            return;
2449        };
2450        let session_id = thread.session_info.session_id.clone();
2451        self.stop_thread(&session_id, cx);
2452    }
2453
2454    fn activate_selected_workspace(
2455        &mut self,
2456        _: &ActivateSelectedWorkspace,
2457        window: &mut Window,
2458        cx: &mut Context<Self>,
2459    ) {
2460        let Some(ix) = self.selection else {
2461            return;
2462        };
2463
2464        let workspace = match self.contents.entries.get(ix) {
2465            Some(ListEntry::ProjectHeader { workspace, .. }) => Some(workspace.clone()),
2466            Some(
2467                ListEntry::Thread(_) | ListEntry::ViewMore { .. } | ListEntry::NewThread { .. },
2468            ) => self.contents.entries[..ix]
2469                .iter()
2470                .rev()
2471                .find_map(|entry| match entry {
2472                    ListEntry::ProjectHeader { workspace, .. } => Some(workspace.clone()),
2473                    _ => None,
2474                }),
2475            _ => None,
2476        };
2477
2478        let Some(workspace) = workspace else {
2479            return;
2480        };
2481
2482        self.focused_thread = None;
2483        if let Some(multi_workspace) = self.multi_workspace.upgrade() {
2484            multi_workspace.update(cx, |multi_workspace, cx| {
2485                multi_workspace.activate(workspace.clone(), cx);
2486            });
2487        }
2488        if AgentPanel::is_visible(&workspace, cx) {
2489            workspace.update(cx, |workspace, cx| {
2490                workspace.focus_panel::<AgentPanel>(window, cx);
2491            });
2492        }
2493    }
2494
2495    fn show_more_threads(
2496        &mut self,
2497        _: &ShowMoreThreads,
2498        _window: &mut Window,
2499        cx: &mut Context<Self>,
2500    ) {
2501        let Some(ix) = self.selection else {
2502            return;
2503        };
2504
2505        let path_list = match self.contents.entries.get(ix) {
2506            Some(ListEntry::ProjectHeader { path_list, .. }) => Some(path_list.clone()),
2507            Some(
2508                ListEntry::Thread(_) | ListEntry::ViewMore { .. } | ListEntry::NewThread { .. },
2509            ) => self.contents.entries[..ix]
2510                .iter()
2511                .rev()
2512                .find_map(|entry| match entry {
2513                    ListEntry::ProjectHeader { path_list, .. } => Some(path_list.clone()),
2514                    _ => None,
2515                }),
2516            _ => None,
2517        };
2518
2519        if let Some(path_list) = path_list {
2520            let current = self.expanded_groups.get(&path_list).copied().unwrap_or(0);
2521            self.expanded_groups.insert(path_list, current + 1);
2522            self.update_entries(cx);
2523        }
2524    }
2525
2526    fn show_fewer_threads(
2527        &mut self,
2528        _: &ShowFewerThreads,
2529        _window: &mut Window,
2530        cx: &mut Context<Self>,
2531    ) {
2532        let Some(ix) = self.selection else {
2533            return;
2534        };
2535
2536        let path_list = match self.contents.entries.get(ix) {
2537            Some(ListEntry::ProjectHeader { path_list, .. }) => Some(path_list.clone()),
2538            Some(
2539                ListEntry::Thread(_) | ListEntry::ViewMore { .. } | ListEntry::NewThread { .. },
2540            ) => self.contents.entries[..ix]
2541                .iter()
2542                .rev()
2543                .find_map(|entry| match entry {
2544                    ListEntry::ProjectHeader { path_list, .. } => Some(path_list.clone()),
2545                    _ => None,
2546                }),
2547            _ => None,
2548        };
2549
2550        if let Some(path_list) = path_list {
2551            self.expanded_groups.remove(&path_list);
2552            self.update_entries(cx);
2553        }
2554    }
2555
2556    fn record_thread_access(&mut self, session_id: &acp::SessionId) {
2557        self.thread_last_accessed
2558            .insert(session_id.clone(), Utc::now());
2559    }
2560
2561    fn record_thread_message_sent(&mut self, session_id: &acp::SessionId) {
2562        self.thread_last_message_sent_or_queued
2563            .insert(session_id.clone(), Utc::now());
2564    }
2565
2566    fn mru_threads_for_switcher(&self, _cx: &App) -> Vec<ThreadSwitcherEntry> {
2567        let mut current_header_workspace: Option<Entity<Workspace>> = None;
2568        let mut entries: Vec<ThreadSwitcherEntry> = self
2569            .contents
2570            .entries
2571            .iter()
2572            .filter_map(|entry| match entry {
2573                ListEntry::ProjectHeader { workspace, .. } => {
2574                    current_header_workspace = Some(workspace.clone());
2575                    None
2576                }
2577                ListEntry::Thread(thread) => {
2578                    let workspace = match &thread.workspace {
2579                        ThreadEntryWorkspace::Open(workspace) => workspace.clone(),
2580                        ThreadEntryWorkspace::Closed(_) => {
2581                            current_header_workspace.as_ref()?.clone()
2582                        }
2583                    };
2584                    let notified = self
2585                        .contents
2586                        .is_thread_notified(&thread.session_info.session_id);
2587                    let timestamp: SharedString = self
2588                        .thread_last_message_sent_or_queued
2589                        .get(&thread.session_info.session_id)
2590                        .copied()
2591                        .or(thread.session_info.created_at)
2592                        .or(thread.session_info.updated_at)
2593                        .map(format_history_entry_timestamp)
2594                        .unwrap_or_default()
2595                        .into();
2596                    Some(ThreadSwitcherEntry {
2597                        session_id: thread.session_info.session_id.clone(),
2598                        title: thread
2599                            .session_info
2600                            .title
2601                            .clone()
2602                            .unwrap_or_else(|| "Untitled".into()),
2603                        icon: thread.icon,
2604                        icon_from_external_svg: thread.icon_from_external_svg.clone(),
2605                        status: thread.status,
2606                        agent: thread.agent.clone(),
2607                        session_info: thread.session_info.clone(),
2608                        workspace,
2609                        worktree_name: thread.worktrees.first().map(|wt| wt.name.clone()),
2610
2611                        diff_stats: thread.diff_stats,
2612                        is_title_generating: thread.is_title_generating,
2613                        notified,
2614                        timestamp,
2615                    })
2616                }
2617                _ => None,
2618            })
2619            .collect();
2620
2621        entries.sort_by(|a, b| {
2622            let a_accessed = self.thread_last_accessed.get(&a.session_id);
2623            let b_accessed = self.thread_last_accessed.get(&b.session_id);
2624
2625            match (a_accessed, b_accessed) {
2626                (Some(a_time), Some(b_time)) => b_time.cmp(a_time),
2627                (Some(_), None) => std::cmp::Ordering::Less,
2628                (None, Some(_)) => std::cmp::Ordering::Greater,
2629                (None, None) => {
2630                    let a_sent = self.thread_last_message_sent_or_queued.get(&a.session_id);
2631                    let b_sent = self.thread_last_message_sent_or_queued.get(&b.session_id);
2632
2633                    match (a_sent, b_sent) {
2634                        (Some(a_time), Some(b_time)) => b_time.cmp(a_time),
2635                        (Some(_), None) => std::cmp::Ordering::Less,
2636                        (None, Some(_)) => std::cmp::Ordering::Greater,
2637                        (None, None) => {
2638                            let a_time = a.session_info.created_at.or(a.session_info.updated_at);
2639                            let b_time = b.session_info.created_at.or(b.session_info.updated_at);
2640                            b_time.cmp(&a_time)
2641                        }
2642                    }
2643                }
2644            }
2645        });
2646
2647        entries
2648    }
2649
2650    fn dismiss_thread_switcher(&mut self, cx: &mut Context<Self>) {
2651        self.thread_switcher = None;
2652        self._thread_switcher_subscriptions.clear();
2653        if let Some(mw) = self.multi_workspace.upgrade() {
2654            mw.update(cx, |mw, cx| {
2655                mw.set_sidebar_overlay(None, cx);
2656            });
2657        }
2658    }
2659
2660    fn on_toggle_thread_switcher(
2661        &mut self,
2662        action: &ToggleThreadSwitcher,
2663        window: &mut Window,
2664        cx: &mut Context<Self>,
2665    ) {
2666        self.toggle_thread_switcher_impl(action.select_last, window, cx);
2667    }
2668
2669    fn toggle_thread_switcher_impl(
2670        &mut self,
2671        select_last: bool,
2672        window: &mut Window,
2673        cx: &mut Context<Self>,
2674    ) {
2675        if let Some(thread_switcher) = &self.thread_switcher {
2676            thread_switcher.update(cx, |switcher, cx| {
2677                if select_last {
2678                    switcher.select_last(cx);
2679                } else {
2680                    switcher.cycle_selection(cx);
2681                }
2682            });
2683            return;
2684        }
2685
2686        let entries = self.mru_threads_for_switcher(cx);
2687        if entries.len() < 2 {
2688            return;
2689        }
2690
2691        let weak_multi_workspace = self.multi_workspace.clone();
2692
2693        let original_agent = self
2694            .focused_thread
2695            .as_ref()
2696            .and_then(|focused_id| entries.iter().find(|e| &e.session_id == focused_id))
2697            .map(|e| e.agent.clone());
2698        let original_session_info = self
2699            .focused_thread
2700            .as_ref()
2701            .and_then(|focused_id| entries.iter().find(|e| &e.session_id == focused_id))
2702            .map(|e| e.session_info.clone());
2703        let original_workspace = self
2704            .multi_workspace
2705            .upgrade()
2706            .map(|mw| mw.read(cx).workspace().clone());
2707
2708        let thread_switcher = cx.new(|cx| ThreadSwitcher::new(entries, select_last, window, cx));
2709
2710        let mut subscriptions = Vec::new();
2711
2712        subscriptions.push(cx.subscribe_in(&thread_switcher, window, {
2713            let thread_switcher = thread_switcher.clone();
2714            move |this, _emitter, event: &ThreadSwitcherEvent, window, cx| match event {
2715                ThreadSwitcherEvent::Preview {
2716                    agent,
2717                    session_info,
2718                    workspace,
2719                } => {
2720                    if let Some(mw) = weak_multi_workspace.upgrade() {
2721                        mw.update(cx, |mw, cx| {
2722                            mw.activate(workspace.clone(), cx);
2723                        });
2724                    }
2725                    this.focused_thread = Some(session_info.session_id.clone());
2726                    this.update_entries(cx);
2727                    Self::load_agent_thread_in_workspace(
2728                        workspace,
2729                        agent.clone(),
2730                        session_info.clone(),
2731                        false,
2732                        window,
2733                        cx,
2734                    );
2735                    let focus = thread_switcher.focus_handle(cx);
2736                    window.focus(&focus, cx);
2737                }
2738                ThreadSwitcherEvent::Confirmed {
2739                    agent,
2740                    session_info,
2741                    workspace,
2742                } => {
2743                    if let Some(mw) = weak_multi_workspace.upgrade() {
2744                        mw.update(cx, |mw, cx| {
2745                            mw.activate(workspace.clone(), cx);
2746                        });
2747                    }
2748                    this.record_thread_access(&session_info.session_id);
2749                    this.focused_thread = Some(session_info.session_id.clone());
2750                    this.update_entries(cx);
2751                    Self::load_agent_thread_in_workspace(
2752                        workspace,
2753                        agent.clone(),
2754                        session_info.clone(),
2755                        false,
2756                        window,
2757                        cx,
2758                    );
2759                    this.dismiss_thread_switcher(cx);
2760                    workspace.update(cx, |workspace, cx| {
2761                        workspace.focus_panel::<AgentPanel>(window, cx);
2762                    });
2763                }
2764                ThreadSwitcherEvent::Dismissed => {
2765                    if let Some(mw) = weak_multi_workspace.upgrade() {
2766                        if let Some(original_ws) = &original_workspace {
2767                            mw.update(cx, |mw, cx| {
2768                                mw.activate(original_ws.clone(), cx);
2769                            });
2770                        }
2771                    }
2772                    if let Some(session_info) = &original_session_info {
2773                        this.focused_thread = Some(session_info.session_id.clone());
2774                        this.update_entries(cx);
2775                        let agent = original_agent.clone().unwrap_or(Agent::NativeAgent);
2776                        if let Some(original_ws) = &original_workspace {
2777                            Self::load_agent_thread_in_workspace(
2778                                original_ws,
2779                                agent,
2780                                session_info.clone(),
2781                                false,
2782                                window,
2783                                cx,
2784                            );
2785                        }
2786                    }
2787                    this.dismiss_thread_switcher(cx);
2788                }
2789            }
2790        }));
2791
2792        subscriptions.push(cx.subscribe_in(
2793            &thread_switcher,
2794            window,
2795            |this, _emitter, _event: &gpui::DismissEvent, _window, cx| {
2796                this.dismiss_thread_switcher(cx);
2797            },
2798        ));
2799
2800        let focus = thread_switcher.focus_handle(cx);
2801        let overlay_view = gpui::AnyView::from(thread_switcher.clone());
2802
2803        // Replay the initial preview that was emitted during construction
2804        // before subscriptions were wired up.
2805        let initial_preview = thread_switcher.read(cx).selected_entry().map(|entry| {
2806            (
2807                entry.agent.clone(),
2808                entry.session_info.clone(),
2809                entry.workspace.clone(),
2810            )
2811        });
2812
2813        self.thread_switcher = Some(thread_switcher);
2814        self._thread_switcher_subscriptions = subscriptions;
2815        if let Some(mw) = self.multi_workspace.upgrade() {
2816            mw.update(cx, |mw, cx| {
2817                mw.set_sidebar_overlay(Some(overlay_view), cx);
2818            });
2819        }
2820
2821        if let Some((agent, session_info, workspace)) = initial_preview {
2822            if let Some(mw) = self.multi_workspace.upgrade() {
2823                mw.update(cx, |mw, cx| {
2824                    mw.activate(workspace.clone(), cx);
2825                });
2826            }
2827            self.focused_thread = Some(session_info.session_id.clone());
2828            self.update_entries(cx);
2829            Self::load_agent_thread_in_workspace(
2830                &workspace,
2831                agent,
2832                session_info,
2833                false,
2834                window,
2835                cx,
2836            );
2837        }
2838
2839        window.focus(&focus, cx);
2840    }
2841
2842    fn render_thread(
2843        &self,
2844        ix: usize,
2845        thread: &ThreadEntry,
2846        is_focused: bool,
2847        cx: &mut Context<Self>,
2848    ) -> AnyElement {
2849        let has_notification = self
2850            .contents
2851            .is_thread_notified(&thread.session_info.session_id);
2852
2853        let title: SharedString = thread
2854            .session_info
2855            .title
2856            .clone()
2857            .unwrap_or_else(|| "Untitled".into());
2858        let session_info = thread.session_info.clone();
2859        let thread_workspace = thread.workspace.clone();
2860
2861        let is_hovered = self.hovered_thread_index == Some(ix);
2862        let is_selected = self.agent_panel_visible
2863            && self.focused_thread.as_ref() == Some(&session_info.session_id);
2864        let is_running = matches!(
2865            thread.status,
2866            AgentThreadStatus::Running | AgentThreadStatus::WaitingForConfirmation
2867        );
2868
2869        let session_id_for_delete = thread.session_info.session_id.clone();
2870        let focus_handle = self.focus_handle.clone();
2871
2872        let id = SharedString::from(format!("thread-entry-{}", ix));
2873
2874        let timestamp = self
2875            .thread_last_message_sent_or_queued
2876            .get(&thread.session_info.session_id)
2877            .copied()
2878            .or(thread.session_info.created_at)
2879            .or(thread.session_info.updated_at)
2880            .map(format_history_entry_timestamp);
2881
2882        ThreadItem::new(id, title)
2883            .icon(thread.icon)
2884            .status(thread.status)
2885            .when_some(thread.icon_from_external_svg.clone(), |this, svg| {
2886                this.custom_icon_from_external_svg(svg)
2887            })
2888            .worktrees(
2889                thread
2890                    .worktrees
2891                    .iter()
2892                    .map(|wt| ThreadItemWorktreeInfo {
2893                        name: wt.name.clone(),
2894                        full_path: wt.full_path.clone(),
2895                        highlight_positions: wt.highlight_positions.clone(),
2896                    })
2897                    .collect(),
2898            )
2899            .when_some(timestamp, |this, ts| this.timestamp(ts))
2900            .highlight_positions(thread.highlight_positions.to_vec())
2901            .title_generating(thread.is_title_generating)
2902            .notified(has_notification)
2903            .when(thread.diff_stats.lines_added > 0, |this| {
2904                this.added(thread.diff_stats.lines_added as usize)
2905            })
2906            .when(thread.diff_stats.lines_removed > 0, |this| {
2907                this.removed(thread.diff_stats.lines_removed as usize)
2908            })
2909            .selected(is_selected)
2910            .focused(is_focused)
2911            .hovered(is_hovered)
2912            .on_hover(cx.listener(move |this, is_hovered: &bool, _window, cx| {
2913                if *is_hovered {
2914                    this.hovered_thread_index = Some(ix);
2915                } else if this.hovered_thread_index == Some(ix) {
2916                    this.hovered_thread_index = None;
2917                }
2918                cx.notify();
2919            }))
2920            .when(is_hovered && is_running, |this| {
2921                this.action_slot(
2922                    IconButton::new("stop-thread", IconName::Stop)
2923                        .icon_size(IconSize::Small)
2924                        .icon_color(Color::Error)
2925                        .style(ButtonStyle::Tinted(TintColor::Error))
2926                        .tooltip(Tooltip::text("Stop Generation"))
2927                        .on_click({
2928                            let session_id = session_id_for_delete.clone();
2929                            cx.listener(move |this, _, _window, cx| {
2930                                this.stop_thread(&session_id, cx);
2931                            })
2932                        }),
2933                )
2934            })
2935            .when(is_hovered && !is_running, |this| {
2936                this.action_slot(
2937                    IconButton::new("archive-thread", IconName::Archive)
2938                        .icon_size(IconSize::Small)
2939                        .icon_color(Color::Muted)
2940                        .tooltip({
2941                            let focus_handle = focus_handle.clone();
2942                            move |_window, cx| {
2943                                Tooltip::for_action_in(
2944                                    "Archive Thread",
2945                                    &RemoveSelectedThread,
2946                                    &focus_handle,
2947                                    cx,
2948                                )
2949                            }
2950                        })
2951                        .on_click({
2952                            let session_id = session_id_for_delete.clone();
2953                            cx.listener(move |this, _, window, cx| {
2954                                this.archive_thread(&session_id, window, cx);
2955                            })
2956                        }),
2957                )
2958            })
2959            .on_click({
2960                let agent = thread.agent.clone();
2961                cx.listener(move |this, _, window, cx| {
2962                    this.selection = None;
2963                    match &thread_workspace {
2964                        ThreadEntryWorkspace::Open(workspace) => {
2965                            this.activate_thread(
2966                                agent.clone(),
2967                                session_info.clone(),
2968                                workspace,
2969                                window,
2970                                cx,
2971                            );
2972                        }
2973                        ThreadEntryWorkspace::Closed(path_list) => {
2974                            this.open_workspace_and_activate_thread(
2975                                agent.clone(),
2976                                session_info.clone(),
2977                                path_list.clone(),
2978                                window,
2979                                cx,
2980                            );
2981                        }
2982                    }
2983                })
2984            })
2985            .into_any_element()
2986    }
2987
2988    fn render_filter_input(&self, cx: &mut Context<Self>) -> impl IntoElement {
2989        div()
2990            .min_w_0()
2991            .flex_1()
2992            .capture_action(
2993                cx.listener(|this, _: &editor::actions::Newline, window, cx| {
2994                    this.editor_confirm(window, cx);
2995                }),
2996            )
2997            .child(self.filter_editor.clone())
2998    }
2999
3000    fn render_recent_projects_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
3001        let multi_workspace = self.multi_workspace.upgrade();
3002
3003        let workspace = multi_workspace
3004            .as_ref()
3005            .map(|mw| mw.read(cx).workspace().downgrade());
3006
3007        let focus_handle = workspace
3008            .as_ref()
3009            .and_then(|ws| ws.upgrade())
3010            .map(|w| w.read(cx).focus_handle(cx))
3011            .unwrap_or_else(|| cx.focus_handle());
3012
3013        let sibling_workspace_ids: HashSet<WorkspaceId> = multi_workspace
3014            .as_ref()
3015            .map(|mw| {
3016                mw.read(cx)
3017                    .workspaces()
3018                    .iter()
3019                    .filter_map(|ws| ws.read(cx).database_id())
3020                    .collect()
3021            })
3022            .unwrap_or_default();
3023
3024        let popover_handle = self.recent_projects_popover_handle.clone();
3025
3026        PopoverMenu::new("sidebar-recent-projects-menu")
3027            .with_handle(popover_handle)
3028            .menu(move |window, cx| {
3029                workspace.as_ref().map(|ws| {
3030                    SidebarRecentProjects::popover(
3031                        ws.clone(),
3032                        sibling_workspace_ids.clone(),
3033                        focus_handle.clone(),
3034                        window,
3035                        cx,
3036                    )
3037                })
3038            })
3039            .trigger_with_tooltip(
3040                IconButton::new("open-project", IconName::OpenFolder)
3041                    .icon_size(IconSize::Small)
3042                    .selected_style(ButtonStyle::Tinted(TintColor::Accent)),
3043                |_window, cx| {
3044                    Tooltip::for_action(
3045                        "Add Project",
3046                        &OpenRecent {
3047                            create_new_window: false,
3048                        },
3049                        cx,
3050                    )
3051                },
3052            )
3053            .offset(gpui::Point {
3054                x: px(-2.0),
3055                y: px(-2.0),
3056            })
3057            .anchor(gpui::Corner::BottomRight)
3058    }
3059
3060    fn render_view_more(
3061        &self,
3062        ix: usize,
3063        path_list: &PathList,
3064        is_fully_expanded: bool,
3065        is_selected: bool,
3066        cx: &mut Context<Self>,
3067    ) -> AnyElement {
3068        let path_list = path_list.clone();
3069        let id = SharedString::from(format!("view-more-{}", ix));
3070
3071        let label: SharedString = if is_fully_expanded {
3072            "Collapse".into()
3073        } else {
3074            "View More".into()
3075        };
3076
3077        ThreadItem::new(id, label)
3078            .focused(is_selected)
3079            .icon_visible(false)
3080            .title_label_color(Color::Muted)
3081            .on_click(cx.listener(move |this, _, _window, cx| {
3082                this.selection = None;
3083                if is_fully_expanded {
3084                    this.expanded_groups.remove(&path_list);
3085                } else {
3086                    let current = this.expanded_groups.get(&path_list).copied().unwrap_or(0);
3087                    this.expanded_groups.insert(path_list.clone(), current + 1);
3088                }
3089                this.update_entries(cx);
3090            }))
3091            .into_any_element()
3092    }
3093
3094    fn new_thread_in_group(
3095        &mut self,
3096        _: &NewThreadInGroup,
3097        window: &mut Window,
3098        cx: &mut Context<Self>,
3099    ) {
3100        // If there is a keyboard selection, walk backwards through
3101        // `project_header_indices` to find the header that owns the selected
3102        // row. Otherwise fall back to the active workspace.
3103        let workspace = if let Some(selected_ix) = self.selection {
3104            self.contents
3105                .project_header_indices
3106                .iter()
3107                .rev()
3108                .find(|&&header_ix| header_ix <= selected_ix)
3109                .and_then(|&header_ix| match &self.contents.entries[header_ix] {
3110                    ListEntry::ProjectHeader { workspace, .. } => Some(workspace.clone()),
3111                    _ => None,
3112                })
3113        } else {
3114            // Use the currently active workspace.
3115            self.multi_workspace
3116                .upgrade()
3117                .map(|mw| mw.read(cx).workspace().clone())
3118        };
3119
3120        let Some(workspace) = workspace else {
3121            return;
3122        };
3123
3124        self.create_new_thread(&workspace, window, cx);
3125    }
3126
3127    fn create_new_thread(
3128        &mut self,
3129        workspace: &Entity<Workspace>,
3130        window: &mut Window,
3131        cx: &mut Context<Self>,
3132    ) {
3133        let Some(multi_workspace) = self.multi_workspace.upgrade() else {
3134            return;
3135        };
3136
3137        // Clear focused_thread immediately so no existing thread stays
3138        // highlighted while the new blank thread is being shown. Without this,
3139        // if the target workspace is already active (so ActiveWorkspaceChanged
3140        // never fires), the previous thread's highlight would linger.
3141        self.focused_thread = None;
3142
3143        multi_workspace.update(cx, |multi_workspace, cx| {
3144            multi_workspace.activate(workspace.clone(), cx);
3145        });
3146
3147        workspace.update(cx, |workspace, cx| {
3148            if let Some(agent_panel) = workspace.panel::<AgentPanel>(cx) {
3149                agent_panel.update(cx, |panel, cx| {
3150                    panel.new_thread(&NewThread, window, cx);
3151                });
3152            }
3153            workspace.focus_panel::<AgentPanel>(window, cx);
3154        });
3155    }
3156
3157    fn render_new_thread(
3158        &self,
3159        ix: usize,
3160        _path_list: &PathList,
3161        workspace: &Entity<Workspace>,
3162        is_active_draft: bool,
3163        is_selected: bool,
3164        cx: &mut Context<Self>,
3165    ) -> AnyElement {
3166        let is_active = is_active_draft && self.agent_panel_visible && self.active_thread_is_draft;
3167
3168        let label: SharedString = if is_active {
3169            self.active_draft_text(cx)
3170                .unwrap_or_else(|| DEFAULT_THREAD_TITLE.into())
3171        } else {
3172            DEFAULT_THREAD_TITLE.into()
3173        };
3174
3175        let workspace = workspace.clone();
3176        let id = SharedString::from(format!("new-thread-btn-{}", ix));
3177
3178        let thread_item = ThreadItem::new(id, label)
3179            .icon(IconName::Plus)
3180            .icon_color(Color::Custom(cx.theme().colors().icon_muted.opacity(0.8)))
3181            .selected(is_active)
3182            .focused(is_selected)
3183            .when(!is_active, |this| {
3184                this.on_click(cx.listener(move |this, _, window, cx| {
3185                    this.selection = None;
3186                    this.create_new_thread(&workspace, window, cx);
3187                }))
3188            });
3189
3190        if is_active {
3191            div()
3192                .on_mouse_down(gpui::MouseButton::Left, |_, _, cx| {
3193                    cx.stop_propagation();
3194                })
3195                .child(thread_item)
3196                .into_any_element()
3197        } else {
3198            thread_item.into_any_element()
3199        }
3200    }
3201
3202    fn render_no_results(&self, cx: &mut Context<Self>) -> impl IntoElement {
3203        let has_query = self.has_filter_query(cx);
3204        let message = if has_query {
3205            "No threads match your search."
3206        } else {
3207            "No threads yet"
3208        };
3209
3210        v_flex()
3211            .id("sidebar-no-results")
3212            .p_4()
3213            .size_full()
3214            .items_center()
3215            .justify_center()
3216            .child(
3217                Label::new(message)
3218                    .size(LabelSize::Small)
3219                    .color(Color::Muted),
3220            )
3221    }
3222
3223    fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
3224        v_flex()
3225            .id("sidebar-empty-state")
3226            .p_4()
3227            .size_full()
3228            .items_center()
3229            .justify_center()
3230            .gap_1()
3231            .track_focus(&self.focus_handle(cx))
3232            .child(
3233                Button::new("open_project", "Open Project")
3234                    .full_width()
3235                    .key_binding(KeyBinding::for_action(&workspace::Open::default(), cx))
3236                    .on_click(|_, window, cx| {
3237                        window.dispatch_action(
3238                            Open {
3239                                create_new_window: false,
3240                            }
3241                            .boxed_clone(),
3242                            cx,
3243                        );
3244                    }),
3245            )
3246            .child(
3247                h_flex()
3248                    .w_1_2()
3249                    .gap_2()
3250                    .child(Divider::horizontal())
3251                    .child(Label::new("or").size(LabelSize::XSmall).color(Color::Muted))
3252                    .child(Divider::horizontal()),
3253            )
3254            .child(
3255                Button::new("clone_repo", "Clone Repository")
3256                    .full_width()
3257                    .on_click(|_, window, cx| {
3258                        window.dispatch_action(git::Clone.boxed_clone(), cx);
3259                    }),
3260            )
3261    }
3262
3263    fn render_sidebar_header(
3264        &self,
3265        no_open_projects: bool,
3266        window: &Window,
3267        cx: &mut Context<Self>,
3268    ) -> impl IntoElement {
3269        let has_query = self.has_filter_query(cx);
3270        let sidebar_on_left = self.side(cx) == SidebarSide::Left;
3271        let traffic_lights =
3272            cfg!(target_os = "macos") && !window.is_fullscreen() && sidebar_on_left;
3273        let header_height = platform_title_bar_height(window);
3274
3275        h_flex()
3276            .h(header_height)
3277            .mt_px()
3278            .pb_px()
3279            .map(|this| {
3280                if traffic_lights {
3281                    this.pl(px(ui::utils::TRAFFIC_LIGHT_PADDING))
3282                } else {
3283                    this.pl_1p5()
3284                }
3285            })
3286            .pr_1p5()
3287            .gap_1()
3288            .when(!no_open_projects, |this| {
3289                this.border_b_1()
3290                    .border_color(cx.theme().colors().border)
3291                    .when(traffic_lights, |this| {
3292                        this.child(Divider::vertical().color(ui::DividerColor::Border))
3293                    })
3294                    .child(
3295                        div().ml_1().child(
3296                            Icon::new(IconName::MagnifyingGlass)
3297                                .size(IconSize::Small)
3298                                .color(Color::Muted),
3299                        ),
3300                    )
3301                    .child(self.render_filter_input(cx))
3302                    .child(
3303                        h_flex()
3304                            .gap_1()
3305                            .when(
3306                                self.selection.is_some()
3307                                    && !self.filter_editor.focus_handle(cx).is_focused(window),
3308                                |this| this.child(KeyBinding::for_action(&FocusSidebarFilter, cx)),
3309                            )
3310                            .when(has_query, |this| {
3311                                this.child(
3312                                    IconButton::new("clear_filter", IconName::Close)
3313                                        .icon_size(IconSize::Small)
3314                                        .tooltip(Tooltip::text("Clear Search"))
3315                                        .on_click(cx.listener(|this, _, window, cx| {
3316                                            this.reset_filter_editor_text(window, cx);
3317                                            this.update_entries(cx);
3318                                        })),
3319                                )
3320                            }),
3321                    )
3322            })
3323    }
3324
3325    fn render_sidebar_toggle_button(&self, _cx: &mut Context<Self>) -> impl IntoElement {
3326        let on_right = AgentSettings::get_global(_cx).sidebar_side() == SidebarSide::Right;
3327
3328        sidebar_side_context_menu("sidebar-toggle-menu", _cx)
3329            .anchor(if on_right {
3330                gpui::Corner::BottomRight
3331            } else {
3332                gpui::Corner::BottomLeft
3333            })
3334            .attach(if on_right {
3335                gpui::Corner::TopRight
3336            } else {
3337                gpui::Corner::TopLeft
3338            })
3339            .trigger(move |_is_active, _window, _cx| {
3340                let icon = if on_right {
3341                    IconName::ThreadsSidebarRightOpen
3342                } else {
3343                    IconName::ThreadsSidebarLeftOpen
3344                };
3345                IconButton::new("sidebar-close-toggle", icon)
3346                    .icon_size(IconSize::Small)
3347                    .tooltip(Tooltip::element(move |_window, cx| {
3348                        v_flex()
3349                            .gap_1()
3350                            .child(
3351                                h_flex()
3352                                    .gap_2()
3353                                    .justify_between()
3354                                    .child(Label::new("Toggle Sidebar"))
3355                                    .child(KeyBinding::for_action(&ToggleWorkspaceSidebar, cx)),
3356                            )
3357                            .child(
3358                                h_flex()
3359                                    .pt_1()
3360                                    .gap_2()
3361                                    .border_t_1()
3362                                    .border_color(cx.theme().colors().border_variant)
3363                                    .justify_between()
3364                                    .child(Label::new("Focus Sidebar"))
3365                                    .child(KeyBinding::for_action(&FocusWorkspaceSidebar, cx)),
3366                            )
3367                            .into_any_element()
3368                    }))
3369                    .on_click(|_, window, cx| {
3370                        if let Some(multi_workspace) = window.root::<MultiWorkspace>().flatten() {
3371                            multi_workspace.update(cx, |multi_workspace, cx| {
3372                                multi_workspace.close_sidebar(window, cx);
3373                            });
3374                        }
3375                    })
3376            })
3377    }
3378
3379    fn render_sidebar_bottom_bar(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
3380        let on_right = self.side(cx) == SidebarSide::Right;
3381        let is_archive = matches!(self.view, SidebarView::Archive(..));
3382        let action_buttons = h_flex()
3383            .gap_1()
3384            .child(
3385                IconButton::new("archive", IconName::Archive)
3386                    .icon_size(IconSize::Small)
3387                    .toggle_state(is_archive)
3388                    .tooltip(move |_, cx| {
3389                        Tooltip::for_action("Toggle Archived Threads", &ToggleArchive, cx)
3390                    })
3391                    .on_click(cx.listener(|this, _, window, cx| {
3392                        this.toggle_archive(&ToggleArchive, window, cx);
3393                    })),
3394            )
3395            .child(self.render_recent_projects_button(cx));
3396        let border_color = cx.theme().colors().border;
3397        let toggle_button = self.render_sidebar_toggle_button(cx);
3398
3399        let bar = h_flex()
3400            .p_1()
3401            .gap_1()
3402            .justify_between()
3403            .border_t_1()
3404            .border_color(border_color);
3405
3406        if on_right {
3407            bar.child(action_buttons).child(toggle_button)
3408        } else {
3409            bar.child(toggle_button).child(action_buttons)
3410        }
3411    }
3412
3413    fn toggle_archive(&mut self, _: &ToggleArchive, window: &mut Window, cx: &mut Context<Self>) {
3414        match &self.view {
3415            SidebarView::ThreadList => self.show_archive(window, cx),
3416            SidebarView::Archive(_) => self.show_thread_list(window, cx),
3417        }
3418    }
3419
3420    fn show_archive(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3421        let Some(active_workspace) = self.multi_workspace.upgrade().and_then(|w| {
3422            w.read(cx)
3423                .workspaces()
3424                .get(w.read(cx).active_workspace_index())
3425                .cloned()
3426        }) else {
3427            return;
3428        };
3429
3430        let Some(agent_panel) = active_workspace.read(cx).panel::<AgentPanel>(cx) else {
3431            return;
3432        };
3433
3434        let thread_store = agent_panel.read(cx).thread_store().clone();
3435        let fs = active_workspace.read(cx).project().read(cx).fs().clone();
3436        let agent_connection_store = agent_panel.read(cx).connection_store().clone();
3437        let agent_server_store = active_workspace
3438            .read(cx)
3439            .project()
3440            .read(cx)
3441            .agent_server_store()
3442            .clone();
3443
3444        let archive_view = cx.new(|cx| {
3445            ThreadsArchiveView::new(
3446                agent_connection_store,
3447                agent_server_store,
3448                thread_store,
3449                fs,
3450                window,
3451                cx,
3452            )
3453        });
3454        let subscription = cx.subscribe_in(
3455            &archive_view,
3456            window,
3457            |this, _, event: &ThreadsArchiveViewEvent, window, cx| match event {
3458                ThreadsArchiveViewEvent::Close => {
3459                    this.show_thread_list(window, cx);
3460                }
3461                ThreadsArchiveViewEvent::Unarchive {
3462                    agent,
3463                    session_info,
3464                } => {
3465                    this.show_thread_list(window, cx);
3466                    this.activate_archived_thread(agent.clone(), session_info.clone(), window, cx);
3467                }
3468            },
3469        );
3470
3471        self._subscriptions.push(subscription);
3472        self.view = SidebarView::Archive(archive_view.clone());
3473        archive_view.update(cx, |view, cx| view.focus_filter_editor(window, cx));
3474        cx.notify();
3475    }
3476
3477    fn show_thread_list(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3478        self.view = SidebarView::ThreadList;
3479        self._subscriptions.clear();
3480        let handle = self.filter_editor.read(cx).focus_handle(cx);
3481        handle.focus(window, cx);
3482        cx.notify();
3483    }
3484}
3485
3486impl WorkspaceSidebar for Sidebar {
3487    fn width(&self, _cx: &App) -> Pixels {
3488        self.width
3489    }
3490
3491    fn set_width(&mut self, width: Option<Pixels>, cx: &mut Context<Self>) {
3492        self.width = width.unwrap_or(DEFAULT_WIDTH).clamp(MIN_WIDTH, MAX_WIDTH);
3493        cx.notify();
3494    }
3495
3496    fn has_notifications(&self, _cx: &App) -> bool {
3497        !self.contents.notified_threads.is_empty()
3498    }
3499
3500    fn is_threads_list_view_active(&self) -> bool {
3501        matches!(self.view, SidebarView::ThreadList)
3502    }
3503
3504    fn side(&self, cx: &App) -> SidebarSide {
3505        AgentSettings::get_global(cx).sidebar_side()
3506    }
3507
3508    fn prepare_for_focus(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
3509        self.selection = None;
3510        cx.notify();
3511    }
3512
3513    fn toggle_thread_switcher(
3514        &mut self,
3515        select_last: bool,
3516        window: &mut Window,
3517        cx: &mut Context<Self>,
3518    ) {
3519        self.toggle_thread_switcher_impl(select_last, window, cx);
3520    }
3521}
3522
3523impl Focusable for Sidebar {
3524    fn focus_handle(&self, _cx: &App) -> FocusHandle {
3525        self.focus_handle.clone()
3526    }
3527}
3528
3529impl Render for Sidebar {
3530    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3531        let _titlebar_height = ui::utils::platform_title_bar_height(window);
3532        let ui_font = theme_settings::setup_ui_font(window, cx);
3533        let sticky_header = self.render_sticky_header(window, cx);
3534
3535        let color = cx.theme().colors();
3536        let bg = color
3537            .title_bar_background
3538            .blend(color.panel_background.opacity(0.32));
3539
3540        let no_open_projects = !self.contents.has_open_projects;
3541        let no_search_results = self.contents.entries.is_empty();
3542
3543        v_flex()
3544            .id("workspace-sidebar")
3545            .key_context(self.dispatch_context(window, cx))
3546            .track_focus(&self.focus_handle)
3547            .on_action(cx.listener(Self::select_next))
3548            .on_action(cx.listener(Self::select_previous))
3549            .on_action(cx.listener(Self::editor_move_down))
3550            .on_action(cx.listener(Self::editor_move_up))
3551            .on_action(cx.listener(Self::select_first))
3552            .on_action(cx.listener(Self::select_last))
3553            .on_action(cx.listener(Self::confirm))
3554            .on_action(cx.listener(Self::expand_selected_entry))
3555            .on_action(cx.listener(Self::collapse_selected_entry))
3556            .on_action(cx.listener(Self::toggle_selected_fold))
3557            .on_action(cx.listener(Self::fold_all))
3558            .on_action(cx.listener(Self::unfold_all))
3559            .on_action(cx.listener(Self::cancel))
3560            .on_action(cx.listener(Self::remove_selected_thread))
3561            .on_action(cx.listener(Self::remove_selected_workspace))
3562            .on_action(cx.listener(Self::remove_selected))
3563            .on_action(cx.listener(Self::stop_selected_thread))
3564            .on_action(cx.listener(Self::activate_selected_workspace))
3565            .on_action(cx.listener(Self::show_more_threads))
3566            .on_action(cx.listener(Self::show_fewer_threads))
3567            .on_action(cx.listener(Self::new_thread_in_group))
3568            .on_action(cx.listener(Self::toggle_archive))
3569            .on_action(cx.listener(Self::focus_sidebar_filter))
3570            .on_action(cx.listener(Self::on_toggle_thread_switcher))
3571            .on_action(cx.listener(|this, _: &OpenRecent, window, cx| {
3572                this.recent_projects_popover_handle.toggle(window, cx);
3573            }))
3574            .font(ui_font)
3575            .h_full()
3576            .w(self.width)
3577            .bg(bg)
3578            .when(self.side(cx) == SidebarSide::Left, |el| el.border_r_1())
3579            .when(self.side(cx) == SidebarSide::Right, |el| el.border_l_1())
3580            .border_color(color.border)
3581            .map(|this| match &self.view {
3582                SidebarView::ThreadList => this
3583                    .child(self.render_sidebar_header(no_open_projects, window, cx))
3584                    .map(|this| {
3585                        if no_open_projects {
3586                            this.child(self.render_empty_state(cx))
3587                        } else {
3588                            this.child(
3589                                v_flex()
3590                                    .relative()
3591                                    .flex_1()
3592                                    .overflow_hidden()
3593                                    .child(
3594                                        list(
3595                                            self.list_state.clone(),
3596                                            cx.processor(Self::render_list_entry),
3597                                        )
3598                                        .flex_1()
3599                                        .size_full(),
3600                                    )
3601                                    .when(no_search_results, |this| {
3602                                        this.child(self.render_no_results(cx))
3603                                    })
3604                                    .when_some(sticky_header, |this, header| this.child(header))
3605                                    .vertical_scrollbar_for(&self.list_state, window, cx),
3606                            )
3607                        }
3608                    }),
3609                SidebarView::Archive(archive_view) => this.child(archive_view.clone()),
3610            })
3611            .child(self.render_sidebar_bottom_bar(cx))
3612    }
3613}
3614
3615fn all_thread_infos_for_workspace(
3616    workspace: &Entity<Workspace>,
3617    cx: &App,
3618) -> impl Iterator<Item = ActiveThreadInfo> {
3619    let Some(agent_panel) = workspace.read(cx).panel::<AgentPanel>(cx) else {
3620        return None.into_iter().flatten();
3621    };
3622    let agent_panel = agent_panel.read(cx);
3623
3624    let threads = agent_panel
3625        .parent_threads(cx)
3626        .into_iter()
3627        .map(|thread_view| {
3628            let thread_view_ref = thread_view.read(cx);
3629            let thread = thread_view_ref.thread.read(cx);
3630
3631            let icon = thread_view_ref.agent_icon;
3632            let icon_from_external_svg = thread_view_ref.agent_icon_from_external_svg.clone();
3633            let title = thread
3634                .title()
3635                .unwrap_or_else(|| DEFAULT_THREAD_TITLE.into());
3636            let is_native = thread_view_ref.as_native_thread(cx).is_some();
3637            let is_title_generating = is_native && thread.has_provisional_title();
3638            let session_id = thread.session_id().clone();
3639            let is_background = agent_panel.is_background_thread(&session_id);
3640
3641            let status = if thread.is_waiting_for_confirmation() {
3642                AgentThreadStatus::WaitingForConfirmation
3643            } else if thread.had_error() {
3644                AgentThreadStatus::Error
3645            } else {
3646                match thread.status() {
3647                    ThreadStatus::Generating => AgentThreadStatus::Running,
3648                    ThreadStatus::Idle => AgentThreadStatus::Completed,
3649                }
3650            };
3651
3652            let diff_stats = thread.action_log().read(cx).diff_stats(cx);
3653
3654            ActiveThreadInfo {
3655                session_id,
3656                title,
3657                status,
3658                icon,
3659                icon_from_external_svg,
3660                is_background,
3661                is_title_generating,
3662                diff_stats,
3663            }
3664        });
3665
3666    Some(threads).into_iter().flatten()
3667}