sidebar.rs

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