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