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