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