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