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