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