context_picker.rs

   1mod completion_provider;
   2mod fetch_context_picker;
   3mod file_context_picker;
   4mod rules_context_picker;
   5mod symbol_context_picker;
   6mod thread_context_picker;
   7
   8use std::ops::Range;
   9use std::path::{Path, PathBuf};
  10use std::sync::Arc;
  11
  12use anyhow::{Result, anyhow};
  13pub use completion_provider::ContextPickerCompletionProvider;
  14use editor::display_map::{Crease, CreaseId, CreaseMetadata, FoldId};
  15use editor::{Anchor, AnchorRangeExt as _, Editor, ExcerptId, FoldPlaceholder, ToOffset};
  16use fetch_context_picker::FetchContextPicker;
  17use file_context_picker::FileContextPicker;
  18use file_context_picker::render_file_context_entry;
  19use gpui::{
  20    App, DismissEvent, Empty, Entity, EventEmitter, FocusHandle, Focusable, Subscription, Task,
  21    WeakEntity,
  22};
  23use language::Buffer;
  24use multi_buffer::MultiBufferRow;
  25use paths::contexts_dir;
  26use project::{Entry, ProjectPath};
  27use prompt_store::{PromptStore, UserPromptId};
  28use rules_context_picker::{RulesContextEntry, RulesContextPicker};
  29use symbol_context_picker::SymbolContextPicker;
  30use thread_context_picker::{
  31    ThreadContextEntry, ThreadContextPicker, render_thread_context_entry, unordered_thread_entries,
  32};
  33use ui::{
  34    ButtonLike, ContextMenu, ContextMenuEntry, ContextMenuItem, Disclosure, TintColor, prelude::*,
  35};
  36use uuid::Uuid;
  37use workspace::{Workspace, notifications::NotifyResultExt};
  38
  39use crate::AgentPanel;
  40use agent::{
  41    ThreadId,
  42    context::RULES_ICON,
  43    context_store::ContextStore,
  44    thread_store::{TextThreadStore, ThreadStore},
  45};
  46
  47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  48enum ContextPickerEntry {
  49    Mode(ContextPickerMode),
  50    Action(ContextPickerAction),
  51}
  52
  53impl ContextPickerEntry {
  54    pub fn keyword(&self) -> &'static str {
  55        match self {
  56            Self::Mode(mode) => mode.keyword(),
  57            Self::Action(action) => action.keyword(),
  58        }
  59    }
  60
  61    pub fn label(&self) -> &'static str {
  62        match self {
  63            Self::Mode(mode) => mode.label(),
  64            Self::Action(action) => action.label(),
  65        }
  66    }
  67
  68    pub fn icon(&self) -> IconName {
  69        match self {
  70            Self::Mode(mode) => mode.icon(),
  71            Self::Action(action) => action.icon(),
  72        }
  73    }
  74}
  75
  76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  77enum ContextPickerMode {
  78    File,
  79    Symbol,
  80    Fetch,
  81    Thread,
  82    Rules,
  83}
  84
  85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  86enum ContextPickerAction {
  87    AddSelections,
  88}
  89
  90impl ContextPickerAction {
  91    pub fn keyword(&self) -> &'static str {
  92        match self {
  93            Self::AddSelections => "selection",
  94        }
  95    }
  96
  97    pub fn label(&self) -> &'static str {
  98        match self {
  99            Self::AddSelections => "Selection",
 100        }
 101    }
 102
 103    pub fn icon(&self) -> IconName {
 104        match self {
 105            Self::AddSelections => IconName::Context,
 106        }
 107    }
 108}
 109
 110impl TryFrom<&str> for ContextPickerMode {
 111    type Error = String;
 112
 113    fn try_from(value: &str) -> Result<Self, Self::Error> {
 114        match value {
 115            "file" => Ok(Self::File),
 116            "symbol" => Ok(Self::Symbol),
 117            "fetch" => Ok(Self::Fetch),
 118            "thread" => Ok(Self::Thread),
 119            "rule" => Ok(Self::Rules),
 120            _ => Err(format!("Invalid context picker mode: {}", value)),
 121        }
 122    }
 123}
 124
 125impl ContextPickerMode {
 126    pub fn keyword(&self) -> &'static str {
 127        match self {
 128            Self::File => "file",
 129            Self::Symbol => "symbol",
 130            Self::Fetch => "fetch",
 131            Self::Thread => "thread",
 132            Self::Rules => "rule",
 133        }
 134    }
 135
 136    pub fn label(&self) -> &'static str {
 137        match self {
 138            Self::File => "Files & Directories",
 139            Self::Symbol => "Symbols",
 140            Self::Fetch => "Fetch",
 141            Self::Thread => "Threads",
 142            Self::Rules => "Rules",
 143        }
 144    }
 145
 146    pub fn icon(&self) -> IconName {
 147        match self {
 148            Self::File => IconName::File,
 149            Self::Symbol => IconName::Code,
 150            Self::Fetch => IconName::Globe,
 151            Self::Thread => IconName::MessageBubbles,
 152            Self::Rules => RULES_ICON,
 153        }
 154    }
 155}
 156
 157#[derive(Debug, Clone)]
 158enum ContextPickerState {
 159    Default(Entity<ContextMenu>),
 160    File(Entity<FileContextPicker>),
 161    Symbol(Entity<SymbolContextPicker>),
 162    Fetch(Entity<FetchContextPicker>),
 163    Thread(Entity<ThreadContextPicker>),
 164    Rules(Entity<RulesContextPicker>),
 165}
 166
 167pub(super) struct ContextPicker {
 168    mode: ContextPickerState,
 169    workspace: WeakEntity<Workspace>,
 170    context_store: WeakEntity<ContextStore>,
 171    thread_store: Option<WeakEntity<ThreadStore>>,
 172    text_thread_store: Option<WeakEntity<TextThreadStore>>,
 173    prompt_store: Option<Entity<PromptStore>>,
 174    _subscriptions: Vec<Subscription>,
 175}
 176
 177impl ContextPicker {
 178    pub fn new(
 179        workspace: WeakEntity<Workspace>,
 180        thread_store: Option<WeakEntity<ThreadStore>>,
 181        text_thread_store: Option<WeakEntity<TextThreadStore>>,
 182        context_store: WeakEntity<ContextStore>,
 183        window: &mut Window,
 184        cx: &mut Context<Self>,
 185    ) -> Self {
 186        let subscriptions = context_store
 187            .upgrade()
 188            .map(|context_store| {
 189                cx.observe(&context_store, |this, _, cx| this.notify_current_picker(cx))
 190            })
 191            .into_iter()
 192            .chain(
 193                thread_store
 194                    .as_ref()
 195                    .and_then(|thread_store| thread_store.upgrade())
 196                    .map(|thread_store| {
 197                        cx.observe(&thread_store, |this, _, cx| this.notify_current_picker(cx))
 198                    }),
 199            )
 200            .collect::<Vec<Subscription>>();
 201
 202        let prompt_store = thread_store.as_ref().and_then(|thread_store| {
 203            thread_store
 204                .read_with(cx, |thread_store, _cx| thread_store.prompt_store().clone())
 205                .ok()
 206                .flatten()
 207        });
 208
 209        ContextPicker {
 210            mode: ContextPickerState::Default(ContextMenu::build(
 211                window,
 212                cx,
 213                |menu, _window, _cx| menu,
 214            )),
 215            workspace,
 216            context_store,
 217            thread_store,
 218            text_thread_store,
 219            prompt_store,
 220            _subscriptions: subscriptions,
 221        }
 222    }
 223
 224    pub fn init(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 225        self.mode = ContextPickerState::Default(self.build_menu(window, cx));
 226        cx.notify();
 227    }
 228
 229    fn build_menu(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<ContextMenu> {
 230        let context_picker = cx.entity().clone();
 231
 232        let menu = ContextMenu::build(window, cx, move |menu, _window, cx| {
 233            let recent = self.recent_entries(cx);
 234            let has_recent = !recent.is_empty();
 235            let recent_entries = recent
 236                .into_iter()
 237                .enumerate()
 238                .map(|(ix, entry)| self.recent_menu_item(context_picker.clone(), ix, entry));
 239
 240            let entries = self
 241                .workspace
 242                .upgrade()
 243                .map(|workspace| {
 244                    available_context_picker_entries(
 245                        &self.prompt_store,
 246                        &self.thread_store,
 247                        &workspace,
 248                        cx,
 249                    )
 250                })
 251                .unwrap_or_default();
 252
 253            menu.when(has_recent, |menu| {
 254                menu.custom_row(|_, _| {
 255                    div()
 256                        .mb_1()
 257                        .child(
 258                            Label::new("Recent")
 259                                .color(Color::Muted)
 260                                .size(LabelSize::Small),
 261                        )
 262                        .into_any_element()
 263                })
 264            })
 265            .extend(recent_entries)
 266            .when(has_recent, |menu| menu.separator())
 267            .extend(entries.into_iter().map(|entry| {
 268                let context_picker = context_picker.clone();
 269
 270                ContextMenuEntry::new(entry.label())
 271                    .icon(entry.icon())
 272                    .icon_size(IconSize::XSmall)
 273                    .icon_color(Color::Muted)
 274                    .handler(move |window, cx| {
 275                        context_picker.update(cx, |this, cx| this.select_entry(entry, window, cx))
 276                    })
 277            }))
 278            .keep_open_on_confirm(true)
 279        });
 280
 281        cx.subscribe(&menu, move |_, _, _: &DismissEvent, cx| {
 282            cx.emit(DismissEvent);
 283        })
 284        .detach();
 285
 286        menu
 287    }
 288
 289    /// Whether threads are allowed as context.
 290    pub fn allow_threads(&self) -> bool {
 291        self.thread_store.is_some()
 292    }
 293
 294    fn select_entry(
 295        &mut self,
 296        entry: ContextPickerEntry,
 297        window: &mut Window,
 298        cx: &mut Context<Self>,
 299    ) {
 300        let context_picker = cx.entity().downgrade();
 301
 302        match entry {
 303            ContextPickerEntry::Mode(mode) => match mode {
 304                ContextPickerMode::File => {
 305                    self.mode = ContextPickerState::File(cx.new(|cx| {
 306                        FileContextPicker::new(
 307                            context_picker.clone(),
 308                            self.workspace.clone(),
 309                            self.context_store.clone(),
 310                            window,
 311                            cx,
 312                        )
 313                    }));
 314                }
 315                ContextPickerMode::Symbol => {
 316                    self.mode = ContextPickerState::Symbol(cx.new(|cx| {
 317                        SymbolContextPicker::new(
 318                            context_picker.clone(),
 319                            self.workspace.clone(),
 320                            self.context_store.clone(),
 321                            window,
 322                            cx,
 323                        )
 324                    }));
 325                }
 326                ContextPickerMode::Rules => {
 327                    if let Some(prompt_store) = self.prompt_store.as_ref() {
 328                        self.mode = ContextPickerState::Rules(cx.new(|cx| {
 329                            RulesContextPicker::new(
 330                                prompt_store.clone(),
 331                                context_picker.clone(),
 332                                self.context_store.clone(),
 333                                window,
 334                                cx,
 335                            )
 336                        }));
 337                    }
 338                }
 339                ContextPickerMode::Fetch => {
 340                    self.mode = ContextPickerState::Fetch(cx.new(|cx| {
 341                        FetchContextPicker::new(
 342                            context_picker.clone(),
 343                            self.workspace.clone(),
 344                            self.context_store.clone(),
 345                            window,
 346                            cx,
 347                        )
 348                    }));
 349                }
 350                ContextPickerMode::Thread => {
 351                    if let Some((thread_store, text_thread_store)) = self
 352                        .thread_store
 353                        .as_ref()
 354                        .zip(self.text_thread_store.as_ref())
 355                    {
 356                        self.mode = ContextPickerState::Thread(cx.new(|cx| {
 357                            ThreadContextPicker::new(
 358                                thread_store.clone(),
 359                                text_thread_store.clone(),
 360                                context_picker.clone(),
 361                                self.context_store.clone(),
 362                                window,
 363                                cx,
 364                            )
 365                        }));
 366                    }
 367                }
 368            },
 369            ContextPickerEntry::Action(action) => match action {
 370                ContextPickerAction::AddSelections => {
 371                    if let Some((context_store, workspace)) =
 372                        self.context_store.upgrade().zip(self.workspace.upgrade())
 373                    {
 374                        add_selections_as_context(&context_store, &workspace, cx);
 375                    }
 376
 377                    cx.emit(DismissEvent);
 378                }
 379            },
 380        }
 381
 382        cx.notify();
 383        cx.focus_self(window);
 384    }
 385
 386    pub fn select_first(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 387        match &self.mode {
 388            ContextPickerState::Default(entity) => entity.update(cx, |entity, cx| {
 389                entity.select_first(&Default::default(), window, cx)
 390            }),
 391            // Other variants already select their first entry on open automatically
 392            _ => {}
 393        }
 394    }
 395
 396    fn recent_menu_item(
 397        &self,
 398        context_picker: Entity<ContextPicker>,
 399        ix: usize,
 400        entry: RecentEntry,
 401    ) -> ContextMenuItem {
 402        match entry {
 403            RecentEntry::File {
 404                project_path,
 405                path_prefix,
 406            } => {
 407                let context_store = self.context_store.clone();
 408                let worktree_id = project_path.worktree_id;
 409                let path = project_path.path.clone();
 410
 411                ContextMenuItem::custom_entry(
 412                    move |_window, cx| {
 413                        render_file_context_entry(
 414                            ElementId::named_usize("ctx-recent", ix),
 415                            worktree_id,
 416                            &path,
 417                            &path_prefix,
 418                            false,
 419                            context_store.clone(),
 420                            cx,
 421                        )
 422                        .into_any()
 423                    },
 424                    move |window, cx| {
 425                        context_picker.update(cx, |this, cx| {
 426                            this.add_recent_file(project_path.clone(), window, cx);
 427                        })
 428                    },
 429                )
 430            }
 431            RecentEntry::Thread(thread) => {
 432                let context_store = self.context_store.clone();
 433                let view_thread = thread.clone();
 434
 435                ContextMenuItem::custom_entry(
 436                    move |_window, cx| {
 437                        render_thread_context_entry(&view_thread, context_store.clone(), cx)
 438                            .into_any()
 439                    },
 440                    move |window, cx| {
 441                        context_picker.update(cx, |this, cx| {
 442                            this.add_recent_thread(thread.clone(), window, cx)
 443                                .detach_and_log_err(cx);
 444                        })
 445                    },
 446                )
 447            }
 448        }
 449    }
 450
 451    fn add_recent_file(
 452        &self,
 453        project_path: ProjectPath,
 454        window: &mut Window,
 455        cx: &mut Context<Self>,
 456    ) {
 457        let Some(context_store) = self.context_store.upgrade() else {
 458            return;
 459        };
 460
 461        let task = context_store.update(cx, |context_store, cx| {
 462            context_store.add_file_from_path(project_path.clone(), true, cx)
 463        });
 464
 465        cx.spawn_in(window, async move |_, cx| task.await.notify_async_err(cx))
 466            .detach();
 467
 468        cx.notify();
 469    }
 470
 471    fn add_recent_thread(
 472        &self,
 473        entry: ThreadContextEntry,
 474        window: &mut Window,
 475        cx: &mut Context<Self>,
 476    ) -> Task<Result<()>> {
 477        let Some(context_store) = self.context_store.upgrade() else {
 478            return Task::ready(Err(anyhow!("context store not available")));
 479        };
 480
 481        match entry {
 482            ThreadContextEntry::Thread { id, .. } => {
 483                let Some(thread_store) = self
 484                    .thread_store
 485                    .as_ref()
 486                    .and_then(|thread_store| thread_store.upgrade())
 487                else {
 488                    return Task::ready(Err(anyhow!("thread store not available")));
 489                };
 490
 491                let open_thread_task =
 492                    thread_store.update(cx, |this, cx| this.open_thread(&id, window, cx));
 493                cx.spawn(async move |this, cx| {
 494                    let thread = open_thread_task.await?;
 495                    context_store.update(cx, |context_store, cx| {
 496                        context_store.add_thread(thread, true, cx);
 497                    })?;
 498                    this.update(cx, |_this, cx| cx.notify())
 499                })
 500            }
 501            ThreadContextEntry::Context { path, .. } => {
 502                let Some(text_thread_store) = self
 503                    .text_thread_store
 504                    .as_ref()
 505                    .and_then(|thread_store| thread_store.upgrade())
 506                else {
 507                    return Task::ready(Err(anyhow!("text thread store not available")));
 508                };
 509
 510                let task = text_thread_store
 511                    .update(cx, |this, cx| this.open_local_context(path.clone(), cx));
 512                cx.spawn(async move |this, cx| {
 513                    let thread = task.await?;
 514                    context_store.update(cx, |context_store, cx| {
 515                        context_store.add_text_thread(thread, true, cx);
 516                    })?;
 517                    this.update(cx, |_this, cx| cx.notify())
 518                })
 519            }
 520        }
 521    }
 522
 523    fn recent_entries(&self, cx: &mut App) -> Vec<RecentEntry> {
 524        let Some(workspace) = self.workspace.upgrade() else {
 525            return vec![];
 526        };
 527
 528        let Some(context_store) = self.context_store.upgrade() else {
 529            return vec![];
 530        };
 531
 532        recent_context_picker_entries(
 533            context_store,
 534            self.thread_store.clone(),
 535            self.text_thread_store.clone(),
 536            workspace,
 537            None,
 538            cx,
 539        )
 540    }
 541
 542    fn notify_current_picker(&mut self, cx: &mut Context<Self>) {
 543        match &self.mode {
 544            ContextPickerState::Default(entity) => entity.update(cx, |_, cx| cx.notify()),
 545            ContextPickerState::File(entity) => entity.update(cx, |_, cx| cx.notify()),
 546            ContextPickerState::Symbol(entity) => entity.update(cx, |_, cx| cx.notify()),
 547            ContextPickerState::Fetch(entity) => entity.update(cx, |_, cx| cx.notify()),
 548            ContextPickerState::Thread(entity) => entity.update(cx, |_, cx| cx.notify()),
 549            ContextPickerState::Rules(entity) => entity.update(cx, |_, cx| cx.notify()),
 550        }
 551    }
 552}
 553
 554impl EventEmitter<DismissEvent> for ContextPicker {}
 555
 556impl Focusable for ContextPicker {
 557    fn focus_handle(&self, cx: &App) -> FocusHandle {
 558        match &self.mode {
 559            ContextPickerState::Default(menu) => menu.focus_handle(cx),
 560            ContextPickerState::File(file_picker) => file_picker.focus_handle(cx),
 561            ContextPickerState::Symbol(symbol_picker) => symbol_picker.focus_handle(cx),
 562            ContextPickerState::Fetch(fetch_picker) => fetch_picker.focus_handle(cx),
 563            ContextPickerState::Thread(thread_picker) => thread_picker.focus_handle(cx),
 564            ContextPickerState::Rules(user_rules_picker) => user_rules_picker.focus_handle(cx),
 565        }
 566    }
 567}
 568
 569impl Render for ContextPicker {
 570    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 571        v_flex()
 572            .w(px(400.))
 573            .min_w(px(400.))
 574            .map(|parent| match &self.mode {
 575                ContextPickerState::Default(menu) => parent.child(menu.clone()),
 576                ContextPickerState::File(file_picker) => parent.child(file_picker.clone()),
 577                ContextPickerState::Symbol(symbol_picker) => parent.child(symbol_picker.clone()),
 578                ContextPickerState::Fetch(fetch_picker) => parent.child(fetch_picker.clone()),
 579                ContextPickerState::Thread(thread_picker) => parent.child(thread_picker.clone()),
 580                ContextPickerState::Rules(user_rules_picker) => {
 581                    parent.child(user_rules_picker.clone())
 582                }
 583            })
 584    }
 585}
 586enum RecentEntry {
 587    File {
 588        project_path: ProjectPath,
 589        path_prefix: Arc<str>,
 590    },
 591    Thread(ThreadContextEntry),
 592}
 593
 594fn available_context_picker_entries(
 595    prompt_store: &Option<Entity<PromptStore>>,
 596    thread_store: &Option<WeakEntity<ThreadStore>>,
 597    workspace: &Entity<Workspace>,
 598    cx: &mut App,
 599) -> Vec<ContextPickerEntry> {
 600    let mut entries = vec![
 601        ContextPickerEntry::Mode(ContextPickerMode::File),
 602        ContextPickerEntry::Mode(ContextPickerMode::Symbol),
 603    ];
 604
 605    let has_selection = workspace
 606        .read(cx)
 607        .active_item(cx)
 608        .and_then(|item| item.downcast::<Editor>())
 609        .map_or(false, |editor| {
 610            editor.update(cx, |editor, cx| editor.has_non_empty_selection(cx))
 611        });
 612    if has_selection {
 613        entries.push(ContextPickerEntry::Action(
 614            ContextPickerAction::AddSelections,
 615        ));
 616    }
 617
 618    if thread_store.is_some() {
 619        entries.push(ContextPickerEntry::Mode(ContextPickerMode::Thread));
 620    }
 621
 622    if prompt_store.is_some() {
 623        entries.push(ContextPickerEntry::Mode(ContextPickerMode::Rules));
 624    }
 625
 626    entries.push(ContextPickerEntry::Mode(ContextPickerMode::Fetch));
 627
 628    entries
 629}
 630
 631fn recent_context_picker_entries(
 632    context_store: Entity<ContextStore>,
 633    thread_store: Option<WeakEntity<ThreadStore>>,
 634    text_thread_store: Option<WeakEntity<TextThreadStore>>,
 635    workspace: Entity<Workspace>,
 636    exclude_path: Option<ProjectPath>,
 637    cx: &App,
 638) -> Vec<RecentEntry> {
 639    let mut recent = Vec::with_capacity(6);
 640    let mut current_files = context_store.read(cx).file_paths(cx);
 641    current_files.extend(exclude_path);
 642    let workspace = workspace.read(cx);
 643    let project = workspace.project().read(cx);
 644
 645    recent.extend(
 646        workspace
 647            .recent_navigation_history_iter(cx)
 648            .filter(|(path, _)| !current_files.contains(path))
 649            .take(4)
 650            .filter_map(|(project_path, _)| {
 651                project
 652                    .worktree_for_id(project_path.worktree_id, cx)
 653                    .map(|worktree| RecentEntry::File {
 654                        project_path,
 655                        path_prefix: worktree.read(cx).root_name().into(),
 656                    })
 657            }),
 658    );
 659
 660    let current_threads = context_store.read(cx).thread_ids();
 661
 662    let active_thread_id = workspace
 663        .panel::<AgentPanel>(cx)
 664        .and_then(|panel| Some(panel.read(cx).active_thread(cx)?.read(cx).id()));
 665
 666    if let Some((thread_store, text_thread_store)) = thread_store
 667        .and_then(|store| store.upgrade())
 668        .zip(text_thread_store.and_then(|store| store.upgrade()))
 669    {
 670        let mut threads = unordered_thread_entries(thread_store, text_thread_store, cx)
 671            .filter(|(_, thread)| match thread {
 672                ThreadContextEntry::Thread { id, .. } => {
 673                    Some(id) != active_thread_id && !current_threads.contains(id)
 674                }
 675                ThreadContextEntry::Context { .. } => true,
 676            })
 677            .collect::<Vec<_>>();
 678
 679        const RECENT_COUNT: usize = 2;
 680        if threads.len() > RECENT_COUNT {
 681            threads.select_nth_unstable_by_key(RECENT_COUNT - 1, |(updated_at, _)| {
 682                std::cmp::Reverse(*updated_at)
 683            });
 684            threads.truncate(RECENT_COUNT);
 685        }
 686        threads.sort_unstable_by_key(|(updated_at, _)| std::cmp::Reverse(*updated_at));
 687
 688        recent.extend(
 689            threads
 690                .into_iter()
 691                .map(|(_, thread)| RecentEntry::Thread(thread)),
 692        );
 693    }
 694
 695    recent
 696}
 697
 698fn add_selections_as_context(
 699    context_store: &Entity<ContextStore>,
 700    workspace: &Entity<Workspace>,
 701    cx: &mut App,
 702) {
 703    let selection_ranges = selection_ranges(workspace, cx);
 704    context_store.update(cx, |context_store, cx| {
 705        for (buffer, range) in selection_ranges {
 706            context_store.add_selection(buffer, range, cx);
 707        }
 708    })
 709}
 710
 711fn selection_ranges(
 712    workspace: &Entity<Workspace>,
 713    cx: &mut App,
 714) -> Vec<(Entity<Buffer>, Range<text::Anchor>)> {
 715    let Some(editor) = workspace
 716        .read(cx)
 717        .active_item(cx)
 718        .and_then(|item| item.act_as::<Editor>(cx))
 719    else {
 720        return Vec::new();
 721    };
 722
 723    editor.update(cx, |editor, cx| {
 724        let selections = editor.selections.all_adjusted(cx);
 725
 726        let buffer = editor.buffer().clone().read(cx);
 727        let snapshot = buffer.snapshot(cx);
 728
 729        selections
 730            .into_iter()
 731            .map(|s| snapshot.anchor_after(s.start)..snapshot.anchor_before(s.end))
 732            .flat_map(|range| {
 733                let (start_buffer, start) = buffer.text_anchor_for_position(range.start, cx)?;
 734                let (end_buffer, end) = buffer.text_anchor_for_position(range.end, cx)?;
 735                if start_buffer != end_buffer {
 736                    return None;
 737                }
 738                Some((start_buffer, start..end))
 739            })
 740            .collect::<Vec<_>>()
 741    })
 742}
 743
 744pub(crate) fn insert_crease_for_mention(
 745    excerpt_id: ExcerptId,
 746    crease_start: text::Anchor,
 747    content_len: usize,
 748    crease_label: SharedString,
 749    crease_icon_path: SharedString,
 750    editor_entity: Entity<Editor>,
 751    window: &mut Window,
 752    cx: &mut App,
 753) -> Option<CreaseId> {
 754    editor_entity.update(cx, |editor, cx| {
 755        let snapshot = editor.buffer().read(cx).snapshot(cx);
 756
 757        let start = snapshot.anchor_in_excerpt(excerpt_id, crease_start)?;
 758
 759        let start = start.bias_right(&snapshot);
 760        let end = snapshot.anchor_before(start.to_offset(&snapshot) + content_len);
 761
 762        let crease = crease_for_mention(
 763            crease_label,
 764            crease_icon_path,
 765            start..end,
 766            editor_entity.downgrade(),
 767        );
 768
 769        let ids = editor.insert_creases(vec![crease.clone()], cx);
 770        editor.fold_creases(vec![crease], false, window, cx);
 771
 772        Some(ids[0])
 773    })
 774}
 775
 776pub fn crease_for_mention(
 777    label: SharedString,
 778    icon_path: SharedString,
 779    range: Range<Anchor>,
 780    editor_entity: WeakEntity<Editor>,
 781) -> Crease<Anchor> {
 782    let placeholder = FoldPlaceholder {
 783        render: render_fold_icon_button(icon_path.clone(), label.clone(), editor_entity),
 784        merge_adjacent: false,
 785        ..Default::default()
 786    };
 787
 788    let render_trailer = move |_row, _unfold, _window: &mut Window, _cx: &mut App| Empty.into_any();
 789
 790    Crease::inline(
 791        range,
 792        placeholder.clone(),
 793        fold_toggle("mention"),
 794        render_trailer,
 795    )
 796    .with_metadata(CreaseMetadata { icon_path, label })
 797}
 798
 799fn render_fold_icon_button(
 800    icon_path: SharedString,
 801    label: SharedString,
 802    editor: WeakEntity<Editor>,
 803) -> Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut App) -> AnyElement> {
 804    Arc::new({
 805        move |fold_id, fold_range, cx| {
 806            let is_in_text_selection = editor.upgrade().is_some_and(|editor| {
 807                editor.update(cx, |editor, cx| {
 808                    let snapshot = editor
 809                        .buffer()
 810                        .update(cx, |multi_buffer, cx| multi_buffer.snapshot(cx));
 811
 812                    let is_in_pending_selection = || {
 813                        editor
 814                            .selections
 815                            .pending
 816                            .as_ref()
 817                            .is_some_and(|pending_selection| {
 818                                pending_selection
 819                                    .selection
 820                                    .range()
 821                                    .includes(&fold_range, &snapshot)
 822                            })
 823                    };
 824
 825                    let mut is_in_complete_selection = || {
 826                        editor
 827                            .selections
 828                            .disjoint_in_range::<usize>(fold_range.clone(), cx)
 829                            .into_iter()
 830                            .any(|selection| {
 831                                // This is needed to cover a corner case, if we just check for an existing
 832                                // selection in the fold range, having a cursor at the start of the fold
 833                                // marks it as selected. Non-empty selections don't cause this.
 834                                let length = selection.end - selection.start;
 835                                length > 0
 836                            })
 837                    };
 838
 839                    is_in_pending_selection() || is_in_complete_selection()
 840                })
 841            });
 842
 843            ButtonLike::new(fold_id)
 844                .style(ButtonStyle::Filled)
 845                .selected_style(ButtonStyle::Tinted(TintColor::Accent))
 846                .toggle_state(is_in_text_selection)
 847                .child(
 848                    h_flex()
 849                        .gap_1()
 850                        .child(
 851                            Icon::from_path(icon_path.clone())
 852                                .size(IconSize::XSmall)
 853                                .color(Color::Muted),
 854                        )
 855                        .child(
 856                            Label::new(label.clone())
 857                                .size(LabelSize::Small)
 858                                .buffer_font(cx)
 859                                .single_line(),
 860                        ),
 861                )
 862                .into_any_element()
 863        }
 864    })
 865}
 866
 867fn fold_toggle(
 868    name: &'static str,
 869) -> impl Fn(
 870    MultiBufferRow,
 871    bool,
 872    Arc<dyn Fn(bool, &mut Window, &mut App) + Send + Sync>,
 873    &mut Window,
 874    &mut App,
 875) -> AnyElement {
 876    move |row, is_folded, fold, _window, _cx| {
 877        Disclosure::new((name, row.0 as u64), !is_folded)
 878            .toggle_state(is_folded)
 879            .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
 880            .into_any_element()
 881    }
 882}
 883
 884pub enum MentionLink {
 885    File(ProjectPath, Entry),
 886    Symbol(ProjectPath, String),
 887    Selection(ProjectPath, Range<usize>),
 888    Fetch(String),
 889    Thread(ThreadId),
 890    TextThread(Arc<Path>),
 891    Rule(UserPromptId),
 892}
 893
 894impl MentionLink {
 895    const FILE: &str = "@file";
 896    const SYMBOL: &str = "@symbol";
 897    const SELECTION: &str = "@selection";
 898    const THREAD: &str = "@thread";
 899    const FETCH: &str = "@fetch";
 900    const RULE: &str = "@rule";
 901
 902    const TEXT_THREAD_URL_PREFIX: &str = "text-thread://";
 903
 904    const SEPARATOR: &str = ":";
 905
 906    pub fn is_valid(url: &str) -> bool {
 907        url.starts_with(Self::FILE)
 908            || url.starts_with(Self::SYMBOL)
 909            || url.starts_with(Self::FETCH)
 910            || url.starts_with(Self::SELECTION)
 911            || url.starts_with(Self::THREAD)
 912            || url.starts_with(Self::RULE)
 913    }
 914
 915    pub fn for_file(file_name: &str, full_path: &str) -> String {
 916        format!("[@{}]({}:{})", file_name, Self::FILE, full_path)
 917    }
 918
 919    pub fn for_symbol(symbol_name: &str, full_path: &str) -> String {
 920        format!(
 921            "[@{}]({}:{}:{})",
 922            symbol_name,
 923            Self::SYMBOL,
 924            full_path,
 925            symbol_name
 926        )
 927    }
 928
 929    pub fn for_selection(file_name: &str, full_path: &str, line_range: Range<usize>) -> String {
 930        format!(
 931            "[@{} ({}-{})]({}:{}:{}-{})",
 932            file_name,
 933            line_range.start + 1,
 934            line_range.end + 1,
 935            Self::SELECTION,
 936            full_path,
 937            line_range.start,
 938            line_range.end
 939        )
 940    }
 941
 942    pub fn for_thread(thread: &ThreadContextEntry) -> String {
 943        match thread {
 944            ThreadContextEntry::Thread { id, title } => {
 945                format!("[@{}]({}:{})", title, Self::THREAD, id)
 946            }
 947            ThreadContextEntry::Context { path, title } => {
 948                let filename = path.file_name().unwrap_or_default().to_string_lossy();
 949                let escaped_filename = urlencoding::encode(&filename);
 950                format!(
 951                    "[@{}]({}:{}{})",
 952                    title,
 953                    Self::THREAD,
 954                    Self::TEXT_THREAD_URL_PREFIX,
 955                    escaped_filename
 956                )
 957            }
 958        }
 959    }
 960
 961    pub fn for_fetch(url: &str) -> String {
 962        format!("[@{}]({}:{})", url, Self::FETCH, url)
 963    }
 964
 965    pub fn for_rule(rule: &RulesContextEntry) -> String {
 966        format!("[@{}]({}:{})", rule.title, Self::RULE, rule.prompt_id.0)
 967    }
 968
 969    pub fn try_parse(link: &str, workspace: &Entity<Workspace>, cx: &App) -> Option<Self> {
 970        fn extract_project_path_from_link(
 971            path: &str,
 972            workspace: &Entity<Workspace>,
 973            cx: &App,
 974        ) -> Option<ProjectPath> {
 975            let path = PathBuf::from(path);
 976            let worktree_name = path.iter().next()?;
 977            let path: PathBuf = path.iter().skip(1).collect();
 978            let worktree_id = workspace
 979                .read(cx)
 980                .visible_worktrees(cx)
 981                .find(|worktree| worktree.read(cx).root_name() == worktree_name)
 982                .map(|worktree| worktree.read(cx).id())?;
 983            Some(ProjectPath {
 984                worktree_id,
 985                path: path.into(),
 986            })
 987        }
 988
 989        let (prefix, argument) = link.split_once(Self::SEPARATOR)?;
 990        match prefix {
 991            Self::FILE => {
 992                let project_path = extract_project_path_from_link(argument, workspace, cx)?;
 993                let entry = workspace
 994                    .read(cx)
 995                    .project()
 996                    .read(cx)
 997                    .entry_for_path(&project_path, cx)?;
 998                Some(MentionLink::File(project_path, entry))
 999            }
1000            Self::SYMBOL => {
1001                let (path, symbol) = argument.split_once(Self::SEPARATOR)?;
1002                let project_path = extract_project_path_from_link(path, workspace, cx)?;
1003                Some(MentionLink::Symbol(project_path, symbol.to_string()))
1004            }
1005            Self::SELECTION => {
1006                let (path, line_args) = argument.split_once(Self::SEPARATOR)?;
1007                let project_path = extract_project_path_from_link(path, workspace, cx)?;
1008
1009                let line_range = {
1010                    let (start, end) = line_args
1011                        .trim_start_matches('(')
1012                        .trim_end_matches(')')
1013                        .split_once('-')?;
1014                    start.parse::<usize>().ok()?..end.parse::<usize>().ok()?
1015                };
1016
1017                Some(MentionLink::Selection(project_path, line_range))
1018            }
1019            Self::THREAD => {
1020                if let Some(encoded_filename) = argument.strip_prefix(Self::TEXT_THREAD_URL_PREFIX)
1021                {
1022                    let filename = urlencoding::decode(encoded_filename).ok()?;
1023                    let path = contexts_dir().join(filename.as_ref()).into();
1024                    Some(MentionLink::TextThread(path))
1025                } else {
1026                    let thread_id = ThreadId::from(argument);
1027                    Some(MentionLink::Thread(thread_id))
1028                }
1029            }
1030            Self::FETCH => Some(MentionLink::Fetch(argument.to_string())),
1031            Self::RULE => {
1032                let prompt_id = UserPromptId(Uuid::try_parse(argument).ok()?);
1033                Some(MentionLink::Rule(prompt_id))
1034            }
1035            _ => None,
1036        }
1037    }
1038}