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