completion_provider.rs

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