sidebar.rs

   1use acp_thread::ThreadStatus;
   2use agent::ThreadStore;
   3use agent_client_protocol as acp;
   4use agent_ui::{AgentPanel, AgentPanelEvent, NewThread};
   5use chrono::Utc;
   6use editor::{Editor, EditorElement, EditorStyle};
   7use feature_flags::{AgentV2FeatureFlag, FeatureFlagViewExt as _};
   8use gpui::{
   9    AnyElement, App, Context, Entity, EventEmitter, FocusHandle, Focusable, FontStyle, ListState,
  10    Pixels, Render, SharedString, TextStyle, WeakEntity, Window, actions, list, prelude::*, px,
  11    relative, rems,
  12};
  13use menu::{Cancel, Confirm, SelectFirst, SelectLast, SelectNext, SelectPrevious};
  14use project::Event as ProjectEvent;
  15use recent_projects::RecentProjects;
  16use settings::Settings;
  17use std::collections::{HashMap, HashSet};
  18use std::mem;
  19use theme::{ActiveTheme, ThemeSettings};
  20use ui::utils::TRAFFIC_LIGHT_PADDING;
  21use ui::{
  22    AgentThreadStatus, ButtonStyle, GradientFade, HighlightedLabel, IconButtonShape, KeyBinding,
  23    ListItem, PopoverMenu, PopoverMenuHandle, Tab, ThreadItem, TintColor, Tooltip, WithScrollbar,
  24    prelude::*,
  25};
  26use util::path_list::PathList;
  27use workspace::{
  28    FocusWorkspaceSidebar, MultiWorkspace, MultiWorkspaceEvent, Sidebar as WorkspaceSidebar,
  29    SidebarEvent, ToggleWorkspaceSidebar, Workspace,
  30};
  31use zed_actions::OpenRecent;
  32use zed_actions::editor::{MoveDown, MoveUp};
  33
  34actions!(
  35    agents_sidebar,
  36    [
  37        /// Collapses the selected entry in the workspace sidebar.
  38        CollapseSelectedEntry,
  39        /// Expands the selected entry in the workspace sidebar.
  40        ExpandSelectedEntry,
  41    ]
  42);
  43
  44const DEFAULT_WIDTH: Pixels = px(320.0);
  45const MIN_WIDTH: Pixels = px(200.0);
  46const MAX_WIDTH: Pixels = px(800.0);
  47const DEFAULT_THREADS_SHOWN: usize = 5;
  48
  49#[derive(Clone, Debug)]
  50struct ActiveThreadInfo {
  51    session_id: acp::SessionId,
  52    title: SharedString,
  53    status: AgentThreadStatus,
  54    icon: IconName,
  55    icon_from_external_svg: Option<SharedString>,
  56    is_background: bool,
  57}
  58
  59impl From<&ActiveThreadInfo> for acp_thread::AgentSessionInfo {
  60    fn from(info: &ActiveThreadInfo) -> Self {
  61        Self {
  62            session_id: info.session_id.clone(),
  63            cwd: None,
  64            title: Some(info.title.clone()),
  65            updated_at: Some(Utc::now()),
  66            created_at: Some(Utc::now()),
  67            meta: None,
  68        }
  69    }
  70}
  71
  72#[derive(Clone)]
  73struct ThreadEntry {
  74    session_info: acp_thread::AgentSessionInfo,
  75    icon: IconName,
  76    icon_from_external_svg: Option<SharedString>,
  77    status: AgentThreadStatus,
  78    workspace: Entity<Workspace>,
  79    is_live: bool,
  80    is_background: bool,
  81    highlight_positions: Vec<usize>,
  82}
  83
  84#[derive(Clone)]
  85enum ListEntry {
  86    ProjectHeader {
  87        path_list: PathList,
  88        label: SharedString,
  89        workspace: Entity<Workspace>,
  90        highlight_positions: Vec<usize>,
  91        has_threads: bool,
  92    },
  93    Thread(ThreadEntry),
  94    ViewMore {
  95        path_list: PathList,
  96        remaining_count: usize,
  97        is_fully_expanded: bool,
  98    },
  99    NewThread {
 100        path_list: PathList,
 101        workspace: Entity<Workspace>,
 102    },
 103}
 104
 105impl From<ThreadEntry> for ListEntry {
 106    fn from(thread: ThreadEntry) -> Self {
 107        ListEntry::Thread(thread)
 108    }
 109}
 110
 111#[derive(Default)]
 112struct SidebarContents {
 113    entries: Vec<ListEntry>,
 114    notified_threads: HashSet<acp::SessionId>,
 115}
 116
 117impl SidebarContents {
 118    fn is_thread_notified(&self, session_id: &acp::SessionId) -> bool {
 119        self.notified_threads.contains(session_id)
 120    }
 121}
 122
 123fn fuzzy_match_positions(query: &str, candidate: &str) -> Option<Vec<usize>> {
 124    let mut positions = Vec::new();
 125    let mut query_chars = query.chars().peekable();
 126
 127    for (byte_idx, candidate_char) in candidate.char_indices() {
 128        if let Some(&query_char) = query_chars.peek() {
 129            if candidate_char.eq_ignore_ascii_case(&query_char) {
 130                positions.push(byte_idx);
 131                query_chars.next();
 132            }
 133        } else {
 134            break;
 135        }
 136    }
 137
 138    if query_chars.peek().is_none() {
 139        Some(positions)
 140    } else {
 141        None
 142    }
 143}
 144
 145fn workspace_path_list_and_label(
 146    workspace: &Entity<Workspace>,
 147    cx: &App,
 148) -> (PathList, SharedString) {
 149    let workspace_ref = workspace.read(cx);
 150    let mut paths = Vec::new();
 151    let mut names = Vec::new();
 152
 153    for worktree in workspace_ref.worktrees(cx) {
 154        let worktree_ref = worktree.read(cx);
 155        if !worktree_ref.is_visible() {
 156            continue;
 157        }
 158        let abs_path = worktree_ref.abs_path();
 159        paths.push(abs_path.to_path_buf());
 160        if let Some(name) = abs_path.file_name() {
 161            names.push(name.to_string_lossy().to_string());
 162        }
 163    }
 164
 165    let label: SharedString = if names.is_empty() {
 166        // TODO: Can we do something better in this case?
 167        "Empty Workspace".into()
 168    } else {
 169        names.join(", ").into()
 170    };
 171
 172    (PathList::new(&paths), label)
 173}
 174
 175pub struct Sidebar {
 176    multi_workspace: WeakEntity<MultiWorkspace>,
 177    width: Pixels,
 178    focus_handle: FocusHandle,
 179    filter_editor: Entity<Editor>,
 180    list_state: ListState,
 181    contents: SidebarContents,
 182    /// The index of the list item that currently has the keyboard focus
 183    ///
 184    /// Note: This is NOT the same as the active item.
 185    selection: Option<usize>,
 186    focused_thread: Option<acp::SessionId>,
 187    active_entry_index: Option<usize>,
 188    collapsed_groups: HashSet<PathList>,
 189    expanded_groups: HashMap<PathList, usize>,
 190    recent_projects_popover_handle: PopoverMenuHandle<RecentProjects>,
 191}
 192
 193impl EventEmitter<SidebarEvent> for Sidebar {}
 194
 195impl Sidebar {
 196    pub fn new(
 197        multi_workspace: Entity<MultiWorkspace>,
 198        window: &mut Window,
 199        cx: &mut Context<Self>,
 200    ) -> Self {
 201        let focus_handle = cx.focus_handle();
 202        cx.on_focus_in(&focus_handle, window, Self::focus_in)
 203            .detach();
 204
 205        let filter_editor = cx.new(|cx| {
 206            let mut editor = Editor::single_line(window, cx);
 207            editor.set_placeholder_text("Search…", window, cx);
 208            editor
 209        });
 210
 211        cx.subscribe_in(
 212            &multi_workspace,
 213            window,
 214            |this, _multi_workspace, event: &MultiWorkspaceEvent, window, cx| match event {
 215                MultiWorkspaceEvent::ActiveWorkspaceChanged => {
 216                    this.focused_thread = None;
 217                    this.update_entries(cx);
 218                }
 219                MultiWorkspaceEvent::WorkspaceAdded(workspace) => {
 220                    this.subscribe_to_workspace(workspace, window, cx);
 221                    this.update_entries(cx);
 222                }
 223                MultiWorkspaceEvent::WorkspaceRemoved(_) => {
 224                    this.update_entries(cx);
 225                }
 226            },
 227        )
 228        .detach();
 229
 230        cx.subscribe(&filter_editor, |this: &mut Self, _, event, cx| {
 231            if let editor::EditorEvent::BufferEdited = event {
 232                let query = this.filter_editor.read(cx).text(cx);
 233                if !query.is_empty() {
 234                    this.selection.take();
 235                }
 236                this.update_entries(cx);
 237                if !query.is_empty() {
 238                    this.selection = this
 239                        .contents
 240                        .entries
 241                        .iter()
 242                        .position(|entry| matches!(entry, ListEntry::Thread(_)))
 243                        .or_else(|| {
 244                            if this.contents.entries.is_empty() {
 245                                None
 246                            } else {
 247                                Some(0)
 248                            }
 249                        });
 250                }
 251            }
 252        })
 253        .detach();
 254
 255        let thread_store = ThreadStore::global(cx);
 256        cx.observe_in(&thread_store, window, |this, _, _window, cx| {
 257            this.update_entries(cx);
 258        })
 259        .detach();
 260
 261        cx.observe_flag::<AgentV2FeatureFlag, _>(window, |_is_enabled, this, _window, cx| {
 262            this.update_entries(cx);
 263        })
 264        .detach();
 265
 266        let workspaces = multi_workspace.read(cx).workspaces().to_vec();
 267        cx.defer_in(window, move |this, window, cx| {
 268            for workspace in &workspaces {
 269                this.subscribe_to_workspace(workspace, window, cx);
 270            }
 271            this.update_entries(cx);
 272        });
 273
 274        Self {
 275            multi_workspace: multi_workspace.downgrade(),
 276            width: DEFAULT_WIDTH,
 277            focus_handle,
 278            filter_editor,
 279            list_state: ListState::new(0, gpui::ListAlignment::Top, px(1000.)),
 280            contents: SidebarContents::default(),
 281            selection: None,
 282            focused_thread: None,
 283            active_entry_index: None,
 284            collapsed_groups: HashSet::new(),
 285            expanded_groups: HashMap::new(),
 286            recent_projects_popover_handle: PopoverMenuHandle::default(),
 287        }
 288    }
 289
 290    fn subscribe_to_workspace(
 291        &self,
 292        workspace: &Entity<Workspace>,
 293        window: &mut Window,
 294        cx: &mut Context<Self>,
 295    ) {
 296        let project = workspace.read(cx).project().clone();
 297        cx.subscribe_in(
 298            &project,
 299            window,
 300            |this, _project, event, _window, cx| match event {
 301                ProjectEvent::WorktreeAdded(_)
 302                | ProjectEvent::WorktreeRemoved(_)
 303                | ProjectEvent::WorktreeOrderChanged => {
 304                    this.update_entries(cx);
 305                }
 306                _ => {}
 307            },
 308        )
 309        .detach();
 310
 311        cx.subscribe_in(
 312            workspace,
 313            window,
 314            |this, _workspace, event: &workspace::Event, window, cx| {
 315                if let workspace::Event::PanelAdded(view) = event {
 316                    if let Ok(agent_panel) = view.clone().downcast::<AgentPanel>() {
 317                        this.subscribe_to_agent_panel(&agent_panel, window, cx);
 318                    }
 319                }
 320            },
 321        )
 322        .detach();
 323
 324        if let Some(agent_panel) = workspace.read(cx).panel::<AgentPanel>(cx) {
 325            self.subscribe_to_agent_panel(&agent_panel, window, cx);
 326        }
 327    }
 328
 329    fn subscribe_to_agent_panel(
 330        &self,
 331        agent_panel: &Entity<AgentPanel>,
 332        window: &mut Window,
 333        cx: &mut Context<Self>,
 334    ) {
 335        cx.subscribe_in(
 336            agent_panel,
 337            window,
 338            |this, agent_panel, event: &AgentPanelEvent, _window, cx| match event {
 339                AgentPanelEvent::ActiveViewChanged => {
 340                    match agent_panel.read(cx).active_connection_view() {
 341                        Some(thread) => {
 342                            if let Some(session_id) = thread.read(cx).parent_id(cx) {
 343                                this.focused_thread = Some(session_id);
 344                            }
 345                        }
 346                        None => {
 347                            this.focused_thread = None;
 348                        }
 349                    }
 350                    this.update_entries(cx);
 351                }
 352                AgentPanelEvent::ThreadFocused => {
 353                    let new_focused = agent_panel
 354                        .read(cx)
 355                        .active_connection_view()
 356                        .and_then(|thread| thread.read(cx).parent_id(cx));
 357                    if new_focused.is_some() && new_focused != this.focused_thread {
 358                        this.focused_thread = new_focused;
 359                        this.update_entries(cx);
 360                    }
 361                }
 362                AgentPanelEvent::BackgroundThreadChanged => {
 363                    this.update_entries(cx);
 364                }
 365            },
 366        )
 367        .detach();
 368    }
 369
 370    fn all_thread_infos_for_workspace(
 371        workspace: &Entity<Workspace>,
 372        cx: &App,
 373    ) -> Vec<ActiveThreadInfo> {
 374        let Some(agent_panel) = workspace.read(cx).panel::<AgentPanel>(cx) else {
 375            return Vec::new();
 376        };
 377        let agent_panel_ref = agent_panel.read(cx);
 378
 379        agent_panel_ref
 380            .parent_threads(cx)
 381            .into_iter()
 382            .map(|thread_view| {
 383                let thread_view_ref = thread_view.read(cx);
 384                let thread = thread_view_ref.thread.read(cx);
 385
 386                let icon = thread_view_ref.agent_icon;
 387                let icon_from_external_svg = thread_view_ref.agent_icon_from_external_svg.clone();
 388                let title = thread.title();
 389                let session_id = thread.session_id().clone();
 390                let is_background = agent_panel_ref.is_background_thread(&session_id);
 391
 392                let status = if thread.is_waiting_for_confirmation() {
 393                    AgentThreadStatus::WaitingForConfirmation
 394                } else if thread.had_error() {
 395                    AgentThreadStatus::Error
 396                } else {
 397                    match thread.status() {
 398                        ThreadStatus::Generating => AgentThreadStatus::Running,
 399                        ThreadStatus::Idle => AgentThreadStatus::Completed,
 400                    }
 401                };
 402
 403                ActiveThreadInfo {
 404                    session_id,
 405                    title,
 406                    status,
 407                    icon,
 408                    icon_from_external_svg,
 409                    is_background,
 410                }
 411            })
 412            .collect()
 413    }
 414
 415    fn rebuild_contents(&mut self, cx: &App) {
 416        let Some(multi_workspace) = self.multi_workspace.upgrade() else {
 417            return;
 418        };
 419        let mw = multi_workspace.read(cx);
 420        let workspaces = mw.workspaces().to_vec();
 421        let active_workspace = mw.workspaces().get(mw.active_workspace_index()).cloned();
 422
 423        let thread_store = ThreadStore::try_global(cx);
 424        let query = self.filter_editor.read(cx).text(cx);
 425
 426        let previous = mem::take(&mut self.contents);
 427
 428        let old_statuses: HashMap<acp::SessionId, AgentThreadStatus> = previous
 429            .entries
 430            .iter()
 431            .filter_map(|entry| match entry {
 432                ListEntry::Thread(thread) if thread.is_live => {
 433                    Some((thread.session_info.session_id.clone(), thread.status))
 434                }
 435                _ => None,
 436            })
 437            .collect();
 438
 439        let mut entries = Vec::new();
 440        let mut notified_threads = previous.notified_threads;
 441        // Track all session IDs we add to entries so we can prune stale
 442        // notifications without a separate pass at the end.
 443        let mut current_session_ids: HashSet<acp::SessionId> = HashSet::new();
 444        // Compute active_entry_index inline during the build pass.
 445        let mut active_entry_index: Option<usize> = None;
 446
 447        for workspace in workspaces.iter() {
 448            let (path_list, label) = workspace_path_list_and_label(workspace, cx);
 449
 450            let is_collapsed = self.collapsed_groups.contains(&path_list);
 451            let should_load_threads = !is_collapsed || !query.is_empty();
 452
 453            let mut threads: Vec<ThreadEntry> = Vec::new();
 454
 455            if should_load_threads {
 456                if let Some(ref thread_store) = thread_store {
 457                    for meta in thread_store.read(cx).threads_for_paths(&path_list) {
 458                        threads.push(ThreadEntry {
 459                            session_info: meta.into(),
 460                            icon: IconName::ZedAgent,
 461                            icon_from_external_svg: None,
 462                            status: AgentThreadStatus::default(),
 463                            workspace: workspace.clone(),
 464                            is_live: false,
 465                            is_background: false,
 466                            highlight_positions: Vec::new(),
 467                        });
 468                    }
 469                }
 470
 471                let live_infos = Self::all_thread_infos_for_workspace(workspace, cx);
 472
 473                if !live_infos.is_empty() {
 474                    let thread_index_by_session: HashMap<acp::SessionId, usize> = threads
 475                        .iter()
 476                        .enumerate()
 477                        .map(|(i, t)| (t.session_info.session_id.clone(), i))
 478                        .collect();
 479
 480                    for info in &live_infos {
 481                        let Some(&idx) = thread_index_by_session.get(&info.session_id) else {
 482                            continue;
 483                        };
 484
 485                        let thread = &mut threads[idx];
 486                        thread.session_info.title = Some(info.title.clone());
 487                        thread.status = info.status;
 488                        thread.icon = info.icon;
 489                        thread.icon_from_external_svg = info.icon_from_external_svg.clone();
 490                        thread.is_live = true;
 491                        thread.is_background = info.is_background;
 492                    }
 493                }
 494
 495                // Update notification state for live threads in the same pass.
 496                let is_active_workspace = active_workspace
 497                    .as_ref()
 498                    .is_some_and(|active| active == workspace);
 499
 500                for thread in &threads {
 501                    let session_id = &thread.session_info.session_id;
 502                    if thread.is_background && thread.status == AgentThreadStatus::Completed {
 503                        notified_threads.insert(session_id.clone());
 504                    } else if thread.status == AgentThreadStatus::Completed
 505                        && !is_active_workspace
 506                        && old_statuses.get(session_id) == Some(&AgentThreadStatus::Running)
 507                    {
 508                        notified_threads.insert(session_id.clone());
 509                    }
 510
 511                    if is_active_workspace && !thread.is_background {
 512                        notified_threads.remove(session_id);
 513                    }
 514                }
 515
 516                // Sort by created_at (newest first), falling back to updated_at
 517                // for threads without a created_at (e.g., ACP sessions).
 518                threads.sort_by(|a, b| {
 519                    let a_time = a.session_info.created_at.or(a.session_info.updated_at);
 520                    let b_time = b.session_info.created_at.or(b.session_info.updated_at);
 521                    b_time.cmp(&a_time)
 522                });
 523            }
 524
 525            if !query.is_empty() {
 526                let has_threads = !threads.is_empty();
 527
 528                let workspace_highlight_positions =
 529                    fuzzy_match_positions(&query, &label).unwrap_or_default();
 530                let workspace_matched = !workspace_highlight_positions.is_empty();
 531
 532                let mut matched_threads: Vec<ThreadEntry> = Vec::new();
 533                for mut thread in threads {
 534                    let title = thread
 535                        .session_info
 536                        .title
 537                        .as_ref()
 538                        .map(|s| s.as_ref())
 539                        .unwrap_or("");
 540                    if let Some(positions) = fuzzy_match_positions(&query, title) {
 541                        thread.highlight_positions = positions;
 542                    }
 543                    if workspace_matched || !thread.highlight_positions.is_empty() {
 544                        matched_threads.push(thread);
 545                    }
 546                }
 547
 548                if matched_threads.is_empty() && !workspace_matched {
 549                    continue;
 550                }
 551
 552                if active_entry_index.is_none()
 553                    && self.focused_thread.is_none()
 554                    && active_workspace
 555                        .as_ref()
 556                        .is_some_and(|active| active == workspace)
 557                {
 558                    active_entry_index = Some(entries.len());
 559                }
 560
 561                entries.push(ListEntry::ProjectHeader {
 562                    path_list: path_list.clone(),
 563                    label,
 564                    workspace: workspace.clone(),
 565                    highlight_positions: workspace_highlight_positions,
 566                    has_threads,
 567                });
 568
 569                // Track session IDs and compute active_entry_index as we add
 570                // thread entries.
 571                for thread in matched_threads {
 572                    current_session_ids.insert(thread.session_info.session_id.clone());
 573                    if active_entry_index.is_none() {
 574                        if let Some(focused) = &self.focused_thread {
 575                            if &thread.session_info.session_id == focused {
 576                                active_entry_index = Some(entries.len());
 577                            }
 578                        }
 579                    }
 580                    entries.push(thread.into());
 581                }
 582            } else {
 583                let has_threads = !threads.is_empty();
 584
 585                // Check if this header is the active entry before pushing it.
 586                if active_entry_index.is_none()
 587                    && self.focused_thread.is_none()
 588                    && active_workspace
 589                        .as_ref()
 590                        .is_some_and(|active| active == workspace)
 591                {
 592                    active_entry_index = Some(entries.len());
 593                }
 594
 595                entries.push(ListEntry::ProjectHeader {
 596                    path_list: path_list.clone(),
 597                    label,
 598                    workspace: workspace.clone(),
 599                    highlight_positions: Vec::new(),
 600                    has_threads,
 601                });
 602
 603                if is_collapsed {
 604                    continue;
 605                }
 606
 607                let total = threads.len();
 608
 609                let extra_batches = self.expanded_groups.get(&path_list).copied().unwrap_or(0);
 610                let threads_to_show =
 611                    DEFAULT_THREADS_SHOWN + (extra_batches * DEFAULT_THREADS_SHOWN);
 612                let count = threads_to_show.min(total);
 613                let is_fully_expanded = count >= total;
 614
 615                // Track session IDs and compute active_entry_index as we add
 616                // thread entries.
 617                for thread in threads.into_iter().take(count) {
 618                    current_session_ids.insert(thread.session_info.session_id.clone());
 619                    if active_entry_index.is_none() {
 620                        if let Some(focused) = &self.focused_thread {
 621                            if &thread.session_info.session_id == focused {
 622                                active_entry_index = Some(entries.len());
 623                            }
 624                        }
 625                    }
 626                    entries.push(thread.into());
 627                }
 628
 629                if total > DEFAULT_THREADS_SHOWN {
 630                    entries.push(ListEntry::ViewMore {
 631                        path_list: path_list.clone(),
 632                        remaining_count: total.saturating_sub(count),
 633                        is_fully_expanded,
 634                    });
 635                }
 636
 637                if total == 0 {
 638                    entries.push(ListEntry::NewThread {
 639                        path_list: path_list.clone(),
 640                        workspace: workspace.clone(),
 641                    });
 642                }
 643            }
 644        }
 645
 646        // Prune stale notifications using the session IDs we collected during
 647        // the build pass (no extra scan needed).
 648        notified_threads.retain(|id| current_session_ids.contains(id));
 649
 650        self.active_entry_index = active_entry_index;
 651        self.contents = SidebarContents {
 652            entries,
 653            notified_threads,
 654        };
 655    }
 656
 657    fn update_entries(&mut self, cx: &mut Context<Self>) {
 658        let Some(multi_workspace) = self.multi_workspace.upgrade() else {
 659            return;
 660        };
 661        if !multi_workspace.read(cx).multi_workspace_enabled(cx) {
 662            return;
 663        }
 664
 665        let had_notifications = self.has_notifications(cx);
 666
 667        let scroll_position = self.list_state.logical_scroll_top();
 668
 669        self.rebuild_contents(cx);
 670
 671        self.list_state.reset(self.contents.entries.len());
 672        self.list_state.scroll_to(scroll_position);
 673
 674        if had_notifications != self.has_notifications(cx) {
 675            multi_workspace.update(cx, |_, cx| {
 676                cx.notify();
 677            });
 678        }
 679
 680        cx.notify();
 681    }
 682
 683    fn render_list_entry(
 684        &mut self,
 685        ix: usize,
 686        window: &mut Window,
 687        cx: &mut Context<Self>,
 688    ) -> AnyElement {
 689        let Some(entry) = self.contents.entries.get(ix) else {
 690            return div().into_any_element();
 691        };
 692        let is_focused = self.focus_handle.is_focused(window)
 693            || self.filter_editor.focus_handle(cx).is_focused(window);
 694        // is_selected means the keyboard selector is here.
 695        let is_selected = is_focused && self.selection == Some(ix);
 696
 697        let is_group_header_after_first =
 698            ix > 0 && matches!(entry, ListEntry::ProjectHeader { .. });
 699
 700        let rendered = match entry {
 701            ListEntry::ProjectHeader {
 702                path_list,
 703                label,
 704                workspace,
 705                highlight_positions,
 706                has_threads,
 707            } => self.render_project_header(
 708                ix,
 709                path_list,
 710                label,
 711                workspace,
 712                highlight_positions,
 713                *has_threads,
 714                is_selected,
 715                cx,
 716            ),
 717            ListEntry::Thread(thread) => self.render_thread(ix, thread, is_selected, cx),
 718            ListEntry::ViewMore {
 719                path_list,
 720                remaining_count,
 721                is_fully_expanded,
 722            } => self.render_view_more(
 723                ix,
 724                path_list,
 725                *remaining_count,
 726                *is_fully_expanded,
 727                is_selected,
 728                cx,
 729            ),
 730            ListEntry::NewThread {
 731                path_list,
 732                workspace,
 733            } => self.render_new_thread(ix, path_list, workspace, is_selected, cx),
 734        };
 735
 736        if is_group_header_after_first {
 737            v_flex()
 738                .w_full()
 739                .border_t_1()
 740                .border_color(cx.theme().colors().border_variant)
 741                .child(rendered)
 742                .into_any_element()
 743        } else {
 744            rendered
 745        }
 746    }
 747
 748    fn render_project_header(
 749        &self,
 750        ix: usize,
 751        path_list: &PathList,
 752        label: &SharedString,
 753        workspace: &Entity<Workspace>,
 754        highlight_positions: &[usize],
 755        has_threads: bool,
 756        is_selected: bool,
 757        cx: &mut Context<Self>,
 758    ) -> AnyElement {
 759        let id = SharedString::from(format!("project-header-{}", ix));
 760        let group_name = SharedString::from(format!("header-group-{}", ix));
 761        let ib_id = SharedString::from(format!("project-header-new-thread-{}", ix));
 762
 763        let is_collapsed = self.collapsed_groups.contains(path_list);
 764        let disclosure_icon = if is_collapsed {
 765            IconName::ChevronRight
 766        } else {
 767            IconName::ChevronDown
 768        };
 769        let workspace_for_new_thread = workspace.clone();
 770        let workspace_for_remove = workspace.clone();
 771        // let workspace_for_activate = workspace.clone();
 772
 773        let path_list_for_toggle = path_list.clone();
 774        let path_list_for_collapse = path_list.clone();
 775        let view_more_expanded = self.expanded_groups.contains_key(path_list);
 776
 777        let multi_workspace = self.multi_workspace.upgrade();
 778        let workspace_count = multi_workspace
 779            .as_ref()
 780            .map_or(0, |mw| mw.read(cx).workspaces().len());
 781        let is_active_workspace = self.focused_thread.is_none()
 782            && multi_workspace
 783                .as_ref()
 784                .is_some_and(|mw| mw.read(cx).workspace() == workspace);
 785
 786        let label = if highlight_positions.is_empty() {
 787            Label::new(label.clone())
 788                .size(LabelSize::Small)
 789                .color(Color::Muted)
 790                .into_any_element()
 791        } else {
 792            HighlightedLabel::new(label.clone(), highlight_positions.to_vec())
 793                .size(LabelSize::Small)
 794                .color(Color::Muted)
 795                .into_any_element()
 796        };
 797
 798        let color = cx.theme().colors();
 799        let base_bg = if is_active_workspace {
 800            color.ghost_element_selected
 801        } else {
 802            color.panel_background
 803        };
 804        let gradient_overlay =
 805            GradientFade::new(base_bg, color.element_hover, color.element_active)
 806                .width(px(48.0))
 807                .group_name(group_name.clone());
 808
 809        ListItem::new(id)
 810            .group_name(group_name)
 811            .toggle_state(is_active_workspace)
 812            .focused(is_selected)
 813            .child(
 814                h_flex()
 815                    .relative()
 816                    .min_w_0()
 817                    .w_full()
 818                    .p_1()
 819                    .gap_1p5()
 820                    .child(
 821                        Icon::new(disclosure_icon)
 822                            .size(IconSize::Small)
 823                            .color(Color::Custom(cx.theme().colors().icon_muted.opacity(0.6))),
 824                    )
 825                    .child(label)
 826                    .child(gradient_overlay),
 827            )
 828            .end_hover_slot(
 829                h_flex()
 830                    .when(workspace_count > 1, |this| {
 831                        this.child(
 832                            IconButton::new(
 833                                SharedString::from(format!("project-header-remove-{}", ix)),
 834                                IconName::Close,
 835                            )
 836                            .icon_size(IconSize::Small)
 837                            .icon_color(Color::Muted)
 838                            .tooltip(Tooltip::text("Remove Project"))
 839                            .on_click(cx.listener(
 840                                move |this, _, window, cx| {
 841                                    this.remove_workspace(&workspace_for_remove, window, cx);
 842                                },
 843                            )),
 844                        )
 845                    })
 846                    .when(view_more_expanded && !is_collapsed, |this| {
 847                        this.child(
 848                            IconButton::new(
 849                                SharedString::from(format!("project-header-collapse-{}", ix)),
 850                                IconName::ListCollapse,
 851                            )
 852                            .icon_size(IconSize::Small)
 853                            .icon_color(Color::Muted)
 854                            .tooltip(Tooltip::text("Collapse Displayed Threads"))
 855                            .on_click(cx.listener({
 856                                let path_list_for_collapse = path_list_for_collapse.clone();
 857                                move |this, _, _window, cx| {
 858                                    this.selection = None;
 859                                    this.expanded_groups.remove(&path_list_for_collapse);
 860                                    this.update_entries(cx);
 861                                }
 862                            })),
 863                        )
 864                    })
 865                    .when(has_threads, |this| {
 866                        this.child(
 867                            IconButton::new(ib_id, IconName::NewThread)
 868                                .icon_size(IconSize::Small)
 869                                .icon_color(Color::Muted)
 870                                .tooltip(Tooltip::text("New Thread"))
 871                                .on_click(cx.listener(move |this, _, window, cx| {
 872                                    this.selection = None;
 873                                    this.create_new_thread(&workspace_for_new_thread, window, cx);
 874                                })),
 875                        )
 876                    }),
 877            )
 878            .on_click(cx.listener(move |this, _, window, cx| {
 879                this.selection = None;
 880                this.toggle_collapse(&path_list_for_toggle, window, cx);
 881            }))
 882            // TODO: Decide if we really want the header to be activating different workspaces
 883            // .on_click(cx.listener(move |this, _, window, cx| {
 884            //     this.selection = None;
 885            //     this.activate_workspace(&workspace_for_activate, window, cx);
 886            // }))
 887            .into_any_element()
 888    }
 889
 890    fn activate_workspace(
 891        &mut self,
 892        workspace: &Entity<Workspace>,
 893        window: &mut Window,
 894        cx: &mut Context<Self>,
 895    ) {
 896        let Some(multi_workspace) = self.multi_workspace.upgrade() else {
 897            return;
 898        };
 899
 900        self.focused_thread = None;
 901
 902        multi_workspace.update(cx, |multi_workspace, cx| {
 903            multi_workspace.activate(workspace.clone(), cx);
 904        });
 905
 906        multi_workspace.update(cx, |multi_workspace, cx| {
 907            multi_workspace.focus_active_workspace(window, cx);
 908        });
 909    }
 910
 911    fn remove_workspace(
 912        &mut self,
 913        workspace: &Entity<Workspace>,
 914        window: &mut Window,
 915        cx: &mut Context<Self>,
 916    ) {
 917        let Some(multi_workspace) = self.multi_workspace.upgrade() else {
 918            return;
 919        };
 920
 921        multi_workspace.update(cx, |multi_workspace, cx| {
 922            let Some(index) = multi_workspace
 923                .workspaces()
 924                .iter()
 925                .position(|w| w == workspace)
 926            else {
 927                return;
 928            };
 929            multi_workspace.remove_workspace(index, window, cx);
 930        });
 931    }
 932
 933    fn toggle_collapse(
 934        &mut self,
 935        path_list: &PathList,
 936        _window: &mut Window,
 937        cx: &mut Context<Self>,
 938    ) {
 939        if self.collapsed_groups.contains(path_list) {
 940            self.collapsed_groups.remove(path_list);
 941        } else {
 942            self.collapsed_groups.insert(path_list.clone());
 943        }
 944        self.update_entries(cx);
 945    }
 946
 947    fn focus_in(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {}
 948
 949    fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 950        if self.reset_filter_editor_text(window, cx) {
 951            self.update_entries(cx);
 952        } else {
 953            self.focus_handle.focus(window, cx);
 954        }
 955    }
 956
 957    fn reset_filter_editor_text(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 958        self.filter_editor.update(cx, |editor, cx| {
 959            if editor.buffer().read(cx).len(cx).0 > 0 {
 960                editor.set_text("", window, cx);
 961                true
 962            } else {
 963                false
 964            }
 965        })
 966    }
 967
 968    fn has_filter_query(&self, cx: &App) -> bool {
 969        self.filter_editor.read(cx).buffer().read(cx).is_empty()
 970    }
 971
 972    fn editor_move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 973        self.select_next(&SelectNext, window, cx);
 974    }
 975
 976    fn editor_move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 977        self.select_previous(&SelectPrevious, window, cx);
 978    }
 979
 980    fn select_next(&mut self, _: &SelectNext, _window: &mut Window, cx: &mut Context<Self>) {
 981        let next = match self.selection {
 982            Some(ix) if ix + 1 < self.contents.entries.len() => ix + 1,
 983            None if !self.contents.entries.is_empty() => 0,
 984            _ => return,
 985        };
 986        self.selection = Some(next);
 987        self.list_state.scroll_to_reveal_item(next);
 988        cx.notify();
 989    }
 990
 991    fn select_previous(
 992        &mut self,
 993        _: &SelectPrevious,
 994        _window: &mut Window,
 995        cx: &mut Context<Self>,
 996    ) {
 997        let prev = match self.selection {
 998            Some(ix) if ix > 0 => ix - 1,
 999            None if !self.contents.entries.is_empty() => self.contents.entries.len() - 1,
1000            _ => return,
1001        };
1002        self.selection = Some(prev);
1003        self.list_state.scroll_to_reveal_item(prev);
1004        cx.notify();
1005    }
1006
1007    fn select_first(&mut self, _: &SelectFirst, _window: &mut Window, cx: &mut Context<Self>) {
1008        if !self.contents.entries.is_empty() {
1009            self.selection = Some(0);
1010            self.list_state.scroll_to_reveal_item(0);
1011            cx.notify();
1012        }
1013    }
1014
1015    fn select_last(&mut self, _: &SelectLast, _window: &mut Window, cx: &mut Context<Self>) {
1016        if let Some(last) = self.contents.entries.len().checked_sub(1) {
1017            self.selection = Some(last);
1018            self.list_state.scroll_to_reveal_item(last);
1019            cx.notify();
1020        }
1021    }
1022
1023    fn confirm(&mut self, _: &Confirm, window: &mut Window, cx: &mut Context<Self>) {
1024        let Some(ix) = self.selection else { return };
1025        let Some(entry) = self.contents.entries.get(ix) else {
1026            return;
1027        };
1028
1029        match entry {
1030            ListEntry::ProjectHeader { workspace, .. } => {
1031                let workspace = workspace.clone();
1032                self.activate_workspace(&workspace, window, cx);
1033            }
1034            ListEntry::Thread(thread) => {
1035                let session_info = thread.session_info.clone();
1036                let workspace = thread.workspace.clone();
1037                self.activate_thread(session_info, &workspace, window, cx);
1038            }
1039            ListEntry::ViewMore {
1040                path_list,
1041                is_fully_expanded,
1042                ..
1043            } => {
1044                let path_list = path_list.clone();
1045                if *is_fully_expanded {
1046                    self.expanded_groups.remove(&path_list);
1047                } else {
1048                    let current = self.expanded_groups.get(&path_list).copied().unwrap_or(0);
1049                    self.expanded_groups.insert(path_list, current + 1);
1050                }
1051                self.update_entries(cx);
1052            }
1053            ListEntry::NewThread { workspace, .. } => {
1054                let workspace = workspace.clone();
1055                self.create_new_thread(&workspace, window, cx);
1056            }
1057        }
1058    }
1059
1060    fn activate_thread(
1061        &mut self,
1062        session_info: acp_thread::AgentSessionInfo,
1063        workspace: &Entity<Workspace>,
1064        window: &mut Window,
1065        cx: &mut Context<Self>,
1066    ) {
1067        let Some(multi_workspace) = self.multi_workspace.upgrade() else {
1068            return;
1069        };
1070
1071        multi_workspace.update(cx, |multi_workspace, cx| {
1072            multi_workspace.activate(workspace.clone(), cx);
1073        });
1074
1075        workspace.update(cx, |workspace, cx| {
1076            workspace.open_panel::<AgentPanel>(window, cx);
1077        });
1078
1079        if let Some(agent_panel) = workspace.read(cx).panel::<AgentPanel>(cx) {
1080            agent_panel.update(cx, |panel, cx| {
1081                panel.load_agent_thread(
1082                    session_info.session_id,
1083                    session_info.cwd,
1084                    session_info.title,
1085                    window,
1086                    cx,
1087                );
1088            });
1089        }
1090    }
1091
1092    fn expand_selected_entry(
1093        &mut self,
1094        _: &ExpandSelectedEntry,
1095        _window: &mut Window,
1096        cx: &mut Context<Self>,
1097    ) {
1098        let Some(ix) = self.selection else { return };
1099
1100        match self.contents.entries.get(ix) {
1101            Some(ListEntry::ProjectHeader { path_list, .. }) => {
1102                if self.collapsed_groups.contains(path_list) {
1103                    let path_list = path_list.clone();
1104                    self.collapsed_groups.remove(&path_list);
1105                    self.update_entries(cx);
1106                } else if ix + 1 < self.contents.entries.len() {
1107                    self.selection = Some(ix + 1);
1108                    self.list_state.scroll_to_reveal_item(ix + 1);
1109                    cx.notify();
1110                }
1111            }
1112            _ => {}
1113        }
1114    }
1115
1116    fn collapse_selected_entry(
1117        &mut self,
1118        _: &CollapseSelectedEntry,
1119        _window: &mut Window,
1120        cx: &mut Context<Self>,
1121    ) {
1122        let Some(ix) = self.selection else { return };
1123
1124        match self.contents.entries.get(ix) {
1125            Some(ListEntry::ProjectHeader { path_list, .. }) => {
1126                if !self.collapsed_groups.contains(path_list) {
1127                    let path_list = path_list.clone();
1128                    self.collapsed_groups.insert(path_list);
1129                    self.update_entries(cx);
1130                }
1131            }
1132            Some(
1133                ListEntry::Thread(_) | ListEntry::ViewMore { .. } | ListEntry::NewThread { .. },
1134            ) => {
1135                for i in (0..ix).rev() {
1136                    if let Some(ListEntry::ProjectHeader { path_list, .. }) =
1137                        self.contents.entries.get(i)
1138                    {
1139                        let path_list = path_list.clone();
1140                        self.selection = Some(i);
1141                        self.collapsed_groups.insert(path_list);
1142                        self.update_entries(cx);
1143                        break;
1144                    }
1145                }
1146            }
1147            None => {}
1148        }
1149    }
1150
1151    fn render_thread(
1152        &self,
1153        ix: usize,
1154        thread: &ThreadEntry,
1155        is_selected: bool,
1156        cx: &mut Context<Self>,
1157    ) -> AnyElement {
1158        let has_notification = self
1159            .contents
1160            .is_thread_notified(&thread.session_info.session_id);
1161
1162        let title: SharedString = thread
1163            .session_info
1164            .title
1165            .clone()
1166            .unwrap_or_else(|| "Untitled".into());
1167        let session_info = thread.session_info.clone();
1168        let workspace = thread.workspace.clone();
1169
1170        let id = SharedString::from(format!("thread-entry-{}", ix));
1171        ThreadItem::new(id, title)
1172            .icon(thread.icon)
1173            .when_some(thread.icon_from_external_svg.clone(), |this, svg| {
1174                this.custom_icon_from_external_svg(svg)
1175            })
1176            .highlight_positions(thread.highlight_positions.to_vec())
1177            .status(thread.status)
1178            .notified(has_notification)
1179            .selected(self.focused_thread.as_ref() == Some(&session_info.session_id))
1180            .focused(is_selected)
1181            .on_click(cx.listener(move |this, _, window, cx| {
1182                this.selection = None;
1183                this.activate_thread(session_info.clone(), &workspace, window, cx);
1184            }))
1185            .into_any_element()
1186    }
1187
1188    fn render_recent_projects_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
1189        let workspace = self
1190            .multi_workspace
1191            .upgrade()
1192            .map(|mw| mw.read(cx).workspace().downgrade());
1193
1194        let focus_handle = workspace
1195            .as_ref()
1196            .and_then(|ws| ws.upgrade())
1197            .map(|w| w.read(cx).focus_handle(cx))
1198            .unwrap_or_else(|| cx.focus_handle());
1199
1200        let popover_handle = self.recent_projects_popover_handle.clone();
1201
1202        PopoverMenu::new("sidebar-recent-projects-menu")
1203            .with_handle(popover_handle)
1204            .menu(move |window, cx| {
1205                workspace.as_ref().map(|ws| {
1206                    RecentProjects::popover(ws.clone(), false, focus_handle.clone(), window, cx)
1207                })
1208            })
1209            .trigger_with_tooltip(
1210                IconButton::new("open-project", IconName::OpenFolder)
1211                    .icon_size(IconSize::Small)
1212                    .selected_style(ButtonStyle::Tinted(TintColor::Accent)),
1213                |_window, cx| {
1214                    Tooltip::for_action(
1215                        "Recent Projects",
1216                        &OpenRecent {
1217                            create_new_window: false,
1218                        },
1219                        cx,
1220                    )
1221                },
1222            )
1223            .anchor(gpui::Corner::TopLeft)
1224            .offset(gpui::Point {
1225                x: px(0.0),
1226                y: px(2.0),
1227            })
1228    }
1229
1230    fn render_filter_input(&self, cx: &mut Context<Self>) -> impl IntoElement {
1231        let settings = ThemeSettings::get_global(cx);
1232        let text_style = TextStyle {
1233            color: cx.theme().colors().text,
1234            font_family: settings.ui_font.family.clone(),
1235            font_features: settings.ui_font.features.clone(),
1236            font_fallbacks: settings.ui_font.fallbacks.clone(),
1237            font_size: rems(0.875).into(),
1238            font_weight: settings.ui_font.weight,
1239            font_style: FontStyle::Normal,
1240            line_height: relative(1.3),
1241            ..Default::default()
1242        };
1243
1244        EditorElement::new(
1245            &self.filter_editor,
1246            EditorStyle {
1247                local_player: cx.theme().players().local(),
1248                text: text_style,
1249                ..Default::default()
1250            },
1251        )
1252    }
1253
1254    fn render_view_more(
1255        &self,
1256        ix: usize,
1257        path_list: &PathList,
1258        remaining_count: usize,
1259        is_fully_expanded: bool,
1260        is_selected: bool,
1261        cx: &mut Context<Self>,
1262    ) -> AnyElement {
1263        let path_list = path_list.clone();
1264        let id = SharedString::from(format!("view-more-{}", ix));
1265
1266        let (icon, label) = if is_fully_expanded {
1267            (IconName::ListCollapse, "Collapse List")
1268        } else {
1269            (IconName::Plus, "View More")
1270        };
1271
1272        ListItem::new(id)
1273            .focused(is_selected)
1274            .child(
1275                h_flex()
1276                    .p_1()
1277                    .gap_1p5()
1278                    .child(Icon::new(icon).size(IconSize::Small).color(Color::Muted))
1279                    .child(Label::new(label).color(Color::Muted))
1280                    .when(!is_fully_expanded, |this| {
1281                        this.child(
1282                            Label::new(format!("({})", remaining_count))
1283                                .color(Color::Custom(cx.theme().colors().text_muted.opacity(0.5))),
1284                        )
1285                    }),
1286            )
1287            .on_click(cx.listener(move |this, _, _window, cx| {
1288                this.selection = None;
1289                if is_fully_expanded {
1290                    this.expanded_groups.remove(&path_list);
1291                } else {
1292                    let current = this.expanded_groups.get(&path_list).copied().unwrap_or(0);
1293                    this.expanded_groups.insert(path_list.clone(), current + 1);
1294                }
1295                this.update_entries(cx);
1296            }))
1297            .into_any_element()
1298    }
1299
1300    fn create_new_thread(
1301        &mut self,
1302        workspace: &Entity<Workspace>,
1303        window: &mut Window,
1304        cx: &mut Context<Self>,
1305    ) {
1306        let Some(multi_workspace) = self.multi_workspace.upgrade() else {
1307            return;
1308        };
1309
1310        multi_workspace.update(cx, |multi_workspace, cx| {
1311            multi_workspace.activate(workspace.clone(), cx);
1312        });
1313
1314        workspace.update(cx, |workspace, cx| {
1315            if let Some(agent_panel) = workspace.panel::<AgentPanel>(cx) {
1316                agent_panel.update(cx, |panel, cx| {
1317                    panel.new_thread(&NewThread, window, cx);
1318                });
1319            }
1320            workspace.focus_panel::<AgentPanel>(window, cx);
1321        });
1322    }
1323
1324    fn render_new_thread(
1325        &self,
1326        ix: usize,
1327        _path_list: &PathList,
1328        workspace: &Entity<Workspace>,
1329        is_selected: bool,
1330        cx: &mut Context<Self>,
1331    ) -> AnyElement {
1332        let workspace = workspace.clone();
1333
1334        div()
1335            .w_full()
1336            .p_2()
1337            .child(
1338                Button::new(
1339                    SharedString::from(format!("new-thread-btn-{}", ix)),
1340                    "New Thread",
1341                )
1342                .full_width()
1343                .style(ButtonStyle::Outlined)
1344                .icon(IconName::Plus)
1345                .icon_color(Color::Muted)
1346                .icon_size(IconSize::Small)
1347                .icon_position(IconPosition::Start)
1348                .toggle_state(is_selected)
1349                .on_click(cx.listener(move |this, _, window, cx| {
1350                    this.selection = None;
1351                    this.create_new_thread(&workspace, window, cx);
1352                })),
1353            )
1354            .into_any_element()
1355    }
1356}
1357
1358impl WorkspaceSidebar for Sidebar {
1359    fn width(&self, _cx: &App) -> Pixels {
1360        self.width
1361    }
1362
1363    fn set_width(&mut self, width: Option<Pixels>, cx: &mut Context<Self>) {
1364        self.width = width.unwrap_or(DEFAULT_WIDTH).clamp(MIN_WIDTH, MAX_WIDTH);
1365        cx.notify();
1366    }
1367
1368    fn has_notifications(&self, _cx: &App) -> bool {
1369        !self.contents.notified_threads.is_empty()
1370    }
1371
1372    fn toggle_recent_projects_popover(&self, window: &mut Window, cx: &mut App) {
1373        self.recent_projects_popover_handle.toggle(window, cx);
1374    }
1375
1376    fn is_recent_projects_popover_deployed(&self) -> bool {
1377        self.recent_projects_popover_handle.is_deployed()
1378    }
1379}
1380
1381impl Focusable for Sidebar {
1382    fn focus_handle(&self, cx: &App) -> FocusHandle {
1383        self.filter_editor.focus_handle(cx)
1384    }
1385}
1386
1387impl Render for Sidebar {
1388    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1389        let titlebar_height = ui::utils::platform_title_bar_height(window);
1390        let ui_font = theme::setup_ui_font(window, cx);
1391        let is_focused = self.focus_handle.is_focused(window)
1392            || self.filter_editor.focus_handle(cx).is_focused(window);
1393        let has_query = self.has_filter_query(cx);
1394
1395        let focus_tooltip_label = if is_focused {
1396            "Focus Workspace"
1397        } else {
1398            "Focus Sidebar"
1399        };
1400
1401        v_flex()
1402            .id("workspace-sidebar")
1403            .key_context("WorkspaceSidebar")
1404            .track_focus(&self.focus_handle)
1405            .on_action(cx.listener(Self::select_next))
1406            .on_action(cx.listener(Self::select_previous))
1407            .on_action(cx.listener(Self::editor_move_down))
1408            .on_action(cx.listener(Self::editor_move_up))
1409            .on_action(cx.listener(Self::select_first))
1410            .on_action(cx.listener(Self::select_last))
1411            .on_action(cx.listener(Self::confirm))
1412            .on_action(cx.listener(Self::expand_selected_entry))
1413            .on_action(cx.listener(Self::collapse_selected_entry))
1414            .on_action(cx.listener(Self::cancel))
1415            .font(ui_font)
1416            .h_full()
1417            .w(self.width)
1418            .bg(cx.theme().colors().surface_background)
1419            .border_r_1()
1420            .border_color(cx.theme().colors().border)
1421            .child(
1422                h_flex()
1423                    .flex_none()
1424                    .h(titlebar_height)
1425                    .w_full()
1426                    .mt_px()
1427                    .pb_px()
1428                    .pr_1()
1429                    .when_else(
1430                        cfg!(target_os = "macos") && !window.is_fullscreen(),
1431                        |this| this.pl(px(TRAFFIC_LIGHT_PADDING)),
1432                        |this| this.pl_2(),
1433                    )
1434                    .justify_between()
1435                    .border_b_1()
1436                    .border_color(cx.theme().colors().border)
1437                    .child({
1438                        let focus_handle_toggle = self.focus_handle.clone();
1439                        let focus_handle_focus = self.focus_handle.clone();
1440                        IconButton::new("close-sidebar", IconName::WorkspaceNavOpen)
1441                            .icon_size(IconSize::Small)
1442                            .tooltip(Tooltip::element(move |_, cx| {
1443                                v_flex()
1444                                    .gap_1()
1445                                    .child(
1446                                        h_flex()
1447                                            .gap_2()
1448                                            .justify_between()
1449                                            .child(Label::new("Close Sidebar"))
1450                                            .child(KeyBinding::for_action_in(
1451                                                &ToggleWorkspaceSidebar,
1452                                                &focus_handle_toggle,
1453                                                cx,
1454                                            )),
1455                                    )
1456                                    .child(
1457                                        h_flex()
1458                                            .pt_1()
1459                                            .gap_2()
1460                                            .border_t_1()
1461                                            .border_color(cx.theme().colors().border_variant)
1462                                            .justify_between()
1463                                            .child(Label::new(focus_tooltip_label))
1464                                            .child(KeyBinding::for_action_in(
1465                                                &FocusWorkspaceSidebar,
1466                                                &focus_handle_focus,
1467                                                cx,
1468                                            )),
1469                                    )
1470                                    .into_any_element()
1471                            }))
1472                            .on_click(cx.listener(|_this, _, _window, cx| {
1473                                cx.emit(SidebarEvent::Close);
1474                            }))
1475                    })
1476                    .child(self.render_recent_projects_button(cx)),
1477            )
1478            .child(
1479                h_flex()
1480                    .flex_none()
1481                    .px_2p5()
1482                    .h(Tab::container_height(cx))
1483                    .gap_2()
1484                    .border_b_1()
1485                    .border_color(cx.theme().colors().border)
1486                    .child(
1487                        Icon::new(IconName::MagnifyingGlass)
1488                            .size(IconSize::Small)
1489                            .color(Color::Muted),
1490                    )
1491                    .child(self.render_filter_input(cx))
1492                    .when(has_query, |this| {
1493                        this.pr_1().child(
1494                            IconButton::new("clear_filter", IconName::Close)
1495                                .shape(IconButtonShape::Square)
1496                                .tooltip(Tooltip::text("Clear Search"))
1497                                .on_click(cx.listener(|this, _, window, cx| {
1498                                    this.reset_filter_editor_text(window, cx);
1499                                    this.update_entries(cx);
1500                                })),
1501                        )
1502                    }),
1503            )
1504            .child(
1505                v_flex()
1506                    .flex_1()
1507                    .overflow_hidden()
1508                    .child(
1509                        list(
1510                            self.list_state.clone(),
1511                            cx.processor(Self::render_list_entry),
1512                        )
1513                        .flex_1()
1514                        .size_full(),
1515                    )
1516                    .vertical_scrollbar_for(&self.list_state, window, cx),
1517            )
1518    }
1519}
1520
1521#[cfg(test)]
1522mod tests {
1523    use super::*;
1524    use acp_thread::StubAgentConnection;
1525    use agent::ThreadStore;
1526    use agent_ui::test_support::{active_session_id, open_thread_with_connection, send_message};
1527    use assistant_text_thread::TextThreadStore;
1528    use chrono::DateTime;
1529    use feature_flags::FeatureFlagAppExt as _;
1530    use fs::FakeFs;
1531    use gpui::TestAppContext;
1532    use settings::SettingsStore;
1533    use std::sync::Arc;
1534    use util::path_list::PathList;
1535
1536    fn init_test(cx: &mut TestAppContext) {
1537        cx.update(|cx| {
1538            let settings_store = SettingsStore::test(cx);
1539            cx.set_global(settings_store);
1540            theme::init(theme::LoadThemes::JustBase, cx);
1541            editor::init(cx);
1542            cx.update_flags(false, vec!["agent-v2".into()]);
1543            ThreadStore::init_global(cx);
1544        });
1545    }
1546
1547    fn make_test_thread(title: &str, updated_at: DateTime<Utc>) -> agent::DbThread {
1548        agent::DbThread {
1549            title: title.to_string().into(),
1550            messages: Vec::new(),
1551            updated_at,
1552            detailed_summary: None,
1553            initial_project_snapshot: None,
1554            cumulative_token_usage: Default::default(),
1555            request_token_usage: Default::default(),
1556            model: None,
1557            profile: None,
1558            imported: false,
1559            subagent_context: None,
1560            speed: None,
1561            thinking_enabled: false,
1562            thinking_effort: None,
1563            draft_prompt: None,
1564            ui_scroll_position: None,
1565        }
1566    }
1567
1568    async fn init_test_project(
1569        worktree_path: &str,
1570        cx: &mut TestAppContext,
1571    ) -> Entity<project::Project> {
1572        init_test(cx);
1573        let fs = FakeFs::new(cx.executor());
1574        fs.insert_tree(worktree_path, serde_json::json!({ "src": {} }))
1575            .await;
1576        cx.update(|cx| <dyn fs::Fs>::set_global(fs.clone(), cx));
1577        project::Project::test(fs, [worktree_path.as_ref()], cx).await
1578    }
1579
1580    fn setup_sidebar(
1581        multi_workspace: &Entity<MultiWorkspace>,
1582        cx: &mut gpui::VisualTestContext,
1583    ) -> Entity<Sidebar> {
1584        let multi_workspace = multi_workspace.clone();
1585        let sidebar =
1586            cx.update(|window, cx| cx.new(|cx| Sidebar::new(multi_workspace.clone(), window, cx)));
1587        multi_workspace.update_in(cx, |mw, window, cx| {
1588            mw.register_sidebar(sidebar.clone(), window, cx);
1589        });
1590        cx.run_until_parked();
1591        sidebar
1592    }
1593
1594    async fn save_n_test_threads(
1595        count: u32,
1596        path_list: &PathList,
1597        cx: &mut gpui::VisualTestContext,
1598    ) {
1599        let thread_store = cx.update(|_window, cx| ThreadStore::global(cx));
1600        for i in 0..count {
1601            let save_task = thread_store.update(cx, |store, cx| {
1602                store.save_thread(
1603                    acp::SessionId::new(Arc::from(format!("thread-{}", i))),
1604                    make_test_thread(
1605                        &format!("Thread {}", i + 1),
1606                        chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 1, 0, 0, i).unwrap(),
1607                    ),
1608                    path_list.clone(),
1609                    cx,
1610                )
1611            });
1612            save_task.await.unwrap();
1613        }
1614        cx.run_until_parked();
1615    }
1616
1617    async fn save_thread_to_store(
1618        session_id: &acp::SessionId,
1619        path_list: &PathList,
1620        cx: &mut gpui::VisualTestContext,
1621    ) {
1622        let thread_store = cx.update(|_window, cx| ThreadStore::global(cx));
1623        let save_task = thread_store.update(cx, |store, cx| {
1624            store.save_thread(
1625                session_id.clone(),
1626                make_test_thread(
1627                    "Test",
1628                    chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 1, 0, 0, 0).unwrap(),
1629                ),
1630                path_list.clone(),
1631                cx,
1632            )
1633        });
1634        save_task.await.unwrap();
1635        cx.run_until_parked();
1636    }
1637
1638    fn open_and_focus_sidebar(
1639        sidebar: &Entity<Sidebar>,
1640        multi_workspace: &Entity<MultiWorkspace>,
1641        cx: &mut gpui::VisualTestContext,
1642    ) {
1643        multi_workspace.update_in(cx, |mw, window, cx| {
1644            mw.toggle_sidebar(window, cx);
1645        });
1646        cx.run_until_parked();
1647        sidebar.update_in(cx, |_, window, cx| {
1648            cx.focus_self(window);
1649        });
1650        cx.run_until_parked();
1651    }
1652
1653    fn visible_entries_as_strings(
1654        sidebar: &Entity<Sidebar>,
1655        cx: &mut gpui::VisualTestContext,
1656    ) -> Vec<String> {
1657        sidebar.read_with(cx, |sidebar, _cx| {
1658            sidebar
1659                .contents
1660                .entries
1661                .iter()
1662                .enumerate()
1663                .map(|(ix, entry)| {
1664                    let selected = if sidebar.selection == Some(ix) {
1665                        "  <== selected"
1666                    } else {
1667                        ""
1668                    };
1669                    match entry {
1670                        ListEntry::ProjectHeader {
1671                            label,
1672                            path_list,
1673                            highlight_positions: _,
1674                            ..
1675                        } => {
1676                            let icon = if sidebar.collapsed_groups.contains(path_list) {
1677                                ">"
1678                            } else {
1679                                "v"
1680                            };
1681                            format!("{} [{}]{}", icon, label, selected)
1682                        }
1683                        ListEntry::Thread(thread) => {
1684                            let title = thread
1685                                .session_info
1686                                .title
1687                                .as_ref()
1688                                .map(|s| s.as_ref())
1689                                .unwrap_or("Untitled");
1690                            let active = if thread.is_live { " *" } else { "" };
1691                            let status_str = match thread.status {
1692                                AgentThreadStatus::Running => " (running)",
1693                                AgentThreadStatus::Error => " (error)",
1694                                AgentThreadStatus::WaitingForConfirmation => " (waiting)",
1695                                _ => "",
1696                            };
1697                            let notified = if sidebar
1698                                .contents
1699                                .is_thread_notified(&thread.session_info.session_id)
1700                            {
1701                                " (!)"
1702                            } else {
1703                                ""
1704                            };
1705                            format!(
1706                                "  {}{}{}{}{}",
1707                                title, active, status_str, notified, selected
1708                            )
1709                        }
1710                        ListEntry::ViewMore {
1711                            remaining_count,
1712                            is_fully_expanded,
1713                            ..
1714                        } => {
1715                            if *is_fully_expanded {
1716                                format!("  - Collapse{}", selected)
1717                            } else {
1718                                format!("  + View More ({}){}", remaining_count, selected)
1719                            }
1720                        }
1721                        ListEntry::NewThread { .. } => {
1722                            format!("  [+ New Thread]{}", selected)
1723                        }
1724                    }
1725                })
1726                .collect()
1727        })
1728    }
1729
1730    #[gpui::test]
1731    async fn test_single_workspace_no_threads(cx: &mut TestAppContext) {
1732        let project = init_test_project("/my-project", cx).await;
1733        let (multi_workspace, cx) =
1734            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
1735        let sidebar = setup_sidebar(&multi_workspace, cx);
1736
1737        assert_eq!(
1738            visible_entries_as_strings(&sidebar, cx),
1739            vec!["v [my-project]", "  [+ New Thread]"]
1740        );
1741    }
1742
1743    #[gpui::test]
1744    async fn test_single_workspace_with_saved_threads(cx: &mut TestAppContext) {
1745        let project = init_test_project("/my-project", cx).await;
1746        let (multi_workspace, cx) =
1747            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
1748        let sidebar = setup_sidebar(&multi_workspace, cx);
1749
1750        let path_list = PathList::new(&[std::path::PathBuf::from("/my-project")]);
1751        let thread_store = cx.update(|_window, cx| ThreadStore::global(cx));
1752
1753        let save_task = thread_store.update(cx, |store, cx| {
1754            store.save_thread(
1755                acp::SessionId::new(Arc::from("thread-1")),
1756                make_test_thread(
1757                    "Fix crash in project panel",
1758                    chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 3, 0, 0, 0).unwrap(),
1759                ),
1760                path_list.clone(),
1761                cx,
1762            )
1763        });
1764        save_task.await.unwrap();
1765
1766        let save_task = thread_store.update(cx, |store, cx| {
1767            store.save_thread(
1768                acp::SessionId::new(Arc::from("thread-2")),
1769                make_test_thread(
1770                    "Add inline diff view",
1771                    chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 2, 0, 0, 0).unwrap(),
1772                ),
1773                path_list.clone(),
1774                cx,
1775            )
1776        });
1777        save_task.await.unwrap();
1778        cx.run_until_parked();
1779
1780        multi_workspace.update_in(cx, |_, _window, cx| cx.notify());
1781        cx.run_until_parked();
1782
1783        assert_eq!(
1784            visible_entries_as_strings(&sidebar, cx),
1785            vec![
1786                "v [my-project]",
1787                "  Fix crash in project panel",
1788                "  Add inline diff view",
1789            ]
1790        );
1791    }
1792
1793    #[gpui::test]
1794    async fn test_workspace_lifecycle(cx: &mut TestAppContext) {
1795        let project = init_test_project("/project-a", cx).await;
1796        let (multi_workspace, cx) =
1797            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
1798        let sidebar = setup_sidebar(&multi_workspace, cx);
1799
1800        // Single workspace with a thread
1801        let path_list = PathList::new(&[std::path::PathBuf::from("/project-a")]);
1802        let thread_store = cx.update(|_window, cx| ThreadStore::global(cx));
1803
1804        let save_task = thread_store.update(cx, |store, cx| {
1805            store.save_thread(
1806                acp::SessionId::new(Arc::from("thread-a1")),
1807                make_test_thread(
1808                    "Thread A1",
1809                    chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 1, 0, 0, 0).unwrap(),
1810                ),
1811                path_list.clone(),
1812                cx,
1813            )
1814        });
1815        save_task.await.unwrap();
1816        cx.run_until_parked();
1817
1818        multi_workspace.update_in(cx, |_, _window, cx| cx.notify());
1819        cx.run_until_parked();
1820
1821        assert_eq!(
1822            visible_entries_as_strings(&sidebar, cx),
1823            vec!["v [project-a]", "  Thread A1"]
1824        );
1825
1826        // Add a second workspace
1827        multi_workspace.update_in(cx, |mw, window, cx| {
1828            mw.create_workspace(window, cx);
1829        });
1830        cx.run_until_parked();
1831
1832        assert_eq!(
1833            visible_entries_as_strings(&sidebar, cx),
1834            vec![
1835                "v [project-a]",
1836                "  Thread A1",
1837                "v [Empty Workspace]",
1838                "  [+ New Thread]"
1839            ]
1840        );
1841
1842        // Remove the second workspace
1843        multi_workspace.update_in(cx, |mw, window, cx| {
1844            mw.remove_workspace(1, window, cx);
1845        });
1846        cx.run_until_parked();
1847
1848        assert_eq!(
1849            visible_entries_as_strings(&sidebar, cx),
1850            vec!["v [project-a]", "  Thread A1"]
1851        );
1852    }
1853
1854    #[gpui::test]
1855    async fn test_view_more_pagination(cx: &mut TestAppContext) {
1856        let project = init_test_project("/my-project", cx).await;
1857        let (multi_workspace, cx) =
1858            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
1859        let sidebar = setup_sidebar(&multi_workspace, cx);
1860
1861        let path_list = PathList::new(&[std::path::PathBuf::from("/my-project")]);
1862        save_n_test_threads(12, &path_list, cx).await;
1863
1864        multi_workspace.update_in(cx, |_, _window, cx| cx.notify());
1865        cx.run_until_parked();
1866
1867        assert_eq!(
1868            visible_entries_as_strings(&sidebar, cx),
1869            vec![
1870                "v [my-project]",
1871                "  Thread 12",
1872                "  Thread 11",
1873                "  Thread 10",
1874                "  Thread 9",
1875                "  Thread 8",
1876                "  + View More (7)",
1877            ]
1878        );
1879    }
1880
1881    #[gpui::test]
1882    async fn test_view_more_batched_expansion(cx: &mut TestAppContext) {
1883        let project = init_test_project("/my-project", cx).await;
1884        let (multi_workspace, cx) =
1885            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
1886        let sidebar = setup_sidebar(&multi_workspace, cx);
1887
1888        let path_list = PathList::new(&[std::path::PathBuf::from("/my-project")]);
1889        // Create 17 threads: initially shows 5, then 10, then 15, then all 17 with Collapse
1890        save_n_test_threads(17, &path_list, cx).await;
1891
1892        multi_workspace.update_in(cx, |_, _window, cx| cx.notify());
1893        cx.run_until_parked();
1894
1895        // Initially shows 5 threads + View More (12 remaining)
1896        let entries = visible_entries_as_strings(&sidebar, cx);
1897        assert_eq!(entries.len(), 7); // header + 5 threads + View More
1898        assert!(entries.iter().any(|e| e.contains("View More (12)")));
1899
1900        // Focus and navigate to View More, then confirm to expand by one batch
1901        open_and_focus_sidebar(&sidebar, &multi_workspace, cx);
1902        for _ in 0..7 {
1903            cx.dispatch_action(SelectNext);
1904        }
1905        cx.dispatch_action(Confirm);
1906        cx.run_until_parked();
1907
1908        // Now shows 10 threads + View More (7 remaining)
1909        let entries = visible_entries_as_strings(&sidebar, cx);
1910        assert_eq!(entries.len(), 12); // header + 10 threads + View More
1911        assert!(entries.iter().any(|e| e.contains("View More (7)")));
1912
1913        // Expand again by one batch
1914        sidebar.update_in(cx, |s, _window, cx| {
1915            let current = s.expanded_groups.get(&path_list).copied().unwrap_or(0);
1916            s.expanded_groups.insert(path_list.clone(), current + 1);
1917            s.update_entries(cx);
1918        });
1919        cx.run_until_parked();
1920
1921        // Now shows 15 threads + View More (2 remaining)
1922        let entries = visible_entries_as_strings(&sidebar, cx);
1923        assert_eq!(entries.len(), 17); // header + 15 threads + View More
1924        assert!(entries.iter().any(|e| e.contains("View More (2)")));
1925
1926        // Expand one more time - should show all 17 threads with Collapse button
1927        sidebar.update_in(cx, |s, _window, cx| {
1928            let current = s.expanded_groups.get(&path_list).copied().unwrap_or(0);
1929            s.expanded_groups.insert(path_list.clone(), current + 1);
1930            s.update_entries(cx);
1931        });
1932        cx.run_until_parked();
1933
1934        // All 17 threads shown with Collapse button
1935        let entries = visible_entries_as_strings(&sidebar, cx);
1936        assert_eq!(entries.len(), 19); // header + 17 threads + Collapse
1937        assert!(!entries.iter().any(|e| e.contains("View More")));
1938        assert!(entries.iter().any(|e| e.contains("Collapse")));
1939
1940        // Click collapse - should go back to showing 5 threads
1941        sidebar.update_in(cx, |s, _window, cx| {
1942            s.expanded_groups.remove(&path_list);
1943            s.update_entries(cx);
1944        });
1945        cx.run_until_parked();
1946
1947        // Back to initial state: 5 threads + View More (12 remaining)
1948        let entries = visible_entries_as_strings(&sidebar, cx);
1949        assert_eq!(entries.len(), 7); // header + 5 threads + View More
1950        assert!(entries.iter().any(|e| e.contains("View More (12)")));
1951    }
1952
1953    #[gpui::test]
1954    async fn test_collapse_and_expand_group(cx: &mut TestAppContext) {
1955        let project = init_test_project("/my-project", cx).await;
1956        let (multi_workspace, cx) =
1957            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
1958        let sidebar = setup_sidebar(&multi_workspace, cx);
1959
1960        let path_list = PathList::new(&[std::path::PathBuf::from("/my-project")]);
1961        save_n_test_threads(1, &path_list, cx).await;
1962
1963        multi_workspace.update_in(cx, |_, _window, cx| cx.notify());
1964        cx.run_until_parked();
1965
1966        assert_eq!(
1967            visible_entries_as_strings(&sidebar, cx),
1968            vec!["v [my-project]", "  Thread 1"]
1969        );
1970
1971        // Collapse
1972        sidebar.update_in(cx, |s, window, cx| {
1973            s.toggle_collapse(&path_list, window, cx);
1974        });
1975        cx.run_until_parked();
1976
1977        assert_eq!(
1978            visible_entries_as_strings(&sidebar, cx),
1979            vec!["> [my-project]"]
1980        );
1981
1982        // Expand
1983        sidebar.update_in(cx, |s, window, cx| {
1984            s.toggle_collapse(&path_list, window, cx);
1985        });
1986        cx.run_until_parked();
1987
1988        assert_eq!(
1989            visible_entries_as_strings(&sidebar, cx),
1990            vec!["v [my-project]", "  Thread 1"]
1991        );
1992    }
1993
1994    #[gpui::test]
1995    async fn test_visible_entries_as_strings(cx: &mut TestAppContext) {
1996        let project = init_test_project("/my-project", cx).await;
1997        let (multi_workspace, cx) =
1998            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
1999        let sidebar = setup_sidebar(&multi_workspace, cx);
2000
2001        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2002        let expanded_path = PathList::new(&[std::path::PathBuf::from("/expanded")]);
2003        let collapsed_path = PathList::new(&[std::path::PathBuf::from("/collapsed")]);
2004
2005        sidebar.update_in(cx, |s, _window, _cx| {
2006            s.collapsed_groups.insert(collapsed_path.clone());
2007            s.contents
2008                .notified_threads
2009                .insert(acp::SessionId::new(Arc::from("t-5")));
2010            s.contents.entries = vec![
2011                // Expanded project header
2012                ListEntry::ProjectHeader {
2013                    path_list: expanded_path.clone(),
2014                    label: "expanded-project".into(),
2015                    workspace: workspace.clone(),
2016                    highlight_positions: Vec::new(),
2017                    has_threads: true,
2018                },
2019                // Thread with default (Completed) status, not active
2020                ListEntry::Thread(ThreadEntry {
2021                    session_info: acp_thread::AgentSessionInfo {
2022                        session_id: acp::SessionId::new(Arc::from("t-1")),
2023                        cwd: None,
2024                        title: Some("Completed thread".into()),
2025                        updated_at: Some(Utc::now()),
2026                        created_at: Some(Utc::now()),
2027                        meta: None,
2028                    },
2029                    icon: IconName::ZedAgent,
2030                    icon_from_external_svg: None,
2031                    status: AgentThreadStatus::Completed,
2032                    workspace: workspace.clone(),
2033                    is_live: false,
2034                    is_background: false,
2035                    highlight_positions: Vec::new(),
2036                }),
2037                // Active thread with Running status
2038                ListEntry::Thread(ThreadEntry {
2039                    session_info: acp_thread::AgentSessionInfo {
2040                        session_id: acp::SessionId::new(Arc::from("t-2")),
2041                        cwd: None,
2042                        title: Some("Running thread".into()),
2043                        updated_at: Some(Utc::now()),
2044                        created_at: Some(Utc::now()),
2045                        meta: None,
2046                    },
2047                    icon: IconName::ZedAgent,
2048                    icon_from_external_svg: None,
2049                    status: AgentThreadStatus::Running,
2050                    workspace: workspace.clone(),
2051                    is_live: true,
2052                    is_background: false,
2053                    highlight_positions: Vec::new(),
2054                }),
2055                // Active thread with Error status
2056                ListEntry::Thread(ThreadEntry {
2057                    session_info: acp_thread::AgentSessionInfo {
2058                        session_id: acp::SessionId::new(Arc::from("t-3")),
2059                        cwd: None,
2060                        title: Some("Error thread".into()),
2061                        updated_at: Some(Utc::now()),
2062                        created_at: Some(Utc::now()),
2063                        meta: None,
2064                    },
2065                    icon: IconName::ZedAgent,
2066                    icon_from_external_svg: None,
2067                    status: AgentThreadStatus::Error,
2068                    workspace: workspace.clone(),
2069                    is_live: true,
2070                    is_background: false,
2071                    highlight_positions: Vec::new(),
2072                }),
2073                // Thread with WaitingForConfirmation status, not active
2074                ListEntry::Thread(ThreadEntry {
2075                    session_info: acp_thread::AgentSessionInfo {
2076                        session_id: acp::SessionId::new(Arc::from("t-4")),
2077                        cwd: None,
2078                        title: Some("Waiting thread".into()),
2079                        updated_at: Some(Utc::now()),
2080                        created_at: Some(Utc::now()),
2081                        meta: None,
2082                    },
2083                    icon: IconName::ZedAgent,
2084                    icon_from_external_svg: None,
2085                    status: AgentThreadStatus::WaitingForConfirmation,
2086                    workspace: workspace.clone(),
2087                    is_live: false,
2088                    is_background: false,
2089                    highlight_positions: Vec::new(),
2090                }),
2091                // Background thread that completed (should show notification)
2092                ListEntry::Thread(ThreadEntry {
2093                    session_info: acp_thread::AgentSessionInfo {
2094                        session_id: acp::SessionId::new(Arc::from("t-5")),
2095                        cwd: None,
2096                        title: Some("Notified thread".into()),
2097                        updated_at: Some(Utc::now()),
2098                        created_at: Some(Utc::now()),
2099                        meta: None,
2100                    },
2101                    icon: IconName::ZedAgent,
2102                    icon_from_external_svg: None,
2103                    status: AgentThreadStatus::Completed,
2104                    workspace: workspace.clone(),
2105                    is_live: true,
2106                    is_background: true,
2107                    highlight_positions: Vec::new(),
2108                }),
2109                // View More entry
2110                ListEntry::ViewMore {
2111                    path_list: expanded_path.clone(),
2112                    remaining_count: 42,
2113                    is_fully_expanded: false,
2114                },
2115                // Collapsed project header
2116                ListEntry::ProjectHeader {
2117                    path_list: collapsed_path.clone(),
2118                    label: "collapsed-project".into(),
2119                    workspace: workspace.clone(),
2120                    highlight_positions: Vec::new(),
2121                    has_threads: true,
2122                },
2123            ];
2124            // Select the Running thread (index 2)
2125            s.selection = Some(2);
2126        });
2127
2128        assert_eq!(
2129            visible_entries_as_strings(&sidebar, cx),
2130            vec![
2131                "v [expanded-project]",
2132                "  Completed thread",
2133                "  Running thread * (running)  <== selected",
2134                "  Error thread * (error)",
2135                "  Waiting thread (waiting)",
2136                "  Notified thread * (!)",
2137                "  + View More (42)",
2138                "> [collapsed-project]",
2139            ]
2140        );
2141
2142        // Move selection to the collapsed header
2143        sidebar.update_in(cx, |s, _window, _cx| {
2144            s.selection = Some(7);
2145        });
2146
2147        assert_eq!(
2148            visible_entries_as_strings(&sidebar, cx).last().cloned(),
2149            Some("> [collapsed-project]  <== selected".to_string()),
2150        );
2151
2152        // Clear selection
2153        sidebar.update_in(cx, |s, _window, _cx| {
2154            s.selection = None;
2155        });
2156
2157        // No entry should have the selected marker
2158        let entries = visible_entries_as_strings(&sidebar, cx);
2159        for entry in &entries {
2160            assert!(
2161                !entry.contains("<== selected"),
2162                "unexpected selection marker in: {}",
2163                entry
2164            );
2165        }
2166    }
2167
2168    #[gpui::test]
2169    async fn test_keyboard_select_next_and_previous(cx: &mut TestAppContext) {
2170        let project = init_test_project("/my-project", cx).await;
2171        let (multi_workspace, cx) =
2172            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
2173        let sidebar = setup_sidebar(&multi_workspace, cx);
2174
2175        let path_list = PathList::new(&[std::path::PathBuf::from("/my-project")]);
2176        save_n_test_threads(3, &path_list, cx).await;
2177
2178        multi_workspace.update_in(cx, |_, _window, cx| cx.notify());
2179        cx.run_until_parked();
2180
2181        // Entries: [header, thread3, thread2, thread1]
2182        // Focusing the sidebar does not set a selection; select_next/select_previous
2183        // handle None gracefully by starting from the first or last entry.
2184        open_and_focus_sidebar(&sidebar, &multi_workspace, cx);
2185        assert_eq!(sidebar.read_with(cx, |s, _| s.selection), None);
2186
2187        // First SelectNext from None starts at index 0
2188        cx.dispatch_action(SelectNext);
2189        assert_eq!(sidebar.read_with(cx, |s, _| s.selection), Some(0));
2190
2191        // Move down through remaining entries
2192        cx.dispatch_action(SelectNext);
2193        assert_eq!(sidebar.read_with(cx, |s, _| s.selection), Some(1));
2194
2195        cx.dispatch_action(SelectNext);
2196        assert_eq!(sidebar.read_with(cx, |s, _| s.selection), Some(2));
2197
2198        cx.dispatch_action(SelectNext);
2199        assert_eq!(sidebar.read_with(cx, |s, _| s.selection), Some(3));
2200
2201        // At the end, selection stays on the last entry
2202        cx.dispatch_action(SelectNext);
2203        assert_eq!(sidebar.read_with(cx, |s, _| s.selection), Some(3));
2204
2205        // Move back up
2206
2207        cx.dispatch_action(SelectPrevious);
2208        assert_eq!(sidebar.read_with(cx, |s, _| s.selection), Some(2));
2209
2210        cx.dispatch_action(SelectPrevious);
2211        assert_eq!(sidebar.read_with(cx, |s, _| s.selection), Some(1));
2212
2213        cx.dispatch_action(SelectPrevious);
2214        assert_eq!(sidebar.read_with(cx, |s, _| s.selection), Some(0));
2215
2216        // At the top, selection stays on the first entry
2217        cx.dispatch_action(SelectPrevious);
2218        assert_eq!(sidebar.read_with(cx, |s, _| s.selection), Some(0));
2219    }
2220
2221    #[gpui::test]
2222    async fn test_keyboard_select_first_and_last(cx: &mut TestAppContext) {
2223        let project = init_test_project("/my-project", cx).await;
2224        let (multi_workspace, cx) =
2225            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
2226        let sidebar = setup_sidebar(&multi_workspace, cx);
2227
2228        let path_list = PathList::new(&[std::path::PathBuf::from("/my-project")]);
2229        save_n_test_threads(3, &path_list, cx).await;
2230        multi_workspace.update_in(cx, |_, _window, cx| cx.notify());
2231        cx.run_until_parked();
2232
2233        open_and_focus_sidebar(&sidebar, &multi_workspace, cx);
2234
2235        // SelectLast jumps to the end
2236        cx.dispatch_action(SelectLast);
2237        assert_eq!(sidebar.read_with(cx, |s, _| s.selection), Some(3));
2238
2239        // SelectFirst jumps to the beginning
2240        cx.dispatch_action(SelectFirst);
2241        assert_eq!(sidebar.read_with(cx, |s, _| s.selection), Some(0));
2242    }
2243
2244    #[gpui::test]
2245    async fn test_keyboard_focus_in_does_not_set_selection(cx: &mut TestAppContext) {
2246        let project = init_test_project("/my-project", cx).await;
2247        let (multi_workspace, cx) =
2248            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
2249        let sidebar = setup_sidebar(&multi_workspace, cx);
2250
2251        // Initially no selection
2252        assert_eq!(sidebar.read_with(cx, |s, _| s.selection), None);
2253
2254        // Open the sidebar so it's rendered, then focus it to trigger focus_in.
2255        // focus_in no longer sets a default selection.
2256        open_and_focus_sidebar(&sidebar, &multi_workspace, cx);
2257        assert_eq!(sidebar.read_with(cx, |s, _| s.selection), None);
2258
2259        // Manually set a selection, blur, then refocus — selection should be preserved
2260        sidebar.update_in(cx, |sidebar, _window, _cx| {
2261            sidebar.selection = Some(0);
2262        });
2263
2264        cx.update(|window, _cx| {
2265            window.blur();
2266        });
2267        cx.run_until_parked();
2268
2269        sidebar.update_in(cx, |_, window, cx| {
2270            cx.focus_self(window);
2271        });
2272        cx.run_until_parked();
2273        assert_eq!(sidebar.read_with(cx, |s, _| s.selection), Some(0));
2274    }
2275
2276    #[gpui::test]
2277    async fn test_keyboard_confirm_on_project_header_activates_workspace(cx: &mut TestAppContext) {
2278        let project = init_test_project("/my-project", cx).await;
2279        let (multi_workspace, cx) =
2280            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
2281        let sidebar = setup_sidebar(&multi_workspace, cx);
2282
2283        multi_workspace.update_in(cx, |mw, window, cx| {
2284            mw.create_workspace(window, cx);
2285        });
2286        cx.run_until_parked();
2287
2288        let path_list = PathList::new(&[std::path::PathBuf::from("/my-project")]);
2289        save_n_test_threads(1, &path_list, cx).await;
2290        multi_workspace.update_in(cx, |_, _window, cx| cx.notify());
2291        cx.run_until_parked();
2292
2293        assert_eq!(
2294            visible_entries_as_strings(&sidebar, cx),
2295            vec![
2296                "v [my-project]",
2297                "  Thread 1",
2298                "v [Empty Workspace]",
2299                "  [+ New Thread]",
2300            ]
2301        );
2302
2303        // Switch to workspace 1 so we can verify confirm switches back.
2304        multi_workspace.update_in(cx, |mw, window, cx| {
2305            mw.activate_index(1, window, cx);
2306        });
2307        cx.run_until_parked();
2308        assert_eq!(
2309            multi_workspace.read_with(cx, |mw, _| mw.active_workspace_index()),
2310            1
2311        );
2312
2313        // Focus the sidebar and manually select the header (index 0)
2314        open_and_focus_sidebar(&sidebar, &multi_workspace, cx);
2315        sidebar.update_in(cx, |sidebar, _window, _cx| {
2316            sidebar.selection = Some(0);
2317        });
2318
2319        // Press confirm on project header (workspace 0) to activate it.
2320        cx.dispatch_action(Confirm);
2321        cx.run_until_parked();
2322
2323        assert_eq!(
2324            multi_workspace.read_with(cx, |mw, _| mw.active_workspace_index()),
2325            0
2326        );
2327
2328        // Focus should have moved out of the sidebar to the workspace center.
2329        let workspace_0 = multi_workspace.read_with(cx, |mw, _cx| mw.workspaces()[0].clone());
2330        workspace_0.update_in(cx, |workspace, window, cx| {
2331            let pane_focus = workspace.active_pane().read(cx).focus_handle(cx);
2332            assert!(
2333                pane_focus.contains_focused(window, cx),
2334                "Confirming a project header should focus the workspace center pane"
2335            );
2336        });
2337    }
2338
2339    #[gpui::test]
2340    async fn test_keyboard_confirm_on_view_more_expands(cx: &mut TestAppContext) {
2341        let project = init_test_project("/my-project", cx).await;
2342        let (multi_workspace, cx) =
2343            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
2344        let sidebar = setup_sidebar(&multi_workspace, cx);
2345
2346        let path_list = PathList::new(&[std::path::PathBuf::from("/my-project")]);
2347        save_n_test_threads(8, &path_list, cx).await;
2348        multi_workspace.update_in(cx, |_, _window, cx| cx.notify());
2349        cx.run_until_parked();
2350
2351        // Should show header + 5 threads + "View More (3)"
2352        let entries = visible_entries_as_strings(&sidebar, cx);
2353        assert_eq!(entries.len(), 7);
2354        assert!(entries.iter().any(|e| e.contains("View More (3)")));
2355
2356        // Focus sidebar (selection starts at None), then navigate down to the "View More" entry (index 6)
2357        open_and_focus_sidebar(&sidebar, &multi_workspace, cx);
2358        for _ in 0..7 {
2359            cx.dispatch_action(SelectNext);
2360        }
2361        assert_eq!(sidebar.read_with(cx, |s, _| s.selection), Some(6));
2362
2363        // Confirm on "View More" to expand
2364        cx.dispatch_action(Confirm);
2365        cx.run_until_parked();
2366
2367        // All 8 threads should now be visible with a "Collapse" button
2368        let entries = visible_entries_as_strings(&sidebar, cx);
2369        assert_eq!(entries.len(), 10); // header + 8 threads + Collapse button
2370        assert!(!entries.iter().any(|e| e.contains("View More")));
2371        assert!(entries.iter().any(|e| e.contains("Collapse")));
2372    }
2373
2374    #[gpui::test]
2375    async fn test_keyboard_expand_and_collapse_selected_entry(cx: &mut TestAppContext) {
2376        let project = init_test_project("/my-project", cx).await;
2377        let (multi_workspace, cx) =
2378            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
2379        let sidebar = setup_sidebar(&multi_workspace, cx);
2380
2381        let path_list = PathList::new(&[std::path::PathBuf::from("/my-project")]);
2382        save_n_test_threads(1, &path_list, cx).await;
2383        multi_workspace.update_in(cx, |_, _window, cx| cx.notify());
2384        cx.run_until_parked();
2385
2386        assert_eq!(
2387            visible_entries_as_strings(&sidebar, cx),
2388            vec!["v [my-project]", "  Thread 1"]
2389        );
2390
2391        // Focus sidebar and manually select the header (index 0). Press left to collapse.
2392        open_and_focus_sidebar(&sidebar, &multi_workspace, cx);
2393        sidebar.update_in(cx, |sidebar, _window, _cx| {
2394            sidebar.selection = Some(0);
2395        });
2396
2397        cx.dispatch_action(CollapseSelectedEntry);
2398        cx.run_until_parked();
2399
2400        assert_eq!(
2401            visible_entries_as_strings(&sidebar, cx),
2402            vec!["> [my-project]  <== selected"]
2403        );
2404
2405        // Press right to expand
2406        cx.dispatch_action(ExpandSelectedEntry);
2407        cx.run_until_parked();
2408
2409        assert_eq!(
2410            visible_entries_as_strings(&sidebar, cx),
2411            vec!["v [my-project]  <== selected", "  Thread 1",]
2412        );
2413
2414        // Press right again on already-expanded header moves selection down
2415        cx.dispatch_action(ExpandSelectedEntry);
2416        assert_eq!(sidebar.read_with(cx, |s, _| s.selection), Some(1));
2417    }
2418
2419    #[gpui::test]
2420    async fn test_keyboard_collapse_from_child_selects_parent(cx: &mut TestAppContext) {
2421        let project = init_test_project("/my-project", cx).await;
2422        let (multi_workspace, cx) =
2423            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
2424        let sidebar = setup_sidebar(&multi_workspace, cx);
2425
2426        let path_list = PathList::new(&[std::path::PathBuf::from("/my-project")]);
2427        save_n_test_threads(1, &path_list, cx).await;
2428        multi_workspace.update_in(cx, |_, _window, cx| cx.notify());
2429        cx.run_until_parked();
2430
2431        // Focus sidebar (selection starts at None), then navigate down to the thread (child)
2432        open_and_focus_sidebar(&sidebar, &multi_workspace, cx);
2433        cx.dispatch_action(SelectNext);
2434        cx.dispatch_action(SelectNext);
2435        assert_eq!(sidebar.read_with(cx, |s, _| s.selection), Some(1));
2436
2437        assert_eq!(
2438            visible_entries_as_strings(&sidebar, cx),
2439            vec!["v [my-project]", "  Thread 1  <== selected",]
2440        );
2441
2442        // Pressing left on a child collapses the parent group and selects it
2443        cx.dispatch_action(CollapseSelectedEntry);
2444        cx.run_until_parked();
2445
2446        assert_eq!(sidebar.read_with(cx, |s, _| s.selection), Some(0));
2447        assert_eq!(
2448            visible_entries_as_strings(&sidebar, cx),
2449            vec!["> [my-project]  <== selected"]
2450        );
2451    }
2452
2453    #[gpui::test]
2454    async fn test_keyboard_navigation_on_empty_list(cx: &mut TestAppContext) {
2455        let project = init_test_project("/empty-project", cx).await;
2456        let (multi_workspace, cx) =
2457            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
2458        let sidebar = setup_sidebar(&multi_workspace, cx);
2459
2460        // Even an empty project has the header and a new thread button
2461        assert_eq!(
2462            visible_entries_as_strings(&sidebar, cx),
2463            vec!["v [empty-project]", "  [+ New Thread]"]
2464        );
2465
2466        // Focus sidebar — focus_in does not set a selection
2467        open_and_focus_sidebar(&sidebar, &multi_workspace, cx);
2468        assert_eq!(sidebar.read_with(cx, |s, _| s.selection), None);
2469
2470        // First SelectNext from None starts at index 0 (header)
2471        cx.dispatch_action(SelectNext);
2472        assert_eq!(sidebar.read_with(cx, |s, _| s.selection), Some(0));
2473
2474        // SelectNext moves to the new thread button
2475        cx.dispatch_action(SelectNext);
2476        assert_eq!(sidebar.read_with(cx, |s, _| s.selection), Some(1));
2477
2478        // At the end, selection stays on the last entry
2479        cx.dispatch_action(SelectNext);
2480        assert_eq!(sidebar.read_with(cx, |s, _| s.selection), Some(1));
2481
2482        // SelectPrevious goes back to the header
2483        cx.dispatch_action(SelectPrevious);
2484        assert_eq!(sidebar.read_with(cx, |s, _| s.selection), Some(0));
2485    }
2486
2487    #[gpui::test]
2488    async fn test_selection_clamps_after_entry_removal(cx: &mut TestAppContext) {
2489        let project = init_test_project("/my-project", cx).await;
2490        let (multi_workspace, cx) =
2491            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
2492        let sidebar = setup_sidebar(&multi_workspace, cx);
2493
2494        let path_list = PathList::new(&[std::path::PathBuf::from("/my-project")]);
2495        save_n_test_threads(1, &path_list, cx).await;
2496        multi_workspace.update_in(cx, |_, _window, cx| cx.notify());
2497        cx.run_until_parked();
2498
2499        // Focus sidebar (selection starts at None), navigate down to the thread (index 1)
2500        open_and_focus_sidebar(&sidebar, &multi_workspace, cx);
2501        cx.dispatch_action(SelectNext);
2502        cx.dispatch_action(SelectNext);
2503        assert_eq!(sidebar.read_with(cx, |s, _| s.selection), Some(1));
2504
2505        // Collapse the group, which removes the thread from the list
2506        cx.dispatch_action(CollapseSelectedEntry);
2507        cx.run_until_parked();
2508
2509        // Selection should be clamped to the last valid index (0 = header)
2510        let selection = sidebar.read_with(cx, |s, _| s.selection);
2511        let entry_count = sidebar.read_with(cx, |s, _| s.contents.entries.len());
2512        assert!(
2513            selection.unwrap_or(0) < entry_count,
2514            "selection {} should be within bounds (entries: {})",
2515            selection.unwrap_or(0),
2516            entry_count,
2517        );
2518    }
2519
2520    async fn init_test_project_with_agent_panel(
2521        worktree_path: &str,
2522        cx: &mut TestAppContext,
2523    ) -> Entity<project::Project> {
2524        agent_ui::test_support::init_test(cx);
2525        cx.update(|cx| {
2526            cx.update_flags(false, vec!["agent-v2".into()]);
2527            ThreadStore::init_global(cx);
2528            language_model::LanguageModelRegistry::test(cx);
2529        });
2530
2531        let fs = FakeFs::new(cx.executor());
2532        fs.insert_tree(worktree_path, serde_json::json!({ "src": {} }))
2533            .await;
2534        cx.update(|cx| <dyn fs::Fs>::set_global(fs.clone(), cx));
2535        project::Project::test(fs, [worktree_path.as_ref()], cx).await
2536    }
2537
2538    fn add_agent_panel(
2539        workspace: &Entity<Workspace>,
2540        project: &Entity<project::Project>,
2541        cx: &mut gpui::VisualTestContext,
2542    ) -> Entity<AgentPanel> {
2543        workspace.update_in(cx, |workspace, window, cx| {
2544            let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
2545            let panel = cx.new(|cx| AgentPanel::test_new(workspace, text_thread_store, window, cx));
2546            workspace.add_panel(panel.clone(), window, cx);
2547            panel
2548        })
2549    }
2550
2551    fn setup_sidebar_with_agent_panel(
2552        multi_workspace: &Entity<MultiWorkspace>,
2553        project: &Entity<project::Project>,
2554        cx: &mut gpui::VisualTestContext,
2555    ) -> (Entity<Sidebar>, Entity<AgentPanel>) {
2556        let sidebar = setup_sidebar(multi_workspace, cx);
2557        let workspace = multi_workspace.read_with(cx, |mw, _cx| mw.workspace().clone());
2558        let panel = add_agent_panel(&workspace, project, cx);
2559        (sidebar, panel)
2560    }
2561
2562    #[gpui::test]
2563    async fn test_parallel_threads_shown_with_live_status(cx: &mut TestAppContext) {
2564        let project = init_test_project_with_agent_panel("/my-project", cx).await;
2565        let (multi_workspace, cx) =
2566            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
2567        let (sidebar, panel) = setup_sidebar_with_agent_panel(&multi_workspace, &project, cx);
2568
2569        let path_list = PathList::new(&[std::path::PathBuf::from("/my-project")]);
2570
2571        // Open thread A and keep it generating.
2572        let connection_a = StubAgentConnection::new();
2573        open_thread_with_connection(&panel, connection_a.clone(), cx);
2574        send_message(&panel, cx);
2575
2576        let session_id_a = active_session_id(&panel, cx);
2577        save_thread_to_store(&session_id_a, &path_list, cx).await;
2578
2579        cx.update(|_, cx| {
2580            connection_a.send_update(
2581                session_id_a.clone(),
2582                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("working...".into())),
2583                cx,
2584            );
2585        });
2586        cx.run_until_parked();
2587
2588        // Open thread B (idle, default response) — thread A goes to background.
2589        let connection_b = StubAgentConnection::new();
2590        connection_b.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
2591            acp::ContentChunk::new("Done".into()),
2592        )]);
2593        open_thread_with_connection(&panel, connection_b, cx);
2594        send_message(&panel, cx);
2595
2596        let session_id_b = active_session_id(&panel, cx);
2597        save_thread_to_store(&session_id_b, &path_list, cx).await;
2598
2599        cx.run_until_parked();
2600
2601        let mut entries = visible_entries_as_strings(&sidebar, cx);
2602        entries[1..].sort();
2603        assert_eq!(
2604            entries,
2605            vec!["v [my-project]", "  Hello *", "  Hello * (running)",]
2606        );
2607    }
2608
2609    #[gpui::test]
2610    async fn test_background_thread_completion_triggers_notification(cx: &mut TestAppContext) {
2611        let project_a = init_test_project_with_agent_panel("/project-a", cx).await;
2612        let (multi_workspace, cx) = cx
2613            .add_window_view(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
2614        let (sidebar, panel_a) = setup_sidebar_with_agent_panel(&multi_workspace, &project_a, cx);
2615
2616        let path_list_a = PathList::new(&[std::path::PathBuf::from("/project-a")]);
2617
2618        // Open thread on workspace A and keep it generating.
2619        let connection_a = StubAgentConnection::new();
2620        open_thread_with_connection(&panel_a, connection_a.clone(), cx);
2621        send_message(&panel_a, cx);
2622
2623        let session_id_a = active_session_id(&panel_a, cx);
2624        save_thread_to_store(&session_id_a, &path_list_a, cx).await;
2625
2626        cx.update(|_, cx| {
2627            connection_a.send_update(
2628                session_id_a.clone(),
2629                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("chunk".into())),
2630                cx,
2631            );
2632        });
2633        cx.run_until_parked();
2634
2635        // Add a second workspace and activate it (making workspace A the background).
2636        let fs = cx.update(|_, cx| <dyn fs::Fs>::global(cx));
2637        let project_b = project::Project::test(fs, [], cx).await;
2638        multi_workspace.update_in(cx, |mw, window, cx| {
2639            mw.test_add_workspace(project_b, window, cx);
2640        });
2641        cx.run_until_parked();
2642
2643        // Thread A is still running; no notification yet.
2644        assert_eq!(
2645            visible_entries_as_strings(&sidebar, cx),
2646            vec![
2647                "v [project-a]",
2648                "  Hello * (running)",
2649                "v [Empty Workspace]",
2650                "  [+ New Thread]",
2651            ]
2652        );
2653
2654        // Complete thread A's turn (transition Running → Completed).
2655        connection_a.end_turn(session_id_a.clone(), acp::StopReason::EndTurn);
2656        cx.run_until_parked();
2657
2658        // The completed background thread shows a notification indicator.
2659        assert_eq!(
2660            visible_entries_as_strings(&sidebar, cx),
2661            vec![
2662                "v [project-a]",
2663                "  Hello * (!)",
2664                "v [Empty Workspace]",
2665                "  [+ New Thread]",
2666            ]
2667        );
2668    }
2669
2670    fn type_in_search(sidebar: &Entity<Sidebar>, query: &str, cx: &mut gpui::VisualTestContext) {
2671        sidebar.update_in(cx, |sidebar, window, cx| {
2672            window.focus(&sidebar.filter_editor.focus_handle(cx), cx);
2673            sidebar.filter_editor.update(cx, |editor, cx| {
2674                editor.set_text(query, window, cx);
2675            });
2676        });
2677        cx.run_until_parked();
2678    }
2679
2680    #[gpui::test]
2681    async fn test_search_narrows_visible_threads_to_matches(cx: &mut TestAppContext) {
2682        let project = init_test_project("/my-project", cx).await;
2683        let (multi_workspace, cx) =
2684            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
2685        let sidebar = setup_sidebar(&multi_workspace, cx);
2686
2687        let path_list = PathList::new(&[std::path::PathBuf::from("/my-project")]);
2688        let thread_store = cx.update(|_window, cx| ThreadStore::global(cx));
2689
2690        for (id, title, hour) in [
2691            ("t-1", "Fix crash in project panel", 3),
2692            ("t-2", "Add inline diff view", 2),
2693            ("t-3", "Refactor settings module", 1),
2694        ] {
2695            let save_task = thread_store.update(cx, |store, cx| {
2696                store.save_thread(
2697                    acp::SessionId::new(Arc::from(id)),
2698                    make_test_thread(
2699                        title,
2700                        chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 1, hour, 0, 0).unwrap(),
2701                    ),
2702                    path_list.clone(),
2703                    cx,
2704                )
2705            });
2706            save_task.await.unwrap();
2707        }
2708        cx.run_until_parked();
2709
2710        assert_eq!(
2711            visible_entries_as_strings(&sidebar, cx),
2712            vec![
2713                "v [my-project]",
2714                "  Fix crash in project panel",
2715                "  Add inline diff view",
2716                "  Refactor settings module",
2717            ]
2718        );
2719
2720        // User types "diff" in the search box — only the matching thread remains,
2721        // with its workspace header preserved for context.
2722        type_in_search(&sidebar, "diff", cx);
2723        assert_eq!(
2724            visible_entries_as_strings(&sidebar, cx),
2725            vec!["v [my-project]", "  Add inline diff view  <== selected",]
2726        );
2727
2728        // User changes query to something with no matches — list is empty.
2729        type_in_search(&sidebar, "nonexistent", cx);
2730        assert_eq!(
2731            visible_entries_as_strings(&sidebar, cx),
2732            Vec::<String>::new()
2733        );
2734    }
2735
2736    #[gpui::test]
2737    async fn test_search_matches_regardless_of_case(cx: &mut TestAppContext) {
2738        // Scenario: A user remembers a thread title but not the exact casing.
2739        // Search should match case-insensitively so they can still find it.
2740        let project = init_test_project("/my-project", cx).await;
2741        let (multi_workspace, cx) =
2742            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
2743        let sidebar = setup_sidebar(&multi_workspace, cx);
2744
2745        let path_list = PathList::new(&[std::path::PathBuf::from("/my-project")]);
2746        let thread_store = cx.update(|_window, cx| ThreadStore::global(cx));
2747
2748        let save_task = thread_store.update(cx, |store, cx| {
2749            store.save_thread(
2750                acp::SessionId::new(Arc::from("thread-1")),
2751                make_test_thread(
2752                    "Fix Crash In Project Panel",
2753                    chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 1, 0, 0, 0).unwrap(),
2754                ),
2755                path_list.clone(),
2756                cx,
2757            )
2758        });
2759        save_task.await.unwrap();
2760        cx.run_until_parked();
2761
2762        // Lowercase query matches mixed-case title.
2763        type_in_search(&sidebar, "fix crash", cx);
2764        assert_eq!(
2765            visible_entries_as_strings(&sidebar, cx),
2766            vec![
2767                "v [my-project]",
2768                "  Fix Crash In Project Panel  <== selected",
2769            ]
2770        );
2771
2772        // Uppercase query also matches the same title.
2773        type_in_search(&sidebar, "FIX CRASH", cx);
2774        assert_eq!(
2775            visible_entries_as_strings(&sidebar, cx),
2776            vec![
2777                "v [my-project]",
2778                "  Fix Crash In Project Panel  <== selected",
2779            ]
2780        );
2781    }
2782
2783    #[gpui::test]
2784    async fn test_escape_clears_search_and_restores_full_list(cx: &mut TestAppContext) {
2785        // Scenario: A user searches, finds what they need, then presses Escape
2786        // to dismiss the filter and see the full list again.
2787        let project = init_test_project("/my-project", cx).await;
2788        let (multi_workspace, cx) =
2789            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
2790        let sidebar = setup_sidebar(&multi_workspace, cx);
2791
2792        let path_list = PathList::new(&[std::path::PathBuf::from("/my-project")]);
2793        let thread_store = cx.update(|_window, cx| ThreadStore::global(cx));
2794
2795        for (id, title, hour) in [("t-1", "Alpha thread", 2), ("t-2", "Beta thread", 1)] {
2796            let save_task = thread_store.update(cx, |store, cx| {
2797                store.save_thread(
2798                    acp::SessionId::new(Arc::from(id)),
2799                    make_test_thread(
2800                        title,
2801                        chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 1, hour, 0, 0).unwrap(),
2802                    ),
2803                    path_list.clone(),
2804                    cx,
2805                )
2806            });
2807            save_task.await.unwrap();
2808        }
2809        cx.run_until_parked();
2810
2811        // Confirm the full list is showing.
2812        assert_eq!(
2813            visible_entries_as_strings(&sidebar, cx),
2814            vec!["v [my-project]", "  Alpha thread", "  Beta thread",]
2815        );
2816
2817        // User types a search query to filter down.
2818        open_and_focus_sidebar(&sidebar, &multi_workspace, cx);
2819        type_in_search(&sidebar, "alpha", cx);
2820        assert_eq!(
2821            visible_entries_as_strings(&sidebar, cx),
2822            vec!["v [my-project]", "  Alpha thread  <== selected",]
2823        );
2824
2825        // User presses Escape — filter clears, full list is restored.
2826        cx.dispatch_action(Cancel);
2827        cx.run_until_parked();
2828        assert_eq!(
2829            visible_entries_as_strings(&sidebar, cx),
2830            vec![
2831                "v [my-project]",
2832                "  Alpha thread  <== selected",
2833                "  Beta thread",
2834            ]
2835        );
2836    }
2837
2838    #[gpui::test]
2839    async fn test_search_only_shows_workspace_headers_with_matches(cx: &mut TestAppContext) {
2840        let project_a = init_test_project("/project-a", cx).await;
2841        let (multi_workspace, cx) =
2842            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project_a, window, cx));
2843        let sidebar = setup_sidebar(&multi_workspace, cx);
2844
2845        let path_list_a = PathList::new(&[std::path::PathBuf::from("/project-a")]);
2846        let thread_store = cx.update(|_window, cx| ThreadStore::global(cx));
2847
2848        for (id, title, hour) in [
2849            ("a1", "Fix bug in sidebar", 2),
2850            ("a2", "Add tests for editor", 1),
2851        ] {
2852            let save_task = thread_store.update(cx, |store, cx| {
2853                store.save_thread(
2854                    acp::SessionId::new(Arc::from(id)),
2855                    make_test_thread(
2856                        title,
2857                        chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 1, hour, 0, 0).unwrap(),
2858                    ),
2859                    path_list_a.clone(),
2860                    cx,
2861                )
2862            });
2863            save_task.await.unwrap();
2864        }
2865
2866        // Add a second workspace.
2867        multi_workspace.update_in(cx, |mw, window, cx| {
2868            mw.create_workspace(window, cx);
2869        });
2870        cx.run_until_parked();
2871
2872        let path_list_b = PathList::new::<std::path::PathBuf>(&[]);
2873
2874        for (id, title, hour) in [
2875            ("b1", "Refactor sidebar layout", 3),
2876            ("b2", "Fix typo in README", 1),
2877        ] {
2878            let save_task = thread_store.update(cx, |store, cx| {
2879                store.save_thread(
2880                    acp::SessionId::new(Arc::from(id)),
2881                    make_test_thread(
2882                        title,
2883                        chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 1, hour, 0, 0).unwrap(),
2884                    ),
2885                    path_list_b.clone(),
2886                    cx,
2887                )
2888            });
2889            save_task.await.unwrap();
2890        }
2891        cx.run_until_parked();
2892
2893        assert_eq!(
2894            visible_entries_as_strings(&sidebar, cx),
2895            vec![
2896                "v [project-a]",
2897                "  Fix bug in sidebar",
2898                "  Add tests for editor",
2899                "v [Empty Workspace]",
2900                "  Refactor sidebar layout",
2901                "  Fix typo in README",
2902            ]
2903        );
2904
2905        // "sidebar" matches a thread in each workspace — both headers stay visible.
2906        type_in_search(&sidebar, "sidebar", cx);
2907        assert_eq!(
2908            visible_entries_as_strings(&sidebar, cx),
2909            vec![
2910                "v [project-a]",
2911                "  Fix bug in sidebar  <== selected",
2912                "v [Empty Workspace]",
2913                "  Refactor sidebar layout",
2914            ]
2915        );
2916
2917        // "typo" only matches in the second workspace — the first header disappears.
2918        type_in_search(&sidebar, "typo", cx);
2919        assert_eq!(
2920            visible_entries_as_strings(&sidebar, cx),
2921            vec!["v [Empty Workspace]", "  Fix typo in README  <== selected",]
2922        );
2923
2924        // "project-a" matches the first workspace name — the header appears
2925        // with all child threads included.
2926        type_in_search(&sidebar, "project-a", cx);
2927        assert_eq!(
2928            visible_entries_as_strings(&sidebar, cx),
2929            vec![
2930                "v [project-a]",
2931                "  Fix bug in sidebar  <== selected",
2932                "  Add tests for editor",
2933            ]
2934        );
2935    }
2936
2937    #[gpui::test]
2938    async fn test_search_matches_workspace_name(cx: &mut TestAppContext) {
2939        let project_a = init_test_project("/alpha-project", cx).await;
2940        let (multi_workspace, cx) =
2941            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project_a, window, cx));
2942        let sidebar = setup_sidebar(&multi_workspace, cx);
2943
2944        let path_list_a = PathList::new(&[std::path::PathBuf::from("/alpha-project")]);
2945        let thread_store = cx.update(|_window, cx| ThreadStore::global(cx));
2946
2947        for (id, title, hour) in [
2948            ("a1", "Fix bug in sidebar", 2),
2949            ("a2", "Add tests for editor", 1),
2950        ] {
2951            let save_task = thread_store.update(cx, |store, cx| {
2952                store.save_thread(
2953                    acp::SessionId::new(Arc::from(id)),
2954                    make_test_thread(
2955                        title,
2956                        chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 1, hour, 0, 0).unwrap(),
2957                    ),
2958                    path_list_a.clone(),
2959                    cx,
2960                )
2961            });
2962            save_task.await.unwrap();
2963        }
2964
2965        // Add a second workspace.
2966        multi_workspace.update_in(cx, |mw, window, cx| {
2967            mw.create_workspace(window, cx);
2968        });
2969        cx.run_until_parked();
2970
2971        let path_list_b = PathList::new::<std::path::PathBuf>(&[]);
2972
2973        for (id, title, hour) in [
2974            ("b1", "Refactor sidebar layout", 3),
2975            ("b2", "Fix typo in README", 1),
2976        ] {
2977            let save_task = thread_store.update(cx, |store, cx| {
2978                store.save_thread(
2979                    acp::SessionId::new(Arc::from(id)),
2980                    make_test_thread(
2981                        title,
2982                        chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 1, hour, 0, 0).unwrap(),
2983                    ),
2984                    path_list_b.clone(),
2985                    cx,
2986                )
2987            });
2988            save_task.await.unwrap();
2989        }
2990        cx.run_until_parked();
2991
2992        // "alpha" matches the workspace name "alpha-project" but no thread titles.
2993        // The workspace header should appear with all child threads included.
2994        type_in_search(&sidebar, "alpha", cx);
2995        assert_eq!(
2996            visible_entries_as_strings(&sidebar, cx),
2997            vec![
2998                "v [alpha-project]",
2999                "  Fix bug in sidebar  <== selected",
3000                "  Add tests for editor",
3001            ]
3002        );
3003
3004        // "sidebar" matches thread titles in both workspaces but not workspace names.
3005        // Both headers appear with their matching threads.
3006        type_in_search(&sidebar, "sidebar", cx);
3007        assert_eq!(
3008            visible_entries_as_strings(&sidebar, cx),
3009            vec![
3010                "v [alpha-project]",
3011                "  Fix bug in sidebar  <== selected",
3012                "v [Empty Workspace]",
3013                "  Refactor sidebar layout",
3014            ]
3015        );
3016
3017        // "alpha sidebar" matches the workspace name "alpha-project" (fuzzy: a-l-p-h-a-s-i-d-e-b-a-r
3018        // doesn't match) — but does not match either workspace name or any thread.
3019        // Actually let's test something simpler: a query that matches both a workspace
3020        // name AND some threads in that workspace. Matching threads should still appear.
3021        type_in_search(&sidebar, "fix", cx);
3022        assert_eq!(
3023            visible_entries_as_strings(&sidebar, cx),
3024            vec![
3025                "v [alpha-project]",
3026                "  Fix bug in sidebar  <== selected",
3027                "v [Empty Workspace]",
3028                "  Fix typo in README",
3029            ]
3030        );
3031
3032        // A query that matches a workspace name AND a thread in that same workspace.
3033        // Both the header (highlighted) and all child threads should appear.
3034        type_in_search(&sidebar, "alpha", cx);
3035        assert_eq!(
3036            visible_entries_as_strings(&sidebar, cx),
3037            vec![
3038                "v [alpha-project]",
3039                "  Fix bug in sidebar  <== selected",
3040                "  Add tests for editor",
3041            ]
3042        );
3043
3044        // Now search for something that matches only a workspace name when there
3045        // are also threads with matching titles — the non-matching workspace's
3046        // threads should still appear if their titles match.
3047        type_in_search(&sidebar, "alp", cx);
3048        assert_eq!(
3049            visible_entries_as_strings(&sidebar, cx),
3050            vec![
3051                "v [alpha-project]",
3052                "  Fix bug in sidebar  <== selected",
3053                "  Add tests for editor",
3054            ]
3055        );
3056    }
3057
3058    #[gpui::test]
3059    async fn test_search_finds_threads_hidden_behind_view_more(cx: &mut TestAppContext) {
3060        let project = init_test_project("/my-project", cx).await;
3061        let (multi_workspace, cx) =
3062            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
3063        let sidebar = setup_sidebar(&multi_workspace, cx);
3064
3065        let path_list = PathList::new(&[std::path::PathBuf::from("/my-project")]);
3066        let thread_store = cx.update(|_window, cx| ThreadStore::global(cx));
3067
3068        // Create 8 threads. The oldest one has a unique name and will be
3069        // behind View More (only 5 shown by default).
3070        for i in 0..8u32 {
3071            let title = if i == 0 {
3072                "Hidden gem thread".to_string()
3073            } else {
3074                format!("Thread {}", i + 1)
3075            };
3076            let save_task = thread_store.update(cx, |store, cx| {
3077                store.save_thread(
3078                    acp::SessionId::new(Arc::from(format!("thread-{}", i))),
3079                    make_test_thread(
3080                        &title,
3081                        chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 1, 0, 0, i).unwrap(),
3082                    ),
3083                    path_list.clone(),
3084                    cx,
3085                )
3086            });
3087            save_task.await.unwrap();
3088        }
3089        cx.run_until_parked();
3090
3091        // Confirm the thread is not visible and View More is shown.
3092        let entries = visible_entries_as_strings(&sidebar, cx);
3093        assert!(
3094            entries.iter().any(|e| e.contains("View More")),
3095            "should have View More button"
3096        );
3097        assert!(
3098            !entries.iter().any(|e| e.contains("Hidden gem")),
3099            "Hidden gem should be behind View More"
3100        );
3101
3102        // User searches for the hidden thread — it appears, and View More is gone.
3103        type_in_search(&sidebar, "hidden gem", cx);
3104        let filtered = visible_entries_as_strings(&sidebar, cx);
3105        assert_eq!(
3106            filtered,
3107            vec!["v [my-project]", "  Hidden gem thread  <== selected",]
3108        );
3109        assert!(
3110            !filtered.iter().any(|e| e.contains("View More")),
3111            "View More should not appear when filtering"
3112        );
3113    }
3114
3115    #[gpui::test]
3116    async fn test_search_finds_threads_inside_collapsed_groups(cx: &mut TestAppContext) {
3117        let project = init_test_project("/my-project", cx).await;
3118        let (multi_workspace, cx) =
3119            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
3120        let sidebar = setup_sidebar(&multi_workspace, cx);
3121
3122        let path_list = PathList::new(&[std::path::PathBuf::from("/my-project")]);
3123        let thread_store = cx.update(|_window, cx| ThreadStore::global(cx));
3124
3125        let save_task = thread_store.update(cx, |store, cx| {
3126            store.save_thread(
3127                acp::SessionId::new(Arc::from("thread-1")),
3128                make_test_thread(
3129                    "Important thread",
3130                    chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 1, 0, 0, 0).unwrap(),
3131                ),
3132                path_list.clone(),
3133                cx,
3134            )
3135        });
3136        save_task.await.unwrap();
3137        cx.run_until_parked();
3138
3139        // User focuses the sidebar and collapses the group using keyboard:
3140        // manually select the header, then press CollapseSelectedEntry to collapse.
3141        open_and_focus_sidebar(&sidebar, &multi_workspace, cx);
3142        sidebar.update_in(cx, |sidebar, _window, _cx| {
3143            sidebar.selection = Some(0);
3144        });
3145        cx.dispatch_action(CollapseSelectedEntry);
3146        cx.run_until_parked();
3147
3148        assert_eq!(
3149            visible_entries_as_strings(&sidebar, cx),
3150            vec!["> [my-project]  <== selected"]
3151        );
3152
3153        // User types a search — the thread appears even though its group is collapsed.
3154        type_in_search(&sidebar, "important", cx);
3155        assert_eq!(
3156            visible_entries_as_strings(&sidebar, cx),
3157            vec!["> [my-project]", "  Important thread  <== selected",]
3158        );
3159    }
3160
3161    #[gpui::test]
3162    async fn test_search_then_keyboard_navigate_and_confirm(cx: &mut TestAppContext) {
3163        let project = init_test_project("/my-project", cx).await;
3164        let (multi_workspace, cx) =
3165            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
3166        let sidebar = setup_sidebar(&multi_workspace, cx);
3167
3168        let path_list = PathList::new(&[std::path::PathBuf::from("/my-project")]);
3169        let thread_store = cx.update(|_window, cx| ThreadStore::global(cx));
3170
3171        for (id, title, hour) in [
3172            ("t-1", "Fix crash in panel", 3),
3173            ("t-2", "Fix lint warnings", 2),
3174            ("t-3", "Add new feature", 1),
3175        ] {
3176            let save_task = thread_store.update(cx, |store, cx| {
3177                store.save_thread(
3178                    acp::SessionId::new(Arc::from(id)),
3179                    make_test_thread(
3180                        title,
3181                        chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 1, hour, 0, 0).unwrap(),
3182                    ),
3183                    path_list.clone(),
3184                    cx,
3185                )
3186            });
3187            save_task.await.unwrap();
3188        }
3189        cx.run_until_parked();
3190
3191        open_and_focus_sidebar(&sidebar, &multi_workspace, cx);
3192
3193        // User types "fix" — two threads match.
3194        type_in_search(&sidebar, "fix", cx);
3195        assert_eq!(
3196            visible_entries_as_strings(&sidebar, cx),
3197            vec![
3198                "v [my-project]",
3199                "  Fix crash in panel  <== selected",
3200                "  Fix lint warnings",
3201            ]
3202        );
3203
3204        // Selection starts on the first matching thread. User presses
3205        // SelectNext to move to the second match.
3206        cx.dispatch_action(SelectNext);
3207        assert_eq!(
3208            visible_entries_as_strings(&sidebar, cx),
3209            vec![
3210                "v [my-project]",
3211                "  Fix crash in panel",
3212                "  Fix lint warnings  <== selected",
3213            ]
3214        );
3215
3216        // User can also jump back with SelectPrevious.
3217        cx.dispatch_action(SelectPrevious);
3218        assert_eq!(
3219            visible_entries_as_strings(&sidebar, cx),
3220            vec![
3221                "v [my-project]",
3222                "  Fix crash in panel  <== selected",
3223                "  Fix lint warnings",
3224            ]
3225        );
3226    }
3227
3228    #[gpui::test]
3229    async fn test_confirm_on_historical_thread_activates_workspace(cx: &mut TestAppContext) {
3230        let project = init_test_project("/my-project", cx).await;
3231        let (multi_workspace, cx) =
3232            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
3233        let sidebar = setup_sidebar(&multi_workspace, cx);
3234
3235        multi_workspace.update_in(cx, |mw, window, cx| {
3236            mw.create_workspace(window, cx);
3237        });
3238        cx.run_until_parked();
3239
3240        let path_list = PathList::new(&[std::path::PathBuf::from("/my-project")]);
3241        let thread_store = cx.update(|_window, cx| ThreadStore::global(cx));
3242
3243        let save_task = thread_store.update(cx, |store, cx| {
3244            store.save_thread(
3245                acp::SessionId::new(Arc::from("hist-1")),
3246                make_test_thread(
3247                    "Historical Thread",
3248                    chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 6, 1, 0, 0, 0).unwrap(),
3249                ),
3250                path_list.clone(),
3251                cx,
3252            )
3253        });
3254        save_task.await.unwrap();
3255        cx.run_until_parked();
3256        multi_workspace.update_in(cx, |_, _window, cx| cx.notify());
3257        cx.run_until_parked();
3258
3259        assert_eq!(
3260            visible_entries_as_strings(&sidebar, cx),
3261            vec![
3262                "v [my-project]",
3263                "  Historical Thread",
3264                "v [Empty Workspace]",
3265                "  [+ New Thread]",
3266            ]
3267        );
3268
3269        // Switch to workspace 1 so we can verify the confirm switches back.
3270        multi_workspace.update_in(cx, |mw, window, cx| {
3271            mw.activate_index(1, window, cx);
3272        });
3273        cx.run_until_parked();
3274        assert_eq!(
3275            multi_workspace.read_with(cx, |mw, _| mw.active_workspace_index()),
3276            1
3277        );
3278
3279        // Confirm on the historical (non-live) thread at index 1.
3280        // Before a previous fix, the workspace field was Option<usize> and
3281        // historical threads had None, so activate_thread early-returned
3282        // without switching the workspace.
3283        sidebar.update_in(cx, |sidebar, window, cx| {
3284            sidebar.selection = Some(1);
3285            sidebar.confirm(&Confirm, window, cx);
3286        });
3287        cx.run_until_parked();
3288
3289        assert_eq!(
3290            multi_workspace.read_with(cx, |mw, _| mw.active_workspace_index()),
3291            0
3292        );
3293    }
3294
3295    #[gpui::test]
3296    async fn test_click_clears_selection_and_focus_in_restores_it(cx: &mut TestAppContext) {
3297        let project = init_test_project("/my-project", cx).await;
3298        let (multi_workspace, cx) =
3299            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
3300        let sidebar = setup_sidebar(&multi_workspace, cx);
3301
3302        let path_list = PathList::new(&[std::path::PathBuf::from("/my-project")]);
3303        let thread_store = cx.update(|_window, cx| ThreadStore::global(cx));
3304
3305        let save_task = thread_store.update(cx, |store, cx| {
3306            store.save_thread(
3307                acp::SessionId::new(Arc::from("t-1")),
3308                make_test_thread(
3309                    "Thread A",
3310                    chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 2, 0, 0, 0).unwrap(),
3311                ),
3312                path_list.clone(),
3313                cx,
3314            )
3315        });
3316        save_task.await.unwrap();
3317        let save_task = thread_store.update(cx, |store, cx| {
3318            store.save_thread(
3319                acp::SessionId::new(Arc::from("t-2")),
3320                make_test_thread(
3321                    "Thread B",
3322                    chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 1, 0, 0, 0).unwrap(),
3323                ),
3324                path_list.clone(),
3325                cx,
3326            )
3327        });
3328        save_task.await.unwrap();
3329        cx.run_until_parked();
3330        multi_workspace.update_in(cx, |_, _window, cx| cx.notify());
3331        cx.run_until_parked();
3332
3333        assert_eq!(
3334            visible_entries_as_strings(&sidebar, cx),
3335            vec!["v [my-project]", "  Thread A", "  Thread B",]
3336        );
3337
3338        // Keyboard confirm preserves selection.
3339        sidebar.update_in(cx, |sidebar, window, cx| {
3340            sidebar.selection = Some(1);
3341            sidebar.confirm(&Confirm, window, cx);
3342        });
3343        assert_eq!(
3344            sidebar.read_with(cx, |sidebar, _| sidebar.selection),
3345            Some(1)
3346        );
3347
3348        // Click handlers clear selection to None so no highlight lingers
3349        // after a click regardless of focus state. The hover style provides
3350        // visual feedback during mouse interaction instead.
3351        sidebar.update_in(cx, |sidebar, window, cx| {
3352            sidebar.selection = None;
3353            let path_list = PathList::new(&[std::path::PathBuf::from("/my-project")]);
3354            sidebar.toggle_collapse(&path_list, window, cx);
3355        });
3356        assert_eq!(sidebar.read_with(cx, |sidebar, _| sidebar.selection), None);
3357
3358        // When the user tabs back into the sidebar, focus_in no longer
3359        // restores selection — it stays None.
3360        sidebar.update_in(cx, |sidebar, window, cx| {
3361            sidebar.focus_in(window, cx);
3362        });
3363        assert_eq!(sidebar.read_with(cx, |sidebar, _| sidebar.selection), None);
3364    }
3365
3366    #[gpui::test]
3367    async fn test_thread_title_update_propagates_to_sidebar(cx: &mut TestAppContext) {
3368        let project = init_test_project_with_agent_panel("/my-project", cx).await;
3369        let (multi_workspace, cx) =
3370            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
3371        let (sidebar, panel) = setup_sidebar_with_agent_panel(&multi_workspace, &project, cx);
3372
3373        let path_list = PathList::new(&[std::path::PathBuf::from("/my-project")]);
3374
3375        let connection = StubAgentConnection::new();
3376        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
3377            acp::ContentChunk::new("Hi there!".into()),
3378        )]);
3379        open_thread_with_connection(&panel, connection, cx);
3380        send_message(&panel, cx);
3381
3382        let session_id = active_session_id(&panel, cx);
3383        save_thread_to_store(&session_id, &path_list, cx).await;
3384        cx.run_until_parked();
3385
3386        assert_eq!(
3387            visible_entries_as_strings(&sidebar, cx),
3388            vec!["v [my-project]", "  Hello *"]
3389        );
3390
3391        // Simulate the agent generating a title. The notification chain is:
3392        // AcpThread::set_title emits TitleUpdated →
3393        // ConnectionView::handle_thread_event calls cx.notify() →
3394        // AgentPanel observer fires and emits AgentPanelEvent →
3395        // Sidebar subscription calls update_entries / rebuild_contents.
3396        //
3397        // Before the fix, handle_thread_event did NOT call cx.notify() for
3398        // TitleUpdated, so the AgentPanel observer never fired and the
3399        // sidebar kept showing the old title.
3400        let thread = panel.read_with(cx, |panel, cx| panel.active_agent_thread(cx).unwrap());
3401        thread.update(cx, |thread, cx| {
3402            thread
3403                .set_title("Friendly Greeting with AI".into(), cx)
3404                .detach();
3405        });
3406        cx.run_until_parked();
3407
3408        assert_eq!(
3409            visible_entries_as_strings(&sidebar, cx),
3410            vec!["v [my-project]", "  Friendly Greeting with AI *"]
3411        );
3412    }
3413
3414    #[gpui::test]
3415    async fn test_focused_thread_tracks_user_intent(cx: &mut TestAppContext) {
3416        let project_a = init_test_project_with_agent_panel("/project-a", cx).await;
3417        let (multi_workspace, cx) = cx
3418            .add_window_view(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
3419        let (sidebar, panel_a) = setup_sidebar_with_agent_panel(&multi_workspace, &project_a, cx);
3420
3421        let path_list_a = PathList::new(&[std::path::PathBuf::from("/project-a")]);
3422
3423        // Save a thread so it appears in the list.
3424        let connection_a = StubAgentConnection::new();
3425        connection_a.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
3426            acp::ContentChunk::new("Done".into()),
3427        )]);
3428        open_thread_with_connection(&panel_a, connection_a, cx);
3429        send_message(&panel_a, cx);
3430        let session_id_a = active_session_id(&panel_a, cx);
3431        save_thread_to_store(&session_id_a, &path_list_a, cx).await;
3432
3433        // Add a second workspace with its own agent panel.
3434        let fs = cx.update(|_, cx| <dyn fs::Fs>::global(cx));
3435        fs.as_fake()
3436            .insert_tree("/project-b", serde_json::json!({ "src": {} }))
3437            .await;
3438        let project_b = project::Project::test(fs, ["/project-b".as_ref()], cx).await;
3439        let workspace_b = multi_workspace.update_in(cx, |mw, window, cx| {
3440            mw.test_add_workspace(project_b.clone(), window, cx)
3441        });
3442        let panel_b = add_agent_panel(&workspace_b, &project_b, cx);
3443        cx.run_until_parked();
3444
3445        let workspace_a = multi_workspace.read_with(cx, |mw, _cx| mw.workspaces()[0].clone());
3446
3447        // ── 1. Initial state: no focused thread ──────────────────────────────
3448        // Workspace B is active (just added), so its header is the active entry.
3449        sidebar.read_with(cx, |sidebar, _cx| {
3450            assert_eq!(
3451                sidebar.focused_thread, None,
3452                "Initially no thread should be focused"
3453            );
3454            let active_entry = sidebar
3455                .active_entry_index
3456                .and_then(|ix| sidebar.contents.entries.get(ix));
3457            assert!(
3458                matches!(active_entry, Some(ListEntry::ProjectHeader { .. })),
3459                "Active entry should be the active workspace header"
3460            );
3461        });
3462
3463        sidebar.update_in(cx, |sidebar, window, cx| {
3464            sidebar.activate_thread(
3465                acp_thread::AgentSessionInfo {
3466                    session_id: session_id_a.clone(),
3467                    cwd: None,
3468                    title: Some("Test".into()),
3469                    updated_at: None,
3470                    created_at: None,
3471                    meta: None,
3472                },
3473                &workspace_a,
3474                window,
3475                cx,
3476            );
3477        });
3478        cx.run_until_parked();
3479
3480        sidebar.read_with(cx, |sidebar, _cx| {
3481            assert_eq!(
3482                sidebar.focused_thread.as_ref(),
3483                Some(&session_id_a),
3484                "After clicking a thread, it should be the focused thread"
3485            );
3486            let active_entry = sidebar.active_entry_index
3487                .and_then(|ix| sidebar.contents.entries.get(ix));
3488            assert!(
3489                matches!(active_entry, Some(ListEntry::Thread(thread)) if thread.session_info.session_id == session_id_a),
3490                "Active entry should be the clicked thread"
3491            );
3492        });
3493
3494        workspace_a.read_with(cx, |workspace, cx| {
3495            assert!(
3496                workspace.panel::<AgentPanel>(cx).is_some(),
3497                "Agent panel should exist"
3498            );
3499            let dock = workspace.right_dock().read(cx);
3500            assert!(
3501                dock.is_open(),
3502                "Clicking a thread should open the agent panel dock"
3503            );
3504        });
3505
3506        let connection_b = StubAgentConnection::new();
3507        connection_b.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
3508            acp::ContentChunk::new("Thread B".into()),
3509        )]);
3510        open_thread_with_connection(&panel_b, connection_b, cx);
3511        send_message(&panel_b, cx);
3512        let session_id_b = active_session_id(&panel_b, cx);
3513        let path_list_b = PathList::new(&[std::path::PathBuf::from("/project-b")]);
3514        save_thread_to_store(&session_id_b, &path_list_b, cx).await;
3515        cx.run_until_parked();
3516
3517        // Workspace A is currently active. Click a thread in workspace B,
3518        // which also triggers a workspace switch.
3519        sidebar.update_in(cx, |sidebar, window, cx| {
3520            sidebar.activate_thread(
3521                acp_thread::AgentSessionInfo {
3522                    session_id: session_id_b.clone(),
3523                    cwd: None,
3524                    title: Some("Thread B".into()),
3525                    updated_at: None,
3526                    created_at: None,
3527                    meta: None,
3528                },
3529                &workspace_b,
3530                window,
3531                cx,
3532            );
3533        });
3534        cx.run_until_parked();
3535
3536        sidebar.read_with(cx, |sidebar, _cx| {
3537            assert_eq!(
3538                sidebar.focused_thread.as_ref(),
3539                Some(&session_id_b),
3540                "Clicking a thread in another workspace should focus that thread"
3541            );
3542            let active_entry = sidebar
3543                .active_entry_index
3544                .and_then(|ix| sidebar.contents.entries.get(ix));
3545            assert!(
3546                matches!(active_entry, Some(ListEntry::Thread(thread)) if thread.session_info.session_id == session_id_b),
3547                "Active entry should be the cross-workspace thread"
3548            );
3549        });
3550
3551        multi_workspace.update_in(cx, |mw, window, cx| {
3552            mw.activate_next_workspace(window, cx);
3553        });
3554        cx.run_until_parked();
3555
3556        sidebar.read_with(cx, |sidebar, _cx| {
3557            assert_eq!(
3558                sidebar.focused_thread, None,
3559                "External workspace switch should clear focused_thread"
3560            );
3561            let active_entry = sidebar
3562                .active_entry_index
3563                .and_then(|ix| sidebar.contents.entries.get(ix));
3564            assert!(
3565                matches!(active_entry, Some(ListEntry::ProjectHeader { .. })),
3566                "Active entry should be the workspace header after external switch"
3567            );
3568        });
3569
3570        let connection_b2 = StubAgentConnection::new();
3571        connection_b2.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
3572            acp::ContentChunk::new("New thread".into()),
3573        )]);
3574        open_thread_with_connection(&panel_b, connection_b2, cx);
3575        send_message(&panel_b, cx);
3576        let session_id_b2 = active_session_id(&panel_b, cx);
3577        save_thread_to_store(&session_id_b2, &path_list_b, cx).await;
3578        cx.run_until_parked();
3579
3580        sidebar.read_with(cx, |sidebar, _cx| {
3581            assert_eq!(
3582                sidebar.focused_thread.as_ref(),
3583                Some(&session_id_b2),
3584                "Opening a thread externally should set focused_thread"
3585            );
3586        });
3587
3588        workspace_b.update_in(cx, |workspace, window, cx| {
3589            workspace.focus_handle(cx).focus(window, cx);
3590        });
3591        cx.run_until_parked();
3592
3593        sidebar.read_with(cx, |sidebar, _cx| {
3594            assert_eq!(
3595                sidebar.focused_thread.as_ref(),
3596                Some(&session_id_b2),
3597                "Defocusing the sidebar should not clear focused_thread"
3598            );
3599        });
3600
3601        sidebar.update_in(cx, |sidebar, window, cx| {
3602            sidebar.activate_workspace(&workspace_b, window, cx);
3603        });
3604        cx.run_until_parked();
3605
3606        sidebar.read_with(cx, |sidebar, _cx| {
3607            assert_eq!(
3608                sidebar.focused_thread, None,
3609                "Clicking a workspace header should clear focused_thread"
3610            );
3611            let active_entry = sidebar
3612                .active_entry_index
3613                .and_then(|ix| sidebar.contents.entries.get(ix));
3614            assert!(
3615                matches!(active_entry, Some(ListEntry::ProjectHeader { .. })),
3616                "Active entry should be the workspace header"
3617            );
3618        });
3619
3620        // ── 8. Focusing the agent panel thread restores focused_thread ────
3621        // Workspace B still has session_id_b2 loaded in the agent panel.
3622        // Clicking into the thread (simulated by focusing its view) should
3623        // set focused_thread via the ThreadFocused event.
3624        panel_b.update_in(cx, |panel, window, cx| {
3625            if let Some(thread_view) = panel.active_connection_view() {
3626                thread_view.read(cx).focus_handle(cx).focus(window, cx);
3627            }
3628        });
3629        cx.run_until_parked();
3630
3631        sidebar.read_with(cx, |sidebar, _cx| {
3632            assert_eq!(
3633                sidebar.focused_thread.as_ref(),
3634                Some(&session_id_b2),
3635                "Focusing the agent panel thread should set focused_thread"
3636            );
3637            let active_entry = sidebar
3638                .active_entry_index
3639                .and_then(|ix| sidebar.contents.entries.get(ix));
3640            assert!(
3641                matches!(active_entry, Some(ListEntry::Thread(thread)) if thread.session_info.session_id == session_id_b2),
3642                "Active entry should be the focused thread"
3643            );
3644        });
3645    }
3646}