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 has_multiple_projects = multi_workspace
1680 .read_with(cx, |mw, _| mw.project_group_keys().count() >= 2)
1681 .unwrap_or(false);
1682
1683 let menu =
1684 ContextMenu::build_persistent(window, cx, move |menu, _window, menu_cx| {
1685 let mut menu = menu
1686 .header("Project Folders")
1687 .end_slot_action(Box::new(menu::EndSlot));
1688
1689 for path in project_group_key.path_list().paths() {
1690 let Some(name) = path.file_name() else {
1691 continue;
1692 };
1693 let name: SharedString = name.to_string_lossy().into_owned().into();
1694 let path = path.clone();
1695 let project_group_key = project_group_key.clone();
1696 let multi_workspace = multi_workspace.clone();
1697 menu = menu.entry_with_end_slot_on_hover(
1698 name.clone(),
1699 None,
1700 |_, _| {},
1701 IconName::Close,
1702 "Remove Folder".into(),
1703 move |_window, cx| {
1704 multi_workspace
1705 .update(cx, |multi_workspace, cx| {
1706 multi_workspace.remove_folder_from_project_group(
1707 &project_group_key,
1708 &path,
1709 cx,
1710 );
1711 })
1712 .ok();
1713 },
1714 );
1715 }
1716
1717 let menu = menu.separator().entry(
1718 "Add Folder to Project",
1719 Some(Box::new(AddFolderToProject)),
1720 {
1721 let project_group_key = project_group_key.clone();
1722 let multi_workspace = multi_workspace.clone();
1723 move |window, cx| {
1724 multi_workspace
1725 .update(cx, |multi_workspace, cx| {
1726 multi_workspace.prompt_to_add_folders_to_project_group(
1727 &project_group_key,
1728 window,
1729 cx,
1730 );
1731 })
1732 .ok();
1733 }
1734 },
1735 );
1736
1737 let menu = if project_group_key.host().is_none() && has_multiple_projects {
1738 menu.entry(
1739 "Open Project in New Window",
1740 Some(Box::new(workspace::MoveProjectToNewWindow)),
1741 {
1742 let project_group_key = project_group_key.clone();
1743 let multi_workspace = multi_workspace.clone();
1744 move |window, cx| {
1745 multi_workspace
1746 .update(cx, |multi_workspace, cx| {
1747 multi_workspace
1748 .open_project_group_in_new_window(
1749 &project_group_key,
1750 window,
1751 cx,
1752 )
1753 .detach_and_log_err(cx);
1754 })
1755 .ok();
1756 }
1757 },
1758 )
1759 } else {
1760 menu
1761 };
1762
1763 let project_group_key = project_group_key.clone();
1764 let multi_workspace = multi_workspace.clone();
1765 let weak_menu = menu_cx.weak_entity();
1766 menu.separator()
1767 .entry("Remove Project", None, move |window, cx| {
1768 multi_workspace
1769 .update(cx, |multi_workspace, cx| {
1770 multi_workspace
1771 .remove_project_group(&project_group_key, window, cx)
1772 .detach_and_log_err(cx);
1773 })
1774 .ok();
1775 weak_menu.update(cx, |_, cx| cx.emit(DismissEvent)).ok();
1776 })
1777 });
1778
1779 let this = this.clone();
1780 window
1781 .subscribe(&menu, cx, move |_, _: &gpui::DismissEvent, _window, cx| {
1782 this.update(cx, |sidebar, cx| {
1783 sidebar.project_header_menu_ix = None;
1784 cx.notify();
1785 })
1786 .ok();
1787 })
1788 .detach();
1789
1790 Some(menu)
1791 })
1792 .trigger(
1793 IconButton::new(
1794 SharedString::from(format!("{id_prefix}-ellipsis-menu-{ix}")),
1795 IconName::Ellipsis,
1796 )
1797 .selected_style(ButtonStyle::Tinted(TintColor::Accent))
1798 .icon_size(IconSize::Small),
1799 )
1800 .anchor(gpui::Corner::TopRight)
1801 .offset(gpui::Point {
1802 x: px(0.),
1803 y: px(1.),
1804 })
1805 }
1806
1807 fn render_sticky_header(
1808 &self,
1809 window: &mut Window,
1810 cx: &mut Context<Self>,
1811 ) -> Option<AnyElement> {
1812 let scroll_top = self.list_state.logical_scroll_top();
1813
1814 let &header_idx = self
1815 .contents
1816 .project_header_indices
1817 .iter()
1818 .rev()
1819 .find(|&&idx| idx <= scroll_top.item_ix)?;
1820
1821 let needs_sticky = header_idx < scroll_top.item_ix
1822 || (header_idx == scroll_top.item_ix && scroll_top.offset_in_item > px(0.));
1823
1824 if !needs_sticky {
1825 return None;
1826 }
1827
1828 let ListEntry::ProjectHeader {
1829 key,
1830 label,
1831 highlight_positions,
1832 has_running_threads,
1833 waiting_thread_count,
1834 is_active,
1835 has_threads,
1836 } = self.contents.entries.get(header_idx)?
1837 else {
1838 return None;
1839 };
1840
1841 let is_focused = self.focus_handle.is_focused(window);
1842 let is_selected = is_focused && self.selection == Some(header_idx);
1843
1844 let header_element = self.render_project_header(
1845 header_idx,
1846 true,
1847 key,
1848 &label,
1849 &highlight_positions,
1850 *has_running_threads,
1851 *waiting_thread_count,
1852 *is_active,
1853 *has_threads,
1854 is_selected,
1855 cx,
1856 );
1857
1858 let top_offset = self
1859 .contents
1860 .project_header_indices
1861 .iter()
1862 .find(|&&idx| idx > header_idx)
1863 .and_then(|&next_idx| {
1864 let bounds = self.list_state.bounds_for_item(next_idx)?;
1865 let viewport = self.list_state.viewport_bounds();
1866 let y_in_viewport = bounds.origin.y - viewport.origin.y;
1867 let header_height = bounds.size.height;
1868 (y_in_viewport < header_height).then_some(y_in_viewport - header_height)
1869 })
1870 .unwrap_or(px(0.));
1871
1872 let color = cx.theme().colors();
1873 let background = color
1874 .title_bar_background
1875 .blend(color.panel_background.opacity(0.2));
1876
1877 let element = v_flex()
1878 .absolute()
1879 .top(top_offset)
1880 .left_0()
1881 .w_full()
1882 .bg(background)
1883 .border_b_1()
1884 .border_color(color.border.opacity(0.5))
1885 .child(header_element)
1886 .shadow_xs()
1887 .into_any_element();
1888
1889 Some(element)
1890 }
1891
1892 fn toggle_collapse(
1893 &mut self,
1894 project_group_key: &ProjectGroupKey,
1895 _window: &mut Window,
1896 cx: &mut Context<Self>,
1897 ) {
1898 if self.collapsed_groups.contains(project_group_key) {
1899 self.collapsed_groups.remove(project_group_key);
1900 } else {
1901 self.collapsed_groups.insert(project_group_key.clone());
1902 }
1903 self.serialize(cx);
1904 self.update_entries(cx);
1905 }
1906
1907 fn dispatch_context(&self, window: &Window, cx: &Context<Self>) -> KeyContext {
1908 let mut dispatch_context = KeyContext::new_with_defaults();
1909 dispatch_context.add("ThreadsSidebar");
1910 dispatch_context.add("menu");
1911
1912 let is_archived_search_focused = matches!(&self.view, SidebarView::Archive(archive) if archive.read(cx).is_filter_editor_focused(window, cx));
1913
1914 let identifier = if self.filter_editor.focus_handle(cx).is_focused(window)
1915 || is_archived_search_focused
1916 {
1917 "searching"
1918 } else {
1919 "not_searching"
1920 };
1921
1922 dispatch_context.add(identifier);
1923 dispatch_context
1924 }
1925
1926 fn focus_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1927 if !self.focus_handle.is_focused(window) {
1928 return;
1929 }
1930
1931 if let SidebarView::Archive(archive) = &self.view {
1932 let has_selection = archive.read(cx).has_selection();
1933 if !has_selection {
1934 archive.update(cx, |view, cx| view.focus_filter_editor(window, cx));
1935 }
1936 } else if self.selection.is_none() {
1937 self.filter_editor.focus_handle(cx).focus(window, cx);
1938 }
1939 }
1940
1941 fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
1942 if self.reset_filter_editor_text(window, cx) {
1943 self.update_entries(cx);
1944 } else {
1945 self.selection = None;
1946 self.filter_editor.focus_handle(cx).focus(window, cx);
1947 cx.notify();
1948 }
1949 }
1950
1951 fn focus_sidebar_filter(
1952 &mut self,
1953 _: &FocusSidebarFilter,
1954 window: &mut Window,
1955 cx: &mut Context<Self>,
1956 ) {
1957 self.selection = None;
1958 if let SidebarView::Archive(archive) = &self.view {
1959 archive.update(cx, |view, cx| {
1960 view.clear_selection();
1961 view.focus_filter_editor(window, cx);
1962 });
1963 } else {
1964 self.filter_editor.focus_handle(cx).focus(window, cx);
1965 }
1966
1967 // When vim mode is active, the editor defaults to normal mode which
1968 // blocks text input. Switch to insert mode so the user can type
1969 // immediately.
1970 if vim_mode_setting::VimModeSetting::get_global(cx).0 {
1971 if let Ok(action) = cx.build_action("vim::SwitchToInsertMode", None) {
1972 window.dispatch_action(action, cx);
1973 }
1974 }
1975
1976 cx.notify();
1977 }
1978
1979 fn reset_filter_editor_text(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
1980 self.filter_editor.update(cx, |editor, cx| {
1981 if editor.buffer().read(cx).len(cx).0 > 0 {
1982 editor.set_text("", window, cx);
1983 true
1984 } else {
1985 false
1986 }
1987 })
1988 }
1989
1990 fn has_filter_query(&self, cx: &App) -> bool {
1991 !self.filter_editor.read(cx).text(cx).is_empty()
1992 }
1993
1994 fn editor_move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
1995 self.select_next(&SelectNext, window, cx);
1996 if self.selection.is_some() {
1997 self.focus_handle.focus(window, cx);
1998 }
1999 }
2000
2001 fn editor_move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
2002 self.select_previous(&SelectPrevious, window, cx);
2003 if self.selection.is_some() {
2004 self.focus_handle.focus(window, cx);
2005 }
2006 }
2007
2008 fn editor_confirm(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2009 if self.selection.is_none() {
2010 self.select_next(&SelectNext, window, cx);
2011 }
2012 if self.selection.is_some() {
2013 self.focus_handle.focus(window, cx);
2014 }
2015 }
2016
2017 fn select_next(&mut self, _: &SelectNext, _window: &mut Window, cx: &mut Context<Self>) {
2018 let next = match self.selection {
2019 Some(ix) if ix + 1 < self.contents.entries.len() => ix + 1,
2020 Some(_) if !self.contents.entries.is_empty() => 0,
2021 None if !self.contents.entries.is_empty() => 0,
2022 _ => return,
2023 };
2024 self.selection = Some(next);
2025 self.list_state.scroll_to_reveal_item(next);
2026 cx.notify();
2027 }
2028
2029 fn select_previous(&mut self, _: &SelectPrevious, window: &mut Window, cx: &mut Context<Self>) {
2030 match self.selection {
2031 Some(0) => {
2032 self.selection = None;
2033 self.filter_editor.focus_handle(cx).focus(window, cx);
2034 cx.notify();
2035 }
2036 Some(ix) => {
2037 self.selection = Some(ix - 1);
2038 self.list_state.scroll_to_reveal_item(ix - 1);
2039 cx.notify();
2040 }
2041 None if !self.contents.entries.is_empty() => {
2042 let last = self.contents.entries.len() - 1;
2043 self.selection = Some(last);
2044 self.list_state.scroll_to_reveal_item(last);
2045 cx.notify();
2046 }
2047 None => {}
2048 }
2049 }
2050
2051 fn select_first(&mut self, _: &SelectFirst, _window: &mut Window, cx: &mut Context<Self>) {
2052 if !self.contents.entries.is_empty() {
2053 self.selection = Some(0);
2054 self.list_state.scroll_to_reveal_item(0);
2055 cx.notify();
2056 }
2057 }
2058
2059 fn select_last(&mut self, _: &SelectLast, _window: &mut Window, cx: &mut Context<Self>) {
2060 if let Some(last) = self.contents.entries.len().checked_sub(1) {
2061 self.selection = Some(last);
2062 self.list_state.scroll_to_reveal_item(last);
2063 cx.notify();
2064 }
2065 }
2066
2067 fn confirm(&mut self, _: &Confirm, window: &mut Window, cx: &mut Context<Self>) {
2068 let Some(ix) = self.selection else { return };
2069 let Some(entry) = self.contents.entries.get(ix) else {
2070 return;
2071 };
2072
2073 match entry {
2074 ListEntry::ProjectHeader { key, .. } => {
2075 let key = key.clone();
2076 self.toggle_collapse(&key, window, cx);
2077 }
2078 ListEntry::Thread(thread) => {
2079 let metadata = thread.metadata.clone();
2080 match &thread.workspace {
2081 ThreadEntryWorkspace::Open(workspace) => {
2082 let workspace = workspace.clone();
2083 self.activate_thread(metadata, &workspace, false, window, cx);
2084 }
2085 ThreadEntryWorkspace::Closed {
2086 folder_paths,
2087 project_group_key,
2088 } => {
2089 let folder_paths = folder_paths.clone();
2090 let project_group_key = project_group_key.clone();
2091 self.open_workspace_and_activate_thread(
2092 metadata,
2093 folder_paths,
2094 &project_group_key,
2095 window,
2096 cx,
2097 );
2098 }
2099 }
2100 }
2101 ListEntry::ViewMore {
2102 key,
2103 is_fully_expanded,
2104 ..
2105 } => {
2106 let key = key.clone();
2107 if *is_fully_expanded {
2108 self.reset_thread_group_expansion(&key, cx);
2109 } else {
2110 self.expand_thread_group(&key, cx);
2111 }
2112 }
2113 ListEntry::DraftThread { key, workspace, .. } => {
2114 let key = key.clone();
2115 let workspace = workspace.clone();
2116 if let Some(workspace) = workspace.or_else(|| {
2117 self.multi_workspace.upgrade().and_then(|mw| {
2118 mw.read(cx)
2119 .workspace_for_paths(key.path_list(), key.host().as_ref(), cx)
2120 })
2121 }) {
2122 self.create_new_thread(&workspace, window, cx);
2123 } else {
2124 self.open_workspace_for_group(&key, window, cx);
2125 }
2126 }
2127 }
2128 }
2129
2130 fn find_workspace_across_windows(
2131 &self,
2132 cx: &App,
2133 predicate: impl Fn(&Entity<Workspace>, &App) -> bool,
2134 ) -> Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> {
2135 cx.windows()
2136 .into_iter()
2137 .filter_map(|window| window.downcast::<MultiWorkspace>())
2138 .find_map(|window| {
2139 let workspace = window.read(cx).ok().and_then(|multi_workspace| {
2140 multi_workspace
2141 .workspaces()
2142 .find(|workspace| predicate(workspace, cx))
2143 .cloned()
2144 })?;
2145 Some((window, workspace))
2146 })
2147 }
2148
2149 fn find_workspace_in_current_window(
2150 &self,
2151 cx: &App,
2152 predicate: impl Fn(&Entity<Workspace>, &App) -> bool,
2153 ) -> Option<Entity<Workspace>> {
2154 self.multi_workspace.upgrade().and_then(|multi_workspace| {
2155 multi_workspace
2156 .read(cx)
2157 .workspaces()
2158 .find(|workspace| predicate(workspace, cx))
2159 .cloned()
2160 })
2161 }
2162
2163 fn load_agent_thread_in_workspace(
2164 workspace: &Entity<Workspace>,
2165 metadata: &ThreadMetadata,
2166 focus: bool,
2167 window: &mut Window,
2168 cx: &mut App,
2169 ) {
2170 workspace.update(cx, |workspace, cx| {
2171 workspace.reveal_panel::<AgentPanel>(window, cx);
2172 });
2173
2174 if let Some(agent_panel) = workspace.read(cx).panel::<AgentPanel>(cx) {
2175 agent_panel.update(cx, |panel, cx| {
2176 panel.load_agent_thread(
2177 Agent::from(metadata.agent_id.clone()),
2178 metadata.session_id.clone(),
2179 Some(metadata.folder_paths.clone()),
2180 Some(metadata.title.clone()),
2181 focus,
2182 window,
2183 cx,
2184 );
2185 });
2186 }
2187 }
2188
2189 fn activate_thread_locally(
2190 &mut self,
2191 metadata: &ThreadMetadata,
2192 workspace: &Entity<Workspace>,
2193 retain: bool,
2194 window: &mut Window,
2195 cx: &mut Context<Self>,
2196 ) {
2197 let Some(multi_workspace) = self.multi_workspace.upgrade() else {
2198 return;
2199 };
2200
2201 // Set active_entry eagerly so the sidebar highlight updates
2202 // immediately, rather than waiting for a deferred AgentPanel
2203 // event which can race with ActiveWorkspaceChanged clearing it.
2204 self.active_entry = Some(ActiveEntry::Thread {
2205 session_id: metadata.session_id.clone(),
2206 workspace: workspace.clone(),
2207 });
2208 self.record_thread_access(&metadata.session_id);
2209
2210 multi_workspace.update(cx, |multi_workspace, cx| {
2211 multi_workspace.activate(workspace.clone(), window, cx);
2212 if retain {
2213 multi_workspace.retain_active_workspace(cx);
2214 }
2215 });
2216
2217 Self::load_agent_thread_in_workspace(workspace, metadata, true, window, cx);
2218
2219 self.update_entries(cx);
2220 }
2221
2222 fn activate_thread_in_other_window(
2223 &self,
2224 metadata: ThreadMetadata,
2225 workspace: Entity<Workspace>,
2226 target_window: WindowHandle<MultiWorkspace>,
2227 cx: &mut Context<Self>,
2228 ) {
2229 let target_session_id = metadata.session_id.clone();
2230 let workspace_for_entry = workspace.clone();
2231
2232 let activated = target_window
2233 .update(cx, |multi_workspace, window, cx| {
2234 window.activate_window();
2235 multi_workspace.activate(workspace.clone(), window, cx);
2236 Self::load_agent_thread_in_workspace(&workspace, &metadata, true, window, cx);
2237 })
2238 .log_err()
2239 .is_some();
2240
2241 if activated {
2242 if let Some(target_sidebar) = target_window
2243 .read(cx)
2244 .ok()
2245 .and_then(|multi_workspace| {
2246 multi_workspace.sidebar().map(|sidebar| sidebar.to_any())
2247 })
2248 .and_then(|sidebar| sidebar.downcast::<Self>().ok())
2249 {
2250 target_sidebar.update(cx, |sidebar, cx| {
2251 sidebar.active_entry = Some(ActiveEntry::Thread {
2252 session_id: target_session_id.clone(),
2253 workspace: workspace_for_entry.clone(),
2254 });
2255 sidebar.record_thread_access(&target_session_id);
2256 sidebar.update_entries(cx);
2257 });
2258 }
2259 }
2260 }
2261
2262 fn activate_thread(
2263 &mut self,
2264 metadata: ThreadMetadata,
2265 workspace: &Entity<Workspace>,
2266 retain: bool,
2267 window: &mut Window,
2268 cx: &mut Context<Self>,
2269 ) {
2270 if self
2271 .find_workspace_in_current_window(cx, |candidate, _| candidate == workspace)
2272 .is_some()
2273 {
2274 self.activate_thread_locally(&metadata, &workspace, retain, window, cx);
2275 return;
2276 }
2277
2278 let Some((target_window, workspace)) =
2279 self.find_workspace_across_windows(cx, |candidate, _| candidate == workspace)
2280 else {
2281 return;
2282 };
2283
2284 self.activate_thread_in_other_window(metadata, workspace, target_window, cx);
2285 }
2286
2287 fn open_workspace_and_activate_thread(
2288 &mut self,
2289 metadata: ThreadMetadata,
2290 folder_paths: PathList,
2291 project_group_key: &ProjectGroupKey,
2292 window: &mut Window,
2293 cx: &mut Context<Self>,
2294 ) {
2295 let Some(multi_workspace) = self.multi_workspace.upgrade() else {
2296 return;
2297 };
2298
2299 let pending_session_id = metadata.session_id.clone();
2300 let is_remote = project_group_key.host().is_some();
2301 if is_remote {
2302 self.pending_remote_thread_activation = Some(pending_session_id.clone());
2303 }
2304
2305 let host = project_group_key.host();
2306 let provisional_key = Some(project_group_key.clone());
2307 let active_workspace = multi_workspace.read(cx).workspace().clone();
2308
2309 let open_task = multi_workspace.update(cx, |this, cx| {
2310 this.find_or_create_workspace(
2311 folder_paths,
2312 host,
2313 provisional_key,
2314 |options, window, cx| connect_remote(active_workspace, options, window, cx),
2315 window,
2316 cx,
2317 )
2318 });
2319
2320 cx.spawn_in(window, async move |this, cx| {
2321 let result = open_task.await;
2322
2323 if result.is_err() || is_remote {
2324 this.update(cx, |this, _cx| {
2325 if this.pending_remote_thread_activation.as_ref() == Some(&pending_session_id) {
2326 this.pending_remote_thread_activation = None;
2327 }
2328 })
2329 .ok();
2330 }
2331
2332 let workspace = result?;
2333 this.update_in(cx, |this, window, cx| {
2334 this.activate_thread(metadata, &workspace, false, window, cx);
2335 })?;
2336 anyhow::Ok(())
2337 })
2338 .detach_and_log_err(cx);
2339 }
2340
2341 fn find_current_workspace_for_path_list(
2342 &self,
2343 path_list: &PathList,
2344 cx: &App,
2345 ) -> Option<Entity<Workspace>> {
2346 self.find_workspace_in_current_window(cx, |workspace, cx| {
2347 workspace_path_list(workspace, cx).paths() == path_list.paths()
2348 })
2349 }
2350
2351 fn find_open_workspace_for_path_list(
2352 &self,
2353 path_list: &PathList,
2354 cx: &App,
2355 ) -> Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> {
2356 self.find_workspace_across_windows(cx, |workspace, cx| {
2357 workspace_path_list(workspace, cx).paths() == path_list.paths()
2358 })
2359 }
2360
2361 fn activate_archived_thread(
2362 &mut self,
2363 metadata: ThreadMetadata,
2364 window: &mut Window,
2365 cx: &mut Context<Self>,
2366 ) {
2367 let session_id = metadata.session_id.clone();
2368
2369 ThreadMetadataStore::global(cx).update(cx, |store, cx| store.unarchive(&session_id, cx));
2370
2371 if metadata.folder_paths.paths().is_empty() {
2372 let active_workspace = self
2373 .multi_workspace
2374 .upgrade()
2375 .map(|w| w.read(cx).workspace().clone());
2376
2377 if let Some(workspace) = active_workspace {
2378 self.activate_thread_locally(&metadata, &workspace, false, window, cx);
2379 } else {
2380 let path_list = metadata.folder_paths.clone();
2381 if let Some((target_window, workspace)) =
2382 self.find_open_workspace_for_path_list(&path_list, cx)
2383 {
2384 self.activate_thread_in_other_window(metadata, workspace, target_window, cx);
2385 } else {
2386 // Archived thread metadata doesn't carry the remote host,
2387 // so we construct a local-only key as a best-effort fallback.
2388 let key = ProjectGroupKey::new(None, path_list.clone());
2389 self.open_workspace_and_activate_thread(metadata, path_list, &key, window, cx);
2390 }
2391 }
2392 return;
2393 }
2394
2395 let store = ThreadMetadataStore::global(cx);
2396 let task = store
2397 .read(cx)
2398 .get_archived_worktrees_for_thread(session_id.0.to_string(), cx);
2399 let path_list = metadata.folder_paths.clone();
2400
2401 cx.spawn_in(window, async move |this, cx| {
2402 let archived_worktrees = task.await?;
2403
2404 // No archived worktrees means the thread wasn't associated with a
2405 // linked worktree that got deleted, so we just need to find (or
2406 // open) a workspace that matches the thread's folder paths.
2407 if archived_worktrees.is_empty() {
2408 this.update_in(cx, |this, window, cx| {
2409 if let Some(workspace) =
2410 this.find_current_workspace_for_path_list(&path_list, cx)
2411 {
2412 this.activate_thread_locally(&metadata, &workspace, false, window, cx);
2413 } else if let Some((target_window, workspace)) =
2414 this.find_open_workspace_for_path_list(&path_list, cx)
2415 {
2416 this.activate_thread_in_other_window(
2417 metadata,
2418 workspace,
2419 target_window,
2420 cx,
2421 );
2422 } else {
2423 let key = ProjectGroupKey::new(None, path_list.clone());
2424 this.open_workspace_and_activate_thread(
2425 metadata, path_list, &key, window, cx,
2426 );
2427 }
2428 })?;
2429 return anyhow::Ok(());
2430 }
2431
2432 // Restore each archived worktree back to disk via git. If the
2433 // worktree already exists (e.g. a previous unarchive of a different
2434 // thread on the same worktree already restored it), it's reused
2435 // as-is. We track (old_path, restored_path) pairs so we can update
2436 // the thread's folder_paths afterward.
2437 let mut path_replacements: Vec<(PathBuf, PathBuf)> = Vec::new();
2438 for row in &archived_worktrees {
2439 match thread_worktree_archive::restore_worktree_via_git(row, &mut *cx).await {
2440 Ok(restored_path) => {
2441 // The worktree is on disk now; clean up the DB record
2442 // and git ref we created during archival.
2443 thread_worktree_archive::cleanup_archived_worktree_record(row, &mut *cx)
2444 .await;
2445 path_replacements.push((row.worktree_path.clone(), restored_path));
2446 }
2447 Err(error) => {
2448 log::error!("Failed to restore worktree: {error:#}");
2449 this.update_in(cx, |this, _window, cx| {
2450 if let Some(multi_workspace) = this.multi_workspace.upgrade() {
2451 let workspace = multi_workspace.read(cx).workspace().clone();
2452 workspace.update(cx, |workspace, cx| {
2453 struct RestoreWorktreeErrorToast;
2454 workspace.show_toast(
2455 Toast::new(
2456 NotificationId::unique::<RestoreWorktreeErrorToast>(),
2457 format!("Failed to restore worktree: {error:#}"),
2458 )
2459 .autohide(),
2460 cx,
2461 );
2462 });
2463 }
2464 })
2465 .ok();
2466 return anyhow::Ok(());
2467 }
2468 }
2469 }
2470
2471 if !path_replacements.is_empty() {
2472 // Update the thread's stored folder_paths: swap each old
2473 // worktree path for the restored path (which may differ if
2474 // the worktree was restored to a new location).
2475 cx.update(|_window, cx| {
2476 store.update(cx, |store, cx| {
2477 store.update_restored_worktree_paths(&session_id, &path_replacements, cx);
2478 });
2479 })?;
2480
2481 // Re-read the metadata (now with updated paths) and open
2482 // the workspace so the user lands in the restored worktree.
2483 let updated_metadata =
2484 cx.update(|_window, cx| store.read(cx).entry(&session_id).cloned())?;
2485
2486 if let Some(updated_metadata) = updated_metadata {
2487 let new_paths = updated_metadata.folder_paths.clone();
2488 this.update_in(cx, |this, window, cx| {
2489 let key = ProjectGroupKey::new(None, new_paths.clone());
2490 this.open_workspace_and_activate_thread(
2491 updated_metadata,
2492 new_paths,
2493 &key,
2494 window,
2495 cx,
2496 );
2497 })?;
2498 }
2499 }
2500
2501 anyhow::Ok(())
2502 })
2503 .detach_and_log_err(cx);
2504 }
2505
2506 fn expand_selected_entry(
2507 &mut self,
2508 _: &SelectChild,
2509 _window: &mut Window,
2510 cx: &mut Context<Self>,
2511 ) {
2512 let Some(ix) = self.selection else { return };
2513
2514 match self.contents.entries.get(ix) {
2515 Some(ListEntry::ProjectHeader { key, .. }) => {
2516 if self.collapsed_groups.contains(key) {
2517 self.collapsed_groups.remove(key);
2518 self.update_entries(cx);
2519 } else if ix + 1 < self.contents.entries.len() {
2520 self.selection = Some(ix + 1);
2521 self.list_state.scroll_to_reveal_item(ix + 1);
2522 cx.notify();
2523 }
2524 }
2525 _ => {}
2526 }
2527 }
2528
2529 fn collapse_selected_entry(
2530 &mut self,
2531 _: &SelectParent,
2532 _window: &mut Window,
2533 cx: &mut Context<Self>,
2534 ) {
2535 let Some(ix) = self.selection else { return };
2536
2537 match self.contents.entries.get(ix) {
2538 Some(ListEntry::ProjectHeader { key, .. }) => {
2539 if !self.collapsed_groups.contains(key) {
2540 self.collapsed_groups.insert(key.clone());
2541 self.update_entries(cx);
2542 }
2543 }
2544 Some(
2545 ListEntry::Thread(_) | ListEntry::ViewMore { .. } | ListEntry::DraftThread { .. },
2546 ) => {
2547 for i in (0..ix).rev() {
2548 if let Some(ListEntry::ProjectHeader { key, .. }) = self.contents.entries.get(i)
2549 {
2550 self.selection = Some(i);
2551 self.collapsed_groups.insert(key.clone());
2552 self.update_entries(cx);
2553 break;
2554 }
2555 }
2556 }
2557 None => {}
2558 }
2559 }
2560
2561 fn toggle_selected_fold(
2562 &mut self,
2563 _: &editor::actions::ToggleFold,
2564 _window: &mut Window,
2565 cx: &mut Context<Self>,
2566 ) {
2567 let Some(ix) = self.selection else { return };
2568
2569 // Find the group header for the current selection.
2570 let header_ix = match self.contents.entries.get(ix) {
2571 Some(ListEntry::ProjectHeader { .. }) => Some(ix),
2572 Some(
2573 ListEntry::Thread(_) | ListEntry::ViewMore { .. } | ListEntry::DraftThread { .. },
2574 ) => (0..ix).rev().find(|&i| {
2575 matches!(
2576 self.contents.entries.get(i),
2577 Some(ListEntry::ProjectHeader { .. })
2578 )
2579 }),
2580 None => None,
2581 };
2582
2583 if let Some(header_ix) = header_ix {
2584 if let Some(ListEntry::ProjectHeader { key, .. }) = self.contents.entries.get(header_ix)
2585 {
2586 if self.collapsed_groups.contains(key) {
2587 self.collapsed_groups.remove(key);
2588 } else {
2589 self.selection = Some(header_ix);
2590 self.collapsed_groups.insert(key.clone());
2591 }
2592 self.update_entries(cx);
2593 }
2594 }
2595 }
2596
2597 fn fold_all(
2598 &mut self,
2599 _: &editor::actions::FoldAll,
2600 _window: &mut Window,
2601 cx: &mut Context<Self>,
2602 ) {
2603 for entry in &self.contents.entries {
2604 if let ListEntry::ProjectHeader { key, .. } = entry {
2605 self.collapsed_groups.insert(key.clone());
2606 }
2607 }
2608 self.update_entries(cx);
2609 }
2610
2611 fn unfold_all(
2612 &mut self,
2613 _: &editor::actions::UnfoldAll,
2614 _window: &mut Window,
2615 cx: &mut Context<Self>,
2616 ) {
2617 self.collapsed_groups.clear();
2618 self.update_entries(cx);
2619 }
2620
2621 fn stop_thread(&mut self, session_id: &acp::SessionId, cx: &mut Context<Self>) {
2622 let Some(multi_workspace) = self.multi_workspace.upgrade() else {
2623 return;
2624 };
2625
2626 let workspaces: Vec<_> = multi_workspace.read(cx).workspaces().cloned().collect();
2627 for workspace in workspaces {
2628 if let Some(agent_panel) = workspace.read(cx).panel::<AgentPanel>(cx) {
2629 let cancelled =
2630 agent_panel.update(cx, |panel, cx| panel.cancel_thread(session_id, cx));
2631 if cancelled {
2632 return;
2633 }
2634 }
2635 }
2636 }
2637
2638 fn archive_thread(
2639 &mut self,
2640 session_id: &acp::SessionId,
2641 window: &mut Window,
2642 cx: &mut Context<Self>,
2643 ) {
2644 let metadata = ThreadMetadataStore::global(cx)
2645 .read(cx)
2646 .entry(session_id)
2647 .cloned();
2648 let thread_folder_paths = metadata.as_ref().map(|m| m.folder_paths.clone());
2649
2650 // Compute which linked worktree roots should be archived from disk if
2651 // this thread is archived. This must happen before we remove any
2652 // workspace from the MultiWorkspace, because `build_root_plan` needs
2653 // the currently open workspaces in order to find the affected projects
2654 // and repository handles for each linked worktree.
2655 let roots_to_archive = metadata
2656 .as_ref()
2657 .map(|metadata| {
2658 let mut workspaces = self
2659 .multi_workspace
2660 .upgrade()
2661 .map(|multi_workspace| {
2662 multi_workspace
2663 .read(cx)
2664 .workspaces()
2665 .cloned()
2666 .collect::<Vec<_>>()
2667 })
2668 .unwrap_or_default();
2669 for workspace in thread_worktree_archive::all_open_workspaces(cx) {
2670 if !workspaces.contains(&workspace) {
2671 workspaces.push(workspace);
2672 }
2673 }
2674 metadata
2675 .folder_paths
2676 .ordered_paths()
2677 .filter_map(|path| {
2678 thread_worktree_archive::build_root_plan(path, &workspaces, cx)
2679 })
2680 .filter(|plan| {
2681 !thread_worktree_archive::path_is_referenced_by_other_unarchived_threads(
2682 session_id,
2683 &plan.root_path,
2684 cx,
2685 )
2686 })
2687 .collect::<Vec<_>>()
2688 })
2689 .unwrap_or_default();
2690
2691 // Find the neighbor thread in the sidebar (by display position).
2692 // Look below first, then above, for the nearest thread that isn't
2693 // the one being archived. We capture both the neighbor's metadata
2694 // (for activation) and its workspace paths (for the workspace
2695 // removal fallback).
2696 let current_pos = self.contents.entries.iter().position(
2697 |entry| matches!(entry, ListEntry::Thread(t) if &t.metadata.session_id == session_id),
2698 );
2699 let neighbor = current_pos.and_then(|pos| {
2700 self.contents.entries[pos + 1..]
2701 .iter()
2702 .chain(self.contents.entries[..pos].iter().rev())
2703 .find_map(|entry| match entry {
2704 ListEntry::Thread(t) if t.metadata.session_id != *session_id => {
2705 let workspace_paths = match &t.workspace {
2706 ThreadEntryWorkspace::Open(ws) => {
2707 PathList::new(&ws.read(cx).root_paths(cx))
2708 }
2709 ThreadEntryWorkspace::Closed { folder_paths, .. } => {
2710 folder_paths.clone()
2711 }
2712 };
2713 Some((t.metadata.clone(), workspace_paths))
2714 }
2715 _ => None,
2716 })
2717 });
2718
2719 // Check if archiving this thread would leave its worktree workspace
2720 // with no threads, requiring workspace removal.
2721 let workspace_to_remove = thread_folder_paths.as_ref().and_then(|folder_paths| {
2722 if folder_paths.is_empty() {
2723 return None;
2724 }
2725
2726 let remaining = ThreadMetadataStore::global(cx)
2727 .read(cx)
2728 .entries_for_path(folder_paths)
2729 .filter(|t| t.session_id != *session_id)
2730 .count();
2731 if remaining > 0 {
2732 return None;
2733 }
2734
2735 let multi_workspace = self.multi_workspace.upgrade()?;
2736 // Thread metadata doesn't carry host info yet, so we pass
2737 // `None` here. This may match a local workspace with the same
2738 // paths instead of the intended remote one.
2739 let workspace = multi_workspace
2740 .read(cx)
2741 .workspace_for_paths(folder_paths, None, cx)?;
2742
2743 // Don't remove the main worktree workspace — the project
2744 // header always provides access to it.
2745 let group_key = workspace.read(cx).project_group_key(cx);
2746 (group_key.path_list() != folder_paths).then_some(workspace)
2747 });
2748
2749 if let Some(workspace_to_remove) = workspace_to_remove {
2750 let multi_workspace = self.multi_workspace.upgrade().unwrap();
2751 let session_id = session_id.clone();
2752
2753 // For the workspace-removal fallback, use the neighbor's workspace
2754 // paths if available, otherwise fall back to the project group key.
2755 let fallback_paths = neighbor
2756 .as_ref()
2757 .map(|(_, paths)| paths.clone())
2758 .unwrap_or_else(|| {
2759 workspace_to_remove
2760 .read(cx)
2761 .project_group_key(cx)
2762 .path_list()
2763 .clone()
2764 });
2765
2766 let remove_task = multi_workspace.update(cx, |mw, cx| {
2767 mw.remove(
2768 [workspace_to_remove],
2769 move |this, window, cx| {
2770 this.find_or_create_local_workspace(fallback_paths, window, cx)
2771 },
2772 window,
2773 cx,
2774 )
2775 });
2776
2777 let neighbor_metadata = neighbor.map(|(metadata, _)| metadata);
2778 let thread_folder_paths = thread_folder_paths.clone();
2779 cx.spawn_in(window, async move |this, cx| {
2780 let removed = remove_task.await?;
2781 if removed {
2782 this.update_in(cx, |this, window, cx| {
2783 let in_flight =
2784 this.start_archive_worktree_task(&session_id, roots_to_archive, cx);
2785 this.archive_and_activate(
2786 &session_id,
2787 neighbor_metadata.as_ref(),
2788 thread_folder_paths.as_ref(),
2789 in_flight,
2790 window,
2791 cx,
2792 );
2793 })?;
2794 }
2795 anyhow::Ok(())
2796 })
2797 .detach_and_log_err(cx);
2798 } else {
2799 // Simple case: no workspace removal needed.
2800 let neighbor_metadata = neighbor.map(|(metadata, _)| metadata);
2801 let in_flight = self.start_archive_worktree_task(session_id, roots_to_archive, cx);
2802 self.archive_and_activate(
2803 session_id,
2804 neighbor_metadata.as_ref(),
2805 thread_folder_paths.as_ref(),
2806 in_flight,
2807 window,
2808 cx,
2809 );
2810 }
2811 }
2812
2813 /// Archive a thread and activate the nearest neighbor or a draft.
2814 ///
2815 /// IMPORTANT: when activating a neighbor or creating a fallback draft,
2816 /// this method also activates the target workspace in the MultiWorkspace.
2817 /// This is critical because `rebuild_contents` derives the active
2818 /// workspace from `mw.workspace()`. If the linked worktree workspace is
2819 /// still active after archiving its last thread, `rebuild_contents` sees
2820 /// the threadless linked worktree as active and emits a spurious
2821 /// "+ New Thread" entry with the worktree chip — keeping the worktree
2822 /// alive and preventing disk cleanup.
2823 ///
2824 /// When `in_flight_archive` is present, it is the background task that
2825 /// persists the linked worktree's git state and deletes it from disk.
2826 /// We attach it to the metadata store at the same time we mark the thread
2827 /// archived so failures can automatically unarchive the thread and user-
2828 /// initiated unarchive can cancel the task.
2829 fn archive_and_activate(
2830 &mut self,
2831 session_id: &acp::SessionId,
2832 neighbor: Option<&ThreadMetadata>,
2833 thread_folder_paths: Option<&PathList>,
2834 in_flight_archive: Option<(Task<()>, smol::channel::Sender<()>)>,
2835 window: &mut Window,
2836 cx: &mut Context<Self>,
2837 ) {
2838 ThreadMetadataStore::global(cx).update(cx, |store, cx| {
2839 store.archive(session_id, in_flight_archive, cx);
2840 });
2841
2842 let is_active = self
2843 .active_entry
2844 .as_ref()
2845 .is_some_and(|e| e.is_active_thread(session_id));
2846
2847 if !is_active {
2848 // The user is looking at a different thread/draft. Clear the
2849 // archived thread from its workspace's panel so that switching
2850 // to that workspace later doesn't show a stale thread.
2851 if let Some(folder_paths) = thread_folder_paths {
2852 if let Some(workspace) = self
2853 .multi_workspace
2854 .upgrade()
2855 .and_then(|mw| mw.read(cx).workspace_for_paths(folder_paths, None, cx))
2856 {
2857 if let Some(panel) = workspace.read(cx).panel::<AgentPanel>(cx) {
2858 let panel_shows_archived = panel
2859 .read(cx)
2860 .active_conversation_view()
2861 .and_then(|cv| cv.read(cx).parent_id(cx))
2862 .is_some_and(|id| id == *session_id);
2863 if panel_shows_archived {
2864 panel.update(cx, |panel, cx| {
2865 panel.clear_active_thread(window, cx);
2866 });
2867 }
2868 }
2869 }
2870 }
2871 return;
2872 }
2873
2874 // Try to activate the neighbor thread. If its workspace is open,
2875 // tell the panel to load it and activate that workspace.
2876 // `rebuild_contents` will reconcile `active_entry` once the thread
2877 // finishes loading.
2878 if let Some(metadata) = neighbor {
2879 if let Some(workspace) = self.multi_workspace.upgrade().and_then(|mw| {
2880 mw.read(cx)
2881 .workspace_for_paths(&metadata.folder_paths, None, cx)
2882 }) {
2883 self.activate_workspace(&workspace, window, cx);
2884 Self::load_agent_thread_in_workspace(&workspace, metadata, true, window, cx);
2885 return;
2886 }
2887 }
2888
2889 // No neighbor or its workspace isn't open — fall back to a new
2890 // draft. Use the group workspace (main project) rather than the
2891 // active entry workspace, which may be a linked worktree that is
2892 // about to be cleaned up.
2893 let fallback_workspace = thread_folder_paths
2894 .and_then(|folder_paths| {
2895 let mw = self.multi_workspace.upgrade()?;
2896 let mw = mw.read(cx);
2897 // Find the group's main workspace (whose root paths match
2898 // the project group key, not the thread's folder paths).
2899 let thread_workspace = mw.workspace_for_paths(folder_paths, None, cx)?;
2900 let group_key = thread_workspace.read(cx).project_group_key(cx);
2901 mw.workspace_for_paths(group_key.path_list(), None, cx)
2902 })
2903 .or_else(|| self.active_entry_workspace().cloned());
2904
2905 if let Some(workspace) = fallback_workspace {
2906 self.activate_workspace(&workspace, window, cx);
2907 if let Some(panel) = workspace.read(cx).panel::<AgentPanel>(cx) {
2908 panel.update(cx, |panel, cx| {
2909 panel.new_thread(&NewThread, window, cx);
2910 });
2911 }
2912 }
2913 }
2914
2915 fn start_archive_worktree_task(
2916 &self,
2917 session_id: &acp::SessionId,
2918 roots: Vec<thread_worktree_archive::RootPlan>,
2919 cx: &mut Context<Self>,
2920 ) -> Option<(Task<()>, smol::channel::Sender<()>)> {
2921 if roots.is_empty() {
2922 return None;
2923 }
2924
2925 let (cancel_tx, cancel_rx) = smol::channel::bounded::<()>(1);
2926 let session_id = session_id.clone();
2927 let task = cx.spawn(async move |_this, cx| {
2928 match Self::archive_worktree_roots(roots, cancel_rx, cx).await {
2929 Ok(ArchiveWorktreeOutcome::Success) => {
2930 cx.update(|cx| {
2931 ThreadMetadataStore::global(cx).update(cx, |store, _cx| {
2932 store.cleanup_completed_archive(&session_id);
2933 });
2934 });
2935 }
2936 Ok(ArchiveWorktreeOutcome::Cancelled) => {}
2937 Err(error) => {
2938 log::error!("Failed to archive worktree: {error:#}");
2939 cx.update(|cx| {
2940 ThreadMetadataStore::global(cx).update(cx, |store, cx| {
2941 store.unarchive(&session_id, cx);
2942 });
2943 });
2944 }
2945 }
2946 });
2947
2948 Some((task, cancel_tx))
2949 }
2950
2951 async fn archive_worktree_roots(
2952 roots: Vec<thread_worktree_archive::RootPlan>,
2953 cancel_rx: smol::channel::Receiver<()>,
2954 cx: &mut gpui::AsyncApp,
2955 ) -> anyhow::Result<ArchiveWorktreeOutcome> {
2956 let mut completed_persists: Vec<(i64, thread_worktree_archive::RootPlan)> = Vec::new();
2957
2958 for root in &roots {
2959 if cancel_rx.is_closed() {
2960 for &(id, ref completed_root) in completed_persists.iter().rev() {
2961 thread_worktree_archive::rollback_persist(id, completed_root, cx).await;
2962 }
2963 return Ok(ArchiveWorktreeOutcome::Cancelled);
2964 }
2965
2966 if root.worktree_repo.is_some() {
2967 match thread_worktree_archive::persist_worktree_state(root, cx).await {
2968 Ok(id) => {
2969 completed_persists.push((id, root.clone()));
2970 }
2971 Err(error) => {
2972 for &(id, ref completed_root) in completed_persists.iter().rev() {
2973 thread_worktree_archive::rollback_persist(id, completed_root, cx).await;
2974 }
2975 return Err(error);
2976 }
2977 }
2978 }
2979
2980 if cancel_rx.is_closed() {
2981 for &(id, ref completed_root) in completed_persists.iter().rev() {
2982 thread_worktree_archive::rollback_persist(id, completed_root, cx).await;
2983 }
2984 return Ok(ArchiveWorktreeOutcome::Cancelled);
2985 }
2986
2987 if let Err(error) = thread_worktree_archive::remove_root(root.clone(), cx).await {
2988 if let Some(&(id, ref completed_root)) = completed_persists.last() {
2989 if completed_root.root_path == root.root_path {
2990 thread_worktree_archive::rollback_persist(id, completed_root, cx).await;
2991 completed_persists.pop();
2992 }
2993 }
2994 for &(id, ref completed_root) in completed_persists.iter().rev() {
2995 thread_worktree_archive::rollback_persist(id, completed_root, cx).await;
2996 }
2997 return Err(error);
2998 }
2999 }
3000
3001 Ok(ArchiveWorktreeOutcome::Success)
3002 }
3003
3004 fn activate_workspace(
3005 &self,
3006 workspace: &Entity<Workspace>,
3007 window: &mut Window,
3008 cx: &mut Context<Self>,
3009 ) {
3010 if let Some(multi_workspace) = self.multi_workspace.upgrade() {
3011 multi_workspace.update(cx, |mw, cx| {
3012 mw.activate(workspace.clone(), window, cx);
3013 });
3014 }
3015 }
3016
3017 fn remove_selected_thread(
3018 &mut self,
3019 _: &RemoveSelectedThread,
3020 window: &mut Window,
3021 cx: &mut Context<Self>,
3022 ) {
3023 let Some(ix) = self.selection else {
3024 return;
3025 };
3026 match self.contents.entries.get(ix) {
3027 Some(ListEntry::Thread(thread)) => {
3028 match thread.status {
3029 AgentThreadStatus::Running | AgentThreadStatus::WaitingForConfirmation => {
3030 return;
3031 }
3032 AgentThreadStatus::Completed | AgentThreadStatus::Error => {}
3033 }
3034 let session_id = thread.metadata.session_id.clone();
3035 self.archive_thread(&session_id, window, cx);
3036 }
3037 Some(ListEntry::DraftThread {
3038 workspace: Some(workspace),
3039 ..
3040 }) => {
3041 self.remove_worktree_workspace(workspace.clone(), window, cx);
3042 }
3043 _ => {}
3044 }
3045 }
3046
3047 fn remove_worktree_workspace(
3048 &mut self,
3049 workspace: Entity<Workspace>,
3050 window: &mut Window,
3051 cx: &mut Context<Self>,
3052 ) {
3053 if let Some(multi_workspace) = self.multi_workspace.upgrade() {
3054 multi_workspace
3055 .update(cx, |mw, cx| {
3056 mw.remove(
3057 [workspace],
3058 |this, _window, _cx| gpui::Task::ready(Ok(this.workspace().clone())),
3059 window,
3060 cx,
3061 )
3062 })
3063 .detach_and_log_err(cx);
3064 }
3065 }
3066
3067 fn record_thread_access(&mut self, session_id: &acp::SessionId) {
3068 self.thread_last_accessed
3069 .insert(session_id.clone(), Utc::now());
3070 }
3071
3072 fn record_thread_message_sent(&mut self, session_id: &acp::SessionId) {
3073 self.thread_last_message_sent_or_queued
3074 .insert(session_id.clone(), Utc::now());
3075 }
3076
3077 fn mru_threads_for_switcher(&self, cx: &App) -> Vec<ThreadSwitcherEntry> {
3078 let mut current_header_label: Option<SharedString> = None;
3079 let mut current_header_key: Option<ProjectGroupKey> = None;
3080 let mut entries: Vec<ThreadSwitcherEntry> = self
3081 .contents
3082 .entries
3083 .iter()
3084 .filter_map(|entry| match entry {
3085 ListEntry::ProjectHeader { label, key, .. } => {
3086 current_header_label = Some(label.clone());
3087 current_header_key = Some(key.clone());
3088 None
3089 }
3090 ListEntry::Thread(thread) => {
3091 let workspace = match &thread.workspace {
3092 ThreadEntryWorkspace::Open(workspace) => Some(workspace.clone()),
3093 ThreadEntryWorkspace::Closed { .. } => {
3094 current_header_key.as_ref().and_then(|key| {
3095 self.multi_workspace.upgrade().and_then(|mw| {
3096 mw.read(cx).workspace_for_paths(
3097 key.path_list(),
3098 key.host().as_ref(),
3099 cx,
3100 )
3101 })
3102 })
3103 }
3104 }?;
3105 let notified = self
3106 .contents
3107 .is_thread_notified(&thread.metadata.session_id);
3108 let timestamp: SharedString = format_history_entry_timestamp(
3109 self.thread_last_message_sent_or_queued
3110 .get(&thread.metadata.session_id)
3111 .copied()
3112 .or(thread.metadata.created_at)
3113 .unwrap_or(thread.metadata.updated_at),
3114 )
3115 .into();
3116 Some(ThreadSwitcherEntry {
3117 session_id: thread.metadata.session_id.clone(),
3118 title: thread.metadata.title.clone(),
3119 icon: thread.icon,
3120 icon_from_external_svg: thread.icon_from_external_svg.clone(),
3121 status: thread.status,
3122 metadata: thread.metadata.clone(),
3123 workspace,
3124 project_name: current_header_label.clone(),
3125 worktrees: thread
3126 .worktrees
3127 .iter()
3128 .map(|wt| ThreadItemWorktreeInfo {
3129 name: wt.name.clone(),
3130 full_path: wt.full_path.clone(),
3131 highlight_positions: Vec::new(),
3132 kind: wt.kind,
3133 })
3134 .collect(),
3135 diff_stats: thread.diff_stats,
3136 is_title_generating: thread.is_title_generating,
3137 notified,
3138 timestamp,
3139 })
3140 }
3141 _ => None,
3142 })
3143 .collect();
3144
3145 entries.sort_by(|a, b| {
3146 let a_accessed = self.thread_last_accessed.get(&a.session_id);
3147 let b_accessed = self.thread_last_accessed.get(&b.session_id);
3148
3149 match (a_accessed, b_accessed) {
3150 (Some(a_time), Some(b_time)) => b_time.cmp(a_time),
3151 (Some(_), None) => std::cmp::Ordering::Less,
3152 (None, Some(_)) => std::cmp::Ordering::Greater,
3153 (None, None) => {
3154 let a_sent = self.thread_last_message_sent_or_queued.get(&a.session_id);
3155 let b_sent = self.thread_last_message_sent_or_queued.get(&b.session_id);
3156
3157 match (a_sent, b_sent) {
3158 (Some(a_time), Some(b_time)) => b_time.cmp(a_time),
3159 (Some(_), None) => std::cmp::Ordering::Less,
3160 (None, Some(_)) => std::cmp::Ordering::Greater,
3161 (None, None) => {
3162 let a_time = a.metadata.created_at.or(Some(a.metadata.updated_at));
3163 let b_time = b.metadata.created_at.or(Some(b.metadata.updated_at));
3164 b_time.cmp(&a_time)
3165 }
3166 }
3167 }
3168 }
3169 });
3170
3171 entries
3172 }
3173
3174 fn dismiss_thread_switcher(&mut self, cx: &mut Context<Self>) {
3175 self.thread_switcher = None;
3176 self._thread_switcher_subscriptions.clear();
3177 if let Some(mw) = self.multi_workspace.upgrade() {
3178 mw.update(cx, |mw, cx| {
3179 mw.set_sidebar_overlay(None, cx);
3180 });
3181 }
3182 }
3183
3184 fn on_toggle_thread_switcher(
3185 &mut self,
3186 action: &ToggleThreadSwitcher,
3187 window: &mut Window,
3188 cx: &mut Context<Self>,
3189 ) {
3190 self.toggle_thread_switcher_impl(action.select_last, window, cx);
3191 }
3192
3193 fn toggle_thread_switcher_impl(
3194 &mut self,
3195 select_last: bool,
3196 window: &mut Window,
3197 cx: &mut Context<Self>,
3198 ) {
3199 if let Some(thread_switcher) = &self.thread_switcher {
3200 thread_switcher.update(cx, |switcher, cx| {
3201 if select_last {
3202 switcher.select_last(cx);
3203 } else {
3204 switcher.cycle_selection(cx);
3205 }
3206 });
3207 return;
3208 }
3209
3210 let entries = self.mru_threads_for_switcher(cx);
3211 if entries.len() < 2 {
3212 return;
3213 }
3214
3215 let weak_multi_workspace = self.multi_workspace.clone();
3216
3217 let original_metadata = match &self.active_entry {
3218 Some(ActiveEntry::Thread { session_id, .. }) => entries
3219 .iter()
3220 .find(|e| &e.session_id == session_id)
3221 .map(|e| e.metadata.clone()),
3222 _ => None,
3223 };
3224 let original_workspace = self
3225 .multi_workspace
3226 .upgrade()
3227 .map(|mw| mw.read(cx).workspace().clone());
3228
3229 let thread_switcher = cx.new(|cx| ThreadSwitcher::new(entries, select_last, window, cx));
3230
3231 let mut subscriptions = Vec::new();
3232
3233 subscriptions.push(cx.subscribe_in(&thread_switcher, window, {
3234 let thread_switcher = thread_switcher.clone();
3235 move |this, _emitter, event: &ThreadSwitcherEvent, window, cx| match event {
3236 ThreadSwitcherEvent::Preview {
3237 metadata,
3238 workspace,
3239 } => {
3240 if let Some(mw) = weak_multi_workspace.upgrade() {
3241 mw.update(cx, |mw, cx| {
3242 mw.activate(workspace.clone(), window, cx);
3243 });
3244 }
3245 this.active_entry = Some(ActiveEntry::Thread {
3246 session_id: metadata.session_id.clone(),
3247 workspace: workspace.clone(),
3248 });
3249 this.update_entries(cx);
3250 Self::load_agent_thread_in_workspace(workspace, metadata, false, window, cx);
3251 let focus = thread_switcher.focus_handle(cx);
3252 window.focus(&focus, cx);
3253 }
3254 ThreadSwitcherEvent::Confirmed {
3255 metadata,
3256 workspace,
3257 } => {
3258 if let Some(mw) = weak_multi_workspace.upgrade() {
3259 mw.update(cx, |mw, cx| {
3260 mw.activate(workspace.clone(), window, cx);
3261 mw.retain_active_workspace(cx);
3262 });
3263 }
3264 this.record_thread_access(&metadata.session_id);
3265 this.active_entry = Some(ActiveEntry::Thread {
3266 session_id: metadata.session_id.clone(),
3267 workspace: workspace.clone(),
3268 });
3269 this.update_entries(cx);
3270 Self::load_agent_thread_in_workspace(workspace, metadata, false, window, cx);
3271 this.dismiss_thread_switcher(cx);
3272 workspace.update(cx, |workspace, cx| {
3273 workspace.focus_panel::<AgentPanel>(window, cx);
3274 });
3275 }
3276 ThreadSwitcherEvent::Dismissed => {
3277 if let Some(mw) = weak_multi_workspace.upgrade() {
3278 if let Some(original_ws) = &original_workspace {
3279 mw.update(cx, |mw, cx| {
3280 mw.activate(original_ws.clone(), window, cx);
3281 });
3282 }
3283 }
3284 if let Some(metadata) = &original_metadata {
3285 if let Some(original_ws) = &original_workspace {
3286 this.active_entry = Some(ActiveEntry::Thread {
3287 session_id: metadata.session_id.clone(),
3288 workspace: original_ws.clone(),
3289 });
3290 }
3291 this.update_entries(cx);
3292 if let Some(original_ws) = &original_workspace {
3293 Self::load_agent_thread_in_workspace(
3294 original_ws,
3295 metadata,
3296 false,
3297 window,
3298 cx,
3299 );
3300 }
3301 }
3302 this.dismiss_thread_switcher(cx);
3303 }
3304 }
3305 }));
3306
3307 subscriptions.push(cx.subscribe_in(
3308 &thread_switcher,
3309 window,
3310 |this, _emitter, _event: &gpui::DismissEvent, _window, cx| {
3311 this.dismiss_thread_switcher(cx);
3312 },
3313 ));
3314
3315 let focus = thread_switcher.focus_handle(cx);
3316 let overlay_view = gpui::AnyView::from(thread_switcher.clone());
3317
3318 // Replay the initial preview that was emitted during construction
3319 // before subscriptions were wired up.
3320 let initial_preview = thread_switcher
3321 .read(cx)
3322 .selected_entry()
3323 .map(|entry| (entry.metadata.clone(), entry.workspace.clone()));
3324
3325 self.thread_switcher = Some(thread_switcher);
3326 self._thread_switcher_subscriptions = subscriptions;
3327 if let Some(mw) = self.multi_workspace.upgrade() {
3328 mw.update(cx, |mw, cx| {
3329 mw.set_sidebar_overlay(Some(overlay_view), cx);
3330 });
3331 }
3332
3333 if let Some((metadata, workspace)) = initial_preview {
3334 if let Some(mw) = self.multi_workspace.upgrade() {
3335 mw.update(cx, |mw, cx| {
3336 mw.activate(workspace.clone(), window, cx);
3337 });
3338 }
3339 self.active_entry = Some(ActiveEntry::Thread {
3340 session_id: metadata.session_id.clone(),
3341 workspace: workspace.clone(),
3342 });
3343 self.update_entries(cx);
3344 Self::load_agent_thread_in_workspace(&workspace, &metadata, false, window, cx);
3345 }
3346
3347 window.focus(&focus, cx);
3348 }
3349
3350 fn render_thread(
3351 &self,
3352 ix: usize,
3353 thread: &ThreadEntry,
3354 is_active: bool,
3355 is_focused: bool,
3356 cx: &mut Context<Self>,
3357 ) -> AnyElement {
3358 let has_notification = self
3359 .contents
3360 .is_thread_notified(&thread.metadata.session_id);
3361
3362 let title: SharedString = thread.metadata.title.clone();
3363 let metadata = thread.metadata.clone();
3364 let thread_workspace = thread.workspace.clone();
3365
3366 let is_hovered = self.hovered_thread_index == Some(ix);
3367 let is_selected = is_active;
3368 let is_running = matches!(
3369 thread.status,
3370 AgentThreadStatus::Running | AgentThreadStatus::WaitingForConfirmation
3371 );
3372
3373 let session_id_for_delete = thread.metadata.session_id.clone();
3374 let focus_handle = self.focus_handle.clone();
3375
3376 let id = SharedString::from(format!("thread-entry-{}", ix));
3377
3378 let color = cx.theme().colors();
3379 let sidebar_bg = color
3380 .title_bar_background
3381 .blend(color.panel_background.opacity(0.25));
3382
3383 let timestamp = format_history_entry_timestamp(
3384 self.thread_last_message_sent_or_queued
3385 .get(&thread.metadata.session_id)
3386 .copied()
3387 .or(thread.metadata.created_at)
3388 .unwrap_or(thread.metadata.updated_at),
3389 );
3390
3391 let is_remote = thread.workspace.is_remote(cx);
3392
3393 ThreadItem::new(id, title)
3394 .base_bg(sidebar_bg)
3395 .icon(thread.icon)
3396 .status(thread.status)
3397 .is_remote(is_remote)
3398 .when_some(thread.icon_from_external_svg.clone(), |this, svg| {
3399 this.custom_icon_from_external_svg(svg)
3400 })
3401 .worktrees(
3402 thread
3403 .worktrees
3404 .iter()
3405 .map(|wt| ThreadItemWorktreeInfo {
3406 name: wt.name.clone(),
3407 full_path: wt.full_path.clone(),
3408 highlight_positions: wt.highlight_positions.clone(),
3409 kind: wt.kind,
3410 })
3411 .collect(),
3412 )
3413 .timestamp(timestamp)
3414 .highlight_positions(thread.highlight_positions.to_vec())
3415 .title_generating(thread.is_title_generating)
3416 .notified(has_notification)
3417 .when(thread.diff_stats.lines_added > 0, |this| {
3418 this.added(thread.diff_stats.lines_added as usize)
3419 })
3420 .when(thread.diff_stats.lines_removed > 0, |this| {
3421 this.removed(thread.diff_stats.lines_removed as usize)
3422 })
3423 .selected(is_selected)
3424 .focused(is_focused)
3425 .hovered(is_hovered)
3426 .on_hover(cx.listener(move |this, is_hovered: &bool, _window, cx| {
3427 if *is_hovered {
3428 this.hovered_thread_index = Some(ix);
3429 } else if this.hovered_thread_index == Some(ix) {
3430 this.hovered_thread_index = None;
3431 }
3432 cx.notify();
3433 }))
3434 .when(is_hovered && is_running, |this| {
3435 this.action_slot(
3436 IconButton::new("stop-thread", IconName::Stop)
3437 .icon_size(IconSize::Small)
3438 .icon_color(Color::Error)
3439 .style(ButtonStyle::Tinted(TintColor::Error))
3440 .tooltip(Tooltip::text("Stop Generation"))
3441 .on_click({
3442 let session_id = session_id_for_delete.clone();
3443 cx.listener(move |this, _, _window, cx| {
3444 this.stop_thread(&session_id, cx);
3445 })
3446 }),
3447 )
3448 })
3449 .when(is_hovered && !is_running, |this| {
3450 this.action_slot(
3451 IconButton::new("archive-thread", IconName::Archive)
3452 .icon_size(IconSize::Small)
3453 .icon_color(Color::Muted)
3454 .tooltip({
3455 let focus_handle = focus_handle.clone();
3456 move |_window, cx| {
3457 Tooltip::for_action_in(
3458 "Archive Thread",
3459 &RemoveSelectedThread,
3460 &focus_handle,
3461 cx,
3462 )
3463 }
3464 })
3465 .on_click({
3466 let session_id = session_id_for_delete.clone();
3467 cx.listener(move |this, _, window, cx| {
3468 this.archive_thread(&session_id, window, cx);
3469 })
3470 }),
3471 )
3472 })
3473 .on_click({
3474 cx.listener(move |this, _, window, cx| {
3475 this.selection = None;
3476 match &thread_workspace {
3477 ThreadEntryWorkspace::Open(workspace) => {
3478 this.activate_thread(metadata.clone(), workspace, false, window, cx);
3479 }
3480 ThreadEntryWorkspace::Closed {
3481 folder_paths,
3482 project_group_key,
3483 } => {
3484 this.open_workspace_and_activate_thread(
3485 metadata.clone(),
3486 folder_paths.clone(),
3487 project_group_key,
3488 window,
3489 cx,
3490 );
3491 }
3492 }
3493 })
3494 })
3495 .into_any_element()
3496 }
3497
3498 fn render_filter_input(&self, cx: &mut Context<Self>) -> impl IntoElement {
3499 div()
3500 .min_w_0()
3501 .flex_1()
3502 .capture_action(
3503 cx.listener(|this, _: &editor::actions::Newline, window, cx| {
3504 this.editor_confirm(window, cx);
3505 }),
3506 )
3507 .child(self.filter_editor.clone())
3508 }
3509
3510 fn render_recent_projects_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
3511 let multi_workspace = self.multi_workspace.upgrade();
3512
3513 let workspace = multi_workspace
3514 .as_ref()
3515 .map(|mw| mw.read(cx).workspace().downgrade());
3516
3517 let focus_handle = workspace
3518 .as_ref()
3519 .and_then(|ws| ws.upgrade())
3520 .map(|w| w.read(cx).focus_handle(cx))
3521 .unwrap_or_else(|| cx.focus_handle());
3522
3523 let window_project_groups: Vec<ProjectGroupKey> = multi_workspace
3524 .as_ref()
3525 .map(|mw| mw.read(cx).project_group_keys().cloned().collect())
3526 .unwrap_or_default();
3527
3528 let popover_handle = self.recent_projects_popover_handle.clone();
3529
3530 PopoverMenu::new("sidebar-recent-projects-menu")
3531 .with_handle(popover_handle)
3532 .menu(move |window, cx| {
3533 workspace.as_ref().map(|ws| {
3534 SidebarRecentProjects::popover(
3535 ws.clone(),
3536 window_project_groups.clone(),
3537 focus_handle.clone(),
3538 window,
3539 cx,
3540 )
3541 })
3542 })
3543 .trigger_with_tooltip(
3544 IconButton::new("open-project", IconName::OpenFolder)
3545 .icon_size(IconSize::Small)
3546 .selected_style(ButtonStyle::Tinted(TintColor::Accent)),
3547 |_window, cx| {
3548 Tooltip::for_action(
3549 "Add Project",
3550 &OpenRecent {
3551 create_new_window: false,
3552 },
3553 cx,
3554 )
3555 },
3556 )
3557 .offset(gpui::Point {
3558 x: px(-2.0),
3559 y: px(-2.0),
3560 })
3561 .anchor(gpui::Corner::BottomRight)
3562 }
3563
3564 fn render_view_more(
3565 &self,
3566 ix: usize,
3567 key: &ProjectGroupKey,
3568 is_fully_expanded: bool,
3569 is_selected: bool,
3570 cx: &mut Context<Self>,
3571 ) -> AnyElement {
3572 let key = key.clone();
3573 let id = SharedString::from(format!("view-more-{}", ix));
3574
3575 let label: SharedString = if is_fully_expanded {
3576 "Collapse".into()
3577 } else {
3578 "View More".into()
3579 };
3580
3581 ThreadItem::new(id, label)
3582 .focused(is_selected)
3583 .icon_visible(false)
3584 .title_label_color(Color::Muted)
3585 .on_click(cx.listener(move |this, _, _window, cx| {
3586 this.selection = None;
3587 if is_fully_expanded {
3588 this.reset_thread_group_expansion(&key, cx);
3589 } else {
3590 this.expand_thread_group(&key, cx);
3591 }
3592 }))
3593 .into_any_element()
3594 }
3595
3596 fn new_thread_in_group(
3597 &mut self,
3598 _: &NewThreadInGroup,
3599 window: &mut Window,
3600 cx: &mut Context<Self>,
3601 ) {
3602 // If there is a keyboard selection, walk backwards through
3603 // `project_header_indices` to find the header that owns the selected
3604 // row. Otherwise fall back to the active workspace.
3605 let workspace = if let Some(selected_ix) = self.selection {
3606 self.contents
3607 .project_header_indices
3608 .iter()
3609 .rev()
3610 .find(|&&header_ix| header_ix <= selected_ix)
3611 .and_then(|&header_ix| match &self.contents.entries[header_ix] {
3612 ListEntry::ProjectHeader { key, .. } => {
3613 self.multi_workspace.upgrade().and_then(|mw| {
3614 mw.read(cx).workspace_for_paths(
3615 key.path_list(),
3616 key.host().as_ref(),
3617 cx,
3618 )
3619 })
3620 }
3621 _ => None,
3622 })
3623 } else {
3624 // Use the currently active workspace.
3625 self.multi_workspace
3626 .upgrade()
3627 .map(|mw| mw.read(cx).workspace().clone())
3628 };
3629
3630 let Some(workspace) = workspace else {
3631 return;
3632 };
3633
3634 self.create_new_thread(&workspace, window, cx);
3635 }
3636
3637 fn create_new_thread(
3638 &mut self,
3639 workspace: &Entity<Workspace>,
3640 window: &mut Window,
3641 cx: &mut Context<Self>,
3642 ) {
3643 let Some(multi_workspace) = self.multi_workspace.upgrade() else {
3644 return;
3645 };
3646
3647 self.active_entry = Some(ActiveEntry::Draft(workspace.clone()));
3648
3649 multi_workspace.update(cx, |multi_workspace, cx| {
3650 multi_workspace.activate(workspace.clone(), window, cx);
3651 });
3652
3653 workspace.update(cx, |workspace, cx| {
3654 if let Some(agent_panel) = workspace.panel::<AgentPanel>(cx) {
3655 agent_panel.update(cx, |panel, cx| {
3656 panel.new_thread(&NewThread, window, cx);
3657 });
3658 }
3659 workspace.focus_panel::<AgentPanel>(window, cx);
3660 });
3661 }
3662
3663 fn active_project_group_key(&self, cx: &App) -> Option<ProjectGroupKey> {
3664 let multi_workspace = self.multi_workspace.upgrade()?;
3665 let multi_workspace = multi_workspace.read(cx);
3666 Some(multi_workspace.project_group_key_for_workspace(multi_workspace.workspace(), cx))
3667 }
3668
3669 fn active_project_header_position(&self, cx: &App) -> Option<usize> {
3670 let active_key = self.active_project_group_key(cx)?;
3671 self.contents
3672 .project_header_indices
3673 .iter()
3674 .position(|&entry_ix| {
3675 matches!(
3676 &self.contents.entries[entry_ix],
3677 ListEntry::ProjectHeader { key, .. } if *key == active_key
3678 )
3679 })
3680 }
3681
3682 fn cycle_project_impl(&mut self, forward: bool, window: &mut Window, cx: &mut Context<Self>) {
3683 let Some(multi_workspace) = self.multi_workspace.upgrade() else {
3684 return;
3685 };
3686
3687 let header_count = self.contents.project_header_indices.len();
3688 if header_count == 0 {
3689 return;
3690 }
3691
3692 let current_pos = self.active_project_header_position(cx);
3693
3694 let next_pos = match current_pos {
3695 Some(pos) => {
3696 if forward {
3697 (pos + 1) % header_count
3698 } else {
3699 (pos + header_count - 1) % header_count
3700 }
3701 }
3702 None => 0,
3703 };
3704
3705 let header_entry_ix = self.contents.project_header_indices[next_pos];
3706 let Some(ListEntry::ProjectHeader { key, .. }) = self.contents.entries.get(header_entry_ix)
3707 else {
3708 return;
3709 };
3710 let key = key.clone();
3711
3712 // Uncollapse the target group so that threads become visible.
3713 self.collapsed_groups.remove(&key);
3714
3715 if let Some(workspace) = self.multi_workspace.upgrade().and_then(|mw| {
3716 mw.read(cx)
3717 .workspace_for_paths(key.path_list(), key.host().as_ref(), cx)
3718 }) {
3719 multi_workspace.update(cx, |multi_workspace, cx| {
3720 multi_workspace.activate(workspace, window, cx);
3721 multi_workspace.retain_active_workspace(cx);
3722 });
3723 } else {
3724 self.open_workspace_for_group(&key, window, cx);
3725 }
3726 }
3727
3728 fn on_next_project(&mut self, _: &NextProject, window: &mut Window, cx: &mut Context<Self>) {
3729 self.cycle_project_impl(true, window, cx);
3730 }
3731
3732 fn on_previous_project(
3733 &mut self,
3734 _: &PreviousProject,
3735 window: &mut Window,
3736 cx: &mut Context<Self>,
3737 ) {
3738 self.cycle_project_impl(false, window, cx);
3739 }
3740
3741 fn cycle_thread_impl(&mut self, forward: bool, window: &mut Window, cx: &mut Context<Self>) {
3742 let thread_indices: Vec<usize> = self
3743 .contents
3744 .entries
3745 .iter()
3746 .enumerate()
3747 .filter_map(|(ix, entry)| match entry {
3748 ListEntry::Thread(_) => Some(ix),
3749 _ => None,
3750 })
3751 .collect();
3752
3753 if thread_indices.is_empty() {
3754 return;
3755 }
3756
3757 let current_thread_pos = self.active_entry.as_ref().and_then(|active| {
3758 thread_indices
3759 .iter()
3760 .position(|&ix| active.matches_entry(&self.contents.entries[ix]))
3761 });
3762
3763 let next_pos = match current_thread_pos {
3764 Some(pos) => {
3765 let count = thread_indices.len();
3766 if forward {
3767 (pos + 1) % count
3768 } else {
3769 (pos + count - 1) % count
3770 }
3771 }
3772 None => 0,
3773 };
3774
3775 let entry_ix = thread_indices[next_pos];
3776 let ListEntry::Thread(thread) = &self.contents.entries[entry_ix] else {
3777 return;
3778 };
3779
3780 let metadata = thread.metadata.clone();
3781 match &thread.workspace {
3782 ThreadEntryWorkspace::Open(workspace) => {
3783 let workspace = workspace.clone();
3784 self.activate_thread(metadata, &workspace, true, window, cx);
3785 }
3786 ThreadEntryWorkspace::Closed {
3787 folder_paths,
3788 project_group_key,
3789 } => {
3790 let folder_paths = folder_paths.clone();
3791 let project_group_key = project_group_key.clone();
3792 self.open_workspace_and_activate_thread(
3793 metadata,
3794 folder_paths,
3795 &project_group_key,
3796 window,
3797 cx,
3798 );
3799 }
3800 }
3801 }
3802
3803 fn on_next_thread(&mut self, _: &NextThread, window: &mut Window, cx: &mut Context<Self>) {
3804 self.cycle_thread_impl(true, window, cx);
3805 }
3806
3807 fn on_previous_thread(
3808 &mut self,
3809 _: &PreviousThread,
3810 window: &mut Window,
3811 cx: &mut Context<Self>,
3812 ) {
3813 self.cycle_thread_impl(false, window, cx);
3814 }
3815
3816 fn expand_thread_group(&mut self, project_group_key: &ProjectGroupKey, cx: &mut Context<Self>) {
3817 let current = self
3818 .expanded_groups
3819 .get(project_group_key)
3820 .copied()
3821 .unwrap_or(0);
3822 self.expanded_groups
3823 .insert(project_group_key.clone(), current + 1);
3824 self.serialize(cx);
3825 self.update_entries(cx);
3826 }
3827
3828 fn reset_thread_group_expansion(
3829 &mut self,
3830 project_group_key: &ProjectGroupKey,
3831 cx: &mut Context<Self>,
3832 ) {
3833 self.expanded_groups.remove(project_group_key);
3834 self.serialize(cx);
3835 self.update_entries(cx);
3836 }
3837
3838 fn collapse_thread_group(
3839 &mut self,
3840 project_group_key: &ProjectGroupKey,
3841 cx: &mut Context<Self>,
3842 ) {
3843 match self.expanded_groups.get(project_group_key).copied() {
3844 Some(batches) if batches > 1 => {
3845 self.expanded_groups
3846 .insert(project_group_key.clone(), batches - 1);
3847 }
3848 Some(_) => {
3849 self.expanded_groups.remove(project_group_key);
3850 }
3851 None => return,
3852 }
3853 self.serialize(cx);
3854 self.update_entries(cx);
3855 }
3856
3857 fn on_show_more_threads(
3858 &mut self,
3859 _: &ShowMoreThreads,
3860 _window: &mut Window,
3861 cx: &mut Context<Self>,
3862 ) {
3863 let Some(active_key) = self.active_project_group_key(cx) else {
3864 return;
3865 };
3866 self.expand_thread_group(&active_key, cx);
3867 }
3868
3869 fn on_show_fewer_threads(
3870 &mut self,
3871 _: &ShowFewerThreads,
3872 _window: &mut Window,
3873 cx: &mut Context<Self>,
3874 ) {
3875 let Some(active_key) = self.active_project_group_key(cx) else {
3876 return;
3877 };
3878 self.collapse_thread_group(&active_key, cx);
3879 }
3880
3881 fn on_new_thread(
3882 &mut self,
3883 _: &workspace::NewThread,
3884 window: &mut Window,
3885 cx: &mut Context<Self>,
3886 ) {
3887 let Some(workspace) = self.active_workspace(cx) else {
3888 return;
3889 };
3890 self.create_new_thread(&workspace, window, cx);
3891 }
3892
3893 fn render_draft_thread(
3894 &self,
3895 ix: usize,
3896 is_active: bool,
3897 worktrees: &[WorktreeInfo],
3898 is_selected: bool,
3899 cx: &mut Context<Self>,
3900 ) -> AnyElement {
3901 let label: SharedString = if is_active {
3902 self.active_draft_text(cx)
3903 .unwrap_or_else(|| "New Thread".into())
3904 } else {
3905 "New Thread".into()
3906 };
3907
3908 let id = SharedString::from(format!("draft-thread-btn-{}", ix));
3909
3910 let thread_item = ThreadItem::new(id, label)
3911 .icon(IconName::Plus)
3912 .icon_color(Color::Custom(cx.theme().colors().icon_muted.opacity(0.8)))
3913 .worktrees(
3914 worktrees
3915 .iter()
3916 .map(|wt| ThreadItemWorktreeInfo {
3917 name: wt.name.clone(),
3918 full_path: wt.full_path.clone(),
3919 highlight_positions: wt.highlight_positions.clone(),
3920 kind: wt.kind,
3921 })
3922 .collect(),
3923 )
3924 .selected(true)
3925 .focused(is_selected)
3926 .on_click(cx.listener(|this, _, window, cx| {
3927 if let Some(workspace) = this.active_workspace(cx) {
3928 if !AgentPanel::is_visible(&workspace, cx) {
3929 workspace.update(cx, |workspace, cx| {
3930 workspace.focus_panel::<AgentPanel>(window, cx);
3931 });
3932 }
3933 }
3934 }));
3935
3936 div()
3937 .on_mouse_down(gpui::MouseButton::Left, |_, _, cx| {
3938 cx.stop_propagation();
3939 })
3940 .child(thread_item)
3941 .into_any_element()
3942 }
3943
3944 fn render_new_thread(
3945 &self,
3946 ix: usize,
3947 key: &ProjectGroupKey,
3948 worktrees: &[WorktreeInfo],
3949 workspace: Option<&Entity<Workspace>>,
3950 is_selected: bool,
3951 cx: &mut Context<Self>,
3952 ) -> AnyElement {
3953 let label: SharedString = DEFAULT_THREAD_TITLE.into();
3954 let key = key.clone();
3955
3956 let id = SharedString::from(format!("new-thread-btn-{}", ix));
3957
3958 let mut thread_item = ThreadItem::new(id, label)
3959 .icon(IconName::Plus)
3960 .icon_color(Color::Custom(cx.theme().colors().icon_muted.opacity(0.8)))
3961 .worktrees(
3962 worktrees
3963 .iter()
3964 .map(|wt| ThreadItemWorktreeInfo {
3965 name: wt.name.clone(),
3966 full_path: wt.full_path.clone(),
3967 highlight_positions: wt.highlight_positions.clone(),
3968 kind: wt.kind,
3969 })
3970 .collect(),
3971 )
3972 .selected(false)
3973 .focused(is_selected)
3974 .on_click(cx.listener(move |this, _, window, cx| {
3975 this.selection = None;
3976 if let Some(workspace) = this.multi_workspace.upgrade().and_then(|mw| {
3977 mw.read(cx)
3978 .workspace_for_paths(key.path_list(), key.host().as_ref(), cx)
3979 }) {
3980 this.create_new_thread(&workspace, window, cx);
3981 } else {
3982 this.open_workspace_for_group(&key, window, cx);
3983 }
3984 }));
3985
3986 // Linked worktree DraftThread entries can be dismissed, which removes
3987 // the workspace from the multi-workspace.
3988 if let Some(workspace) = workspace.cloned() {
3989 thread_item = thread_item.action_slot(
3990 IconButton::new("close-worktree-workspace", IconName::Close)
3991 .icon_size(IconSize::Small)
3992 .icon_color(Color::Muted)
3993 .tooltip(Tooltip::text("Close Workspace"))
3994 .on_click(cx.listener(move |this, _, window, cx| {
3995 this.remove_worktree_workspace(workspace.clone(), window, cx);
3996 })),
3997 );
3998 }
3999
4000 thread_item.into_any_element()
4001 }
4002
4003 fn render_no_results(&self, cx: &mut Context<Self>) -> impl IntoElement {
4004 let has_query = self.has_filter_query(cx);
4005 let message = if has_query {
4006 "No threads match your search."
4007 } else {
4008 "No threads yet"
4009 };
4010
4011 v_flex()
4012 .id("sidebar-no-results")
4013 .p_4()
4014 .size_full()
4015 .items_center()
4016 .justify_center()
4017 .child(
4018 Label::new(message)
4019 .size(LabelSize::Small)
4020 .color(Color::Muted),
4021 )
4022 }
4023
4024 fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
4025 v_flex()
4026 .id("sidebar-empty-state")
4027 .p_4()
4028 .size_full()
4029 .items_center()
4030 .justify_center()
4031 .gap_1()
4032 .track_focus(&self.focus_handle(cx))
4033 .child(
4034 Button::new("open_project", "Open Project")
4035 .full_width()
4036 .key_binding(KeyBinding::for_action(&workspace::Open::default(), cx))
4037 .on_click(|_, window, cx| {
4038 window.dispatch_action(
4039 Open {
4040 create_new_window: false,
4041 }
4042 .boxed_clone(),
4043 cx,
4044 );
4045 }),
4046 )
4047 .child(
4048 h_flex()
4049 .w_1_2()
4050 .gap_2()
4051 .child(Divider::horizontal().color(ui::DividerColor::Border))
4052 .child(Label::new("or").size(LabelSize::XSmall).color(Color::Muted))
4053 .child(Divider::horizontal().color(ui::DividerColor::Border)),
4054 )
4055 .child(
4056 Button::new("clone_repo", "Clone Repository")
4057 .full_width()
4058 .on_click(|_, window, cx| {
4059 window.dispatch_action(git::Clone.boxed_clone(), cx);
4060 }),
4061 )
4062 }
4063
4064 fn render_sidebar_header(
4065 &self,
4066 no_open_projects: bool,
4067 window: &Window,
4068 cx: &mut Context<Self>,
4069 ) -> impl IntoElement {
4070 let has_query = self.has_filter_query(cx);
4071 let sidebar_on_left = self.side(cx) == SidebarSide::Left;
4072 let sidebar_on_right = self.side(cx) == SidebarSide::Right;
4073 let not_fullscreen = !window.is_fullscreen();
4074 let traffic_lights = cfg!(target_os = "macos") && not_fullscreen && sidebar_on_left;
4075 let left_window_controls = !cfg!(target_os = "macos") && not_fullscreen && sidebar_on_left;
4076 let right_window_controls =
4077 !cfg!(target_os = "macos") && not_fullscreen && sidebar_on_right;
4078 let header_height = platform_title_bar_height(window);
4079
4080 h_flex()
4081 .h(header_height)
4082 .mt_px()
4083 .pb_px()
4084 .when(left_window_controls, |this| {
4085 this.children(Self::render_left_window_controls(window, cx))
4086 })
4087 .map(|this| {
4088 if traffic_lights {
4089 this.pl(px(ui::utils::TRAFFIC_LIGHT_PADDING))
4090 } else if !left_window_controls {
4091 this.pl_1p5()
4092 } else {
4093 this
4094 }
4095 })
4096 .when(!right_window_controls, |this| this.pr_1p5())
4097 .gap_1()
4098 .when(!no_open_projects, |this| {
4099 this.border_b_1()
4100 .border_color(cx.theme().colors().border)
4101 .when(traffic_lights, |this| {
4102 this.child(Divider::vertical().color(ui::DividerColor::Border))
4103 })
4104 .child(
4105 div().ml_1().child(
4106 Icon::new(IconName::MagnifyingGlass)
4107 .size(IconSize::Small)
4108 .color(Color::Muted),
4109 ),
4110 )
4111 .child(self.render_filter_input(cx))
4112 .child(
4113 h_flex()
4114 .gap_1()
4115 .when(
4116 self.selection.is_some()
4117 && !self.filter_editor.focus_handle(cx).is_focused(window),
4118 |this| this.child(KeyBinding::for_action(&FocusSidebarFilter, cx)),
4119 )
4120 .when(has_query, |this| {
4121 this.child(
4122 IconButton::new("clear_filter", IconName::Close)
4123 .icon_size(IconSize::Small)
4124 .tooltip(Tooltip::text("Clear Search"))
4125 .on_click(cx.listener(|this, _, window, cx| {
4126 this.reset_filter_editor_text(window, cx);
4127 this.update_entries(cx);
4128 })),
4129 )
4130 }),
4131 )
4132 })
4133 .when(right_window_controls, |this| {
4134 this.children(Self::render_right_window_controls(window, cx))
4135 })
4136 }
4137
4138 fn render_left_window_controls(window: &Window, cx: &mut App) -> Option<AnyElement> {
4139 platform_title_bar::render_left_window_controls(
4140 cx.button_layout(),
4141 Box::new(CloseWindow),
4142 window,
4143 )
4144 }
4145
4146 fn render_right_window_controls(window: &Window, cx: &mut App) -> Option<AnyElement> {
4147 platform_title_bar::render_right_window_controls(
4148 cx.button_layout(),
4149 Box::new(CloseWindow),
4150 window,
4151 )
4152 }
4153
4154 fn render_sidebar_toggle_button(&self, _cx: &mut Context<Self>) -> impl IntoElement {
4155 let on_right = AgentSettings::get_global(_cx).sidebar_side() == SidebarSide::Right;
4156
4157 sidebar_side_context_menu("sidebar-toggle-menu", _cx)
4158 .anchor(if on_right {
4159 gpui::Corner::BottomRight
4160 } else {
4161 gpui::Corner::BottomLeft
4162 })
4163 .attach(if on_right {
4164 gpui::Corner::TopRight
4165 } else {
4166 gpui::Corner::TopLeft
4167 })
4168 .trigger(move |_is_active, _window, _cx| {
4169 let icon = if on_right {
4170 IconName::ThreadsSidebarRightOpen
4171 } else {
4172 IconName::ThreadsSidebarLeftOpen
4173 };
4174 IconButton::new("sidebar-close-toggle", icon)
4175 .icon_size(IconSize::Small)
4176 .tooltip(Tooltip::element(move |_window, cx| {
4177 v_flex()
4178 .gap_1()
4179 .child(
4180 h_flex()
4181 .gap_2()
4182 .justify_between()
4183 .child(Label::new("Toggle Sidebar"))
4184 .child(KeyBinding::for_action(&ToggleWorkspaceSidebar, cx)),
4185 )
4186 .child(
4187 h_flex()
4188 .pt_1()
4189 .gap_2()
4190 .border_t_1()
4191 .border_color(cx.theme().colors().border_variant)
4192 .justify_between()
4193 .child(Label::new("Focus Sidebar"))
4194 .child(KeyBinding::for_action(&FocusWorkspaceSidebar, cx)),
4195 )
4196 .into_any_element()
4197 }))
4198 .on_click(|_, window, cx| {
4199 if let Some(multi_workspace) = window.root::<MultiWorkspace>().flatten() {
4200 multi_workspace.update(cx, |multi_workspace, cx| {
4201 multi_workspace.close_sidebar(window, cx);
4202 });
4203 }
4204 })
4205 })
4206 }
4207
4208 fn render_sidebar_bottom_bar(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
4209 let is_archive = matches!(self.view, SidebarView::Archive(..));
4210 let show_import_button = is_archive && !self.should_render_acp_import_onboarding(cx);
4211 let on_right = self.side(cx) == SidebarSide::Right;
4212
4213 let action_buttons = h_flex()
4214 .gap_1()
4215 .when(on_right, |this| this.flex_row_reverse())
4216 .when(show_import_button, |this| {
4217 this.child(
4218 IconButton::new("thread-import", IconName::ThreadImport)
4219 .icon_size(IconSize::Small)
4220 .tooltip(Tooltip::text("Import ACP Threads"))
4221 .on_click(cx.listener(|this, _, window, cx| {
4222 this.show_archive(window, cx);
4223 this.show_thread_import_modal(window, cx);
4224 })),
4225 )
4226 })
4227 .child(
4228 IconButton::new("archive", IconName::Archive)
4229 .icon_size(IconSize::Small)
4230 .toggle_state(is_archive)
4231 .tooltip(move |_, cx| {
4232 Tooltip::for_action("Toggle Archived Threads", &ToggleArchive, cx)
4233 })
4234 .on_click(cx.listener(|this, _, window, cx| {
4235 this.toggle_archive(&ToggleArchive, window, cx);
4236 })),
4237 )
4238 .child(self.render_recent_projects_button(cx));
4239
4240 h_flex()
4241 .p_1()
4242 .gap_1()
4243 .when(on_right, |this| this.flex_row_reverse())
4244 .justify_between()
4245 .border_t_1()
4246 .border_color(cx.theme().colors().border)
4247 .child(self.render_sidebar_toggle_button(cx))
4248 .child(action_buttons)
4249 }
4250
4251 fn active_workspace(&self, cx: &App) -> Option<Entity<Workspace>> {
4252 self.multi_workspace
4253 .upgrade()
4254 .map(|w| w.read(cx).workspace().clone())
4255 }
4256
4257 fn show_thread_import_modal(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4258 let Some(active_workspace) = self.active_workspace(cx) else {
4259 return;
4260 };
4261
4262 let Some(agent_registry_store) = AgentRegistryStore::try_global(cx) else {
4263 return;
4264 };
4265
4266 let agent_server_store = active_workspace
4267 .read(cx)
4268 .project()
4269 .read(cx)
4270 .agent_server_store()
4271 .clone();
4272
4273 let workspace_handle = active_workspace.downgrade();
4274 let multi_workspace = self.multi_workspace.clone();
4275
4276 active_workspace.update(cx, |workspace, cx| {
4277 workspace.toggle_modal(window, cx, |window, cx| {
4278 ThreadImportModal::new(
4279 agent_server_store,
4280 agent_registry_store,
4281 workspace_handle.clone(),
4282 multi_workspace.clone(),
4283 window,
4284 cx,
4285 )
4286 });
4287 });
4288 }
4289
4290 fn should_render_acp_import_onboarding(&self, cx: &App) -> bool {
4291 let has_external_agents = self
4292 .active_workspace(cx)
4293 .map(|ws| {
4294 ws.read(cx)
4295 .project()
4296 .read(cx)
4297 .agent_server_store()
4298 .read(cx)
4299 .has_external_agents()
4300 })
4301 .unwrap_or(false);
4302
4303 has_external_agents && !AcpThreadImportOnboarding::dismissed(cx)
4304 }
4305
4306 fn render_acp_import_onboarding(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
4307 let description =
4308 "Import threads from your ACP agents — whether started in Zed or another client.";
4309
4310 let bg = cx.theme().colors().text_accent;
4311
4312 v_flex()
4313 .min_w_0()
4314 .w_full()
4315 .p_2()
4316 .border_t_1()
4317 .border_color(cx.theme().colors().border)
4318 .bg(linear_gradient(
4319 360.,
4320 linear_color_stop(bg.opacity(0.06), 1.),
4321 linear_color_stop(bg.opacity(0.), 0.),
4322 ))
4323 .child(
4324 h_flex()
4325 .min_w_0()
4326 .w_full()
4327 .gap_1()
4328 .justify_between()
4329 .child(Label::new("Looking for ACP threads?"))
4330 .child(
4331 IconButton::new("close-onboarding", IconName::Close)
4332 .icon_size(IconSize::Small)
4333 .on_click(|_, _window, cx| AcpThreadImportOnboarding::dismiss(cx)),
4334 ),
4335 )
4336 .child(Label::new(description).color(Color::Muted).mb_2())
4337 .child(
4338 Button::new("import-acp", "Import ACP Threads")
4339 .full_width()
4340 .style(ButtonStyle::OutlinedCustom(cx.theme().colors().border))
4341 .label_size(LabelSize::Small)
4342 .start_icon(
4343 Icon::new(IconName::ThreadImport)
4344 .size(IconSize::Small)
4345 .color(Color::Muted),
4346 )
4347 .on_click(cx.listener(|this, _, window, cx| {
4348 this.show_archive(window, cx);
4349 this.show_thread_import_modal(window, cx);
4350 })),
4351 )
4352 }
4353
4354 fn toggle_archive(&mut self, _: &ToggleArchive, window: &mut Window, cx: &mut Context<Self>) {
4355 match &self.view {
4356 SidebarView::ThreadList => self.show_archive(window, cx),
4357 SidebarView::Archive(_) => self.show_thread_list(window, cx),
4358 }
4359 }
4360
4361 fn show_archive(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4362 let Some(active_workspace) = self
4363 .multi_workspace
4364 .upgrade()
4365 .map(|w| w.read(cx).workspace().clone())
4366 else {
4367 return;
4368 };
4369 let Some(agent_panel) = active_workspace.read(cx).panel::<AgentPanel>(cx) else {
4370 return;
4371 };
4372
4373 let agent_server_store = active_workspace
4374 .read(cx)
4375 .project()
4376 .read(cx)
4377 .agent_server_store()
4378 .downgrade();
4379
4380 let agent_connection_store = agent_panel.read(cx).connection_store().downgrade();
4381
4382 let archive_view = cx.new(|cx| {
4383 ThreadsArchiveView::new(
4384 active_workspace.downgrade(),
4385 agent_connection_store.clone(),
4386 agent_server_store.clone(),
4387 window,
4388 cx,
4389 )
4390 });
4391
4392 let subscription = cx.subscribe_in(
4393 &archive_view,
4394 window,
4395 |this, _, event: &ThreadsArchiveViewEvent, window, cx| match event {
4396 ThreadsArchiveViewEvent::Close => {
4397 this.show_thread_list(window, cx);
4398 }
4399 ThreadsArchiveViewEvent::Unarchive { thread } => {
4400 this.show_thread_list(window, cx);
4401 this.activate_archived_thread(thread.clone(), window, cx);
4402 }
4403 },
4404 );
4405
4406 self._subscriptions.push(subscription);
4407 self.view = SidebarView::Archive(archive_view.clone());
4408 archive_view.update(cx, |view, cx| view.focus_filter_editor(window, cx));
4409 self.serialize(cx);
4410 cx.notify();
4411 }
4412
4413 fn show_thread_list(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4414 self.view = SidebarView::ThreadList;
4415 self._subscriptions.clear();
4416 let handle = self.filter_editor.read(cx).focus_handle(cx);
4417 handle.focus(window, cx);
4418 self.serialize(cx);
4419 cx.notify();
4420 }
4421}
4422
4423impl WorkspaceSidebar for Sidebar {
4424 fn width(&self, _cx: &App) -> Pixels {
4425 self.width
4426 }
4427
4428 fn set_width(&mut self, width: Option<Pixels>, cx: &mut Context<Self>) {
4429 self.width = width.unwrap_or(DEFAULT_WIDTH).clamp(MIN_WIDTH, MAX_WIDTH);
4430 cx.notify();
4431 }
4432
4433 fn has_notifications(&self, _cx: &App) -> bool {
4434 !self.contents.notified_threads.is_empty()
4435 }
4436
4437 fn is_threads_list_view_active(&self) -> bool {
4438 matches!(self.view, SidebarView::ThreadList)
4439 }
4440
4441 fn side(&self, cx: &App) -> SidebarSide {
4442 AgentSettings::get_global(cx).sidebar_side()
4443 }
4444
4445 fn prepare_for_focus(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
4446 self.selection = None;
4447 cx.notify();
4448 }
4449
4450 fn toggle_thread_switcher(
4451 &mut self,
4452 select_last: bool,
4453 window: &mut Window,
4454 cx: &mut Context<Self>,
4455 ) {
4456 self.toggle_thread_switcher_impl(select_last, window, cx);
4457 }
4458
4459 fn cycle_project(&mut self, forward: bool, window: &mut Window, cx: &mut Context<Self>) {
4460 self.cycle_project_impl(forward, window, cx);
4461 }
4462
4463 fn cycle_thread(&mut self, forward: bool, window: &mut Window, cx: &mut Context<Self>) {
4464 self.cycle_thread_impl(forward, window, cx);
4465 }
4466
4467 fn serialized_state(&self, _cx: &App) -> Option<String> {
4468 let serialized = SerializedSidebar {
4469 width: Some(f32::from(self.width)),
4470 collapsed_groups: self
4471 .collapsed_groups
4472 .iter()
4473 .cloned()
4474 .map(SerializedProjectGroupKey::from)
4475 .collect(),
4476 expanded_groups: self
4477 .expanded_groups
4478 .iter()
4479 .map(|(key, count)| (SerializedProjectGroupKey::from(key.clone()), *count))
4480 .collect(),
4481 active_view: match self.view {
4482 SidebarView::ThreadList => SerializedSidebarView::ThreadList,
4483 SidebarView::Archive(_) => SerializedSidebarView::Archive,
4484 },
4485 };
4486 serde_json::to_string(&serialized).ok()
4487 }
4488
4489 fn restore_serialized_state(
4490 &mut self,
4491 state: &str,
4492 window: &mut Window,
4493 cx: &mut Context<Self>,
4494 ) {
4495 if let Some(serialized) = serde_json::from_str::<SerializedSidebar>(state).log_err() {
4496 if let Some(width) = serialized.width {
4497 self.width = px(width).clamp(MIN_WIDTH, MAX_WIDTH);
4498 }
4499 self.collapsed_groups = serialized
4500 .collapsed_groups
4501 .into_iter()
4502 .map(ProjectGroupKey::from)
4503 .collect();
4504 self.expanded_groups = serialized
4505 .expanded_groups
4506 .into_iter()
4507 .map(|(s, count)| (ProjectGroupKey::from(s), count))
4508 .collect();
4509 if serialized.active_view == SerializedSidebarView::Archive {
4510 cx.defer_in(window, |this, window, cx| {
4511 this.show_archive(window, cx);
4512 });
4513 }
4514 }
4515 cx.notify();
4516 }
4517}
4518
4519impl gpui::EventEmitter<workspace::SidebarEvent> for Sidebar {}
4520
4521impl Focusable for Sidebar {
4522 fn focus_handle(&self, _cx: &App) -> FocusHandle {
4523 self.focus_handle.clone()
4524 }
4525}
4526
4527impl Render for Sidebar {
4528 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4529 let _titlebar_height = ui::utils::platform_title_bar_height(window);
4530 let ui_font = theme_settings::setup_ui_font(window, cx);
4531 let sticky_header = self.render_sticky_header(window, cx);
4532
4533 let color = cx.theme().colors();
4534 let bg = color
4535 .title_bar_background
4536 .blend(color.panel_background.opacity(0.25));
4537
4538 let no_open_projects = !self.contents.has_open_projects;
4539 let no_search_results = self.contents.entries.is_empty();
4540
4541 v_flex()
4542 .id("workspace-sidebar")
4543 .key_context(self.dispatch_context(window, cx))
4544 .track_focus(&self.focus_handle)
4545 .on_action(cx.listener(Self::select_next))
4546 .on_action(cx.listener(Self::select_previous))
4547 .on_action(cx.listener(Self::editor_move_down))
4548 .on_action(cx.listener(Self::editor_move_up))
4549 .on_action(cx.listener(Self::select_first))
4550 .on_action(cx.listener(Self::select_last))
4551 .on_action(cx.listener(Self::confirm))
4552 .on_action(cx.listener(Self::expand_selected_entry))
4553 .on_action(cx.listener(Self::collapse_selected_entry))
4554 .on_action(cx.listener(Self::toggle_selected_fold))
4555 .on_action(cx.listener(Self::fold_all))
4556 .on_action(cx.listener(Self::unfold_all))
4557 .on_action(cx.listener(Self::cancel))
4558 .on_action(cx.listener(Self::remove_selected_thread))
4559 .on_action(cx.listener(Self::new_thread_in_group))
4560 .on_action(cx.listener(Self::toggle_archive))
4561 .on_action(cx.listener(Self::focus_sidebar_filter))
4562 .on_action(cx.listener(Self::on_toggle_thread_switcher))
4563 .on_action(cx.listener(Self::on_next_project))
4564 .on_action(cx.listener(Self::on_previous_project))
4565 .on_action(cx.listener(Self::on_next_thread))
4566 .on_action(cx.listener(Self::on_previous_thread))
4567 .on_action(cx.listener(Self::on_show_more_threads))
4568 .on_action(cx.listener(Self::on_show_fewer_threads))
4569 .on_action(cx.listener(Self::on_new_thread))
4570 .on_action(cx.listener(|this, _: &OpenRecent, window, cx| {
4571 this.recent_projects_popover_handle.toggle(window, cx);
4572 }))
4573 .font(ui_font)
4574 .h_full()
4575 .w(self.width)
4576 .bg(bg)
4577 .when(self.side(cx) == SidebarSide::Left, |el| el.border_r_1())
4578 .when(self.side(cx) == SidebarSide::Right, |el| el.border_l_1())
4579 .border_color(color.border)
4580 .map(|this| match &self.view {
4581 SidebarView::ThreadList => this
4582 .child(self.render_sidebar_header(no_open_projects, window, cx))
4583 .map(|this| {
4584 if no_open_projects {
4585 this.child(self.render_empty_state(cx))
4586 } else {
4587 this.child(
4588 v_flex()
4589 .relative()
4590 .flex_1()
4591 .overflow_hidden()
4592 .child(
4593 list(
4594 self.list_state.clone(),
4595 cx.processor(Self::render_list_entry),
4596 )
4597 .flex_1()
4598 .size_full(),
4599 )
4600 .when(no_search_results, |this| {
4601 this.child(self.render_no_results(cx))
4602 })
4603 .when_some(sticky_header, |this, header| this.child(header))
4604 .vertical_scrollbar_for(&self.list_state, window, cx),
4605 )
4606 }
4607 }),
4608 SidebarView::Archive(archive_view) => this.child(archive_view.clone()),
4609 })
4610 .when(self.should_render_acp_import_onboarding(cx), |this| {
4611 this.child(self.render_acp_import_onboarding(cx))
4612 })
4613 .child(self.render_sidebar_bottom_bar(cx))
4614 }
4615}
4616
4617fn all_thread_infos_for_workspace(
4618 workspace: &Entity<Workspace>,
4619 cx: &App,
4620) -> impl Iterator<Item = ActiveThreadInfo> {
4621 let Some(agent_panel) = workspace.read(cx).panel::<AgentPanel>(cx) else {
4622 return None.into_iter().flatten();
4623 };
4624 let agent_panel = agent_panel.read(cx);
4625 let threads = agent_panel
4626 .conversation_views()
4627 .into_iter()
4628 .filter_map(|conversation_view| {
4629 let has_pending_tool_call = conversation_view
4630 .read(cx)
4631 .root_thread_has_pending_tool_call(cx);
4632 let thread_view = conversation_view.read(cx).root_thread(cx)?;
4633 let thread_view_ref = thread_view.read(cx);
4634 let thread = thread_view_ref.thread.read(cx);
4635
4636 let icon = thread_view_ref.agent_icon;
4637 let icon_from_external_svg = thread_view_ref.agent_icon_from_external_svg.clone();
4638 let title = thread
4639 .title()
4640 .unwrap_or_else(|| DEFAULT_THREAD_TITLE.into());
4641 let is_native = thread_view_ref.as_native_thread(cx).is_some();
4642 let is_title_generating = is_native && thread.has_provisional_title();
4643 let session_id = thread.session_id().clone();
4644 let is_background = agent_panel.is_background_thread(&session_id);
4645
4646 let status = if has_pending_tool_call {
4647 AgentThreadStatus::WaitingForConfirmation
4648 } else if thread.had_error() {
4649 AgentThreadStatus::Error
4650 } else {
4651 match thread.status() {
4652 ThreadStatus::Generating => AgentThreadStatus::Running,
4653 ThreadStatus::Idle => AgentThreadStatus::Completed,
4654 }
4655 };
4656
4657 let diff_stats = thread.action_log().read(cx).diff_stats(cx);
4658
4659 Some(ActiveThreadInfo {
4660 session_id,
4661 title,
4662 status,
4663 icon,
4664 icon_from_external_svg,
4665 is_background,
4666 is_title_generating,
4667 diff_stats,
4668 })
4669 });
4670
4671 Some(threads).into_iter().flatten()
4672}
4673
4674pub fn dump_workspace_info(
4675 workspace: &mut Workspace,
4676 _: &DumpWorkspaceInfo,
4677 window: &mut gpui::Window,
4678 cx: &mut gpui::Context<Workspace>,
4679) {
4680 use std::fmt::Write;
4681
4682 let mut output = String::new();
4683 let this_entity = cx.entity();
4684
4685 let multi_workspace = workspace.multi_workspace().and_then(|weak| weak.upgrade());
4686 let workspaces: Vec<gpui::Entity<Workspace>> = match &multi_workspace {
4687 Some(mw) => mw.read(cx).workspaces().cloned().collect(),
4688 None => vec![this_entity.clone()],
4689 };
4690 let active_workspace = multi_workspace
4691 .as_ref()
4692 .map(|mw| mw.read(cx).workspace().clone());
4693
4694 writeln!(output, "MultiWorkspace: {} workspace(s)", workspaces.len()).ok();
4695
4696 if let Some(mw) = &multi_workspace {
4697 let keys: Vec<_> = mw.read(cx).project_group_keys().cloned().collect();
4698 writeln!(output, "Project group keys ({}):", keys.len()).ok();
4699 for key in keys {
4700 writeln!(output, " - {key:?}").ok();
4701 }
4702 }
4703
4704 writeln!(output).ok();
4705
4706 for (index, ws) in workspaces.iter().enumerate() {
4707 let is_active = active_workspace.as_ref() == Some(ws);
4708 writeln!(
4709 output,
4710 "--- Workspace {index}{} ---",
4711 if is_active { " (active)" } else { "" }
4712 )
4713 .ok();
4714
4715 // The action handler is already inside an update on `this_entity`,
4716 // so we must avoid a nested read/update on that same entity.
4717 if *ws == this_entity {
4718 dump_single_workspace(workspace, &mut output, cx);
4719 } else {
4720 ws.read_with(cx, |ws, cx| {
4721 dump_single_workspace(ws, &mut output, cx);
4722 });
4723 }
4724 }
4725
4726 let project = workspace.project().clone();
4727 cx.spawn_in(window, async move |_this, cx| {
4728 let buffer = project
4729 .update(cx, |project, cx| project.create_buffer(None, false, cx))
4730 .await?;
4731
4732 buffer.update(cx, |buffer, cx| {
4733 buffer.set_text(output, cx);
4734 });
4735
4736 let buffer = cx.new(|cx| {
4737 editor::MultiBuffer::singleton(buffer, cx).with_title("Workspace Info".into())
4738 });
4739
4740 _this.update_in(cx, |workspace, window, cx| {
4741 workspace.add_item_to_active_pane(
4742 Box::new(cx.new(|cx| {
4743 let mut editor =
4744 editor::Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
4745 editor.set_read_only(true);
4746 editor.set_should_serialize(false, cx);
4747 editor.set_breadcrumb_header("Workspace Info".into());
4748 editor
4749 })),
4750 None,
4751 true,
4752 window,
4753 cx,
4754 );
4755 })
4756 })
4757 .detach_and_log_err(cx);
4758}
4759
4760fn dump_single_workspace(workspace: &Workspace, output: &mut String, cx: &gpui::App) {
4761 use std::fmt::Write;
4762
4763 let workspace_db_id = workspace.database_id();
4764 match workspace_db_id {
4765 Some(id) => writeln!(output, "Workspace DB ID: {id:?}").ok(),
4766 None => writeln!(output, "Workspace DB ID: (none)").ok(),
4767 };
4768
4769 let project = workspace.project().read(cx);
4770
4771 let repos: Vec<_> = project
4772 .repositories(cx)
4773 .values()
4774 .map(|repo| repo.read(cx).snapshot())
4775 .collect();
4776
4777 writeln!(output, "Worktrees:").ok();
4778 for worktree in project.worktrees(cx) {
4779 let worktree = worktree.read(cx);
4780 let abs_path = worktree.abs_path();
4781 let visible = worktree.is_visible();
4782
4783 let repo_info = repos
4784 .iter()
4785 .find(|snapshot| abs_path.starts_with(&*snapshot.work_directory_abs_path));
4786
4787 let is_linked = repo_info.map(|s| s.is_linked_worktree()).unwrap_or(false);
4788 let original_repo_path = repo_info.map(|s| &s.original_repo_abs_path);
4789 let branch = repo_info.and_then(|s| s.branch.as_ref().map(|b| b.ref_name.clone()));
4790
4791 write!(output, " - {}", abs_path.display()).ok();
4792 if !visible {
4793 write!(output, " (hidden)").ok();
4794 }
4795 if let Some(branch) = &branch {
4796 write!(output, " [branch: {branch}]").ok();
4797 }
4798 if is_linked {
4799 if let Some(original) = original_repo_path {
4800 write!(output, " [linked worktree -> {}]", original.display()).ok();
4801 } else {
4802 write!(output, " [linked worktree]").ok();
4803 }
4804 }
4805 writeln!(output).ok();
4806 }
4807
4808 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
4809 let panel = panel.read(cx);
4810
4811 let panel_workspace_id = panel.workspace_id();
4812 if panel_workspace_id != workspace_db_id {
4813 writeln!(
4814 output,
4815 " \u{26a0} workspace ID mismatch! panel has {panel_workspace_id:?}, workspace has {workspace_db_id:?}"
4816 )
4817 .ok();
4818 }
4819
4820 if let Some(thread) = panel.active_agent_thread(cx) {
4821 let thread = thread.read(cx);
4822 let title = thread.title().unwrap_or_else(|| "(untitled)".into());
4823 let session_id = thread.session_id();
4824 let status = match thread.status() {
4825 ThreadStatus::Idle => "idle",
4826 ThreadStatus::Generating => "generating",
4827 };
4828 let entry_count = thread.entries().len();
4829 write!(output, "Active thread: {title} (session: {session_id})").ok();
4830 write!(output, " [{status}, {entry_count} entries").ok();
4831 if panel
4832 .active_conversation_view()
4833 .is_some_and(|conversation_view| {
4834 conversation_view
4835 .read(cx)
4836 .root_thread_has_pending_tool_call(cx)
4837 })
4838 {
4839 write!(output, ", awaiting confirmation").ok();
4840 }
4841 writeln!(output, "]").ok();
4842 } else {
4843 writeln!(output, "Active thread: (none)").ok();
4844 }
4845
4846 let background_threads = panel.background_threads();
4847 if !background_threads.is_empty() {
4848 writeln!(
4849 output,
4850 "Background threads ({}): ",
4851 background_threads.len()
4852 )
4853 .ok();
4854 for (session_id, conversation_view) in background_threads {
4855 if let Some(thread_view) = conversation_view.read(cx).root_thread(cx) {
4856 let thread = thread_view.read(cx).thread.read(cx);
4857 let title = thread.title().unwrap_or_else(|| "(untitled)".into());
4858 let status = match thread.status() {
4859 ThreadStatus::Idle => "idle",
4860 ThreadStatus::Generating => "generating",
4861 };
4862 let entry_count = thread.entries().len();
4863 write!(output, " - {title} (session: {session_id})").ok();
4864 write!(output, " [{status}, {entry_count} entries").ok();
4865 if conversation_view
4866 .read(cx)
4867 .root_thread_has_pending_tool_call(cx)
4868 {
4869 write!(output, ", awaiting confirmation").ok();
4870 }
4871 writeln!(output, "]").ok();
4872 } else {
4873 writeln!(output, " - (not connected) (session: {session_id})").ok();
4874 }
4875 }
4876 }
4877 } else {
4878 writeln!(output, "Agent panel: not loaded").ok();
4879 }
4880
4881 writeln!(output).ok();
4882}