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