completion_provider.rs

   1use std::cmp::Reverse;
   2use std::ops::Range;
   3use std::path::PathBuf;
   4use std::sync::Arc;
   5use std::sync::atomic::AtomicBool;
   6
   7use crate::acp::AcpThreadHistory;
   8use acp_thread::{AgentSessionInfo, MentionUri};
   9use anyhow::Result;
  10use editor::{
  11    CompletionProvider, Editor, ExcerptId, code_context_menus::COMPLETION_MENU_MAX_WIDTH,
  12};
  13use fuzzy::{PathMatch, StringMatch, StringMatchCandidate};
  14use gpui::{App, BackgroundExecutor, Entity, SharedString, Task, WeakEntity};
  15use language::{Buffer, CodeLabel, CodeLabelBuilder, HighlightId};
  16use lsp::CompletionContext;
  17use ordered_float::OrderedFloat;
  18use project::lsp_store::{CompletionDocumentation, SymbolLocation};
  19use project::{
  20    Completion, CompletionDisplayOptions, CompletionIntent, CompletionResponse,
  21    PathMatchCandidateSet, Project, ProjectPath, Symbol, WorktreeId,
  22};
  23use prompt_store::{PromptStore, UserPromptId};
  24use rope::Point;
  25use text::{Anchor, ToPoint as _};
  26use ui::prelude::*;
  27use util::ResultExt as _;
  28use util::paths::PathStyle;
  29use util::rel_path::RelPath;
  30use util::truncate_and_remove_front;
  31use workspace::Workspace;
  32
  33use crate::AgentPanel;
  34use crate::mention_set::MentionSet;
  35
  36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  37pub(crate) enum PromptContextEntry {
  38    Mode(PromptContextType),
  39    Action(PromptContextAction),
  40}
  41
  42impl PromptContextEntry {
  43    pub fn keyword(&self) -> &'static str {
  44        match self {
  45            Self::Mode(mode) => mode.keyword(),
  46            Self::Action(action) => action.keyword(),
  47        }
  48    }
  49}
  50
  51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  52pub(crate) enum PromptContextType {
  53    File,
  54    Symbol,
  55    Fetch,
  56    Thread,
  57    Rules,
  58}
  59
  60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  61pub(crate) enum PromptContextAction {
  62    AddSelections,
  63}
  64
  65impl PromptContextAction {
  66    pub fn keyword(&self) -> &'static str {
  67        match self {
  68            Self::AddSelections => "selection",
  69        }
  70    }
  71
  72    pub fn label(&self) -> &'static str {
  73        match self {
  74            Self::AddSelections => "Selection",
  75        }
  76    }
  77
  78    pub fn icon(&self) -> IconName {
  79        match self {
  80            Self::AddSelections => IconName::Reader,
  81        }
  82    }
  83}
  84
  85impl TryFrom<&str> for PromptContextType {
  86    type Error = String;
  87
  88    fn try_from(value: &str) -> Result<Self, Self::Error> {
  89        match value {
  90            "file" => Ok(Self::File),
  91            "symbol" => Ok(Self::Symbol),
  92            "fetch" => Ok(Self::Fetch),
  93            "thread" => Ok(Self::Thread),
  94            "rule" => Ok(Self::Rules),
  95            _ => Err(format!("Invalid context picker mode: {}", value)),
  96        }
  97    }
  98}
  99
 100impl PromptContextType {
 101    pub fn keyword(&self) -> &'static str {
 102        match self {
 103            Self::File => "file",
 104            Self::Symbol => "symbol",
 105            Self::Fetch => "fetch",
 106            Self::Thread => "thread",
 107            Self::Rules => "rule",
 108        }
 109    }
 110
 111    pub fn label(&self) -> &'static str {
 112        match self {
 113            Self::File => "Files & Directories",
 114            Self::Symbol => "Symbols",
 115            Self::Fetch => "Fetch",
 116            Self::Thread => "Threads",
 117            Self::Rules => "Rules",
 118        }
 119    }
 120
 121    pub fn icon(&self) -> IconName {
 122        match self {
 123            Self::File => IconName::File,
 124            Self::Symbol => IconName::Code,
 125            Self::Fetch => IconName::ToolWeb,
 126            Self::Thread => IconName::Thread,
 127            Self::Rules => IconName::Reader,
 128        }
 129    }
 130}
 131
 132pub(crate) enum Match {
 133    File(FileMatch),
 134    Symbol(SymbolMatch),
 135    Thread(AgentSessionInfo),
 136    RecentThread(AgentSessionInfo),
 137    Fetch(SharedString),
 138    Rules(RulesContextEntry),
 139    Entry(EntryMatch),
 140}
 141
 142impl Match {
 143    pub fn score(&self) -> f64 {
 144        match self {
 145            Match::File(file) => file.mat.score,
 146            Match::Entry(mode) => mode.mat.as_ref().map(|mat| mat.score).unwrap_or(1.),
 147            Match::Thread(_) => 1.,
 148            Match::RecentThread(_) => 1.,
 149            Match::Symbol(_) => 1.,
 150            Match::Rules(_) => 1.,
 151            Match::Fetch(_) => 1.,
 152        }
 153    }
 154}
 155
 156pub struct EntryMatch {
 157    mat: Option<StringMatch>,
 158    entry: PromptContextEntry,
 159}
 160
 161fn session_title(session: &AgentSessionInfo) -> SharedString {
 162    session
 163        .title
 164        .clone()
 165        .filter(|title| !title.is_empty())
 166        .unwrap_or_else(|| SharedString::new_static("New Thread"))
 167}
 168
 169#[derive(Debug, Clone)]
 170pub struct RulesContextEntry {
 171    pub prompt_id: UserPromptId,
 172    pub title: SharedString,
 173}
 174
 175#[derive(Debug, Clone)]
 176pub struct AvailableCommand {
 177    pub name: Arc<str>,
 178    pub description: Arc<str>,
 179    pub requires_argument: bool,
 180}
 181
 182pub trait PromptCompletionProviderDelegate: Send + Sync + 'static {
 183    fn supports_context(&self, mode: PromptContextType, cx: &App) -> bool {
 184        self.supported_modes(cx).contains(&mode)
 185    }
 186    fn supported_modes(&self, cx: &App) -> Vec<PromptContextType>;
 187    fn supports_images(&self, cx: &App) -> bool;
 188
 189    fn available_commands(&self, cx: &App) -> Vec<AvailableCommand>;
 190    fn confirm_command(&self, cx: &mut App);
 191}
 192
 193pub struct PromptCompletionProvider<T: PromptCompletionProviderDelegate> {
 194    source: Arc<T>,
 195    editor: WeakEntity<Editor>,
 196    mention_set: Entity<MentionSet>,
 197    history: WeakEntity<AcpThreadHistory>,
 198    prompt_store: Option<Entity<PromptStore>>,
 199    workspace: WeakEntity<Workspace>,
 200}
 201
 202impl<T: PromptCompletionProviderDelegate> PromptCompletionProvider<T> {
 203    pub fn new(
 204        source: T,
 205        editor: WeakEntity<Editor>,
 206        mention_set: Entity<MentionSet>,
 207        history: WeakEntity<AcpThreadHistory>,
 208        prompt_store: Option<Entity<PromptStore>>,
 209        workspace: WeakEntity<Workspace>,
 210    ) -> Self {
 211        Self {
 212            source: Arc::new(source),
 213            editor,
 214            mention_set,
 215            workspace,
 216            history,
 217            prompt_store,
 218        }
 219    }
 220
 221    fn completion_for_entry(
 222        entry: PromptContextEntry,
 223        source_range: Range<Anchor>,
 224        editor: WeakEntity<Editor>,
 225        mention_set: WeakEntity<MentionSet>,
 226        workspace: &Entity<Workspace>,
 227        cx: &mut App,
 228    ) -> Option<Completion> {
 229        match entry {
 230            PromptContextEntry::Mode(mode) => Some(Completion {
 231                replace_range: source_range,
 232                new_text: format!("@{} ", mode.keyword()),
 233                label: CodeLabel::plain(mode.label().to_string(), None),
 234                icon_path: Some(mode.icon().path().into()),
 235                documentation: None,
 236                source: project::CompletionSource::Custom,
 237                match_start: None,
 238                snippet_deduplication_key: None,
 239                insert_text_mode: None,
 240                // This ensures that when a user accepts this completion, the
 241                // completion menu will still be shown after "@category " is
 242                // inserted
 243                confirm: Some(Arc::new(|_, _, _| true)),
 244            }),
 245            PromptContextEntry::Action(action) => Self::completion_for_action(
 246                action,
 247                source_range,
 248                editor,
 249                mention_set,
 250                workspace,
 251                cx,
 252            ),
 253        }
 254    }
 255
 256    fn completion_for_thread(
 257        thread_entry: AgentSessionInfo,
 258        source_range: Range<Anchor>,
 259        recent: bool,
 260        source: Arc<T>,
 261        editor: WeakEntity<Editor>,
 262        mention_set: WeakEntity<MentionSet>,
 263        workspace: Entity<Workspace>,
 264        cx: &mut App,
 265    ) -> Completion {
 266        let title = session_title(&thread_entry);
 267        let uri = MentionUri::Thread {
 268            id: thread_entry.session_id,
 269            name: title.to_string(),
 270        };
 271
 272        let icon_for_completion = if recent {
 273            IconName::HistoryRerun.path().into()
 274        } else {
 275            uri.icon_path(cx)
 276        };
 277
 278        let new_text = format!("{} ", uri.as_link());
 279
 280        let new_text_len = new_text.len();
 281        Completion {
 282            replace_range: source_range.clone(),
 283            new_text,
 284            label: CodeLabel::plain(title.to_string(), None),
 285            documentation: None,
 286            insert_text_mode: None,
 287            source: project::CompletionSource::Custom,
 288            match_start: None,
 289            snippet_deduplication_key: None,
 290            icon_path: Some(icon_for_completion),
 291            confirm: Some(confirm_completion_callback(
 292                title,
 293                source_range.start,
 294                new_text_len - 1,
 295                uri,
 296                source,
 297                editor,
 298                mention_set,
 299                workspace,
 300            )),
 301        }
 302    }
 303
 304    fn completion_for_rules(
 305        rule: RulesContextEntry,
 306        source_range: Range<Anchor>,
 307        source: Arc<T>,
 308        editor: WeakEntity<Editor>,
 309        mention_set: WeakEntity<MentionSet>,
 310        workspace: Entity<Workspace>,
 311        cx: &mut App,
 312    ) -> Completion {
 313        let uri = MentionUri::Rule {
 314            id: rule.prompt_id.into(),
 315            name: rule.title.to_string(),
 316        };
 317        let new_text = format!("{} ", uri.as_link());
 318        let new_text_len = new_text.len();
 319        let icon_path = uri.icon_path(cx);
 320        Completion {
 321            replace_range: source_range.clone(),
 322            new_text,
 323            label: CodeLabel::plain(rule.title.to_string(), None),
 324            documentation: None,
 325            insert_text_mode: None,
 326            source: project::CompletionSource::Custom,
 327            match_start: None,
 328            snippet_deduplication_key: None,
 329            icon_path: Some(icon_path),
 330            confirm: Some(confirm_completion_callback(
 331                rule.title,
 332                source_range.start,
 333                new_text_len - 1,
 334                uri,
 335                source,
 336                editor,
 337                mention_set,
 338                workspace,
 339            )),
 340        }
 341    }
 342
 343    pub(crate) fn completion_for_path(
 344        project_path: ProjectPath,
 345        path_prefix: &RelPath,
 346        is_recent: bool,
 347        is_directory: bool,
 348        source_range: Range<Anchor>,
 349        source: Arc<T>,
 350        editor: WeakEntity<Editor>,
 351        mention_set: WeakEntity<MentionSet>,
 352        workspace: Entity<Workspace>,
 353        project: Entity<Project>,
 354        label_max_chars: usize,
 355        cx: &mut App,
 356    ) -> Option<Completion> {
 357        let path_style = project.read(cx).path_style(cx);
 358        let (file_name, directory) =
 359            extract_file_name_and_directory(&project_path.path, path_prefix, path_style);
 360
 361        let label = build_code_label_for_path(
 362            &file_name,
 363            directory.as_ref().map(|s| s.as_ref()),
 364            None,
 365            label_max_chars,
 366            cx,
 367        );
 368
 369        let abs_path = project.read(cx).absolute_path(&project_path, cx)?;
 370
 371        let uri = if is_directory {
 372            MentionUri::Directory { abs_path }
 373        } else {
 374            MentionUri::File { abs_path }
 375        };
 376
 377        let crease_icon_path = uri.icon_path(cx);
 378        let completion_icon_path = if is_recent {
 379            IconName::HistoryRerun.path().into()
 380        } else {
 381            crease_icon_path
 382        };
 383
 384        let new_text = format!("{} ", uri.as_link());
 385        let new_text_len = new_text.len();
 386        Some(Completion {
 387            replace_range: source_range.clone(),
 388            new_text,
 389            label,
 390            documentation: None,
 391            source: project::CompletionSource::Custom,
 392            icon_path: Some(completion_icon_path),
 393            match_start: None,
 394            snippet_deduplication_key: None,
 395            insert_text_mode: None,
 396            confirm: Some(confirm_completion_callback(
 397                file_name,
 398                source_range.start,
 399                new_text_len - 1,
 400                uri,
 401                source,
 402                editor,
 403                mention_set,
 404                workspace,
 405            )),
 406        })
 407    }
 408
 409    fn completion_for_symbol(
 410        symbol: Symbol,
 411        source_range: Range<Anchor>,
 412        source: Arc<T>,
 413        editor: WeakEntity<Editor>,
 414        mention_set: WeakEntity<MentionSet>,
 415        workspace: Entity<Workspace>,
 416        label_max_chars: usize,
 417        cx: &mut App,
 418    ) -> Option<Completion> {
 419        let project = workspace.read(cx).project().clone();
 420
 421        let (abs_path, file_name) = match &symbol.path {
 422            SymbolLocation::InProject(project_path) => (
 423                project.read(cx).absolute_path(&project_path, cx)?,
 424                project_path.path.file_name()?.to_string().into(),
 425            ),
 426            SymbolLocation::OutsideProject {
 427                abs_path,
 428                signature: _,
 429            } => (
 430                PathBuf::from(abs_path.as_ref()),
 431                abs_path.file_name().map(|f| f.to_string_lossy())?,
 432            ),
 433        };
 434
 435        let label = build_code_label_for_path(
 436            &symbol.name,
 437            Some(&file_name),
 438            Some(symbol.range.start.0.row + 1),
 439            label_max_chars,
 440            cx,
 441        );
 442
 443        let uri = MentionUri::Symbol {
 444            abs_path,
 445            name: symbol.name.clone(),
 446            line_range: symbol.range.start.0.row..=symbol.range.end.0.row,
 447        };
 448        let new_text = format!("{} ", uri.as_link());
 449        let new_text_len = new_text.len();
 450        let icon_path = uri.icon_path(cx);
 451        Some(Completion {
 452            replace_range: source_range.clone(),
 453            new_text,
 454            label,
 455            documentation: None,
 456            source: project::CompletionSource::Custom,
 457            icon_path: Some(icon_path),
 458            match_start: None,
 459            snippet_deduplication_key: None,
 460            insert_text_mode: None,
 461            confirm: Some(confirm_completion_callback(
 462                symbol.name.into(),
 463                source_range.start,
 464                new_text_len - 1,
 465                uri,
 466                source,
 467                editor,
 468                mention_set,
 469                workspace,
 470            )),
 471        })
 472    }
 473
 474    fn completion_for_fetch(
 475        source_range: Range<Anchor>,
 476        url_to_fetch: SharedString,
 477        source: Arc<T>,
 478        editor: WeakEntity<Editor>,
 479        mention_set: WeakEntity<MentionSet>,
 480        workspace: Entity<Workspace>,
 481        cx: &mut App,
 482    ) -> Option<Completion> {
 483        let new_text = format!("@fetch {} ", url_to_fetch);
 484        let url_to_fetch = url::Url::parse(url_to_fetch.as_ref())
 485            .or_else(|_| url::Url::parse(&format!("https://{url_to_fetch}")))
 486            .ok()?;
 487        let mention_uri = MentionUri::Fetch {
 488            url: url_to_fetch.clone(),
 489        };
 490        let icon_path = mention_uri.icon_path(cx);
 491        Some(Completion {
 492            replace_range: source_range.clone(),
 493            new_text: new_text.clone(),
 494            label: CodeLabel::plain(url_to_fetch.to_string(), None),
 495            documentation: None,
 496            source: project::CompletionSource::Custom,
 497            icon_path: Some(icon_path),
 498            match_start: None,
 499            snippet_deduplication_key: None,
 500            insert_text_mode: None,
 501            confirm: Some(confirm_completion_callback(
 502                url_to_fetch.to_string().into(),
 503                source_range.start,
 504                new_text.len() - 1,
 505                mention_uri,
 506                source,
 507                editor,
 508                mention_set,
 509                workspace,
 510            )),
 511        })
 512    }
 513
 514    pub(crate) fn completion_for_action(
 515        action: PromptContextAction,
 516        source_range: Range<Anchor>,
 517        editor: WeakEntity<Editor>,
 518        mention_set: WeakEntity<MentionSet>,
 519        workspace: &Entity<Workspace>,
 520        cx: &mut App,
 521    ) -> Option<Completion> {
 522        let (new_text, on_action) = match action {
 523            PromptContextAction::AddSelections => {
 524                const PLACEHOLDER: &str = "selection ";
 525                let selections = selection_ranges(workspace, cx)
 526                    .into_iter()
 527                    .enumerate()
 528                    .map(|(ix, (buffer, range))| {
 529                        (
 530                            buffer,
 531                            range,
 532                            (PLACEHOLDER.len() * ix)..(PLACEHOLDER.len() * (ix + 1) - 1),
 533                        )
 534                    })
 535                    .collect::<Vec<_>>();
 536
 537                let new_text: String = PLACEHOLDER.repeat(selections.len());
 538
 539                let callback = Arc::new({
 540                    let source_range = source_range.clone();
 541                    move |_, window: &mut Window, cx: &mut App| {
 542                        let editor = editor.clone();
 543                        let selections = selections.clone();
 544                        let mention_set = mention_set.clone();
 545                        let source_range = source_range.clone();
 546                        window.defer(cx, move |window, cx| {
 547                            if let Some(editor) = editor.upgrade() {
 548                                mention_set
 549                                    .update(cx, |store, cx| {
 550                                        store.confirm_mention_for_selection(
 551                                            source_range,
 552                                            selections,
 553                                            editor,
 554                                            window,
 555                                            cx,
 556                                        )
 557                                    })
 558                                    .ok();
 559                            }
 560                        });
 561                        false
 562                    }
 563                });
 564
 565                (new_text, callback)
 566            }
 567        };
 568
 569        Some(Completion {
 570            replace_range: source_range,
 571            new_text,
 572            label: CodeLabel::plain(action.label().to_string(), None),
 573            icon_path: Some(action.icon().path().into()),
 574            documentation: None,
 575            source: project::CompletionSource::Custom,
 576            match_start: None,
 577            snippet_deduplication_key: None,
 578            insert_text_mode: None,
 579            // This ensures that when a user accepts this completion, the
 580            // completion menu will still be shown after "@category " is
 581            // inserted
 582            confirm: Some(on_action),
 583        })
 584    }
 585
 586    fn search_slash_commands(&self, query: String, cx: &mut App) -> Task<Vec<AvailableCommand>> {
 587        let commands = self.source.available_commands(cx);
 588        if commands.is_empty() {
 589            return Task::ready(Vec::new());
 590        }
 591
 592        cx.spawn(async move |cx| {
 593            let candidates = commands
 594                .iter()
 595                .enumerate()
 596                .map(|(id, command)| StringMatchCandidate::new(id, &command.name))
 597                .collect::<Vec<_>>();
 598
 599            let matches = fuzzy::match_strings(
 600                &candidates,
 601                &query,
 602                false,
 603                true,
 604                100,
 605                &Arc::new(AtomicBool::default()),
 606                cx.background_executor().clone(),
 607            )
 608            .await;
 609
 610            matches
 611                .into_iter()
 612                .map(|mat| commands[mat.candidate_id].clone())
 613                .collect()
 614        })
 615    }
 616
 617    fn search_mentions(
 618        &self,
 619        mode: Option<PromptContextType>,
 620        query: String,
 621        cancellation_flag: Arc<AtomicBool>,
 622        cx: &mut App,
 623    ) -> Task<Vec<Match>> {
 624        let Some(workspace) = self.workspace.upgrade() else {
 625            return Task::ready(Vec::default());
 626        };
 627        match mode {
 628            Some(PromptContextType::File) => {
 629                let search_files_task = search_files(query, cancellation_flag, &workspace, cx);
 630                cx.background_spawn(async move {
 631                    search_files_task
 632                        .await
 633                        .into_iter()
 634                        .map(Match::File)
 635                        .collect()
 636                })
 637            }
 638
 639            Some(PromptContextType::Symbol) => {
 640                let search_symbols_task = search_symbols(query, cancellation_flag, &workspace, cx);
 641                cx.background_spawn(async move {
 642                    search_symbols_task
 643                        .await
 644                        .into_iter()
 645                        .map(Match::Symbol)
 646                        .collect()
 647                })
 648            }
 649
 650            Some(PromptContextType::Thread) => {
 651                if let Some(history) = self.history.upgrade() {
 652                    let sessions = history.read(cx).sessions().to_vec();
 653                    let search_task =
 654                        filter_sessions_by_query(query, cancellation_flag, sessions, cx);
 655                    cx.spawn(async move |_cx| {
 656                        search_task.await.into_iter().map(Match::Thread).collect()
 657                    })
 658                } else {
 659                    Task::ready(Vec::new())
 660                }
 661            }
 662
 663            Some(PromptContextType::Fetch) => {
 664                if !query.is_empty() {
 665                    Task::ready(vec![Match::Fetch(query.into())])
 666                } else {
 667                    Task::ready(Vec::new())
 668                }
 669            }
 670
 671            Some(PromptContextType::Rules) => {
 672                if let Some(prompt_store) = self.prompt_store.as_ref() {
 673                    let search_rules_task =
 674                        search_rules(query, cancellation_flag, prompt_store, cx);
 675                    cx.background_spawn(async move {
 676                        search_rules_task
 677                            .await
 678                            .into_iter()
 679                            .map(Match::Rules)
 680                            .collect::<Vec<_>>()
 681                    })
 682                } else {
 683                    Task::ready(Vec::new())
 684                }
 685            }
 686
 687            None if query.is_empty() => {
 688                let recent_task = self.recent_context_picker_entries(&workspace, cx);
 689                let entries = self
 690                    .available_context_picker_entries(&workspace, cx)
 691                    .into_iter()
 692                    .map(|mode| {
 693                        Match::Entry(EntryMatch {
 694                            entry: mode,
 695                            mat: None,
 696                        })
 697                    })
 698                    .collect::<Vec<_>>();
 699
 700                cx.spawn(async move |_cx| {
 701                    let mut matches = recent_task.await;
 702                    matches.extend(entries);
 703                    matches
 704                })
 705            }
 706            None => {
 707                let executor = cx.background_executor().clone();
 708
 709                let search_files_task =
 710                    search_files(query.clone(), cancellation_flag, &workspace, cx);
 711
 712                let entries = self.available_context_picker_entries(&workspace, cx);
 713                let entry_candidates = entries
 714                    .iter()
 715                    .enumerate()
 716                    .map(|(ix, entry)| StringMatchCandidate::new(ix, entry.keyword()))
 717                    .collect::<Vec<_>>();
 718
 719                cx.background_spawn(async move {
 720                    let mut matches = search_files_task
 721                        .await
 722                        .into_iter()
 723                        .map(Match::File)
 724                        .collect::<Vec<_>>();
 725
 726                    let entry_matches = fuzzy::match_strings(
 727                        &entry_candidates,
 728                        &query,
 729                        false,
 730                        true,
 731                        100,
 732                        &Arc::new(AtomicBool::default()),
 733                        executor,
 734                    )
 735                    .await;
 736
 737                    matches.extend(entry_matches.into_iter().map(|mat| {
 738                        Match::Entry(EntryMatch {
 739                            entry: entries[mat.candidate_id],
 740                            mat: Some(mat),
 741                        })
 742                    }));
 743
 744                    matches.sort_by(|a, b| {
 745                        b.score()
 746                            .partial_cmp(&a.score())
 747                            .unwrap_or(std::cmp::Ordering::Equal)
 748                    });
 749
 750                    matches
 751                })
 752            }
 753        }
 754    }
 755
 756    fn recent_context_picker_entries(
 757        &self,
 758        workspace: &Entity<Workspace>,
 759        cx: &mut App,
 760    ) -> Task<Vec<Match>> {
 761        let mut recent = Vec::with_capacity(6);
 762
 763        let mut mentions = self
 764            .mention_set
 765            .read_with(cx, |store, _cx| store.mentions());
 766        let workspace = workspace.read(cx);
 767        let project = workspace.project().read(cx);
 768        let include_root_name = workspace.visible_worktrees(cx).count() > 1;
 769
 770        if let Some(agent_panel) = workspace.panel::<AgentPanel>(cx)
 771            && let Some(thread) = agent_panel.read(cx).active_agent_thread(cx)
 772        {
 773            let thread = thread.read(cx);
 774            mentions.insert(MentionUri::Thread {
 775                id: thread.session_id().clone(),
 776                name: thread.title().into(),
 777            });
 778        }
 779
 780        recent.extend(
 781            workspace
 782                .recent_navigation_history_iter(cx)
 783                .filter(|(_, abs_path)| {
 784                    abs_path.as_ref().is_none_or(|path| {
 785                        !mentions.contains(&MentionUri::File {
 786                            abs_path: path.clone(),
 787                        })
 788                    })
 789                })
 790                .take(4)
 791                .filter_map(|(project_path, _)| {
 792                    project
 793                        .worktree_for_id(project_path.worktree_id, cx)
 794                        .map(|worktree| {
 795                            let path_prefix = if include_root_name {
 796                                worktree.read(cx).root_name().into()
 797                            } else {
 798                                RelPath::empty().into()
 799                            };
 800                            Match::File(FileMatch {
 801                                mat: fuzzy::PathMatch {
 802                                    score: 1.,
 803                                    positions: Vec::new(),
 804                                    worktree_id: project_path.worktree_id.to_usize(),
 805                                    path: project_path.path,
 806                                    path_prefix,
 807                                    is_dir: false,
 808                                    distance_to_relative_ancestor: 0,
 809                                },
 810                                is_recent: true,
 811                            })
 812                        })
 813                }),
 814        );
 815
 816        if !self.source.supports_context(PromptContextType::Thread, cx) {
 817            return Task::ready(recent);
 818        }
 819
 820        if let Some(history) = self.history.upgrade() {
 821            const RECENT_COUNT: usize = 2;
 822            recent.extend(
 823                history
 824                    .read(cx)
 825                    .sessions()
 826                    .into_iter()
 827                    .filter(|session| {
 828                        let uri = MentionUri::Thread {
 829                            id: session.session_id.clone(),
 830                            name: session_title(session).to_string(),
 831                        };
 832                        !mentions.contains(&uri)
 833                    })
 834                    .take(RECENT_COUNT)
 835                    .cloned()
 836                    .map(Match::RecentThread),
 837            );
 838            return Task::ready(recent);
 839        }
 840
 841        Task::ready(recent)
 842    }
 843
 844    fn available_context_picker_entries(
 845        &self,
 846        workspace: &Entity<Workspace>,
 847        cx: &mut App,
 848    ) -> Vec<PromptContextEntry> {
 849        let mut entries = vec![
 850            PromptContextEntry::Mode(PromptContextType::File),
 851            PromptContextEntry::Mode(PromptContextType::Symbol),
 852        ];
 853
 854        if self.source.supports_context(PromptContextType::Thread, cx) {
 855            entries.push(PromptContextEntry::Mode(PromptContextType::Thread));
 856        }
 857
 858        let has_selection = workspace
 859            .read(cx)
 860            .active_item(cx)
 861            .and_then(|item| item.downcast::<Editor>())
 862            .is_some_and(|editor| {
 863                editor.update(cx, |editor, cx| {
 864                    editor.has_non_empty_selection(&editor.display_snapshot(cx))
 865                })
 866            });
 867        if has_selection {
 868            entries.push(PromptContextEntry::Action(
 869                PromptContextAction::AddSelections,
 870            ));
 871        }
 872
 873        if self.prompt_store.is_some() && self.source.supports_context(PromptContextType::Rules, cx)
 874        {
 875            entries.push(PromptContextEntry::Mode(PromptContextType::Rules));
 876        }
 877
 878        if self.source.supports_context(PromptContextType::Fetch, cx) {
 879            entries.push(PromptContextEntry::Mode(PromptContextType::Fetch));
 880        }
 881
 882        entries
 883    }
 884}
 885
 886impl<T: PromptCompletionProviderDelegate> CompletionProvider for PromptCompletionProvider<T> {
 887    fn completions(
 888        &self,
 889        _excerpt_id: ExcerptId,
 890        buffer: &Entity<Buffer>,
 891        buffer_position: Anchor,
 892        _trigger: CompletionContext,
 893        window: &mut Window,
 894        cx: &mut Context<Editor>,
 895    ) -> Task<Result<Vec<CompletionResponse>>> {
 896        let state = buffer.update(cx, |buffer, cx| {
 897            let position = buffer_position.to_point(buffer);
 898            let line_start = Point::new(position.row, 0);
 899            let offset_to_line = buffer.point_to_offset(line_start);
 900            let mut lines = buffer.text_for_range(line_start..position).lines();
 901            let line = lines.next()?;
 902            PromptCompletion::try_parse(line, offset_to_line, &self.source.supported_modes(cx))
 903        });
 904        let Some(state) = state else {
 905            return Task::ready(Ok(Vec::new()));
 906        };
 907
 908        let Some(workspace) = self.workspace.upgrade() else {
 909            return Task::ready(Ok(Vec::new()));
 910        };
 911
 912        let project = workspace.read(cx).project().clone();
 913        let snapshot = buffer.read(cx).snapshot();
 914        let source_range = snapshot.anchor_before(state.source_range().start)
 915            ..snapshot.anchor_after(state.source_range().end);
 916
 917        let source = self.source.clone();
 918        let editor = self.editor.clone();
 919        let mention_set = self.mention_set.downgrade();
 920        match state {
 921            PromptCompletion::SlashCommand(SlashCommandCompletion {
 922                command, argument, ..
 923            }) => {
 924                let search_task = self.search_slash_commands(command.unwrap_or_default(), cx);
 925                cx.background_spawn(async move {
 926                    let completions = search_task
 927                        .await
 928                        .into_iter()
 929                        .map(|command| {
 930                            let new_text = if let Some(argument) = argument.as_ref() {
 931                                format!("/{} {}", command.name, argument)
 932                            } else {
 933                                format!("/{} ", command.name)
 934                            };
 935
 936                            let is_missing_argument =
 937                                command.requires_argument && argument.is_none();
 938                            Completion {
 939                                replace_range: source_range.clone(),
 940                                new_text,
 941                                label: CodeLabel::plain(command.name.to_string(), None),
 942                                documentation: Some(CompletionDocumentation::MultiLinePlainText(
 943                                    command.description.into(),
 944                                )),
 945                                source: project::CompletionSource::Custom,
 946                                icon_path: None,
 947                                match_start: None,
 948                                snippet_deduplication_key: None,
 949                                insert_text_mode: None,
 950                                confirm: Some(Arc::new({
 951                                    let source = source.clone();
 952                                    move |intent, _window, cx| {
 953                                        if !is_missing_argument {
 954                                            cx.defer({
 955                                                let source = source.clone();
 956                                                move |cx| match intent {
 957                                                    CompletionIntent::Complete
 958                                                    | CompletionIntent::CompleteWithInsert
 959                                                    | CompletionIntent::CompleteWithReplace => {
 960                                                        source.confirm_command(cx);
 961                                                    }
 962                                                    CompletionIntent::Compose => {}
 963                                                }
 964                                            });
 965                                        }
 966                                        false
 967                                    }
 968                                })),
 969                            }
 970                        })
 971                        .collect();
 972
 973                    Ok(vec![CompletionResponse {
 974                        completions,
 975                        display_options: CompletionDisplayOptions {
 976                            dynamic_width: true,
 977                        },
 978                        // Since this does its own filtering (see `filter_completions()` returns false),
 979                        // there is no benefit to computing whether this set of completions is incomplete.
 980                        is_incomplete: true,
 981                    }])
 982                })
 983            }
 984            PromptCompletion::Mention(MentionCompletion { mode, argument, .. }) => {
 985                let query = argument.unwrap_or_default();
 986                let search_task =
 987                    self.search_mentions(mode, query, Arc::<AtomicBool>::default(), cx);
 988
 989                // Calculate maximum characters available for the full label (file_name + space + directory)
 990                // based on maximum menu width after accounting for padding, spacing, and icon width
 991                let label_max_chars = {
 992                    // Base06 left padding + Base06 gap + Base06 right padding + icon width
 993                    let used_pixels = DynamicSpacing::Base06.px(cx) * 3.0
 994                        + IconSize::XSmall.rems() * window.rem_size();
 995
 996                    let style = window.text_style();
 997                    let font_id = window.text_system().resolve_font(&style.font());
 998                    let font_size = TextSize::Small.rems(cx).to_pixels(window.rem_size());
 999
1000                    // Fallback em_width of 10px matches file_finder.rs fallback for TextSize::Small
1001                    let em_width = cx
1002                        .text_system()
1003                        .em_width(font_id, font_size)
1004                        .unwrap_or(px(10.0));
1005
1006                    // Calculate available pixels for text (file_name + directory)
1007                    // Using max width since dynamic_width allows the menu to expand up to this
1008                    let available_pixels = COMPLETION_MENU_MAX_WIDTH - used_pixels;
1009
1010                    // Convert to character count (total available for file_name + directory)
1011                    (f32::from(available_pixels) / f32::from(em_width)) as usize
1012                };
1013
1014                cx.spawn(async move |_, cx| {
1015                    let matches = search_task.await;
1016
1017                    let completions = cx.update(|cx| {
1018                        matches
1019                            .into_iter()
1020                            .filter_map(|mat| match mat {
1021                                Match::File(FileMatch { mat, is_recent }) => {
1022                                    let project_path = ProjectPath {
1023                                        worktree_id: WorktreeId::from_usize(mat.worktree_id),
1024                                        path: mat.path.clone(),
1025                                    };
1026
1027                                    // If path is empty, this means we're matching with the root directory itself
1028                                    // so we use the path_prefix as the name
1029                                    let path_prefix = if mat.path.is_empty() {
1030                                        project
1031                                            .read(cx)
1032                                            .worktree_for_id(project_path.worktree_id, cx)
1033                                            .map(|wt| wt.read(cx).root_name().into())
1034                                            .unwrap_or_else(|| mat.path_prefix.clone())
1035                                    } else {
1036                                        mat.path_prefix.clone()
1037                                    };
1038
1039                                    Self::completion_for_path(
1040                                        project_path,
1041                                        &path_prefix,
1042                                        is_recent,
1043                                        mat.is_dir,
1044                                        source_range.clone(),
1045                                        source.clone(),
1046                                        editor.clone(),
1047                                        mention_set.clone(),
1048                                        workspace.clone(),
1049                                        project.clone(),
1050                                        label_max_chars,
1051                                        cx,
1052                                    )
1053                                }
1054
1055                                Match::Symbol(SymbolMatch { symbol, .. }) => {
1056                                    Self::completion_for_symbol(
1057                                        symbol,
1058                                        source_range.clone(),
1059                                        source.clone(),
1060                                        editor.clone(),
1061                                        mention_set.clone(),
1062                                        workspace.clone(),
1063                                        label_max_chars,
1064                                        cx,
1065                                    )
1066                                }
1067
1068                                Match::Thread(thread) => Some(Self::completion_for_thread(
1069                                    thread,
1070                                    source_range.clone(),
1071                                    false,
1072                                    source.clone(),
1073                                    editor.clone(),
1074                                    mention_set.clone(),
1075                                    workspace.clone(),
1076                                    cx,
1077                                )),
1078
1079                                Match::RecentThread(thread) => Some(Self::completion_for_thread(
1080                                    thread,
1081                                    source_range.clone(),
1082                                    true,
1083                                    source.clone(),
1084                                    editor.clone(),
1085                                    mention_set.clone(),
1086                                    workspace.clone(),
1087                                    cx,
1088                                )),
1089
1090                                Match::Rules(user_rules) => Some(Self::completion_for_rules(
1091                                    user_rules,
1092                                    source_range.clone(),
1093                                    source.clone(),
1094                                    editor.clone(),
1095                                    mention_set.clone(),
1096                                    workspace.clone(),
1097                                    cx,
1098                                )),
1099
1100                                Match::Fetch(url) => Self::completion_for_fetch(
1101                                    source_range.clone(),
1102                                    url,
1103                                    source.clone(),
1104                                    editor.clone(),
1105                                    mention_set.clone(),
1106                                    workspace.clone(),
1107                                    cx,
1108                                ),
1109
1110                                Match::Entry(EntryMatch { entry, .. }) => {
1111                                    Self::completion_for_entry(
1112                                        entry,
1113                                        source_range.clone(),
1114                                        editor.clone(),
1115                                        mention_set.clone(),
1116                                        &workspace,
1117                                        cx,
1118                                    )
1119                                }
1120                            })
1121                            .collect::<Vec<_>>()
1122                    });
1123
1124                    Ok(vec![CompletionResponse {
1125                        completions,
1126                        display_options: CompletionDisplayOptions {
1127                            dynamic_width: true,
1128                        },
1129                        // Since this does its own filtering (see `filter_completions()` returns false),
1130                        // there is no benefit to computing whether this set of completions is incomplete.
1131                        is_incomplete: true,
1132                    }])
1133                })
1134            }
1135        }
1136    }
1137
1138    fn is_completion_trigger(
1139        &self,
1140        buffer: &Entity<language::Buffer>,
1141        position: language::Anchor,
1142        _text: &str,
1143        _trigger_in_words: bool,
1144        cx: &mut Context<Editor>,
1145    ) -> bool {
1146        let buffer = buffer.read(cx);
1147        let position = position.to_point(buffer);
1148        let line_start = Point::new(position.row, 0);
1149        let offset_to_line = buffer.point_to_offset(line_start);
1150        let mut lines = buffer.text_for_range(line_start..position).lines();
1151        if let Some(line) = lines.next() {
1152            PromptCompletion::try_parse(line, offset_to_line, &self.source.supported_modes(cx))
1153                .filter(|completion| {
1154                    // Right now we don't support completing arguments of slash commands
1155                    let is_slash_command_with_argument = matches!(
1156                        completion,
1157                        PromptCompletion::SlashCommand(SlashCommandCompletion {
1158                            argument: Some(_),
1159                            ..
1160                        })
1161                    );
1162                    !is_slash_command_with_argument
1163                })
1164                .map(|completion| {
1165                    completion.source_range().start <= offset_to_line + position.column as usize
1166                        && completion.source_range().end
1167                            >= offset_to_line + position.column as usize
1168                })
1169                .unwrap_or(false)
1170        } else {
1171            false
1172        }
1173    }
1174
1175    fn sort_completions(&self) -> bool {
1176        false
1177    }
1178
1179    fn filter_completions(&self) -> bool {
1180        false
1181    }
1182}
1183
1184fn confirm_completion_callback<T: PromptCompletionProviderDelegate>(
1185    crease_text: SharedString,
1186    start: Anchor,
1187    content_len: usize,
1188    mention_uri: MentionUri,
1189    source: Arc<T>,
1190    editor: WeakEntity<Editor>,
1191    mention_set: WeakEntity<MentionSet>,
1192    workspace: Entity<Workspace>,
1193) -> Arc<dyn Fn(CompletionIntent, &mut Window, &mut App) -> bool + Send + Sync> {
1194    Arc::new(move |_, window, cx| {
1195        let source = source.clone();
1196        let editor = editor.clone();
1197        let mention_set = mention_set.clone();
1198        let crease_text = crease_text.clone();
1199        let mention_uri = mention_uri.clone();
1200        let workspace = workspace.clone();
1201        window.defer(cx, move |window, cx| {
1202            if let Some(editor) = editor.upgrade() {
1203                mention_set
1204                    .clone()
1205                    .update(cx, |mention_set, cx| {
1206                        mention_set
1207                            .confirm_mention_completion(
1208                                crease_text,
1209                                start,
1210                                content_len,
1211                                mention_uri,
1212                                source.supports_images(cx),
1213                                editor,
1214                                &workspace,
1215                                window,
1216                                cx,
1217                            )
1218                            .detach();
1219                    })
1220                    .ok();
1221            }
1222        });
1223        false
1224    })
1225}
1226
1227#[derive(Debug, PartialEq)]
1228enum PromptCompletion {
1229    SlashCommand(SlashCommandCompletion),
1230    Mention(MentionCompletion),
1231}
1232
1233impl PromptCompletion {
1234    fn source_range(&self) -> Range<usize> {
1235        match self {
1236            Self::SlashCommand(completion) => completion.source_range.clone(),
1237            Self::Mention(completion) => completion.source_range.clone(),
1238        }
1239    }
1240
1241    fn try_parse(
1242        line: &str,
1243        offset_to_line: usize,
1244        supported_modes: &[PromptContextType],
1245    ) -> Option<Self> {
1246        if line.contains('@') {
1247            if let Some(mention) =
1248                MentionCompletion::try_parse(line, offset_to_line, supported_modes)
1249            {
1250                return Some(Self::Mention(mention));
1251            }
1252        }
1253        SlashCommandCompletion::try_parse(line, offset_to_line).map(Self::SlashCommand)
1254    }
1255}
1256
1257#[derive(Debug, Default, PartialEq)]
1258pub struct SlashCommandCompletion {
1259    pub source_range: Range<usize>,
1260    pub command: Option<String>,
1261    pub argument: Option<String>,
1262}
1263
1264impl SlashCommandCompletion {
1265    pub fn try_parse(line: &str, offset_to_line: usize) -> Option<Self> {
1266        // If we decide to support commands that are not at the beginning of the prompt, we can remove this check
1267        if !line.starts_with('/') || offset_to_line != 0 {
1268            return None;
1269        }
1270
1271        let (prefix, last_command) = line.rsplit_once('/')?;
1272        if prefix.chars().last().is_some_and(|c| !c.is_whitespace())
1273            || last_command.starts_with(char::is_whitespace)
1274        {
1275            return None;
1276        }
1277
1278        let mut argument = None;
1279        let mut command = None;
1280        if let Some((command_text, args)) = last_command.split_once(char::is_whitespace) {
1281            if !args.is_empty() {
1282                argument = Some(args.trim_end().to_string());
1283            }
1284            command = Some(command_text.to_string());
1285        } else if !last_command.is_empty() {
1286            command = Some(last_command.to_string());
1287        };
1288
1289        Some(Self {
1290            source_range: prefix.len() + offset_to_line
1291                ..line
1292                    .rfind(|c: char| !c.is_whitespace())
1293                    .unwrap_or_else(|| line.len())
1294                    + 1
1295                    + offset_to_line,
1296            command,
1297            argument,
1298        })
1299    }
1300}
1301
1302#[derive(Debug, Default, PartialEq)]
1303struct MentionCompletion {
1304    source_range: Range<usize>,
1305    mode: Option<PromptContextType>,
1306    argument: Option<String>,
1307}
1308
1309impl MentionCompletion {
1310    fn try_parse(
1311        line: &str,
1312        offset_to_line: usize,
1313        supported_modes: &[PromptContextType],
1314    ) -> Option<Self> {
1315        let last_mention_start = line.rfind('@')?;
1316
1317        // No whitespace immediately after '@'
1318        if line[last_mention_start + 1..]
1319            .chars()
1320            .next()
1321            .is_some_and(|c| c.is_whitespace())
1322        {
1323            return None;
1324        }
1325
1326        //  Must be a word boundary before '@'
1327        if last_mention_start > 0
1328            && line[..last_mention_start]
1329                .chars()
1330                .last()
1331                .is_some_and(|c| !c.is_whitespace())
1332        {
1333            return None;
1334        }
1335
1336        let rest_of_line = &line[last_mention_start + 1..];
1337
1338        let mut mode = None;
1339        let mut argument = None;
1340
1341        let mut parts = rest_of_line.split_whitespace();
1342        let mut end = last_mention_start + 1;
1343
1344        if let Some(mode_text) = parts.next() {
1345            // Safe since we check no leading whitespace above
1346            end += mode_text.len();
1347
1348            if let Some(parsed_mode) = PromptContextType::try_from(mode_text).ok()
1349                && supported_modes.contains(&parsed_mode)
1350            {
1351                mode = Some(parsed_mode);
1352            } else {
1353                argument = Some(mode_text.to_string());
1354            }
1355            match rest_of_line[mode_text.len()..].find(|c: char| !c.is_whitespace()) {
1356                Some(whitespace_count) => {
1357                    if let Some(argument_text) = parts.next() {
1358                        // If mode wasn't recognized but we have an argument, don't suggest completions
1359                        // (e.g. '@something word')
1360                        if mode.is_none() && !argument_text.is_empty() {
1361                            return None;
1362                        }
1363
1364                        argument = Some(argument_text.to_string());
1365                        end += whitespace_count + argument_text.len();
1366                    }
1367                }
1368                None => {
1369                    // Rest of line is entirely whitespace
1370                    end += rest_of_line.len() - mode_text.len();
1371                }
1372            }
1373        }
1374
1375        Some(Self {
1376            source_range: last_mention_start + offset_to_line..end + offset_to_line,
1377            mode,
1378            argument,
1379        })
1380    }
1381}
1382
1383pub(crate) fn search_files(
1384    query: String,
1385    cancellation_flag: Arc<AtomicBool>,
1386    workspace: &Entity<Workspace>,
1387    cx: &App,
1388) -> Task<Vec<FileMatch>> {
1389    if query.is_empty() {
1390        let workspace = workspace.read(cx);
1391        let project = workspace.project().read(cx);
1392        let visible_worktrees = workspace.visible_worktrees(cx).collect::<Vec<_>>();
1393        let include_root_name = visible_worktrees.len() > 1;
1394
1395        let recent_matches = workspace
1396            .recent_navigation_history(Some(10), cx)
1397            .into_iter()
1398            .map(|(project_path, _)| {
1399                let path_prefix = if include_root_name {
1400                    project
1401                        .worktree_for_id(project_path.worktree_id, cx)
1402                        .map(|wt| wt.read(cx).root_name().into())
1403                        .unwrap_or_else(|| RelPath::empty().into())
1404                } else {
1405                    RelPath::empty().into()
1406                };
1407
1408                FileMatch {
1409                    mat: PathMatch {
1410                        score: 0.,
1411                        positions: Vec::new(),
1412                        worktree_id: project_path.worktree_id.to_usize(),
1413                        path: project_path.path,
1414                        path_prefix,
1415                        distance_to_relative_ancestor: 0,
1416                        is_dir: false,
1417                    },
1418                    is_recent: true,
1419                }
1420            });
1421
1422        let file_matches = visible_worktrees.into_iter().flat_map(|worktree| {
1423            let worktree = worktree.read(cx);
1424            let path_prefix: Arc<RelPath> = if include_root_name {
1425                worktree.root_name().into()
1426            } else {
1427                RelPath::empty().into()
1428            };
1429            worktree.entries(false, 0).map(move |entry| FileMatch {
1430                mat: PathMatch {
1431                    score: 0.,
1432                    positions: Vec::new(),
1433                    worktree_id: worktree.id().to_usize(),
1434                    path: entry.path.clone(),
1435                    path_prefix: path_prefix.clone(),
1436                    distance_to_relative_ancestor: 0,
1437                    is_dir: entry.is_dir(),
1438                },
1439                is_recent: false,
1440            })
1441        });
1442
1443        Task::ready(recent_matches.chain(file_matches).collect())
1444    } else {
1445        let worktrees = workspace.read(cx).visible_worktrees(cx).collect::<Vec<_>>();
1446        let include_root_name = worktrees.len() > 1;
1447        let candidate_sets = worktrees
1448            .into_iter()
1449            .map(|worktree| {
1450                let worktree = worktree.read(cx);
1451
1452                PathMatchCandidateSet {
1453                    snapshot: worktree.snapshot(),
1454                    include_ignored: worktree.root_entry().is_some_and(|entry| entry.is_ignored),
1455                    include_root_name,
1456                    candidates: project::Candidates::Entries,
1457                }
1458            })
1459            .collect::<Vec<_>>();
1460
1461        let executor = cx.background_executor().clone();
1462        cx.foreground_executor().spawn(async move {
1463            fuzzy::match_path_sets(
1464                candidate_sets.as_slice(),
1465                query.as_str(),
1466                &None,
1467                false,
1468                100,
1469                &cancellation_flag,
1470                executor,
1471            )
1472            .await
1473            .into_iter()
1474            .map(|mat| FileMatch {
1475                mat,
1476                is_recent: false,
1477            })
1478            .collect::<Vec<_>>()
1479        })
1480    }
1481}
1482
1483pub(crate) fn search_symbols(
1484    query: String,
1485    cancellation_flag: Arc<AtomicBool>,
1486    workspace: &Entity<Workspace>,
1487    cx: &mut App,
1488) -> Task<Vec<SymbolMatch>> {
1489    let symbols_task = workspace.update(cx, |workspace, cx| {
1490        workspace
1491            .project()
1492            .update(cx, |project, cx| project.symbols(&query, cx))
1493    });
1494    let project = workspace.read(cx).project().clone();
1495    cx.spawn(async move |cx| {
1496        let Some(symbols) = symbols_task.await.log_err() else {
1497            return Vec::new();
1498        };
1499        let (visible_match_candidates, external_match_candidates): (Vec<_>, Vec<_>) = project
1500            .update(cx, |project, cx| {
1501                symbols
1502                    .iter()
1503                    .enumerate()
1504                    .map(|(id, symbol)| StringMatchCandidate::new(id, symbol.label.filter_text()))
1505                    .partition(|candidate| match &symbols[candidate.id].path {
1506                        SymbolLocation::InProject(project_path) => project
1507                            .entry_for_path(project_path, cx)
1508                            .is_some_and(|e| !e.is_ignored),
1509                        SymbolLocation::OutsideProject { .. } => false,
1510                    })
1511            });
1512        // Try to support rust-analyzer's path based symbols feature which
1513        // allows to search by rust path syntax, in that case we only want to
1514        // filter names by the last segment
1515        // Ideally this was a first class LSP feature (rich queries)
1516        let query = query
1517            .rsplit_once("::")
1518            .map_or(&*query, |(_, suffix)| suffix)
1519            .to_owned();
1520        // Note if you make changes to this filtering below, also change `project_symbols::ProjectSymbolsDelegate::filter`
1521        const MAX_MATCHES: usize = 100;
1522        let mut visible_matches = cx.foreground_executor().block_on(fuzzy::match_strings(
1523            &visible_match_candidates,
1524            &query,
1525            false,
1526            true,
1527            MAX_MATCHES,
1528            &cancellation_flag,
1529            cx.background_executor().clone(),
1530        ));
1531        let mut external_matches = cx.foreground_executor().block_on(fuzzy::match_strings(
1532            &external_match_candidates,
1533            &query,
1534            false,
1535            true,
1536            MAX_MATCHES - visible_matches.len().min(MAX_MATCHES),
1537            &cancellation_flag,
1538            cx.background_executor().clone(),
1539        ));
1540        let sort_key_for_match = |mat: &StringMatch| {
1541            let symbol = &symbols[mat.candidate_id];
1542            (Reverse(OrderedFloat(mat.score)), symbol.label.filter_text())
1543        };
1544
1545        visible_matches.sort_unstable_by_key(sort_key_for_match);
1546        external_matches.sort_unstable_by_key(sort_key_for_match);
1547        let mut matches = visible_matches;
1548        matches.append(&mut external_matches);
1549
1550        matches
1551            .into_iter()
1552            .map(|mut mat| {
1553                let symbol = symbols[mat.candidate_id].clone();
1554                let filter_start = symbol.label.filter_range.start;
1555                for position in &mut mat.positions {
1556                    *position += filter_start;
1557                }
1558                SymbolMatch { symbol }
1559            })
1560            .collect()
1561    })
1562}
1563
1564fn filter_sessions_by_query(
1565    query: String,
1566    cancellation_flag: Arc<AtomicBool>,
1567    sessions: Vec<AgentSessionInfo>,
1568    cx: &mut App,
1569) -> Task<Vec<AgentSessionInfo>> {
1570    if query.is_empty() {
1571        return Task::ready(sessions);
1572    }
1573    let executor = cx.background_executor().clone();
1574    cx.background_spawn(async move {
1575        filter_sessions(query, cancellation_flag, sessions, executor).await
1576    })
1577}
1578
1579async fn filter_sessions(
1580    query: String,
1581    cancellation_flag: Arc<AtomicBool>,
1582    sessions: Vec<AgentSessionInfo>,
1583    executor: BackgroundExecutor,
1584) -> Vec<AgentSessionInfo> {
1585    let titles = sessions.iter().map(session_title).collect::<Vec<_>>();
1586    let candidates = titles
1587        .iter()
1588        .enumerate()
1589        .map(|(id, title)| StringMatchCandidate::new(id, title.as_ref()))
1590        .collect::<Vec<_>>();
1591    let matches = fuzzy::match_strings(
1592        &candidates,
1593        &query,
1594        false,
1595        true,
1596        100,
1597        &cancellation_flag,
1598        executor,
1599    )
1600    .await;
1601
1602    matches
1603        .into_iter()
1604        .map(|mat| sessions[mat.candidate_id].clone())
1605        .collect()
1606}
1607
1608pub(crate) fn search_rules(
1609    query: String,
1610    cancellation_flag: Arc<AtomicBool>,
1611    prompt_store: &Entity<PromptStore>,
1612    cx: &mut App,
1613) -> Task<Vec<RulesContextEntry>> {
1614    let search_task = prompt_store.read(cx).search(query, cancellation_flag, cx);
1615    cx.background_spawn(async move {
1616        search_task
1617            .await
1618            .into_iter()
1619            .flat_map(|metadata| {
1620                // Default prompts are filtered out as they are automatically included.
1621                if metadata.default {
1622                    None
1623                } else {
1624                    Some(RulesContextEntry {
1625                        prompt_id: metadata.id.as_user()?,
1626                        title: metadata.title?,
1627                    })
1628                }
1629            })
1630            .collect::<Vec<_>>()
1631    })
1632}
1633
1634pub struct SymbolMatch {
1635    pub symbol: Symbol,
1636}
1637
1638pub struct FileMatch {
1639    pub mat: PathMatch,
1640    pub is_recent: bool,
1641}
1642
1643pub fn extract_file_name_and_directory(
1644    path: &RelPath,
1645    path_prefix: &RelPath,
1646    path_style: PathStyle,
1647) -> (SharedString, Option<SharedString>) {
1648    // If path is empty, this means we're matching with the root directory itself
1649    // so we use the path_prefix as the name
1650    if path.is_empty() && !path_prefix.is_empty() {
1651        return (path_prefix.display(path_style).to_string().into(), None);
1652    }
1653
1654    let full_path = path_prefix.join(path);
1655    let file_name = full_path.file_name().unwrap_or_default();
1656    let display_path = full_path.display(path_style);
1657    let (directory, file_name) = display_path.split_at(display_path.len() - file_name.len());
1658    (
1659        file_name.to_string().into(),
1660        Some(SharedString::new(directory)).filter(|dir| !dir.is_empty()),
1661    )
1662}
1663
1664fn build_code_label_for_path(
1665    file: &str,
1666    directory: Option<&str>,
1667    line_number: Option<u32>,
1668    label_max_chars: usize,
1669    cx: &App,
1670) -> CodeLabel {
1671    let variable_highlight_id = cx
1672        .theme()
1673        .syntax()
1674        .highlight_id("variable")
1675        .map(HighlightId);
1676    let mut label = CodeLabelBuilder::default();
1677
1678    label.push_str(file, None);
1679    label.push_str(" ", None);
1680
1681    if let Some(directory) = directory {
1682        let file_name_chars = file.chars().count();
1683        // Account for: file_name + space (ellipsis is handled by truncate_and_remove_front)
1684        let directory_max_chars = label_max_chars
1685            .saturating_sub(file_name_chars)
1686            .saturating_sub(1);
1687        let truncated_directory = truncate_and_remove_front(directory, directory_max_chars.max(5));
1688        label.push_str(&truncated_directory, variable_highlight_id);
1689    }
1690    if let Some(line_number) = line_number {
1691        label.push_str(&format!(" L{}", line_number), variable_highlight_id);
1692    }
1693    label.build()
1694}
1695
1696fn selection_ranges(
1697    workspace: &Entity<Workspace>,
1698    cx: &mut App,
1699) -> Vec<(Entity<Buffer>, Range<text::Anchor>)> {
1700    let Some(editor) = workspace
1701        .read(cx)
1702        .active_item(cx)
1703        .and_then(|item| item.act_as::<Editor>(cx))
1704    else {
1705        return Vec::new();
1706    };
1707
1708    editor.update(cx, |editor, cx| {
1709        let selections = editor.selections.all_adjusted(&editor.display_snapshot(cx));
1710
1711        let buffer = editor.buffer().clone().read(cx);
1712        let snapshot = buffer.snapshot(cx);
1713
1714        selections
1715            .into_iter()
1716            .map(|s| snapshot.anchor_after(s.start)..snapshot.anchor_before(s.end))
1717            .flat_map(|range| {
1718                let (start_buffer, start) = buffer.text_anchor_for_position(range.start, cx)?;
1719                let (end_buffer, end) = buffer.text_anchor_for_position(range.end, cx)?;
1720                if start_buffer != end_buffer {
1721                    return None;
1722                }
1723                Some((start_buffer, start..end))
1724            })
1725            .collect::<Vec<_>>()
1726    })
1727}
1728
1729#[cfg(test)]
1730mod tests {
1731    use super::*;
1732    use gpui::TestAppContext;
1733
1734    #[test]
1735    fn test_prompt_completion_parse() {
1736        let supported_modes = vec![PromptContextType::File, PromptContextType::Symbol];
1737
1738        assert_eq!(
1739            PromptCompletion::try_parse("/", 0, &supported_modes),
1740            Some(PromptCompletion::SlashCommand(SlashCommandCompletion {
1741                source_range: 0..1,
1742                command: None,
1743                argument: None,
1744            }))
1745        );
1746
1747        assert_eq!(
1748            PromptCompletion::try_parse("@", 0, &supported_modes),
1749            Some(PromptCompletion::Mention(MentionCompletion {
1750                source_range: 0..1,
1751                mode: None,
1752                argument: None,
1753            }))
1754        );
1755
1756        assert_eq!(
1757            PromptCompletion::try_parse("/test @file", 0, &supported_modes),
1758            Some(PromptCompletion::Mention(MentionCompletion {
1759                source_range: 6..11,
1760                mode: Some(PromptContextType::File),
1761                argument: None,
1762            }))
1763        );
1764    }
1765
1766    #[test]
1767    fn test_slash_command_completion_parse() {
1768        assert_eq!(
1769            SlashCommandCompletion::try_parse("/", 0),
1770            Some(SlashCommandCompletion {
1771                source_range: 0..1,
1772                command: None,
1773                argument: None,
1774            })
1775        );
1776
1777        assert_eq!(
1778            SlashCommandCompletion::try_parse("/help", 0),
1779            Some(SlashCommandCompletion {
1780                source_range: 0..5,
1781                command: Some("help".to_string()),
1782                argument: None,
1783            })
1784        );
1785
1786        assert_eq!(
1787            SlashCommandCompletion::try_parse("/help ", 0),
1788            Some(SlashCommandCompletion {
1789                source_range: 0..5,
1790                command: Some("help".to_string()),
1791                argument: None,
1792            })
1793        );
1794
1795        assert_eq!(
1796            SlashCommandCompletion::try_parse("/help arg1", 0),
1797            Some(SlashCommandCompletion {
1798                source_range: 0..10,
1799                command: Some("help".to_string()),
1800                argument: Some("arg1".to_string()),
1801            })
1802        );
1803
1804        assert_eq!(
1805            SlashCommandCompletion::try_parse("/help arg1 arg2", 0),
1806            Some(SlashCommandCompletion {
1807                source_range: 0..15,
1808                command: Some("help".to_string()),
1809                argument: Some("arg1 arg2".to_string()),
1810            })
1811        );
1812
1813        assert_eq!(
1814            SlashCommandCompletion::try_parse("/拿不到命令 拿不到命令 ", 0),
1815            Some(SlashCommandCompletion {
1816                source_range: 0..30,
1817                command: Some("拿不到命令".to_string()),
1818                argument: Some("拿不到命令".to_string()),
1819            })
1820        );
1821
1822        assert_eq!(SlashCommandCompletion::try_parse("Lorem Ipsum", 0), None);
1823
1824        assert_eq!(SlashCommandCompletion::try_parse("Lorem /", 0), None);
1825
1826        assert_eq!(SlashCommandCompletion::try_parse("Lorem /help", 0), None);
1827
1828        assert_eq!(SlashCommandCompletion::try_parse("Lorem/", 0), None);
1829
1830        assert_eq!(SlashCommandCompletion::try_parse("/ ", 0), None);
1831    }
1832
1833    #[test]
1834    fn test_mention_completion_parse() {
1835        let supported_modes = vec![PromptContextType::File, PromptContextType::Symbol];
1836
1837        assert_eq!(
1838            MentionCompletion::try_parse("Lorem Ipsum", 0, &supported_modes),
1839            None
1840        );
1841
1842        assert_eq!(
1843            MentionCompletion::try_parse("Lorem @", 0, &supported_modes),
1844            Some(MentionCompletion {
1845                source_range: 6..7,
1846                mode: None,
1847                argument: None,
1848            })
1849        );
1850
1851        assert_eq!(
1852            MentionCompletion::try_parse("Lorem @file", 0, &supported_modes),
1853            Some(MentionCompletion {
1854                source_range: 6..11,
1855                mode: Some(PromptContextType::File),
1856                argument: None,
1857            })
1858        );
1859
1860        assert_eq!(
1861            MentionCompletion::try_parse("Lorem @file ", 0, &supported_modes),
1862            Some(MentionCompletion {
1863                source_range: 6..12,
1864                mode: Some(PromptContextType::File),
1865                argument: None,
1866            })
1867        );
1868
1869        assert_eq!(
1870            MentionCompletion::try_parse("Lorem @file main.rs", 0, &supported_modes),
1871            Some(MentionCompletion {
1872                source_range: 6..19,
1873                mode: Some(PromptContextType::File),
1874                argument: Some("main.rs".to_string()),
1875            })
1876        );
1877
1878        assert_eq!(
1879            MentionCompletion::try_parse("Lorem @file main.rs ", 0, &supported_modes),
1880            Some(MentionCompletion {
1881                source_range: 6..19,
1882                mode: Some(PromptContextType::File),
1883                argument: Some("main.rs".to_string()),
1884            })
1885        );
1886
1887        assert_eq!(
1888            MentionCompletion::try_parse("Lorem @file main.rs Ipsum", 0, &supported_modes),
1889            Some(MentionCompletion {
1890                source_range: 6..19,
1891                mode: Some(PromptContextType::File),
1892                argument: Some("main.rs".to_string()),
1893            })
1894        );
1895
1896        assert_eq!(
1897            MentionCompletion::try_parse("Lorem @main", 0, &supported_modes),
1898            Some(MentionCompletion {
1899                source_range: 6..11,
1900                mode: None,
1901                argument: Some("main".to_string()),
1902            })
1903        );
1904
1905        assert_eq!(
1906            MentionCompletion::try_parse("Lorem @main ", 0, &supported_modes),
1907            Some(MentionCompletion {
1908                source_range: 6..12,
1909                mode: None,
1910                argument: Some("main".to_string()),
1911            })
1912        );
1913
1914        assert_eq!(
1915            MentionCompletion::try_parse("Lorem @main m", 0, &supported_modes),
1916            None
1917        );
1918
1919        assert_eq!(
1920            MentionCompletion::try_parse("test@", 0, &supported_modes),
1921            None
1922        );
1923
1924        // Allowed non-file mentions
1925
1926        assert_eq!(
1927            MentionCompletion::try_parse("Lorem @symbol main", 0, &supported_modes),
1928            Some(MentionCompletion {
1929                source_range: 6..18,
1930                mode: Some(PromptContextType::Symbol),
1931                argument: Some("main".to_string()),
1932            })
1933        );
1934
1935        assert_eq!(
1936            MentionCompletion::try_parse(
1937                "Lorem @symbol agent_ui::completion_provider",
1938                0,
1939                &supported_modes
1940            ),
1941            Some(MentionCompletion {
1942                source_range: 6..43,
1943                mode: Some(PromptContextType::Symbol),
1944                argument: Some("agent_ui::completion_provider".to_string()),
1945            })
1946        );
1947
1948        // Disallowed non-file mentions
1949        assert_eq!(
1950            MentionCompletion::try_parse("Lorem @symbol main", 0, &[PromptContextType::File]),
1951            None
1952        );
1953
1954        assert_eq!(
1955            MentionCompletion::try_parse("Lorem@symbol", 0, &supported_modes),
1956            None,
1957            "Should not parse mention inside word"
1958        );
1959
1960        assert_eq!(
1961            MentionCompletion::try_parse("Lorem @ file", 0, &supported_modes),
1962            None,
1963            "Should not parse with a space after @"
1964        );
1965
1966        assert_eq!(
1967            MentionCompletion::try_parse("@ file", 0, &supported_modes),
1968            None,
1969            "Should not parse with a space after @ at the start of the line"
1970        );
1971    }
1972
1973    #[gpui::test]
1974    async fn test_filter_sessions_by_query(cx: &mut TestAppContext) {
1975        let mut alpha = AgentSessionInfo::new("session-alpha");
1976        alpha.title = Some("Alpha Session".into());
1977        let mut beta = AgentSessionInfo::new("session-beta");
1978        beta.title = Some("Beta Session".into());
1979
1980        let sessions = vec![alpha.clone(), beta];
1981
1982        let task = {
1983            let mut app = cx.app.borrow_mut();
1984            filter_sessions_by_query(
1985                "Alpha".into(),
1986                Arc::new(AtomicBool::default()),
1987                sessions,
1988                &mut app,
1989            )
1990        };
1991
1992        let results = task.await;
1993        assert_eq!(results.len(), 1);
1994        assert_eq!(results[0].session_id, alpha.session_id);
1995    }
1996}