1use std::collections::HashSet;
2use std::sync::Arc;
3
4use crate::agent_connection_store::AgentConnectionStore;
5
6use crate::thread_metadata_store::{ThreadMetadata, ThreadMetadataStore};
7use crate::{Agent, RemoveSelectedThread};
8
9use agent::ThreadStore;
10use agent_client_protocol as acp;
11use agent_settings::AgentSettings;
12use chrono::{DateTime, Datelike as _, Local, NaiveDate, TimeDelta, Utc};
13use editor::Editor;
14use fs::Fs;
15use fuzzy::{StringMatch, StringMatchCandidate};
16use gpui::{
17 AnyElement, App, Context, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable,
18 ListState, Render, SharedString, Subscription, Task, WeakEntity, Window, list, prelude::*, px,
19};
20use itertools::Itertools as _;
21use menu::{Confirm, SelectFirst, SelectLast, SelectNext, SelectPrevious};
22use picker::{
23 Picker, PickerDelegate,
24 highlighted_match_with_paths::{HighlightedMatch, HighlightedMatchWithPaths},
25};
26use project::{AgentId, AgentServerStore};
27use settings::Settings as _;
28use theme::ActiveTheme;
29use ui::ThreadItem;
30use ui::{
31 Divider, KeyBinding, ListItem, ListItemSpacing, ListSubHeader, Tooltip, WithScrollbar,
32 prelude::*, utils::platform_title_bar_height,
33};
34use ui_input::ErasedEditor;
35use util::ResultExt;
36use util::paths::PathExt;
37use workspace::{
38 ModalView, PathList, SerializedWorkspaceLocation, Workspace, WorkspaceDb, WorkspaceId,
39 resolve_worktree_workspaces,
40};
41
42use zed_actions::agents_sidebar::FocusSidebarFilter;
43use zed_actions::editor::{MoveDown, MoveUp};
44
45#[derive(Clone)]
46enum ArchiveListItem {
47 BucketSeparator(TimeBucket),
48 Entry {
49 thread: ThreadMetadata,
50 highlight_positions: Vec<usize>,
51 },
52}
53
54#[derive(Clone, Copy, Debug, PartialEq, Eq)]
55enum TimeBucket {
56 Today,
57 Yesterday,
58 ThisWeek,
59 PastWeek,
60 Older,
61}
62
63impl TimeBucket {
64 fn from_dates(reference: NaiveDate, date: NaiveDate) -> Self {
65 if date == reference {
66 return TimeBucket::Today;
67 }
68 if date == reference - TimeDelta::days(1) {
69 return TimeBucket::Yesterday;
70 }
71 let week = date.iso_week();
72 if reference.iso_week() == week {
73 return TimeBucket::ThisWeek;
74 }
75 let last_week = (reference - TimeDelta::days(7)).iso_week();
76 if week == last_week {
77 return TimeBucket::PastWeek;
78 }
79 TimeBucket::Older
80 }
81
82 fn label(&self) -> &'static str {
83 match self {
84 TimeBucket::Today => "Today",
85 TimeBucket::Yesterday => "Yesterday",
86 TimeBucket::ThisWeek => "This Week",
87 TimeBucket::PastWeek => "Past Week",
88 TimeBucket::Older => "Older",
89 }
90 }
91}
92
93fn fuzzy_match_positions(query: &str, text: &str) -> Option<Vec<usize>> {
94 let mut positions = Vec::new();
95 let mut query_chars = query.chars().peekable();
96 for (byte_idx, candidate_char) in text.char_indices() {
97 if let Some(&query_char) = query_chars.peek() {
98 if candidate_char.eq_ignore_ascii_case(&query_char) {
99 positions.push(byte_idx);
100 query_chars.next();
101 }
102 } else {
103 break;
104 }
105 }
106 if query_chars.peek().is_none() {
107 Some(positions)
108 } else {
109 None
110 }
111}
112
113pub enum ThreadsArchiveViewEvent {
114 Close,
115 Unarchive { thread: ThreadMetadata },
116}
117
118impl EventEmitter<ThreadsArchiveViewEvent> for ThreadsArchiveView {}
119
120pub struct ThreadsArchiveView {
121 _history_subscription: Subscription,
122 focus_handle: FocusHandle,
123 list_state: ListState,
124 items: Vec<ArchiveListItem>,
125 selection: Option<usize>,
126 hovered_index: Option<usize>,
127 preserve_selection_on_next_update: bool,
128 filter_editor: Entity<Editor>,
129 _subscriptions: Vec<gpui::Subscription>,
130 _refresh_history_task: Task<()>,
131 workspace: WeakEntity<Workspace>,
132 agent_connection_store: WeakEntity<AgentConnectionStore>,
133 agent_server_store: WeakEntity<AgentServerStore>,
134}
135
136impl ThreadsArchiveView {
137 pub fn new(
138 workspace: WeakEntity<Workspace>,
139 agent_connection_store: WeakEntity<AgentConnectionStore>,
140 agent_server_store: WeakEntity<AgentServerStore>,
141 window: &mut Window,
142 cx: &mut Context<Self>,
143 ) -> Self {
144 let focus_handle = cx.focus_handle();
145
146 let filter_editor = cx.new(|cx| {
147 let mut editor = Editor::single_line(window, cx);
148 editor.set_placeholder_text("Search archive…", window, cx);
149 editor
150 });
151
152 let filter_editor_subscription =
153 cx.subscribe(&filter_editor, |this: &mut Self, _, event, cx| {
154 if let editor::EditorEvent::BufferEdited = event {
155 this.update_items(cx);
156 }
157 });
158
159 let filter_focus_handle = filter_editor.read(cx).focus_handle(cx);
160 cx.on_focus_in(
161 &filter_focus_handle,
162 window,
163 |this: &mut Self, _window, cx| {
164 if this.selection.is_some() {
165 this.selection = None;
166 cx.notify();
167 }
168 },
169 )
170 .detach();
171
172 let thread_metadata_store_subscription = cx.observe(
173 &ThreadMetadataStore::global(cx),
174 |this: &mut Self, _, cx| {
175 this.update_items(cx);
176 },
177 );
178
179 cx.on_focus_out(&focus_handle, window, |this: &mut Self, _, _window, cx| {
180 this.selection = None;
181 cx.notify();
182 })
183 .detach();
184
185 let mut this = Self {
186 _history_subscription: Subscription::new(|| {}),
187 focus_handle,
188 list_state: ListState::new(0, gpui::ListAlignment::Top, px(1000.)),
189 items: Vec::new(),
190 selection: None,
191 hovered_index: None,
192 preserve_selection_on_next_update: false,
193 filter_editor,
194 _subscriptions: vec![
195 filter_editor_subscription,
196 thread_metadata_store_subscription,
197 ],
198 _refresh_history_task: Task::ready(()),
199 workspace,
200 agent_connection_store,
201 agent_server_store,
202 };
203
204 this.update_items(cx);
205 this
206 }
207
208 pub fn has_selection(&self) -> bool {
209 self.selection.is_some()
210 }
211
212 pub fn clear_selection(&mut self) {
213 self.selection = None;
214 }
215
216 pub fn focus_filter_editor(&self, window: &mut Window, cx: &mut App) {
217 let handle = self.filter_editor.read(cx).focus_handle(cx);
218 handle.focus(window, cx);
219 }
220
221 pub fn is_filter_editor_focused(&self, window: &Window, cx: &App) -> bool {
222 self.filter_editor
223 .read(cx)
224 .focus_handle(cx)
225 .is_focused(window)
226 }
227
228 fn update_items(&mut self, cx: &mut Context<Self>) {
229 let sessions = ThreadMetadataStore::global(cx)
230 .read(cx)
231 .archived_entries()
232 .sorted_by_cached_key(|t| t.created_at.unwrap_or(t.updated_at))
233 .rev()
234 .cloned()
235 .collect::<Vec<_>>();
236
237 let query = self.filter_editor.read(cx).text(cx).to_lowercase();
238 let today = Local::now().naive_local().date();
239
240 let mut items = Vec::with_capacity(sessions.len() + 5);
241 let mut current_bucket: Option<TimeBucket> = None;
242
243 for session in sessions {
244 let highlight_positions = if !query.is_empty() {
245 match fuzzy_match_positions(&query, &session.title) {
246 Some(positions) => positions,
247 None => continue,
248 }
249 } else {
250 Vec::new()
251 };
252
253 let entry_bucket = {
254 let entry_date = session
255 .created_at
256 .unwrap_or(session.updated_at)
257 .with_timezone(&Local)
258 .naive_local()
259 .date();
260 TimeBucket::from_dates(today, entry_date)
261 };
262
263 if Some(entry_bucket) != current_bucket {
264 current_bucket = Some(entry_bucket);
265 items.push(ArchiveListItem::BucketSeparator(entry_bucket));
266 }
267
268 items.push(ArchiveListItem::Entry {
269 thread: session,
270 highlight_positions,
271 });
272 }
273
274 let preserve = self.preserve_selection_on_next_update;
275 self.preserve_selection_on_next_update = false;
276
277 let saved_scroll = if preserve {
278 Some(self.list_state.logical_scroll_top())
279 } else {
280 None
281 };
282
283 self.list_state.reset(items.len());
284 self.items = items;
285
286 if !preserve {
287 self.hovered_index = None;
288 } else if let Some(ix) = self.hovered_index {
289 if ix >= self.items.len() || !self.is_selectable_item(ix) {
290 self.hovered_index = None;
291 }
292 }
293
294 if let Some(scroll_top) = saved_scroll {
295 self.list_state.scroll_to(scroll_top);
296
297 if let Some(ix) = self.selection {
298 let next = self.find_next_selectable(ix).or_else(|| {
299 ix.checked_sub(1)
300 .and_then(|i| self.find_previous_selectable(i))
301 });
302 self.selection = next;
303 if let Some(next) = next {
304 self.list_state.scroll_to_reveal_item(next);
305 }
306 }
307 } else {
308 self.selection = None;
309 }
310
311 cx.notify();
312 }
313
314 fn reset_filter_editor_text(&mut self, window: &mut Window, cx: &mut Context<Self>) {
315 self.filter_editor.update(cx, |editor, cx| {
316 editor.set_text("", window, cx);
317 });
318 }
319
320 fn unarchive_thread(
321 &mut self,
322 thread: ThreadMetadata,
323 window: &mut Window,
324 cx: &mut Context<Self>,
325 ) {
326 if thread.folder_paths.is_empty() {
327 self.show_project_picker_for_thread(thread, window, cx);
328 return;
329 }
330
331 self.selection = None;
332 self.reset_filter_editor_text(window, cx);
333 cx.emit(ThreadsArchiveViewEvent::Unarchive { thread });
334 }
335
336 fn show_project_picker_for_thread(
337 &mut self,
338 thread: ThreadMetadata,
339 window: &mut Window,
340 cx: &mut Context<Self>,
341 ) {
342 let Some(workspace) = self.workspace.upgrade() else {
343 return;
344 };
345
346 let archive_view = cx.weak_entity();
347 let fs = workspace.read(cx).app_state().fs.clone();
348 let current_workspace_id = workspace.read(cx).database_id();
349 let sibling_workspace_ids: HashSet<WorkspaceId> = workspace
350 .read(cx)
351 .multi_workspace()
352 .and_then(|mw| mw.upgrade())
353 .map(|mw| {
354 mw.read(cx)
355 .workspaces()
356 .filter_map(|ws| ws.read(cx).database_id())
357 .collect()
358 })
359 .unwrap_or_default();
360
361 workspace.update(cx, |workspace, cx| {
362 workspace.toggle_modal(window, cx, |window, cx| {
363 ProjectPickerModal::new(
364 thread,
365 fs,
366 archive_view,
367 current_workspace_id,
368 sibling_workspace_ids,
369 window,
370 cx,
371 )
372 });
373 });
374 }
375
376 fn is_selectable_item(&self, ix: usize) -> bool {
377 matches!(self.items.get(ix), Some(ArchiveListItem::Entry { .. }))
378 }
379
380 fn find_next_selectable(&self, start: usize) -> Option<usize> {
381 (start..self.items.len()).find(|&i| self.is_selectable_item(i))
382 }
383
384 fn find_previous_selectable(&self, start: usize) -> Option<usize> {
385 (0..=start).rev().find(|&i| self.is_selectable_item(i))
386 }
387
388 fn editor_move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
389 self.select_next(&SelectNext, window, cx);
390 if self.selection.is_some() {
391 self.focus_handle.focus(window, cx);
392 }
393 }
394
395 fn editor_move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
396 self.select_previous(&SelectPrevious, window, cx);
397 if self.selection.is_some() {
398 self.focus_handle.focus(window, cx);
399 }
400 }
401
402 fn select_next(&mut self, _: &SelectNext, _window: &mut Window, cx: &mut Context<Self>) {
403 let next = match self.selection {
404 Some(ix) => self.find_next_selectable(ix + 1),
405 None => self.find_next_selectable(0),
406 };
407 if let Some(next) = next {
408 self.selection = Some(next);
409 self.list_state.scroll_to_reveal_item(next);
410 cx.notify();
411 }
412 }
413
414 fn select_previous(&mut self, _: &SelectPrevious, window: &mut Window, cx: &mut Context<Self>) {
415 match self.selection {
416 Some(ix) => {
417 if let Some(prev) = (ix > 0)
418 .then(|| self.find_previous_selectable(ix - 1))
419 .flatten()
420 {
421 self.selection = Some(prev);
422 self.list_state.scroll_to_reveal_item(prev);
423 } else {
424 self.selection = None;
425 self.focus_filter_editor(window, cx);
426 }
427 cx.notify();
428 }
429 None => {
430 let last = self.items.len().saturating_sub(1);
431 if let Some(prev) = self.find_previous_selectable(last) {
432 self.selection = Some(prev);
433 self.list_state.scroll_to_reveal_item(prev);
434 cx.notify();
435 }
436 }
437 }
438 }
439
440 fn select_first(&mut self, _: &SelectFirst, _window: &mut Window, cx: &mut Context<Self>) {
441 if let Some(first) = self.find_next_selectable(0) {
442 self.selection = Some(first);
443 self.list_state.scroll_to_reveal_item(first);
444 cx.notify();
445 }
446 }
447
448 fn select_last(&mut self, _: &SelectLast, _window: &mut Window, cx: &mut Context<Self>) {
449 let last = self.items.len().saturating_sub(1);
450 if let Some(last) = self.find_previous_selectable(last) {
451 self.selection = Some(last);
452 self.list_state.scroll_to_reveal_item(last);
453 cx.notify();
454 }
455 }
456
457 fn confirm(&mut self, _: &Confirm, window: &mut Window, cx: &mut Context<Self>) {
458 let Some(ix) = self.selection else { return };
459 let Some(ArchiveListItem::Entry { thread, .. }) = self.items.get(ix) else {
460 return;
461 };
462
463 self.unarchive_thread(thread.clone(), window, cx);
464 }
465
466 fn render_list_entry(
467 &mut self,
468 ix: usize,
469 _window: &mut Window,
470 cx: &mut Context<Self>,
471 ) -> AnyElement {
472 let Some(item) = self.items.get(ix) else {
473 return div().into_any_element();
474 };
475
476 match item {
477 ArchiveListItem::BucketSeparator(bucket) => div()
478 .w_full()
479 .px_2p5()
480 .pt_3()
481 .pb_1()
482 .child(
483 Label::new(bucket.label())
484 .size(LabelSize::Small)
485 .color(Color::Muted),
486 )
487 .into_any_element(),
488 ArchiveListItem::Entry {
489 thread,
490 highlight_positions,
491 } => {
492 let id = SharedString::from(format!("archive-entry-{}", ix));
493
494 let is_focused = self.selection == Some(ix);
495 let is_hovered = self.hovered_index == Some(ix);
496
497 let focus_handle = self.focus_handle.clone();
498
499 let timestamp =
500 format_history_entry_timestamp(thread.created_at.unwrap_or(thread.updated_at));
501
502 let icon_from_external_svg = self
503 .agent_server_store
504 .upgrade()
505 .and_then(|store| store.read(cx).agent_icon(&thread.agent_id));
506
507 let icon = if thread.agent_id.as_ref() == agent::ZED_AGENT_ID.as_ref() {
508 IconName::ZedAgent
509 } else {
510 IconName::Sparkle
511 };
512
513 ThreadItem::new(id, thread.title.clone())
514 .icon(icon)
515 .when_some(icon_from_external_svg, |this, svg| {
516 this.custom_icon_from_external_svg(svg)
517 })
518 .timestamp(timestamp)
519 .highlight_positions(highlight_positions.clone())
520 .project_paths(thread.folder_paths.paths_owned())
521 .focused(is_focused)
522 .hovered(is_hovered)
523 .on_hover(cx.listener(move |this, is_hovered, _window, cx| {
524 if *is_hovered {
525 this.hovered_index = Some(ix);
526 } else if this.hovered_index == Some(ix) {
527 this.hovered_index = None;
528 }
529 cx.notify();
530 }))
531 .action_slot(
532 IconButton::new("delete-thread", IconName::Trash)
533 .style(ButtonStyle::Filled)
534 .icon_size(IconSize::Small)
535 .icon_color(Color::Muted)
536 .tooltip({
537 move |_window, cx| {
538 Tooltip::for_action_in(
539 "Delete Thread",
540 &RemoveSelectedThread,
541 &focus_handle,
542 cx,
543 )
544 }
545 })
546 .on_click({
547 let agent = thread.agent_id.clone();
548 let session_id = thread.session_id.clone();
549 cx.listener(move |this, _, _, cx| {
550 this.preserve_selection_on_next_update = true;
551 this.delete_thread(session_id.clone(), agent.clone(), cx);
552 cx.stop_propagation();
553 })
554 }),
555 )
556 .tooltip(move |_, cx| Tooltip::for_action("Restore Thread", &menu::Confirm, cx))
557 .on_click({
558 let thread = thread.clone();
559 cx.listener(move |this, _, window, cx| {
560 this.unarchive_thread(thread.clone(), window, cx);
561 })
562 })
563 .into_any_element()
564 }
565 }
566 }
567
568 fn remove_selected_thread(
569 &mut self,
570 _: &RemoveSelectedThread,
571 _window: &mut Window,
572 cx: &mut Context<Self>,
573 ) {
574 let Some(ix) = self.selection else { return };
575 let Some(ArchiveListItem::Entry { thread, .. }) = self.items.get(ix) else {
576 return;
577 };
578
579 self.preserve_selection_on_next_update = true;
580 self.delete_thread(thread.session_id.clone(), thread.agent_id.clone(), cx);
581 }
582
583 fn delete_thread(
584 &mut self,
585 session_id: acp::SessionId,
586 agent: AgentId,
587 cx: &mut Context<Self>,
588 ) {
589 ThreadMetadataStore::global(cx)
590 .update(cx, |store, cx| store.delete(session_id.clone(), cx));
591
592 let agent = Agent::from(agent);
593
594 let Some(agent_connection_store) = self.agent_connection_store.upgrade() else {
595 return;
596 };
597 let fs = <dyn Fs>::global(cx);
598
599 let task = agent_connection_store.update(cx, |store, cx| {
600 store
601 .request_connection(agent.clone(), agent.server(fs, ThreadStore::global(cx)), cx)
602 .read(cx)
603 .wait_for_connection()
604 });
605 cx.spawn(async move |_this, cx| {
606 let state = task.await?;
607 let task = cx.update(|cx| {
608 if let Some(list) = state.connection.session_list(cx) {
609 list.delete_session(&session_id, cx)
610 } else {
611 Task::ready(Ok(()))
612 }
613 });
614 task.await
615 })
616 .detach_and_log_err(cx);
617 }
618
619 fn render_header(&self, window: &Window, cx: &mut Context<Self>) -> impl IntoElement {
620 let has_query = !self.filter_editor.read(cx).text(cx).is_empty();
621 let sidebar_on_left = matches!(
622 AgentSettings::get_global(cx).sidebar_side(),
623 settings::SidebarSide::Left
624 );
625 let traffic_lights =
626 cfg!(target_os = "macos") && !window.is_fullscreen() && sidebar_on_left;
627 let header_height = platform_title_bar_height(window);
628 let show_focus_keybinding =
629 self.selection.is_some() && !self.filter_editor.focus_handle(cx).is_focused(window);
630
631 h_flex()
632 .h(header_height)
633 .mt_px()
634 .pb_px()
635 .map(|this| {
636 if traffic_lights {
637 this.pl(px(ui::utils::TRAFFIC_LIGHT_PADDING))
638 } else {
639 this.pl_1p5()
640 }
641 })
642 .pr_1p5()
643 .gap_1()
644 .justify_between()
645 .border_b_1()
646 .border_color(cx.theme().colors().border)
647 .when(traffic_lights, |this| {
648 this.child(Divider::vertical().color(ui::DividerColor::Border))
649 })
650 .child(
651 h_flex()
652 .ml_1()
653 .min_w_0()
654 .w_full()
655 .gap_1()
656 .child(
657 Icon::new(IconName::MagnifyingGlass)
658 .size(IconSize::Small)
659 .color(Color::Muted),
660 )
661 .child(self.filter_editor.clone()),
662 )
663 .when(show_focus_keybinding, |this| {
664 this.child(KeyBinding::for_action(&FocusSidebarFilter, cx))
665 })
666 .when(has_query, |this| {
667 this.child(
668 IconButton::new("clear-filter", IconName::Close)
669 .icon_size(IconSize::Small)
670 .tooltip(Tooltip::text("Clear Search"))
671 .on_click(cx.listener(|this, _, window, cx| {
672 this.reset_filter_editor_text(window, cx);
673 this.update_items(cx);
674 })),
675 )
676 })
677 }
678}
679
680pub fn format_history_entry_timestamp(entry_time: DateTime<Utc>) -> String {
681 let now = Utc::now();
682 let duration = now.signed_duration_since(entry_time);
683
684 let minutes = duration.num_minutes();
685 let hours = duration.num_hours();
686 let days = duration.num_days();
687 let weeks = days / 7;
688 let months = days / 30;
689
690 if minutes < 60 {
691 format!("{}m", minutes.max(1))
692 } else if hours < 24 {
693 format!("{}h", hours.max(1))
694 } else if days < 7 {
695 format!("{}d", days.max(1))
696 } else if weeks < 4 {
697 format!("{}w", weeks.max(1))
698 } else {
699 format!("{}mo", months.max(1))
700 }
701}
702
703impl Focusable for ThreadsArchiveView {
704 fn focus_handle(&self, _cx: &App) -> FocusHandle {
705 self.focus_handle.clone()
706 }
707}
708
709impl Render for ThreadsArchiveView {
710 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
711 let is_empty = self.items.is_empty();
712 let has_query = !self.filter_editor.read(cx).text(cx).is_empty();
713
714 let content = if is_empty {
715 let message = if has_query {
716 "No threads match your search."
717 } else {
718 "No archived or hidden threads yet."
719 };
720
721 v_flex()
722 .flex_1()
723 .justify_center()
724 .items_center()
725 .child(
726 Label::new(message)
727 .size(LabelSize::Small)
728 .color(Color::Muted),
729 )
730 .into_any_element()
731 } else {
732 v_flex()
733 .flex_1()
734 .overflow_hidden()
735 .child(
736 list(
737 self.list_state.clone(),
738 cx.processor(Self::render_list_entry),
739 )
740 .flex_1()
741 .size_full(),
742 )
743 .vertical_scrollbar_for(&self.list_state, window, cx)
744 .into_any_element()
745 };
746
747 v_flex()
748 .key_context("ThreadsArchiveView")
749 .track_focus(&self.focus_handle)
750 .on_action(cx.listener(Self::select_next))
751 .on_action(cx.listener(Self::select_previous))
752 .on_action(cx.listener(Self::editor_move_down))
753 .on_action(cx.listener(Self::editor_move_up))
754 .on_action(cx.listener(Self::select_first))
755 .on_action(cx.listener(Self::select_last))
756 .on_action(cx.listener(Self::confirm))
757 .on_action(cx.listener(Self::remove_selected_thread))
758 .size_full()
759 .child(self.render_header(window, cx))
760 .child(content)
761 }
762}
763
764struct ProjectPickerModal {
765 picker: Entity<Picker<ProjectPickerDelegate>>,
766 _subscription: Subscription,
767}
768
769impl ProjectPickerModal {
770 fn new(
771 thread: ThreadMetadata,
772 fs: Arc<dyn Fs>,
773 archive_view: WeakEntity<ThreadsArchiveView>,
774 current_workspace_id: Option<WorkspaceId>,
775 sibling_workspace_ids: HashSet<WorkspaceId>,
776 window: &mut Window,
777 cx: &mut Context<Self>,
778 ) -> Self {
779 let delegate = ProjectPickerDelegate {
780 thread,
781 archive_view,
782 workspaces: Vec::new(),
783 filtered_entries: Vec::new(),
784 selected_index: 0,
785 current_workspace_id,
786 sibling_workspace_ids,
787 focus_handle: cx.focus_handle(),
788 };
789
790 let picker = cx.new(|cx| {
791 Picker::list(delegate, window, cx)
792 .list_measure_all()
793 .modal(false)
794 });
795
796 let picker_focus_handle = picker.focus_handle(cx);
797 picker.update(cx, |picker, _| {
798 picker.delegate.focus_handle = picker_focus_handle;
799 });
800
801 let _subscription =
802 cx.subscribe(&picker, |_this: &mut Self, _, _event: &DismissEvent, cx| {
803 cx.emit(DismissEvent);
804 });
805
806 let db = WorkspaceDb::global(cx);
807 cx.spawn_in(window, async move |this, cx| {
808 let workspaces = db
809 .recent_workspaces_on_disk(fs.as_ref())
810 .await
811 .log_err()
812 .unwrap_or_default();
813 let workspaces = resolve_worktree_workspaces(workspaces, fs.as_ref()).await;
814 this.update_in(cx, move |this, window, cx| {
815 this.picker.update(cx, move |picker, cx| {
816 picker.delegate.workspaces = workspaces;
817 picker.update_matches(picker.query(cx), window, cx)
818 })
819 })
820 .ok();
821 })
822 .detach();
823
824 picker.focus_handle(cx).focus(window, cx);
825
826 Self {
827 picker,
828 _subscription,
829 }
830 }
831}
832
833impl EventEmitter<DismissEvent> for ProjectPickerModal {}
834
835impl Focusable for ProjectPickerModal {
836 fn focus_handle(&self, cx: &App) -> FocusHandle {
837 self.picker.focus_handle(cx)
838 }
839}
840
841impl ModalView for ProjectPickerModal {}
842
843impl Render for ProjectPickerModal {
844 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
845 v_flex()
846 .key_context("ProjectPickerModal")
847 .elevation_3(cx)
848 .w(rems(34.))
849 .on_action(cx.listener(|this, _: &workspace::Open, window, cx| {
850 this.picker.update(cx, |picker, cx| {
851 picker.delegate.open_local_folder(window, cx)
852 })
853 }))
854 .child(self.picker.clone())
855 }
856}
857
858enum ProjectPickerEntry {
859 Header(SharedString),
860 Workspace(StringMatch),
861}
862
863struct ProjectPickerDelegate {
864 thread: ThreadMetadata,
865 archive_view: WeakEntity<ThreadsArchiveView>,
866 current_workspace_id: Option<WorkspaceId>,
867 sibling_workspace_ids: HashSet<WorkspaceId>,
868 workspaces: Vec<(
869 WorkspaceId,
870 SerializedWorkspaceLocation,
871 PathList,
872 DateTime<Utc>,
873 )>,
874 filtered_entries: Vec<ProjectPickerEntry>,
875 selected_index: usize,
876 focus_handle: FocusHandle,
877}
878
879impl ProjectPickerDelegate {
880 fn update_working_directories_and_unarchive(
881 &mut self,
882 paths: PathList,
883 window: &mut Window,
884 cx: &mut Context<Picker<Self>>,
885 ) {
886 self.thread.folder_paths = paths.clone();
887 ThreadMetadataStore::global(cx).update(cx, |store, cx| {
888 store.update_working_directories(&self.thread.session_id, paths, cx);
889 });
890
891 self.archive_view
892 .update(cx, |view, cx| {
893 view.selection = None;
894 view.reset_filter_editor_text(window, cx);
895 cx.emit(ThreadsArchiveViewEvent::Unarchive {
896 thread: self.thread.clone(),
897 });
898 })
899 .log_err();
900 }
901
902 fn is_current_workspace(&self, workspace_id: WorkspaceId) -> bool {
903 self.current_workspace_id == Some(workspace_id)
904 }
905
906 fn is_sibling_workspace(&self, workspace_id: WorkspaceId) -> bool {
907 self.sibling_workspace_ids.contains(&workspace_id)
908 && !self.is_current_workspace(workspace_id)
909 }
910
911 fn selected_match(&self) -> Option<&StringMatch> {
912 match self.filtered_entries.get(self.selected_index)? {
913 ProjectPickerEntry::Workspace(hit) => Some(hit),
914 ProjectPickerEntry::Header(_) => None,
915 }
916 }
917
918 fn open_local_folder(&mut self, window: &mut Window, cx: &mut Context<Picker<Self>>) {
919 let paths_receiver = cx.prompt_for_paths(gpui::PathPromptOptions {
920 files: false,
921 directories: true,
922 multiple: false,
923 prompt: None,
924 });
925 cx.spawn_in(window, async move |this, cx| {
926 let Ok(Ok(Some(paths))) = paths_receiver.await else {
927 return;
928 };
929 if paths.is_empty() {
930 return;
931 }
932
933 let work_dirs = PathList::new(&paths);
934
935 this.update_in(cx, |this, window, cx| {
936 this.delegate
937 .update_working_directories_and_unarchive(work_dirs, window, cx);
938 cx.emit(DismissEvent);
939 })
940 .log_err();
941 })
942 .detach();
943 }
944}
945
946impl EventEmitter<DismissEvent> for ProjectPickerDelegate {}
947
948impl PickerDelegate for ProjectPickerDelegate {
949 type ListItem = AnyElement;
950
951 fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc<str> {
952 format!("Associate the \"{}\" thread with...", self.thread.title).into()
953 }
954
955 fn render_editor(
956 &self,
957 editor: &Arc<dyn ErasedEditor>,
958 window: &mut Window,
959 cx: &mut Context<Picker<Self>>,
960 ) -> Div {
961 h_flex()
962 .flex_none()
963 .h_9()
964 .px_2p5()
965 .justify_between()
966 .border_b_1()
967 .border_color(cx.theme().colors().border_variant)
968 .child(editor.render(window, cx))
969 }
970
971 fn match_count(&self) -> usize {
972 self.filtered_entries.len()
973 }
974
975 fn selected_index(&self) -> usize {
976 self.selected_index
977 }
978
979 fn set_selected_index(
980 &mut self,
981 ix: usize,
982 _window: &mut Window,
983 _cx: &mut Context<Picker<Self>>,
984 ) {
985 self.selected_index = ix;
986 }
987
988 fn can_select(&self, ix: usize, _window: &mut Window, _cx: &mut Context<Picker<Self>>) -> bool {
989 matches!(
990 self.filtered_entries.get(ix),
991 Some(ProjectPickerEntry::Workspace(_))
992 )
993 }
994
995 fn update_matches(
996 &mut self,
997 query: String,
998 _window: &mut Window,
999 cx: &mut Context<Picker<Self>>,
1000 ) -> Task<()> {
1001 let query = query.trim_start();
1002 let smart_case = query.chars().any(|c| c.is_uppercase());
1003 let is_empty_query = query.is_empty();
1004
1005 let sibling_candidates: Vec<_> = self
1006 .workspaces
1007 .iter()
1008 .enumerate()
1009 .filter(|(_, (id, _, _, _))| self.is_sibling_workspace(*id))
1010 .map(|(id, (_, _, paths, _))| {
1011 let combined_string = paths
1012 .ordered_paths()
1013 .map(|path| path.compact().to_string_lossy().into_owned())
1014 .collect::<Vec<_>>()
1015 .join("");
1016 StringMatchCandidate::new(id, &combined_string)
1017 })
1018 .collect();
1019
1020 let mut sibling_matches = smol::block_on(fuzzy::match_strings(
1021 &sibling_candidates,
1022 query,
1023 smart_case,
1024 true,
1025 100,
1026 &Default::default(),
1027 cx.background_executor().clone(),
1028 ));
1029
1030 sibling_matches.sort_unstable_by(|a, b| {
1031 b.score
1032 .partial_cmp(&a.score)
1033 .unwrap_or(std::cmp::Ordering::Equal)
1034 .then_with(|| a.candidate_id.cmp(&b.candidate_id))
1035 });
1036
1037 let recent_candidates: Vec<_> = self
1038 .workspaces
1039 .iter()
1040 .enumerate()
1041 .filter(|(_, (id, _, _, _))| {
1042 !self.is_current_workspace(*id) && !self.is_sibling_workspace(*id)
1043 })
1044 .map(|(id, (_, _, paths, _))| {
1045 let combined_string = paths
1046 .ordered_paths()
1047 .map(|path| path.compact().to_string_lossy().into_owned())
1048 .collect::<Vec<_>>()
1049 .join("");
1050 StringMatchCandidate::new(id, &combined_string)
1051 })
1052 .collect();
1053
1054 let mut recent_matches = smol::block_on(fuzzy::match_strings(
1055 &recent_candidates,
1056 query,
1057 smart_case,
1058 true,
1059 100,
1060 &Default::default(),
1061 cx.background_executor().clone(),
1062 ));
1063
1064 recent_matches.sort_unstable_by(|a, b| {
1065 b.score
1066 .partial_cmp(&a.score)
1067 .unwrap_or(std::cmp::Ordering::Equal)
1068 .then_with(|| a.candidate_id.cmp(&b.candidate_id))
1069 });
1070
1071 let mut entries = Vec::new();
1072
1073 let has_siblings_to_show = if is_empty_query {
1074 !sibling_candidates.is_empty()
1075 } else {
1076 !sibling_matches.is_empty()
1077 };
1078
1079 if has_siblings_to_show {
1080 entries.push(ProjectPickerEntry::Header("This Window".into()));
1081
1082 if is_empty_query {
1083 for (id, (workspace_id, _, _, _)) in self.workspaces.iter().enumerate() {
1084 if self.is_sibling_workspace(*workspace_id) {
1085 entries.push(ProjectPickerEntry::Workspace(StringMatch {
1086 candidate_id: id,
1087 score: 0.0,
1088 positions: Vec::new(),
1089 string: String::new(),
1090 }));
1091 }
1092 }
1093 } else {
1094 for m in sibling_matches {
1095 entries.push(ProjectPickerEntry::Workspace(m));
1096 }
1097 }
1098 }
1099
1100 let has_recent_to_show = if is_empty_query {
1101 !recent_candidates.is_empty()
1102 } else {
1103 !recent_matches.is_empty()
1104 };
1105
1106 if has_recent_to_show {
1107 entries.push(ProjectPickerEntry::Header("Recent Projects".into()));
1108
1109 if is_empty_query {
1110 for (id, (workspace_id, _, _, _)) in self.workspaces.iter().enumerate() {
1111 if !self.is_current_workspace(*workspace_id)
1112 && !self.is_sibling_workspace(*workspace_id)
1113 {
1114 entries.push(ProjectPickerEntry::Workspace(StringMatch {
1115 candidate_id: id,
1116 score: 0.0,
1117 positions: Vec::new(),
1118 string: String::new(),
1119 }));
1120 }
1121 }
1122 } else {
1123 for m in recent_matches {
1124 entries.push(ProjectPickerEntry::Workspace(m));
1125 }
1126 }
1127 }
1128
1129 self.filtered_entries = entries;
1130
1131 self.selected_index = self
1132 .filtered_entries
1133 .iter()
1134 .position(|e| matches!(e, ProjectPickerEntry::Workspace(_)))
1135 .unwrap_or(0);
1136
1137 Task::ready(())
1138 }
1139
1140 fn confirm(&mut self, _secondary: bool, window: &mut Window, cx: &mut Context<Picker<Self>>) {
1141 let candidate_id = match self.filtered_entries.get(self.selected_index) {
1142 Some(ProjectPickerEntry::Workspace(hit)) => hit.candidate_id,
1143 _ => return,
1144 };
1145 let Some((_workspace_id, _location, paths, _)) = self.workspaces.get(candidate_id) else {
1146 return;
1147 };
1148
1149 self.update_working_directories_and_unarchive(paths.clone(), window, cx);
1150 cx.emit(DismissEvent);
1151 }
1152
1153 fn dismissed(&mut self, _window: &mut Window, _cx: &mut Context<Picker<Self>>) {}
1154
1155 fn no_matches_text(&self, _window: &mut Window, _cx: &mut App) -> Option<SharedString> {
1156 let text = if self.workspaces.is_empty() {
1157 "No recent projects found"
1158 } else {
1159 "No matches"
1160 };
1161 Some(text.into())
1162 }
1163
1164 fn render_match(
1165 &self,
1166 ix: usize,
1167 selected: bool,
1168 window: &mut Window,
1169 cx: &mut Context<Picker<Self>>,
1170 ) -> Option<Self::ListItem> {
1171 match self.filtered_entries.get(ix)? {
1172 ProjectPickerEntry::Header(title) => Some(
1173 v_flex()
1174 .w_full()
1175 .gap_1()
1176 .when(ix > 0, |this| this.mt_1().child(Divider::horizontal()))
1177 .child(ListSubHeader::new(title.clone()).inset(true))
1178 .into_any_element(),
1179 ),
1180 ProjectPickerEntry::Workspace(hit) => {
1181 let (_, location, paths, _) = self.workspaces.get(hit.candidate_id)?;
1182
1183 let ordered_paths: Vec<_> = paths
1184 .ordered_paths()
1185 .map(|p| p.compact().to_string_lossy().to_string())
1186 .collect();
1187
1188 let tooltip_path: SharedString = ordered_paths.join("\n").into();
1189
1190 let mut path_start_offset = 0;
1191 let match_labels: Vec<_> = paths
1192 .ordered_paths()
1193 .map(|p| p.compact())
1194 .map(|path| {
1195 let path_string = path.to_string_lossy();
1196 let path_text = path_string.to_string();
1197 let path_byte_len = path_text.len();
1198
1199 let path_positions: Vec<usize> = hit
1200 .positions
1201 .iter()
1202 .copied()
1203 .skip_while(|pos| *pos < path_start_offset)
1204 .take_while(|pos| *pos < path_start_offset + path_byte_len)
1205 .map(|pos| pos - path_start_offset)
1206 .collect();
1207
1208 let file_name_match = path.file_name().map(|file_name| {
1209 let file_name_text = file_name.to_string_lossy().into_owned();
1210 let file_name_start = path_byte_len - file_name_text.len();
1211 let highlight_positions: Vec<usize> = path_positions
1212 .iter()
1213 .copied()
1214 .skip_while(|pos| *pos < file_name_start)
1215 .take_while(|pos| *pos < file_name_start + file_name_text.len())
1216 .map(|pos| pos - file_name_start)
1217 .collect();
1218 HighlightedMatch {
1219 text: file_name_text,
1220 highlight_positions,
1221 color: Color::Default,
1222 }
1223 });
1224
1225 path_start_offset += path_byte_len;
1226 file_name_match
1227 })
1228 .collect();
1229
1230 let highlighted_match = HighlightedMatchWithPaths {
1231 prefix: match location {
1232 SerializedWorkspaceLocation::Remote(options) => {
1233 Some(SharedString::from(options.display_name()))
1234 }
1235 _ => None,
1236 },
1237 match_label: HighlightedMatch::join(match_labels.into_iter().flatten(), ", "),
1238 paths: Vec::new(),
1239 active: false,
1240 };
1241
1242 Some(
1243 ListItem::new(ix)
1244 .toggle_state(selected)
1245 .inset(true)
1246 .spacing(ListItemSpacing::Sparse)
1247 .child(
1248 h_flex()
1249 .gap_3()
1250 .flex_grow()
1251 .child(highlighted_match.render(window, cx)),
1252 )
1253 .tooltip(Tooltip::text(tooltip_path))
1254 .into_any_element(),
1255 )
1256 }
1257 }
1258 }
1259
1260 fn render_footer(&self, _: &mut Window, cx: &mut Context<Picker<Self>>) -> Option<AnyElement> {
1261 let has_selection = self.selected_match().is_some();
1262 let focus_handle = self.focus_handle.clone();
1263
1264 Some(
1265 h_flex()
1266 .flex_1()
1267 .p_1p5()
1268 .gap_1()
1269 .justify_end()
1270 .border_t_1()
1271 .border_color(cx.theme().colors().border_variant)
1272 .child(
1273 Button::new("open_local_folder", "Choose from Local Folders")
1274 .key_binding(KeyBinding::for_action_in(
1275 &workspace::Open::default(),
1276 &focus_handle,
1277 cx,
1278 ))
1279 .on_click(cx.listener(|this, _, window, cx| {
1280 this.delegate.open_local_folder(window, cx);
1281 })),
1282 )
1283 .child(
1284 Button::new("select_project", "Select")
1285 .disabled(!has_selection)
1286 .key_binding(KeyBinding::for_action_in(&menu::Confirm, &focus_handle, cx))
1287 .on_click(cx.listener(move |picker, _, window, cx| {
1288 picker.delegate.confirm(false, window, cx);
1289 })),
1290 )
1291 .into_any(),
1292 )
1293 }
1294}
1295
1296#[cfg(test)]
1297mod tests {
1298 use super::*;
1299
1300 #[test]
1301 fn test_fuzzy_match_positions_returns_byte_indices() {
1302 // "🔥abc" — the fire emoji is 4 bytes, so 'a' starts at byte 4, 'b' at 5, 'c' at 6.
1303 let text = "🔥abc";
1304 let positions = fuzzy_match_positions("ab", text).expect("should match");
1305 assert_eq!(positions, vec![4, 5]);
1306
1307 // Verify positions are valid char boundaries (this is the assertion that
1308 // panicked before the fix).
1309 for &pos in &positions {
1310 assert!(
1311 text.is_char_boundary(pos),
1312 "position {pos} is not a valid UTF-8 boundary in {text:?}"
1313 );
1314 }
1315 }
1316
1317 #[test]
1318 fn test_fuzzy_match_positions_ascii_still_works() {
1319 let positions = fuzzy_match_positions("he", "hello").expect("should match");
1320 assert_eq!(positions, vec![0, 1]);
1321 }
1322
1323 #[test]
1324 fn test_fuzzy_match_positions_case_insensitive() {
1325 let positions = fuzzy_match_positions("HE", "hello").expect("should match");
1326 assert_eq!(positions, vec![0, 1]);
1327 }
1328
1329 #[test]
1330 fn test_fuzzy_match_positions_no_match() {
1331 assert!(fuzzy_match_positions("xyz", "hello").is_none());
1332 }
1333
1334 #[test]
1335 fn test_fuzzy_match_positions_multi_byte_interior() {
1336 // "café" — 'é' is 2 bytes (0xC3 0xA9), so 'f' starts at byte 4, 'é' at byte 5.
1337 let text = "café";
1338 let positions = fuzzy_match_positions("fé", text).expect("should match");
1339 // 'c'=0, 'a'=1, 'f'=2, 'é'=3..4 — wait, let's verify:
1340 // Actually: c=1 byte, a=1 byte, f=1 byte, é=2 bytes
1341 // So byte positions: c=0, a=1, f=2, é=3
1342 assert_eq!(positions, vec![2, 3]);
1343 for &pos in &positions {
1344 assert!(
1345 text.is_char_boundary(pos),
1346 "position {pos} is not a valid UTF-8 boundary in {text:?}"
1347 );
1348 }
1349 }
1350}