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