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