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