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