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 = StubAgentConnection::new();
2573 open_thread_with_connection(&panel, connection.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.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 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
2590 acp::ContentChunk::new("Done".into()),
2591 )]);
2592 open_thread_with_connection(&panel, connection, cx);
2593 send_message(&panel, cx);
2594
2595 let session_id_b = active_session_id(&panel, cx);
2596 save_thread_to_store(&session_id_b, &path_list, cx).await;
2597
2598 cx.run_until_parked();
2599
2600 let mut entries = visible_entries_as_strings(&sidebar, cx);
2601 entries[1..].sort();
2602 assert_eq!(
2603 entries,
2604 vec!["v [my-project]", " Hello *", " Hello * (running)",]
2605 );
2606 }
2607
2608 #[gpui::test]
2609 async fn test_background_thread_completion_triggers_notification(cx: &mut TestAppContext) {
2610 let project_a = init_test_project_with_agent_panel("/project-a", cx).await;
2611 let (multi_workspace, cx) = cx
2612 .add_window_view(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
2613 let (sidebar, panel_a) = setup_sidebar_with_agent_panel(&multi_workspace, &project_a, cx);
2614
2615 let path_list_a = PathList::new(&[std::path::PathBuf::from("/project-a")]);
2616
2617 // Open thread on workspace A and keep it generating.
2618 let connection_a = StubAgentConnection::new();
2619 open_thread_with_connection(&panel_a, connection_a.clone(), cx);
2620 send_message(&panel_a, cx);
2621
2622 let session_id_a = active_session_id(&panel_a, cx);
2623 save_thread_to_store(&session_id_a, &path_list_a, cx).await;
2624
2625 cx.update(|_, cx| {
2626 connection_a.send_update(
2627 session_id_a.clone(),
2628 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("chunk".into())),
2629 cx,
2630 );
2631 });
2632 cx.run_until_parked();
2633
2634 // Add a second workspace and activate it (making workspace A the background).
2635 let fs = cx.update(|_, cx| <dyn fs::Fs>::global(cx));
2636 let project_b = project::Project::test(fs, [], cx).await;
2637 multi_workspace.update_in(cx, |mw, window, cx| {
2638 mw.test_add_workspace(project_b, window, cx);
2639 });
2640 cx.run_until_parked();
2641
2642 // Thread A is still running; no notification yet.
2643 assert_eq!(
2644 visible_entries_as_strings(&sidebar, cx),
2645 vec![
2646 "v [project-a]",
2647 " Hello * (running)",
2648 "v [Empty Workspace]",
2649 " [+ New Thread]",
2650 ]
2651 );
2652
2653 // Complete thread A's turn (transition Running → Completed).
2654 connection_a.end_turn(session_id_a.clone(), acp::StopReason::EndTurn);
2655 cx.run_until_parked();
2656
2657 // The completed background thread shows a notification indicator.
2658 assert_eq!(
2659 visible_entries_as_strings(&sidebar, cx),
2660 vec![
2661 "v [project-a]",
2662 " Hello * (!)",
2663 "v [Empty Workspace]",
2664 " [+ New Thread]",
2665 ]
2666 );
2667 }
2668
2669 fn type_in_search(sidebar: &Entity<Sidebar>, query: &str, cx: &mut gpui::VisualTestContext) {
2670 sidebar.update_in(cx, |sidebar, window, cx| {
2671 window.focus(&sidebar.filter_editor.focus_handle(cx), cx);
2672 sidebar.filter_editor.update(cx, |editor, cx| {
2673 editor.set_text(query, window, cx);
2674 });
2675 });
2676 cx.run_until_parked();
2677 }
2678
2679 #[gpui::test]
2680 async fn test_search_narrows_visible_threads_to_matches(cx: &mut TestAppContext) {
2681 let project = init_test_project("/my-project", cx).await;
2682 let (multi_workspace, cx) =
2683 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
2684 let sidebar = setup_sidebar(&multi_workspace, cx);
2685
2686 let path_list = PathList::new(&[std::path::PathBuf::from("/my-project")]);
2687 let thread_store = cx.update(|_window, cx| ThreadStore::global(cx));
2688
2689 for (id, title, hour) in [
2690 ("t-1", "Fix crash in project panel", 3),
2691 ("t-2", "Add inline diff view", 2),
2692 ("t-3", "Refactor settings module", 1),
2693 ] {
2694 let save_task = thread_store.update(cx, |store, cx| {
2695 store.save_thread(
2696 acp::SessionId::new(Arc::from(id)),
2697 make_test_thread(
2698 title,
2699 chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 1, hour, 0, 0).unwrap(),
2700 ),
2701 path_list.clone(),
2702 cx,
2703 )
2704 });
2705 save_task.await.unwrap();
2706 }
2707 cx.run_until_parked();
2708
2709 assert_eq!(
2710 visible_entries_as_strings(&sidebar, cx),
2711 vec![
2712 "v [my-project]",
2713 " Fix crash in project panel",
2714 " Add inline diff view",
2715 " Refactor settings module",
2716 ]
2717 );
2718
2719 // User types "diff" in the search box — only the matching thread remains,
2720 // with its workspace header preserved for context.
2721 type_in_search(&sidebar, "diff", cx);
2722 assert_eq!(
2723 visible_entries_as_strings(&sidebar, cx),
2724 vec!["v [my-project]", " Add inline diff view <== selected",]
2725 );
2726
2727 // User changes query to something with no matches — list is empty.
2728 type_in_search(&sidebar, "nonexistent", cx);
2729 assert_eq!(
2730 visible_entries_as_strings(&sidebar, cx),
2731 Vec::<String>::new()
2732 );
2733 }
2734
2735 #[gpui::test]
2736 async fn test_search_matches_regardless_of_case(cx: &mut TestAppContext) {
2737 // Scenario: A user remembers a thread title but not the exact casing.
2738 // Search should match case-insensitively so they can still find it.
2739 let project = init_test_project("/my-project", cx).await;
2740 let (multi_workspace, cx) =
2741 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
2742 let sidebar = setup_sidebar(&multi_workspace, cx);
2743
2744 let path_list = PathList::new(&[std::path::PathBuf::from("/my-project")]);
2745 let thread_store = cx.update(|_window, cx| ThreadStore::global(cx));
2746
2747 let save_task = thread_store.update(cx, |store, cx| {
2748 store.save_thread(
2749 acp::SessionId::new(Arc::from("thread-1")),
2750 make_test_thread(
2751 "Fix Crash In Project Panel",
2752 chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 1, 0, 0, 0).unwrap(),
2753 ),
2754 path_list.clone(),
2755 cx,
2756 )
2757 });
2758 save_task.await.unwrap();
2759 cx.run_until_parked();
2760
2761 // Lowercase query matches mixed-case title.
2762 type_in_search(&sidebar, "fix crash", cx);
2763 assert_eq!(
2764 visible_entries_as_strings(&sidebar, cx),
2765 vec![
2766 "v [my-project]",
2767 " Fix Crash In Project Panel <== selected",
2768 ]
2769 );
2770
2771 // Uppercase query also matches the same title.
2772 type_in_search(&sidebar, "FIX CRASH", cx);
2773 assert_eq!(
2774 visible_entries_as_strings(&sidebar, cx),
2775 vec![
2776 "v [my-project]",
2777 " Fix Crash In Project Panel <== selected",
2778 ]
2779 );
2780 }
2781
2782 #[gpui::test]
2783 async fn test_escape_clears_search_and_restores_full_list(cx: &mut TestAppContext) {
2784 // Scenario: A user searches, finds what they need, then presses Escape
2785 // to dismiss the filter and see the full list again.
2786 let project = init_test_project("/my-project", cx).await;
2787 let (multi_workspace, cx) =
2788 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
2789 let sidebar = setup_sidebar(&multi_workspace, cx);
2790
2791 let path_list = PathList::new(&[std::path::PathBuf::from("/my-project")]);
2792 let thread_store = cx.update(|_window, cx| ThreadStore::global(cx));
2793
2794 for (id, title, hour) in [("t-1", "Alpha thread", 2), ("t-2", "Beta thread", 1)] {
2795 let save_task = thread_store.update(cx, |store, cx| {
2796 store.save_thread(
2797 acp::SessionId::new(Arc::from(id)),
2798 make_test_thread(
2799 title,
2800 chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 1, hour, 0, 0).unwrap(),
2801 ),
2802 path_list.clone(),
2803 cx,
2804 )
2805 });
2806 save_task.await.unwrap();
2807 }
2808 cx.run_until_parked();
2809
2810 // Confirm the full list is showing.
2811 assert_eq!(
2812 visible_entries_as_strings(&sidebar, cx),
2813 vec!["v [my-project]", " Alpha thread", " Beta thread",]
2814 );
2815
2816 // User types a search query to filter down.
2817 open_and_focus_sidebar(&sidebar, &multi_workspace, cx);
2818 type_in_search(&sidebar, "alpha", cx);
2819 assert_eq!(
2820 visible_entries_as_strings(&sidebar, cx),
2821 vec!["v [my-project]", " Alpha thread <== selected",]
2822 );
2823
2824 // User presses Escape — filter clears, full list is restored.
2825 cx.dispatch_action(Cancel);
2826 cx.run_until_parked();
2827 assert_eq!(
2828 visible_entries_as_strings(&sidebar, cx),
2829 vec![
2830 "v [my-project]",
2831 " Alpha thread <== selected",
2832 " Beta thread",
2833 ]
2834 );
2835 }
2836
2837 #[gpui::test]
2838 async fn test_search_only_shows_workspace_headers_with_matches(cx: &mut TestAppContext) {
2839 let project_a = init_test_project("/project-a", cx).await;
2840 let (multi_workspace, cx) =
2841 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project_a, window, cx));
2842 let sidebar = setup_sidebar(&multi_workspace, cx);
2843
2844 let path_list_a = PathList::new(&[std::path::PathBuf::from("/project-a")]);
2845 let thread_store = cx.update(|_window, cx| ThreadStore::global(cx));
2846
2847 for (id, title, hour) in [
2848 ("a1", "Fix bug in sidebar", 2),
2849 ("a2", "Add tests for editor", 1),
2850 ] {
2851 let save_task = thread_store.update(cx, |store, cx| {
2852 store.save_thread(
2853 acp::SessionId::new(Arc::from(id)),
2854 make_test_thread(
2855 title,
2856 chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 1, hour, 0, 0).unwrap(),
2857 ),
2858 path_list_a.clone(),
2859 cx,
2860 )
2861 });
2862 save_task.await.unwrap();
2863 }
2864
2865 // Add a second workspace.
2866 multi_workspace.update_in(cx, |mw, window, cx| {
2867 mw.create_workspace(window, cx);
2868 });
2869 cx.run_until_parked();
2870
2871 let path_list_b = PathList::new::<std::path::PathBuf>(&[]);
2872
2873 for (id, title, hour) in [
2874 ("b1", "Refactor sidebar layout", 3),
2875 ("b2", "Fix typo in README", 1),
2876 ] {
2877 let save_task = thread_store.update(cx, |store, cx| {
2878 store.save_thread(
2879 acp::SessionId::new(Arc::from(id)),
2880 make_test_thread(
2881 title,
2882 chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 1, hour, 0, 0).unwrap(),
2883 ),
2884 path_list_b.clone(),
2885 cx,
2886 )
2887 });
2888 save_task.await.unwrap();
2889 }
2890 cx.run_until_parked();
2891
2892 assert_eq!(
2893 visible_entries_as_strings(&sidebar, cx),
2894 vec![
2895 "v [project-a]",
2896 " Fix bug in sidebar",
2897 " Add tests for editor",
2898 "v [Empty Workspace]",
2899 " Refactor sidebar layout",
2900 " Fix typo in README",
2901 ]
2902 );
2903
2904 // "sidebar" matches a thread in each workspace — both headers stay visible.
2905 type_in_search(&sidebar, "sidebar", cx);
2906 assert_eq!(
2907 visible_entries_as_strings(&sidebar, cx),
2908 vec![
2909 "v [project-a]",
2910 " Fix bug in sidebar <== selected",
2911 "v [Empty Workspace]",
2912 " Refactor sidebar layout",
2913 ]
2914 );
2915
2916 // "typo" only matches in the second workspace — the first header disappears.
2917 type_in_search(&sidebar, "typo", cx);
2918 assert_eq!(
2919 visible_entries_as_strings(&sidebar, cx),
2920 vec!["v [Empty Workspace]", " Fix typo in README <== selected",]
2921 );
2922
2923 // "project-a" matches the first workspace name — the header appears
2924 // with all child threads included.
2925 type_in_search(&sidebar, "project-a", cx);
2926 assert_eq!(
2927 visible_entries_as_strings(&sidebar, cx),
2928 vec![
2929 "v [project-a]",
2930 " Fix bug in sidebar <== selected",
2931 " Add tests for editor",
2932 ]
2933 );
2934 }
2935
2936 #[gpui::test]
2937 async fn test_search_matches_workspace_name(cx: &mut TestAppContext) {
2938 let project_a = init_test_project("/alpha-project", cx).await;
2939 let (multi_workspace, cx) =
2940 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project_a, window, cx));
2941 let sidebar = setup_sidebar(&multi_workspace, cx);
2942
2943 let path_list_a = PathList::new(&[std::path::PathBuf::from("/alpha-project")]);
2944 let thread_store = cx.update(|_window, cx| ThreadStore::global(cx));
2945
2946 for (id, title, hour) in [
2947 ("a1", "Fix bug in sidebar", 2),
2948 ("a2", "Add tests for editor", 1),
2949 ] {
2950 let save_task = thread_store.update(cx, |store, cx| {
2951 store.save_thread(
2952 acp::SessionId::new(Arc::from(id)),
2953 make_test_thread(
2954 title,
2955 chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 1, hour, 0, 0).unwrap(),
2956 ),
2957 path_list_a.clone(),
2958 cx,
2959 )
2960 });
2961 save_task.await.unwrap();
2962 }
2963
2964 // Add a second workspace.
2965 multi_workspace.update_in(cx, |mw, window, cx| {
2966 mw.create_workspace(window, cx);
2967 });
2968 cx.run_until_parked();
2969
2970 let path_list_b = PathList::new::<std::path::PathBuf>(&[]);
2971
2972 for (id, title, hour) in [
2973 ("b1", "Refactor sidebar layout", 3),
2974 ("b2", "Fix typo in README", 1),
2975 ] {
2976 let save_task = thread_store.update(cx, |store, cx| {
2977 store.save_thread(
2978 acp::SessionId::new(Arc::from(id)),
2979 make_test_thread(
2980 title,
2981 chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 1, hour, 0, 0).unwrap(),
2982 ),
2983 path_list_b.clone(),
2984 cx,
2985 )
2986 });
2987 save_task.await.unwrap();
2988 }
2989 cx.run_until_parked();
2990
2991 // "alpha" matches the workspace name "alpha-project" but no thread titles.
2992 // The workspace header should appear with all child threads included.
2993 type_in_search(&sidebar, "alpha", cx);
2994 assert_eq!(
2995 visible_entries_as_strings(&sidebar, cx),
2996 vec![
2997 "v [alpha-project]",
2998 " Fix bug in sidebar <== selected",
2999 " Add tests for editor",
3000 ]
3001 );
3002
3003 // "sidebar" matches thread titles in both workspaces but not workspace names.
3004 // Both headers appear with their matching threads.
3005 type_in_search(&sidebar, "sidebar", cx);
3006 assert_eq!(
3007 visible_entries_as_strings(&sidebar, cx),
3008 vec![
3009 "v [alpha-project]",
3010 " Fix bug in sidebar <== selected",
3011 "v [Empty Workspace]",
3012 " Refactor sidebar layout",
3013 ]
3014 );
3015
3016 // "alpha sidebar" matches the workspace name "alpha-project" (fuzzy: a-l-p-h-a-s-i-d-e-b-a-r
3017 // doesn't match) — but does not match either workspace name or any thread.
3018 // Actually let's test something simpler: a query that matches both a workspace
3019 // name AND some threads in that workspace. Matching threads should still appear.
3020 type_in_search(&sidebar, "fix", cx);
3021 assert_eq!(
3022 visible_entries_as_strings(&sidebar, cx),
3023 vec![
3024 "v [alpha-project]",
3025 " Fix bug in sidebar <== selected",
3026 "v [Empty Workspace]",
3027 " Fix typo in README",
3028 ]
3029 );
3030
3031 // A query that matches a workspace name AND a thread in that same workspace.
3032 // Both the header (highlighted) and all child threads should appear.
3033 type_in_search(&sidebar, "alpha", cx);
3034 assert_eq!(
3035 visible_entries_as_strings(&sidebar, cx),
3036 vec![
3037 "v [alpha-project]",
3038 " Fix bug in sidebar <== selected",
3039 " Add tests for editor",
3040 ]
3041 );
3042
3043 // Now search for something that matches only a workspace name when there
3044 // are also threads with matching titles — the non-matching workspace's
3045 // threads should still appear if their titles match.
3046 type_in_search(&sidebar, "alp", cx);
3047 assert_eq!(
3048 visible_entries_as_strings(&sidebar, cx),
3049 vec![
3050 "v [alpha-project]",
3051 " Fix bug in sidebar <== selected",
3052 " Add tests for editor",
3053 ]
3054 );
3055 }
3056
3057 #[gpui::test]
3058 async fn test_search_finds_threads_hidden_behind_view_more(cx: &mut TestAppContext) {
3059 let project = init_test_project("/my-project", cx).await;
3060 let (multi_workspace, cx) =
3061 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
3062 let sidebar = setup_sidebar(&multi_workspace, cx);
3063
3064 let path_list = PathList::new(&[std::path::PathBuf::from("/my-project")]);
3065 let thread_store = cx.update(|_window, cx| ThreadStore::global(cx));
3066
3067 // Create 8 threads. The oldest one has a unique name and will be
3068 // behind View More (only 5 shown by default).
3069 for i in 0..8u32 {
3070 let title = if i == 0 {
3071 "Hidden gem thread".to_string()
3072 } else {
3073 format!("Thread {}", i + 1)
3074 };
3075 let save_task = thread_store.update(cx, |store, cx| {
3076 store.save_thread(
3077 acp::SessionId::new(Arc::from(format!("thread-{}", i))),
3078 make_test_thread(
3079 &title,
3080 chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 1, 0, 0, i).unwrap(),
3081 ),
3082 path_list.clone(),
3083 cx,
3084 )
3085 });
3086 save_task.await.unwrap();
3087 }
3088 cx.run_until_parked();
3089
3090 // Confirm the thread is not visible and View More is shown.
3091 let entries = visible_entries_as_strings(&sidebar, cx);
3092 assert!(
3093 entries.iter().any(|e| e.contains("View More")),
3094 "should have View More button"
3095 );
3096 assert!(
3097 !entries.iter().any(|e| e.contains("Hidden gem")),
3098 "Hidden gem should be behind View More"
3099 );
3100
3101 // User searches for the hidden thread — it appears, and View More is gone.
3102 type_in_search(&sidebar, "hidden gem", cx);
3103 let filtered = visible_entries_as_strings(&sidebar, cx);
3104 assert_eq!(
3105 filtered,
3106 vec!["v [my-project]", " Hidden gem thread <== selected",]
3107 );
3108 assert!(
3109 !filtered.iter().any(|e| e.contains("View More")),
3110 "View More should not appear when filtering"
3111 );
3112 }
3113
3114 #[gpui::test]
3115 async fn test_search_finds_threads_inside_collapsed_groups(cx: &mut TestAppContext) {
3116 let project = init_test_project("/my-project", cx).await;
3117 let (multi_workspace, cx) =
3118 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
3119 let sidebar = setup_sidebar(&multi_workspace, cx);
3120
3121 let path_list = PathList::new(&[std::path::PathBuf::from("/my-project")]);
3122 let thread_store = cx.update(|_window, cx| ThreadStore::global(cx));
3123
3124 let save_task = thread_store.update(cx, |store, cx| {
3125 store.save_thread(
3126 acp::SessionId::new(Arc::from("thread-1")),
3127 make_test_thread(
3128 "Important thread",
3129 chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 1, 0, 0, 0).unwrap(),
3130 ),
3131 path_list.clone(),
3132 cx,
3133 )
3134 });
3135 save_task.await.unwrap();
3136 cx.run_until_parked();
3137
3138 // User focuses the sidebar and collapses the group using keyboard:
3139 // manually select the header, then press CollapseSelectedEntry to collapse.
3140 open_and_focus_sidebar(&sidebar, &multi_workspace, cx);
3141 sidebar.update_in(cx, |sidebar, _window, _cx| {
3142 sidebar.selection = Some(0);
3143 });
3144 cx.dispatch_action(CollapseSelectedEntry);
3145 cx.run_until_parked();
3146
3147 assert_eq!(
3148 visible_entries_as_strings(&sidebar, cx),
3149 vec!["> [my-project] <== selected"]
3150 );
3151
3152 // User types a search — the thread appears even though its group is collapsed.
3153 type_in_search(&sidebar, "important", cx);
3154 assert_eq!(
3155 visible_entries_as_strings(&sidebar, cx),
3156 vec!["> [my-project]", " Important thread <== selected",]
3157 );
3158 }
3159
3160 #[gpui::test]
3161 async fn test_search_then_keyboard_navigate_and_confirm(cx: &mut TestAppContext) {
3162 let project = init_test_project("/my-project", cx).await;
3163 let (multi_workspace, cx) =
3164 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
3165 let sidebar = setup_sidebar(&multi_workspace, cx);
3166
3167 let path_list = PathList::new(&[std::path::PathBuf::from("/my-project")]);
3168 let thread_store = cx.update(|_window, cx| ThreadStore::global(cx));
3169
3170 for (id, title, hour) in [
3171 ("t-1", "Fix crash in panel", 3),
3172 ("t-2", "Fix lint warnings", 2),
3173 ("t-3", "Add new feature", 1),
3174 ] {
3175 let save_task = thread_store.update(cx, |store, cx| {
3176 store.save_thread(
3177 acp::SessionId::new(Arc::from(id)),
3178 make_test_thread(
3179 title,
3180 chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 1, hour, 0, 0).unwrap(),
3181 ),
3182 path_list.clone(),
3183 cx,
3184 )
3185 });
3186 save_task.await.unwrap();
3187 }
3188 cx.run_until_parked();
3189
3190 open_and_focus_sidebar(&sidebar, &multi_workspace, cx);
3191
3192 // User types "fix" — two threads match.
3193 type_in_search(&sidebar, "fix", cx);
3194 assert_eq!(
3195 visible_entries_as_strings(&sidebar, cx),
3196 vec![
3197 "v [my-project]",
3198 " Fix crash in panel <== selected",
3199 " Fix lint warnings",
3200 ]
3201 );
3202
3203 // Selection starts on the first matching thread. User presses
3204 // SelectNext to move to the second match.
3205 cx.dispatch_action(SelectNext);
3206 assert_eq!(
3207 visible_entries_as_strings(&sidebar, cx),
3208 vec![
3209 "v [my-project]",
3210 " Fix crash in panel",
3211 " Fix lint warnings <== selected",
3212 ]
3213 );
3214
3215 // User can also jump back with SelectPrevious.
3216 cx.dispatch_action(SelectPrevious);
3217 assert_eq!(
3218 visible_entries_as_strings(&sidebar, cx),
3219 vec![
3220 "v [my-project]",
3221 " Fix crash in panel <== selected",
3222 " Fix lint warnings",
3223 ]
3224 );
3225 }
3226
3227 #[gpui::test]
3228 async fn test_confirm_on_historical_thread_activates_workspace(cx: &mut TestAppContext) {
3229 let project = init_test_project("/my-project", cx).await;
3230 let (multi_workspace, cx) =
3231 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
3232 let sidebar = setup_sidebar(&multi_workspace, cx);
3233
3234 multi_workspace.update_in(cx, |mw, window, cx| {
3235 mw.create_workspace(window, cx);
3236 });
3237 cx.run_until_parked();
3238
3239 let path_list = PathList::new(&[std::path::PathBuf::from("/my-project")]);
3240 let thread_store = cx.update(|_window, cx| ThreadStore::global(cx));
3241
3242 let save_task = thread_store.update(cx, |store, cx| {
3243 store.save_thread(
3244 acp::SessionId::new(Arc::from("hist-1")),
3245 make_test_thread(
3246 "Historical Thread",
3247 chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 6, 1, 0, 0, 0).unwrap(),
3248 ),
3249 path_list.clone(),
3250 cx,
3251 )
3252 });
3253 save_task.await.unwrap();
3254 cx.run_until_parked();
3255 multi_workspace.update_in(cx, |_, _window, cx| cx.notify());
3256 cx.run_until_parked();
3257
3258 assert_eq!(
3259 visible_entries_as_strings(&sidebar, cx),
3260 vec![
3261 "v [my-project]",
3262 " Historical Thread",
3263 "v [Empty Workspace]",
3264 " [+ New Thread]",
3265 ]
3266 );
3267
3268 // Switch to workspace 1 so we can verify the confirm switches back.
3269 multi_workspace.update_in(cx, |mw, window, cx| {
3270 mw.activate_index(1, window, cx);
3271 });
3272 cx.run_until_parked();
3273 assert_eq!(
3274 multi_workspace.read_with(cx, |mw, _| mw.active_workspace_index()),
3275 1
3276 );
3277
3278 // Confirm on the historical (non-live) thread at index 1.
3279 // Before a previous fix, the workspace field was Option<usize> and
3280 // historical threads had None, so activate_thread early-returned
3281 // without switching the workspace.
3282 sidebar.update_in(cx, |sidebar, window, cx| {
3283 sidebar.selection = Some(1);
3284 sidebar.confirm(&Confirm, window, cx);
3285 });
3286 cx.run_until_parked();
3287
3288 assert_eq!(
3289 multi_workspace.read_with(cx, |mw, _| mw.active_workspace_index()),
3290 0
3291 );
3292 }
3293
3294 #[gpui::test]
3295 async fn test_click_clears_selection_and_focus_in_restores_it(cx: &mut TestAppContext) {
3296 let project = init_test_project("/my-project", cx).await;
3297 let (multi_workspace, cx) =
3298 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
3299 let sidebar = setup_sidebar(&multi_workspace, cx);
3300
3301 let path_list = PathList::new(&[std::path::PathBuf::from("/my-project")]);
3302 let thread_store = cx.update(|_window, cx| ThreadStore::global(cx));
3303
3304 let save_task = thread_store.update(cx, |store, cx| {
3305 store.save_thread(
3306 acp::SessionId::new(Arc::from("t-1")),
3307 make_test_thread(
3308 "Thread A",
3309 chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 2, 0, 0, 0).unwrap(),
3310 ),
3311 path_list.clone(),
3312 cx,
3313 )
3314 });
3315 save_task.await.unwrap();
3316 let save_task = thread_store.update(cx, |store, cx| {
3317 store.save_thread(
3318 acp::SessionId::new(Arc::from("t-2")),
3319 make_test_thread(
3320 "Thread B",
3321 chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 1, 0, 0, 0).unwrap(),
3322 ),
3323 path_list.clone(),
3324 cx,
3325 )
3326 });
3327 save_task.await.unwrap();
3328 cx.run_until_parked();
3329 multi_workspace.update_in(cx, |_, _window, cx| cx.notify());
3330 cx.run_until_parked();
3331
3332 assert_eq!(
3333 visible_entries_as_strings(&sidebar, cx),
3334 vec!["v [my-project]", " Thread A", " Thread B",]
3335 );
3336
3337 // Keyboard confirm preserves selection.
3338 sidebar.update_in(cx, |sidebar, window, cx| {
3339 sidebar.selection = Some(1);
3340 sidebar.confirm(&Confirm, window, cx);
3341 });
3342 assert_eq!(
3343 sidebar.read_with(cx, |sidebar, _| sidebar.selection),
3344 Some(1)
3345 );
3346
3347 // Click handlers clear selection to None so no highlight lingers
3348 // after a click regardless of focus state. The hover style provides
3349 // visual feedback during mouse interaction instead.
3350 sidebar.update_in(cx, |sidebar, window, cx| {
3351 sidebar.selection = None;
3352 let path_list = PathList::new(&[std::path::PathBuf::from("/my-project")]);
3353 sidebar.toggle_collapse(&path_list, window, cx);
3354 });
3355 assert_eq!(sidebar.read_with(cx, |sidebar, _| sidebar.selection), None);
3356
3357 // When the user tabs back into the sidebar, focus_in no longer
3358 // restores selection — it stays None.
3359 sidebar.update_in(cx, |sidebar, window, cx| {
3360 sidebar.focus_in(window, cx);
3361 });
3362 assert_eq!(sidebar.read_with(cx, |sidebar, _| sidebar.selection), None);
3363 }
3364
3365 #[gpui::test]
3366 async fn test_thread_title_update_propagates_to_sidebar(cx: &mut TestAppContext) {
3367 let project = init_test_project_with_agent_panel("/my-project", cx).await;
3368 let (multi_workspace, cx) =
3369 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
3370 let (sidebar, panel) = setup_sidebar_with_agent_panel(&multi_workspace, &project, cx);
3371
3372 let path_list = PathList::new(&[std::path::PathBuf::from("/my-project")]);
3373
3374 let connection = StubAgentConnection::new();
3375 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
3376 acp::ContentChunk::new("Hi there!".into()),
3377 )]);
3378 open_thread_with_connection(&panel, connection, cx);
3379 send_message(&panel, cx);
3380
3381 let session_id = active_session_id(&panel, cx);
3382 save_thread_to_store(&session_id, &path_list, cx).await;
3383 cx.run_until_parked();
3384
3385 assert_eq!(
3386 visible_entries_as_strings(&sidebar, cx),
3387 vec!["v [my-project]", " Hello *"]
3388 );
3389
3390 // Simulate the agent generating a title. The notification chain is:
3391 // AcpThread::set_title emits TitleUpdated →
3392 // ConnectionView::handle_thread_event calls cx.notify() →
3393 // AgentPanel observer fires and emits AgentPanelEvent →
3394 // Sidebar subscription calls update_entries / rebuild_contents.
3395 //
3396 // Before the fix, handle_thread_event did NOT call cx.notify() for
3397 // TitleUpdated, so the AgentPanel observer never fired and the
3398 // sidebar kept showing the old title.
3399 let thread = panel.read_with(cx, |panel, cx| panel.active_agent_thread(cx).unwrap());
3400 thread.update(cx, |thread, cx| {
3401 thread
3402 .set_title("Friendly Greeting with AI".into(), cx)
3403 .detach();
3404 });
3405 cx.run_until_parked();
3406
3407 assert_eq!(
3408 visible_entries_as_strings(&sidebar, cx),
3409 vec!["v [my-project]", " Friendly Greeting with AI *"]
3410 );
3411 }
3412
3413 #[gpui::test]
3414 async fn test_focused_thread_tracks_user_intent(cx: &mut TestAppContext) {
3415 let project_a = init_test_project_with_agent_panel("/project-a", cx).await;
3416 let (multi_workspace, cx) = cx
3417 .add_window_view(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
3418 let (sidebar, panel_a) = setup_sidebar_with_agent_panel(&multi_workspace, &project_a, cx);
3419
3420 let path_list_a = PathList::new(&[std::path::PathBuf::from("/project-a")]);
3421
3422 // Save a thread so it appears in the list.
3423 let connection_a = StubAgentConnection::new();
3424 connection_a.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
3425 acp::ContentChunk::new("Done".into()),
3426 )]);
3427 open_thread_with_connection(&panel_a, connection_a, cx);
3428 send_message(&panel_a, cx);
3429 let session_id_a = active_session_id(&panel_a, cx);
3430 save_thread_to_store(&session_id_a, &path_list_a, cx).await;
3431
3432 // Add a second workspace with its own agent panel.
3433 let fs = cx.update(|_, cx| <dyn fs::Fs>::global(cx));
3434 fs.as_fake()
3435 .insert_tree("/project-b", serde_json::json!({ "src": {} }))
3436 .await;
3437 let project_b = project::Project::test(fs, ["/project-b".as_ref()], cx).await;
3438 let workspace_b = multi_workspace.update_in(cx, |mw, window, cx| {
3439 mw.test_add_workspace(project_b.clone(), window, cx)
3440 });
3441 let panel_b = add_agent_panel(&workspace_b, &project_b, cx);
3442 cx.run_until_parked();
3443
3444 let workspace_a = multi_workspace.read_with(cx, |mw, _cx| mw.workspaces()[0].clone());
3445
3446 // ── 1. Initial state: no focused thread ──────────────────────────────
3447 // Workspace B is active (just added), so its header is the active entry.
3448 sidebar.read_with(cx, |sidebar, _cx| {
3449 assert_eq!(
3450 sidebar.focused_thread, None,
3451 "Initially no thread should be focused"
3452 );
3453 let active_entry = sidebar
3454 .active_entry_index
3455 .and_then(|ix| sidebar.contents.entries.get(ix));
3456 assert!(
3457 matches!(active_entry, Some(ListEntry::ProjectHeader { .. })),
3458 "Active entry should be the active workspace header"
3459 );
3460 });
3461
3462 sidebar.update_in(cx, |sidebar, window, cx| {
3463 sidebar.activate_thread(
3464 acp_thread::AgentSessionInfo {
3465 session_id: session_id_a.clone(),
3466 cwd: None,
3467 title: Some("Test".into()),
3468 updated_at: None,
3469 created_at: None,
3470 meta: None,
3471 },
3472 &workspace_a,
3473 window,
3474 cx,
3475 );
3476 });
3477 cx.run_until_parked();
3478
3479 sidebar.read_with(cx, |sidebar, _cx| {
3480 assert_eq!(
3481 sidebar.focused_thread.as_ref(),
3482 Some(&session_id_a),
3483 "After clicking a thread, it should be the focused thread"
3484 );
3485 let active_entry = sidebar.active_entry_index
3486 .and_then(|ix| sidebar.contents.entries.get(ix));
3487 assert!(
3488 matches!(active_entry, Some(ListEntry::Thread(thread)) if thread.session_info.session_id == session_id_a),
3489 "Active entry should be the clicked thread"
3490 );
3491 });
3492
3493 workspace_a.read_with(cx, |workspace, cx| {
3494 assert!(
3495 workspace.panel::<AgentPanel>(cx).is_some(),
3496 "Agent panel should exist"
3497 );
3498 let dock = workspace.right_dock().read(cx);
3499 assert!(
3500 dock.is_open(),
3501 "Clicking a thread should open the agent panel dock"
3502 );
3503 });
3504
3505 let connection_b = StubAgentConnection::new();
3506 connection_b.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
3507 acp::ContentChunk::new("Thread B".into()),
3508 )]);
3509 open_thread_with_connection(&panel_b, connection_b, cx);
3510 send_message(&panel_b, cx);
3511 let session_id_b = active_session_id(&panel_b, cx);
3512 let path_list_b = PathList::new(&[std::path::PathBuf::from("/project-b")]);
3513 save_thread_to_store(&session_id_b, &path_list_b, cx).await;
3514 cx.run_until_parked();
3515
3516 // Workspace A is currently active. Click a thread in workspace B,
3517 // which also triggers a workspace switch.
3518 sidebar.update_in(cx, |sidebar, window, cx| {
3519 sidebar.activate_thread(
3520 acp_thread::AgentSessionInfo {
3521 session_id: session_id_b.clone(),
3522 cwd: None,
3523 title: Some("Thread B".into()),
3524 updated_at: None,
3525 created_at: None,
3526 meta: None,
3527 },
3528 &workspace_b,
3529 window,
3530 cx,
3531 );
3532 });
3533 cx.run_until_parked();
3534
3535 sidebar.read_with(cx, |sidebar, _cx| {
3536 assert_eq!(
3537 sidebar.focused_thread.as_ref(),
3538 Some(&session_id_b),
3539 "Clicking a thread in another workspace should focus that thread"
3540 );
3541 let active_entry = sidebar
3542 .active_entry_index
3543 .and_then(|ix| sidebar.contents.entries.get(ix));
3544 assert!(
3545 matches!(active_entry, Some(ListEntry::Thread(thread)) if thread.session_info.session_id == session_id_b),
3546 "Active entry should be the cross-workspace thread"
3547 );
3548 });
3549
3550 multi_workspace.update_in(cx, |mw, window, cx| {
3551 mw.activate_next_workspace(window, cx);
3552 });
3553 cx.run_until_parked();
3554
3555 sidebar.read_with(cx, |sidebar, _cx| {
3556 assert_eq!(
3557 sidebar.focused_thread, None,
3558 "External workspace switch should clear focused_thread"
3559 );
3560 let active_entry = sidebar
3561 .active_entry_index
3562 .and_then(|ix| sidebar.contents.entries.get(ix));
3563 assert!(
3564 matches!(active_entry, Some(ListEntry::ProjectHeader { .. })),
3565 "Active entry should be the workspace header after external switch"
3566 );
3567 });
3568
3569 let connection_b2 = StubAgentConnection::new();
3570 connection_b2.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
3571 acp::ContentChunk::new("New thread".into()),
3572 )]);
3573 open_thread_with_connection(&panel_b, connection_b2, cx);
3574 send_message(&panel_b, cx);
3575 let session_id_b2 = active_session_id(&panel_b, cx);
3576 save_thread_to_store(&session_id_b2, &path_list_b, cx).await;
3577 cx.run_until_parked();
3578
3579 sidebar.read_with(cx, |sidebar, _cx| {
3580 assert_eq!(
3581 sidebar.focused_thread.as_ref(),
3582 Some(&session_id_b2),
3583 "Opening a thread externally should set focused_thread"
3584 );
3585 });
3586
3587 workspace_b.update_in(cx, |workspace, window, cx| {
3588 workspace.focus_handle(cx).focus(window, cx);
3589 });
3590 cx.run_until_parked();
3591
3592 sidebar.read_with(cx, |sidebar, _cx| {
3593 assert_eq!(
3594 sidebar.focused_thread.as_ref(),
3595 Some(&session_id_b2),
3596 "Defocusing the sidebar should not clear focused_thread"
3597 );
3598 });
3599
3600 sidebar.update_in(cx, |sidebar, window, cx| {
3601 sidebar.activate_workspace(&workspace_b, window, cx);
3602 });
3603 cx.run_until_parked();
3604
3605 sidebar.read_with(cx, |sidebar, _cx| {
3606 assert_eq!(
3607 sidebar.focused_thread, None,
3608 "Clicking a workspace header should clear focused_thread"
3609 );
3610 let active_entry = sidebar
3611 .active_entry_index
3612 .and_then(|ix| sidebar.contents.entries.get(ix));
3613 assert!(
3614 matches!(active_entry, Some(ListEntry::ProjectHeader { .. })),
3615 "Active entry should be the workspace header"
3616 );
3617 });
3618
3619 // ── 8. Focusing the agent panel thread restores focused_thread ────
3620 // Workspace B still has session_id_b2 loaded in the agent panel.
3621 // Clicking into the thread (simulated by focusing its view) should
3622 // set focused_thread via the ThreadFocused event.
3623 panel_b.update_in(cx, |panel, window, cx| {
3624 if let Some(thread_view) = panel.active_connection_view() {
3625 thread_view.read(cx).focus_handle(cx).focus(window, cx);
3626 }
3627 });
3628 cx.run_until_parked();
3629
3630 sidebar.read_with(cx, |sidebar, _cx| {
3631 assert_eq!(
3632 sidebar.focused_thread.as_ref(),
3633 Some(&session_id_b2),
3634 "Focusing the agent panel thread should set focused_thread"
3635 );
3636 let active_entry = sidebar
3637 .active_entry_index
3638 .and_then(|ix| sidebar.contents.entries.get(ix));
3639 assert!(
3640 matches!(active_entry, Some(ListEntry::Thread(thread)) if thread.session_info.session_id == session_id_b2),
3641 "Active entry should be the focused thread"
3642 );
3643 });
3644 }
3645}