threads_archive_view.rs

   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            crate::thread_worktree_archive::cleanup_thread_archived_worktrees(&session_id, cx)
 607                .await;
 608
 609            let state = task.await?;
 610            let task = cx.update(|cx| {
 611                if let Some(list) = state.connection.session_list(cx) {
 612                    list.delete_session(&session_id, cx)
 613                } else {
 614                    Task::ready(Ok(()))
 615                }
 616            });
 617            task.await
 618        })
 619        .detach_and_log_err(cx);
 620    }
 621
 622    fn render_header(&self, window: &Window, cx: &mut Context<Self>) -> impl IntoElement {
 623        let has_query = !self.filter_editor.read(cx).text(cx).is_empty();
 624        let sidebar_on_left = matches!(
 625            AgentSettings::get_global(cx).sidebar_side(),
 626            settings::SidebarSide::Left
 627        );
 628        let traffic_lights =
 629            cfg!(target_os = "macos") && !window.is_fullscreen() && sidebar_on_left;
 630        let header_height = platform_title_bar_height(window);
 631        let show_focus_keybinding =
 632            self.selection.is_some() && !self.filter_editor.focus_handle(cx).is_focused(window);
 633
 634        h_flex()
 635            .h(header_height)
 636            .mt_px()
 637            .pb_px()
 638            .map(|this| {
 639                if traffic_lights {
 640                    this.pl(px(ui::utils::TRAFFIC_LIGHT_PADDING))
 641                } else {
 642                    this.pl_1p5()
 643                }
 644            })
 645            .pr_1p5()
 646            .gap_1()
 647            .justify_between()
 648            .border_b_1()
 649            .border_color(cx.theme().colors().border)
 650            .when(traffic_lights, |this| {
 651                this.child(Divider::vertical().color(ui::DividerColor::Border))
 652            })
 653            .child(
 654                h_flex()
 655                    .ml_1()
 656                    .min_w_0()
 657                    .w_full()
 658                    .gap_1()
 659                    .child(
 660                        Icon::new(IconName::MagnifyingGlass)
 661                            .size(IconSize::Small)
 662                            .color(Color::Muted),
 663                    )
 664                    .child(self.filter_editor.clone()),
 665            )
 666            .when(show_focus_keybinding, |this| {
 667                this.child(KeyBinding::for_action(&FocusSidebarFilter, cx))
 668            })
 669            .when(has_query, |this| {
 670                this.child(
 671                    IconButton::new("clear-filter", IconName::Close)
 672                        .icon_size(IconSize::Small)
 673                        .tooltip(Tooltip::text("Clear Search"))
 674                        .on_click(cx.listener(|this, _, window, cx| {
 675                            this.reset_filter_editor_text(window, cx);
 676                            this.update_items(cx);
 677                        })),
 678                )
 679            })
 680    }
 681}
 682
 683pub fn format_history_entry_timestamp(entry_time: DateTime<Utc>) -> String {
 684    let now = Utc::now();
 685    let duration = now.signed_duration_since(entry_time);
 686
 687    let minutes = duration.num_minutes();
 688    let hours = duration.num_hours();
 689    let days = duration.num_days();
 690    let weeks = days / 7;
 691    let months = days / 30;
 692
 693    if minutes < 60 {
 694        format!("{}m", minutes.max(1))
 695    } else if hours < 24 {
 696        format!("{}h", hours.max(1))
 697    } else if days < 7 {
 698        format!("{}d", days.max(1))
 699    } else if weeks < 4 {
 700        format!("{}w", weeks.max(1))
 701    } else {
 702        format!("{}mo", months.max(1))
 703    }
 704}
 705
 706impl Focusable for ThreadsArchiveView {
 707    fn focus_handle(&self, _cx: &App) -> FocusHandle {
 708        self.focus_handle.clone()
 709    }
 710}
 711
 712impl Render for ThreadsArchiveView {
 713    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 714        let is_empty = self.items.is_empty();
 715        let has_query = !self.filter_editor.read(cx).text(cx).is_empty();
 716
 717        let content = if is_empty {
 718            let message = if has_query {
 719                "No threads match your search."
 720            } else {
 721                "No archived or hidden threads yet."
 722            };
 723
 724            v_flex()
 725                .flex_1()
 726                .justify_center()
 727                .items_center()
 728                .child(
 729                    Label::new(message)
 730                        .size(LabelSize::Small)
 731                        .color(Color::Muted),
 732                )
 733                .into_any_element()
 734        } else {
 735            v_flex()
 736                .flex_1()
 737                .overflow_hidden()
 738                .child(
 739                    list(
 740                        self.list_state.clone(),
 741                        cx.processor(Self::render_list_entry),
 742                    )
 743                    .flex_1()
 744                    .size_full(),
 745                )
 746                .vertical_scrollbar_for(&self.list_state, window, cx)
 747                .into_any_element()
 748        };
 749
 750        v_flex()
 751            .key_context("ThreadsArchiveView")
 752            .track_focus(&self.focus_handle)
 753            .on_action(cx.listener(Self::select_next))
 754            .on_action(cx.listener(Self::select_previous))
 755            .on_action(cx.listener(Self::editor_move_down))
 756            .on_action(cx.listener(Self::editor_move_up))
 757            .on_action(cx.listener(Self::select_first))
 758            .on_action(cx.listener(Self::select_last))
 759            .on_action(cx.listener(Self::confirm))
 760            .on_action(cx.listener(Self::remove_selected_thread))
 761            .size_full()
 762            .child(self.render_header(window, cx))
 763            .child(content)
 764    }
 765}
 766
 767struct ProjectPickerModal {
 768    picker: Entity<Picker<ProjectPickerDelegate>>,
 769    _subscription: Subscription,
 770}
 771
 772impl ProjectPickerModal {
 773    fn new(
 774        thread: ThreadMetadata,
 775        fs: Arc<dyn Fs>,
 776        archive_view: WeakEntity<ThreadsArchiveView>,
 777        current_workspace_id: Option<WorkspaceId>,
 778        sibling_workspace_ids: HashSet<WorkspaceId>,
 779        window: &mut Window,
 780        cx: &mut Context<Self>,
 781    ) -> Self {
 782        let delegate = ProjectPickerDelegate {
 783            thread,
 784            archive_view,
 785            workspaces: Vec::new(),
 786            filtered_entries: Vec::new(),
 787            selected_index: 0,
 788            current_workspace_id,
 789            sibling_workspace_ids,
 790            focus_handle: cx.focus_handle(),
 791        };
 792
 793        let picker = cx.new(|cx| {
 794            Picker::list(delegate, window, cx)
 795                .list_measure_all()
 796                .modal(false)
 797        });
 798
 799        let picker_focus_handle = picker.focus_handle(cx);
 800        picker.update(cx, |picker, _| {
 801            picker.delegate.focus_handle = picker_focus_handle;
 802        });
 803
 804        let _subscription =
 805            cx.subscribe(&picker, |_this: &mut Self, _, _event: &DismissEvent, cx| {
 806                cx.emit(DismissEvent);
 807            });
 808
 809        let db = WorkspaceDb::global(cx);
 810        cx.spawn_in(window, async move |this, cx| {
 811            let workspaces = db
 812                .recent_workspaces_on_disk(fs.as_ref())
 813                .await
 814                .log_err()
 815                .unwrap_or_default();
 816            let workspaces = resolve_worktree_workspaces(workspaces, fs.as_ref()).await;
 817            this.update_in(cx, move |this, window, cx| {
 818                this.picker.update(cx, move |picker, cx| {
 819                    picker.delegate.workspaces = workspaces;
 820                    picker.update_matches(picker.query(cx), window, cx)
 821                })
 822            })
 823            .ok();
 824        })
 825        .detach();
 826
 827        picker.focus_handle(cx).focus(window, cx);
 828
 829        Self {
 830            picker,
 831            _subscription,
 832        }
 833    }
 834}
 835
 836impl EventEmitter<DismissEvent> for ProjectPickerModal {}
 837
 838impl Focusable for ProjectPickerModal {
 839    fn focus_handle(&self, cx: &App) -> FocusHandle {
 840        self.picker.focus_handle(cx)
 841    }
 842}
 843
 844impl ModalView for ProjectPickerModal {}
 845
 846impl Render for ProjectPickerModal {
 847    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 848        v_flex()
 849            .key_context("ProjectPickerModal")
 850            .elevation_3(cx)
 851            .w(rems(34.))
 852            .on_action(cx.listener(|this, _: &workspace::Open, window, cx| {
 853                this.picker.update(cx, |picker, cx| {
 854                    picker.delegate.open_local_folder(window, cx)
 855                })
 856            }))
 857            .child(self.picker.clone())
 858    }
 859}
 860
 861enum ProjectPickerEntry {
 862    Header(SharedString),
 863    Workspace(StringMatch),
 864}
 865
 866struct ProjectPickerDelegate {
 867    thread: ThreadMetadata,
 868    archive_view: WeakEntity<ThreadsArchiveView>,
 869    current_workspace_id: Option<WorkspaceId>,
 870    sibling_workspace_ids: HashSet<WorkspaceId>,
 871    workspaces: Vec<(
 872        WorkspaceId,
 873        SerializedWorkspaceLocation,
 874        PathList,
 875        DateTime<Utc>,
 876    )>,
 877    filtered_entries: Vec<ProjectPickerEntry>,
 878    selected_index: usize,
 879    focus_handle: FocusHandle,
 880}
 881
 882impl ProjectPickerDelegate {
 883    fn update_working_directories_and_unarchive(
 884        &mut self,
 885        paths: PathList,
 886        window: &mut Window,
 887        cx: &mut Context<Picker<Self>>,
 888    ) {
 889        self.thread.folder_paths = paths.clone();
 890        ThreadMetadataStore::global(cx).update(cx, |store, cx| {
 891            store.update_working_directories(&self.thread.session_id, paths, cx);
 892        });
 893
 894        self.archive_view
 895            .update(cx, |view, cx| {
 896                view.selection = None;
 897                view.reset_filter_editor_text(window, cx);
 898                cx.emit(ThreadsArchiveViewEvent::Unarchive {
 899                    thread: self.thread.clone(),
 900                });
 901            })
 902            .log_err();
 903    }
 904
 905    fn is_current_workspace(&self, workspace_id: WorkspaceId) -> bool {
 906        self.current_workspace_id == Some(workspace_id)
 907    }
 908
 909    fn is_sibling_workspace(&self, workspace_id: WorkspaceId) -> bool {
 910        self.sibling_workspace_ids.contains(&workspace_id)
 911            && !self.is_current_workspace(workspace_id)
 912    }
 913
 914    fn selected_match(&self) -> Option<&StringMatch> {
 915        match self.filtered_entries.get(self.selected_index)? {
 916            ProjectPickerEntry::Workspace(hit) => Some(hit),
 917            ProjectPickerEntry::Header(_) => None,
 918        }
 919    }
 920
 921    fn open_local_folder(&mut self, window: &mut Window, cx: &mut Context<Picker<Self>>) {
 922        let paths_receiver = cx.prompt_for_paths(gpui::PathPromptOptions {
 923            files: false,
 924            directories: true,
 925            multiple: false,
 926            prompt: None,
 927        });
 928        cx.spawn_in(window, async move |this, cx| {
 929            let Ok(Ok(Some(paths))) = paths_receiver.await else {
 930                return;
 931            };
 932            if paths.is_empty() {
 933                return;
 934            }
 935
 936            let work_dirs = PathList::new(&paths);
 937
 938            this.update_in(cx, |this, window, cx| {
 939                this.delegate
 940                    .update_working_directories_and_unarchive(work_dirs, window, cx);
 941                cx.emit(DismissEvent);
 942            })
 943            .log_err();
 944        })
 945        .detach();
 946    }
 947}
 948
 949impl EventEmitter<DismissEvent> for ProjectPickerDelegate {}
 950
 951impl PickerDelegate for ProjectPickerDelegate {
 952    type ListItem = AnyElement;
 953
 954    fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc<str> {
 955        format!("Associate the \"{}\" thread with...", self.thread.title).into()
 956    }
 957
 958    fn render_editor(
 959        &self,
 960        editor: &Arc<dyn ErasedEditor>,
 961        window: &mut Window,
 962        cx: &mut Context<Picker<Self>>,
 963    ) -> Div {
 964        h_flex()
 965            .flex_none()
 966            .h_9()
 967            .px_2p5()
 968            .justify_between()
 969            .border_b_1()
 970            .border_color(cx.theme().colors().border_variant)
 971            .child(editor.render(window, cx))
 972    }
 973
 974    fn match_count(&self) -> usize {
 975        self.filtered_entries.len()
 976    }
 977
 978    fn selected_index(&self) -> usize {
 979        self.selected_index
 980    }
 981
 982    fn set_selected_index(
 983        &mut self,
 984        ix: usize,
 985        _window: &mut Window,
 986        _cx: &mut Context<Picker<Self>>,
 987    ) {
 988        self.selected_index = ix;
 989    }
 990
 991    fn can_select(&self, ix: usize, _window: &mut Window, _cx: &mut Context<Picker<Self>>) -> bool {
 992        matches!(
 993            self.filtered_entries.get(ix),
 994            Some(ProjectPickerEntry::Workspace(_))
 995        )
 996    }
 997
 998    fn update_matches(
 999        &mut self,
1000        query: String,
1001        _window: &mut Window,
1002        cx: &mut Context<Picker<Self>>,
1003    ) -> Task<()> {
1004        let query = query.trim_start();
1005        let smart_case = query.chars().any(|c| c.is_uppercase());
1006        let is_empty_query = query.is_empty();
1007
1008        let sibling_candidates: Vec<_> = self
1009            .workspaces
1010            .iter()
1011            .enumerate()
1012            .filter(|(_, (id, _, _, _))| self.is_sibling_workspace(*id))
1013            .map(|(id, (_, _, paths, _))| {
1014                let combined_string = paths
1015                    .ordered_paths()
1016                    .map(|path| path.compact().to_string_lossy().into_owned())
1017                    .collect::<Vec<_>>()
1018                    .join("");
1019                StringMatchCandidate::new(id, &combined_string)
1020            })
1021            .collect();
1022
1023        let mut sibling_matches = smol::block_on(fuzzy::match_strings(
1024            &sibling_candidates,
1025            query,
1026            smart_case,
1027            true,
1028            100,
1029            &Default::default(),
1030            cx.background_executor().clone(),
1031        ));
1032
1033        sibling_matches.sort_unstable_by(|a, b| {
1034            b.score
1035                .partial_cmp(&a.score)
1036                .unwrap_or(std::cmp::Ordering::Equal)
1037                .then_with(|| a.candidate_id.cmp(&b.candidate_id))
1038        });
1039
1040        let recent_candidates: Vec<_> = self
1041            .workspaces
1042            .iter()
1043            .enumerate()
1044            .filter(|(_, (id, _, _, _))| {
1045                !self.is_current_workspace(*id) && !self.is_sibling_workspace(*id)
1046            })
1047            .map(|(id, (_, _, paths, _))| {
1048                let combined_string = paths
1049                    .ordered_paths()
1050                    .map(|path| path.compact().to_string_lossy().into_owned())
1051                    .collect::<Vec<_>>()
1052                    .join("");
1053                StringMatchCandidate::new(id, &combined_string)
1054            })
1055            .collect();
1056
1057        let mut recent_matches = smol::block_on(fuzzy::match_strings(
1058            &recent_candidates,
1059            query,
1060            smart_case,
1061            true,
1062            100,
1063            &Default::default(),
1064            cx.background_executor().clone(),
1065        ));
1066
1067        recent_matches.sort_unstable_by(|a, b| {
1068            b.score
1069                .partial_cmp(&a.score)
1070                .unwrap_or(std::cmp::Ordering::Equal)
1071                .then_with(|| a.candidate_id.cmp(&b.candidate_id))
1072        });
1073
1074        let mut entries = Vec::new();
1075
1076        let has_siblings_to_show = if is_empty_query {
1077            !sibling_candidates.is_empty()
1078        } else {
1079            !sibling_matches.is_empty()
1080        };
1081
1082        if has_siblings_to_show {
1083            entries.push(ProjectPickerEntry::Header("This Window".into()));
1084
1085            if is_empty_query {
1086                for (id, (workspace_id, _, _, _)) in self.workspaces.iter().enumerate() {
1087                    if self.is_sibling_workspace(*workspace_id) {
1088                        entries.push(ProjectPickerEntry::Workspace(StringMatch {
1089                            candidate_id: id,
1090                            score: 0.0,
1091                            positions: Vec::new(),
1092                            string: String::new(),
1093                        }));
1094                    }
1095                }
1096            } else {
1097                for m in sibling_matches {
1098                    entries.push(ProjectPickerEntry::Workspace(m));
1099                }
1100            }
1101        }
1102
1103        let has_recent_to_show = if is_empty_query {
1104            !recent_candidates.is_empty()
1105        } else {
1106            !recent_matches.is_empty()
1107        };
1108
1109        if has_recent_to_show {
1110            entries.push(ProjectPickerEntry::Header("Recent Projects".into()));
1111
1112            if is_empty_query {
1113                for (id, (workspace_id, _, _, _)) in self.workspaces.iter().enumerate() {
1114                    if !self.is_current_workspace(*workspace_id)
1115                        && !self.is_sibling_workspace(*workspace_id)
1116                    {
1117                        entries.push(ProjectPickerEntry::Workspace(StringMatch {
1118                            candidate_id: id,
1119                            score: 0.0,
1120                            positions: Vec::new(),
1121                            string: String::new(),
1122                        }));
1123                    }
1124                }
1125            } else {
1126                for m in recent_matches {
1127                    entries.push(ProjectPickerEntry::Workspace(m));
1128                }
1129            }
1130        }
1131
1132        self.filtered_entries = entries;
1133
1134        self.selected_index = self
1135            .filtered_entries
1136            .iter()
1137            .position(|e| matches!(e, ProjectPickerEntry::Workspace(_)))
1138            .unwrap_or(0);
1139
1140        Task::ready(())
1141    }
1142
1143    fn confirm(&mut self, _secondary: bool, window: &mut Window, cx: &mut Context<Picker<Self>>) {
1144        let candidate_id = match self.filtered_entries.get(self.selected_index) {
1145            Some(ProjectPickerEntry::Workspace(hit)) => hit.candidate_id,
1146            _ => return,
1147        };
1148        let Some((_workspace_id, _location, paths, _)) = self.workspaces.get(candidate_id) else {
1149            return;
1150        };
1151
1152        self.update_working_directories_and_unarchive(paths.clone(), window, cx);
1153        cx.emit(DismissEvent);
1154    }
1155
1156    fn dismissed(&mut self, _window: &mut Window, _cx: &mut Context<Picker<Self>>) {}
1157
1158    fn no_matches_text(&self, _window: &mut Window, _cx: &mut App) -> Option<SharedString> {
1159        let text = if self.workspaces.is_empty() {
1160            "No recent projects found"
1161        } else {
1162            "No matches"
1163        };
1164        Some(text.into())
1165    }
1166
1167    fn render_match(
1168        &self,
1169        ix: usize,
1170        selected: bool,
1171        window: &mut Window,
1172        cx: &mut Context<Picker<Self>>,
1173    ) -> Option<Self::ListItem> {
1174        match self.filtered_entries.get(ix)? {
1175            ProjectPickerEntry::Header(title) => Some(
1176                v_flex()
1177                    .w_full()
1178                    .gap_1()
1179                    .when(ix > 0, |this| this.mt_1().child(Divider::horizontal()))
1180                    .child(ListSubHeader::new(title.clone()).inset(true))
1181                    .into_any_element(),
1182            ),
1183            ProjectPickerEntry::Workspace(hit) => {
1184                let (_, location, paths, _) = self.workspaces.get(hit.candidate_id)?;
1185
1186                let ordered_paths: Vec<_> = paths
1187                    .ordered_paths()
1188                    .map(|p| p.compact().to_string_lossy().to_string())
1189                    .collect();
1190
1191                let tooltip_path: SharedString = ordered_paths.join("\n").into();
1192
1193                let mut path_start_offset = 0;
1194                let match_labels: Vec<_> = paths
1195                    .ordered_paths()
1196                    .map(|p| p.compact())
1197                    .map(|path| {
1198                        let path_string = path.to_string_lossy();
1199                        let path_text = path_string.to_string();
1200                        let path_byte_len = path_text.len();
1201
1202                        let path_positions: Vec<usize> = hit
1203                            .positions
1204                            .iter()
1205                            .copied()
1206                            .skip_while(|pos| *pos < path_start_offset)
1207                            .take_while(|pos| *pos < path_start_offset + path_byte_len)
1208                            .map(|pos| pos - path_start_offset)
1209                            .collect();
1210
1211                        let file_name_match = path.file_name().map(|file_name| {
1212                            let file_name_text = file_name.to_string_lossy().into_owned();
1213                            let file_name_start = path_byte_len - file_name_text.len();
1214                            let highlight_positions: Vec<usize> = path_positions
1215                                .iter()
1216                                .copied()
1217                                .skip_while(|pos| *pos < file_name_start)
1218                                .take_while(|pos| *pos < file_name_start + file_name_text.len())
1219                                .map(|pos| pos - file_name_start)
1220                                .collect();
1221                            HighlightedMatch {
1222                                text: file_name_text,
1223                                highlight_positions,
1224                                color: Color::Default,
1225                            }
1226                        });
1227
1228                        path_start_offset += path_byte_len;
1229                        file_name_match
1230                    })
1231                    .collect();
1232
1233                let highlighted_match = HighlightedMatchWithPaths {
1234                    prefix: match location {
1235                        SerializedWorkspaceLocation::Remote(options) => {
1236                            Some(SharedString::from(options.display_name()))
1237                        }
1238                        _ => None,
1239                    },
1240                    match_label: HighlightedMatch::join(match_labels.into_iter().flatten(), ", "),
1241                    paths: Vec::new(),
1242                    active: false,
1243                };
1244
1245                Some(
1246                    ListItem::new(ix)
1247                        .toggle_state(selected)
1248                        .inset(true)
1249                        .spacing(ListItemSpacing::Sparse)
1250                        .child(
1251                            h_flex()
1252                                .gap_3()
1253                                .flex_grow()
1254                                .child(highlighted_match.render(window, cx)),
1255                        )
1256                        .tooltip(Tooltip::text(tooltip_path))
1257                        .into_any_element(),
1258                )
1259            }
1260        }
1261    }
1262
1263    fn render_footer(&self, _: &mut Window, cx: &mut Context<Picker<Self>>) -> Option<AnyElement> {
1264        let has_selection = self.selected_match().is_some();
1265        let focus_handle = self.focus_handle.clone();
1266
1267        Some(
1268            h_flex()
1269                .flex_1()
1270                .p_1p5()
1271                .gap_1()
1272                .justify_end()
1273                .border_t_1()
1274                .border_color(cx.theme().colors().border_variant)
1275                .child(
1276                    Button::new("open_local_folder", "Choose from Local Folders")
1277                        .key_binding(KeyBinding::for_action_in(
1278                            &workspace::Open::default(),
1279                            &focus_handle,
1280                            cx,
1281                        ))
1282                        .on_click(cx.listener(|this, _, window, cx| {
1283                            this.delegate.open_local_folder(window, cx);
1284                        })),
1285                )
1286                .child(
1287                    Button::new("select_project", "Select")
1288                        .disabled(!has_selection)
1289                        .key_binding(KeyBinding::for_action_in(&menu::Confirm, &focus_handle, cx))
1290                        .on_click(cx.listener(move |picker, _, window, cx| {
1291                            picker.delegate.confirm(false, window, cx);
1292                        })),
1293                )
1294                .into_any(),
1295        )
1296    }
1297}
1298
1299#[cfg(test)]
1300mod tests {
1301    use super::*;
1302
1303    #[test]
1304    fn test_fuzzy_match_positions_returns_byte_indices() {
1305        // "🔥abc" — the fire emoji is 4 bytes, so 'a' starts at byte 4, 'b' at 5, 'c' at 6.
1306        let text = "🔥abc";
1307        let positions = fuzzy_match_positions("ab", text).expect("should match");
1308        assert_eq!(positions, vec![4, 5]);
1309
1310        // Verify positions are valid char boundaries (this is the assertion that
1311        // panicked before the fix).
1312        for &pos in &positions {
1313            assert!(
1314                text.is_char_boundary(pos),
1315                "position {pos} is not a valid UTF-8 boundary in {text:?}"
1316            );
1317        }
1318    }
1319
1320    #[test]
1321    fn test_fuzzy_match_positions_ascii_still_works() {
1322        let positions = fuzzy_match_positions("he", "hello").expect("should match");
1323        assert_eq!(positions, vec![0, 1]);
1324    }
1325
1326    #[test]
1327    fn test_fuzzy_match_positions_case_insensitive() {
1328        let positions = fuzzy_match_positions("HE", "hello").expect("should match");
1329        assert_eq!(positions, vec![0, 1]);
1330    }
1331
1332    #[test]
1333    fn test_fuzzy_match_positions_no_match() {
1334        assert!(fuzzy_match_positions("xyz", "hello").is_none());
1335    }
1336
1337    #[test]
1338    fn test_fuzzy_match_positions_multi_byte_interior() {
1339        // "café" — 'é' is 2 bytes (0xC3 0xA9), so 'f' starts at byte 4, 'é' at byte 5.
1340        let text = "café";
1341        let positions = fuzzy_match_positions("", text).expect("should match");
1342        // 'c'=0, 'a'=1, 'f'=2, 'é'=3..4 — wait, let's verify:
1343        // Actually: c=1 byte, a=1 byte, f=1 byte, é=2 bytes
1344        // So byte positions: c=0, a=1, f=2, é=3
1345        assert_eq!(positions, vec![2, 3]);
1346        for &pos in &positions {
1347            assert!(
1348                text.is_char_boundary(pos),
1349                "position {pos} is not a valid UTF-8 boundary in {text:?}"
1350            );
1351        }
1352    }
1353}