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