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 crate::user_slash_command::{self, CommandLoadError, UserSlashCommand};
   9use acp_thread::{AgentSessionInfo, MentionUri};
  10use anyhow::Result;
  11use collections::{HashMap, HashSet};
  12use editor::{
  13    CompletionProvider, Editor, ExcerptId, code_context_menus::COMPLETION_MENU_MAX_WIDTH,
  14};
  15use feature_flags::{FeatureFlagAppExt as _, UserSlashCommandsFeatureFlag};
  16use fuzzy::{PathMatch, StringMatch, StringMatchCandidate};
  17use gpui::{App, BackgroundExecutor, Entity, SharedString, Task, WeakEntity};
  18use language::{Buffer, CodeLabel, CodeLabelBuilder, HighlightId};
  19use lsp::CompletionContext;
  20use ordered_float::OrderedFloat;
  21use project::lsp_store::{CompletionDocumentation, SymbolLocation};
  22use project::{
  23    Completion, CompletionDisplayOptions, CompletionIntent, CompletionResponse, DiagnosticSummary,
  24    PathMatchCandidateSet, Project, ProjectPath, Symbol, WorktreeId,
  25};
  26use prompt_store::{PromptStore, UserPromptId};
  27use rope::Point;
  28use text::{Anchor, ToPoint as _};
  29use ui::IconName;
  30use ui::prelude::*;
  31use util::ResultExt as _;
  32use util::paths::PathStyle;
  33use util::rel_path::RelPath;
  34use util::truncate_and_remove_front;
  35use workspace::Workspace;
  36
  37use crate::AgentPanel;
  38use crate::mention_set::MentionSet;
  39
  40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  41pub(crate) enum PromptContextEntry {
  42    Mode(PromptContextType),
  43    Action(PromptContextAction),
  44}
  45
  46impl PromptContextEntry {
  47    pub fn keyword(&self) -> &'static str {
  48        match self {
  49            Self::Mode(mode) => mode.keyword(),
  50            Self::Action(action) => action.keyword(),
  51        }
  52    }
  53}
  54
  55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  56pub(crate) enum PromptContextType {
  57    File,
  58    Symbol,
  59    Fetch,
  60    Thread,
  61    Rules,
  62    Diagnostics,
  63}
  64
  65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  66pub(crate) enum PromptContextAction {
  67    AddSelections,
  68}
  69
  70impl PromptContextAction {
  71    pub fn keyword(&self) -> &'static str {
  72        match self {
  73            Self::AddSelections => "selection",
  74        }
  75    }
  76
  77    pub fn label(&self) -> &'static str {
  78        match self {
  79            Self::AddSelections => "Selection",
  80        }
  81    }
  82
  83    pub fn icon(&self) -> IconName {
  84        match self {
  85            Self::AddSelections => IconName::Reader,
  86        }
  87    }
  88}
  89
  90impl TryFrom<&str> for PromptContextType {
  91    type Error = String;
  92
  93    fn try_from(value: &str) -> Result<Self, Self::Error> {
  94        match value {
  95            "file" => Ok(Self::File),
  96            "symbol" => Ok(Self::Symbol),
  97            "fetch" => Ok(Self::Fetch),
  98            "thread" => Ok(Self::Thread),
  99            "rule" => Ok(Self::Rules),
 100            "diagnostics" => Ok(Self::Diagnostics),
 101            _ => Err(format!("Invalid context picker mode: {}", value)),
 102        }
 103    }
 104}
 105
 106impl PromptContextType {
 107    pub fn keyword(&self) -> &'static str {
 108        match self {
 109            Self::File => "file",
 110            Self::Symbol => "symbol",
 111            Self::Fetch => "fetch",
 112            Self::Thread => "thread",
 113            Self::Rules => "rule",
 114            Self::Diagnostics => "diagnostics",
 115        }
 116    }
 117
 118    pub fn label(&self) -> &'static str {
 119        match self {
 120            Self::File => "Files & Directories",
 121            Self::Symbol => "Symbols",
 122            Self::Fetch => "Fetch",
 123            Self::Thread => "Threads",
 124            Self::Rules => "Rules",
 125            Self::Diagnostics => "Diagnostics",
 126        }
 127    }
 128
 129    pub fn icon(&self) -> IconName {
 130        match self {
 131            Self::File => IconName::File,
 132            Self::Symbol => IconName::Code,
 133            Self::Fetch => IconName::ToolWeb,
 134            Self::Thread => IconName::Thread,
 135            Self::Rules => IconName::Reader,
 136            Self::Diagnostics => IconName::Warning,
 137        }
 138    }
 139}
 140
 141pub(crate) enum Match {
 142    File(FileMatch),
 143    Symbol(SymbolMatch),
 144    Thread(AgentSessionInfo),
 145    RecentThread(AgentSessionInfo),
 146    Fetch(SharedString),
 147    Rules(RulesContextEntry),
 148    Entry(EntryMatch),
 149}
 150
 151impl Match {
 152    pub fn score(&self) -> f64 {
 153        match self {
 154            Match::File(file) => file.mat.score,
 155            Match::Entry(mode) => mode.mat.as_ref().map(|mat| mat.score).unwrap_or(1.),
 156            Match::Thread(_) => 1.,
 157            Match::RecentThread(_) => 1.,
 158            Match::Symbol(_) => 1.,
 159            Match::Rules(_) => 1.,
 160            Match::Fetch(_) => 1.,
 161        }
 162    }
 163}
 164
 165pub struct EntryMatch {
 166    mat: Option<StringMatch>,
 167    entry: PromptContextEntry,
 168}
 169
 170fn session_title(session: &AgentSessionInfo) -> SharedString {
 171    session
 172        .title
 173        .clone()
 174        .filter(|title| !title.is_empty())
 175        .unwrap_or_else(|| SharedString::new_static("New Thread"))
 176}
 177
 178#[derive(Debug, Clone)]
 179pub struct RulesContextEntry {
 180    pub prompt_id: UserPromptId,
 181    pub title: SharedString,
 182}
 183
 184#[derive(Debug, Clone)]
 185pub struct AvailableCommand {
 186    pub name: Arc<str>,
 187    pub description: Arc<str>,
 188    pub requires_argument: bool,
 189    pub source: CommandSource,
 190}
 191
 192/// The source of a slash command, used to differentiate UI behavior.
 193#[derive(Debug, Clone, PartialEq)]
 194pub enum CommandSource {
 195    /// Command provided by the ACP server
 196    Server,
 197    /// User-defined command from a markdown file
 198    UserDefined { template: Arc<str> },
 199    /// User-defined command that failed to load
 200    UserDefinedError { error_message: Arc<str> },
 201}
 202
 203pub trait PromptCompletionProviderDelegate: Send + Sync + 'static {
 204    fn supports_context(&self, mode: PromptContextType, cx: &App) -> bool {
 205        self.supported_modes(cx).contains(&mode)
 206    }
 207    fn supported_modes(&self, cx: &App) -> Vec<PromptContextType>;
 208    fn supports_images(&self, cx: &App) -> bool;
 209
 210    fn available_commands(&self, cx: &App) -> Vec<AvailableCommand>;
 211    fn confirm_command(&self, cx: &mut App);
 212
 213    /// Returns cached user-defined slash commands, if available.
 214    /// Default implementation returns None, meaning commands will be loaded from disk.
 215    fn cached_user_commands(&self, _cx: &App) -> Option<HashMap<String, UserSlashCommand>> {
 216        None
 217    }
 218
 219    /// Returns cached errors from loading user-defined slash commands, if available.
 220    /// Default implementation returns None.
 221    fn cached_user_command_errors(&self, _cx: &App) -> Option<Vec<CommandLoadError>> {
 222        None
 223    }
 224}
 225
 226pub struct PromptCompletionProvider<T: PromptCompletionProviderDelegate> {
 227    source: Arc<T>,
 228    editor: WeakEntity<Editor>,
 229    mention_set: Entity<MentionSet>,
 230    history: WeakEntity<AcpThreadHistory>,
 231    prompt_store: Option<Entity<PromptStore>>,
 232    workspace: WeakEntity<Workspace>,
 233}
 234
 235impl<T: PromptCompletionProviderDelegate> PromptCompletionProvider<T> {
 236    pub fn new(
 237        source: T,
 238        editor: WeakEntity<Editor>,
 239        mention_set: Entity<MentionSet>,
 240        history: WeakEntity<AcpThreadHistory>,
 241        prompt_store: Option<Entity<PromptStore>>,
 242        workspace: WeakEntity<Workspace>,
 243    ) -> Self {
 244        Self {
 245            source: Arc::new(source),
 246            editor,
 247            mention_set,
 248            workspace,
 249            history,
 250            prompt_store,
 251        }
 252    }
 253
 254    fn completion_for_entry(
 255        entry: PromptContextEntry,
 256        source_range: Range<Anchor>,
 257        editor: WeakEntity<Editor>,
 258        mention_set: WeakEntity<MentionSet>,
 259        workspace: &Entity<Workspace>,
 260        cx: &mut App,
 261    ) -> Option<Completion> {
 262        match entry {
 263            PromptContextEntry::Mode(mode) => Some(Completion {
 264                replace_range: source_range,
 265                new_text: format!("@{} ", mode.keyword()),
 266                label: CodeLabel::plain(mode.label().to_string(), None),
 267                icon_path: Some(mode.icon().path().into()),
 268                documentation: None,
 269                source: project::CompletionSource::Custom,
 270                match_start: None,
 271                snippet_deduplication_key: None,
 272                insert_text_mode: None,
 273                // This ensures that when a user accepts this completion, the
 274                // completion menu will still be shown after "@category " is
 275                // inserted
 276                confirm: Some(Arc::new(|_, _, _| true)),
 277            }),
 278            PromptContextEntry::Action(action) => Self::completion_for_action(
 279                action,
 280                source_range,
 281                editor,
 282                mention_set,
 283                workspace,
 284                cx,
 285            ),
 286        }
 287    }
 288
 289    fn completion_for_thread(
 290        thread_entry: AgentSessionInfo,
 291        source_range: Range<Anchor>,
 292        recent: bool,
 293        source: Arc<T>,
 294        editor: WeakEntity<Editor>,
 295        mention_set: WeakEntity<MentionSet>,
 296        workspace: Entity<Workspace>,
 297        cx: &mut App,
 298    ) -> Completion {
 299        let title = session_title(&thread_entry);
 300        let uri = MentionUri::Thread {
 301            id: thread_entry.session_id,
 302            name: title.to_string(),
 303        };
 304
 305        let icon_for_completion = if recent {
 306            IconName::HistoryRerun.path().into()
 307        } else {
 308            uri.icon_path(cx)
 309        };
 310
 311        let new_text = format!("{} ", uri.as_link());
 312
 313        let new_text_len = new_text.len();
 314        Completion {
 315            replace_range: source_range.clone(),
 316            new_text,
 317            label: CodeLabel::plain(title.to_string(), None),
 318            documentation: None,
 319            insert_text_mode: None,
 320            source: project::CompletionSource::Custom,
 321            match_start: None,
 322            snippet_deduplication_key: None,
 323            icon_path: Some(icon_for_completion),
 324            confirm: Some(confirm_completion_callback(
 325                title,
 326                source_range.start,
 327                new_text_len - 1,
 328                uri,
 329                source,
 330                editor,
 331                mention_set,
 332                workspace,
 333            )),
 334        }
 335    }
 336
 337    fn completion_for_rules(
 338        rule: RulesContextEntry,
 339        source_range: Range<Anchor>,
 340        source: Arc<T>,
 341        editor: WeakEntity<Editor>,
 342        mention_set: WeakEntity<MentionSet>,
 343        workspace: Entity<Workspace>,
 344        cx: &mut App,
 345    ) -> Completion {
 346        let uri = MentionUri::Rule {
 347            id: rule.prompt_id.into(),
 348            name: rule.title.to_string(),
 349        };
 350        let new_text = format!("{} ", uri.as_link());
 351        let new_text_len = new_text.len();
 352        let icon_path = uri.icon_path(cx);
 353        Completion {
 354            replace_range: source_range.clone(),
 355            new_text,
 356            label: CodeLabel::plain(rule.title.to_string(), None),
 357            documentation: None,
 358            insert_text_mode: None,
 359            source: project::CompletionSource::Custom,
 360            match_start: None,
 361            snippet_deduplication_key: None,
 362            icon_path: Some(icon_path),
 363            confirm: Some(confirm_completion_callback(
 364                rule.title,
 365                source_range.start,
 366                new_text_len - 1,
 367                uri,
 368                source,
 369                editor,
 370                mention_set,
 371                workspace,
 372            )),
 373        }
 374    }
 375
 376    pub(crate) fn completion_for_path(
 377        project_path: ProjectPath,
 378        path_prefix: &RelPath,
 379        is_recent: bool,
 380        is_directory: bool,
 381        source_range: Range<Anchor>,
 382        source: Arc<T>,
 383        editor: WeakEntity<Editor>,
 384        mention_set: WeakEntity<MentionSet>,
 385        workspace: Entity<Workspace>,
 386        project: Entity<Project>,
 387        label_max_chars: usize,
 388        cx: &mut App,
 389    ) -> Option<Completion> {
 390        let path_style = project.read(cx).path_style(cx);
 391        let (file_name, directory) =
 392            extract_file_name_and_directory(&project_path.path, path_prefix, path_style);
 393
 394        let label = build_code_label_for_path(
 395            &file_name,
 396            directory.as_ref().map(|s| s.as_ref()),
 397            None,
 398            label_max_chars,
 399            cx,
 400        );
 401
 402        let abs_path = project.read(cx).absolute_path(&project_path, cx)?;
 403
 404        let uri = if is_directory {
 405            MentionUri::Directory { abs_path }
 406        } else {
 407            MentionUri::File { abs_path }
 408        };
 409
 410        let crease_icon_path = uri.icon_path(cx);
 411        let completion_icon_path = if is_recent {
 412            IconName::HistoryRerun.path().into()
 413        } else {
 414            crease_icon_path
 415        };
 416
 417        let new_text = format!("{} ", uri.as_link());
 418        let new_text_len = new_text.len();
 419        Some(Completion {
 420            replace_range: source_range.clone(),
 421            new_text,
 422            label,
 423            documentation: None,
 424            source: project::CompletionSource::Custom,
 425            icon_path: Some(completion_icon_path),
 426            match_start: None,
 427            snippet_deduplication_key: None,
 428            insert_text_mode: None,
 429            confirm: Some(confirm_completion_callback(
 430                file_name,
 431                source_range.start,
 432                new_text_len - 1,
 433                uri,
 434                source,
 435                editor,
 436                mention_set,
 437                workspace,
 438            )),
 439        })
 440    }
 441
 442    fn completion_for_symbol(
 443        symbol: Symbol,
 444        source_range: Range<Anchor>,
 445        source: Arc<T>,
 446        editor: WeakEntity<Editor>,
 447        mention_set: WeakEntity<MentionSet>,
 448        workspace: Entity<Workspace>,
 449        label_max_chars: usize,
 450        cx: &mut App,
 451    ) -> Option<Completion> {
 452        let project = workspace.read(cx).project().clone();
 453
 454        let (abs_path, file_name) = match &symbol.path {
 455            SymbolLocation::InProject(project_path) => (
 456                project.read(cx).absolute_path(&project_path, cx)?,
 457                project_path.path.file_name()?.to_string().into(),
 458            ),
 459            SymbolLocation::OutsideProject {
 460                abs_path,
 461                signature: _,
 462            } => (
 463                PathBuf::from(abs_path.as_ref()),
 464                abs_path.file_name().map(|f| f.to_string_lossy())?,
 465            ),
 466        };
 467
 468        let label = build_code_label_for_path(
 469            &symbol.name,
 470            Some(&file_name),
 471            Some(symbol.range.start.0.row + 1),
 472            label_max_chars,
 473            cx,
 474        );
 475
 476        let uri = MentionUri::Symbol {
 477            abs_path,
 478            name: symbol.name.clone(),
 479            line_range: symbol.range.start.0.row..=symbol.range.end.0.row,
 480        };
 481        let new_text = format!("{} ", uri.as_link());
 482        let new_text_len = new_text.len();
 483        let icon_path = uri.icon_path(cx);
 484        Some(Completion {
 485            replace_range: source_range.clone(),
 486            new_text,
 487            label,
 488            documentation: None,
 489            source: project::CompletionSource::Custom,
 490            icon_path: Some(icon_path),
 491            match_start: None,
 492            snippet_deduplication_key: None,
 493            insert_text_mode: None,
 494            confirm: Some(confirm_completion_callback(
 495                symbol.name.into(),
 496                source_range.start,
 497                new_text_len - 1,
 498                uri,
 499                source,
 500                editor,
 501                mention_set,
 502                workspace,
 503            )),
 504        })
 505    }
 506
 507    fn completion_for_fetch(
 508        source_range: Range<Anchor>,
 509        url_to_fetch: SharedString,
 510        source: Arc<T>,
 511        editor: WeakEntity<Editor>,
 512        mention_set: WeakEntity<MentionSet>,
 513        workspace: Entity<Workspace>,
 514        cx: &mut App,
 515    ) -> Option<Completion> {
 516        let new_text = format!("@fetch {} ", url_to_fetch);
 517        let url_to_fetch = url::Url::parse(url_to_fetch.as_ref())
 518            .or_else(|_| url::Url::parse(&format!("https://{url_to_fetch}")))
 519            .ok()?;
 520        let mention_uri = MentionUri::Fetch {
 521            url: url_to_fetch.clone(),
 522        };
 523        let icon_path = mention_uri.icon_path(cx);
 524        Some(Completion {
 525            replace_range: source_range.clone(),
 526            new_text: new_text.clone(),
 527            label: CodeLabel::plain(url_to_fetch.to_string(), None),
 528            documentation: None,
 529            source: project::CompletionSource::Custom,
 530            icon_path: Some(icon_path),
 531            match_start: None,
 532            snippet_deduplication_key: None,
 533            insert_text_mode: None,
 534            confirm: Some(confirm_completion_callback(
 535                url_to_fetch.to_string().into(),
 536                source_range.start,
 537                new_text.len() - 1,
 538                mention_uri,
 539                source,
 540                editor,
 541                mention_set,
 542                workspace,
 543            )),
 544        })
 545    }
 546
 547    pub(crate) fn completion_for_action(
 548        action: PromptContextAction,
 549        source_range: Range<Anchor>,
 550        editor: WeakEntity<Editor>,
 551        mention_set: WeakEntity<MentionSet>,
 552        workspace: &Entity<Workspace>,
 553        cx: &mut App,
 554    ) -> Option<Completion> {
 555        let (new_text, on_action) = match action {
 556            PromptContextAction::AddSelections => {
 557                const PLACEHOLDER: &str = "selection ";
 558                let selections = selection_ranges(workspace, cx)
 559                    .into_iter()
 560                    .enumerate()
 561                    .map(|(ix, (buffer, range))| {
 562                        (
 563                            buffer,
 564                            range,
 565                            (PLACEHOLDER.len() * ix)..(PLACEHOLDER.len() * (ix + 1) - 1),
 566                        )
 567                    })
 568                    .collect::<Vec<_>>();
 569
 570                let new_text: String = PLACEHOLDER.repeat(selections.len());
 571
 572                let callback = Arc::new({
 573                    let source_range = source_range.clone();
 574                    move |_, window: &mut Window, cx: &mut App| {
 575                        let editor = editor.clone();
 576                        let selections = selections.clone();
 577                        let mention_set = mention_set.clone();
 578                        let source_range = source_range.clone();
 579                        window.defer(cx, move |window, cx| {
 580                            if let Some(editor) = editor.upgrade() {
 581                                mention_set
 582                                    .update(cx, |store, cx| {
 583                                        store.confirm_mention_for_selection(
 584                                            source_range,
 585                                            selections,
 586                                            editor,
 587                                            window,
 588                                            cx,
 589                                        )
 590                                    })
 591                                    .ok();
 592                            }
 593                        });
 594                        false
 595                    }
 596                });
 597
 598                (new_text, callback)
 599            }
 600        };
 601
 602        Some(Completion {
 603            replace_range: source_range,
 604            new_text,
 605            label: CodeLabel::plain(action.label().to_string(), None),
 606            icon_path: Some(action.icon().path().into()),
 607            documentation: None,
 608            source: project::CompletionSource::Custom,
 609            match_start: None,
 610            snippet_deduplication_key: None,
 611            insert_text_mode: None,
 612            // This ensures that when a user accepts this completion, the
 613            // completion menu will still be shown after "@category " is
 614            // inserted
 615            confirm: Some(on_action),
 616        })
 617    }
 618
 619    fn completion_for_diagnostics(
 620        source_range: Range<Anchor>,
 621        source: Arc<T>,
 622        editor: WeakEntity<Editor>,
 623        mention_set: WeakEntity<MentionSet>,
 624        workspace: Entity<Workspace>,
 625        cx: &mut App,
 626    ) -> Vec<Completion> {
 627        let summary = workspace
 628            .read(cx)
 629            .project()
 630            .read(cx)
 631            .diagnostic_summary(false, cx);
 632        if summary.error_count == 0 && summary.warning_count == 0 {
 633            return Vec::new();
 634        }
 635        let icon_path = MentionUri::Diagnostics {
 636            include_errors: true,
 637            include_warnings: false,
 638        }
 639        .icon_path(cx);
 640
 641        let mut completions = Vec::new();
 642
 643        let cases = [
 644            (summary.error_count > 0, true, false),
 645            (summary.warning_count > 0, false, true),
 646            (
 647                summary.error_count > 0 && summary.warning_count > 0,
 648                true,
 649                true,
 650            ),
 651        ];
 652
 653        for (condition, include_errors, include_warnings) in cases {
 654            if condition {
 655                completions.push(Self::build_diagnostics_completion(
 656                    diagnostics_submenu_label(summary, include_errors, include_warnings),
 657                    source_range.clone(),
 658                    source.clone(),
 659                    editor.clone(),
 660                    mention_set.clone(),
 661                    workspace.clone(),
 662                    icon_path.clone(),
 663                    include_errors,
 664                    include_warnings,
 665                    summary,
 666                ));
 667            }
 668        }
 669
 670        completions
 671    }
 672
 673    fn build_diagnostics_completion(
 674        menu_label: String,
 675        source_range: Range<Anchor>,
 676        source: Arc<T>,
 677        editor: WeakEntity<Editor>,
 678        mention_set: WeakEntity<MentionSet>,
 679        workspace: Entity<Workspace>,
 680        icon_path: SharedString,
 681        include_errors: bool,
 682        include_warnings: bool,
 683        summary: DiagnosticSummary,
 684    ) -> Completion {
 685        let uri = MentionUri::Diagnostics {
 686            include_errors,
 687            include_warnings,
 688        };
 689        let crease_text = diagnostics_crease_label(summary, include_errors, include_warnings);
 690        let display_text = format!("@{}", crease_text);
 691        let new_text = format!("[{}]({}) ", display_text, uri.to_uri());
 692        let new_text_len = new_text.len();
 693        Completion {
 694            replace_range: source_range.clone(),
 695            new_text,
 696            label: CodeLabel::plain(menu_label, None),
 697            documentation: None,
 698            source: project::CompletionSource::Custom,
 699            icon_path: Some(icon_path),
 700            match_start: None,
 701            snippet_deduplication_key: None,
 702            insert_text_mode: None,
 703            confirm: Some(confirm_completion_callback(
 704                crease_text,
 705                source_range.start,
 706                new_text_len - 1,
 707                uri,
 708                source,
 709                editor,
 710                mention_set,
 711                workspace,
 712            )),
 713        }
 714    }
 715
 716    fn search_slash_commands(&self, query: String, cx: &mut App) -> Task<Vec<AvailableCommand>> {
 717        let commands = self.source.available_commands(cx);
 718        let server_command_names = commands
 719            .iter()
 720            .map(|command| command.name.as_ref().to_string())
 721            .collect::<HashSet<_>>();
 722
 723        // Try to use cached user commands and errors first
 724        let cached_user_commands = if cx.has_flag::<UserSlashCommandsFeatureFlag>() {
 725            self.source.cached_user_commands(cx)
 726        } else {
 727            None
 728        };
 729
 730        let cached_user_command_errors = if cx.has_flag::<UserSlashCommandsFeatureFlag>() {
 731            self.source.cached_user_command_errors(cx)
 732        } else {
 733            None
 734        };
 735
 736        // Get fs and worktree roots for async command loading (only if not cached)
 737        let (fs, worktree_roots) =
 738            if cached_user_commands.is_none() && cx.has_flag::<UserSlashCommandsFeatureFlag>() {
 739                let workspace = self.workspace.upgrade();
 740                let fs = workspace
 741                    .as_ref()
 742                    .map(|w| w.read(cx).project().read(cx).fs().clone());
 743                let roots: Vec<std::path::PathBuf> = workspace
 744                    .map(|workspace| {
 745                        workspace
 746                            .read(cx)
 747                            .visible_worktrees(cx)
 748                            .map(|worktree| worktree.read(cx).abs_path().to_path_buf())
 749                            .collect()
 750                    })
 751                    .unwrap_or_default();
 752                (fs, roots)
 753            } else {
 754                (None, Vec::new())
 755            };
 756
 757        cx.spawn(async move |cx| {
 758            let mut commands = commands;
 759
 760            // Use cached commands/errors if available, otherwise load from disk
 761            let (mut user_commands, mut user_command_errors): (
 762                Vec<UserSlashCommand>,
 763                Vec<CommandLoadError>,
 764            ) = if let Some(cached) = cached_user_commands {
 765                let errors = cached_user_command_errors.unwrap_or_default();
 766                (cached.into_values().collect(), errors)
 767            } else if let Some(fs) = fs {
 768                let load_result =
 769                    crate::user_slash_command::load_all_commands_async(&fs, &worktree_roots).await;
 770
 771                (load_result.commands, load_result.errors)
 772            } else {
 773                (Vec::new(), Vec::new())
 774            };
 775
 776            user_slash_command::apply_server_command_conflicts(
 777                &mut user_commands,
 778                &mut user_command_errors,
 779                &server_command_names,
 780            );
 781
 782            let conflicting_names: HashSet<String> = user_command_errors
 783                .iter()
 784                .filter_map(|error| error.command_name())
 785                .filter(|name| server_command_names.contains(name))
 786                .collect();
 787
 788            if !conflicting_names.is_empty() {
 789                commands.retain(|command| !conflicting_names.contains(command.name.as_ref()));
 790            }
 791
 792            for cmd in user_commands {
 793                commands.push(AvailableCommand {
 794                    name: cmd.name.clone(),
 795                    description: cmd.description().into(),
 796                    requires_argument: cmd.requires_arguments(),
 797                    source: CommandSource::UserDefined {
 798                        template: cmd.template.clone(),
 799                    },
 800                });
 801            }
 802
 803            // Add errored commands so they show up in autocomplete with error indication.
 804            // Errors for commands that don't match the query will be silently ignored here
 805            // since the user will see them via the error callout in the thread view.
 806            for error in user_command_errors {
 807                if let Some(name) = error.command_name() {
 808                    commands.push(AvailableCommand {
 809                        name: name.into(),
 810                        description: "".into(),
 811                        requires_argument: false,
 812                        source: CommandSource::UserDefinedError {
 813                            error_message: error.message.into(),
 814                        },
 815                    });
 816                }
 817            }
 818
 819            if commands.is_empty() {
 820                return Vec::new();
 821            }
 822
 823            let candidates = commands
 824                .iter()
 825                .enumerate()
 826                .map(|(id, command)| StringMatchCandidate::new(id, &command.name))
 827                .collect::<Vec<_>>();
 828
 829            let matches = fuzzy::match_strings(
 830                &candidates,
 831                &query,
 832                false,
 833                true,
 834                100,
 835                &Arc::new(AtomicBool::default()),
 836                cx.background_executor().clone(),
 837            )
 838            .await;
 839
 840            matches
 841                .into_iter()
 842                .map(|mat| commands[mat.candidate_id].clone())
 843                .collect()
 844        })
 845    }
 846
 847    fn search_mentions(
 848        &self,
 849        mode: Option<PromptContextType>,
 850        query: String,
 851        cancellation_flag: Arc<AtomicBool>,
 852        cx: &mut App,
 853    ) -> Task<Vec<Match>> {
 854        let Some(workspace) = self.workspace.upgrade() else {
 855            return Task::ready(Vec::default());
 856        };
 857        match mode {
 858            Some(PromptContextType::File) => {
 859                let search_files_task = search_files(query, cancellation_flag, &workspace, cx);
 860                cx.background_spawn(async move {
 861                    search_files_task
 862                        .await
 863                        .into_iter()
 864                        .map(Match::File)
 865                        .collect()
 866                })
 867            }
 868
 869            Some(PromptContextType::Symbol) => {
 870                let search_symbols_task = search_symbols(query, cancellation_flag, &workspace, cx);
 871                cx.background_spawn(async move {
 872                    search_symbols_task
 873                        .await
 874                        .into_iter()
 875                        .map(Match::Symbol)
 876                        .collect()
 877                })
 878            }
 879
 880            Some(PromptContextType::Thread) => {
 881                if let Some(history) = self.history.upgrade() {
 882                    let sessions = history.read(cx).sessions().to_vec();
 883                    let search_task =
 884                        filter_sessions_by_query(query, cancellation_flag, sessions, cx);
 885                    cx.spawn(async move |_cx| {
 886                        search_task.await.into_iter().map(Match::Thread).collect()
 887                    })
 888                } else {
 889                    Task::ready(Vec::new())
 890                }
 891            }
 892
 893            Some(PromptContextType::Fetch) => {
 894                if !query.is_empty() {
 895                    Task::ready(vec![Match::Fetch(query.into())])
 896                } else {
 897                    Task::ready(Vec::new())
 898                }
 899            }
 900
 901            Some(PromptContextType::Rules) => {
 902                if let Some(prompt_store) = self.prompt_store.as_ref() {
 903                    let search_rules_task =
 904                        search_rules(query, cancellation_flag, prompt_store, cx);
 905                    cx.background_spawn(async move {
 906                        search_rules_task
 907                            .await
 908                            .into_iter()
 909                            .map(Match::Rules)
 910                            .collect::<Vec<_>>()
 911                    })
 912                } else {
 913                    Task::ready(Vec::new())
 914                }
 915            }
 916
 917            Some(PromptContextType::Diagnostics) => Task::ready(Vec::new()),
 918
 919            None if query.is_empty() => {
 920                let recent_task = self.recent_context_picker_entries(&workspace, cx);
 921                let entries = self
 922                    .available_context_picker_entries(&workspace, cx)
 923                    .into_iter()
 924                    .map(|mode| {
 925                        Match::Entry(EntryMatch {
 926                            entry: mode,
 927                            mat: None,
 928                        })
 929                    })
 930                    .collect::<Vec<_>>();
 931
 932                cx.spawn(async move |_cx| {
 933                    let mut matches = recent_task.await;
 934                    matches.extend(entries);
 935                    matches
 936                })
 937            }
 938            None => {
 939                let executor = cx.background_executor().clone();
 940
 941                let search_files_task =
 942                    search_files(query.clone(), cancellation_flag, &workspace, cx);
 943
 944                let entries = self.available_context_picker_entries(&workspace, cx);
 945                let entry_candidates = entries
 946                    .iter()
 947                    .enumerate()
 948                    .map(|(ix, entry)| StringMatchCandidate::new(ix, entry.keyword()))
 949                    .collect::<Vec<_>>();
 950
 951                cx.background_spawn(async move {
 952                    let mut matches = search_files_task
 953                        .await
 954                        .into_iter()
 955                        .map(Match::File)
 956                        .collect::<Vec<_>>();
 957
 958                    let entry_matches = fuzzy::match_strings(
 959                        &entry_candidates,
 960                        &query,
 961                        false,
 962                        true,
 963                        100,
 964                        &Arc::new(AtomicBool::default()),
 965                        executor,
 966                    )
 967                    .await;
 968
 969                    matches.extend(entry_matches.into_iter().map(|mat| {
 970                        Match::Entry(EntryMatch {
 971                            entry: entries[mat.candidate_id],
 972                            mat: Some(mat),
 973                        })
 974                    }));
 975
 976                    matches.sort_by(|a, b| {
 977                        b.score()
 978                            .partial_cmp(&a.score())
 979                            .unwrap_or(std::cmp::Ordering::Equal)
 980                    });
 981
 982                    matches
 983                })
 984            }
 985        }
 986    }
 987
 988    fn recent_context_picker_entries(
 989        &self,
 990        workspace: &Entity<Workspace>,
 991        cx: &mut App,
 992    ) -> Task<Vec<Match>> {
 993        let mut recent = Vec::with_capacity(6);
 994
 995        let mut mentions = self
 996            .mention_set
 997            .read_with(cx, |store, _cx| store.mentions());
 998        let workspace = workspace.read(cx);
 999        let project = workspace.project().read(cx);
1000        let include_root_name = workspace.visible_worktrees(cx).count() > 1;
1001
1002        if let Some(agent_panel) = workspace.panel::<AgentPanel>(cx)
1003            && let Some(thread) = agent_panel.read(cx).active_agent_thread(cx)
1004        {
1005            let thread = thread.read(cx);
1006            mentions.insert(MentionUri::Thread {
1007                id: thread.session_id().clone(),
1008                name: thread.title().into(),
1009            });
1010        }
1011
1012        recent.extend(
1013            workspace
1014                .recent_navigation_history_iter(cx)
1015                .filter(|(_, abs_path)| {
1016                    abs_path.as_ref().is_none_or(|path| {
1017                        !mentions.contains(&MentionUri::File {
1018                            abs_path: path.clone(),
1019                        })
1020                    })
1021                })
1022                .take(4)
1023                .filter_map(|(project_path, _)| {
1024                    project
1025                        .worktree_for_id(project_path.worktree_id, cx)
1026                        .map(|worktree| {
1027                            let path_prefix = if include_root_name {
1028                                worktree.read(cx).root_name().into()
1029                            } else {
1030                                RelPath::empty().into()
1031                            };
1032                            Match::File(FileMatch {
1033                                mat: fuzzy::PathMatch {
1034                                    score: 1.,
1035                                    positions: Vec::new(),
1036                                    worktree_id: project_path.worktree_id.to_usize(),
1037                                    path: project_path.path,
1038                                    path_prefix,
1039                                    is_dir: false,
1040                                    distance_to_relative_ancestor: 0,
1041                                },
1042                                is_recent: true,
1043                            })
1044                        })
1045                }),
1046        );
1047
1048        if !self.source.supports_context(PromptContextType::Thread, cx) {
1049            return Task::ready(recent);
1050        }
1051
1052        if let Some(history) = self.history.upgrade() {
1053            const RECENT_COUNT: usize = 2;
1054            recent.extend(
1055                history
1056                    .read(cx)
1057                    .sessions()
1058                    .into_iter()
1059                    .filter(|session| {
1060                        let uri = MentionUri::Thread {
1061                            id: session.session_id.clone(),
1062                            name: session_title(session).to_string(),
1063                        };
1064                        !mentions.contains(&uri)
1065                    })
1066                    .take(RECENT_COUNT)
1067                    .cloned()
1068                    .map(Match::RecentThread),
1069            );
1070            return Task::ready(recent);
1071        }
1072
1073        Task::ready(recent)
1074    }
1075
1076    fn available_context_picker_entries(
1077        &self,
1078        workspace: &Entity<Workspace>,
1079        cx: &mut App,
1080    ) -> Vec<PromptContextEntry> {
1081        let mut entries = vec![
1082            PromptContextEntry::Mode(PromptContextType::File),
1083            PromptContextEntry::Mode(PromptContextType::Symbol),
1084        ];
1085
1086        if self.source.supports_context(PromptContextType::Thread, cx) {
1087            entries.push(PromptContextEntry::Mode(PromptContextType::Thread));
1088        }
1089
1090        let has_selection = workspace
1091            .read(cx)
1092            .active_item(cx)
1093            .and_then(|item| item.downcast::<Editor>())
1094            .is_some_and(|editor| {
1095                editor.update(cx, |editor, cx| {
1096                    editor.has_non_empty_selection(&editor.display_snapshot(cx))
1097                })
1098            });
1099        if has_selection {
1100            entries.push(PromptContextEntry::Action(
1101                PromptContextAction::AddSelections,
1102            ));
1103        }
1104
1105        if self.prompt_store.is_some() && self.source.supports_context(PromptContextType::Rules, cx)
1106        {
1107            entries.push(PromptContextEntry::Mode(PromptContextType::Rules));
1108        }
1109
1110        if self.source.supports_context(PromptContextType::Fetch, cx) {
1111            entries.push(PromptContextEntry::Mode(PromptContextType::Fetch));
1112        }
1113
1114        if self
1115            .source
1116            .supports_context(PromptContextType::Diagnostics, cx)
1117        {
1118            let summary = workspace
1119                .read(cx)
1120                .project()
1121                .read(cx)
1122                .diagnostic_summary(false, cx);
1123            if summary.error_count > 0 || summary.warning_count > 0 {
1124                entries.push(PromptContextEntry::Mode(PromptContextType::Diagnostics));
1125            }
1126        }
1127
1128        entries
1129    }
1130}
1131
1132impl<T: PromptCompletionProviderDelegate> CompletionProvider for PromptCompletionProvider<T> {
1133    fn completions(
1134        &self,
1135        _excerpt_id: ExcerptId,
1136        buffer: &Entity<Buffer>,
1137        buffer_position: Anchor,
1138        _trigger: CompletionContext,
1139        window: &mut Window,
1140        cx: &mut Context<Editor>,
1141    ) -> Task<Result<Vec<CompletionResponse>>> {
1142        let state = buffer.update(cx, |buffer, cx| {
1143            let position = buffer_position.to_point(buffer);
1144            let line_start = Point::new(position.row, 0);
1145            let offset_to_line = buffer.point_to_offset(line_start);
1146            let mut lines = buffer.text_for_range(line_start..position).lines();
1147            let line = lines.next()?;
1148            PromptCompletion::try_parse(line, offset_to_line, &self.source.supported_modes(cx))
1149        });
1150        let Some(state) = state else {
1151            return Task::ready(Ok(Vec::new()));
1152        };
1153
1154        let Some(workspace) = self.workspace.upgrade() else {
1155            return Task::ready(Ok(Vec::new()));
1156        };
1157
1158        let project = workspace.read(cx).project().clone();
1159        let snapshot = buffer.read(cx).snapshot();
1160        let source_range = snapshot.anchor_before(state.source_range().start)
1161            ..snapshot.anchor_after(state.source_range().end);
1162
1163        let source = self.source.clone();
1164        let editor = self.editor.clone();
1165        let mention_set = self.mention_set.downgrade();
1166        match state {
1167            PromptCompletion::SlashCommand(SlashCommandCompletion {
1168                command, argument, ..
1169            }) => {
1170                let search_task = self.search_slash_commands(command.unwrap_or_default(), cx);
1171                cx.background_spawn(async move {
1172                    let completions = search_task
1173                        .await
1174                        .into_iter()
1175                        .map(|command| {
1176                            let is_error =
1177                                matches!(command.source, CommandSource::UserDefinedError { .. });
1178
1179                            // For errored commands, show the name with "(load error)" suffix
1180                            let label_text = if is_error {
1181                                format!("{} (load error)", command.name)
1182                            } else {
1183                                command.name.to_string()
1184                            };
1185
1186                            // For errored commands, we don't want to insert anything useful
1187                            let new_text = if is_error {
1188                                format!("/{}", command.name)
1189                            } else if let Some(argument) = argument.as_ref() {
1190                                format!("/{} {}", command.name, argument)
1191                            } else {
1192                                format!("/{} ", command.name)
1193                            };
1194
1195                            let is_missing_argument =
1196                                command.requires_argument && argument.is_none();
1197
1198                            // For errored commands, use a deprecated-style label to indicate the error
1199                            let label = if is_error {
1200                                // Create a label where the command name portion has a highlight
1201                                // that will be rendered with strikethrough by the completion menu
1202                                // (similar to deprecated LSP completions)
1203                                CodeLabel::plain(label_text, None)
1204                            } else {
1205                                CodeLabel::plain(label_text, None)
1206                            };
1207
1208                            // For errored commands, show the error message in documentation
1209                            let documentation =
1210                                if let CommandSource::UserDefinedError { error_message } =
1211                                    &command.source
1212                                {
1213                                    Some(CompletionDocumentation::MultiLinePlainText(
1214                                        error_message.to_string().into(),
1215                                    ))
1216                                } else if !command.description.is_empty() {
1217                                    Some(CompletionDocumentation::MultiLinePlainText(
1218                                        command.description.to_string().into(),
1219                                    ))
1220                                } else {
1221                                    None
1222                                };
1223
1224                            // For errored commands, use a red X icon
1225                            let icon_path = if is_error {
1226                                Some(IconName::XCircle.path().into())
1227                            } else {
1228                                None
1229                            };
1230
1231                            Completion {
1232                                replace_range: source_range.clone(),
1233                                new_text,
1234                                label,
1235                                documentation,
1236                                source: if is_error {
1237                                    // Use a custom source that marks this as deprecated/errored
1238                                    // so the completion menu renders it with strikethrough
1239                                    project::CompletionSource::Lsp {
1240                                        insert_range: None,
1241                                        server_id: language::LanguageServerId(0),
1242                                        lsp_completion: Box::new(lsp::CompletionItem {
1243                                            label: command.name.to_string(),
1244                                            deprecated: Some(true),
1245                                            ..Default::default()
1246                                        }),
1247                                        lsp_defaults: None,
1248                                        resolved: true,
1249                                    }
1250                                } else {
1251                                    project::CompletionSource::Custom
1252                                },
1253                                icon_path,
1254                                match_start: None,
1255                                snippet_deduplication_key: None,
1256                                insert_text_mode: None,
1257                                confirm: Some(Arc::new({
1258                                    let source = source.clone();
1259                                    move |intent, _window, cx| {
1260                                        // Don't confirm errored commands
1261                                        if is_error {
1262                                            return false;
1263                                        }
1264                                        if !is_missing_argument {
1265                                            cx.defer({
1266                                                let source = source.clone();
1267                                                move |cx| match intent {
1268                                                    CompletionIntent::Complete
1269                                                    | CompletionIntent::CompleteWithInsert
1270                                                    | CompletionIntent::CompleteWithReplace => {
1271                                                        source.confirm_command(cx);
1272                                                    }
1273                                                    CompletionIntent::Compose => {}
1274                                                }
1275                                            });
1276                                        }
1277                                        false
1278                                    }
1279                                })),
1280                            }
1281                        })
1282                        .collect();
1283
1284                    Ok(vec![CompletionResponse {
1285                        completions,
1286                        display_options: CompletionDisplayOptions {
1287                            dynamic_width: true,
1288                        },
1289                        // Since this does its own filtering (see `filter_completions()` returns false),
1290                        // there is no benefit to computing whether this set of completions is incomplete.
1291                        is_incomplete: true,
1292                    }])
1293                })
1294            }
1295            PromptCompletion::Mention(MentionCompletion { mode, argument, .. }) => {
1296                if let Some(PromptContextType::Diagnostics) = mode {
1297                    if argument.is_some() {
1298                        return Task::ready(Ok(Vec::new()));
1299                    }
1300
1301                    let completions = Self::completion_for_diagnostics(
1302                        source_range.clone(),
1303                        source.clone(),
1304                        editor.clone(),
1305                        mention_set.clone(),
1306                        workspace.clone(),
1307                        cx,
1308                    );
1309                    if !completions.is_empty() {
1310                        return Task::ready(Ok(vec![CompletionResponse {
1311                            completions,
1312                            display_options: CompletionDisplayOptions::default(),
1313                            is_incomplete: false,
1314                        }]));
1315                    }
1316                }
1317
1318                let query = argument.unwrap_or_default();
1319                let search_task =
1320                    self.search_mentions(mode, query, Arc::<AtomicBool>::default(), cx);
1321
1322                // Calculate maximum characters available for the full label (file_name + space + directory)
1323                // based on maximum menu width after accounting for padding, spacing, and icon width
1324                let label_max_chars = {
1325                    // Base06 left padding + Base06 gap + Base06 right padding + icon width
1326                    let used_pixels = DynamicSpacing::Base06.px(cx) * 3.0
1327                        + IconSize::XSmall.rems() * window.rem_size();
1328
1329                    let style = window.text_style();
1330                    let font_id = window.text_system().resolve_font(&style.font());
1331                    let font_size = TextSize::Small.rems(cx).to_pixels(window.rem_size());
1332
1333                    // Fallback em_width of 10px matches file_finder.rs fallback for TextSize::Small
1334                    let em_width = cx
1335                        .text_system()
1336                        .em_width(font_id, font_size)
1337                        .unwrap_or(px(10.0));
1338
1339                    // Calculate available pixels for text (file_name + directory)
1340                    // Using max width since dynamic_width allows the menu to expand up to this
1341                    let available_pixels = COMPLETION_MENU_MAX_WIDTH - used_pixels;
1342
1343                    // Convert to character count (total available for file_name + directory)
1344                    (f32::from(available_pixels) / f32::from(em_width)) as usize
1345                };
1346
1347                cx.spawn(async move |_, cx| {
1348                    let matches = search_task.await;
1349
1350                    let completions = cx.update(|cx| {
1351                        matches
1352                            .into_iter()
1353                            .filter_map(|mat| match mat {
1354                                Match::File(FileMatch { mat, is_recent }) => {
1355                                    let project_path = ProjectPath {
1356                                        worktree_id: WorktreeId::from_usize(mat.worktree_id),
1357                                        path: mat.path.clone(),
1358                                    };
1359
1360                                    // If path is empty, this means we're matching with the root directory itself
1361                                    // so we use the path_prefix as the name
1362                                    let path_prefix = if mat.path.is_empty() {
1363                                        project
1364                                            .read(cx)
1365                                            .worktree_for_id(project_path.worktree_id, cx)
1366                                            .map(|wt| wt.read(cx).root_name().into())
1367                                            .unwrap_or_else(|| mat.path_prefix.clone())
1368                                    } else {
1369                                        mat.path_prefix.clone()
1370                                    };
1371
1372                                    Self::completion_for_path(
1373                                        project_path,
1374                                        &path_prefix,
1375                                        is_recent,
1376                                        mat.is_dir,
1377                                        source_range.clone(),
1378                                        source.clone(),
1379                                        editor.clone(),
1380                                        mention_set.clone(),
1381                                        workspace.clone(),
1382                                        project.clone(),
1383                                        label_max_chars,
1384                                        cx,
1385                                    )
1386                                }
1387                                Match::Symbol(SymbolMatch { symbol, .. }) => {
1388                                    Self::completion_for_symbol(
1389                                        symbol,
1390                                        source_range.clone(),
1391                                        source.clone(),
1392                                        editor.clone(),
1393                                        mention_set.clone(),
1394                                        workspace.clone(),
1395                                        label_max_chars,
1396                                        cx,
1397                                    )
1398                                }
1399                                Match::Thread(thread) => Some(Self::completion_for_thread(
1400                                    thread,
1401                                    source_range.clone(),
1402                                    false,
1403                                    source.clone(),
1404                                    editor.clone(),
1405                                    mention_set.clone(),
1406                                    workspace.clone(),
1407                                    cx,
1408                                )),
1409                                Match::RecentThread(thread) => Some(Self::completion_for_thread(
1410                                    thread,
1411                                    source_range.clone(),
1412                                    true,
1413                                    source.clone(),
1414                                    editor.clone(),
1415                                    mention_set.clone(),
1416                                    workspace.clone(),
1417                                    cx,
1418                                )),
1419                                Match::Rules(user_rules) => Some(Self::completion_for_rules(
1420                                    user_rules,
1421                                    source_range.clone(),
1422                                    source.clone(),
1423                                    editor.clone(),
1424                                    mention_set.clone(),
1425                                    workspace.clone(),
1426                                    cx,
1427                                )),
1428                                Match::Fetch(url) => Self::completion_for_fetch(
1429                                    source_range.clone(),
1430                                    url,
1431                                    source.clone(),
1432                                    editor.clone(),
1433                                    mention_set.clone(),
1434                                    workspace.clone(),
1435                                    cx,
1436                                ),
1437                                Match::Entry(EntryMatch { entry, .. }) => {
1438                                    Self::completion_for_entry(
1439                                        entry,
1440                                        source_range.clone(),
1441                                        editor.clone(),
1442                                        mention_set.clone(),
1443                                        &workspace,
1444                                        cx,
1445                                    )
1446                                }
1447                            })
1448                            .collect::<Vec<_>>()
1449                    });
1450
1451                    Ok(vec![CompletionResponse {
1452                        completions,
1453                        display_options: CompletionDisplayOptions {
1454                            dynamic_width: true,
1455                        },
1456                        // Since this does its own filtering (see `filter_completions()` returns false),
1457                        // there is no benefit to computing whether this set of completions is incomplete.
1458                        is_incomplete: true,
1459                    }])
1460                })
1461            }
1462        }
1463    }
1464
1465    fn is_completion_trigger(
1466        &self,
1467        buffer: &Entity<language::Buffer>,
1468        position: language::Anchor,
1469        _text: &str,
1470        _trigger_in_words: bool,
1471        cx: &mut Context<Editor>,
1472    ) -> bool {
1473        let buffer = buffer.read(cx);
1474        let position = position.to_point(buffer);
1475        let line_start = Point::new(position.row, 0);
1476        let offset_to_line = buffer.point_to_offset(line_start);
1477        let mut lines = buffer.text_for_range(line_start..position).lines();
1478        if let Some(line) = lines.next() {
1479            PromptCompletion::try_parse(line, offset_to_line, &self.source.supported_modes(cx))
1480                .filter(|completion| {
1481                    // Right now we don't support completing arguments of slash commands
1482                    let is_slash_command_with_argument = matches!(
1483                        completion,
1484                        PromptCompletion::SlashCommand(SlashCommandCompletion {
1485                            argument: Some(_),
1486                            ..
1487                        })
1488                    );
1489                    !is_slash_command_with_argument
1490                })
1491                .map(|completion| {
1492                    completion.source_range().start <= offset_to_line + position.column as usize
1493                        && completion.source_range().end
1494                            >= offset_to_line + position.column as usize
1495                })
1496                .unwrap_or(false)
1497        } else {
1498            false
1499        }
1500    }
1501
1502    fn sort_completions(&self) -> bool {
1503        false
1504    }
1505
1506    fn filter_completions(&self) -> bool {
1507        false
1508    }
1509}
1510
1511fn confirm_completion_callback<T: PromptCompletionProviderDelegate>(
1512    crease_text: SharedString,
1513    start: Anchor,
1514    content_len: usize,
1515    mention_uri: MentionUri,
1516    source: Arc<T>,
1517    editor: WeakEntity<Editor>,
1518    mention_set: WeakEntity<MentionSet>,
1519    workspace: Entity<Workspace>,
1520) -> Arc<dyn Fn(CompletionIntent, &mut Window, &mut App) -> bool + Send + Sync> {
1521    Arc::new(move |_, window, cx| {
1522        let source = source.clone();
1523        let editor = editor.clone();
1524        let mention_set = mention_set.clone();
1525        let crease_text = crease_text.clone();
1526        let mention_uri = mention_uri.clone();
1527        let workspace = workspace.clone();
1528        window.defer(cx, move |window, cx| {
1529            if let Some(editor) = editor.upgrade() {
1530                mention_set
1531                    .clone()
1532                    .update(cx, |mention_set, cx| {
1533                        mention_set
1534                            .confirm_mention_completion(
1535                                crease_text,
1536                                start,
1537                                content_len,
1538                                mention_uri,
1539                                source.supports_images(cx),
1540                                editor,
1541                                &workspace,
1542                                window,
1543                                cx,
1544                            )
1545                            .detach();
1546                    })
1547                    .ok();
1548            }
1549        });
1550        false
1551    })
1552}
1553
1554#[derive(Debug, PartialEq)]
1555enum PromptCompletion {
1556    SlashCommand(SlashCommandCompletion),
1557    Mention(MentionCompletion),
1558}
1559
1560impl PromptCompletion {
1561    fn source_range(&self) -> Range<usize> {
1562        match self {
1563            Self::SlashCommand(completion) => completion.source_range.clone(),
1564            Self::Mention(completion) => completion.source_range.clone(),
1565        }
1566    }
1567
1568    fn try_parse(
1569        line: &str,
1570        offset_to_line: usize,
1571        supported_modes: &[PromptContextType],
1572    ) -> Option<Self> {
1573        if line.contains('@') {
1574            if let Some(mention) =
1575                MentionCompletion::try_parse(line, offset_to_line, supported_modes)
1576            {
1577                return Some(Self::Mention(mention));
1578            }
1579        }
1580        SlashCommandCompletion::try_parse(line, offset_to_line).map(Self::SlashCommand)
1581    }
1582}
1583
1584#[derive(Debug, Default, PartialEq)]
1585pub struct SlashCommandCompletion {
1586    pub source_range: Range<usize>,
1587    pub command: Option<String>,
1588    pub argument: Option<String>,
1589}
1590
1591impl SlashCommandCompletion {
1592    pub fn try_parse(line: &str, offset_to_line: usize) -> Option<Self> {
1593        // If we decide to support commands that are not at the beginning of the prompt, we can remove this check
1594        if !line.starts_with('/') || offset_to_line != 0 {
1595            return None;
1596        }
1597
1598        let (prefix, last_command) = line.rsplit_once('/')?;
1599        if prefix.chars().last().is_some_and(|c| !c.is_whitespace())
1600            || last_command.starts_with(char::is_whitespace)
1601        {
1602            return None;
1603        }
1604
1605        let mut argument = None;
1606        let mut command = None;
1607        if let Some((command_text, args)) = last_command.split_once(char::is_whitespace) {
1608            if !args.is_empty() {
1609                argument = Some(args.trim_end().to_string());
1610            }
1611            command = Some(command_text.to_string());
1612        } else if !last_command.is_empty() {
1613            command = Some(last_command.to_string());
1614        };
1615
1616        Some(Self {
1617            source_range: prefix.len() + offset_to_line
1618                ..line
1619                    .rfind(|c: char| !c.is_whitespace())
1620                    .unwrap_or_else(|| line.len())
1621                    + 1
1622                    + offset_to_line,
1623            command,
1624            argument,
1625        })
1626    }
1627}
1628
1629#[derive(Debug, Default, PartialEq)]
1630struct MentionCompletion {
1631    source_range: Range<usize>,
1632    mode: Option<PromptContextType>,
1633    argument: Option<String>,
1634}
1635
1636impl MentionCompletion {
1637    fn try_parse(
1638        line: &str,
1639        offset_to_line: usize,
1640        supported_modes: &[PromptContextType],
1641    ) -> Option<Self> {
1642        let last_mention_start = line.rfind('@')?;
1643
1644        // No whitespace immediately after '@'
1645        if line[last_mention_start + 1..]
1646            .chars()
1647            .next()
1648            .is_some_and(|c| c.is_whitespace())
1649        {
1650            return None;
1651        }
1652
1653        //  Must be a word boundary before '@'
1654        if last_mention_start > 0
1655            && line[..last_mention_start]
1656                .chars()
1657                .last()
1658                .is_some_and(|c| !c.is_whitespace())
1659        {
1660            return None;
1661        }
1662
1663        let rest_of_line = &line[last_mention_start + 1..];
1664
1665        let mut mode = None;
1666        let mut argument = None;
1667
1668        let mut parts = rest_of_line.split_whitespace();
1669        let mut end = last_mention_start + 1;
1670
1671        if let Some(mode_text) = parts.next() {
1672            // Safe since we check no leading whitespace above
1673            end += mode_text.len();
1674
1675            if let Some(parsed_mode) = PromptContextType::try_from(mode_text).ok()
1676                && supported_modes.contains(&parsed_mode)
1677            {
1678                mode = Some(parsed_mode);
1679            } else {
1680                argument = Some(mode_text.to_string());
1681            }
1682            match rest_of_line[mode_text.len()..].find(|c: char| !c.is_whitespace()) {
1683                Some(whitespace_count) => {
1684                    if let Some(argument_text) = parts.next() {
1685                        // If mode wasn't recognized but we have an argument, don't suggest completions
1686                        // (e.g. '@something word')
1687                        if mode.is_none() && !argument_text.is_empty() {
1688                            return None;
1689                        }
1690
1691                        argument = Some(argument_text.to_string());
1692                        end += whitespace_count + argument_text.len();
1693                    }
1694                }
1695                None => {
1696                    // Rest of line is entirely whitespace
1697                    end += rest_of_line.len() - mode_text.len();
1698                }
1699            }
1700        }
1701
1702        Some(Self {
1703            source_range: last_mention_start + offset_to_line..end + offset_to_line,
1704            mode,
1705            argument,
1706        })
1707    }
1708}
1709
1710fn diagnostics_label(
1711    summary: DiagnosticSummary,
1712    include_errors: bool,
1713    include_warnings: bool,
1714) -> String {
1715    let mut parts = Vec::new();
1716
1717    if include_errors && summary.error_count > 0 {
1718        parts.push(format!(
1719            "{} {}",
1720            summary.error_count,
1721            pluralize("error", summary.error_count)
1722        ));
1723    }
1724
1725    if include_warnings && summary.warning_count > 0 {
1726        parts.push(format!(
1727            "{} {}",
1728            summary.warning_count,
1729            pluralize("warning", summary.warning_count)
1730        ));
1731    }
1732
1733    if parts.is_empty() {
1734        return "Diagnostics".into();
1735    }
1736
1737    let body = if parts.len() == 2 {
1738        format!("{} and {}", parts[0], parts[1])
1739    } else {
1740        parts
1741            .pop()
1742            .expect("at least one part present after non-empty check")
1743    };
1744
1745    format!("Diagnostics: {body}")
1746}
1747
1748fn diagnostics_submenu_label(
1749    summary: DiagnosticSummary,
1750    include_errors: bool,
1751    include_warnings: bool,
1752) -> String {
1753    match (include_errors, include_warnings) {
1754        (true, true) => format!(
1755            "{} {} & {} {}",
1756            summary.error_count,
1757            pluralize("error", summary.error_count),
1758            summary.warning_count,
1759            pluralize("warning", summary.warning_count)
1760        ),
1761        (true, _) => format!(
1762            "{} {}",
1763            summary.error_count,
1764            pluralize("error", summary.error_count)
1765        ),
1766        (_, true) => format!(
1767            "{} {}",
1768            summary.warning_count,
1769            pluralize("warning", summary.warning_count)
1770        ),
1771        _ => "Diagnostics".into(),
1772    }
1773}
1774
1775fn diagnostics_crease_label(
1776    summary: DiagnosticSummary,
1777    include_errors: bool,
1778    include_warnings: bool,
1779) -> SharedString {
1780    diagnostics_label(summary, include_errors, include_warnings).into()
1781}
1782
1783fn pluralize(noun: &str, count: usize) -> String {
1784    if count == 1 {
1785        noun.to_string()
1786    } else {
1787        format!("{noun}s")
1788    }
1789}
1790
1791pub(crate) fn search_files(
1792    query: String,
1793    cancellation_flag: Arc<AtomicBool>,
1794    workspace: &Entity<Workspace>,
1795    cx: &App,
1796) -> Task<Vec<FileMatch>> {
1797    if query.is_empty() {
1798        let workspace = workspace.read(cx);
1799        let project = workspace.project().read(cx);
1800        let visible_worktrees = workspace.visible_worktrees(cx).collect::<Vec<_>>();
1801        let include_root_name = visible_worktrees.len() > 1;
1802
1803        let recent_matches = workspace
1804            .recent_navigation_history(Some(10), cx)
1805            .into_iter()
1806            .map(|(project_path, _)| {
1807                let path_prefix = if include_root_name {
1808                    project
1809                        .worktree_for_id(project_path.worktree_id, cx)
1810                        .map(|wt| wt.read(cx).root_name().into())
1811                        .unwrap_or_else(|| RelPath::empty().into())
1812                } else {
1813                    RelPath::empty().into()
1814                };
1815
1816                FileMatch {
1817                    mat: PathMatch {
1818                        score: 0.,
1819                        positions: Vec::new(),
1820                        worktree_id: project_path.worktree_id.to_usize(),
1821                        path: project_path.path,
1822                        path_prefix,
1823                        distance_to_relative_ancestor: 0,
1824                        is_dir: false,
1825                    },
1826                    is_recent: true,
1827                }
1828            });
1829
1830        let file_matches = visible_worktrees.into_iter().flat_map(|worktree| {
1831            let worktree = worktree.read(cx);
1832            let path_prefix: Arc<RelPath> = if include_root_name {
1833                worktree.root_name().into()
1834            } else {
1835                RelPath::empty().into()
1836            };
1837            worktree.entries(false, 0).map(move |entry| FileMatch {
1838                mat: PathMatch {
1839                    score: 0.,
1840                    positions: Vec::new(),
1841                    worktree_id: worktree.id().to_usize(),
1842                    path: entry.path.clone(),
1843                    path_prefix: path_prefix.clone(),
1844                    distance_to_relative_ancestor: 0,
1845                    is_dir: entry.is_dir(),
1846                },
1847                is_recent: false,
1848            })
1849        });
1850
1851        Task::ready(recent_matches.chain(file_matches).collect())
1852    } else {
1853        let workspace = workspace.read(cx);
1854        let relative_to = workspace
1855            .recent_navigation_history_iter(cx)
1856            .next()
1857            .map(|(path, _)| path.path);
1858        let worktrees = workspace.visible_worktrees(cx).collect::<Vec<_>>();
1859        let include_root_name = worktrees.len() > 1;
1860        let candidate_sets = worktrees
1861            .into_iter()
1862            .map(|worktree| {
1863                let worktree = worktree.read(cx);
1864
1865                PathMatchCandidateSet {
1866                    snapshot: worktree.snapshot(),
1867                    include_ignored: worktree.root_entry().is_some_and(|entry| entry.is_ignored),
1868                    include_root_name,
1869                    candidates: project::Candidates::Entries,
1870                }
1871            })
1872            .collect::<Vec<_>>();
1873
1874        let executor = cx.background_executor().clone();
1875        cx.foreground_executor().spawn(async move {
1876            fuzzy::match_path_sets(
1877                candidate_sets.as_slice(),
1878                query.as_str(),
1879                &relative_to,
1880                false,
1881                100,
1882                &cancellation_flag,
1883                executor,
1884            )
1885            .await
1886            .into_iter()
1887            .map(|mat| FileMatch {
1888                mat,
1889                is_recent: false,
1890            })
1891            .collect::<Vec<_>>()
1892        })
1893    }
1894}
1895
1896pub(crate) fn search_symbols(
1897    query: String,
1898    cancellation_flag: Arc<AtomicBool>,
1899    workspace: &Entity<Workspace>,
1900    cx: &mut App,
1901) -> Task<Vec<SymbolMatch>> {
1902    let symbols_task = workspace.update(cx, |workspace, cx| {
1903        workspace
1904            .project()
1905            .update(cx, |project, cx| project.symbols(&query, cx))
1906    });
1907    let project = workspace.read(cx).project().clone();
1908    cx.spawn(async move |cx| {
1909        let Some(symbols) = symbols_task.await.log_err() else {
1910            return Vec::new();
1911        };
1912        let (visible_match_candidates, external_match_candidates): (Vec<_>, Vec<_>) = project
1913            .update(cx, |project, cx| {
1914                symbols
1915                    .iter()
1916                    .enumerate()
1917                    .map(|(id, symbol)| StringMatchCandidate::new(id, symbol.label.filter_text()))
1918                    .partition(|candidate| match &symbols[candidate.id].path {
1919                        SymbolLocation::InProject(project_path) => project
1920                            .entry_for_path(project_path, cx)
1921                            .is_some_and(|e| !e.is_ignored),
1922                        SymbolLocation::OutsideProject { .. } => false,
1923                    })
1924            });
1925        // Try to support rust-analyzer's path based symbols feature which
1926        // allows to search by rust path syntax, in that case we only want to
1927        // filter names by the last segment
1928        // Ideally this was a first class LSP feature (rich queries)
1929        let query = query
1930            .rsplit_once("::")
1931            .map_or(&*query, |(_, suffix)| suffix)
1932            .to_owned();
1933        // Note if you make changes to this filtering below, also change `project_symbols::ProjectSymbolsDelegate::filter`
1934        const MAX_MATCHES: usize = 100;
1935        let mut visible_matches = cx.foreground_executor().block_on(fuzzy::match_strings(
1936            &visible_match_candidates,
1937            &query,
1938            false,
1939            true,
1940            MAX_MATCHES,
1941            &cancellation_flag,
1942            cx.background_executor().clone(),
1943        ));
1944        let mut external_matches = cx.foreground_executor().block_on(fuzzy::match_strings(
1945            &external_match_candidates,
1946            &query,
1947            false,
1948            true,
1949            MAX_MATCHES - visible_matches.len().min(MAX_MATCHES),
1950            &cancellation_flag,
1951            cx.background_executor().clone(),
1952        ));
1953        let sort_key_for_match = |mat: &StringMatch| {
1954            let symbol = &symbols[mat.candidate_id];
1955            (Reverse(OrderedFloat(mat.score)), symbol.label.filter_text())
1956        };
1957
1958        visible_matches.sort_unstable_by_key(sort_key_for_match);
1959        external_matches.sort_unstable_by_key(sort_key_for_match);
1960        let mut matches = visible_matches;
1961        matches.append(&mut external_matches);
1962
1963        matches
1964            .into_iter()
1965            .map(|mut mat| {
1966                let symbol = symbols[mat.candidate_id].clone();
1967                let filter_start = symbol.label.filter_range.start;
1968                for position in &mut mat.positions {
1969                    *position += filter_start;
1970                }
1971                SymbolMatch { symbol }
1972            })
1973            .collect()
1974    })
1975}
1976
1977fn filter_sessions_by_query(
1978    query: String,
1979    cancellation_flag: Arc<AtomicBool>,
1980    sessions: Vec<AgentSessionInfo>,
1981    cx: &mut App,
1982) -> Task<Vec<AgentSessionInfo>> {
1983    if query.is_empty() {
1984        return Task::ready(sessions);
1985    }
1986    let executor = cx.background_executor().clone();
1987    cx.background_spawn(async move {
1988        filter_sessions(query, cancellation_flag, sessions, executor).await
1989    })
1990}
1991
1992async fn filter_sessions(
1993    query: String,
1994    cancellation_flag: Arc<AtomicBool>,
1995    sessions: Vec<AgentSessionInfo>,
1996    executor: BackgroundExecutor,
1997) -> Vec<AgentSessionInfo> {
1998    let titles = sessions.iter().map(session_title).collect::<Vec<_>>();
1999    let candidates = titles
2000        .iter()
2001        .enumerate()
2002        .map(|(id, title)| StringMatchCandidate::new(id, title.as_ref()))
2003        .collect::<Vec<_>>();
2004    let matches = fuzzy::match_strings(
2005        &candidates,
2006        &query,
2007        false,
2008        true,
2009        100,
2010        &cancellation_flag,
2011        executor,
2012    )
2013    .await;
2014
2015    matches
2016        .into_iter()
2017        .map(|mat| sessions[mat.candidate_id].clone())
2018        .collect()
2019}
2020
2021pub(crate) fn search_rules(
2022    query: String,
2023    cancellation_flag: Arc<AtomicBool>,
2024    prompt_store: &Entity<PromptStore>,
2025    cx: &mut App,
2026) -> Task<Vec<RulesContextEntry>> {
2027    let search_task = prompt_store.read(cx).search(query, cancellation_flag, cx);
2028    cx.background_spawn(async move {
2029        search_task
2030            .await
2031            .into_iter()
2032            .flat_map(|metadata| {
2033                // Default prompts are filtered out as they are automatically included.
2034                if metadata.default {
2035                    None
2036                } else {
2037                    Some(RulesContextEntry {
2038                        prompt_id: metadata.id.as_user()?,
2039                        title: metadata.title?,
2040                    })
2041                }
2042            })
2043            .collect::<Vec<_>>()
2044    })
2045}
2046
2047pub struct SymbolMatch {
2048    pub symbol: Symbol,
2049}
2050
2051pub struct FileMatch {
2052    pub mat: PathMatch,
2053    pub is_recent: bool,
2054}
2055
2056pub fn extract_file_name_and_directory(
2057    path: &RelPath,
2058    path_prefix: &RelPath,
2059    path_style: PathStyle,
2060) -> (SharedString, Option<SharedString>) {
2061    // If path is empty, this means we're matching with the root directory itself
2062    // so we use the path_prefix as the name
2063    if path.is_empty() && !path_prefix.is_empty() {
2064        return (path_prefix.display(path_style).to_string().into(), None);
2065    }
2066
2067    let full_path = path_prefix.join(path);
2068    let file_name = full_path.file_name().unwrap_or_default();
2069    let display_path = full_path.display(path_style);
2070    let (directory, file_name) = display_path.split_at(display_path.len() - file_name.len());
2071    (
2072        file_name.to_string().into(),
2073        Some(SharedString::new(directory)).filter(|dir| !dir.is_empty()),
2074    )
2075}
2076
2077fn build_code_label_for_path(
2078    file: &str,
2079    directory: Option<&str>,
2080    line_number: Option<u32>,
2081    label_max_chars: usize,
2082    cx: &App,
2083) -> CodeLabel {
2084    let variable_highlight_id = cx
2085        .theme()
2086        .syntax()
2087        .highlight_id("variable")
2088        .map(HighlightId);
2089    let mut label = CodeLabelBuilder::default();
2090
2091    label.push_str(file, None);
2092    label.push_str(" ", None);
2093
2094    if let Some(directory) = directory {
2095        let file_name_chars = file.chars().count();
2096        // Account for: file_name + space (ellipsis is handled by truncate_and_remove_front)
2097        let directory_max_chars = label_max_chars
2098            .saturating_sub(file_name_chars)
2099            .saturating_sub(1);
2100        let truncated_directory = truncate_and_remove_front(directory, directory_max_chars.max(5));
2101        label.push_str(&truncated_directory, variable_highlight_id);
2102    }
2103    if let Some(line_number) = line_number {
2104        label.push_str(&format!(" L{}", line_number), variable_highlight_id);
2105    }
2106    label.build()
2107}
2108
2109fn selection_ranges(
2110    workspace: &Entity<Workspace>,
2111    cx: &mut App,
2112) -> Vec<(Entity<Buffer>, Range<text::Anchor>)> {
2113    let Some(editor) = workspace
2114        .read(cx)
2115        .active_item(cx)
2116        .and_then(|item| item.act_as::<Editor>(cx))
2117    else {
2118        return Vec::new();
2119    };
2120
2121    editor.update(cx, |editor, cx| {
2122        let selections = editor.selections.all_adjusted(&editor.display_snapshot(cx));
2123
2124        let buffer = editor.buffer().clone().read(cx);
2125        let snapshot = buffer.snapshot(cx);
2126
2127        selections
2128            .into_iter()
2129            .map(|s| snapshot.anchor_after(s.start)..snapshot.anchor_before(s.end))
2130            .flat_map(|range| {
2131                let (start_buffer, start) = buffer.text_anchor_for_position(range.start, cx)?;
2132                let (end_buffer, end) = buffer.text_anchor_for_position(range.end, cx)?;
2133                if start_buffer != end_buffer {
2134                    return None;
2135                }
2136                Some((start_buffer, start..end))
2137            })
2138            .collect::<Vec<_>>()
2139    })
2140}
2141
2142#[cfg(test)]
2143mod tests {
2144    use super::*;
2145    use gpui::TestAppContext;
2146
2147    #[test]
2148    fn test_prompt_completion_parse() {
2149        let supported_modes = vec![PromptContextType::File, PromptContextType::Symbol];
2150
2151        assert_eq!(
2152            PromptCompletion::try_parse("/", 0, &supported_modes),
2153            Some(PromptCompletion::SlashCommand(SlashCommandCompletion {
2154                source_range: 0..1,
2155                command: None,
2156                argument: None,
2157            }))
2158        );
2159
2160        assert_eq!(
2161            PromptCompletion::try_parse("@", 0, &supported_modes),
2162            Some(PromptCompletion::Mention(MentionCompletion {
2163                source_range: 0..1,
2164                mode: None,
2165                argument: None,
2166            }))
2167        );
2168
2169        assert_eq!(
2170            PromptCompletion::try_parse("/test @file", 0, &supported_modes),
2171            Some(PromptCompletion::Mention(MentionCompletion {
2172                source_range: 6..11,
2173                mode: Some(PromptContextType::File),
2174                argument: None,
2175            }))
2176        );
2177    }
2178
2179    #[test]
2180    fn test_slash_command_completion_parse() {
2181        assert_eq!(
2182            SlashCommandCompletion::try_parse("/", 0),
2183            Some(SlashCommandCompletion {
2184                source_range: 0..1,
2185                command: None,
2186                argument: None,
2187            })
2188        );
2189
2190        assert_eq!(
2191            SlashCommandCompletion::try_parse("/help", 0),
2192            Some(SlashCommandCompletion {
2193                source_range: 0..5,
2194                command: Some("help".to_string()),
2195                argument: None,
2196            })
2197        );
2198
2199        assert_eq!(
2200            SlashCommandCompletion::try_parse("/help ", 0),
2201            Some(SlashCommandCompletion {
2202                source_range: 0..5,
2203                command: Some("help".to_string()),
2204                argument: None,
2205            })
2206        );
2207
2208        assert_eq!(
2209            SlashCommandCompletion::try_parse("/help arg1", 0),
2210            Some(SlashCommandCompletion {
2211                source_range: 0..10,
2212                command: Some("help".to_string()),
2213                argument: Some("arg1".to_string()),
2214            })
2215        );
2216
2217        assert_eq!(
2218            SlashCommandCompletion::try_parse("/help arg1 arg2", 0),
2219            Some(SlashCommandCompletion {
2220                source_range: 0..15,
2221                command: Some("help".to_string()),
2222                argument: Some("arg1 arg2".to_string()),
2223            })
2224        );
2225
2226        assert_eq!(
2227            SlashCommandCompletion::try_parse("/拿不到命令 拿不到命令 ", 0),
2228            Some(SlashCommandCompletion {
2229                source_range: 0..30,
2230                command: Some("拿不到命令".to_string()),
2231                argument: Some("拿不到命令".to_string()),
2232            })
2233        );
2234
2235        assert_eq!(SlashCommandCompletion::try_parse("Lorem Ipsum", 0), None);
2236
2237        assert_eq!(SlashCommandCompletion::try_parse("Lorem /", 0), None);
2238
2239        assert_eq!(SlashCommandCompletion::try_parse("Lorem /help", 0), None);
2240
2241        assert_eq!(SlashCommandCompletion::try_parse("Lorem/", 0), None);
2242
2243        assert_eq!(SlashCommandCompletion::try_parse("/ ", 0), None);
2244    }
2245
2246    #[test]
2247    fn test_mention_completion_parse() {
2248        let supported_modes = vec![PromptContextType::File, PromptContextType::Symbol];
2249        let supported_modes_with_diagnostics = vec![
2250            PromptContextType::File,
2251            PromptContextType::Symbol,
2252            PromptContextType::Diagnostics,
2253        ];
2254
2255        assert_eq!(
2256            MentionCompletion::try_parse("Lorem Ipsum", 0, &supported_modes),
2257            None
2258        );
2259
2260        assert_eq!(
2261            MentionCompletion::try_parse("Lorem @", 0, &supported_modes),
2262            Some(MentionCompletion {
2263                source_range: 6..7,
2264                mode: None,
2265                argument: None,
2266            })
2267        );
2268
2269        assert_eq!(
2270            MentionCompletion::try_parse("Lorem @file", 0, &supported_modes),
2271            Some(MentionCompletion {
2272                source_range: 6..11,
2273                mode: Some(PromptContextType::File),
2274                argument: None,
2275            })
2276        );
2277
2278        assert_eq!(
2279            MentionCompletion::try_parse("Lorem @file ", 0, &supported_modes),
2280            Some(MentionCompletion {
2281                source_range: 6..12,
2282                mode: Some(PromptContextType::File),
2283                argument: None,
2284            })
2285        );
2286
2287        assert_eq!(
2288            MentionCompletion::try_parse("Lorem @file main.rs", 0, &supported_modes),
2289            Some(MentionCompletion {
2290                source_range: 6..19,
2291                mode: Some(PromptContextType::File),
2292                argument: Some("main.rs".to_string()),
2293            })
2294        );
2295
2296        assert_eq!(
2297            MentionCompletion::try_parse("Lorem @file main.rs ", 0, &supported_modes),
2298            Some(MentionCompletion {
2299                source_range: 6..19,
2300                mode: Some(PromptContextType::File),
2301                argument: Some("main.rs".to_string()),
2302            })
2303        );
2304
2305        assert_eq!(
2306            MentionCompletion::try_parse("Lorem @file main.rs Ipsum", 0, &supported_modes),
2307            Some(MentionCompletion {
2308                source_range: 6..19,
2309                mode: Some(PromptContextType::File),
2310                argument: Some("main.rs".to_string()),
2311            })
2312        );
2313
2314        assert_eq!(
2315            MentionCompletion::try_parse("Lorem @main", 0, &supported_modes),
2316            Some(MentionCompletion {
2317                source_range: 6..11,
2318                mode: None,
2319                argument: Some("main".to_string()),
2320            })
2321        );
2322
2323        assert_eq!(
2324            MentionCompletion::try_parse("Lorem @main ", 0, &supported_modes),
2325            Some(MentionCompletion {
2326                source_range: 6..12,
2327                mode: None,
2328                argument: Some("main".to_string()),
2329            })
2330        );
2331
2332        assert_eq!(
2333            MentionCompletion::try_parse("Lorem @main m", 0, &supported_modes),
2334            None
2335        );
2336
2337        assert_eq!(
2338            MentionCompletion::try_parse("test@", 0, &supported_modes),
2339            None
2340        );
2341
2342        // Allowed non-file mentions
2343
2344        assert_eq!(
2345            MentionCompletion::try_parse("Lorem @symbol main", 0, &supported_modes),
2346            Some(MentionCompletion {
2347                source_range: 6..18,
2348                mode: Some(PromptContextType::Symbol),
2349                argument: Some("main".to_string()),
2350            })
2351        );
2352
2353        assert_eq!(
2354            MentionCompletion::try_parse(
2355                "Lorem @symbol agent_ui::completion_provider",
2356                0,
2357                &supported_modes
2358            ),
2359            Some(MentionCompletion {
2360                source_range: 6..43,
2361                mode: Some(PromptContextType::Symbol),
2362                argument: Some("agent_ui::completion_provider".to_string()),
2363            })
2364        );
2365
2366        assert_eq!(
2367            MentionCompletion::try_parse(
2368                "Lorem @diagnostics",
2369                0,
2370                &supported_modes_with_diagnostics
2371            ),
2372            Some(MentionCompletion {
2373                source_range: 6..18,
2374                mode: Some(PromptContextType::Diagnostics),
2375                argument: None,
2376            })
2377        );
2378
2379        // Disallowed non-file mentions
2380        assert_eq!(
2381            MentionCompletion::try_parse("Lorem @symbol main", 0, &[PromptContextType::File]),
2382            None
2383        );
2384
2385        assert_eq!(
2386            MentionCompletion::try_parse("Lorem@symbol", 0, &supported_modes),
2387            None,
2388            "Should not parse mention inside word"
2389        );
2390
2391        assert_eq!(
2392            MentionCompletion::try_parse("Lorem @ file", 0, &supported_modes),
2393            None,
2394            "Should not parse with a space after @"
2395        );
2396
2397        assert_eq!(
2398            MentionCompletion::try_parse("@ file", 0, &supported_modes),
2399            None,
2400            "Should not parse with a space after @ at the start of the line"
2401        );
2402    }
2403
2404    #[gpui::test]
2405    async fn test_filter_sessions_by_query(cx: &mut TestAppContext) {
2406        let mut alpha = AgentSessionInfo::new("session-alpha");
2407        alpha.title = Some("Alpha Session".into());
2408        let mut beta = AgentSessionInfo::new("session-beta");
2409        beta.title = Some("Beta Session".into());
2410
2411        let sessions = vec![alpha.clone(), beta];
2412
2413        let task = {
2414            let mut app = cx.app.borrow_mut();
2415            filter_sessions_by_query(
2416                "Alpha".into(),
2417                Arc::new(AtomicBool::default()),
2418                sessions,
2419                &mut app,
2420            )
2421        };
2422
2423        let results = task.await;
2424        assert_eq!(results.len(), 1);
2425        assert_eq!(results[0].session_id, alpha.session_id);
2426    }
2427
2428    #[gpui::test]
2429    async fn test_search_files_path_distance_ordering(cx: &mut TestAppContext) {
2430        use project::Project;
2431        use serde_json::json;
2432        use util::{path, rel_path::rel_path};
2433        use workspace::AppState;
2434
2435        let app_state = cx.update(|cx| {
2436            let state = AppState::test(cx);
2437            theme::init(theme::LoadThemes::JustBase, cx);
2438            editor::init(cx);
2439            state
2440        });
2441
2442        app_state
2443            .fs
2444            .as_fake()
2445            .insert_tree(
2446                path!("/root"),
2447                json!({
2448                    "dir1": { "a.txt": "" },
2449                    "dir2": {
2450                        "a.txt": "",
2451                        "b.txt": ""
2452                    }
2453                }),
2454            )
2455            .await;
2456
2457        let project = Project::test(app_state.fs.clone(), [path!("/root").as_ref()], cx).await;
2458        let (workspace, cx) =
2459            cx.add_window_view(|window, cx| workspace::Workspace::test_new(project, window, cx));
2460
2461        let worktree_id = cx.read(|cx| {
2462            let worktrees = workspace.read(cx).worktrees(cx).collect::<Vec<_>>();
2463            assert_eq!(worktrees.len(), 1);
2464            WorktreeId::from_usize(worktrees[0].entity_id().as_u64() as usize)
2465        });
2466
2467        // Open a file in dir2 to create navigation history.
2468        // When searching for "a.txt", dir2/a.txt should be sorted first because
2469        // it is closer to the most recently opened file (dir2/b.txt).
2470        let b_path = ProjectPath {
2471            worktree_id,
2472            path: rel_path("dir2/b.txt").into(),
2473        };
2474        workspace
2475            .update_in(cx, |workspace, window, cx| {
2476                workspace.open_path(b_path, None, true, window, cx)
2477            })
2478            .await
2479            .unwrap();
2480
2481        let results = cx
2482            .update(|_window, cx| {
2483                search_files(
2484                    "a.txt".into(),
2485                    Arc::new(AtomicBool::default()),
2486                    &workspace,
2487                    cx,
2488                )
2489            })
2490            .await;
2491
2492        assert_eq!(results.len(), 2, "expected 2 matching files");
2493        assert_eq!(
2494            results[0].mat.path.as_ref(),
2495            rel_path("dir2/a.txt"),
2496            "dir2/a.txt should be first because it's closer to the recently opened dir2/b.txt"
2497        );
2498        assert_eq!(
2499            results[1].mat.path.as_ref(),
2500            rel_path("dir1/a.txt"),
2501            "dir1/a.txt should be second"
2502        );
2503    }
2504}