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 worktrees = workspace.read(cx).visible_worktrees(cx).collect::<Vec<_>>();
1854        let include_root_name = worktrees.len() > 1;
1855        let candidate_sets = worktrees
1856            .into_iter()
1857            .map(|worktree| {
1858                let worktree = worktree.read(cx);
1859
1860                PathMatchCandidateSet {
1861                    snapshot: worktree.snapshot(),
1862                    include_ignored: worktree.root_entry().is_some_and(|entry| entry.is_ignored),
1863                    include_root_name,
1864                    candidates: project::Candidates::Entries,
1865                }
1866            })
1867            .collect::<Vec<_>>();
1868
1869        let executor = cx.background_executor().clone();
1870        cx.foreground_executor().spawn(async move {
1871            fuzzy::match_path_sets(
1872                candidate_sets.as_slice(),
1873                query.as_str(),
1874                &None,
1875                false,
1876                100,
1877                &cancellation_flag,
1878                executor,
1879            )
1880            .await
1881            .into_iter()
1882            .map(|mat| FileMatch {
1883                mat,
1884                is_recent: false,
1885            })
1886            .collect::<Vec<_>>()
1887        })
1888    }
1889}
1890
1891pub(crate) fn search_symbols(
1892    query: String,
1893    cancellation_flag: Arc<AtomicBool>,
1894    workspace: &Entity<Workspace>,
1895    cx: &mut App,
1896) -> Task<Vec<SymbolMatch>> {
1897    let symbols_task = workspace.update(cx, |workspace, cx| {
1898        workspace
1899            .project()
1900            .update(cx, |project, cx| project.symbols(&query, cx))
1901    });
1902    let project = workspace.read(cx).project().clone();
1903    cx.spawn(async move |cx| {
1904        let Some(symbols) = symbols_task.await.log_err() else {
1905            return Vec::new();
1906        };
1907        let (visible_match_candidates, external_match_candidates): (Vec<_>, Vec<_>) = project
1908            .update(cx, |project, cx| {
1909                symbols
1910                    .iter()
1911                    .enumerate()
1912                    .map(|(id, symbol)| StringMatchCandidate::new(id, symbol.label.filter_text()))
1913                    .partition(|candidate| match &symbols[candidate.id].path {
1914                        SymbolLocation::InProject(project_path) => project
1915                            .entry_for_path(project_path, cx)
1916                            .is_some_and(|e| !e.is_ignored),
1917                        SymbolLocation::OutsideProject { .. } => false,
1918                    })
1919            });
1920        // Try to support rust-analyzer's path based symbols feature which
1921        // allows to search by rust path syntax, in that case we only want to
1922        // filter names by the last segment
1923        // Ideally this was a first class LSP feature (rich queries)
1924        let query = query
1925            .rsplit_once("::")
1926            .map_or(&*query, |(_, suffix)| suffix)
1927            .to_owned();
1928        // Note if you make changes to this filtering below, also change `project_symbols::ProjectSymbolsDelegate::filter`
1929        const MAX_MATCHES: usize = 100;
1930        let mut visible_matches = cx.foreground_executor().block_on(fuzzy::match_strings(
1931            &visible_match_candidates,
1932            &query,
1933            false,
1934            true,
1935            MAX_MATCHES,
1936            &cancellation_flag,
1937            cx.background_executor().clone(),
1938        ));
1939        let mut external_matches = cx.foreground_executor().block_on(fuzzy::match_strings(
1940            &external_match_candidates,
1941            &query,
1942            false,
1943            true,
1944            MAX_MATCHES - visible_matches.len().min(MAX_MATCHES),
1945            &cancellation_flag,
1946            cx.background_executor().clone(),
1947        ));
1948        let sort_key_for_match = |mat: &StringMatch| {
1949            let symbol = &symbols[mat.candidate_id];
1950            (Reverse(OrderedFloat(mat.score)), symbol.label.filter_text())
1951        };
1952
1953        visible_matches.sort_unstable_by_key(sort_key_for_match);
1954        external_matches.sort_unstable_by_key(sort_key_for_match);
1955        let mut matches = visible_matches;
1956        matches.append(&mut external_matches);
1957
1958        matches
1959            .into_iter()
1960            .map(|mut mat| {
1961                let symbol = symbols[mat.candidate_id].clone();
1962                let filter_start = symbol.label.filter_range.start;
1963                for position in &mut mat.positions {
1964                    *position += filter_start;
1965                }
1966                SymbolMatch { symbol }
1967            })
1968            .collect()
1969    })
1970}
1971
1972fn filter_sessions_by_query(
1973    query: String,
1974    cancellation_flag: Arc<AtomicBool>,
1975    sessions: Vec<AgentSessionInfo>,
1976    cx: &mut App,
1977) -> Task<Vec<AgentSessionInfo>> {
1978    if query.is_empty() {
1979        return Task::ready(sessions);
1980    }
1981    let executor = cx.background_executor().clone();
1982    cx.background_spawn(async move {
1983        filter_sessions(query, cancellation_flag, sessions, executor).await
1984    })
1985}
1986
1987async fn filter_sessions(
1988    query: String,
1989    cancellation_flag: Arc<AtomicBool>,
1990    sessions: Vec<AgentSessionInfo>,
1991    executor: BackgroundExecutor,
1992) -> Vec<AgentSessionInfo> {
1993    let titles = sessions.iter().map(session_title).collect::<Vec<_>>();
1994    let candidates = titles
1995        .iter()
1996        .enumerate()
1997        .map(|(id, title)| StringMatchCandidate::new(id, title.as_ref()))
1998        .collect::<Vec<_>>();
1999    let matches = fuzzy::match_strings(
2000        &candidates,
2001        &query,
2002        false,
2003        true,
2004        100,
2005        &cancellation_flag,
2006        executor,
2007    )
2008    .await;
2009
2010    matches
2011        .into_iter()
2012        .map(|mat| sessions[mat.candidate_id].clone())
2013        .collect()
2014}
2015
2016pub(crate) fn search_rules(
2017    query: String,
2018    cancellation_flag: Arc<AtomicBool>,
2019    prompt_store: &Entity<PromptStore>,
2020    cx: &mut App,
2021) -> Task<Vec<RulesContextEntry>> {
2022    let search_task = prompt_store.read(cx).search(query, cancellation_flag, cx);
2023    cx.background_spawn(async move {
2024        search_task
2025            .await
2026            .into_iter()
2027            .flat_map(|metadata| {
2028                // Default prompts are filtered out as they are automatically included.
2029                if metadata.default {
2030                    None
2031                } else {
2032                    Some(RulesContextEntry {
2033                        prompt_id: metadata.id.as_user()?,
2034                        title: metadata.title?,
2035                    })
2036                }
2037            })
2038            .collect::<Vec<_>>()
2039    })
2040}
2041
2042pub struct SymbolMatch {
2043    pub symbol: Symbol,
2044}
2045
2046pub struct FileMatch {
2047    pub mat: PathMatch,
2048    pub is_recent: bool,
2049}
2050
2051pub fn extract_file_name_and_directory(
2052    path: &RelPath,
2053    path_prefix: &RelPath,
2054    path_style: PathStyle,
2055) -> (SharedString, Option<SharedString>) {
2056    // If path is empty, this means we're matching with the root directory itself
2057    // so we use the path_prefix as the name
2058    if path.is_empty() && !path_prefix.is_empty() {
2059        return (path_prefix.display(path_style).to_string().into(), None);
2060    }
2061
2062    let full_path = path_prefix.join(path);
2063    let file_name = full_path.file_name().unwrap_or_default();
2064    let display_path = full_path.display(path_style);
2065    let (directory, file_name) = display_path.split_at(display_path.len() - file_name.len());
2066    (
2067        file_name.to_string().into(),
2068        Some(SharedString::new(directory)).filter(|dir| !dir.is_empty()),
2069    )
2070}
2071
2072fn build_code_label_for_path(
2073    file: &str,
2074    directory: Option<&str>,
2075    line_number: Option<u32>,
2076    label_max_chars: usize,
2077    cx: &App,
2078) -> CodeLabel {
2079    let variable_highlight_id = cx
2080        .theme()
2081        .syntax()
2082        .highlight_id("variable")
2083        .map(HighlightId);
2084    let mut label = CodeLabelBuilder::default();
2085
2086    label.push_str(file, None);
2087    label.push_str(" ", None);
2088
2089    if let Some(directory) = directory {
2090        let file_name_chars = file.chars().count();
2091        // Account for: file_name + space (ellipsis is handled by truncate_and_remove_front)
2092        let directory_max_chars = label_max_chars
2093            .saturating_sub(file_name_chars)
2094            .saturating_sub(1);
2095        let truncated_directory = truncate_and_remove_front(directory, directory_max_chars.max(5));
2096        label.push_str(&truncated_directory, variable_highlight_id);
2097    }
2098    if let Some(line_number) = line_number {
2099        label.push_str(&format!(" L{}", line_number), variable_highlight_id);
2100    }
2101    label.build()
2102}
2103
2104fn selection_ranges(
2105    workspace: &Entity<Workspace>,
2106    cx: &mut App,
2107) -> Vec<(Entity<Buffer>, Range<text::Anchor>)> {
2108    let Some(editor) = workspace
2109        .read(cx)
2110        .active_item(cx)
2111        .and_then(|item| item.act_as::<Editor>(cx))
2112    else {
2113        return Vec::new();
2114    };
2115
2116    editor.update(cx, |editor, cx| {
2117        let selections = editor.selections.all_adjusted(&editor.display_snapshot(cx));
2118
2119        let buffer = editor.buffer().clone().read(cx);
2120        let snapshot = buffer.snapshot(cx);
2121
2122        selections
2123            .into_iter()
2124            .map(|s| snapshot.anchor_after(s.start)..snapshot.anchor_before(s.end))
2125            .flat_map(|range| {
2126                let (start_buffer, start) = buffer.text_anchor_for_position(range.start, cx)?;
2127                let (end_buffer, end) = buffer.text_anchor_for_position(range.end, cx)?;
2128                if start_buffer != end_buffer {
2129                    return None;
2130                }
2131                Some((start_buffer, start..end))
2132            })
2133            .collect::<Vec<_>>()
2134    })
2135}
2136
2137#[cfg(test)]
2138mod tests {
2139    use super::*;
2140    use gpui::TestAppContext;
2141
2142    #[test]
2143    fn test_prompt_completion_parse() {
2144        let supported_modes = vec![PromptContextType::File, PromptContextType::Symbol];
2145
2146        assert_eq!(
2147            PromptCompletion::try_parse("/", 0, &supported_modes),
2148            Some(PromptCompletion::SlashCommand(SlashCommandCompletion {
2149                source_range: 0..1,
2150                command: None,
2151                argument: None,
2152            }))
2153        );
2154
2155        assert_eq!(
2156            PromptCompletion::try_parse("@", 0, &supported_modes),
2157            Some(PromptCompletion::Mention(MentionCompletion {
2158                source_range: 0..1,
2159                mode: None,
2160                argument: None,
2161            }))
2162        );
2163
2164        assert_eq!(
2165            PromptCompletion::try_parse("/test @file", 0, &supported_modes),
2166            Some(PromptCompletion::Mention(MentionCompletion {
2167                source_range: 6..11,
2168                mode: Some(PromptContextType::File),
2169                argument: None,
2170            }))
2171        );
2172    }
2173
2174    #[test]
2175    fn test_slash_command_completion_parse() {
2176        assert_eq!(
2177            SlashCommandCompletion::try_parse("/", 0),
2178            Some(SlashCommandCompletion {
2179                source_range: 0..1,
2180                command: None,
2181                argument: None,
2182            })
2183        );
2184
2185        assert_eq!(
2186            SlashCommandCompletion::try_parse("/help", 0),
2187            Some(SlashCommandCompletion {
2188                source_range: 0..5,
2189                command: Some("help".to_string()),
2190                argument: None,
2191            })
2192        );
2193
2194        assert_eq!(
2195            SlashCommandCompletion::try_parse("/help ", 0),
2196            Some(SlashCommandCompletion {
2197                source_range: 0..5,
2198                command: Some("help".to_string()),
2199                argument: None,
2200            })
2201        );
2202
2203        assert_eq!(
2204            SlashCommandCompletion::try_parse("/help arg1", 0),
2205            Some(SlashCommandCompletion {
2206                source_range: 0..10,
2207                command: Some("help".to_string()),
2208                argument: Some("arg1".to_string()),
2209            })
2210        );
2211
2212        assert_eq!(
2213            SlashCommandCompletion::try_parse("/help arg1 arg2", 0),
2214            Some(SlashCommandCompletion {
2215                source_range: 0..15,
2216                command: Some("help".to_string()),
2217                argument: Some("arg1 arg2".to_string()),
2218            })
2219        );
2220
2221        assert_eq!(
2222            SlashCommandCompletion::try_parse("/拿不到命令 拿不到命令 ", 0),
2223            Some(SlashCommandCompletion {
2224                source_range: 0..30,
2225                command: Some("拿不到命令".to_string()),
2226                argument: Some("拿不到命令".to_string()),
2227            })
2228        );
2229
2230        assert_eq!(SlashCommandCompletion::try_parse("Lorem Ipsum", 0), None);
2231
2232        assert_eq!(SlashCommandCompletion::try_parse("Lorem /", 0), None);
2233
2234        assert_eq!(SlashCommandCompletion::try_parse("Lorem /help", 0), None);
2235
2236        assert_eq!(SlashCommandCompletion::try_parse("Lorem/", 0), None);
2237
2238        assert_eq!(SlashCommandCompletion::try_parse("/ ", 0), None);
2239    }
2240
2241    #[test]
2242    fn test_mention_completion_parse() {
2243        let supported_modes = vec![PromptContextType::File, PromptContextType::Symbol];
2244        let supported_modes_with_diagnostics = vec![
2245            PromptContextType::File,
2246            PromptContextType::Symbol,
2247            PromptContextType::Diagnostics,
2248        ];
2249
2250        assert_eq!(
2251            MentionCompletion::try_parse("Lorem Ipsum", 0, &supported_modes),
2252            None
2253        );
2254
2255        assert_eq!(
2256            MentionCompletion::try_parse("Lorem @", 0, &supported_modes),
2257            Some(MentionCompletion {
2258                source_range: 6..7,
2259                mode: None,
2260                argument: None,
2261            })
2262        );
2263
2264        assert_eq!(
2265            MentionCompletion::try_parse("Lorem @file", 0, &supported_modes),
2266            Some(MentionCompletion {
2267                source_range: 6..11,
2268                mode: Some(PromptContextType::File),
2269                argument: None,
2270            })
2271        );
2272
2273        assert_eq!(
2274            MentionCompletion::try_parse("Lorem @file ", 0, &supported_modes),
2275            Some(MentionCompletion {
2276                source_range: 6..12,
2277                mode: Some(PromptContextType::File),
2278                argument: None,
2279            })
2280        );
2281
2282        assert_eq!(
2283            MentionCompletion::try_parse("Lorem @file main.rs", 0, &supported_modes),
2284            Some(MentionCompletion {
2285                source_range: 6..19,
2286                mode: Some(PromptContextType::File),
2287                argument: Some("main.rs".to_string()),
2288            })
2289        );
2290
2291        assert_eq!(
2292            MentionCompletion::try_parse("Lorem @file main.rs ", 0, &supported_modes),
2293            Some(MentionCompletion {
2294                source_range: 6..19,
2295                mode: Some(PromptContextType::File),
2296                argument: Some("main.rs".to_string()),
2297            })
2298        );
2299
2300        assert_eq!(
2301            MentionCompletion::try_parse("Lorem @file main.rs Ipsum", 0, &supported_modes),
2302            Some(MentionCompletion {
2303                source_range: 6..19,
2304                mode: Some(PromptContextType::File),
2305                argument: Some("main.rs".to_string()),
2306            })
2307        );
2308
2309        assert_eq!(
2310            MentionCompletion::try_parse("Lorem @main", 0, &supported_modes),
2311            Some(MentionCompletion {
2312                source_range: 6..11,
2313                mode: None,
2314                argument: Some("main".to_string()),
2315            })
2316        );
2317
2318        assert_eq!(
2319            MentionCompletion::try_parse("Lorem @main ", 0, &supported_modes),
2320            Some(MentionCompletion {
2321                source_range: 6..12,
2322                mode: None,
2323                argument: Some("main".to_string()),
2324            })
2325        );
2326
2327        assert_eq!(
2328            MentionCompletion::try_parse("Lorem @main m", 0, &supported_modes),
2329            None
2330        );
2331
2332        assert_eq!(
2333            MentionCompletion::try_parse("test@", 0, &supported_modes),
2334            None
2335        );
2336
2337        // Allowed non-file mentions
2338
2339        assert_eq!(
2340            MentionCompletion::try_parse("Lorem @symbol main", 0, &supported_modes),
2341            Some(MentionCompletion {
2342                source_range: 6..18,
2343                mode: Some(PromptContextType::Symbol),
2344                argument: Some("main".to_string()),
2345            })
2346        );
2347
2348        assert_eq!(
2349            MentionCompletion::try_parse(
2350                "Lorem @symbol agent_ui::completion_provider",
2351                0,
2352                &supported_modes
2353            ),
2354            Some(MentionCompletion {
2355                source_range: 6..43,
2356                mode: Some(PromptContextType::Symbol),
2357                argument: Some("agent_ui::completion_provider".to_string()),
2358            })
2359        );
2360
2361        assert_eq!(
2362            MentionCompletion::try_parse(
2363                "Lorem @diagnostics",
2364                0,
2365                &supported_modes_with_diagnostics
2366            ),
2367            Some(MentionCompletion {
2368                source_range: 6..18,
2369                mode: Some(PromptContextType::Diagnostics),
2370                argument: None,
2371            })
2372        );
2373
2374        // Disallowed non-file mentions
2375        assert_eq!(
2376            MentionCompletion::try_parse("Lorem @symbol main", 0, &[PromptContextType::File]),
2377            None
2378        );
2379
2380        assert_eq!(
2381            MentionCompletion::try_parse("Lorem@symbol", 0, &supported_modes),
2382            None,
2383            "Should not parse mention inside word"
2384        );
2385
2386        assert_eq!(
2387            MentionCompletion::try_parse("Lorem @ file", 0, &supported_modes),
2388            None,
2389            "Should not parse with a space after @"
2390        );
2391
2392        assert_eq!(
2393            MentionCompletion::try_parse("@ file", 0, &supported_modes),
2394            None,
2395            "Should not parse with a space after @ at the start of the line"
2396        );
2397    }
2398
2399    #[gpui::test]
2400    async fn test_filter_sessions_by_query(cx: &mut TestAppContext) {
2401        let mut alpha = AgentSessionInfo::new("session-alpha");
2402        alpha.title = Some("Alpha Session".into());
2403        let mut beta = AgentSessionInfo::new("session-beta");
2404        beta.title = Some("Beta Session".into());
2405
2406        let sessions = vec![alpha.clone(), beta];
2407
2408        let task = {
2409            let mut app = cx.app.borrow_mut();
2410            filter_sessions_by_query(
2411                "Alpha".into(),
2412                Arc::new(AtomicBool::default()),
2413                sessions,
2414                &mut app,
2415            )
2416        };
2417
2418        let results = task.await;
2419        assert_eq!(results.len(), 1);
2420        assert_eq!(results[0].session_id, alpha.session_id);
2421    }
2422}