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::ThreadHistory;
   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<ThreadHistory>,
 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<ThreadHistory>,
 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                                        None,
 621                                        range,
 622                                        editor.downgrade(),
 623                                    );
 624
 625                                    let crease_id = editor.update(cx, |editor, cx| {
 626                                        let crease_ids =
 627                                            editor.insert_creases(vec![crease.clone()], cx);
 628                                        editor.fold_creases(vec![crease], false, window, cx);
 629                                        crease_ids.first().copied().unwrap()
 630                                    });
 631
 632                                    mention_set
 633                                        .update(cx, |mention_set, _| {
 634                                            mention_set.insert_mention(
 635                                                crease_id,
 636                                                mention_uri.clone(),
 637                                                gpui::Task::ready(Ok(
 638                                                    crate::mention_set::Mention::Text {
 639                                                        content: terminal_text,
 640                                                        tracked_buffers: vec![],
 641                                                    },
 642                                                ))
 643                                                .shared(),
 644                                            );
 645                                        })
 646                                        .ok();
 647                                }
 648                            }
 649                        });
 650                        false
 651                    }
 652                });
 653
 654                (
 655                    new_text,
 656                    callback
 657                        as Arc<
 658                            dyn Fn(CompletionIntent, &mut Window, &mut App) -> bool + Send + Sync,
 659                        >,
 660                )
 661            }
 662        };
 663
 664        Some(Completion {
 665            replace_range: source_range,
 666            new_text,
 667            label: CodeLabel::plain(action.label().to_string(), None),
 668            icon_path: Some(action.icon().path().into()),
 669            documentation: None,
 670            source: project::CompletionSource::Custom,
 671            match_start: None,
 672            snippet_deduplication_key: None,
 673            insert_text_mode: None,
 674            // This ensures that when a user accepts this completion, the
 675            // completion menu will still be shown after "@category " is
 676            // inserted
 677            confirm: Some(on_action),
 678        })
 679    }
 680
 681    fn completion_for_diagnostics(
 682        source_range: Range<Anchor>,
 683        source: Arc<T>,
 684        editor: WeakEntity<Editor>,
 685        mention_set: WeakEntity<MentionSet>,
 686        workspace: Entity<Workspace>,
 687        cx: &mut App,
 688    ) -> Vec<Completion> {
 689        let summary = workspace
 690            .read(cx)
 691            .project()
 692            .read(cx)
 693            .diagnostic_summary(false, cx);
 694        if summary.error_count == 0 && summary.warning_count == 0 {
 695            return Vec::new();
 696        }
 697        let icon_path = MentionUri::Diagnostics {
 698            include_errors: true,
 699            include_warnings: false,
 700        }
 701        .icon_path(cx);
 702
 703        let mut completions = Vec::new();
 704
 705        let cases = [
 706            (summary.error_count > 0, true, false),
 707            (summary.warning_count > 0, false, true),
 708            (
 709                summary.error_count > 0 && summary.warning_count > 0,
 710                true,
 711                true,
 712            ),
 713        ];
 714
 715        for (condition, include_errors, include_warnings) in cases {
 716            if condition {
 717                completions.push(Self::build_diagnostics_completion(
 718                    diagnostics_submenu_label(summary, include_errors, include_warnings),
 719                    source_range.clone(),
 720                    source.clone(),
 721                    editor.clone(),
 722                    mention_set.clone(),
 723                    workspace.clone(),
 724                    icon_path.clone(),
 725                    include_errors,
 726                    include_warnings,
 727                    summary,
 728                ));
 729            }
 730        }
 731
 732        completions
 733    }
 734
 735    fn build_diagnostics_completion(
 736        menu_label: String,
 737        source_range: Range<Anchor>,
 738        source: Arc<T>,
 739        editor: WeakEntity<Editor>,
 740        mention_set: WeakEntity<MentionSet>,
 741        workspace: Entity<Workspace>,
 742        icon_path: SharedString,
 743        include_errors: bool,
 744        include_warnings: bool,
 745        summary: DiagnosticSummary,
 746    ) -> Completion {
 747        let uri = MentionUri::Diagnostics {
 748            include_errors,
 749            include_warnings,
 750        };
 751        let crease_text = diagnostics_crease_label(summary, include_errors, include_warnings);
 752        let display_text = format!("@{}", crease_text);
 753        let new_text = format!("[{}]({}) ", display_text, uri.to_uri());
 754        let new_text_len = new_text.len();
 755        Completion {
 756            replace_range: source_range.clone(),
 757            new_text,
 758            label: CodeLabel::plain(menu_label, None),
 759            documentation: None,
 760            source: project::CompletionSource::Custom,
 761            icon_path: Some(icon_path),
 762            match_start: None,
 763            snippet_deduplication_key: None,
 764            insert_text_mode: None,
 765            confirm: Some(confirm_completion_callback(
 766                crease_text,
 767                source_range.start,
 768                new_text_len - 1,
 769                uri,
 770                source,
 771                editor,
 772                mention_set,
 773                workspace,
 774            )),
 775        }
 776    }
 777
 778    fn search_slash_commands(&self, query: String, cx: &mut App) -> Task<Vec<AvailableCommand>> {
 779        let commands = self.source.available_commands(cx);
 780        if commands.is_empty() {
 781            return Task::ready(Vec::new());
 782        }
 783
 784        cx.spawn(async move |cx| {
 785            let candidates = commands
 786                .iter()
 787                .enumerate()
 788                .map(|(id, command)| StringMatchCandidate::new(id, &command.name))
 789                .collect::<Vec<_>>();
 790
 791            let matches = fuzzy::match_strings(
 792                &candidates,
 793                &query,
 794                false,
 795                true,
 796                100,
 797                &Arc::new(AtomicBool::default()),
 798                cx.background_executor().clone(),
 799            )
 800            .await;
 801
 802            matches
 803                .into_iter()
 804                .map(|mat| commands[mat.candidate_id].clone())
 805                .collect()
 806        })
 807    }
 808
 809    fn search_mentions(
 810        &self,
 811        mode: Option<PromptContextType>,
 812        query: String,
 813        cancellation_flag: Arc<AtomicBool>,
 814        cx: &mut App,
 815    ) -> Task<Vec<Match>> {
 816        let Some(workspace) = self.workspace.upgrade() else {
 817            return Task::ready(Vec::default());
 818        };
 819        match mode {
 820            Some(PromptContextType::File) => {
 821                let search_files_task = search_files(query, cancellation_flag, &workspace, cx);
 822                cx.background_spawn(async move {
 823                    search_files_task
 824                        .await
 825                        .into_iter()
 826                        .map(Match::File)
 827                        .collect()
 828                })
 829            }
 830
 831            Some(PromptContextType::Symbol) => {
 832                let search_symbols_task = search_symbols(query, cancellation_flag, &workspace, cx);
 833                cx.background_spawn(async move {
 834                    search_symbols_task
 835                        .await
 836                        .into_iter()
 837                        .map(Match::Symbol)
 838                        .collect()
 839                })
 840            }
 841
 842            Some(PromptContextType::Thread) => {
 843                if let Some(history) = self.history.upgrade() {
 844                    let sessions = history.read(cx).sessions().to_vec();
 845                    let search_task =
 846                        filter_sessions_by_query(query, cancellation_flag, sessions, cx);
 847                    cx.spawn(async move |_cx| {
 848                        search_task.await.into_iter().map(Match::Thread).collect()
 849                    })
 850                } else {
 851                    Task::ready(Vec::new())
 852                }
 853            }
 854
 855            Some(PromptContextType::Fetch) => {
 856                if !query.is_empty() {
 857                    Task::ready(vec![Match::Fetch(query.into())])
 858                } else {
 859                    Task::ready(Vec::new())
 860                }
 861            }
 862
 863            Some(PromptContextType::Rules) => {
 864                if let Some(prompt_store) = self.prompt_store.as_ref() {
 865                    let search_rules_task =
 866                        search_rules(query, cancellation_flag, prompt_store, cx);
 867                    cx.background_spawn(async move {
 868                        search_rules_task
 869                            .await
 870                            .into_iter()
 871                            .map(Match::Rules)
 872                            .collect::<Vec<_>>()
 873                    })
 874                } else {
 875                    Task::ready(Vec::new())
 876                }
 877            }
 878
 879            Some(PromptContextType::Diagnostics) => Task::ready(Vec::new()),
 880
 881            None if query.is_empty() => {
 882                let recent_task = self.recent_context_picker_entries(&workspace, cx);
 883                let entries = self
 884                    .available_context_picker_entries(&workspace, cx)
 885                    .into_iter()
 886                    .map(|mode| {
 887                        Match::Entry(EntryMatch {
 888                            entry: mode,
 889                            mat: None,
 890                        })
 891                    })
 892                    .collect::<Vec<_>>();
 893
 894                cx.spawn(async move |_cx| {
 895                    let mut matches = recent_task.await;
 896                    matches.extend(entries);
 897                    matches
 898                })
 899            }
 900            None => {
 901                let executor = cx.background_executor().clone();
 902
 903                let search_files_task =
 904                    search_files(query.clone(), cancellation_flag, &workspace, cx);
 905
 906                let entries = self.available_context_picker_entries(&workspace, cx);
 907                let entry_candidates = entries
 908                    .iter()
 909                    .enumerate()
 910                    .map(|(ix, entry)| StringMatchCandidate::new(ix, entry.keyword()))
 911                    .collect::<Vec<_>>();
 912
 913                cx.background_spawn(async move {
 914                    let mut matches = search_files_task
 915                        .await
 916                        .into_iter()
 917                        .map(Match::File)
 918                        .collect::<Vec<_>>();
 919
 920                    let entry_matches = fuzzy::match_strings(
 921                        &entry_candidates,
 922                        &query,
 923                        false,
 924                        true,
 925                        100,
 926                        &Arc::new(AtomicBool::default()),
 927                        executor,
 928                    )
 929                    .await;
 930
 931                    matches.extend(entry_matches.into_iter().map(|mat| {
 932                        Match::Entry(EntryMatch {
 933                            entry: entries[mat.candidate_id],
 934                            mat: Some(mat),
 935                        })
 936                    }));
 937
 938                    matches.sort_by(|a, b| {
 939                        b.score()
 940                            .partial_cmp(&a.score())
 941                            .unwrap_or(std::cmp::Ordering::Equal)
 942                    });
 943
 944                    matches
 945                })
 946            }
 947        }
 948    }
 949
 950    fn recent_context_picker_entries(
 951        &self,
 952        workspace: &Entity<Workspace>,
 953        cx: &mut App,
 954    ) -> Task<Vec<Match>> {
 955        let mut recent = Vec::with_capacity(6);
 956
 957        let mut mentions = self
 958            .mention_set
 959            .read_with(cx, |store, _cx| store.mentions());
 960        let workspace = workspace.read(cx);
 961        let project = workspace.project().read(cx);
 962        let include_root_name = workspace.visible_worktrees(cx).count() > 1;
 963
 964        if let Some(agent_panel) = workspace.panel::<AgentPanel>(cx)
 965            && let Some(thread) = agent_panel.read(cx).active_agent_thread(cx)
 966        {
 967            let thread = thread.read(cx);
 968            mentions.insert(MentionUri::Thread {
 969                id: thread.session_id().clone(),
 970                name: thread.title().into(),
 971            });
 972        }
 973
 974        recent.extend(
 975            workspace
 976                .recent_navigation_history_iter(cx)
 977                .filter(|(_, abs_path)| {
 978                    abs_path.as_ref().is_none_or(|path| {
 979                        !mentions.contains(&MentionUri::File {
 980                            abs_path: path.clone(),
 981                        })
 982                    })
 983                })
 984                .take(4)
 985                .filter_map(|(project_path, _)| {
 986                    project
 987                        .worktree_for_id(project_path.worktree_id, cx)
 988                        .map(|worktree| {
 989                            let path_prefix = if include_root_name {
 990                                worktree.read(cx).root_name().into()
 991                            } else {
 992                                RelPath::empty().into()
 993                            };
 994                            Match::File(FileMatch {
 995                                mat: fuzzy::PathMatch {
 996                                    score: 1.,
 997                                    positions: Vec::new(),
 998                                    worktree_id: project_path.worktree_id.to_usize(),
 999                                    path: project_path.path,
1000                                    path_prefix,
1001                                    is_dir: false,
1002                                    distance_to_relative_ancestor: 0,
1003                                },
1004                                is_recent: true,
1005                            })
1006                        })
1007                }),
1008        );
1009
1010        if !self.source.supports_context(PromptContextType::Thread, cx) {
1011            return Task::ready(recent);
1012        }
1013
1014        if let Some(history) = self.history.upgrade() {
1015            const RECENT_COUNT: usize = 2;
1016            recent.extend(
1017                history
1018                    .read(cx)
1019                    .sessions()
1020                    .into_iter()
1021                    .filter(|session| {
1022                        let uri = MentionUri::Thread {
1023                            id: session.session_id.clone(),
1024                            name: session_title(session).to_string(),
1025                        };
1026                        !mentions.contains(&uri)
1027                    })
1028                    .take(RECENT_COUNT)
1029                    .cloned()
1030                    .map(Match::RecentThread),
1031            );
1032            return Task::ready(recent);
1033        }
1034
1035        Task::ready(recent)
1036    }
1037
1038    fn available_context_picker_entries(
1039        &self,
1040        workspace: &Entity<Workspace>,
1041        cx: &mut App,
1042    ) -> Vec<PromptContextEntry> {
1043        let mut entries = vec![
1044            PromptContextEntry::Mode(PromptContextType::File),
1045            PromptContextEntry::Mode(PromptContextType::Symbol),
1046        ];
1047
1048        if self.source.supports_context(PromptContextType::Thread, cx) {
1049            entries.push(PromptContextEntry::Mode(PromptContextType::Thread));
1050        }
1051
1052        let has_editor_selection = workspace
1053            .read(cx)
1054            .active_item(cx)
1055            .and_then(|item| item.downcast::<Editor>())
1056            .is_some_and(|editor| {
1057                editor.update(cx, |editor, cx| {
1058                    editor.has_non_empty_selection(&editor.display_snapshot(cx))
1059                })
1060            });
1061
1062        let has_terminal_selection = !terminal_selections_if_panel_open(workspace, cx).is_empty();
1063
1064        if has_editor_selection || has_terminal_selection {
1065            entries.push(PromptContextEntry::Action(
1066                PromptContextAction::AddSelections,
1067            ));
1068        }
1069
1070        if self.prompt_store.is_some() && self.source.supports_context(PromptContextType::Rules, cx)
1071        {
1072            entries.push(PromptContextEntry::Mode(PromptContextType::Rules));
1073        }
1074
1075        if self.source.supports_context(PromptContextType::Fetch, cx) {
1076            entries.push(PromptContextEntry::Mode(PromptContextType::Fetch));
1077        }
1078
1079        if self
1080            .source
1081            .supports_context(PromptContextType::Diagnostics, cx)
1082        {
1083            let summary = workspace
1084                .read(cx)
1085                .project()
1086                .read(cx)
1087                .diagnostic_summary(false, cx);
1088            if summary.error_count > 0 || summary.warning_count > 0 {
1089                entries.push(PromptContextEntry::Mode(PromptContextType::Diagnostics));
1090            }
1091        }
1092
1093        entries
1094    }
1095}
1096
1097impl<T: PromptCompletionProviderDelegate> CompletionProvider for PromptCompletionProvider<T> {
1098    fn completions(
1099        &self,
1100        _excerpt_id: ExcerptId,
1101        buffer: &Entity<Buffer>,
1102        buffer_position: Anchor,
1103        _trigger: CompletionContext,
1104        window: &mut Window,
1105        cx: &mut Context<Editor>,
1106    ) -> Task<Result<Vec<CompletionResponse>>> {
1107        let state = buffer.update(cx, |buffer, cx| {
1108            let position = buffer_position.to_point(buffer);
1109            let line_start = Point::new(position.row, 0);
1110            let offset_to_line = buffer.point_to_offset(line_start);
1111            let mut lines = buffer.text_for_range(line_start..position).lines();
1112            let line = lines.next()?;
1113            PromptCompletion::try_parse(line, offset_to_line, &self.source.supported_modes(cx))
1114        });
1115        let Some(state) = state else {
1116            return Task::ready(Ok(Vec::new()));
1117        };
1118
1119        let Some(workspace) = self.workspace.upgrade() else {
1120            return Task::ready(Ok(Vec::new()));
1121        };
1122
1123        let project = workspace.read(cx).project().clone();
1124        let snapshot = buffer.read(cx).snapshot();
1125        let source_range = snapshot.anchor_before(state.source_range().start)
1126            ..snapshot.anchor_after(state.source_range().end);
1127
1128        let source = self.source.clone();
1129        let editor = self.editor.clone();
1130        let mention_set = self.mention_set.downgrade();
1131        match state {
1132            PromptCompletion::SlashCommand(SlashCommandCompletion {
1133                command, argument, ..
1134            }) => {
1135                let search_task = self.search_slash_commands(command.unwrap_or_default(), cx);
1136                cx.background_spawn(async move {
1137                    let completions = search_task
1138                        .await
1139                        .into_iter()
1140                        .map(|command| {
1141                            let new_text = if let Some(argument) = argument.as_ref() {
1142                                format!("/{} {}", command.name, argument)
1143                            } else {
1144                                format!("/{} ", command.name)
1145                            };
1146
1147                            let is_missing_argument =
1148                                command.requires_argument && argument.is_none();
1149
1150                            Completion {
1151                                replace_range: source_range.clone(),
1152                                new_text,
1153                                label: CodeLabel::plain(command.name.to_string(), None),
1154                                documentation: Some(CompletionDocumentation::MultiLinePlainText(
1155                                    command.description.into(),
1156                                )),
1157                                source: project::CompletionSource::Custom,
1158                                icon_path: None,
1159                                match_start: None,
1160                                snippet_deduplication_key: None,
1161                                insert_text_mode: None,
1162                                confirm: Some(Arc::new({
1163                                    let source = source.clone();
1164                                    move |intent, _window, cx| {
1165                                        if !is_missing_argument {
1166                                            cx.defer({
1167                                                let source = source.clone();
1168                                                move |cx| match intent {
1169                                                    CompletionIntent::Complete
1170                                                    | CompletionIntent::CompleteWithInsert
1171                                                    | CompletionIntent::CompleteWithReplace => {
1172                                                        source.confirm_command(cx);
1173                                                    }
1174                                                    CompletionIntent::Compose => {}
1175                                                }
1176                                            });
1177                                        }
1178                                        false
1179                                    }
1180                                })),
1181                            }
1182                        })
1183                        .collect();
1184
1185                    Ok(vec![CompletionResponse {
1186                        completions,
1187                        display_options: CompletionDisplayOptions {
1188                            dynamic_width: true,
1189                        },
1190                        // Since this does its own filtering (see `filter_completions()` returns false),
1191                        // there is no benefit to computing whether this set of completions is incomplete.
1192                        is_incomplete: true,
1193                    }])
1194                })
1195            }
1196            PromptCompletion::Mention(MentionCompletion { mode, argument, .. }) => {
1197                if let Some(PromptContextType::Diagnostics) = mode {
1198                    if argument.is_some() {
1199                        return Task::ready(Ok(Vec::new()));
1200                    }
1201
1202                    let completions = Self::completion_for_diagnostics(
1203                        source_range.clone(),
1204                        source.clone(),
1205                        editor.clone(),
1206                        mention_set.clone(),
1207                        workspace.clone(),
1208                        cx,
1209                    );
1210                    if !completions.is_empty() {
1211                        return Task::ready(Ok(vec![CompletionResponse {
1212                            completions,
1213                            display_options: CompletionDisplayOptions::default(),
1214                            is_incomplete: false,
1215                        }]));
1216                    }
1217                }
1218
1219                let query = argument.unwrap_or_default();
1220                let search_task =
1221                    self.search_mentions(mode, query, Arc::<AtomicBool>::default(), cx);
1222
1223                // Calculate maximum characters available for the full label (file_name + space + directory)
1224                // based on maximum menu width after accounting for padding, spacing, and icon width
1225                let label_max_chars = {
1226                    // Base06 left padding + Base06 gap + Base06 right padding + icon width
1227                    let used_pixels = DynamicSpacing::Base06.px(cx) * 3.0
1228                        + IconSize::XSmall.rems() * window.rem_size();
1229
1230                    let style = window.text_style();
1231                    let font_id = window.text_system().resolve_font(&style.font());
1232                    let font_size = TextSize::Small.rems(cx).to_pixels(window.rem_size());
1233
1234                    // Fallback em_width of 10px matches file_finder.rs fallback for TextSize::Small
1235                    let em_width = cx
1236                        .text_system()
1237                        .em_width(font_id, font_size)
1238                        .unwrap_or(px(10.0));
1239
1240                    // Calculate available pixels for text (file_name + directory)
1241                    // Using max width since dynamic_width allows the menu to expand up to this
1242                    let available_pixels = COMPLETION_MENU_MAX_WIDTH - used_pixels;
1243
1244                    // Convert to character count (total available for file_name + directory)
1245                    (f32::from(available_pixels) / f32::from(em_width)) as usize
1246                };
1247
1248                cx.spawn(async move |_, cx| {
1249                    let matches = search_task.await;
1250
1251                    let completions = cx.update(|cx| {
1252                        matches
1253                            .into_iter()
1254                            .filter_map(|mat| match mat {
1255                                Match::File(FileMatch { mat, is_recent }) => {
1256                                    let project_path = ProjectPath {
1257                                        worktree_id: WorktreeId::from_usize(mat.worktree_id),
1258                                        path: mat.path.clone(),
1259                                    };
1260
1261                                    // If path is empty, this means we're matching with the root directory itself
1262                                    // so we use the path_prefix as the name
1263                                    let path_prefix = if mat.path.is_empty() {
1264                                        project
1265                                            .read(cx)
1266                                            .worktree_for_id(project_path.worktree_id, cx)
1267                                            .map(|wt| wt.read(cx).root_name().into())
1268                                            .unwrap_or_else(|| mat.path_prefix.clone())
1269                                    } else {
1270                                        mat.path_prefix.clone()
1271                                    };
1272
1273                                    Self::completion_for_path(
1274                                        project_path,
1275                                        &path_prefix,
1276                                        is_recent,
1277                                        mat.is_dir,
1278                                        source_range.clone(),
1279                                        source.clone(),
1280                                        editor.clone(),
1281                                        mention_set.clone(),
1282                                        workspace.clone(),
1283                                        project.clone(),
1284                                        label_max_chars,
1285                                        cx,
1286                                    )
1287                                }
1288                                Match::Symbol(SymbolMatch { symbol, .. }) => {
1289                                    Self::completion_for_symbol(
1290                                        symbol,
1291                                        source_range.clone(),
1292                                        source.clone(),
1293                                        editor.clone(),
1294                                        mention_set.clone(),
1295                                        workspace.clone(),
1296                                        label_max_chars,
1297                                        cx,
1298                                    )
1299                                }
1300                                Match::Thread(thread) => Some(Self::completion_for_thread(
1301                                    thread,
1302                                    source_range.clone(),
1303                                    false,
1304                                    source.clone(),
1305                                    editor.clone(),
1306                                    mention_set.clone(),
1307                                    workspace.clone(),
1308                                    cx,
1309                                )),
1310                                Match::RecentThread(thread) => Some(Self::completion_for_thread(
1311                                    thread,
1312                                    source_range.clone(),
1313                                    true,
1314                                    source.clone(),
1315                                    editor.clone(),
1316                                    mention_set.clone(),
1317                                    workspace.clone(),
1318                                    cx,
1319                                )),
1320                                Match::Rules(user_rules) => Some(Self::completion_for_rules(
1321                                    user_rules,
1322                                    source_range.clone(),
1323                                    source.clone(),
1324                                    editor.clone(),
1325                                    mention_set.clone(),
1326                                    workspace.clone(),
1327                                    cx,
1328                                )),
1329                                Match::Fetch(url) => Self::completion_for_fetch(
1330                                    source_range.clone(),
1331                                    url,
1332                                    source.clone(),
1333                                    editor.clone(),
1334                                    mention_set.clone(),
1335                                    workspace.clone(),
1336                                    cx,
1337                                ),
1338                                Match::Entry(EntryMatch { entry, .. }) => {
1339                                    Self::completion_for_entry(
1340                                        entry,
1341                                        source_range.clone(),
1342                                        editor.clone(),
1343                                        mention_set.clone(),
1344                                        &workspace,
1345                                        cx,
1346                                    )
1347                                }
1348                            })
1349                            .collect::<Vec<_>>()
1350                    });
1351
1352                    Ok(vec![CompletionResponse {
1353                        completions,
1354                        display_options: CompletionDisplayOptions {
1355                            dynamic_width: true,
1356                        },
1357                        // Since this does its own filtering (see `filter_completions()` returns false),
1358                        // there is no benefit to computing whether this set of completions is incomplete.
1359                        is_incomplete: true,
1360                    }])
1361                })
1362            }
1363        }
1364    }
1365
1366    fn is_completion_trigger(
1367        &self,
1368        buffer: &Entity<language::Buffer>,
1369        position: language::Anchor,
1370        _text: &str,
1371        _trigger_in_words: bool,
1372        cx: &mut Context<Editor>,
1373    ) -> bool {
1374        let buffer = buffer.read(cx);
1375        let position = position.to_point(buffer);
1376        let line_start = Point::new(position.row, 0);
1377        let offset_to_line = buffer.point_to_offset(line_start);
1378        let mut lines = buffer.text_for_range(line_start..position).lines();
1379        if let Some(line) = lines.next() {
1380            PromptCompletion::try_parse(line, offset_to_line, &self.source.supported_modes(cx))
1381                .filter(|completion| {
1382                    // Right now we don't support completing arguments of slash commands
1383                    let is_slash_command_with_argument = matches!(
1384                        completion,
1385                        PromptCompletion::SlashCommand(SlashCommandCompletion {
1386                            argument: Some(_),
1387                            ..
1388                        })
1389                    );
1390                    !is_slash_command_with_argument
1391                })
1392                .map(|completion| {
1393                    completion.source_range().start <= offset_to_line + position.column as usize
1394                        && completion.source_range().end
1395                            >= offset_to_line + position.column as usize
1396                })
1397                .unwrap_or(false)
1398        } else {
1399            false
1400        }
1401    }
1402
1403    fn sort_completions(&self) -> bool {
1404        false
1405    }
1406
1407    fn filter_completions(&self) -> bool {
1408        false
1409    }
1410}
1411
1412fn confirm_completion_callback<T: PromptCompletionProviderDelegate>(
1413    crease_text: SharedString,
1414    start: Anchor,
1415    content_len: usize,
1416    mention_uri: MentionUri,
1417    source: Arc<T>,
1418    editor: WeakEntity<Editor>,
1419    mention_set: WeakEntity<MentionSet>,
1420    workspace: Entity<Workspace>,
1421) -> Arc<dyn Fn(CompletionIntent, &mut Window, &mut App) -> bool + Send + Sync> {
1422    Arc::new(move |_, window, cx| {
1423        let source = source.clone();
1424        let editor = editor.clone();
1425        let mention_set = mention_set.clone();
1426        let crease_text = crease_text.clone();
1427        let mention_uri = mention_uri.clone();
1428        let workspace = workspace.clone();
1429        window.defer(cx, move |window, cx| {
1430            if let Some(editor) = editor.upgrade() {
1431                mention_set
1432                    .clone()
1433                    .update(cx, |mention_set, cx| {
1434                        mention_set
1435                            .confirm_mention_completion(
1436                                crease_text,
1437                                start,
1438                                content_len,
1439                                mention_uri,
1440                                source.supports_images(cx),
1441                                editor,
1442                                &workspace,
1443                                window,
1444                                cx,
1445                            )
1446                            .detach();
1447                    })
1448                    .ok();
1449            }
1450        });
1451        false
1452    })
1453}
1454
1455#[derive(Debug, PartialEq)]
1456enum PromptCompletion {
1457    SlashCommand(SlashCommandCompletion),
1458    Mention(MentionCompletion),
1459}
1460
1461impl PromptCompletion {
1462    fn source_range(&self) -> Range<usize> {
1463        match self {
1464            Self::SlashCommand(completion) => completion.source_range.clone(),
1465            Self::Mention(completion) => completion.source_range.clone(),
1466        }
1467    }
1468
1469    fn try_parse(
1470        line: &str,
1471        offset_to_line: usize,
1472        supported_modes: &[PromptContextType],
1473    ) -> Option<Self> {
1474        if line.contains('@') {
1475            if let Some(mention) =
1476                MentionCompletion::try_parse(line, offset_to_line, supported_modes)
1477            {
1478                return Some(Self::Mention(mention));
1479            }
1480        }
1481        SlashCommandCompletion::try_parse(line, offset_to_line).map(Self::SlashCommand)
1482    }
1483}
1484
1485#[derive(Debug, Default, PartialEq)]
1486pub struct SlashCommandCompletion {
1487    pub source_range: Range<usize>,
1488    pub command: Option<String>,
1489    pub argument: Option<String>,
1490}
1491
1492impl SlashCommandCompletion {
1493    pub fn try_parse(line: &str, offset_to_line: usize) -> Option<Self> {
1494        // If we decide to support commands that are not at the beginning of the prompt, we can remove this check
1495        if !line.starts_with('/') || offset_to_line != 0 {
1496            return None;
1497        }
1498
1499        let (prefix, last_command) = line.rsplit_once('/')?;
1500        if prefix.chars().last().is_some_and(|c| !c.is_whitespace())
1501            || last_command.starts_with(char::is_whitespace)
1502        {
1503            return None;
1504        }
1505
1506        let mut argument = None;
1507        let mut command = None;
1508        if let Some((command_text, args)) = last_command.split_once(char::is_whitespace) {
1509            if !args.is_empty() {
1510                argument = Some(args.trim_end().to_string());
1511            }
1512            command = Some(command_text.to_string());
1513        } else if !last_command.is_empty() {
1514            command = Some(last_command.to_string());
1515        };
1516
1517        Some(Self {
1518            source_range: prefix.len() + offset_to_line
1519                ..line
1520                    .rfind(|c: char| !c.is_whitespace())
1521                    .unwrap_or_else(|| line.len())
1522                    + 1
1523                    + offset_to_line,
1524            command,
1525            argument,
1526        })
1527    }
1528}
1529
1530#[derive(Debug, Default, PartialEq)]
1531struct MentionCompletion {
1532    source_range: Range<usize>,
1533    mode: Option<PromptContextType>,
1534    argument: Option<String>,
1535}
1536
1537impl MentionCompletion {
1538    fn try_parse(
1539        line: &str,
1540        offset_to_line: usize,
1541        supported_modes: &[PromptContextType],
1542    ) -> Option<Self> {
1543        let last_mention_start = line.rfind('@')?;
1544
1545        // No whitespace immediately after '@'
1546        if line[last_mention_start + 1..]
1547            .chars()
1548            .next()
1549            .is_some_and(|c| c.is_whitespace())
1550        {
1551            return None;
1552        }
1553
1554        //  Must be a word boundary before '@'
1555        if last_mention_start > 0
1556            && line[..last_mention_start]
1557                .chars()
1558                .last()
1559                .is_some_and(|c| !c.is_whitespace())
1560        {
1561            return None;
1562        }
1563
1564        let rest_of_line = &line[last_mention_start + 1..];
1565
1566        let mut mode = None;
1567        let mut argument = None;
1568
1569        let mut parts = rest_of_line.split_whitespace();
1570        let mut end = last_mention_start + 1;
1571
1572        if let Some(mode_text) = parts.next() {
1573            // Safe since we check no leading whitespace above
1574            end += mode_text.len();
1575
1576            if let Some(parsed_mode) = PromptContextType::try_from(mode_text).ok()
1577                && supported_modes.contains(&parsed_mode)
1578            {
1579                mode = Some(parsed_mode);
1580            } else {
1581                argument = Some(mode_text.to_string());
1582            }
1583            match rest_of_line[mode_text.len()..].find(|c: char| !c.is_whitespace()) {
1584                Some(whitespace_count) => {
1585                    if let Some(argument_text) = parts.next() {
1586                        // If mode wasn't recognized but we have an argument, don't suggest completions
1587                        // (e.g. '@something word')
1588                        if mode.is_none() && !argument_text.is_empty() {
1589                            return None;
1590                        }
1591
1592                        argument = Some(argument_text.to_string());
1593                        end += whitespace_count + argument_text.len();
1594                    }
1595                }
1596                None => {
1597                    // Rest of line is entirely whitespace
1598                    end += rest_of_line.len() - mode_text.len();
1599                }
1600            }
1601        }
1602
1603        Some(Self {
1604            source_range: last_mention_start + offset_to_line..end + offset_to_line,
1605            mode,
1606            argument,
1607        })
1608    }
1609}
1610
1611fn diagnostics_label(
1612    summary: DiagnosticSummary,
1613    include_errors: bool,
1614    include_warnings: bool,
1615) -> String {
1616    let mut parts = Vec::new();
1617
1618    if include_errors && summary.error_count > 0 {
1619        parts.push(format!(
1620            "{} {}",
1621            summary.error_count,
1622            pluralize("error", summary.error_count)
1623        ));
1624    }
1625
1626    if include_warnings && summary.warning_count > 0 {
1627        parts.push(format!(
1628            "{} {}",
1629            summary.warning_count,
1630            pluralize("warning", summary.warning_count)
1631        ));
1632    }
1633
1634    if parts.is_empty() {
1635        return "Diagnostics".into();
1636    }
1637
1638    let body = if parts.len() == 2 {
1639        format!("{} and {}", parts[0], parts[1])
1640    } else {
1641        parts
1642            .pop()
1643            .expect("at least one part present after non-empty check")
1644    };
1645
1646    format!("Diagnostics: {body}")
1647}
1648
1649fn diagnostics_submenu_label(
1650    summary: DiagnosticSummary,
1651    include_errors: bool,
1652    include_warnings: bool,
1653) -> String {
1654    match (include_errors, include_warnings) {
1655        (true, true) => format!(
1656            "{} {} & {} {}",
1657            summary.error_count,
1658            pluralize("error", summary.error_count),
1659            summary.warning_count,
1660            pluralize("warning", summary.warning_count)
1661        ),
1662        (true, _) => format!(
1663            "{} {}",
1664            summary.error_count,
1665            pluralize("error", summary.error_count)
1666        ),
1667        (_, true) => format!(
1668            "{} {}",
1669            summary.warning_count,
1670            pluralize("warning", summary.warning_count)
1671        ),
1672        _ => "Diagnostics".into(),
1673    }
1674}
1675
1676fn diagnostics_crease_label(
1677    summary: DiagnosticSummary,
1678    include_errors: bool,
1679    include_warnings: bool,
1680) -> SharedString {
1681    diagnostics_label(summary, include_errors, include_warnings).into()
1682}
1683
1684fn pluralize(noun: &str, count: usize) -> String {
1685    if count == 1 {
1686        noun.to_string()
1687    } else {
1688        format!("{noun}s")
1689    }
1690}
1691
1692pub(crate) fn search_files(
1693    query: String,
1694    cancellation_flag: Arc<AtomicBool>,
1695    workspace: &Entity<Workspace>,
1696    cx: &App,
1697) -> Task<Vec<FileMatch>> {
1698    if query.is_empty() {
1699        let workspace = workspace.read(cx);
1700        let project = workspace.project().read(cx);
1701        let visible_worktrees = workspace.visible_worktrees(cx).collect::<Vec<_>>();
1702        let include_root_name = visible_worktrees.len() > 1;
1703
1704        let recent_matches = workspace
1705            .recent_navigation_history(Some(10), cx)
1706            .into_iter()
1707            .map(|(project_path, _)| {
1708                let path_prefix = if include_root_name {
1709                    project
1710                        .worktree_for_id(project_path.worktree_id, cx)
1711                        .map(|wt| wt.read(cx).root_name().into())
1712                        .unwrap_or_else(|| RelPath::empty().into())
1713                } else {
1714                    RelPath::empty().into()
1715                };
1716
1717                FileMatch {
1718                    mat: PathMatch {
1719                        score: 0.,
1720                        positions: Vec::new(),
1721                        worktree_id: project_path.worktree_id.to_usize(),
1722                        path: project_path.path,
1723                        path_prefix,
1724                        distance_to_relative_ancestor: 0,
1725                        is_dir: false,
1726                    },
1727                    is_recent: true,
1728                }
1729            });
1730
1731        let file_matches = visible_worktrees.into_iter().flat_map(|worktree| {
1732            let worktree = worktree.read(cx);
1733            let path_prefix: Arc<RelPath> = if include_root_name {
1734                worktree.root_name().into()
1735            } else {
1736                RelPath::empty().into()
1737            };
1738            worktree.entries(false, 0).map(move |entry| FileMatch {
1739                mat: PathMatch {
1740                    score: 0.,
1741                    positions: Vec::new(),
1742                    worktree_id: worktree.id().to_usize(),
1743                    path: entry.path.clone(),
1744                    path_prefix: path_prefix.clone(),
1745                    distance_to_relative_ancestor: 0,
1746                    is_dir: entry.is_dir(),
1747                },
1748                is_recent: false,
1749            })
1750        });
1751
1752        Task::ready(recent_matches.chain(file_matches).collect())
1753    } else {
1754        let workspace = workspace.read(cx);
1755        let relative_to = workspace
1756            .recent_navigation_history_iter(cx)
1757            .next()
1758            .map(|(path, _)| path.path);
1759        let worktrees = workspace.visible_worktrees(cx).collect::<Vec<_>>();
1760        let include_root_name = worktrees.len() > 1;
1761        let candidate_sets = worktrees
1762            .into_iter()
1763            .map(|worktree| {
1764                let worktree = worktree.read(cx);
1765
1766                PathMatchCandidateSet {
1767                    snapshot: worktree.snapshot(),
1768                    include_ignored: worktree.root_entry().is_some_and(|entry| entry.is_ignored),
1769                    include_root_name,
1770                    candidates: project::Candidates::Entries,
1771                }
1772            })
1773            .collect::<Vec<_>>();
1774
1775        let executor = cx.background_executor().clone();
1776        cx.foreground_executor().spawn(async move {
1777            fuzzy::match_path_sets(
1778                candidate_sets.as_slice(),
1779                query.as_str(),
1780                &relative_to,
1781                false,
1782                100,
1783                &cancellation_flag,
1784                executor,
1785            )
1786            .await
1787            .into_iter()
1788            .map(|mat| FileMatch {
1789                mat,
1790                is_recent: false,
1791            })
1792            .collect::<Vec<_>>()
1793        })
1794    }
1795}
1796
1797pub(crate) fn search_symbols(
1798    query: String,
1799    cancellation_flag: Arc<AtomicBool>,
1800    workspace: &Entity<Workspace>,
1801    cx: &mut App,
1802) -> Task<Vec<SymbolMatch>> {
1803    let symbols_task = workspace.update(cx, |workspace, cx| {
1804        workspace
1805            .project()
1806            .update(cx, |project, cx| project.symbols(&query, cx))
1807    });
1808    let project = workspace.read(cx).project().clone();
1809    cx.spawn(async move |cx| {
1810        let Some(symbols) = symbols_task.await.log_err() else {
1811            return Vec::new();
1812        };
1813        let (visible_match_candidates, external_match_candidates): (Vec<_>, Vec<_>) = project
1814            .update(cx, |project, cx| {
1815                symbols
1816                    .iter()
1817                    .enumerate()
1818                    .map(|(id, symbol)| StringMatchCandidate::new(id, symbol.label.filter_text()))
1819                    .partition(|candidate| match &symbols[candidate.id].path {
1820                        SymbolLocation::InProject(project_path) => project
1821                            .entry_for_path(project_path, cx)
1822                            .is_some_and(|e| !e.is_ignored),
1823                        SymbolLocation::OutsideProject { .. } => false,
1824                    })
1825            });
1826        // Try to support rust-analyzer's path based symbols feature which
1827        // allows to search by rust path syntax, in that case we only want to
1828        // filter names by the last segment
1829        // Ideally this was a first class LSP feature (rich queries)
1830        let query = query
1831            .rsplit_once("::")
1832            .map_or(&*query, |(_, suffix)| suffix)
1833            .to_owned();
1834        // Note if you make changes to this filtering below, also change `project_symbols::ProjectSymbolsDelegate::filter`
1835        const MAX_MATCHES: usize = 100;
1836        let mut visible_matches = cx.foreground_executor().block_on(fuzzy::match_strings(
1837            &visible_match_candidates,
1838            &query,
1839            false,
1840            true,
1841            MAX_MATCHES,
1842            &cancellation_flag,
1843            cx.background_executor().clone(),
1844        ));
1845        let mut external_matches = cx.foreground_executor().block_on(fuzzy::match_strings(
1846            &external_match_candidates,
1847            &query,
1848            false,
1849            true,
1850            MAX_MATCHES - visible_matches.len().min(MAX_MATCHES),
1851            &cancellation_flag,
1852            cx.background_executor().clone(),
1853        ));
1854        let sort_key_for_match = |mat: &StringMatch| {
1855            let symbol = &symbols[mat.candidate_id];
1856            (Reverse(OrderedFloat(mat.score)), symbol.label.filter_text())
1857        };
1858
1859        visible_matches.sort_unstable_by_key(sort_key_for_match);
1860        external_matches.sort_unstable_by_key(sort_key_for_match);
1861        let mut matches = visible_matches;
1862        matches.append(&mut external_matches);
1863
1864        matches
1865            .into_iter()
1866            .map(|mut mat| {
1867                let symbol = symbols[mat.candidate_id].clone();
1868                let filter_start = symbol.label.filter_range.start;
1869                for position in &mut mat.positions {
1870                    *position += filter_start;
1871                }
1872                SymbolMatch { symbol }
1873            })
1874            .collect()
1875    })
1876}
1877
1878fn filter_sessions_by_query(
1879    query: String,
1880    cancellation_flag: Arc<AtomicBool>,
1881    sessions: Vec<AgentSessionInfo>,
1882    cx: &mut App,
1883) -> Task<Vec<AgentSessionInfo>> {
1884    if query.is_empty() {
1885        return Task::ready(sessions);
1886    }
1887    let executor = cx.background_executor().clone();
1888    cx.background_spawn(async move {
1889        filter_sessions(query, cancellation_flag, sessions, executor).await
1890    })
1891}
1892
1893async fn filter_sessions(
1894    query: String,
1895    cancellation_flag: Arc<AtomicBool>,
1896    sessions: Vec<AgentSessionInfo>,
1897    executor: BackgroundExecutor,
1898) -> Vec<AgentSessionInfo> {
1899    let titles = sessions.iter().map(session_title).collect::<Vec<_>>();
1900    let candidates = titles
1901        .iter()
1902        .enumerate()
1903        .map(|(id, title)| StringMatchCandidate::new(id, title.as_ref()))
1904        .collect::<Vec<_>>();
1905    let matches = fuzzy::match_strings(
1906        &candidates,
1907        &query,
1908        false,
1909        true,
1910        100,
1911        &cancellation_flag,
1912        executor,
1913    )
1914    .await;
1915
1916    matches
1917        .into_iter()
1918        .map(|mat| sessions[mat.candidate_id].clone())
1919        .collect()
1920}
1921
1922pub(crate) fn search_rules(
1923    query: String,
1924    cancellation_flag: Arc<AtomicBool>,
1925    prompt_store: &Entity<PromptStore>,
1926    cx: &mut App,
1927) -> Task<Vec<RulesContextEntry>> {
1928    let search_task = prompt_store.read(cx).search(query, cancellation_flag, cx);
1929    cx.background_spawn(async move {
1930        search_task
1931            .await
1932            .into_iter()
1933            .flat_map(|metadata| {
1934                // Default prompts are filtered out as they are automatically included.
1935                if metadata.default {
1936                    None
1937                } else {
1938                    Some(RulesContextEntry {
1939                        prompt_id: metadata.id.as_user()?,
1940                        title: metadata.title?,
1941                    })
1942                }
1943            })
1944            .collect::<Vec<_>>()
1945    })
1946}
1947
1948pub struct SymbolMatch {
1949    pub symbol: Symbol,
1950}
1951
1952pub struct FileMatch {
1953    pub mat: PathMatch,
1954    pub is_recent: bool,
1955}
1956
1957pub fn extract_file_name_and_directory(
1958    path: &RelPath,
1959    path_prefix: &RelPath,
1960    path_style: PathStyle,
1961) -> (SharedString, Option<SharedString>) {
1962    // If path is empty, this means we're matching with the root directory itself
1963    // so we use the path_prefix as the name
1964    if path.is_empty() && !path_prefix.is_empty() {
1965        return (path_prefix.display(path_style).to_string().into(), None);
1966    }
1967
1968    let full_path = path_prefix.join(path);
1969    let file_name = full_path.file_name().unwrap_or_default();
1970    let display_path = full_path.display(path_style);
1971    let (directory, file_name) = display_path.split_at(display_path.len() - file_name.len());
1972    (
1973        file_name.to_string().into(),
1974        Some(SharedString::new(directory)).filter(|dir| !dir.is_empty()),
1975    )
1976}
1977
1978fn build_code_label_for_path(
1979    file: &str,
1980    directory: Option<&str>,
1981    line_number: Option<u32>,
1982    label_max_chars: usize,
1983    cx: &App,
1984) -> CodeLabel {
1985    let variable_highlight_id = cx
1986        .theme()
1987        .syntax()
1988        .highlight_id("variable")
1989        .map(HighlightId);
1990    let mut label = CodeLabelBuilder::default();
1991
1992    label.push_str(file, None);
1993    label.push_str(" ", None);
1994
1995    if let Some(directory) = directory {
1996        let file_name_chars = file.chars().count();
1997        // Account for: file_name + space (ellipsis is handled by truncate_and_remove_front)
1998        let directory_max_chars = label_max_chars
1999            .saturating_sub(file_name_chars)
2000            .saturating_sub(1);
2001        let truncated_directory = truncate_and_remove_front(directory, directory_max_chars.max(5));
2002        label.push_str(&truncated_directory, variable_highlight_id);
2003    }
2004    if let Some(line_number) = line_number {
2005        label.push_str(&format!(" L{}", line_number), variable_highlight_id);
2006    }
2007    label.build()
2008}
2009
2010/// Returns terminal selections from all terminal views if the terminal panel is open.
2011fn terminal_selections_if_panel_open(workspace: &Entity<Workspace>, cx: &App) -> Vec<String> {
2012    let Some(panel) = workspace.read(cx).panel::<TerminalPanel>(cx) else {
2013        return Vec::new();
2014    };
2015
2016    // Check if the dock containing this panel is open
2017    let position = match TerminalSettings::get_global(cx).dock {
2018        TerminalDockPosition::Left => DockPosition::Left,
2019        TerminalDockPosition::Bottom => DockPosition::Bottom,
2020        TerminalDockPosition::Right => DockPosition::Right,
2021    };
2022    let dock_is_open = workspace
2023        .read(cx)
2024        .dock_at_position(position)
2025        .read(cx)
2026        .is_open();
2027    if !dock_is_open {
2028        return Vec::new();
2029    }
2030
2031    panel.read(cx).terminal_selections(cx)
2032}
2033
2034fn selection_ranges(
2035    workspace: &Entity<Workspace>,
2036    cx: &mut App,
2037) -> Vec<(Entity<Buffer>, Range<text::Anchor>)> {
2038    let Some(editor) = workspace
2039        .read(cx)
2040        .active_item(cx)
2041        .and_then(|item| item.act_as::<Editor>(cx))
2042    else {
2043        return Vec::new();
2044    };
2045
2046    editor.update(cx, |editor, cx| {
2047        let selections = editor.selections.all_adjusted(&editor.display_snapshot(cx));
2048
2049        let buffer = editor.buffer().clone().read(cx);
2050        let snapshot = buffer.snapshot(cx);
2051
2052        selections
2053            .into_iter()
2054            .map(|s| {
2055                let (start, end) = if s.is_empty() {
2056                    let row = multi_buffer::MultiBufferRow(s.start.row);
2057                    let line_start = text::Point::new(s.start.row, 0);
2058                    let line_end = text::Point::new(s.start.row, snapshot.line_len(row));
2059                    (line_start, line_end)
2060                } else {
2061                    (s.start, s.end)
2062                };
2063                snapshot.anchor_after(start)..snapshot.anchor_before(end)
2064            })
2065            .flat_map(|range| {
2066                let (start_buffer, start) = buffer.text_anchor_for_position(range.start, cx)?;
2067                let (end_buffer, end) = buffer.text_anchor_for_position(range.end, cx)?;
2068                if start_buffer != end_buffer {
2069                    return None;
2070                }
2071                Some((start_buffer, start..end))
2072            })
2073            .collect::<Vec<_>>()
2074    })
2075}
2076
2077#[cfg(test)]
2078mod tests {
2079    use super::*;
2080    use gpui::TestAppContext;
2081
2082    #[test]
2083    fn test_prompt_completion_parse() {
2084        let supported_modes = vec![PromptContextType::File, PromptContextType::Symbol];
2085
2086        assert_eq!(
2087            PromptCompletion::try_parse("/", 0, &supported_modes),
2088            Some(PromptCompletion::SlashCommand(SlashCommandCompletion {
2089                source_range: 0..1,
2090                command: None,
2091                argument: None,
2092            }))
2093        );
2094
2095        assert_eq!(
2096            PromptCompletion::try_parse("@", 0, &supported_modes),
2097            Some(PromptCompletion::Mention(MentionCompletion {
2098                source_range: 0..1,
2099                mode: None,
2100                argument: None,
2101            }))
2102        );
2103
2104        assert_eq!(
2105            PromptCompletion::try_parse("/test @file", 0, &supported_modes),
2106            Some(PromptCompletion::Mention(MentionCompletion {
2107                source_range: 6..11,
2108                mode: Some(PromptContextType::File),
2109                argument: None,
2110            }))
2111        );
2112    }
2113
2114    #[test]
2115    fn test_slash_command_completion_parse() {
2116        assert_eq!(
2117            SlashCommandCompletion::try_parse("/", 0),
2118            Some(SlashCommandCompletion {
2119                source_range: 0..1,
2120                command: None,
2121                argument: None,
2122            })
2123        );
2124
2125        assert_eq!(
2126            SlashCommandCompletion::try_parse("/help", 0),
2127            Some(SlashCommandCompletion {
2128                source_range: 0..5,
2129                command: Some("help".to_string()),
2130                argument: None,
2131            })
2132        );
2133
2134        assert_eq!(
2135            SlashCommandCompletion::try_parse("/help ", 0),
2136            Some(SlashCommandCompletion {
2137                source_range: 0..5,
2138                command: Some("help".to_string()),
2139                argument: None,
2140            })
2141        );
2142
2143        assert_eq!(
2144            SlashCommandCompletion::try_parse("/help arg1", 0),
2145            Some(SlashCommandCompletion {
2146                source_range: 0..10,
2147                command: Some("help".to_string()),
2148                argument: Some("arg1".to_string()),
2149            })
2150        );
2151
2152        assert_eq!(
2153            SlashCommandCompletion::try_parse("/help arg1 arg2", 0),
2154            Some(SlashCommandCompletion {
2155                source_range: 0..15,
2156                command: Some("help".to_string()),
2157                argument: Some("arg1 arg2".to_string()),
2158            })
2159        );
2160
2161        assert_eq!(
2162            SlashCommandCompletion::try_parse("/拿不到命令 拿不到命令 ", 0),
2163            Some(SlashCommandCompletion {
2164                source_range: 0..30,
2165                command: Some("拿不到命令".to_string()),
2166                argument: Some("拿不到命令".to_string()),
2167            })
2168        );
2169
2170        assert_eq!(SlashCommandCompletion::try_parse("Lorem Ipsum", 0), None);
2171
2172        assert_eq!(SlashCommandCompletion::try_parse("Lorem /", 0), None);
2173
2174        assert_eq!(SlashCommandCompletion::try_parse("Lorem /help", 0), None);
2175
2176        assert_eq!(SlashCommandCompletion::try_parse("Lorem/", 0), None);
2177
2178        assert_eq!(SlashCommandCompletion::try_parse("/ ", 0), None);
2179    }
2180
2181    #[test]
2182    fn test_mention_completion_parse() {
2183        let supported_modes = vec![PromptContextType::File, PromptContextType::Symbol];
2184        let supported_modes_with_diagnostics = vec![
2185            PromptContextType::File,
2186            PromptContextType::Symbol,
2187            PromptContextType::Diagnostics,
2188        ];
2189
2190        assert_eq!(
2191            MentionCompletion::try_parse("Lorem Ipsum", 0, &supported_modes),
2192            None
2193        );
2194
2195        assert_eq!(
2196            MentionCompletion::try_parse("Lorem @", 0, &supported_modes),
2197            Some(MentionCompletion {
2198                source_range: 6..7,
2199                mode: None,
2200                argument: None,
2201            })
2202        );
2203
2204        assert_eq!(
2205            MentionCompletion::try_parse("Lorem @file", 0, &supported_modes),
2206            Some(MentionCompletion {
2207                source_range: 6..11,
2208                mode: Some(PromptContextType::File),
2209                argument: None,
2210            })
2211        );
2212
2213        assert_eq!(
2214            MentionCompletion::try_parse("Lorem @file ", 0, &supported_modes),
2215            Some(MentionCompletion {
2216                source_range: 6..12,
2217                mode: Some(PromptContextType::File),
2218                argument: None,
2219            })
2220        );
2221
2222        assert_eq!(
2223            MentionCompletion::try_parse("Lorem @file main.rs", 0, &supported_modes),
2224            Some(MentionCompletion {
2225                source_range: 6..19,
2226                mode: Some(PromptContextType::File),
2227                argument: Some("main.rs".to_string()),
2228            })
2229        );
2230
2231        assert_eq!(
2232            MentionCompletion::try_parse("Lorem @file main.rs ", 0, &supported_modes),
2233            Some(MentionCompletion {
2234                source_range: 6..19,
2235                mode: Some(PromptContextType::File),
2236                argument: Some("main.rs".to_string()),
2237            })
2238        );
2239
2240        assert_eq!(
2241            MentionCompletion::try_parse("Lorem @file main.rs Ipsum", 0, &supported_modes),
2242            Some(MentionCompletion {
2243                source_range: 6..19,
2244                mode: Some(PromptContextType::File),
2245                argument: Some("main.rs".to_string()),
2246            })
2247        );
2248
2249        assert_eq!(
2250            MentionCompletion::try_parse("Lorem @main", 0, &supported_modes),
2251            Some(MentionCompletion {
2252                source_range: 6..11,
2253                mode: None,
2254                argument: Some("main".to_string()),
2255            })
2256        );
2257
2258        assert_eq!(
2259            MentionCompletion::try_parse("Lorem @main ", 0, &supported_modes),
2260            Some(MentionCompletion {
2261                source_range: 6..12,
2262                mode: None,
2263                argument: Some("main".to_string()),
2264            })
2265        );
2266
2267        assert_eq!(
2268            MentionCompletion::try_parse("Lorem @main m", 0, &supported_modes),
2269            None
2270        );
2271
2272        assert_eq!(
2273            MentionCompletion::try_parse("test@", 0, &supported_modes),
2274            None
2275        );
2276
2277        // Allowed non-file mentions
2278
2279        assert_eq!(
2280            MentionCompletion::try_parse("Lorem @symbol main", 0, &supported_modes),
2281            Some(MentionCompletion {
2282                source_range: 6..18,
2283                mode: Some(PromptContextType::Symbol),
2284                argument: Some("main".to_string()),
2285            })
2286        );
2287
2288        assert_eq!(
2289            MentionCompletion::try_parse(
2290                "Lorem @symbol agent_ui::completion_provider",
2291                0,
2292                &supported_modes
2293            ),
2294            Some(MentionCompletion {
2295                source_range: 6..43,
2296                mode: Some(PromptContextType::Symbol),
2297                argument: Some("agent_ui::completion_provider".to_string()),
2298            })
2299        );
2300
2301        assert_eq!(
2302            MentionCompletion::try_parse(
2303                "Lorem @diagnostics",
2304                0,
2305                &supported_modes_with_diagnostics
2306            ),
2307            Some(MentionCompletion {
2308                source_range: 6..18,
2309                mode: Some(PromptContextType::Diagnostics),
2310                argument: None,
2311            })
2312        );
2313
2314        // Disallowed non-file mentions
2315        assert_eq!(
2316            MentionCompletion::try_parse("Lorem @symbol main", 0, &[PromptContextType::File]),
2317            None
2318        );
2319
2320        assert_eq!(
2321            MentionCompletion::try_parse("Lorem@symbol", 0, &supported_modes),
2322            None,
2323            "Should not parse mention inside word"
2324        );
2325
2326        assert_eq!(
2327            MentionCompletion::try_parse("Lorem @ file", 0, &supported_modes),
2328            None,
2329            "Should not parse with a space after @"
2330        );
2331
2332        assert_eq!(
2333            MentionCompletion::try_parse("@ file", 0, &supported_modes),
2334            None,
2335            "Should not parse with a space after @ at the start of the line"
2336        );
2337    }
2338
2339    #[gpui::test]
2340    async fn test_filter_sessions_by_query(cx: &mut TestAppContext) {
2341        let mut alpha = AgentSessionInfo::new("session-alpha");
2342        alpha.title = Some("Alpha Session".into());
2343        let mut beta = AgentSessionInfo::new("session-beta");
2344        beta.title = Some("Beta Session".into());
2345
2346        let sessions = vec![alpha.clone(), beta];
2347
2348        let task = {
2349            let mut app = cx.app.borrow_mut();
2350            filter_sessions_by_query(
2351                "Alpha".into(),
2352                Arc::new(AtomicBool::default()),
2353                sessions,
2354                &mut app,
2355            )
2356        };
2357
2358        let results = task.await;
2359        assert_eq!(results.len(), 1);
2360        assert_eq!(results[0].session_id, alpha.session_id);
2361    }
2362
2363    #[gpui::test]
2364    async fn test_search_files_path_distance_ordering(cx: &mut TestAppContext) {
2365        use project::Project;
2366        use serde_json::json;
2367        use util::{path, rel_path::rel_path};
2368        use workspace::{AppState, MultiWorkspace};
2369
2370        let app_state = cx.update(|cx| {
2371            let state = AppState::test(cx);
2372            theme::init(theme::LoadThemes::JustBase, cx);
2373            editor::init(cx);
2374            state
2375        });
2376
2377        app_state
2378            .fs
2379            .as_fake()
2380            .insert_tree(
2381                path!("/root"),
2382                json!({
2383                    "dir1": { "a.txt": "" },
2384                    "dir2": {
2385                        "a.txt": "",
2386                        "b.txt": ""
2387                    }
2388                }),
2389            )
2390            .await;
2391
2392        let project = Project::test(app_state.fs.clone(), [path!("/root").as_ref()], cx).await;
2393        let (multi_workspace, cx) =
2394            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
2395        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2396
2397        let worktree_id = cx.read(|cx| {
2398            let worktrees = workspace.read(cx).worktrees(cx).collect::<Vec<_>>();
2399            assert_eq!(worktrees.len(), 1);
2400            worktrees[0].read(cx).id()
2401        });
2402
2403        // Open a file in dir2 to create navigation history.
2404        // When searching for "a.txt", dir2/a.txt should be sorted first because
2405        // it is closer to the most recently opened file (dir2/b.txt).
2406        let b_path = ProjectPath {
2407            worktree_id,
2408            path: rel_path("dir2/b.txt").into(),
2409        };
2410        workspace
2411            .update_in(cx, |workspace, window, cx| {
2412                workspace.open_path(b_path, None, true, window, cx)
2413            })
2414            .await
2415            .unwrap();
2416
2417        let results = cx
2418            .update(|_window, cx| {
2419                search_files(
2420                    "a.txt".into(),
2421                    Arc::new(AtomicBool::default()),
2422                    &workspace,
2423                    cx,
2424                )
2425            })
2426            .await;
2427
2428        assert_eq!(results.len(), 2, "expected 2 matching files");
2429        assert_eq!(
2430            results[0].mat.path.as_ref(),
2431            rel_path("dir2/a.txt"),
2432            "dir2/a.txt should be first because it's closer to the recently opened dir2/b.txt"
2433        );
2434        assert_eq!(
2435            results[1].mat.path.as_ref(),
2436            rel_path("dir1/a.txt"),
2437            "dir1/a.txt should be second"
2438        );
2439    }
2440}