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