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 acp_thread::MentionUri;
   8use agent::{DbThreadMetadata, ThreadStore};
   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, 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(DbThreadMetadata),
 136    RecentThread(DbThreadMetadata),
 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 thread_title(thread: &DbThreadMetadata) -> SharedString {
 162    if thread.title.is_empty() {
 163        "New Thread".into()
 164    } else {
 165        thread.title.clone()
 166    }
 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    thread_store: Entity<ThreadStore>,
 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        thread_store: Entity<ThreadStore>,
 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            thread_store,
 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: DbThreadMetadata,
 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 = thread_title(&thread_entry);
 267        let uri = MentionUri::Thread {
 268            id: thread_entry.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                let search_threads_task =
 652                    search_threads(query, cancellation_flag, &self.thread_store, cx);
 653                cx.background_spawn(async move {
 654                    search_threads_task
 655                        .await
 656                        .into_iter()
 657                        .map(Match::Thread)
 658                        .collect()
 659                })
 660            }
 661
 662            Some(PromptContextType::Fetch) => {
 663                if !query.is_empty() {
 664                    Task::ready(vec![Match::Fetch(query.into())])
 665                } else {
 666                    Task::ready(Vec::new())
 667                }
 668            }
 669
 670            Some(PromptContextType::Rules) => {
 671                if let Some(prompt_store) = self.prompt_store.as_ref() {
 672                    let search_rules_task =
 673                        search_rules(query, cancellation_flag, prompt_store, cx);
 674                    cx.background_spawn(async move {
 675                        search_rules_task
 676                            .await
 677                            .into_iter()
 678                            .map(Match::Rules)
 679                            .collect::<Vec<_>>()
 680                    })
 681                } else {
 682                    Task::ready(Vec::new())
 683                }
 684            }
 685
 686            None if query.is_empty() => {
 687                let mut matches = self.recent_context_picker_entries(&workspace, cx);
 688
 689                matches.extend(
 690                    self.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                );
 699
 700                Task::ready(matches)
 701            }
 702            None => {
 703                let executor = cx.background_executor().clone();
 704
 705                let search_files_task =
 706                    search_files(query.clone(), cancellation_flag, &workspace, cx);
 707
 708                let entries = self.available_context_picker_entries(&workspace, cx);
 709                let entry_candidates = entries
 710                    .iter()
 711                    .enumerate()
 712                    .map(|(ix, entry)| StringMatchCandidate::new(ix, entry.keyword()))
 713                    .collect::<Vec<_>>();
 714
 715                cx.background_spawn(async move {
 716                    let mut matches = search_files_task
 717                        .await
 718                        .into_iter()
 719                        .map(Match::File)
 720                        .collect::<Vec<_>>();
 721
 722                    let entry_matches = fuzzy::match_strings(
 723                        &entry_candidates,
 724                        &query,
 725                        false,
 726                        true,
 727                        100,
 728                        &Arc::new(AtomicBool::default()),
 729                        executor,
 730                    )
 731                    .await;
 732
 733                    matches.extend(entry_matches.into_iter().map(|mat| {
 734                        Match::Entry(EntryMatch {
 735                            entry: entries[mat.candidate_id],
 736                            mat: Some(mat),
 737                        })
 738                    }));
 739
 740                    matches.sort_by(|a, b| {
 741                        b.score()
 742                            .partial_cmp(&a.score())
 743                            .unwrap_or(std::cmp::Ordering::Equal)
 744                    });
 745
 746                    matches
 747                })
 748            }
 749        }
 750    }
 751
 752    fn recent_context_picker_entries(
 753        &self,
 754        workspace: &Entity<Workspace>,
 755        cx: &mut App,
 756    ) -> Vec<Match> {
 757        let mut recent = Vec::with_capacity(6);
 758
 759        let mut mentions = self
 760            .mention_set
 761            .read_with(cx, |store, _cx| store.mentions());
 762        let workspace = workspace.read(cx);
 763        let project = workspace.project().read(cx);
 764        let include_root_name = workspace.visible_worktrees(cx).count() > 1;
 765
 766        if let Some(agent_panel) = workspace.panel::<AgentPanel>(cx)
 767            && let Some(thread) = agent_panel.read(cx).active_agent_thread(cx)
 768        {
 769            let thread = thread.read(cx);
 770            mentions.insert(MentionUri::Thread {
 771                id: thread.session_id().clone(),
 772                name: thread.title().into(),
 773            });
 774        }
 775
 776        recent.extend(
 777            workspace
 778                .recent_navigation_history_iter(cx)
 779                .filter(|(_, abs_path)| {
 780                    abs_path.as_ref().is_none_or(|path| {
 781                        !mentions.contains(&MentionUri::File {
 782                            abs_path: path.clone(),
 783                        })
 784                    })
 785                })
 786                .take(4)
 787                .filter_map(|(project_path, _)| {
 788                    project
 789                        .worktree_for_id(project_path.worktree_id, cx)
 790                        .map(|worktree| {
 791                            let path_prefix = if include_root_name {
 792                                worktree.read(cx).root_name().into()
 793                            } else {
 794                                RelPath::empty().into()
 795                            };
 796                            Match::File(FileMatch {
 797                                mat: fuzzy::PathMatch {
 798                                    score: 1.,
 799                                    positions: Vec::new(),
 800                                    worktree_id: project_path.worktree_id.to_usize(),
 801                                    path: project_path.path,
 802                                    path_prefix,
 803                                    is_dir: false,
 804                                    distance_to_relative_ancestor: 0,
 805                                },
 806                                is_recent: true,
 807                            })
 808                        })
 809                }),
 810        );
 811
 812        if self.source.supports_context(PromptContextType::Thread, cx) {
 813            const RECENT_COUNT: usize = 2;
 814            let threads = self
 815                .thread_store
 816                .read(cx)
 817                .entries()
 818                .filter(|thread| {
 819                    let uri = MentionUri::Thread {
 820                        id: thread.id.clone(),
 821                        name: thread_title(thread).to_string(),
 822                    };
 823                    !mentions.contains(&uri)
 824                })
 825                .take(RECENT_COUNT)
 826                .collect::<Vec<_>>();
 827
 828            recent.extend(threads.into_iter().map(Match::RecentThread));
 829        }
 830
 831        recent
 832    }
 833
 834    fn available_context_picker_entries(
 835        &self,
 836        workspace: &Entity<Workspace>,
 837        cx: &mut App,
 838    ) -> Vec<PromptContextEntry> {
 839        let mut entries = vec![
 840            PromptContextEntry::Mode(PromptContextType::File),
 841            PromptContextEntry::Mode(PromptContextType::Symbol),
 842        ];
 843
 844        if self.source.supports_context(PromptContextType::Thread, cx) {
 845            entries.push(PromptContextEntry::Mode(PromptContextType::Thread));
 846        }
 847
 848        let has_selection = workspace
 849            .read(cx)
 850            .active_item(cx)
 851            .and_then(|item| item.downcast::<Editor>())
 852            .is_some_and(|editor| {
 853                editor.update(cx, |editor, cx| {
 854                    editor.has_non_empty_selection(&editor.display_snapshot(cx))
 855                })
 856            });
 857        if has_selection {
 858            entries.push(PromptContextEntry::Action(
 859                PromptContextAction::AddSelections,
 860            ));
 861        }
 862
 863        if self.prompt_store.is_some() && self.source.supports_context(PromptContextType::Rules, cx)
 864        {
 865            entries.push(PromptContextEntry::Mode(PromptContextType::Rules));
 866        }
 867
 868        if self.source.supports_context(PromptContextType::Fetch, cx) {
 869            entries.push(PromptContextEntry::Mode(PromptContextType::Fetch));
 870        }
 871
 872        entries
 873    }
 874}
 875
 876impl<T: PromptCompletionProviderDelegate> CompletionProvider for PromptCompletionProvider<T> {
 877    fn completions(
 878        &self,
 879        _excerpt_id: ExcerptId,
 880        buffer: &Entity<Buffer>,
 881        buffer_position: Anchor,
 882        _trigger: CompletionContext,
 883        window: &mut Window,
 884        cx: &mut Context<Editor>,
 885    ) -> Task<Result<Vec<CompletionResponse>>> {
 886        let state = buffer.update(cx, |buffer, cx| {
 887            let position = buffer_position.to_point(buffer);
 888            let line_start = Point::new(position.row, 0);
 889            let offset_to_line = buffer.point_to_offset(line_start);
 890            let mut lines = buffer.text_for_range(line_start..position).lines();
 891            let line = lines.next()?;
 892            PromptCompletion::try_parse(line, offset_to_line, &self.source.supported_modes(cx))
 893        });
 894        let Some(state) = state else {
 895            return Task::ready(Ok(Vec::new()));
 896        };
 897
 898        let Some(workspace) = self.workspace.upgrade() else {
 899            return Task::ready(Ok(Vec::new()));
 900        };
 901
 902        let project = workspace.read(cx).project().clone();
 903        let snapshot = buffer.read(cx).snapshot();
 904        let source_range = snapshot.anchor_before(state.source_range().start)
 905            ..snapshot.anchor_after(state.source_range().end);
 906
 907        let source = self.source.clone();
 908        let editor = self.editor.clone();
 909        let mention_set = self.mention_set.downgrade();
 910        match state {
 911            PromptCompletion::SlashCommand(SlashCommandCompletion {
 912                command, argument, ..
 913            }) => {
 914                let search_task = self.search_slash_commands(command.unwrap_or_default(), cx);
 915                cx.background_spawn(async move {
 916                    let completions = search_task
 917                        .await
 918                        .into_iter()
 919                        .map(|command| {
 920                            let new_text = if let Some(argument) = argument.as_ref() {
 921                                format!("/{} {}", command.name, argument)
 922                            } else {
 923                                format!("/{} ", command.name)
 924                            };
 925
 926                            let is_missing_argument =
 927                                command.requires_argument && argument.is_none();
 928                            Completion {
 929                                replace_range: source_range.clone(),
 930                                new_text,
 931                                label: CodeLabel::plain(command.name.to_string(), None),
 932                                documentation: Some(CompletionDocumentation::MultiLinePlainText(
 933                                    command.description.into(),
 934                                )),
 935                                source: project::CompletionSource::Custom,
 936                                icon_path: None,
 937                                match_start: None,
 938                                snippet_deduplication_key: None,
 939                                insert_text_mode: None,
 940                                confirm: Some(Arc::new({
 941                                    let source = source.clone();
 942                                    move |intent, _window, cx| {
 943                                        if !is_missing_argument {
 944                                            cx.defer({
 945                                                let source = source.clone();
 946                                                move |cx| match intent {
 947                                                    CompletionIntent::Complete
 948                                                    | CompletionIntent::CompleteWithInsert
 949                                                    | CompletionIntent::CompleteWithReplace => {
 950                                                        source.confirm_command(cx);
 951                                                    }
 952                                                    CompletionIntent::Compose => {}
 953                                                }
 954                                            });
 955                                        }
 956                                        false
 957                                    }
 958                                })),
 959                            }
 960                        })
 961                        .collect();
 962
 963                    Ok(vec![CompletionResponse {
 964                        completions,
 965                        display_options: CompletionDisplayOptions {
 966                            dynamic_width: true,
 967                        },
 968                        // Since this does its own filtering (see `filter_completions()` returns false),
 969                        // there is no benefit to computing whether this set of completions is incomplete.
 970                        is_incomplete: true,
 971                    }])
 972                })
 973            }
 974            PromptCompletion::Mention(MentionCompletion { mode, argument, .. }) => {
 975                let query = argument.unwrap_or_default();
 976                let search_task =
 977                    self.search_mentions(mode, query, Arc::<AtomicBool>::default(), cx);
 978
 979                // Calculate maximum characters available for the full label (file_name + space + directory)
 980                // based on maximum menu width after accounting for padding, spacing, and icon width
 981                let label_max_chars = {
 982                    // Base06 left padding + Base06 gap + Base06 right padding + icon width
 983                    let used_pixels = DynamicSpacing::Base06.px(cx) * 3.0
 984                        + IconSize::XSmall.rems() * window.rem_size();
 985
 986                    let style = window.text_style();
 987                    let font_id = window.text_system().resolve_font(&style.font());
 988                    let font_size = TextSize::Small.rems(cx).to_pixels(window.rem_size());
 989
 990                    // Fallback em_width of 10px matches file_finder.rs fallback for TextSize::Small
 991                    let em_width = cx
 992                        .text_system()
 993                        .em_width(font_id, font_size)
 994                        .unwrap_or(px(10.0));
 995
 996                    // Calculate available pixels for text (file_name + directory)
 997                    // Using max width since dynamic_width allows the menu to expand up to this
 998                    let available_pixels = COMPLETION_MENU_MAX_WIDTH - used_pixels;
 999
1000                    // Convert to character count (total available for file_name + directory)
1001                    (f32::from(available_pixels) / f32::from(em_width)) as usize
1002                };
1003
1004                cx.spawn(async move |_, cx| {
1005                    let matches = search_task.await;
1006
1007                    let completions = cx.update(|cx| {
1008                        matches
1009                            .into_iter()
1010                            .filter_map(|mat| match mat {
1011                                Match::File(FileMatch { mat, is_recent }) => {
1012                                    let project_path = ProjectPath {
1013                                        worktree_id: WorktreeId::from_usize(mat.worktree_id),
1014                                        path: mat.path.clone(),
1015                                    };
1016
1017                                    // If path is empty, this means we're matching with the root directory itself
1018                                    // so we use the path_prefix as the name
1019                                    let path_prefix = if mat.path.is_empty() {
1020                                        project
1021                                            .read(cx)
1022                                            .worktree_for_id(project_path.worktree_id, cx)
1023                                            .map(|wt| wt.read(cx).root_name().into())
1024                                            .unwrap_or_else(|| mat.path_prefix.clone())
1025                                    } else {
1026                                        mat.path_prefix.clone()
1027                                    };
1028
1029                                    Self::completion_for_path(
1030                                        project_path,
1031                                        &path_prefix,
1032                                        is_recent,
1033                                        mat.is_dir,
1034                                        source_range.clone(),
1035                                        source.clone(),
1036                                        editor.clone(),
1037                                        mention_set.clone(),
1038                                        workspace.clone(),
1039                                        project.clone(),
1040                                        label_max_chars,
1041                                        cx,
1042                                    )
1043                                }
1044
1045                                Match::Symbol(SymbolMatch { symbol, .. }) => {
1046                                    Self::completion_for_symbol(
1047                                        symbol,
1048                                        source_range.clone(),
1049                                        source.clone(),
1050                                        editor.clone(),
1051                                        mention_set.clone(),
1052                                        workspace.clone(),
1053                                        label_max_chars,
1054                                        cx,
1055                                    )
1056                                }
1057
1058                                Match::Thread(thread) => Some(Self::completion_for_thread(
1059                                    thread,
1060                                    source_range.clone(),
1061                                    false,
1062                                    source.clone(),
1063                                    editor.clone(),
1064                                    mention_set.clone(),
1065                                    workspace.clone(),
1066                                    cx,
1067                                )),
1068
1069                                Match::RecentThread(thread) => Some(Self::completion_for_thread(
1070                                    thread,
1071                                    source_range.clone(),
1072                                    true,
1073                                    source.clone(),
1074                                    editor.clone(),
1075                                    mention_set.clone(),
1076                                    workspace.clone(),
1077                                    cx,
1078                                )),
1079
1080                                Match::Rules(user_rules) => Some(Self::completion_for_rules(
1081                                    user_rules,
1082                                    source_range.clone(),
1083                                    source.clone(),
1084                                    editor.clone(),
1085                                    mention_set.clone(),
1086                                    workspace.clone(),
1087                                    cx,
1088                                )),
1089
1090                                Match::Fetch(url) => Self::completion_for_fetch(
1091                                    source_range.clone(),
1092                                    url,
1093                                    source.clone(),
1094                                    editor.clone(),
1095                                    mention_set.clone(),
1096                                    workspace.clone(),
1097                                    cx,
1098                                ),
1099
1100                                Match::Entry(EntryMatch { entry, .. }) => {
1101                                    Self::completion_for_entry(
1102                                        entry,
1103                                        source_range.clone(),
1104                                        editor.clone(),
1105                                        mention_set.clone(),
1106                                        &workspace,
1107                                        cx,
1108                                    )
1109                                }
1110                            })
1111                            .collect::<Vec<_>>()
1112                    });
1113
1114                    Ok(vec![CompletionResponse {
1115                        completions,
1116                        display_options: CompletionDisplayOptions {
1117                            dynamic_width: true,
1118                        },
1119                        // Since this does its own filtering (see `filter_completions()` returns false),
1120                        // there is no benefit to computing whether this set of completions is incomplete.
1121                        is_incomplete: true,
1122                    }])
1123                })
1124            }
1125        }
1126    }
1127
1128    fn is_completion_trigger(
1129        &self,
1130        buffer: &Entity<language::Buffer>,
1131        position: language::Anchor,
1132        _text: &str,
1133        _trigger_in_words: bool,
1134        cx: &mut Context<Editor>,
1135    ) -> bool {
1136        let buffer = buffer.read(cx);
1137        let position = position.to_point(buffer);
1138        let line_start = Point::new(position.row, 0);
1139        let offset_to_line = buffer.point_to_offset(line_start);
1140        let mut lines = buffer.text_for_range(line_start..position).lines();
1141        if let Some(line) = lines.next() {
1142            PromptCompletion::try_parse(line, offset_to_line, &self.source.supported_modes(cx))
1143                .filter(|completion| {
1144                    // Right now we don't support completing arguments of slash commands
1145                    let is_slash_command_with_argument = matches!(
1146                        completion,
1147                        PromptCompletion::SlashCommand(SlashCommandCompletion {
1148                            argument: Some(_),
1149                            ..
1150                        })
1151                    );
1152                    !is_slash_command_with_argument
1153                })
1154                .map(|completion| {
1155                    completion.source_range().start <= offset_to_line + position.column as usize
1156                        && completion.source_range().end
1157                            >= offset_to_line + position.column as usize
1158                })
1159                .unwrap_or(false)
1160        } else {
1161            false
1162        }
1163    }
1164
1165    fn sort_completions(&self) -> bool {
1166        false
1167    }
1168
1169    fn filter_completions(&self) -> bool {
1170        false
1171    }
1172}
1173
1174fn confirm_completion_callback<T: PromptCompletionProviderDelegate>(
1175    crease_text: SharedString,
1176    start: Anchor,
1177    content_len: usize,
1178    mention_uri: MentionUri,
1179    source: Arc<T>,
1180    editor: WeakEntity<Editor>,
1181    mention_set: WeakEntity<MentionSet>,
1182    workspace: Entity<Workspace>,
1183) -> Arc<dyn Fn(CompletionIntent, &mut Window, &mut App) -> bool + Send + Sync> {
1184    Arc::new(move |_, window, cx| {
1185        let source = source.clone();
1186        let editor = editor.clone();
1187        let mention_set = mention_set.clone();
1188        let crease_text = crease_text.clone();
1189        let mention_uri = mention_uri.clone();
1190        let workspace = workspace.clone();
1191        window.defer(cx, move |window, cx| {
1192            if let Some(editor) = editor.upgrade() {
1193                mention_set
1194                    .clone()
1195                    .update(cx, |mention_set, cx| {
1196                        mention_set
1197                            .confirm_mention_completion(
1198                                crease_text,
1199                                start,
1200                                content_len,
1201                                mention_uri,
1202                                source.supports_images(cx),
1203                                editor,
1204                                &workspace,
1205                                window,
1206                                cx,
1207                            )
1208                            .detach();
1209                    })
1210                    .ok();
1211            }
1212        });
1213        false
1214    })
1215}
1216
1217#[derive(Debug, PartialEq)]
1218enum PromptCompletion {
1219    SlashCommand(SlashCommandCompletion),
1220    Mention(MentionCompletion),
1221}
1222
1223impl PromptCompletion {
1224    fn source_range(&self) -> Range<usize> {
1225        match self {
1226            Self::SlashCommand(completion) => completion.source_range.clone(),
1227            Self::Mention(completion) => completion.source_range.clone(),
1228        }
1229    }
1230
1231    fn try_parse(
1232        line: &str,
1233        offset_to_line: usize,
1234        supported_modes: &[PromptContextType],
1235    ) -> Option<Self> {
1236        if line.contains('@') {
1237            if let Some(mention) =
1238                MentionCompletion::try_parse(line, offset_to_line, supported_modes)
1239            {
1240                return Some(Self::Mention(mention));
1241            }
1242        }
1243        SlashCommandCompletion::try_parse(line, offset_to_line).map(Self::SlashCommand)
1244    }
1245}
1246
1247#[derive(Debug, Default, PartialEq)]
1248pub struct SlashCommandCompletion {
1249    pub source_range: Range<usize>,
1250    pub command: Option<String>,
1251    pub argument: Option<String>,
1252}
1253
1254impl SlashCommandCompletion {
1255    pub fn try_parse(line: &str, offset_to_line: usize) -> Option<Self> {
1256        // If we decide to support commands that are not at the beginning of the prompt, we can remove this check
1257        if !line.starts_with('/') || offset_to_line != 0 {
1258            return None;
1259        }
1260
1261        let (prefix, last_command) = line.rsplit_once('/')?;
1262        if prefix.chars().last().is_some_and(|c| !c.is_whitespace())
1263            || last_command.starts_with(char::is_whitespace)
1264        {
1265            return None;
1266        }
1267
1268        let mut argument = None;
1269        let mut command = None;
1270        if let Some((command_text, args)) = last_command.split_once(char::is_whitespace) {
1271            if !args.is_empty() {
1272                argument = Some(args.trim_end().to_string());
1273            }
1274            command = Some(command_text.to_string());
1275        } else if !last_command.is_empty() {
1276            command = Some(last_command.to_string());
1277        };
1278
1279        Some(Self {
1280            source_range: prefix.len() + offset_to_line
1281                ..line
1282                    .rfind(|c: char| !c.is_whitespace())
1283                    .unwrap_or_else(|| line.len())
1284                    + 1
1285                    + offset_to_line,
1286            command,
1287            argument,
1288        })
1289    }
1290}
1291
1292#[derive(Debug, Default, PartialEq)]
1293struct MentionCompletion {
1294    source_range: Range<usize>,
1295    mode: Option<PromptContextType>,
1296    argument: Option<String>,
1297}
1298
1299impl MentionCompletion {
1300    fn try_parse(
1301        line: &str,
1302        offset_to_line: usize,
1303        supported_modes: &[PromptContextType],
1304    ) -> Option<Self> {
1305        let last_mention_start = line.rfind('@')?;
1306
1307        // No whitespace immediately after '@'
1308        if line[last_mention_start + 1..]
1309            .chars()
1310            .next()
1311            .is_some_and(|c| c.is_whitespace())
1312        {
1313            return None;
1314        }
1315
1316        //  Must be a word boundary before '@'
1317        if last_mention_start > 0
1318            && line[..last_mention_start]
1319                .chars()
1320                .last()
1321                .is_some_and(|c| !c.is_whitespace())
1322        {
1323            return None;
1324        }
1325
1326        let rest_of_line = &line[last_mention_start + 1..];
1327
1328        let mut mode = None;
1329        let mut argument = None;
1330
1331        let mut parts = rest_of_line.split_whitespace();
1332        let mut end = last_mention_start + 1;
1333
1334        if let Some(mode_text) = parts.next() {
1335            // Safe since we check no leading whitespace above
1336            end += mode_text.len();
1337
1338            if let Some(parsed_mode) = PromptContextType::try_from(mode_text).ok()
1339                && supported_modes.contains(&parsed_mode)
1340            {
1341                mode = Some(parsed_mode);
1342            } else {
1343                argument = Some(mode_text.to_string());
1344            }
1345            match rest_of_line[mode_text.len()..].find(|c: char| !c.is_whitespace()) {
1346                Some(whitespace_count) => {
1347                    if let Some(argument_text) = parts.next() {
1348                        // If mode wasn't recognized but we have an argument, don't suggest completions
1349                        // (e.g. '@something word')
1350                        if mode.is_none() && !argument_text.is_empty() {
1351                            return None;
1352                        }
1353
1354                        argument = Some(argument_text.to_string());
1355                        end += whitespace_count + argument_text.len();
1356                    }
1357                }
1358                None => {
1359                    // Rest of line is entirely whitespace
1360                    end += rest_of_line.len() - mode_text.len();
1361                }
1362            }
1363        }
1364
1365        Some(Self {
1366            source_range: last_mention_start + offset_to_line..end + offset_to_line,
1367            mode,
1368            argument,
1369        })
1370    }
1371}
1372
1373pub(crate) fn search_files(
1374    query: String,
1375    cancellation_flag: Arc<AtomicBool>,
1376    workspace: &Entity<Workspace>,
1377    cx: &App,
1378) -> Task<Vec<FileMatch>> {
1379    if query.is_empty() {
1380        let workspace = workspace.read(cx);
1381        let project = workspace.project().read(cx);
1382        let visible_worktrees = workspace.visible_worktrees(cx).collect::<Vec<_>>();
1383        let include_root_name = visible_worktrees.len() > 1;
1384
1385        let recent_matches = workspace
1386            .recent_navigation_history(Some(10), cx)
1387            .into_iter()
1388            .map(|(project_path, _)| {
1389                let path_prefix = if include_root_name {
1390                    project
1391                        .worktree_for_id(project_path.worktree_id, cx)
1392                        .map(|wt| wt.read(cx).root_name().into())
1393                        .unwrap_or_else(|| RelPath::empty().into())
1394                } else {
1395                    RelPath::empty().into()
1396                };
1397
1398                FileMatch {
1399                    mat: PathMatch {
1400                        score: 0.,
1401                        positions: Vec::new(),
1402                        worktree_id: project_path.worktree_id.to_usize(),
1403                        path: project_path.path,
1404                        path_prefix,
1405                        distance_to_relative_ancestor: 0,
1406                        is_dir: false,
1407                    },
1408                    is_recent: true,
1409                }
1410            });
1411
1412        let file_matches = visible_worktrees.into_iter().flat_map(|worktree| {
1413            let worktree = worktree.read(cx);
1414            let path_prefix: Arc<RelPath> = if include_root_name {
1415                worktree.root_name().into()
1416            } else {
1417                RelPath::empty().into()
1418            };
1419            worktree.entries(false, 0).map(move |entry| FileMatch {
1420                mat: PathMatch {
1421                    score: 0.,
1422                    positions: Vec::new(),
1423                    worktree_id: worktree.id().to_usize(),
1424                    path: entry.path.clone(),
1425                    path_prefix: path_prefix.clone(),
1426                    distance_to_relative_ancestor: 0,
1427                    is_dir: entry.is_dir(),
1428                },
1429                is_recent: false,
1430            })
1431        });
1432
1433        Task::ready(recent_matches.chain(file_matches).collect())
1434    } else {
1435        let worktrees = workspace.read(cx).visible_worktrees(cx).collect::<Vec<_>>();
1436        let include_root_name = worktrees.len() > 1;
1437        let candidate_sets = worktrees
1438            .into_iter()
1439            .map(|worktree| {
1440                let worktree = worktree.read(cx);
1441
1442                PathMatchCandidateSet {
1443                    snapshot: worktree.snapshot(),
1444                    include_ignored: worktree.root_entry().is_some_and(|entry| entry.is_ignored),
1445                    include_root_name,
1446                    candidates: project::Candidates::Entries,
1447                }
1448            })
1449            .collect::<Vec<_>>();
1450
1451        let executor = cx.background_executor().clone();
1452        cx.foreground_executor().spawn(async move {
1453            fuzzy::match_path_sets(
1454                candidate_sets.as_slice(),
1455                query.as_str(),
1456                &None,
1457                false,
1458                100,
1459                &cancellation_flag,
1460                executor,
1461            )
1462            .await
1463            .into_iter()
1464            .map(|mat| FileMatch {
1465                mat,
1466                is_recent: false,
1467            })
1468            .collect::<Vec<_>>()
1469        })
1470    }
1471}
1472
1473pub(crate) fn search_symbols(
1474    query: String,
1475    cancellation_flag: Arc<AtomicBool>,
1476    workspace: &Entity<Workspace>,
1477    cx: &mut App,
1478) -> Task<Vec<SymbolMatch>> {
1479    let symbols_task = workspace.update(cx, |workspace, cx| {
1480        workspace
1481            .project()
1482            .update(cx, |project, cx| project.symbols(&query, cx))
1483    });
1484    let project = workspace.read(cx).project().clone();
1485    cx.spawn(async move |cx| {
1486        let Some(symbols) = symbols_task.await.log_err() else {
1487            return Vec::new();
1488        };
1489        let (visible_match_candidates, external_match_candidates): (Vec<_>, Vec<_>) = project
1490            .update(cx, |project, cx| {
1491                symbols
1492                    .iter()
1493                    .enumerate()
1494                    .map(|(id, symbol)| StringMatchCandidate::new(id, symbol.label.filter_text()))
1495                    .partition(|candidate| match &symbols[candidate.id].path {
1496                        SymbolLocation::InProject(project_path) => project
1497                            .entry_for_path(project_path, cx)
1498                            .is_some_and(|e| !e.is_ignored),
1499                        SymbolLocation::OutsideProject { .. } => false,
1500                    })
1501            });
1502
1503        const MAX_MATCHES: usize = 100;
1504        let mut visible_matches = cx.background_executor().block(fuzzy::match_strings(
1505            &visible_match_candidates,
1506            &query,
1507            false,
1508            true,
1509            MAX_MATCHES,
1510            &cancellation_flag,
1511            cx.background_executor().clone(),
1512        ));
1513        let mut external_matches = cx.background_executor().block(fuzzy::match_strings(
1514            &external_match_candidates,
1515            &query,
1516            false,
1517            true,
1518            MAX_MATCHES - visible_matches.len().min(MAX_MATCHES),
1519            &cancellation_flag,
1520            cx.background_executor().clone(),
1521        ));
1522        let sort_key_for_match = |mat: &StringMatch| {
1523            let symbol = &symbols[mat.candidate_id];
1524            (Reverse(OrderedFloat(mat.score)), symbol.label.filter_text())
1525        };
1526
1527        visible_matches.sort_unstable_by_key(sort_key_for_match);
1528        external_matches.sort_unstable_by_key(sort_key_for_match);
1529        let mut matches = visible_matches;
1530        matches.append(&mut external_matches);
1531
1532        matches
1533            .into_iter()
1534            .map(|mut mat| {
1535                let symbol = symbols[mat.candidate_id].clone();
1536                let filter_start = symbol.label.filter_range.start;
1537                for position in &mut mat.positions {
1538                    *position += filter_start;
1539                }
1540                SymbolMatch { symbol }
1541            })
1542            .collect()
1543    })
1544}
1545
1546pub(crate) fn search_threads(
1547    query: String,
1548    cancellation_flag: Arc<AtomicBool>,
1549    thread_store: &Entity<ThreadStore>,
1550    cx: &mut App,
1551) -> Task<Vec<DbThreadMetadata>> {
1552    let threads = thread_store.read(cx).entries().collect();
1553    if query.is_empty() {
1554        return Task::ready(threads);
1555    }
1556
1557    let executor = cx.background_executor().clone();
1558    cx.background_spawn(async move {
1559        let candidates = threads
1560            .iter()
1561            .enumerate()
1562            .map(|(id, thread)| StringMatchCandidate::new(id, thread_title(thread).as_ref()))
1563            .collect::<Vec<_>>();
1564        let matches = fuzzy::match_strings(
1565            &candidates,
1566            &query,
1567            false,
1568            true,
1569            100,
1570            &cancellation_flag,
1571            executor,
1572        )
1573        .await;
1574
1575        matches
1576            .into_iter()
1577            .map(|mat| threads[mat.candidate_id].clone())
1578            .collect()
1579    })
1580}
1581
1582pub(crate) fn search_rules(
1583    query: String,
1584    cancellation_flag: Arc<AtomicBool>,
1585    prompt_store: &Entity<PromptStore>,
1586    cx: &mut App,
1587) -> Task<Vec<RulesContextEntry>> {
1588    let search_task = prompt_store.read(cx).search(query, cancellation_flag, cx);
1589    cx.background_spawn(async move {
1590        search_task
1591            .await
1592            .into_iter()
1593            .flat_map(|metadata| {
1594                // Default prompts are filtered out as they are automatically included.
1595                if metadata.default {
1596                    None
1597                } else {
1598                    Some(RulesContextEntry {
1599                        prompt_id: metadata.id.as_user()?,
1600                        title: metadata.title?,
1601                    })
1602                }
1603            })
1604            .collect::<Vec<_>>()
1605    })
1606}
1607
1608pub struct SymbolMatch {
1609    pub symbol: Symbol,
1610}
1611
1612pub struct FileMatch {
1613    pub mat: PathMatch,
1614    pub is_recent: bool,
1615}
1616
1617pub fn extract_file_name_and_directory(
1618    path: &RelPath,
1619    path_prefix: &RelPath,
1620    path_style: PathStyle,
1621) -> (SharedString, Option<SharedString>) {
1622    // If path is empty, this means we're matching with the root directory itself
1623    // so we use the path_prefix as the name
1624    if path.is_empty() && !path_prefix.is_empty() {
1625        return (path_prefix.display(path_style).to_string().into(), None);
1626    }
1627
1628    let full_path = path_prefix.join(path);
1629    let file_name = full_path.file_name().unwrap_or_default();
1630    let display_path = full_path.display(path_style);
1631    let (directory, file_name) = display_path.split_at(display_path.len() - file_name.len());
1632    (
1633        file_name.to_string().into(),
1634        Some(SharedString::new(directory)).filter(|dir| !dir.is_empty()),
1635    )
1636}
1637
1638fn build_code_label_for_path(
1639    file: &str,
1640    directory: Option<&str>,
1641    line_number: Option<u32>,
1642    label_max_chars: usize,
1643    cx: &App,
1644) -> CodeLabel {
1645    let variable_highlight_id = cx
1646        .theme()
1647        .syntax()
1648        .highlight_id("variable")
1649        .map(HighlightId);
1650    let mut label = CodeLabelBuilder::default();
1651
1652    label.push_str(file, None);
1653    label.push_str(" ", None);
1654
1655    if let Some(directory) = directory {
1656        let file_name_chars = file.chars().count();
1657        // Account for: file_name + space (ellipsis is handled by truncate_and_remove_front)
1658        let directory_max_chars = label_max_chars
1659            .saturating_sub(file_name_chars)
1660            .saturating_sub(1);
1661        let truncated_directory = truncate_and_remove_front(directory, directory_max_chars.max(5));
1662        label.push_str(&truncated_directory, variable_highlight_id);
1663    }
1664    if let Some(line_number) = line_number {
1665        label.push_str(&format!(" L{}", line_number), variable_highlight_id);
1666    }
1667    label.build()
1668}
1669
1670fn selection_ranges(
1671    workspace: &Entity<Workspace>,
1672    cx: &mut App,
1673) -> Vec<(Entity<Buffer>, Range<text::Anchor>)> {
1674    let Some(editor) = workspace
1675        .read(cx)
1676        .active_item(cx)
1677        .and_then(|item| item.act_as::<Editor>(cx))
1678    else {
1679        return Vec::new();
1680    };
1681
1682    editor.update(cx, |editor, cx| {
1683        let selections = editor.selections.all_adjusted(&editor.display_snapshot(cx));
1684
1685        let buffer = editor.buffer().clone().read(cx);
1686        let snapshot = buffer.snapshot(cx);
1687
1688        selections
1689            .into_iter()
1690            .map(|s| snapshot.anchor_after(s.start)..snapshot.anchor_before(s.end))
1691            .flat_map(|range| {
1692                let (start_buffer, start) = buffer.text_anchor_for_position(range.start, cx)?;
1693                let (end_buffer, end) = buffer.text_anchor_for_position(range.end, cx)?;
1694                if start_buffer != end_buffer {
1695                    return None;
1696                }
1697                Some((start_buffer, start..end))
1698            })
1699            .collect::<Vec<_>>()
1700    })
1701}
1702
1703#[cfg(test)]
1704mod tests {
1705    use super::*;
1706
1707    #[test]
1708    fn test_prompt_completion_parse() {
1709        let supported_modes = vec![PromptContextType::File, PromptContextType::Symbol];
1710
1711        assert_eq!(
1712            PromptCompletion::try_parse("/", 0, &supported_modes),
1713            Some(PromptCompletion::SlashCommand(SlashCommandCompletion {
1714                source_range: 0..1,
1715                command: None,
1716                argument: None,
1717            }))
1718        );
1719
1720        assert_eq!(
1721            PromptCompletion::try_parse("@", 0, &supported_modes),
1722            Some(PromptCompletion::Mention(MentionCompletion {
1723                source_range: 0..1,
1724                mode: None,
1725                argument: None,
1726            }))
1727        );
1728
1729        assert_eq!(
1730            PromptCompletion::try_parse("/test @file", 0, &supported_modes),
1731            Some(PromptCompletion::Mention(MentionCompletion {
1732                source_range: 6..11,
1733                mode: Some(PromptContextType::File),
1734                argument: None,
1735            }))
1736        );
1737    }
1738
1739    #[test]
1740    fn test_slash_command_completion_parse() {
1741        assert_eq!(
1742            SlashCommandCompletion::try_parse("/", 0),
1743            Some(SlashCommandCompletion {
1744                source_range: 0..1,
1745                command: None,
1746                argument: None,
1747            })
1748        );
1749
1750        assert_eq!(
1751            SlashCommandCompletion::try_parse("/help", 0),
1752            Some(SlashCommandCompletion {
1753                source_range: 0..5,
1754                command: Some("help".to_string()),
1755                argument: None,
1756            })
1757        );
1758
1759        assert_eq!(
1760            SlashCommandCompletion::try_parse("/help ", 0),
1761            Some(SlashCommandCompletion {
1762                source_range: 0..5,
1763                command: Some("help".to_string()),
1764                argument: None,
1765            })
1766        );
1767
1768        assert_eq!(
1769            SlashCommandCompletion::try_parse("/help arg1", 0),
1770            Some(SlashCommandCompletion {
1771                source_range: 0..10,
1772                command: Some("help".to_string()),
1773                argument: Some("arg1".to_string()),
1774            })
1775        );
1776
1777        assert_eq!(
1778            SlashCommandCompletion::try_parse("/help arg1 arg2", 0),
1779            Some(SlashCommandCompletion {
1780                source_range: 0..15,
1781                command: Some("help".to_string()),
1782                argument: Some("arg1 arg2".to_string()),
1783            })
1784        );
1785
1786        assert_eq!(
1787            SlashCommandCompletion::try_parse("/拿不到命令 拿不到命令 ", 0),
1788            Some(SlashCommandCompletion {
1789                source_range: 0..30,
1790                command: Some("拿不到命令".to_string()),
1791                argument: Some("拿不到命令".to_string()),
1792            })
1793        );
1794
1795        assert_eq!(SlashCommandCompletion::try_parse("Lorem Ipsum", 0), None);
1796
1797        assert_eq!(SlashCommandCompletion::try_parse("Lorem /", 0), None);
1798
1799        assert_eq!(SlashCommandCompletion::try_parse("Lorem /help", 0), None);
1800
1801        assert_eq!(SlashCommandCompletion::try_parse("Lorem/", 0), None);
1802
1803        assert_eq!(SlashCommandCompletion::try_parse("/ ", 0), None);
1804    }
1805
1806    #[test]
1807    fn test_mention_completion_parse() {
1808        let supported_modes = vec![PromptContextType::File, PromptContextType::Symbol];
1809
1810        assert_eq!(
1811            MentionCompletion::try_parse("Lorem Ipsum", 0, &supported_modes),
1812            None
1813        );
1814
1815        assert_eq!(
1816            MentionCompletion::try_parse("Lorem @", 0, &supported_modes),
1817            Some(MentionCompletion {
1818                source_range: 6..7,
1819                mode: None,
1820                argument: None,
1821            })
1822        );
1823
1824        assert_eq!(
1825            MentionCompletion::try_parse("Lorem @file", 0, &supported_modes),
1826            Some(MentionCompletion {
1827                source_range: 6..11,
1828                mode: Some(PromptContextType::File),
1829                argument: None,
1830            })
1831        );
1832
1833        assert_eq!(
1834            MentionCompletion::try_parse("Lorem @file ", 0, &supported_modes),
1835            Some(MentionCompletion {
1836                source_range: 6..12,
1837                mode: Some(PromptContextType::File),
1838                argument: None,
1839            })
1840        );
1841
1842        assert_eq!(
1843            MentionCompletion::try_parse("Lorem @file main.rs", 0, &supported_modes),
1844            Some(MentionCompletion {
1845                source_range: 6..19,
1846                mode: Some(PromptContextType::File),
1847                argument: Some("main.rs".to_string()),
1848            })
1849        );
1850
1851        assert_eq!(
1852            MentionCompletion::try_parse("Lorem @file main.rs ", 0, &supported_modes),
1853            Some(MentionCompletion {
1854                source_range: 6..19,
1855                mode: Some(PromptContextType::File),
1856                argument: Some("main.rs".to_string()),
1857            })
1858        );
1859
1860        assert_eq!(
1861            MentionCompletion::try_parse("Lorem @file main.rs Ipsum", 0, &supported_modes),
1862            Some(MentionCompletion {
1863                source_range: 6..19,
1864                mode: Some(PromptContextType::File),
1865                argument: Some("main.rs".to_string()),
1866            })
1867        );
1868
1869        assert_eq!(
1870            MentionCompletion::try_parse("Lorem @main", 0, &supported_modes),
1871            Some(MentionCompletion {
1872                source_range: 6..11,
1873                mode: None,
1874                argument: Some("main".to_string()),
1875            })
1876        );
1877
1878        assert_eq!(
1879            MentionCompletion::try_parse("Lorem @main ", 0, &supported_modes),
1880            Some(MentionCompletion {
1881                source_range: 6..12,
1882                mode: None,
1883                argument: Some("main".to_string()),
1884            })
1885        );
1886
1887        assert_eq!(
1888            MentionCompletion::try_parse("Lorem @main m", 0, &supported_modes),
1889            None
1890        );
1891
1892        assert_eq!(
1893            MentionCompletion::try_parse("test@", 0, &supported_modes),
1894            None
1895        );
1896
1897        // Allowed non-file mentions
1898
1899        assert_eq!(
1900            MentionCompletion::try_parse("Lorem @symbol main", 0, &supported_modes),
1901            Some(MentionCompletion {
1902                source_range: 6..18,
1903                mode: Some(PromptContextType::Symbol),
1904                argument: Some("main".to_string()),
1905            })
1906        );
1907
1908        // Disallowed non-file mentions
1909        assert_eq!(
1910            MentionCompletion::try_parse("Lorem @symbol main", 0, &[PromptContextType::File]),
1911            None
1912        );
1913
1914        assert_eq!(
1915            MentionCompletion::try_parse("Lorem@symbol", 0, &supported_modes),
1916            None,
1917            "Should not parse mention inside word"
1918        );
1919
1920        assert_eq!(
1921            MentionCompletion::try_parse("Lorem @ file", 0, &supported_modes),
1922            None,
1923            "Should not parse with a space after @"
1924        );
1925
1926        assert_eq!(
1927            MentionCompletion::try_parse("@ file", 0, &supported_modes),
1928            None,
1929            "Should not parse with a space after @ at the start of the line"
1930        );
1931    }
1932}