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 excluded = [workspace_to_remove.clone()];
2780 let remove_task = multi_workspace.update(cx, |mw, cx| {
2781 mw.remove(
2782 [workspace_to_remove],
2783 move |this, window, cx| {
2784 this.find_or_create_local_workspace(fallback_paths, &excluded, window, cx)
2785 },
2786 window,
2787 cx,
2788 )
2789 });
2790
2791 let neighbor_metadata = neighbor.map(|(metadata, _)| metadata);
2792 let thread_folder_paths = thread_folder_paths.clone();
2793 cx.spawn_in(window, async move |this, cx| {
2794 let removed = remove_task.await?;
2795 if removed {
2796 this.update_in(cx, |this, window, cx| {
2797 let in_flight =
2798 this.start_archive_worktree_task(&session_id, roots_to_archive, cx);
2799 this.archive_and_activate(
2800 &session_id,
2801 neighbor_metadata.as_ref(),
2802 thread_folder_paths.as_ref(),
2803 in_flight,
2804 window,
2805 cx,
2806 );
2807 })?;
2808 }
2809 anyhow::Ok(())
2810 })
2811 .detach_and_log_err(cx);
2812 } else {
2813 // Simple case: no workspace removal needed.
2814 let neighbor_metadata = neighbor.map(|(metadata, _)| metadata);
2815 let in_flight = self.start_archive_worktree_task(session_id, roots_to_archive, cx);
2816 self.archive_and_activate(
2817 session_id,
2818 neighbor_metadata.as_ref(),
2819 thread_folder_paths.as_ref(),
2820 in_flight,
2821 window,
2822 cx,
2823 );
2824 }
2825 }
2826
2827 /// Archive a thread and activate the nearest neighbor or a draft.
2828 ///
2829 /// IMPORTANT: when activating a neighbor or creating a fallback draft,
2830 /// this method also activates the target workspace in the MultiWorkspace.
2831 /// This is critical because `rebuild_contents` derives the active
2832 /// workspace from `mw.workspace()`. If the linked worktree workspace is
2833 /// still active after archiving its last thread, `rebuild_contents` sees
2834 /// the threadless linked worktree as active and emits a spurious
2835 /// "+ New Thread" entry with the worktree chip — keeping the worktree
2836 /// alive and preventing disk cleanup.
2837 ///
2838 /// When `in_flight_archive` is present, it is the background task that
2839 /// persists the linked worktree's git state and deletes it from disk.
2840 /// We attach it to the metadata store at the same time we mark the thread
2841 /// archived so failures can automatically unarchive the thread and user-
2842 /// initiated unarchive can cancel the task.
2843 fn archive_and_activate(
2844 &mut self,
2845 session_id: &acp::SessionId,
2846 neighbor: Option<&ThreadMetadata>,
2847 thread_folder_paths: Option<&PathList>,
2848 in_flight_archive: Option<(Task<()>, smol::channel::Sender<()>)>,
2849 window: &mut Window,
2850 cx: &mut Context<Self>,
2851 ) {
2852 ThreadMetadataStore::global(cx).update(cx, |store, cx| {
2853 store.archive(session_id, in_flight_archive, cx);
2854 });
2855
2856 let is_active = self
2857 .active_entry
2858 .as_ref()
2859 .is_some_and(|e| e.is_active_thread(session_id));
2860
2861 if !is_active {
2862 // The user is looking at a different thread/draft. Clear the
2863 // archived thread from its workspace's panel so that switching
2864 // to that workspace later doesn't show a stale thread.
2865 if let Some(folder_paths) = thread_folder_paths {
2866 if let Some(workspace) = self
2867 .multi_workspace
2868 .upgrade()
2869 .and_then(|mw| mw.read(cx).workspace_for_paths(folder_paths, None, cx))
2870 {
2871 if let Some(panel) = workspace.read(cx).panel::<AgentPanel>(cx) {
2872 let panel_shows_archived = panel
2873 .read(cx)
2874 .active_conversation_view()
2875 .and_then(|cv| cv.read(cx).parent_id(cx))
2876 .is_some_and(|id| id == *session_id);
2877 if panel_shows_archived {
2878 panel.update(cx, |panel, cx| {
2879 panel.clear_active_thread(window, cx);
2880 });
2881 }
2882 }
2883 }
2884 }
2885 return;
2886 }
2887
2888 // Try to activate the neighbor thread. If its workspace is open,
2889 // tell the panel to load it and activate that workspace.
2890 // `rebuild_contents` will reconcile `active_entry` once the thread
2891 // finishes loading.
2892 if let Some(metadata) = neighbor {
2893 if let Some(workspace) = self.multi_workspace.upgrade().and_then(|mw| {
2894 mw.read(cx)
2895 .workspace_for_paths(&metadata.folder_paths, None, cx)
2896 }) {
2897 self.activate_workspace(&workspace, window, cx);
2898 Self::load_agent_thread_in_workspace(&workspace, metadata, true, window, cx);
2899 return;
2900 }
2901 }
2902
2903 // No neighbor or its workspace isn't open — fall back to a new
2904 // draft. Use the group workspace (main project) rather than the
2905 // active entry workspace, which may be a linked worktree that is
2906 // about to be cleaned up.
2907 let fallback_workspace = thread_folder_paths
2908 .and_then(|folder_paths| {
2909 let mw = self.multi_workspace.upgrade()?;
2910 let mw = mw.read(cx);
2911 // Find the group's main workspace (whose root paths match
2912 // the project group key, not the thread's folder paths).
2913 let thread_workspace = mw.workspace_for_paths(folder_paths, None, cx)?;
2914 let group_key = thread_workspace.read(cx).project_group_key(cx);
2915 mw.workspace_for_paths(group_key.path_list(), None, cx)
2916 })
2917 .or_else(|| self.active_entry_workspace().cloned());
2918
2919 if let Some(workspace) = fallback_workspace {
2920 self.activate_workspace(&workspace, window, cx);
2921 if let Some(panel) = workspace.read(cx).panel::<AgentPanel>(cx) {
2922 panel.update(cx, |panel, cx| {
2923 panel.new_thread(&NewThread, window, cx);
2924 });
2925 }
2926 }
2927 }
2928
2929 fn start_archive_worktree_task(
2930 &self,
2931 session_id: &acp::SessionId,
2932 roots: Vec<thread_worktree_archive::RootPlan>,
2933 cx: &mut Context<Self>,
2934 ) -> Option<(Task<()>, smol::channel::Sender<()>)> {
2935 if roots.is_empty() {
2936 return None;
2937 }
2938
2939 let (cancel_tx, cancel_rx) = smol::channel::bounded::<()>(1);
2940 let session_id = session_id.clone();
2941 let task = cx.spawn(async move |_this, cx| {
2942 match Self::archive_worktree_roots(roots, cancel_rx, cx).await {
2943 Ok(ArchiveWorktreeOutcome::Success) => {
2944 cx.update(|cx| {
2945 ThreadMetadataStore::global(cx).update(cx, |store, _cx| {
2946 store.cleanup_completed_archive(&session_id);
2947 });
2948 });
2949 }
2950 Ok(ArchiveWorktreeOutcome::Cancelled) => {}
2951 Err(error) => {
2952 log::error!("Failed to archive worktree: {error:#}");
2953 cx.update(|cx| {
2954 ThreadMetadataStore::global(cx).update(cx, |store, cx| {
2955 store.unarchive(&session_id, cx);
2956 });
2957 });
2958 }
2959 }
2960 });
2961
2962 Some((task, cancel_tx))
2963 }
2964
2965 async fn archive_worktree_roots(
2966 roots: Vec<thread_worktree_archive::RootPlan>,
2967 cancel_rx: smol::channel::Receiver<()>,
2968 cx: &mut gpui::AsyncApp,
2969 ) -> anyhow::Result<ArchiveWorktreeOutcome> {
2970 let mut completed_persists: Vec<(i64, thread_worktree_archive::RootPlan)> = Vec::new();
2971
2972 for root in &roots {
2973 if cancel_rx.is_closed() {
2974 for &(id, ref completed_root) in completed_persists.iter().rev() {
2975 thread_worktree_archive::rollback_persist(id, completed_root, cx).await;
2976 }
2977 return Ok(ArchiveWorktreeOutcome::Cancelled);
2978 }
2979
2980 if root.worktree_repo.is_some() {
2981 match thread_worktree_archive::persist_worktree_state(root, cx).await {
2982 Ok(id) => {
2983 completed_persists.push((id, root.clone()));
2984 }
2985 Err(error) => {
2986 for &(id, ref completed_root) in completed_persists.iter().rev() {
2987 thread_worktree_archive::rollback_persist(id, completed_root, cx).await;
2988 }
2989 return Err(error);
2990 }
2991 }
2992 }
2993
2994 if cancel_rx.is_closed() {
2995 for &(id, ref completed_root) in completed_persists.iter().rev() {
2996 thread_worktree_archive::rollback_persist(id, completed_root, cx).await;
2997 }
2998 return Ok(ArchiveWorktreeOutcome::Cancelled);
2999 }
3000
3001 if let Err(error) = thread_worktree_archive::remove_root(root.clone(), cx).await {
3002 if let Some(&(id, ref completed_root)) = completed_persists.last() {
3003 if completed_root.root_path == root.root_path {
3004 thread_worktree_archive::rollback_persist(id, completed_root, cx).await;
3005 completed_persists.pop();
3006 }
3007 }
3008 for &(id, ref completed_root) in completed_persists.iter().rev() {
3009 thread_worktree_archive::rollback_persist(id, completed_root, cx).await;
3010 }
3011 return Err(error);
3012 }
3013 }
3014
3015 Ok(ArchiveWorktreeOutcome::Success)
3016 }
3017
3018 fn activate_workspace(
3019 &self,
3020 workspace: &Entity<Workspace>,
3021 window: &mut Window,
3022 cx: &mut Context<Self>,
3023 ) {
3024 if let Some(multi_workspace) = self.multi_workspace.upgrade() {
3025 multi_workspace.update(cx, |mw, cx| {
3026 mw.activate(workspace.clone(), window, cx);
3027 });
3028 }
3029 }
3030
3031 fn remove_selected_thread(
3032 &mut self,
3033 _: &RemoveSelectedThread,
3034 window: &mut Window,
3035 cx: &mut Context<Self>,
3036 ) {
3037 let Some(ix) = self.selection else {
3038 return;
3039 };
3040 match self.contents.entries.get(ix) {
3041 Some(ListEntry::Thread(thread)) => {
3042 match thread.status {
3043 AgentThreadStatus::Running | AgentThreadStatus::WaitingForConfirmation => {
3044 return;
3045 }
3046 AgentThreadStatus::Completed | AgentThreadStatus::Error => {}
3047 }
3048 let session_id = thread.metadata.session_id.clone();
3049 self.archive_thread(&session_id, window, cx);
3050 }
3051 Some(ListEntry::DraftThread {
3052 workspace: Some(workspace),
3053 ..
3054 }) => {
3055 self.remove_worktree_workspace(workspace.clone(), window, cx);
3056 }
3057 _ => {}
3058 }
3059 }
3060
3061 fn remove_worktree_workspace(
3062 &mut self,
3063 workspace: Entity<Workspace>,
3064 window: &mut Window,
3065 cx: &mut Context<Self>,
3066 ) {
3067 if let Some(multi_workspace) = self.multi_workspace.upgrade() {
3068 multi_workspace
3069 .update(cx, |mw, cx| {
3070 mw.remove(
3071 [workspace],
3072 |this, _window, _cx| gpui::Task::ready(Ok(this.workspace().clone())),
3073 window,
3074 cx,
3075 )
3076 })
3077 .detach_and_log_err(cx);
3078 }
3079 }
3080
3081 fn record_thread_access(&mut self, session_id: &acp::SessionId) {
3082 self.thread_last_accessed
3083 .insert(session_id.clone(), Utc::now());
3084 }
3085
3086 fn record_thread_message_sent(&mut self, session_id: &acp::SessionId) {
3087 self.thread_last_message_sent_or_queued
3088 .insert(session_id.clone(), Utc::now());
3089 }
3090
3091 fn mru_threads_for_switcher(&self, cx: &App) -> Vec<ThreadSwitcherEntry> {
3092 let mut current_header_label: Option<SharedString> = None;
3093 let mut current_header_key: Option<ProjectGroupKey> = None;
3094 let mut entries: Vec<ThreadSwitcherEntry> = self
3095 .contents
3096 .entries
3097 .iter()
3098 .filter_map(|entry| match entry {
3099 ListEntry::ProjectHeader { label, key, .. } => {
3100 current_header_label = Some(label.clone());
3101 current_header_key = Some(key.clone());
3102 None
3103 }
3104 ListEntry::Thread(thread) => {
3105 let workspace = match &thread.workspace {
3106 ThreadEntryWorkspace::Open(workspace) => Some(workspace.clone()),
3107 ThreadEntryWorkspace::Closed { .. } => {
3108 current_header_key.as_ref().and_then(|key| {
3109 self.multi_workspace.upgrade().and_then(|mw| {
3110 mw.read(cx).workspace_for_paths(
3111 key.path_list(),
3112 key.host().as_ref(),
3113 cx,
3114 )
3115 })
3116 })
3117 }
3118 }?;
3119 let notified = self
3120 .contents
3121 .is_thread_notified(&thread.metadata.session_id);
3122 let timestamp: SharedString = format_history_entry_timestamp(
3123 self.thread_last_message_sent_or_queued
3124 .get(&thread.metadata.session_id)
3125 .copied()
3126 .or(thread.metadata.created_at)
3127 .unwrap_or(thread.metadata.updated_at),
3128 )
3129 .into();
3130 Some(ThreadSwitcherEntry {
3131 session_id: thread.metadata.session_id.clone(),
3132 title: thread.metadata.title.clone(),
3133 icon: thread.icon,
3134 icon_from_external_svg: thread.icon_from_external_svg.clone(),
3135 status: thread.status,
3136 metadata: thread.metadata.clone(),
3137 workspace,
3138 project_name: current_header_label.clone(),
3139 worktrees: thread
3140 .worktrees
3141 .iter()
3142 .map(|wt| ThreadItemWorktreeInfo {
3143 name: wt.name.clone(),
3144 full_path: wt.full_path.clone(),
3145 highlight_positions: Vec::new(),
3146 kind: wt.kind,
3147 })
3148 .collect(),
3149 diff_stats: thread.diff_stats,
3150 is_title_generating: thread.is_title_generating,
3151 notified,
3152 timestamp,
3153 })
3154 }
3155 _ => None,
3156 })
3157 .collect();
3158
3159 entries.sort_by(|a, b| {
3160 let a_accessed = self.thread_last_accessed.get(&a.session_id);
3161 let b_accessed = self.thread_last_accessed.get(&b.session_id);
3162
3163 match (a_accessed, b_accessed) {
3164 (Some(a_time), Some(b_time)) => b_time.cmp(a_time),
3165 (Some(_), None) => std::cmp::Ordering::Less,
3166 (None, Some(_)) => std::cmp::Ordering::Greater,
3167 (None, None) => {
3168 let a_sent = self.thread_last_message_sent_or_queued.get(&a.session_id);
3169 let b_sent = self.thread_last_message_sent_or_queued.get(&b.session_id);
3170
3171 match (a_sent, b_sent) {
3172 (Some(a_time), Some(b_time)) => b_time.cmp(a_time),
3173 (Some(_), None) => std::cmp::Ordering::Less,
3174 (None, Some(_)) => std::cmp::Ordering::Greater,
3175 (None, None) => {
3176 let a_time = a.metadata.created_at.or(Some(a.metadata.updated_at));
3177 let b_time = b.metadata.created_at.or(Some(b.metadata.updated_at));
3178 b_time.cmp(&a_time)
3179 }
3180 }
3181 }
3182 }
3183 });
3184
3185 entries
3186 }
3187
3188 fn dismiss_thread_switcher(&mut self, cx: &mut Context<Self>) {
3189 self.thread_switcher = None;
3190 self._thread_switcher_subscriptions.clear();
3191 if let Some(mw) = self.multi_workspace.upgrade() {
3192 mw.update(cx, |mw, cx| {
3193 mw.set_sidebar_overlay(None, cx);
3194 });
3195 }
3196 }
3197
3198 fn on_toggle_thread_switcher(
3199 &mut self,
3200 action: &ToggleThreadSwitcher,
3201 window: &mut Window,
3202 cx: &mut Context<Self>,
3203 ) {
3204 self.toggle_thread_switcher_impl(action.select_last, window, cx);
3205 }
3206
3207 fn toggle_thread_switcher_impl(
3208 &mut self,
3209 select_last: bool,
3210 window: &mut Window,
3211 cx: &mut Context<Self>,
3212 ) {
3213 if let Some(thread_switcher) = &self.thread_switcher {
3214 thread_switcher.update(cx, |switcher, cx| {
3215 if select_last {
3216 switcher.select_last(cx);
3217 } else {
3218 switcher.cycle_selection(cx);
3219 }
3220 });
3221 return;
3222 }
3223
3224 let entries = self.mru_threads_for_switcher(cx);
3225 if entries.len() < 2 {
3226 return;
3227 }
3228
3229 let weak_multi_workspace = self.multi_workspace.clone();
3230
3231 let original_metadata = match &self.active_entry {
3232 Some(ActiveEntry::Thread { session_id, .. }) => entries
3233 .iter()
3234 .find(|e| &e.session_id == session_id)
3235 .map(|e| e.metadata.clone()),
3236 _ => None,
3237 };
3238 let original_workspace = self
3239 .multi_workspace
3240 .upgrade()
3241 .map(|mw| mw.read(cx).workspace().clone());
3242
3243 let thread_switcher = cx.new(|cx| ThreadSwitcher::new(entries, select_last, window, cx));
3244
3245 let mut subscriptions = Vec::new();
3246
3247 subscriptions.push(cx.subscribe_in(&thread_switcher, window, {
3248 let thread_switcher = thread_switcher.clone();
3249 move |this, _emitter, event: &ThreadSwitcherEvent, window, cx| match event {
3250 ThreadSwitcherEvent::Preview {
3251 metadata,
3252 workspace,
3253 } => {
3254 if let Some(mw) = weak_multi_workspace.upgrade() {
3255 mw.update(cx, |mw, cx| {
3256 mw.activate(workspace.clone(), window, cx);
3257 });
3258 }
3259 this.active_entry = Some(ActiveEntry::Thread {
3260 session_id: metadata.session_id.clone(),
3261 workspace: workspace.clone(),
3262 });
3263 this.update_entries(cx);
3264 Self::load_agent_thread_in_workspace(workspace, metadata, false, window, cx);
3265 let focus = thread_switcher.focus_handle(cx);
3266 window.focus(&focus, cx);
3267 }
3268 ThreadSwitcherEvent::Confirmed {
3269 metadata,
3270 workspace,
3271 } => {
3272 if let Some(mw) = weak_multi_workspace.upgrade() {
3273 mw.update(cx, |mw, cx| {
3274 mw.activate(workspace.clone(), window, cx);
3275 mw.retain_active_workspace(cx);
3276 });
3277 }
3278 this.record_thread_access(&metadata.session_id);
3279 this.active_entry = Some(ActiveEntry::Thread {
3280 session_id: metadata.session_id.clone(),
3281 workspace: workspace.clone(),
3282 });
3283 this.update_entries(cx);
3284 Self::load_agent_thread_in_workspace(workspace, metadata, false, window, cx);
3285 this.dismiss_thread_switcher(cx);
3286 workspace.update(cx, |workspace, cx| {
3287 workspace.focus_panel::<AgentPanel>(window, cx);
3288 });
3289 }
3290 ThreadSwitcherEvent::Dismissed => {
3291 if let Some(mw) = weak_multi_workspace.upgrade() {
3292 if let Some(original_ws) = &original_workspace {
3293 mw.update(cx, |mw, cx| {
3294 mw.activate(original_ws.clone(), window, cx);
3295 });
3296 }
3297 }
3298 if let Some(metadata) = &original_metadata {
3299 if let Some(original_ws) = &original_workspace {
3300 this.active_entry = Some(ActiveEntry::Thread {
3301 session_id: metadata.session_id.clone(),
3302 workspace: original_ws.clone(),
3303 });
3304 }
3305 this.update_entries(cx);
3306 if let Some(original_ws) = &original_workspace {
3307 Self::load_agent_thread_in_workspace(
3308 original_ws,
3309 metadata,
3310 false,
3311 window,
3312 cx,
3313 );
3314 }
3315 }
3316 this.dismiss_thread_switcher(cx);
3317 }
3318 }
3319 }));
3320
3321 subscriptions.push(cx.subscribe_in(
3322 &thread_switcher,
3323 window,
3324 |this, _emitter, _event: &gpui::DismissEvent, _window, cx| {
3325 this.dismiss_thread_switcher(cx);
3326 },
3327 ));
3328
3329 let focus = thread_switcher.focus_handle(cx);
3330 let overlay_view = gpui::AnyView::from(thread_switcher.clone());
3331
3332 // Replay the initial preview that was emitted during construction
3333 // before subscriptions were wired up.
3334 let initial_preview = thread_switcher
3335 .read(cx)
3336 .selected_entry()
3337 .map(|entry| (entry.metadata.clone(), entry.workspace.clone()));
3338
3339 self.thread_switcher = Some(thread_switcher);
3340 self._thread_switcher_subscriptions = subscriptions;
3341 if let Some(mw) = self.multi_workspace.upgrade() {
3342 mw.update(cx, |mw, cx| {
3343 mw.set_sidebar_overlay(Some(overlay_view), cx);
3344 });
3345 }
3346
3347 if let Some((metadata, workspace)) = initial_preview {
3348 if let Some(mw) = self.multi_workspace.upgrade() {
3349 mw.update(cx, |mw, cx| {
3350 mw.activate(workspace.clone(), window, cx);
3351 });
3352 }
3353 self.active_entry = Some(ActiveEntry::Thread {
3354 session_id: metadata.session_id.clone(),
3355 workspace: workspace.clone(),
3356 });
3357 self.update_entries(cx);
3358 Self::load_agent_thread_in_workspace(&workspace, &metadata, false, window, cx);
3359 }
3360
3361 window.focus(&focus, cx);
3362 }
3363
3364 fn render_thread(
3365 &self,
3366 ix: usize,
3367 thread: &ThreadEntry,
3368 is_active: bool,
3369 is_focused: bool,
3370 cx: &mut Context<Self>,
3371 ) -> AnyElement {
3372 let has_notification = self
3373 .contents
3374 .is_thread_notified(&thread.metadata.session_id);
3375
3376 let title: SharedString = thread.metadata.title.clone();
3377 let metadata = thread.metadata.clone();
3378 let thread_workspace = thread.workspace.clone();
3379
3380 let is_hovered = self.hovered_thread_index == Some(ix);
3381 let is_selected = is_active;
3382 let is_running = matches!(
3383 thread.status,
3384 AgentThreadStatus::Running | AgentThreadStatus::WaitingForConfirmation
3385 );
3386
3387 let session_id_for_delete = thread.metadata.session_id.clone();
3388 let focus_handle = self.focus_handle.clone();
3389
3390 let id = SharedString::from(format!("thread-entry-{}", ix));
3391
3392 let color = cx.theme().colors();
3393 let sidebar_bg = color
3394 .title_bar_background
3395 .blend(color.panel_background.opacity(0.25));
3396
3397 let timestamp = format_history_entry_timestamp(
3398 self.thread_last_message_sent_or_queued
3399 .get(&thread.metadata.session_id)
3400 .copied()
3401 .or(thread.metadata.created_at)
3402 .unwrap_or(thread.metadata.updated_at),
3403 );
3404
3405 let is_remote = thread.workspace.is_remote(cx);
3406
3407 ThreadItem::new(id, title)
3408 .base_bg(sidebar_bg)
3409 .icon(thread.icon)
3410 .status(thread.status)
3411 .is_remote(is_remote)
3412 .when_some(thread.icon_from_external_svg.clone(), |this, svg| {
3413 this.custom_icon_from_external_svg(svg)
3414 })
3415 .worktrees(
3416 thread
3417 .worktrees
3418 .iter()
3419 .map(|wt| ThreadItemWorktreeInfo {
3420 name: wt.name.clone(),
3421 full_path: wt.full_path.clone(),
3422 highlight_positions: wt.highlight_positions.clone(),
3423 kind: wt.kind,
3424 })
3425 .collect(),
3426 )
3427 .timestamp(timestamp)
3428 .highlight_positions(thread.highlight_positions.to_vec())
3429 .title_generating(thread.is_title_generating)
3430 .notified(has_notification)
3431 .when(thread.diff_stats.lines_added > 0, |this| {
3432 this.added(thread.diff_stats.lines_added as usize)
3433 })
3434 .when(thread.diff_stats.lines_removed > 0, |this| {
3435 this.removed(thread.diff_stats.lines_removed as usize)
3436 })
3437 .selected(is_selected)
3438 .focused(is_focused)
3439 .hovered(is_hovered)
3440 .on_hover(cx.listener(move |this, is_hovered: &bool, _window, cx| {
3441 if *is_hovered {
3442 this.hovered_thread_index = Some(ix);
3443 } else if this.hovered_thread_index == Some(ix) {
3444 this.hovered_thread_index = None;
3445 }
3446 cx.notify();
3447 }))
3448 .when(is_hovered && is_running, |this| {
3449 this.action_slot(
3450 IconButton::new("stop-thread", IconName::Stop)
3451 .icon_size(IconSize::Small)
3452 .icon_color(Color::Error)
3453 .style(ButtonStyle::Tinted(TintColor::Error))
3454 .tooltip(Tooltip::text("Stop Generation"))
3455 .on_click({
3456 let session_id = session_id_for_delete.clone();
3457 cx.listener(move |this, _, _window, cx| {
3458 this.stop_thread(&session_id, cx);
3459 })
3460 }),
3461 )
3462 })
3463 .when(is_hovered && !is_running, |this| {
3464 this.action_slot(
3465 IconButton::new("archive-thread", IconName::Archive)
3466 .icon_size(IconSize::Small)
3467 .icon_color(Color::Muted)
3468 .tooltip({
3469 let focus_handle = focus_handle.clone();
3470 move |_window, cx| {
3471 Tooltip::for_action_in(
3472 "Archive Thread",
3473 &RemoveSelectedThread,
3474 &focus_handle,
3475 cx,
3476 )
3477 }
3478 })
3479 .on_click({
3480 let session_id = session_id_for_delete.clone();
3481 cx.listener(move |this, _, window, cx| {
3482 this.archive_thread(&session_id, window, cx);
3483 })
3484 }),
3485 )
3486 })
3487 .on_click({
3488 cx.listener(move |this, _, window, cx| {
3489 this.selection = None;
3490 match &thread_workspace {
3491 ThreadEntryWorkspace::Open(workspace) => {
3492 this.activate_thread(metadata.clone(), workspace, false, window, cx);
3493 }
3494 ThreadEntryWorkspace::Closed {
3495 folder_paths,
3496 project_group_key,
3497 } => {
3498 this.open_workspace_and_activate_thread(
3499 metadata.clone(),
3500 folder_paths.clone(),
3501 project_group_key,
3502 window,
3503 cx,
3504 );
3505 }
3506 }
3507 })
3508 })
3509 .into_any_element()
3510 }
3511
3512 fn render_filter_input(&self, cx: &mut Context<Self>) -> impl IntoElement {
3513 div()
3514 .min_w_0()
3515 .flex_1()
3516 .capture_action(
3517 cx.listener(|this, _: &editor::actions::Newline, window, cx| {
3518 this.editor_confirm(window, cx);
3519 }),
3520 )
3521 .child(self.filter_editor.clone())
3522 }
3523
3524 fn render_recent_projects_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
3525 let multi_workspace = self.multi_workspace.upgrade();
3526
3527 let workspace = multi_workspace
3528 .as_ref()
3529 .map(|mw| mw.read(cx).workspace().downgrade());
3530
3531 let focus_handle = workspace
3532 .as_ref()
3533 .and_then(|ws| ws.upgrade())
3534 .map(|w| w.read(cx).focus_handle(cx))
3535 .unwrap_or_else(|| cx.focus_handle());
3536
3537 let window_project_groups: Vec<ProjectGroupKey> = multi_workspace
3538 .as_ref()
3539 .map(|mw| mw.read(cx).project_group_keys().cloned().collect())
3540 .unwrap_or_default();
3541
3542 let popover_handle = self.recent_projects_popover_handle.clone();
3543
3544 PopoverMenu::new("sidebar-recent-projects-menu")
3545 .with_handle(popover_handle)
3546 .menu(move |window, cx| {
3547 workspace.as_ref().map(|ws| {
3548 SidebarRecentProjects::popover(
3549 ws.clone(),
3550 window_project_groups.clone(),
3551 focus_handle.clone(),
3552 window,
3553 cx,
3554 )
3555 })
3556 })
3557 .trigger_with_tooltip(
3558 IconButton::new("open-project", IconName::OpenFolder)
3559 .icon_size(IconSize::Small)
3560 .selected_style(ButtonStyle::Tinted(TintColor::Accent)),
3561 |_window, cx| {
3562 Tooltip::for_action(
3563 "Add Project",
3564 &OpenRecent {
3565 create_new_window: false,
3566 },
3567 cx,
3568 )
3569 },
3570 )
3571 .offset(gpui::Point {
3572 x: px(-2.0),
3573 y: px(-2.0),
3574 })
3575 .anchor(gpui::Corner::BottomRight)
3576 }
3577
3578 fn render_view_more(
3579 &self,
3580 ix: usize,
3581 key: &ProjectGroupKey,
3582 is_fully_expanded: bool,
3583 is_selected: bool,
3584 cx: &mut Context<Self>,
3585 ) -> AnyElement {
3586 let key = key.clone();
3587 let id = SharedString::from(format!("view-more-{}", ix));
3588
3589 let label: SharedString = if is_fully_expanded {
3590 "Collapse".into()
3591 } else {
3592 "View More".into()
3593 };
3594
3595 ThreadItem::new(id, label)
3596 .focused(is_selected)
3597 .icon_visible(false)
3598 .title_label_color(Color::Muted)
3599 .on_click(cx.listener(move |this, _, _window, cx| {
3600 this.selection = None;
3601 if is_fully_expanded {
3602 this.reset_thread_group_expansion(&key, cx);
3603 } else {
3604 this.expand_thread_group(&key, cx);
3605 }
3606 }))
3607 .into_any_element()
3608 }
3609
3610 fn new_thread_in_group(
3611 &mut self,
3612 _: &NewThreadInGroup,
3613 window: &mut Window,
3614 cx: &mut Context<Self>,
3615 ) {
3616 // If there is a keyboard selection, walk backwards through
3617 // `project_header_indices` to find the header that owns the selected
3618 // row. Otherwise fall back to the active workspace.
3619 let workspace = if let Some(selected_ix) = self.selection {
3620 self.contents
3621 .project_header_indices
3622 .iter()
3623 .rev()
3624 .find(|&&header_ix| header_ix <= selected_ix)
3625 .and_then(|&header_ix| match &self.contents.entries[header_ix] {
3626 ListEntry::ProjectHeader { key, .. } => {
3627 self.multi_workspace.upgrade().and_then(|mw| {
3628 mw.read(cx).workspace_for_paths(
3629 key.path_list(),
3630 key.host().as_ref(),
3631 cx,
3632 )
3633 })
3634 }
3635 _ => None,
3636 })
3637 } else {
3638 // Use the currently active workspace.
3639 self.multi_workspace
3640 .upgrade()
3641 .map(|mw| mw.read(cx).workspace().clone())
3642 };
3643
3644 let Some(workspace) = workspace else {
3645 return;
3646 };
3647
3648 self.create_new_thread(&workspace, window, cx);
3649 }
3650
3651 fn create_new_thread(
3652 &mut self,
3653 workspace: &Entity<Workspace>,
3654 window: &mut Window,
3655 cx: &mut Context<Self>,
3656 ) {
3657 let Some(multi_workspace) = self.multi_workspace.upgrade() else {
3658 return;
3659 };
3660
3661 self.active_entry = Some(ActiveEntry::Draft(workspace.clone()));
3662
3663 multi_workspace.update(cx, |multi_workspace, cx| {
3664 multi_workspace.activate(workspace.clone(), window, cx);
3665 });
3666
3667 workspace.update(cx, |workspace, cx| {
3668 if let Some(agent_panel) = workspace.panel::<AgentPanel>(cx) {
3669 agent_panel.update(cx, |panel, cx| {
3670 panel.new_thread(&NewThread, window, cx);
3671 });
3672 }
3673 workspace.focus_panel::<AgentPanel>(window, cx);
3674 });
3675 }
3676
3677 fn active_project_group_key(&self, cx: &App) -> Option<ProjectGroupKey> {
3678 let multi_workspace = self.multi_workspace.upgrade()?;
3679 let multi_workspace = multi_workspace.read(cx);
3680 Some(multi_workspace.project_group_key_for_workspace(multi_workspace.workspace(), cx))
3681 }
3682
3683 fn active_project_header_position(&self, cx: &App) -> Option<usize> {
3684 let active_key = self.active_project_group_key(cx)?;
3685 self.contents
3686 .project_header_indices
3687 .iter()
3688 .position(|&entry_ix| {
3689 matches!(
3690 &self.contents.entries[entry_ix],
3691 ListEntry::ProjectHeader { key, .. } if *key == active_key
3692 )
3693 })
3694 }
3695
3696 fn cycle_project_impl(&mut self, forward: bool, window: &mut Window, cx: &mut Context<Self>) {
3697 let Some(multi_workspace) = self.multi_workspace.upgrade() else {
3698 return;
3699 };
3700
3701 let header_count = self.contents.project_header_indices.len();
3702 if header_count == 0 {
3703 return;
3704 }
3705
3706 let current_pos = self.active_project_header_position(cx);
3707
3708 let next_pos = match current_pos {
3709 Some(pos) => {
3710 if forward {
3711 (pos + 1) % header_count
3712 } else {
3713 (pos + header_count - 1) % header_count
3714 }
3715 }
3716 None => 0,
3717 };
3718
3719 let header_entry_ix = self.contents.project_header_indices[next_pos];
3720 let Some(ListEntry::ProjectHeader { key, .. }) = self.contents.entries.get(header_entry_ix)
3721 else {
3722 return;
3723 };
3724 let key = key.clone();
3725
3726 // Uncollapse the target group so that threads become visible.
3727 self.collapsed_groups.remove(&key);
3728
3729 if let Some(workspace) = self.multi_workspace.upgrade().and_then(|mw| {
3730 mw.read(cx)
3731 .workspace_for_paths(key.path_list(), key.host().as_ref(), cx)
3732 }) {
3733 multi_workspace.update(cx, |multi_workspace, cx| {
3734 multi_workspace.activate(workspace, window, cx);
3735 multi_workspace.retain_active_workspace(cx);
3736 });
3737 } else {
3738 self.open_workspace_for_group(&key, window, cx);
3739 }
3740 }
3741
3742 fn on_next_project(&mut self, _: &NextProject, window: &mut Window, cx: &mut Context<Self>) {
3743 self.cycle_project_impl(true, window, cx);
3744 }
3745
3746 fn on_previous_project(
3747 &mut self,
3748 _: &PreviousProject,
3749 window: &mut Window,
3750 cx: &mut Context<Self>,
3751 ) {
3752 self.cycle_project_impl(false, window, cx);
3753 }
3754
3755 fn cycle_thread_impl(&mut self, forward: bool, window: &mut Window, cx: &mut Context<Self>) {
3756 let thread_indices: Vec<usize> = self
3757 .contents
3758 .entries
3759 .iter()
3760 .enumerate()
3761 .filter_map(|(ix, entry)| match entry {
3762 ListEntry::Thread(_) => Some(ix),
3763 _ => None,
3764 })
3765 .collect();
3766
3767 if thread_indices.is_empty() {
3768 return;
3769 }
3770
3771 let current_thread_pos = self.active_entry.as_ref().and_then(|active| {
3772 thread_indices
3773 .iter()
3774 .position(|&ix| active.matches_entry(&self.contents.entries[ix]))
3775 });
3776
3777 let next_pos = match current_thread_pos {
3778 Some(pos) => {
3779 let count = thread_indices.len();
3780 if forward {
3781 (pos + 1) % count
3782 } else {
3783 (pos + count - 1) % count
3784 }
3785 }
3786 None => 0,
3787 };
3788
3789 let entry_ix = thread_indices[next_pos];
3790 let ListEntry::Thread(thread) = &self.contents.entries[entry_ix] else {
3791 return;
3792 };
3793
3794 let metadata = thread.metadata.clone();
3795 match &thread.workspace {
3796 ThreadEntryWorkspace::Open(workspace) => {
3797 let workspace = workspace.clone();
3798 self.activate_thread(metadata, &workspace, true, window, cx);
3799 }
3800 ThreadEntryWorkspace::Closed {
3801 folder_paths,
3802 project_group_key,
3803 } => {
3804 let folder_paths = folder_paths.clone();
3805 let project_group_key = project_group_key.clone();
3806 self.open_workspace_and_activate_thread(
3807 metadata,
3808 folder_paths,
3809 &project_group_key,
3810 window,
3811 cx,
3812 );
3813 }
3814 }
3815 }
3816
3817 fn on_next_thread(&mut self, _: &NextThread, window: &mut Window, cx: &mut Context<Self>) {
3818 self.cycle_thread_impl(true, window, cx);
3819 }
3820
3821 fn on_previous_thread(
3822 &mut self,
3823 _: &PreviousThread,
3824 window: &mut Window,
3825 cx: &mut Context<Self>,
3826 ) {
3827 self.cycle_thread_impl(false, window, cx);
3828 }
3829
3830 fn expand_thread_group(&mut self, project_group_key: &ProjectGroupKey, cx: &mut Context<Self>) {
3831 let current = self
3832 .expanded_groups
3833 .get(project_group_key)
3834 .copied()
3835 .unwrap_or(0);
3836 self.expanded_groups
3837 .insert(project_group_key.clone(), current + 1);
3838 self.serialize(cx);
3839 self.update_entries(cx);
3840 }
3841
3842 fn reset_thread_group_expansion(
3843 &mut self,
3844 project_group_key: &ProjectGroupKey,
3845 cx: &mut Context<Self>,
3846 ) {
3847 self.expanded_groups.remove(project_group_key);
3848 self.serialize(cx);
3849 self.update_entries(cx);
3850 }
3851
3852 fn collapse_thread_group(
3853 &mut self,
3854 project_group_key: &ProjectGroupKey,
3855 cx: &mut Context<Self>,
3856 ) {
3857 match self.expanded_groups.get(project_group_key).copied() {
3858 Some(batches) if batches > 1 => {
3859 self.expanded_groups
3860 .insert(project_group_key.clone(), batches - 1);
3861 }
3862 Some(_) => {
3863 self.expanded_groups.remove(project_group_key);
3864 }
3865 None => return,
3866 }
3867 self.serialize(cx);
3868 self.update_entries(cx);
3869 }
3870
3871 fn on_show_more_threads(
3872 &mut self,
3873 _: &ShowMoreThreads,
3874 _window: &mut Window,
3875 cx: &mut Context<Self>,
3876 ) {
3877 let Some(active_key) = self.active_project_group_key(cx) else {
3878 return;
3879 };
3880 self.expand_thread_group(&active_key, cx);
3881 }
3882
3883 fn on_show_fewer_threads(
3884 &mut self,
3885 _: &ShowFewerThreads,
3886 _window: &mut Window,
3887 cx: &mut Context<Self>,
3888 ) {
3889 let Some(active_key) = self.active_project_group_key(cx) else {
3890 return;
3891 };
3892 self.collapse_thread_group(&active_key, cx);
3893 }
3894
3895 fn on_new_thread(
3896 &mut self,
3897 _: &workspace::NewThread,
3898 window: &mut Window,
3899 cx: &mut Context<Self>,
3900 ) {
3901 let Some(workspace) = self.active_workspace(cx) else {
3902 return;
3903 };
3904 self.create_new_thread(&workspace, window, cx);
3905 }
3906
3907 fn render_draft_thread(
3908 &self,
3909 ix: usize,
3910 is_active: bool,
3911 worktrees: &[WorktreeInfo],
3912 is_selected: bool,
3913 cx: &mut Context<Self>,
3914 ) -> AnyElement {
3915 let label: SharedString = if is_active {
3916 self.active_draft_text(cx)
3917 .unwrap_or_else(|| "New Thread".into())
3918 } else {
3919 "New Thread".into()
3920 };
3921
3922 let id = SharedString::from(format!("draft-thread-btn-{}", ix));
3923
3924 let thread_item = ThreadItem::new(id, label)
3925 .icon(IconName::Plus)
3926 .icon_color(Color::Custom(cx.theme().colors().icon_muted.opacity(0.8)))
3927 .worktrees(
3928 worktrees
3929 .iter()
3930 .map(|wt| ThreadItemWorktreeInfo {
3931 name: wt.name.clone(),
3932 full_path: wt.full_path.clone(),
3933 highlight_positions: wt.highlight_positions.clone(),
3934 kind: wt.kind,
3935 })
3936 .collect(),
3937 )
3938 .selected(true)
3939 .focused(is_selected)
3940 .on_click(cx.listener(|this, _, window, cx| {
3941 if let Some(workspace) = this.active_workspace(cx) {
3942 if !AgentPanel::is_visible(&workspace, cx) {
3943 workspace.update(cx, |workspace, cx| {
3944 workspace.focus_panel::<AgentPanel>(window, cx);
3945 });
3946 }
3947 }
3948 }));
3949
3950 div()
3951 .on_mouse_down(gpui::MouseButton::Left, |_, _, cx| {
3952 cx.stop_propagation();
3953 })
3954 .child(thread_item)
3955 .into_any_element()
3956 }
3957
3958 fn render_new_thread(
3959 &self,
3960 ix: usize,
3961 key: &ProjectGroupKey,
3962 worktrees: &[WorktreeInfo],
3963 workspace: Option<&Entity<Workspace>>,
3964 is_selected: bool,
3965 cx: &mut Context<Self>,
3966 ) -> AnyElement {
3967 let label: SharedString = DEFAULT_THREAD_TITLE.into();
3968 let key = key.clone();
3969
3970 let id = SharedString::from(format!("new-thread-btn-{}", ix));
3971
3972 let mut thread_item = ThreadItem::new(id, label)
3973 .icon(IconName::Plus)
3974 .icon_color(Color::Custom(cx.theme().colors().icon_muted.opacity(0.8)))
3975 .worktrees(
3976 worktrees
3977 .iter()
3978 .map(|wt| ThreadItemWorktreeInfo {
3979 name: wt.name.clone(),
3980 full_path: wt.full_path.clone(),
3981 highlight_positions: wt.highlight_positions.clone(),
3982 kind: wt.kind,
3983 })
3984 .collect(),
3985 )
3986 .selected(false)
3987 .focused(is_selected)
3988 .on_click(cx.listener(move |this, _, window, cx| {
3989 this.selection = None;
3990 if let Some(workspace) = this.multi_workspace.upgrade().and_then(|mw| {
3991 mw.read(cx)
3992 .workspace_for_paths(key.path_list(), key.host().as_ref(), cx)
3993 }) {
3994 this.create_new_thread(&workspace, window, cx);
3995 } else {
3996 this.open_workspace_for_group(&key, window, cx);
3997 }
3998 }));
3999
4000 // Linked worktree DraftThread entries can be dismissed, which removes
4001 // the workspace from the multi-workspace.
4002 if let Some(workspace) = workspace.cloned() {
4003 thread_item = thread_item.action_slot(
4004 IconButton::new("close-worktree-workspace", IconName::Close)
4005 .icon_size(IconSize::Small)
4006 .icon_color(Color::Muted)
4007 .tooltip(Tooltip::text("Close Workspace"))
4008 .on_click(cx.listener(move |this, _, window, cx| {
4009 this.remove_worktree_workspace(workspace.clone(), window, cx);
4010 })),
4011 );
4012 }
4013
4014 thread_item.into_any_element()
4015 }
4016
4017 fn render_no_results(&self, cx: &mut Context<Self>) -> impl IntoElement {
4018 let has_query = self.has_filter_query(cx);
4019 let message = if has_query {
4020 "No threads match your search."
4021 } else {
4022 "No threads yet"
4023 };
4024
4025 v_flex()
4026 .id("sidebar-no-results")
4027 .p_4()
4028 .size_full()
4029 .items_center()
4030 .justify_center()
4031 .child(
4032 Label::new(message)
4033 .size(LabelSize::Small)
4034 .color(Color::Muted),
4035 )
4036 }
4037
4038 fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
4039 v_flex()
4040 .id("sidebar-empty-state")
4041 .p_4()
4042 .size_full()
4043 .items_center()
4044 .justify_center()
4045 .gap_1()
4046 .track_focus(&self.focus_handle(cx))
4047 .child(
4048 Button::new("open_project", "Open Project")
4049 .full_width()
4050 .key_binding(KeyBinding::for_action(&workspace::Open::default(), cx))
4051 .on_click(|_, window, cx| {
4052 window.dispatch_action(
4053 Open {
4054 create_new_window: false,
4055 }
4056 .boxed_clone(),
4057 cx,
4058 );
4059 }),
4060 )
4061 .child(
4062 h_flex()
4063 .w_1_2()
4064 .gap_2()
4065 .child(Divider::horizontal().color(ui::DividerColor::Border))
4066 .child(Label::new("or").size(LabelSize::XSmall).color(Color::Muted))
4067 .child(Divider::horizontal().color(ui::DividerColor::Border)),
4068 )
4069 .child(
4070 Button::new("clone_repo", "Clone Repository")
4071 .full_width()
4072 .on_click(|_, window, cx| {
4073 window.dispatch_action(git::Clone.boxed_clone(), cx);
4074 }),
4075 )
4076 }
4077
4078 fn render_sidebar_header(
4079 &self,
4080 no_open_projects: bool,
4081 window: &Window,
4082 cx: &mut Context<Self>,
4083 ) -> impl IntoElement {
4084 let has_query = self.has_filter_query(cx);
4085 let sidebar_on_left = self.side(cx) == SidebarSide::Left;
4086 let sidebar_on_right = self.side(cx) == SidebarSide::Right;
4087 let not_fullscreen = !window.is_fullscreen();
4088 let traffic_lights = cfg!(target_os = "macos") && not_fullscreen && sidebar_on_left;
4089 let left_window_controls = !cfg!(target_os = "macos") && not_fullscreen && sidebar_on_left;
4090 let right_window_controls =
4091 !cfg!(target_os = "macos") && not_fullscreen && sidebar_on_right;
4092 let header_height = platform_title_bar_height(window);
4093
4094 h_flex()
4095 .h(header_height)
4096 .mt_px()
4097 .pb_px()
4098 .when(left_window_controls, |this| {
4099 this.children(Self::render_left_window_controls(window, cx))
4100 })
4101 .map(|this| {
4102 if traffic_lights {
4103 this.pl(px(ui::utils::TRAFFIC_LIGHT_PADDING))
4104 } else if !left_window_controls {
4105 this.pl_1p5()
4106 } else {
4107 this
4108 }
4109 })
4110 .when(!right_window_controls, |this| this.pr_1p5())
4111 .gap_1()
4112 .when(!no_open_projects, |this| {
4113 this.border_b_1()
4114 .border_color(cx.theme().colors().border)
4115 .when(traffic_lights, |this| {
4116 this.child(Divider::vertical().color(ui::DividerColor::Border))
4117 })
4118 .child(
4119 div().ml_1().child(
4120 Icon::new(IconName::MagnifyingGlass)
4121 .size(IconSize::Small)
4122 .color(Color::Muted),
4123 ),
4124 )
4125 .child(self.render_filter_input(cx))
4126 .child(
4127 h_flex()
4128 .gap_1()
4129 .when(
4130 self.selection.is_some()
4131 && !self.filter_editor.focus_handle(cx).is_focused(window),
4132 |this| this.child(KeyBinding::for_action(&FocusSidebarFilter, cx)),
4133 )
4134 .when(has_query, |this| {
4135 this.child(
4136 IconButton::new("clear_filter", IconName::Close)
4137 .icon_size(IconSize::Small)
4138 .tooltip(Tooltip::text("Clear Search"))
4139 .on_click(cx.listener(|this, _, window, cx| {
4140 this.reset_filter_editor_text(window, cx);
4141 this.update_entries(cx);
4142 })),
4143 )
4144 }),
4145 )
4146 })
4147 .when(right_window_controls, |this| {
4148 this.children(Self::render_right_window_controls(window, cx))
4149 })
4150 }
4151
4152 fn render_left_window_controls(window: &Window, cx: &mut App) -> Option<AnyElement> {
4153 platform_title_bar::render_left_window_controls(
4154 cx.button_layout(),
4155 Box::new(CloseWindow),
4156 window,
4157 )
4158 }
4159
4160 fn render_right_window_controls(window: &Window, cx: &mut App) -> Option<AnyElement> {
4161 platform_title_bar::render_right_window_controls(
4162 cx.button_layout(),
4163 Box::new(CloseWindow),
4164 window,
4165 )
4166 }
4167
4168 fn render_sidebar_toggle_button(&self, _cx: &mut Context<Self>) -> impl IntoElement {
4169 let on_right = AgentSettings::get_global(_cx).sidebar_side() == SidebarSide::Right;
4170
4171 sidebar_side_context_menu("sidebar-toggle-menu", _cx)
4172 .anchor(if on_right {
4173 gpui::Corner::BottomRight
4174 } else {
4175 gpui::Corner::BottomLeft
4176 })
4177 .attach(if on_right {
4178 gpui::Corner::TopRight
4179 } else {
4180 gpui::Corner::TopLeft
4181 })
4182 .trigger(move |_is_active, _window, _cx| {
4183 let icon = if on_right {
4184 IconName::ThreadsSidebarRightOpen
4185 } else {
4186 IconName::ThreadsSidebarLeftOpen
4187 };
4188 IconButton::new("sidebar-close-toggle", icon)
4189 .icon_size(IconSize::Small)
4190 .tooltip(Tooltip::element(move |_window, cx| {
4191 v_flex()
4192 .gap_1()
4193 .child(
4194 h_flex()
4195 .gap_2()
4196 .justify_between()
4197 .child(Label::new("Toggle Sidebar"))
4198 .child(KeyBinding::for_action(&ToggleWorkspaceSidebar, cx)),
4199 )
4200 .child(
4201 h_flex()
4202 .pt_1()
4203 .gap_2()
4204 .border_t_1()
4205 .border_color(cx.theme().colors().border_variant)
4206 .justify_between()
4207 .child(Label::new("Focus Sidebar"))
4208 .child(KeyBinding::for_action(&FocusWorkspaceSidebar, cx)),
4209 )
4210 .into_any_element()
4211 }))
4212 .on_click(|_, window, cx| {
4213 if let Some(multi_workspace) = window.root::<MultiWorkspace>().flatten() {
4214 multi_workspace.update(cx, |multi_workspace, cx| {
4215 multi_workspace.close_sidebar(window, cx);
4216 });
4217 }
4218 })
4219 })
4220 }
4221
4222 fn render_sidebar_bottom_bar(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
4223 let is_archive = matches!(self.view, SidebarView::Archive(..));
4224 let show_import_button = is_archive && !self.should_render_acp_import_onboarding(cx);
4225 let on_right = self.side(cx) == SidebarSide::Right;
4226
4227 let action_buttons = h_flex()
4228 .gap_1()
4229 .when(on_right, |this| this.flex_row_reverse())
4230 .when(show_import_button, |this| {
4231 this.child(
4232 IconButton::new("thread-import", IconName::ThreadImport)
4233 .icon_size(IconSize::Small)
4234 .tooltip(Tooltip::text("Import ACP Threads"))
4235 .on_click(cx.listener(|this, _, window, cx| {
4236 this.show_archive(window, cx);
4237 this.show_thread_import_modal(window, cx);
4238 })),
4239 )
4240 })
4241 .child(
4242 IconButton::new("archive", IconName::Archive)
4243 .icon_size(IconSize::Small)
4244 .toggle_state(is_archive)
4245 .tooltip(move |_, cx| {
4246 Tooltip::for_action("Toggle Archived Threads", &ToggleArchive, cx)
4247 })
4248 .on_click(cx.listener(|this, _, window, cx| {
4249 this.toggle_archive(&ToggleArchive, window, cx);
4250 })),
4251 )
4252 .child(self.render_recent_projects_button(cx));
4253
4254 h_flex()
4255 .p_1()
4256 .gap_1()
4257 .when(on_right, |this| this.flex_row_reverse())
4258 .justify_between()
4259 .border_t_1()
4260 .border_color(cx.theme().colors().border)
4261 .child(self.render_sidebar_toggle_button(cx))
4262 .child(action_buttons)
4263 }
4264
4265 fn active_workspace(&self, cx: &App) -> Option<Entity<Workspace>> {
4266 self.multi_workspace
4267 .upgrade()
4268 .map(|w| w.read(cx).workspace().clone())
4269 }
4270
4271 fn show_thread_import_modal(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4272 let Some(active_workspace) = self.active_workspace(cx) else {
4273 return;
4274 };
4275
4276 let Some(agent_registry_store) = AgentRegistryStore::try_global(cx) else {
4277 return;
4278 };
4279
4280 let agent_server_store = active_workspace
4281 .read(cx)
4282 .project()
4283 .read(cx)
4284 .agent_server_store()
4285 .clone();
4286
4287 let workspace_handle = active_workspace.downgrade();
4288 let multi_workspace = self.multi_workspace.clone();
4289
4290 active_workspace.update(cx, |workspace, cx| {
4291 workspace.toggle_modal(window, cx, |window, cx| {
4292 ThreadImportModal::new(
4293 agent_server_store,
4294 agent_registry_store,
4295 workspace_handle.clone(),
4296 multi_workspace.clone(),
4297 window,
4298 cx,
4299 )
4300 });
4301 });
4302 }
4303
4304 fn should_render_acp_import_onboarding(&self, cx: &App) -> bool {
4305 let has_external_agents = self
4306 .active_workspace(cx)
4307 .map(|ws| {
4308 ws.read(cx)
4309 .project()
4310 .read(cx)
4311 .agent_server_store()
4312 .read(cx)
4313 .has_external_agents()
4314 })
4315 .unwrap_or(false);
4316
4317 has_external_agents && !AcpThreadImportOnboarding::dismissed(cx)
4318 }
4319
4320 fn render_acp_import_onboarding(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
4321 let description =
4322 "Import threads from your ACP agents — whether started in Zed or another client.";
4323
4324 let bg = cx.theme().colors().text_accent;
4325
4326 v_flex()
4327 .min_w_0()
4328 .w_full()
4329 .p_2()
4330 .border_t_1()
4331 .border_color(cx.theme().colors().border)
4332 .bg(linear_gradient(
4333 360.,
4334 linear_color_stop(bg.opacity(0.06), 1.),
4335 linear_color_stop(bg.opacity(0.), 0.),
4336 ))
4337 .child(
4338 h_flex()
4339 .min_w_0()
4340 .w_full()
4341 .gap_1()
4342 .justify_between()
4343 .child(Label::new("Looking for ACP threads?"))
4344 .child(
4345 IconButton::new("close-onboarding", IconName::Close)
4346 .icon_size(IconSize::Small)
4347 .on_click(|_, _window, cx| AcpThreadImportOnboarding::dismiss(cx)),
4348 ),
4349 )
4350 .child(Label::new(description).color(Color::Muted).mb_2())
4351 .child(
4352 Button::new("import-acp", "Import ACP Threads")
4353 .full_width()
4354 .style(ButtonStyle::OutlinedCustom(cx.theme().colors().border))
4355 .label_size(LabelSize::Small)
4356 .start_icon(
4357 Icon::new(IconName::ThreadImport)
4358 .size(IconSize::Small)
4359 .color(Color::Muted),
4360 )
4361 .on_click(cx.listener(|this, _, window, cx| {
4362 this.show_archive(window, cx);
4363 this.show_thread_import_modal(window, cx);
4364 })),
4365 )
4366 }
4367
4368 fn toggle_archive(&mut self, _: &ToggleArchive, window: &mut Window, cx: &mut Context<Self>) {
4369 match &self.view {
4370 SidebarView::ThreadList => self.show_archive(window, cx),
4371 SidebarView::Archive(_) => self.show_thread_list(window, cx),
4372 }
4373 }
4374
4375 fn show_archive(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4376 let Some(active_workspace) = self
4377 .multi_workspace
4378 .upgrade()
4379 .map(|w| w.read(cx).workspace().clone())
4380 else {
4381 return;
4382 };
4383 let Some(agent_panel) = active_workspace.read(cx).panel::<AgentPanel>(cx) else {
4384 return;
4385 };
4386
4387 let agent_server_store = active_workspace
4388 .read(cx)
4389 .project()
4390 .read(cx)
4391 .agent_server_store()
4392 .downgrade();
4393
4394 let agent_connection_store = agent_panel.read(cx).connection_store().downgrade();
4395
4396 let archive_view = cx.new(|cx| {
4397 ThreadsArchiveView::new(
4398 active_workspace.downgrade(),
4399 agent_connection_store.clone(),
4400 agent_server_store.clone(),
4401 window,
4402 cx,
4403 )
4404 });
4405
4406 let subscription = cx.subscribe_in(
4407 &archive_view,
4408 window,
4409 |this, _, event: &ThreadsArchiveViewEvent, window, cx| match event {
4410 ThreadsArchiveViewEvent::Close => {
4411 this.show_thread_list(window, cx);
4412 }
4413 ThreadsArchiveViewEvent::Unarchive { thread } => {
4414 this.activate_archived_thread(thread.clone(), window, cx);
4415 }
4416 ThreadsArchiveViewEvent::CancelRestore { session_id } => {
4417 this.restoring_tasks.remove(session_id);
4418 }
4419 },
4420 );
4421
4422 self._subscriptions.push(subscription);
4423 self.view = SidebarView::Archive(archive_view.clone());
4424 archive_view.update(cx, |view, cx| view.focus_filter_editor(window, cx));
4425 self.serialize(cx);
4426 cx.notify();
4427 }
4428
4429 fn show_thread_list(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4430 self.view = SidebarView::ThreadList;
4431 self._subscriptions.clear();
4432 let handle = self.filter_editor.read(cx).focus_handle(cx);
4433 handle.focus(window, cx);
4434 self.serialize(cx);
4435 cx.notify();
4436 }
4437}
4438
4439impl WorkspaceSidebar for Sidebar {
4440 fn width(&self, _cx: &App) -> Pixels {
4441 self.width
4442 }
4443
4444 fn set_width(&mut self, width: Option<Pixels>, cx: &mut Context<Self>) {
4445 self.width = width.unwrap_or(DEFAULT_WIDTH).clamp(MIN_WIDTH, MAX_WIDTH);
4446 cx.notify();
4447 }
4448
4449 fn has_notifications(&self, _cx: &App) -> bool {
4450 !self.contents.notified_threads.is_empty()
4451 }
4452
4453 fn is_threads_list_view_active(&self) -> bool {
4454 matches!(self.view, SidebarView::ThreadList)
4455 }
4456
4457 fn side(&self, cx: &App) -> SidebarSide {
4458 AgentSettings::get_global(cx).sidebar_side()
4459 }
4460
4461 fn prepare_for_focus(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
4462 self.selection = None;
4463 cx.notify();
4464 }
4465
4466 fn toggle_thread_switcher(
4467 &mut self,
4468 select_last: bool,
4469 window: &mut Window,
4470 cx: &mut Context<Self>,
4471 ) {
4472 self.toggle_thread_switcher_impl(select_last, window, cx);
4473 }
4474
4475 fn cycle_project(&mut self, forward: bool, window: &mut Window, cx: &mut Context<Self>) {
4476 self.cycle_project_impl(forward, window, cx);
4477 }
4478
4479 fn cycle_thread(&mut self, forward: bool, window: &mut Window, cx: &mut Context<Self>) {
4480 self.cycle_thread_impl(forward, window, cx);
4481 }
4482
4483 fn serialized_state(&self, _cx: &App) -> Option<String> {
4484 let serialized = SerializedSidebar {
4485 width: Some(f32::from(self.width)),
4486 collapsed_groups: self
4487 .collapsed_groups
4488 .iter()
4489 .cloned()
4490 .map(SerializedProjectGroupKey::from)
4491 .collect(),
4492 expanded_groups: self
4493 .expanded_groups
4494 .iter()
4495 .map(|(key, count)| (SerializedProjectGroupKey::from(key.clone()), *count))
4496 .collect(),
4497 active_view: match self.view {
4498 SidebarView::ThreadList => SerializedSidebarView::ThreadList,
4499 SidebarView::Archive(_) => SerializedSidebarView::Archive,
4500 },
4501 };
4502 serde_json::to_string(&serialized).ok()
4503 }
4504
4505 fn restore_serialized_state(
4506 &mut self,
4507 state: &str,
4508 window: &mut Window,
4509 cx: &mut Context<Self>,
4510 ) {
4511 if let Some(serialized) = serde_json::from_str::<SerializedSidebar>(state).log_err() {
4512 if let Some(width) = serialized.width {
4513 self.width = px(width).clamp(MIN_WIDTH, MAX_WIDTH);
4514 }
4515 self.collapsed_groups = serialized
4516 .collapsed_groups
4517 .into_iter()
4518 .map(ProjectGroupKey::from)
4519 .collect();
4520 self.expanded_groups = serialized
4521 .expanded_groups
4522 .into_iter()
4523 .map(|(s, count)| (ProjectGroupKey::from(s), count))
4524 .collect();
4525 if serialized.active_view == SerializedSidebarView::Archive {
4526 cx.defer_in(window, |this, window, cx| {
4527 this.show_archive(window, cx);
4528 });
4529 }
4530 }
4531 cx.notify();
4532 }
4533}
4534
4535impl gpui::EventEmitter<workspace::SidebarEvent> for Sidebar {}
4536
4537impl Focusable for Sidebar {
4538 fn focus_handle(&self, _cx: &App) -> FocusHandle {
4539 self.focus_handle.clone()
4540 }
4541}
4542
4543impl Render for Sidebar {
4544 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4545 let _titlebar_height = ui::utils::platform_title_bar_height(window);
4546 let ui_font = theme_settings::setup_ui_font(window, cx);
4547 let sticky_header = self.render_sticky_header(window, cx);
4548
4549 let color = cx.theme().colors();
4550 let bg = color
4551 .title_bar_background
4552 .blend(color.panel_background.opacity(0.25));
4553
4554 let no_open_projects = !self.contents.has_open_projects;
4555 let no_search_results = self.contents.entries.is_empty();
4556
4557 v_flex()
4558 .id("workspace-sidebar")
4559 .key_context(self.dispatch_context(window, cx))
4560 .track_focus(&self.focus_handle)
4561 .on_action(cx.listener(Self::select_next))
4562 .on_action(cx.listener(Self::select_previous))
4563 .on_action(cx.listener(Self::editor_move_down))
4564 .on_action(cx.listener(Self::editor_move_up))
4565 .on_action(cx.listener(Self::select_first))
4566 .on_action(cx.listener(Self::select_last))
4567 .on_action(cx.listener(Self::confirm))
4568 .on_action(cx.listener(Self::expand_selected_entry))
4569 .on_action(cx.listener(Self::collapse_selected_entry))
4570 .on_action(cx.listener(Self::toggle_selected_fold))
4571 .on_action(cx.listener(Self::fold_all))
4572 .on_action(cx.listener(Self::unfold_all))
4573 .on_action(cx.listener(Self::cancel))
4574 .on_action(cx.listener(Self::remove_selected_thread))
4575 .on_action(cx.listener(Self::new_thread_in_group))
4576 .on_action(cx.listener(Self::toggle_archive))
4577 .on_action(cx.listener(Self::focus_sidebar_filter))
4578 .on_action(cx.listener(Self::on_toggle_thread_switcher))
4579 .on_action(cx.listener(Self::on_next_project))
4580 .on_action(cx.listener(Self::on_previous_project))
4581 .on_action(cx.listener(Self::on_next_thread))
4582 .on_action(cx.listener(Self::on_previous_thread))
4583 .on_action(cx.listener(Self::on_show_more_threads))
4584 .on_action(cx.listener(Self::on_show_fewer_threads))
4585 .on_action(cx.listener(Self::on_new_thread))
4586 .on_action(cx.listener(|this, _: &OpenRecent, window, cx| {
4587 this.recent_projects_popover_handle.toggle(window, cx);
4588 }))
4589 .font(ui_font)
4590 .h_full()
4591 .w(self.width)
4592 .bg(bg)
4593 .when(self.side(cx) == SidebarSide::Left, |el| el.border_r_1())
4594 .when(self.side(cx) == SidebarSide::Right, |el| el.border_l_1())
4595 .border_color(color.border)
4596 .map(|this| match &self.view {
4597 SidebarView::ThreadList => this
4598 .child(self.render_sidebar_header(no_open_projects, window, cx))
4599 .map(|this| {
4600 if no_open_projects {
4601 this.child(self.render_empty_state(cx))
4602 } else {
4603 this.child(
4604 v_flex()
4605 .relative()
4606 .flex_1()
4607 .overflow_hidden()
4608 .child(
4609 list(
4610 self.list_state.clone(),
4611 cx.processor(Self::render_list_entry),
4612 )
4613 .flex_1()
4614 .size_full(),
4615 )
4616 .when(no_search_results, |this| {
4617 this.child(self.render_no_results(cx))
4618 })
4619 .when_some(sticky_header, |this, header| this.child(header))
4620 .vertical_scrollbar_for(&self.list_state, window, cx),
4621 )
4622 }
4623 }),
4624 SidebarView::Archive(archive_view) => this.child(archive_view.clone()),
4625 })
4626 .when(self.should_render_acp_import_onboarding(cx), |this| {
4627 this.child(self.render_acp_import_onboarding(cx))
4628 })
4629 .child(self.render_sidebar_bottom_bar(cx))
4630 }
4631}
4632
4633fn all_thread_infos_for_workspace(
4634 workspace: &Entity<Workspace>,
4635 cx: &App,
4636) -> impl Iterator<Item = ActiveThreadInfo> {
4637 let Some(agent_panel) = workspace.read(cx).panel::<AgentPanel>(cx) else {
4638 return None.into_iter().flatten();
4639 };
4640 let agent_panel = agent_panel.read(cx);
4641 let threads = agent_panel
4642 .conversation_views()
4643 .into_iter()
4644 .filter_map(|conversation_view| {
4645 let has_pending_tool_call = conversation_view
4646 .read(cx)
4647 .root_thread_has_pending_tool_call(cx);
4648 let thread_view = conversation_view.read(cx).root_thread(cx)?;
4649 let thread_view_ref = thread_view.read(cx);
4650 let thread = thread_view_ref.thread.read(cx);
4651
4652 let icon = thread_view_ref.agent_icon;
4653 let icon_from_external_svg = thread_view_ref.agent_icon_from_external_svg.clone();
4654 let title = thread
4655 .title()
4656 .unwrap_or_else(|| DEFAULT_THREAD_TITLE.into());
4657 let is_native = thread_view_ref.as_native_thread(cx).is_some();
4658 let is_title_generating = is_native && thread.has_provisional_title();
4659 let session_id = thread.session_id().clone();
4660 let is_background = agent_panel.is_background_thread(&session_id);
4661
4662 let status = if has_pending_tool_call {
4663 AgentThreadStatus::WaitingForConfirmation
4664 } else if thread.had_error() {
4665 AgentThreadStatus::Error
4666 } else {
4667 match thread.status() {
4668 ThreadStatus::Generating => AgentThreadStatus::Running,
4669 ThreadStatus::Idle => AgentThreadStatus::Completed,
4670 }
4671 };
4672
4673 let diff_stats = thread.action_log().read(cx).diff_stats(cx);
4674
4675 Some(ActiveThreadInfo {
4676 session_id,
4677 title,
4678 status,
4679 icon,
4680 icon_from_external_svg,
4681 is_background,
4682 is_title_generating,
4683 diff_stats,
4684 })
4685 });
4686
4687 Some(threads).into_iter().flatten()
4688}
4689
4690pub fn dump_workspace_info(
4691 workspace: &mut Workspace,
4692 _: &DumpWorkspaceInfo,
4693 window: &mut gpui::Window,
4694 cx: &mut gpui::Context<Workspace>,
4695) {
4696 use std::fmt::Write;
4697
4698 let mut output = String::new();
4699 let this_entity = cx.entity();
4700
4701 let multi_workspace = workspace.multi_workspace().and_then(|weak| weak.upgrade());
4702 let workspaces: Vec<gpui::Entity<Workspace>> = match &multi_workspace {
4703 Some(mw) => mw.read(cx).workspaces().cloned().collect(),
4704 None => vec![this_entity.clone()],
4705 };
4706 let active_workspace = multi_workspace
4707 .as_ref()
4708 .map(|mw| mw.read(cx).workspace().clone());
4709
4710 writeln!(output, "MultiWorkspace: {} workspace(s)", workspaces.len()).ok();
4711
4712 if let Some(mw) = &multi_workspace {
4713 let keys: Vec<_> = mw.read(cx).project_group_keys().cloned().collect();
4714 writeln!(output, "Project group keys ({}):", keys.len()).ok();
4715 for key in keys {
4716 writeln!(output, " - {key:?}").ok();
4717 }
4718 }
4719
4720 writeln!(output).ok();
4721
4722 for (index, ws) in workspaces.iter().enumerate() {
4723 let is_active = active_workspace.as_ref() == Some(ws);
4724 writeln!(
4725 output,
4726 "--- Workspace {index}{} ---",
4727 if is_active { " (active)" } else { "" }
4728 )
4729 .ok();
4730
4731 // The action handler is already inside an update on `this_entity`,
4732 // so we must avoid a nested read/update on that same entity.
4733 if *ws == this_entity {
4734 dump_single_workspace(workspace, &mut output, cx);
4735 } else {
4736 ws.read_with(cx, |ws, cx| {
4737 dump_single_workspace(ws, &mut output, cx);
4738 });
4739 }
4740 }
4741
4742 let project = workspace.project().clone();
4743 cx.spawn_in(window, async move |_this, cx| {
4744 let buffer = project
4745 .update(cx, |project, cx| project.create_buffer(None, false, cx))
4746 .await?;
4747
4748 buffer.update(cx, |buffer, cx| {
4749 buffer.set_text(output, cx);
4750 });
4751
4752 let buffer = cx.new(|cx| {
4753 editor::MultiBuffer::singleton(buffer, cx).with_title("Workspace Info".into())
4754 });
4755
4756 _this.update_in(cx, |workspace, window, cx| {
4757 workspace.add_item_to_active_pane(
4758 Box::new(cx.new(|cx| {
4759 let mut editor =
4760 editor::Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
4761 editor.set_read_only(true);
4762 editor.set_should_serialize(false, cx);
4763 editor.set_breadcrumb_header("Workspace Info".into());
4764 editor
4765 })),
4766 None,
4767 true,
4768 window,
4769 cx,
4770 );
4771 })
4772 })
4773 .detach_and_log_err(cx);
4774}
4775
4776fn dump_single_workspace(workspace: &Workspace, output: &mut String, cx: &gpui::App) {
4777 use std::fmt::Write;
4778
4779 let workspace_db_id = workspace.database_id();
4780 match workspace_db_id {
4781 Some(id) => writeln!(output, "Workspace DB ID: {id:?}").ok(),
4782 None => writeln!(output, "Workspace DB ID: (none)").ok(),
4783 };
4784
4785 let project = workspace.project().read(cx);
4786
4787 let repos: Vec<_> = project
4788 .repositories(cx)
4789 .values()
4790 .map(|repo| repo.read(cx).snapshot())
4791 .collect();
4792
4793 writeln!(output, "Worktrees:").ok();
4794 for worktree in project.worktrees(cx) {
4795 let worktree = worktree.read(cx);
4796 let abs_path = worktree.abs_path();
4797 let visible = worktree.is_visible();
4798
4799 let repo_info = repos
4800 .iter()
4801 .find(|snapshot| abs_path.starts_with(&*snapshot.work_directory_abs_path));
4802
4803 let is_linked = repo_info.map(|s| s.is_linked_worktree()).unwrap_or(false);
4804 let original_repo_path = repo_info.map(|s| &s.original_repo_abs_path);
4805 let branch = repo_info.and_then(|s| s.branch.as_ref().map(|b| b.ref_name.clone()));
4806
4807 write!(output, " - {}", abs_path.display()).ok();
4808 if !visible {
4809 write!(output, " (hidden)").ok();
4810 }
4811 if let Some(branch) = &branch {
4812 write!(output, " [branch: {branch}]").ok();
4813 }
4814 if is_linked {
4815 if let Some(original) = original_repo_path {
4816 write!(output, " [linked worktree -> {}]", original.display()).ok();
4817 } else {
4818 write!(output, " [linked worktree]").ok();
4819 }
4820 }
4821 writeln!(output).ok();
4822 }
4823
4824 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
4825 let panel = panel.read(cx);
4826
4827 let panel_workspace_id = panel.workspace_id();
4828 if panel_workspace_id != workspace_db_id {
4829 writeln!(
4830 output,
4831 " \u{26a0} workspace ID mismatch! panel has {panel_workspace_id:?}, workspace has {workspace_db_id:?}"
4832 )
4833 .ok();
4834 }
4835
4836 if let Some(thread) = panel.active_agent_thread(cx) {
4837 let thread = thread.read(cx);
4838 let title = thread.title().unwrap_or_else(|| "(untitled)".into());
4839 let session_id = thread.session_id();
4840 let status = match thread.status() {
4841 ThreadStatus::Idle => "idle",
4842 ThreadStatus::Generating => "generating",
4843 };
4844 let entry_count = thread.entries().len();
4845 write!(output, "Active thread: {title} (session: {session_id})").ok();
4846 write!(output, " [{status}, {entry_count} entries").ok();
4847 if panel
4848 .active_conversation_view()
4849 .is_some_and(|conversation_view| {
4850 conversation_view
4851 .read(cx)
4852 .root_thread_has_pending_tool_call(cx)
4853 })
4854 {
4855 write!(output, ", awaiting confirmation").ok();
4856 }
4857 writeln!(output, "]").ok();
4858 } else {
4859 writeln!(output, "Active thread: (none)").ok();
4860 }
4861
4862 let background_threads = panel.background_threads();
4863 if !background_threads.is_empty() {
4864 writeln!(
4865 output,
4866 "Background threads ({}): ",
4867 background_threads.len()
4868 )
4869 .ok();
4870 for (session_id, conversation_view) in background_threads {
4871 if let Some(thread_view) = conversation_view.read(cx).root_thread(cx) {
4872 let thread = thread_view.read(cx).thread.read(cx);
4873 let title = thread.title().unwrap_or_else(|| "(untitled)".into());
4874 let status = match thread.status() {
4875 ThreadStatus::Idle => "idle",
4876 ThreadStatus::Generating => "generating",
4877 };
4878 let entry_count = thread.entries().len();
4879 write!(output, " - {title} (session: {session_id})").ok();
4880 write!(output, " [{status}, {entry_count} entries").ok();
4881 if conversation_view
4882 .read(cx)
4883 .root_thread_has_pending_tool_call(cx)
4884 {
4885 write!(output, ", awaiting confirmation").ok();
4886 }
4887 writeln!(output, "]").ok();
4888 } else {
4889 writeln!(output, " - (not connected) (session: {session_id})").ok();
4890 }
4891 }
4892 }
4893 } else {
4894 writeln!(output, "Agent panel: not loaded").ok();
4895 }
4896
4897 writeln!(output).ok();
4898}