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::DEFAULT_THREAD_TITLE;
   8use crate::ThreadHistory;
   9use acp_thread::MentionUri;
  10use agent_client_protocol as acp;
  11use anyhow::Result;
  12use editor::{
  13    CompletionProvider, Editor, ExcerptId, code_context_menus::COMPLETION_MENU_MAX_WIDTH,
  14};
  15use futures::FutureExt as _;
  16use fuzzy::{PathMatch, StringMatch, StringMatchCandidate};
  17use gpui::{App, BackgroundExecutor, Entity, SharedString, Task, WeakEntity};
  18use language::{Buffer, CodeLabel, CodeLabelBuilder, HighlightId};
  19use lsp::CompletionContext;
  20use multi_buffer::ToOffset as _;
  21use ordered_float::OrderedFloat;
  22use project::lsp_store::{CompletionDocumentation, SymbolLocation};
  23use project::{
  24    Completion, CompletionDisplayOptions, CompletionIntent, CompletionResponse, DiagnosticSummary,
  25    PathMatchCandidateSet, Project, ProjectPath, Symbol, WorktreeId,
  26};
  27use prompt_store::{PromptStore, UserPromptId};
  28use rope::Point;
  29use settings::{Settings, TerminalDockPosition};
  30use terminal::terminal_settings::TerminalSettings;
  31use terminal_view::{TerminalView, terminal_panel::TerminalPanel};
  32use text::{Anchor, ToOffset as _, ToPoint as _};
  33use ui::IconName;
  34use ui::prelude::*;
  35use util::ResultExt as _;
  36use util::paths::PathStyle;
  37use util::rel_path::RelPath;
  38use util::truncate_and_remove_front;
  39use workspace::Workspace;
  40use workspace::dock::DockPosition;
  41
  42use crate::AgentPanel;
  43use crate::mention_set::MentionSet;
  44
  45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  46pub(crate) enum PromptContextEntry {
  47    Mode(PromptContextType),
  48    Action(PromptContextAction),
  49}
  50
  51impl PromptContextEntry {
  52    pub fn keyword(&self) -> &'static str {
  53        match self {
  54            Self::Mode(mode) => mode.keyword(),
  55            Self::Action(action) => action.keyword(),
  56        }
  57    }
  58}
  59
  60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  61pub(crate) enum PromptContextType {
  62    File,
  63    Symbol,
  64    Fetch,
  65    Thread,
  66    Rules,
  67    Diagnostics,
  68    BranchDiff,
  69}
  70
  71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  72pub(crate) enum PromptContextAction {
  73    AddSelections,
  74}
  75
  76impl PromptContextAction {
  77    pub fn keyword(&self) -> &'static str {
  78        match self {
  79            Self::AddSelections => "selection",
  80        }
  81    }
  82
  83    pub fn label(&self) -> &'static str {
  84        match self {
  85            Self::AddSelections => "Selection",
  86        }
  87    }
  88
  89    pub fn icon(&self) -> IconName {
  90        match self {
  91            Self::AddSelections => IconName::Reader,
  92        }
  93    }
  94}
  95
  96impl TryFrom<&str> for PromptContextType {
  97    type Error = String;
  98
  99    fn try_from(value: &str) -> Result<Self, Self::Error> {
 100        match value {
 101            "file" => Ok(Self::File),
 102            "symbol" => Ok(Self::Symbol),
 103            "fetch" => Ok(Self::Fetch),
 104            "thread" => Ok(Self::Thread),
 105            "rule" => Ok(Self::Rules),
 106            "diagnostics" => Ok(Self::Diagnostics),
 107            "diff" => Ok(Self::BranchDiff),
 108            _ => Err(format!("Invalid context picker mode: {}", value)),
 109        }
 110    }
 111}
 112
 113impl PromptContextType {
 114    pub fn keyword(&self) -> &'static str {
 115        match self {
 116            Self::File => "file",
 117            Self::Symbol => "symbol",
 118            Self::Fetch => "fetch",
 119            Self::Thread => "thread",
 120            Self::Rules => "rule",
 121            Self::Diagnostics => "diagnostics",
 122            Self::BranchDiff => "branch diff",
 123        }
 124    }
 125
 126    pub fn label(&self) -> &'static str {
 127        match self {
 128            Self::File => "Files & Directories",
 129            Self::Symbol => "Symbols",
 130            Self::Fetch => "Fetch",
 131            Self::Thread => "Threads",
 132            Self::Rules => "Rules",
 133            Self::Diagnostics => "Diagnostics",
 134            Self::BranchDiff => "Branch Diff",
 135        }
 136    }
 137
 138    pub fn icon(&self) -> IconName {
 139        match self {
 140            Self::File => IconName::File,
 141            Self::Symbol => IconName::Code,
 142            Self::Fetch => IconName::ToolWeb,
 143            Self::Thread => IconName::Thread,
 144            Self::Rules => IconName::Reader,
 145            Self::Diagnostics => IconName::Warning,
 146            Self::BranchDiff => IconName::GitBranch,
 147        }
 148    }
 149}
 150
 151pub(crate) enum Match {
 152    File(FileMatch),
 153    Symbol(SymbolMatch),
 154    Thread(SessionMatch),
 155    RecentThread(SessionMatch),
 156    Fetch(SharedString),
 157    Rules(RulesContextEntry),
 158    Entry(EntryMatch),
 159    BranchDiff(BranchDiffMatch),
 160}
 161
 162#[derive(Debug, Clone)]
 163pub struct BranchDiffMatch {
 164    pub base_ref: SharedString,
 165}
 166
 167impl Match {
 168    pub fn score(&self) -> f64 {
 169        match self {
 170            Match::File(file) => file.mat.score,
 171            Match::Entry(mode) => mode.mat.as_ref().map(|mat| mat.score).unwrap_or(1.),
 172            Match::Thread(_) => 1.,
 173            Match::RecentThread(_) => 1.,
 174            Match::Symbol(_) => 1.,
 175            Match::Rules(_) => 1.,
 176            Match::Fetch(_) => 1.,
 177            Match::BranchDiff(_) => 1.,
 178        }
 179    }
 180}
 181
 182#[derive(Debug, Clone)]
 183pub struct SessionMatch {
 184    session_id: acp::SessionId,
 185    title: SharedString,
 186}
 187
 188pub struct EntryMatch {
 189    mat: Option<StringMatch>,
 190    entry: PromptContextEntry,
 191}
 192
 193fn session_title(title: Option<SharedString>) -> SharedString {
 194    title
 195        .filter(|title| !title.is_empty())
 196        .unwrap_or_else(|| SharedString::new_static(DEFAULT_THREAD_TITLE))
 197}
 198
 199#[derive(Debug, Clone)]
 200pub struct RulesContextEntry {
 201    pub prompt_id: UserPromptId,
 202    pub title: SharedString,
 203}
 204
 205#[derive(Debug, Clone)]
 206pub struct AvailableCommand {
 207    pub name: Arc<str>,
 208    pub description: Arc<str>,
 209    pub requires_argument: bool,
 210}
 211
 212pub trait PromptCompletionProviderDelegate: Send + Sync + 'static {
 213    fn supports_context(&self, mode: PromptContextType, cx: &App) -> bool {
 214        self.supported_modes(cx).contains(&mode)
 215    }
 216    fn supported_modes(&self, cx: &App) -> Vec<PromptContextType>;
 217    fn supports_images(&self, cx: &App) -> bool;
 218
 219    fn available_commands(&self, cx: &App) -> Vec<AvailableCommand>;
 220    fn confirm_command(&self, cx: &mut App);
 221}
 222
 223pub struct PromptCompletionProvider<T: PromptCompletionProviderDelegate> {
 224    source: Arc<T>,
 225    editor: WeakEntity<Editor>,
 226    mention_set: Entity<MentionSet>,
 227    history: Option<WeakEntity<ThreadHistory>>,
 228    prompt_store: Option<Entity<PromptStore>>,
 229    workspace: WeakEntity<Workspace>,
 230}
 231
 232impl<T: PromptCompletionProviderDelegate> PromptCompletionProvider<T> {
 233    pub fn new(
 234        source: T,
 235        editor: WeakEntity<Editor>,
 236        mention_set: Entity<MentionSet>,
 237        history: Option<WeakEntity<ThreadHistory>>,
 238        prompt_store: Option<Entity<PromptStore>>,
 239        workspace: WeakEntity<Workspace>,
 240    ) -> Self {
 241        Self {
 242            source: Arc::new(source),
 243            editor,
 244            mention_set,
 245            workspace,
 246            history,
 247            prompt_store,
 248        }
 249    }
 250
 251    fn completion_for_entry(
 252        entry: PromptContextEntry,
 253        source_range: Range<Anchor>,
 254        editor: WeakEntity<Editor>,
 255        mention_set: WeakEntity<MentionSet>,
 256        workspace: &Entity<Workspace>,
 257        cx: &mut App,
 258    ) -> Option<Completion> {
 259        match entry {
 260            PromptContextEntry::Mode(mode) => Some(Completion {
 261                replace_range: source_range,
 262                new_text: format!("@{} ", mode.keyword()),
 263                label: CodeLabel::plain(mode.label().to_string(), None),
 264                icon_path: Some(mode.icon().path().into()),
 265                documentation: None,
 266                source: project::CompletionSource::Custom,
 267                match_start: None,
 268                snippet_deduplication_key: None,
 269                insert_text_mode: None,
 270                // This ensures that when a user accepts this completion, the
 271                // completion menu will still be shown after "@category " is
 272                // inserted
 273                confirm: Some(Arc::new(|_, _, _| true)),
 274            }),
 275            PromptContextEntry::Action(action) => Self::completion_for_action(
 276                action,
 277                source_range,
 278                editor,
 279                mention_set,
 280                workspace,
 281                cx,
 282            ),
 283        }
 284    }
 285
 286    fn completion_for_thread(
 287        session_id: acp::SessionId,
 288        title: Option<SharedString>,
 289        source_range: Range<Anchor>,
 290        recent: bool,
 291        source: Arc<T>,
 292        editor: WeakEntity<Editor>,
 293        mention_set: WeakEntity<MentionSet>,
 294        workspace: Entity<Workspace>,
 295        cx: &mut App,
 296    ) -> Completion {
 297        let title = session_title(title);
 298        let uri = MentionUri::Thread {
 299            id: session_id,
 300            name: title.to_string(),
 301        };
 302
 303        let icon_for_completion = if recent {
 304            IconName::HistoryRerun.path().into()
 305        } else {
 306            uri.icon_path(cx)
 307        };
 308
 309        let new_text = format!("{} ", uri.as_link());
 310
 311        let new_text_len = new_text.len();
 312        Completion {
 313            replace_range: source_range.clone(),
 314            new_text,
 315            label: CodeLabel::plain(title.to_string(), None),
 316            documentation: None,
 317            insert_text_mode: None,
 318            source: project::CompletionSource::Custom,
 319            match_start: None,
 320            snippet_deduplication_key: None,
 321            icon_path: Some(icon_for_completion),
 322            confirm: Some(confirm_completion_callback(
 323                title,
 324                source_range.start,
 325                new_text_len - 1,
 326                uri,
 327                source,
 328                editor,
 329                mention_set,
 330                workspace,
 331            )),
 332        }
 333    }
 334
 335    fn completion_for_rules(
 336        rule: RulesContextEntry,
 337        source_range: Range<Anchor>,
 338        source: Arc<T>,
 339        editor: WeakEntity<Editor>,
 340        mention_set: WeakEntity<MentionSet>,
 341        workspace: Entity<Workspace>,
 342        cx: &mut App,
 343    ) -> Completion {
 344        let uri = MentionUri::Rule {
 345            id: rule.prompt_id.into(),
 346            name: rule.title.to_string(),
 347        };
 348        let new_text = format!("{} ", uri.as_link());
 349        let new_text_len = new_text.len();
 350        let icon_path = uri.icon_path(cx);
 351        Completion {
 352            replace_range: source_range.clone(),
 353            new_text,
 354            label: CodeLabel::plain(rule.title.to_string(), None),
 355            documentation: None,
 356            insert_text_mode: None,
 357            source: project::CompletionSource::Custom,
 358            match_start: None,
 359            snippet_deduplication_key: None,
 360            icon_path: Some(icon_path),
 361            confirm: Some(confirm_completion_callback(
 362                rule.title,
 363                source_range.start,
 364                new_text_len - 1,
 365                uri,
 366                source,
 367                editor,
 368                mention_set,
 369                workspace,
 370            )),
 371        }
 372    }
 373
 374    pub(crate) fn completion_for_path(
 375        project_path: ProjectPath,
 376        path_prefix: &RelPath,
 377        is_recent: bool,
 378        is_directory: bool,
 379        source_range: Range<Anchor>,
 380        source: Arc<T>,
 381        editor: WeakEntity<Editor>,
 382        mention_set: WeakEntity<MentionSet>,
 383        workspace: Entity<Workspace>,
 384        project: Entity<Project>,
 385        label_max_chars: usize,
 386        cx: &mut App,
 387    ) -> Option<Completion> {
 388        let path_style = project.read(cx).path_style(cx);
 389        let (file_name, directory) =
 390            extract_file_name_and_directory(&project_path.path, path_prefix, path_style);
 391
 392        let label = build_code_label_for_path(
 393            &file_name,
 394            directory.as_ref().map(|s| s.as_ref()),
 395            None,
 396            label_max_chars,
 397            cx,
 398        );
 399
 400        let abs_path = project.read(cx).absolute_path(&project_path, cx)?;
 401
 402        let uri = if is_directory {
 403            MentionUri::Directory { abs_path }
 404        } else {
 405            MentionUri::File { abs_path }
 406        };
 407
 408        let crease_icon_path = uri.icon_path(cx);
 409        let completion_icon_path = if is_recent {
 410            IconName::HistoryRerun.path().into()
 411        } else {
 412            crease_icon_path
 413        };
 414
 415        let new_text = format!("{} ", uri.as_link());
 416        let new_text_len = new_text.len();
 417        Some(Completion {
 418            replace_range: source_range.clone(),
 419            new_text,
 420            label,
 421            documentation: None,
 422            source: project::CompletionSource::Custom,
 423            icon_path: Some(completion_icon_path),
 424            match_start: None,
 425            snippet_deduplication_key: None,
 426            insert_text_mode: None,
 427            confirm: Some(confirm_completion_callback(
 428                file_name,
 429                source_range.start,
 430                new_text_len - 1,
 431                uri,
 432                source,
 433                editor,
 434                mention_set,
 435                workspace,
 436            )),
 437        })
 438    }
 439
 440    fn completion_for_symbol(
 441        symbol: Symbol,
 442        source_range: Range<Anchor>,
 443        source: Arc<T>,
 444        editor: WeakEntity<Editor>,
 445        mention_set: WeakEntity<MentionSet>,
 446        workspace: Entity<Workspace>,
 447        label_max_chars: usize,
 448        cx: &mut App,
 449    ) -> Option<Completion> {
 450        let project = workspace.read(cx).project().clone();
 451
 452        let (abs_path, file_name) = match &symbol.path {
 453            SymbolLocation::InProject(project_path) => (
 454                project.read(cx).absolute_path(&project_path, cx)?,
 455                project_path.path.file_name()?.to_string().into(),
 456            ),
 457            SymbolLocation::OutsideProject {
 458                abs_path,
 459                signature: _,
 460            } => (
 461                PathBuf::from(abs_path.as_ref()),
 462                abs_path.file_name().map(|f| f.to_string_lossy())?,
 463            ),
 464        };
 465
 466        let label = build_code_label_for_path(
 467            &symbol.name,
 468            Some(&file_name),
 469            Some(symbol.range.start.0.row + 1),
 470            label_max_chars,
 471            cx,
 472        );
 473
 474        let uri = MentionUri::Symbol {
 475            abs_path,
 476            name: symbol.name.clone(),
 477            line_range: symbol.range.start.0.row..=symbol.range.end.0.row,
 478        };
 479        let new_text = format!("{} ", uri.as_link());
 480        let new_text_len = new_text.len();
 481        let icon_path = uri.icon_path(cx);
 482        Some(Completion {
 483            replace_range: source_range.clone(),
 484            new_text,
 485            label,
 486            documentation: None,
 487            source: project::CompletionSource::Custom,
 488            icon_path: Some(icon_path),
 489            match_start: None,
 490            snippet_deduplication_key: None,
 491            insert_text_mode: None,
 492            confirm: Some(confirm_completion_callback(
 493                symbol.name.into(),
 494                source_range.start,
 495                new_text_len - 1,
 496                uri,
 497                source,
 498                editor,
 499                mention_set,
 500                workspace,
 501            )),
 502        })
 503    }
 504
 505    fn completion_for_fetch(
 506        source_range: Range<Anchor>,
 507        url_to_fetch: SharedString,
 508        source: Arc<T>,
 509        editor: WeakEntity<Editor>,
 510        mention_set: WeakEntity<MentionSet>,
 511        workspace: Entity<Workspace>,
 512        cx: &mut App,
 513    ) -> Option<Completion> {
 514        let new_text = format!("@fetch {} ", url_to_fetch);
 515        let url_to_fetch = url::Url::parse(url_to_fetch.as_ref())
 516            .or_else(|_| url::Url::parse(&format!("https://{url_to_fetch}")))
 517            .ok()?;
 518        let mention_uri = MentionUri::Fetch {
 519            url: url_to_fetch.clone(),
 520        };
 521        let icon_path = mention_uri.icon_path(cx);
 522        Some(Completion {
 523            replace_range: source_range.clone(),
 524            new_text: new_text.clone(),
 525            label: CodeLabel::plain(url_to_fetch.to_string(), None),
 526            documentation: None,
 527            source: project::CompletionSource::Custom,
 528            icon_path: Some(icon_path),
 529            match_start: None,
 530            snippet_deduplication_key: None,
 531            insert_text_mode: None,
 532            confirm: Some(confirm_completion_callback(
 533                url_to_fetch.to_string().into(),
 534                source_range.start,
 535                new_text.len() - 1,
 536                mention_uri,
 537                source,
 538                editor,
 539                mention_set,
 540                workspace,
 541            )),
 542        })
 543    }
 544
 545    pub(crate) fn completion_for_action(
 546        action: PromptContextAction,
 547        source_range: Range<Anchor>,
 548        editor: WeakEntity<Editor>,
 549        mention_set: WeakEntity<MentionSet>,
 550        workspace: &Entity<Workspace>,
 551        cx: &mut App,
 552    ) -> Option<Completion> {
 553        let (new_text, on_action) = match action {
 554            PromptContextAction::AddSelections => {
 555                // Collect non-empty editor selections
 556                let editor_selections: Vec<_> = selection_ranges(workspace, cx)
 557                    .into_iter()
 558                    .filter(|(buffer, range)| {
 559                        let snapshot = buffer.read(cx).snapshot();
 560                        range.start.to_offset(&snapshot) != range.end.to_offset(&snapshot)
 561                    })
 562                    .collect();
 563
 564                // Collect terminal selections from all terminal views if the terminal panel is visible
 565                let terminal_selections: Vec<String> = terminal_selections(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(true));
 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.as_ref().and_then(|h| h.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            && let Some(title) = thread.read(cx).title()
1102        {
1103            mentions.insert(MentionUri::Thread {
1104                id: thread.read(cx).session_id().clone(),
1105                name: title.to_string(),
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.as_ref().and_then(|h| h.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(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        // Find the rightmost '@' that has a word boundary before it and no whitespace immediately after
1695        let mut last_mention_start = None;
1696        for (idx, _) in line.rmatch_indices('@') {
1697            // No whitespace immediately after '@'
1698            if line[idx + 1..]
1699                .chars()
1700                .next()
1701                .is_some_and(|c| c.is_whitespace())
1702            {
1703                continue;
1704            }
1705
1706            // Must be a word boundary before '@'
1707            if idx > 0
1708                && line[..idx]
1709                    .chars()
1710                    .last()
1711                    .is_some_and(|c| !c.is_whitespace())
1712            {
1713                continue;
1714            }
1715
1716            last_mention_start = Some(idx);
1717            break;
1718        }
1719
1720        let last_mention_start = last_mention_start?;
1721
1722        let rest_of_line = &line[last_mention_start + 1..];
1723
1724        let mut mode = None;
1725        let mut argument = None;
1726
1727        let mut parts = rest_of_line.split_whitespace();
1728        let mut end = last_mention_start + 1;
1729
1730        if let Some(mode_text) = parts.next() {
1731            // Safe since we check no leading whitespace above
1732            end += mode_text.len();
1733
1734            if let Some(parsed_mode) = PromptContextType::try_from(mode_text).ok()
1735                && supported_modes.contains(&parsed_mode)
1736            {
1737                mode = Some(parsed_mode);
1738            } else {
1739                argument = Some(mode_text.to_string());
1740            }
1741            match rest_of_line[mode_text.len()..].find(|c: char| !c.is_whitespace()) {
1742                Some(whitespace_count) => {
1743                    if let Some(argument_text) = parts.next() {
1744                        // If mode wasn't recognized but we have an argument, don't suggest completions
1745                        // (e.g. '@something word')
1746                        if mode.is_none() && !argument_text.is_empty() {
1747                            return None;
1748                        }
1749
1750                        argument = Some(argument_text.to_string());
1751                        end += whitespace_count + argument_text.len();
1752                    }
1753                }
1754                None => {
1755                    // Rest of line is entirely whitespace
1756                    end += rest_of_line.len() - mode_text.len();
1757                }
1758            }
1759        }
1760
1761        Some(Self {
1762            source_range: last_mention_start + offset_to_line..end + offset_to_line,
1763            mode,
1764            argument,
1765        })
1766    }
1767}
1768
1769fn diagnostics_label(
1770    summary: DiagnosticSummary,
1771    include_errors: bool,
1772    include_warnings: bool,
1773) -> String {
1774    let mut parts = Vec::new();
1775
1776    if include_errors && summary.error_count > 0 {
1777        parts.push(format!(
1778            "{} {}",
1779            summary.error_count,
1780            pluralize("error", summary.error_count)
1781        ));
1782    }
1783
1784    if include_warnings && summary.warning_count > 0 {
1785        parts.push(format!(
1786            "{} {}",
1787            summary.warning_count,
1788            pluralize("warning", summary.warning_count)
1789        ));
1790    }
1791
1792    if parts.is_empty() {
1793        return "Diagnostics".into();
1794    }
1795
1796    let body = if parts.len() == 2 {
1797        format!("{} and {}", parts[0], parts[1])
1798    } else {
1799        parts
1800            .pop()
1801            .expect("at least one part present after non-empty check")
1802    };
1803
1804    format!("Diagnostics: {body}")
1805}
1806
1807fn diagnostics_submenu_label(
1808    summary: DiagnosticSummary,
1809    include_errors: bool,
1810    include_warnings: bool,
1811) -> String {
1812    match (include_errors, include_warnings) {
1813        (true, true) => format!(
1814            "{} {} & {} {}",
1815            summary.error_count,
1816            pluralize("error", summary.error_count),
1817            summary.warning_count,
1818            pluralize("warning", summary.warning_count)
1819        ),
1820        (true, _) => format!(
1821            "{} {}",
1822            summary.error_count,
1823            pluralize("error", summary.error_count)
1824        ),
1825        (_, true) => format!(
1826            "{} {}",
1827            summary.warning_count,
1828            pluralize("warning", summary.warning_count)
1829        ),
1830        _ => "Diagnostics".into(),
1831    }
1832}
1833
1834fn diagnostics_crease_label(
1835    summary: DiagnosticSummary,
1836    include_errors: bool,
1837    include_warnings: bool,
1838) -> SharedString {
1839    diagnostics_label(summary, include_errors, include_warnings).into()
1840}
1841
1842fn pluralize(noun: &str, count: usize) -> String {
1843    if count == 1 {
1844        noun.to_string()
1845    } else {
1846        format!("{noun}s")
1847    }
1848}
1849
1850pub(crate) fn search_files(
1851    query: String,
1852    cancellation_flag: Arc<AtomicBool>,
1853    workspace: &Entity<Workspace>,
1854    cx: &App,
1855) -> Task<Vec<FileMatch>> {
1856    if query.is_empty() {
1857        let workspace = workspace.read(cx);
1858        let project = workspace.project().read(cx);
1859        let visible_worktrees = workspace.visible_worktrees(cx).collect::<Vec<_>>();
1860        let include_root_name = visible_worktrees.len() > 1;
1861
1862        let recent_matches = workspace
1863            .recent_navigation_history(Some(10), cx)
1864            .into_iter()
1865            .map(|(project_path, _)| {
1866                let path_prefix = if include_root_name {
1867                    project
1868                        .worktree_for_id(project_path.worktree_id, cx)
1869                        .map(|wt| wt.read(cx).root_name().into())
1870                        .unwrap_or_else(|| RelPath::empty().into())
1871                } else {
1872                    RelPath::empty().into()
1873                };
1874
1875                FileMatch {
1876                    mat: PathMatch {
1877                        score: 0.,
1878                        positions: Vec::new(),
1879                        worktree_id: project_path.worktree_id.to_usize(),
1880                        path: project_path.path,
1881                        path_prefix,
1882                        distance_to_relative_ancestor: 0,
1883                        is_dir: false,
1884                    },
1885                    is_recent: true,
1886                }
1887            });
1888
1889        let file_matches = visible_worktrees.into_iter().flat_map(|worktree| {
1890            let worktree = worktree.read(cx);
1891            let path_prefix: Arc<RelPath> = if include_root_name {
1892                worktree.root_name().into()
1893            } else {
1894                RelPath::empty().into()
1895            };
1896            worktree.entries(false, 0).map(move |entry| FileMatch {
1897                mat: PathMatch {
1898                    score: 0.,
1899                    positions: Vec::new(),
1900                    worktree_id: worktree.id().to_usize(),
1901                    path: entry.path.clone(),
1902                    path_prefix: path_prefix.clone(),
1903                    distance_to_relative_ancestor: 0,
1904                    is_dir: entry.is_dir(),
1905                },
1906                is_recent: false,
1907            })
1908        });
1909
1910        Task::ready(recent_matches.chain(file_matches).collect())
1911    } else {
1912        let workspace = workspace.read(cx);
1913        let relative_to = workspace
1914            .recent_navigation_history_iter(cx)
1915            .next()
1916            .map(|(path, _)| path.path);
1917        let worktrees = workspace.visible_worktrees(cx).collect::<Vec<_>>();
1918        let include_root_name = worktrees.len() > 1;
1919        let candidate_sets = worktrees
1920            .into_iter()
1921            .map(|worktree| {
1922                let worktree = worktree.read(cx);
1923
1924                PathMatchCandidateSet {
1925                    snapshot: worktree.snapshot(),
1926                    include_ignored: worktree.root_entry().is_some_and(|entry| entry.is_ignored),
1927                    include_root_name,
1928                    candidates: project::Candidates::Entries,
1929                }
1930            })
1931            .collect::<Vec<_>>();
1932
1933        let executor = cx.background_executor().clone();
1934        cx.foreground_executor().spawn(async move {
1935            fuzzy::match_path_sets(
1936                candidate_sets.as_slice(),
1937                query.as_str(),
1938                &relative_to,
1939                false,
1940                100,
1941                &cancellation_flag,
1942                executor,
1943            )
1944            .await
1945            .into_iter()
1946            .map(|mat| FileMatch {
1947                mat,
1948                is_recent: false,
1949            })
1950            .collect::<Vec<_>>()
1951        })
1952    }
1953}
1954
1955pub(crate) fn search_symbols(
1956    query: String,
1957    cancellation_flag: Arc<AtomicBool>,
1958    workspace: &Entity<Workspace>,
1959    cx: &mut App,
1960) -> Task<Vec<SymbolMatch>> {
1961    let symbols_task = workspace.update(cx, |workspace, cx| {
1962        workspace
1963            .project()
1964            .update(cx, |project, cx| project.symbols(&query, cx))
1965    });
1966    let project = workspace.read(cx).project().clone();
1967    cx.spawn(async move |cx| {
1968        let Some(symbols) = symbols_task.await.log_err() else {
1969            return Vec::new();
1970        };
1971        let (visible_match_candidates, external_match_candidates): (Vec<_>, Vec<_>) = project
1972            .update(cx, |project, cx| {
1973                symbols
1974                    .iter()
1975                    .enumerate()
1976                    .map(|(id, symbol)| StringMatchCandidate::new(id, symbol.label.filter_text()))
1977                    .partition(|candidate| match &symbols[candidate.id].path {
1978                        SymbolLocation::InProject(project_path) => project
1979                            .entry_for_path(project_path, cx)
1980                            .is_some_and(|e| !e.is_ignored),
1981                        SymbolLocation::OutsideProject { .. } => false,
1982                    })
1983            });
1984        // Try to support rust-analyzer's path based symbols feature which
1985        // allows to search by rust path syntax, in that case we only want to
1986        // filter names by the last segment
1987        // Ideally this was a first class LSP feature (rich queries)
1988        let query = query
1989            .rsplit_once("::")
1990            .map_or(&*query, |(_, suffix)| suffix)
1991            .to_owned();
1992        // Note if you make changes to this filtering below, also change `project_symbols::ProjectSymbolsDelegate::filter`
1993        const MAX_MATCHES: usize = 100;
1994        let mut visible_matches = cx.foreground_executor().block_on(fuzzy::match_strings(
1995            &visible_match_candidates,
1996            &query,
1997            false,
1998            true,
1999            MAX_MATCHES,
2000            &cancellation_flag,
2001            cx.background_executor().clone(),
2002        ));
2003        let mut external_matches = cx.foreground_executor().block_on(fuzzy::match_strings(
2004            &external_match_candidates,
2005            &query,
2006            false,
2007            true,
2008            MAX_MATCHES - visible_matches.len().min(MAX_MATCHES),
2009            &cancellation_flag,
2010            cx.background_executor().clone(),
2011        ));
2012        let sort_key_for_match = |mat: &StringMatch| {
2013            let symbol = &symbols[mat.candidate_id];
2014            (Reverse(OrderedFloat(mat.score)), symbol.label.filter_text())
2015        };
2016
2017        visible_matches.sort_unstable_by_key(sort_key_for_match);
2018        external_matches.sort_unstable_by_key(sort_key_for_match);
2019        let mut matches = visible_matches;
2020        matches.append(&mut external_matches);
2021
2022        matches
2023            .into_iter()
2024            .map(|mut mat| {
2025                let symbol = symbols[mat.candidate_id].clone();
2026                let filter_start = symbol.label.filter_range.start;
2027                for position in &mut mat.positions {
2028                    *position += filter_start;
2029                }
2030                SymbolMatch { symbol }
2031            })
2032            .collect()
2033    })
2034}
2035
2036fn filter_sessions_by_query(
2037    query: String,
2038    cancellation_flag: Arc<AtomicBool>,
2039    sessions: Vec<SessionMatch>,
2040    cx: &mut App,
2041) -> Task<Vec<SessionMatch>> {
2042    if query.is_empty() {
2043        return Task::ready(sessions);
2044    }
2045    let executor = cx.background_executor().clone();
2046    cx.background_spawn(async move {
2047        filter_sessions(query, cancellation_flag, sessions, executor).await
2048    })
2049}
2050
2051async fn filter_sessions(
2052    query: String,
2053    cancellation_flag: Arc<AtomicBool>,
2054    sessions: Vec<SessionMatch>,
2055    executor: BackgroundExecutor,
2056) -> Vec<SessionMatch> {
2057    let titles = sessions
2058        .iter()
2059        .map(|session| session.title.clone())
2060        .collect::<Vec<_>>();
2061    let candidates = titles
2062        .iter()
2063        .enumerate()
2064        .map(|(id, title)| StringMatchCandidate::new(id, title.as_ref()))
2065        .collect::<Vec<_>>();
2066    let matches = fuzzy::match_strings(
2067        &candidates,
2068        &query,
2069        false,
2070        true,
2071        100,
2072        &cancellation_flag,
2073        executor,
2074    )
2075    .await;
2076
2077    matches
2078        .into_iter()
2079        .map(|mat| sessions[mat.candidate_id].clone())
2080        .collect()
2081}
2082
2083pub(crate) fn search_rules(
2084    query: String,
2085    cancellation_flag: Arc<AtomicBool>,
2086    prompt_store: &Entity<PromptStore>,
2087    cx: &mut App,
2088) -> Task<Vec<RulesContextEntry>> {
2089    let search_task = prompt_store.read(cx).search(query, cancellation_flag, cx);
2090    cx.background_spawn(async move {
2091        search_task
2092            .await
2093            .into_iter()
2094            .flat_map(|metadata| {
2095                // Default prompts are filtered out as they are automatically included.
2096                if metadata.default {
2097                    None
2098                } else {
2099                    Some(RulesContextEntry {
2100                        prompt_id: metadata.id.as_user()?,
2101                        title: metadata.title?,
2102                    })
2103                }
2104            })
2105            .collect::<Vec<_>>()
2106    })
2107}
2108
2109pub struct SymbolMatch {
2110    pub symbol: Symbol,
2111}
2112
2113pub struct FileMatch {
2114    pub mat: PathMatch,
2115    pub is_recent: bool,
2116}
2117
2118pub fn extract_file_name_and_directory(
2119    path: &RelPath,
2120    path_prefix: &RelPath,
2121    path_style: PathStyle,
2122) -> (SharedString, Option<SharedString>) {
2123    // If path is empty, this means we're matching with the root directory itself
2124    // so we use the path_prefix as the name
2125    if path.is_empty() && !path_prefix.is_empty() {
2126        return (path_prefix.display(path_style).to_string().into(), None);
2127    }
2128
2129    let full_path = path_prefix.join(path);
2130    let file_name = full_path.file_name().unwrap_or_default();
2131    let display_path = full_path.display(path_style);
2132    let (directory, file_name) = display_path.split_at(display_path.len() - file_name.len());
2133    (
2134        file_name.to_string().into(),
2135        Some(SharedString::new(directory)).filter(|dir| !dir.is_empty()),
2136    )
2137}
2138
2139fn build_code_label_for_path(
2140    file: &str,
2141    directory: Option<&str>,
2142    line_number: Option<u32>,
2143    label_max_chars: usize,
2144    cx: &App,
2145) -> CodeLabel {
2146    let variable_highlight_id = cx
2147        .theme()
2148        .syntax()
2149        .highlight_id("variable")
2150        .map(HighlightId);
2151    let mut label = CodeLabelBuilder::default();
2152
2153    label.push_str(file, None);
2154    label.push_str(" ", None);
2155
2156    if let Some(directory) = directory {
2157        let file_name_chars = file.chars().count();
2158        // Account for: file_name + space (ellipsis is handled by truncate_and_remove_front)
2159        let directory_max_chars = label_max_chars
2160            .saturating_sub(file_name_chars)
2161            .saturating_sub(1);
2162        let truncated_directory = truncate_and_remove_front(directory, directory_max_chars.max(5));
2163        label.push_str(&truncated_directory, variable_highlight_id);
2164    }
2165    if let Some(line_number) = line_number {
2166        label.push_str(&format!(" L{}", line_number), variable_highlight_id);
2167    }
2168    label.build()
2169}
2170
2171fn terminal_selections(workspace: &Entity<Workspace>, cx: &App) -> Vec<String> {
2172    let mut selections = Vec::new();
2173
2174    // Check if the active item is a terminal (in a panel or not)
2175    if let Some(terminal_view) = workspace
2176        .read(cx)
2177        .active_item(cx)
2178        .and_then(|item| item.act_as::<TerminalView>(cx))
2179    {
2180        if let Some(text) = terminal_view
2181            .read(cx)
2182            .terminal()
2183            .read(cx)
2184            .last_content
2185            .selection_text
2186            .clone()
2187            .filter(|text| !text.is_empty())
2188        {
2189            selections.push(text);
2190        }
2191    }
2192
2193    if let Some(panel) = workspace.read(cx).panel::<TerminalPanel>(cx) {
2194        let position = match TerminalSettings::get_global(cx).dock {
2195            TerminalDockPosition::Left => DockPosition::Left,
2196            TerminalDockPosition::Bottom => DockPosition::Bottom,
2197            TerminalDockPosition::Right => DockPosition::Right,
2198        };
2199        let dock_is_open = workspace
2200            .read(cx)
2201            .dock_at_position(position)
2202            .read(cx)
2203            .is_open();
2204        if dock_is_open {
2205            selections.extend(panel.read(cx).terminal_selections(cx));
2206        }
2207    }
2208
2209    selections
2210}
2211
2212fn selection_ranges(
2213    workspace: &Entity<Workspace>,
2214    cx: &mut App,
2215) -> Vec<(Entity<Buffer>, Range<text::Anchor>)> {
2216    let Some(editor) = workspace
2217        .read(cx)
2218        .active_item(cx)
2219        .and_then(|item| item.act_as::<Editor>(cx))
2220    else {
2221        return Vec::new();
2222    };
2223
2224    editor.update(cx, |editor, cx| {
2225        let selections = editor.selections.all_adjusted(&editor.display_snapshot(cx));
2226
2227        let buffer = editor.buffer().clone().read(cx);
2228        let snapshot = buffer.snapshot(cx);
2229
2230        selections
2231            .into_iter()
2232            .filter(|s| !s.is_empty())
2233            .map(|s| snapshot.anchor_after(s.start)..snapshot.anchor_before(s.end))
2234            .flat_map(|range| {
2235                let (start_buffer, start) = buffer.text_anchor_for_position(range.start, cx)?;
2236                let (end_buffer, end) = buffer.text_anchor_for_position(range.end, cx)?;
2237                if start_buffer != end_buffer {
2238                    return None;
2239                }
2240                Some((start_buffer, start..end))
2241            })
2242            .collect::<Vec<_>>()
2243    })
2244}
2245
2246#[cfg(test)]
2247mod tests {
2248    use super::*;
2249    use gpui::TestAppContext;
2250
2251    #[test]
2252    fn test_prompt_completion_parse() {
2253        let supported_modes = vec![PromptContextType::File, PromptContextType::Symbol];
2254
2255        assert_eq!(
2256            PromptCompletion::try_parse("/", 0, &supported_modes),
2257            Some(PromptCompletion::SlashCommand(SlashCommandCompletion {
2258                source_range: 0..1,
2259                command: None,
2260                argument: None,
2261            }))
2262        );
2263
2264        assert_eq!(
2265            PromptCompletion::try_parse("@", 0, &supported_modes),
2266            Some(PromptCompletion::Mention(MentionCompletion {
2267                source_range: 0..1,
2268                mode: None,
2269                argument: None,
2270            }))
2271        );
2272
2273        assert_eq!(
2274            PromptCompletion::try_parse("/test @file", 0, &supported_modes),
2275            Some(PromptCompletion::Mention(MentionCompletion {
2276                source_range: 6..11,
2277                mode: Some(PromptContextType::File),
2278                argument: None,
2279            }))
2280        );
2281    }
2282
2283    #[test]
2284    fn test_slash_command_completion_parse() {
2285        assert_eq!(
2286            SlashCommandCompletion::try_parse("/", 0),
2287            Some(SlashCommandCompletion {
2288                source_range: 0..1,
2289                command: None,
2290                argument: None,
2291            })
2292        );
2293
2294        assert_eq!(
2295            SlashCommandCompletion::try_parse("/help", 0),
2296            Some(SlashCommandCompletion {
2297                source_range: 0..5,
2298                command: Some("help".to_string()),
2299                argument: None,
2300            })
2301        );
2302
2303        assert_eq!(
2304            SlashCommandCompletion::try_parse("/help ", 0),
2305            Some(SlashCommandCompletion {
2306                source_range: 0..5,
2307                command: Some("help".to_string()),
2308                argument: None,
2309            })
2310        );
2311
2312        assert_eq!(
2313            SlashCommandCompletion::try_parse("/help arg1", 0),
2314            Some(SlashCommandCompletion {
2315                source_range: 0..10,
2316                command: Some("help".to_string()),
2317                argument: Some("arg1".to_string()),
2318            })
2319        );
2320
2321        assert_eq!(
2322            SlashCommandCompletion::try_parse("/help arg1 arg2", 0),
2323            Some(SlashCommandCompletion {
2324                source_range: 0..15,
2325                command: Some("help".to_string()),
2326                argument: Some("arg1 arg2".to_string()),
2327            })
2328        );
2329
2330        assert_eq!(
2331            SlashCommandCompletion::try_parse("/拿不到命令 拿不到命令 ", 0),
2332            Some(SlashCommandCompletion {
2333                source_range: 0..30,
2334                command: Some("拿不到命令".to_string()),
2335                argument: Some("拿不到命令".to_string()),
2336            })
2337        );
2338
2339        assert_eq!(SlashCommandCompletion::try_parse("Lorem Ipsum", 0), None);
2340
2341        assert_eq!(SlashCommandCompletion::try_parse("Lorem /", 0), None);
2342
2343        assert_eq!(SlashCommandCompletion::try_parse("Lorem /help", 0), None);
2344
2345        assert_eq!(SlashCommandCompletion::try_parse("Lorem/", 0), None);
2346
2347        assert_eq!(SlashCommandCompletion::try_parse("/ ", 0), None);
2348    }
2349
2350    #[test]
2351    fn test_mention_completion_parse() {
2352        let supported_modes = vec![PromptContextType::File, PromptContextType::Symbol];
2353        let supported_modes_with_diagnostics = vec![
2354            PromptContextType::File,
2355            PromptContextType::Symbol,
2356            PromptContextType::Diagnostics,
2357        ];
2358
2359        assert_eq!(
2360            MentionCompletion::try_parse("Lorem Ipsum", 0, &supported_modes),
2361            None
2362        );
2363
2364        assert_eq!(
2365            MentionCompletion::try_parse("Lorem @", 0, &supported_modes),
2366            Some(MentionCompletion {
2367                source_range: 6..7,
2368                mode: None,
2369                argument: None,
2370            })
2371        );
2372
2373        assert_eq!(
2374            MentionCompletion::try_parse("Lorem @file", 0, &supported_modes),
2375            Some(MentionCompletion {
2376                source_range: 6..11,
2377                mode: Some(PromptContextType::File),
2378                argument: None,
2379            })
2380        );
2381
2382        assert_eq!(
2383            MentionCompletion::try_parse("Lorem @file ", 0, &supported_modes),
2384            Some(MentionCompletion {
2385                source_range: 6..12,
2386                mode: Some(PromptContextType::File),
2387                argument: None,
2388            })
2389        );
2390
2391        assert_eq!(
2392            MentionCompletion::try_parse("Lorem @file main.rs", 0, &supported_modes),
2393            Some(MentionCompletion {
2394                source_range: 6..19,
2395                mode: Some(PromptContextType::File),
2396                argument: Some("main.rs".to_string()),
2397            })
2398        );
2399
2400        assert_eq!(
2401            MentionCompletion::try_parse("Lorem @file main.rs ", 0, &supported_modes),
2402            Some(MentionCompletion {
2403                source_range: 6..19,
2404                mode: Some(PromptContextType::File),
2405                argument: Some("main.rs".to_string()),
2406            })
2407        );
2408
2409        assert_eq!(
2410            MentionCompletion::try_parse("Lorem @file main.rs Ipsum", 0, &supported_modes),
2411            Some(MentionCompletion {
2412                source_range: 6..19,
2413                mode: Some(PromptContextType::File),
2414                argument: Some("main.rs".to_string()),
2415            })
2416        );
2417
2418        assert_eq!(
2419            MentionCompletion::try_parse("Lorem @main", 0, &supported_modes),
2420            Some(MentionCompletion {
2421                source_range: 6..11,
2422                mode: None,
2423                argument: Some("main".to_string()),
2424            })
2425        );
2426
2427        assert_eq!(
2428            MentionCompletion::try_parse("Lorem @main ", 0, &supported_modes),
2429            Some(MentionCompletion {
2430                source_range: 6..12,
2431                mode: None,
2432                argument: Some("main".to_string()),
2433            })
2434        );
2435
2436        assert_eq!(
2437            MentionCompletion::try_parse("Lorem @main m", 0, &supported_modes),
2438            None
2439        );
2440
2441        assert_eq!(
2442            MentionCompletion::try_parse("test@", 0, &supported_modes),
2443            None
2444        );
2445
2446        // Allowed non-file mentions
2447
2448        assert_eq!(
2449            MentionCompletion::try_parse("Lorem @symbol main", 0, &supported_modes),
2450            Some(MentionCompletion {
2451                source_range: 6..18,
2452                mode: Some(PromptContextType::Symbol),
2453                argument: Some("main".to_string()),
2454            })
2455        );
2456
2457        assert_eq!(
2458            MentionCompletion::try_parse(
2459                "Lorem @symbol agent_ui::completion_provider",
2460                0,
2461                &supported_modes
2462            ),
2463            Some(MentionCompletion {
2464                source_range: 6..43,
2465                mode: Some(PromptContextType::Symbol),
2466                argument: Some("agent_ui::completion_provider".to_string()),
2467            })
2468        );
2469
2470        assert_eq!(
2471            MentionCompletion::try_parse(
2472                "Lorem @diagnostics",
2473                0,
2474                &supported_modes_with_diagnostics
2475            ),
2476            Some(MentionCompletion {
2477                source_range: 6..18,
2478                mode: Some(PromptContextType::Diagnostics),
2479                argument: None,
2480            })
2481        );
2482
2483        // Disallowed non-file mentions
2484        assert_eq!(
2485            MentionCompletion::try_parse("Lorem @symbol main", 0, &[PromptContextType::File]),
2486            None
2487        );
2488
2489        assert_eq!(
2490            MentionCompletion::try_parse("Lorem@symbol", 0, &supported_modes),
2491            None,
2492            "Should not parse mention inside word"
2493        );
2494
2495        assert_eq!(
2496            MentionCompletion::try_parse("Lorem @ file", 0, &supported_modes),
2497            None,
2498            "Should not parse with a space after @"
2499        );
2500
2501        assert_eq!(
2502            MentionCompletion::try_parse("@ file", 0, &supported_modes),
2503            None,
2504            "Should not parse with a space after @ at the start of the line"
2505        );
2506
2507        assert_eq!(
2508            MentionCompletion::try_parse(
2509                "@fetch https://www.npmjs.com/package/@matterport/sdk",
2510                0,
2511                &[PromptContextType::Fetch]
2512            ),
2513            Some(MentionCompletion {
2514                source_range: 0..52,
2515                mode: Some(PromptContextType::Fetch),
2516                argument: Some("https://www.npmjs.com/package/@matterport/sdk".to_string()),
2517            }),
2518            "Should handle URLs with @ in the path"
2519        );
2520
2521        assert_eq!(
2522            MentionCompletion::try_parse(
2523                "@fetch https://example.com/@org/@repo/file",
2524                0,
2525                &[PromptContextType::Fetch]
2526            ),
2527            Some(MentionCompletion {
2528                source_range: 0..42,
2529                mode: Some(PromptContextType::Fetch),
2530                argument: Some("https://example.com/@org/@repo/file".to_string()),
2531            }),
2532            "Should handle URLs with multiple @ characters"
2533        );
2534
2535        assert_eq!(
2536            MentionCompletion::try_parse(
2537                "@fetch https://example.com/@",
2538                0,
2539                &[PromptContextType::Fetch]
2540            ),
2541            Some(MentionCompletion {
2542                source_range: 0..28,
2543                mode: Some(PromptContextType::Fetch),
2544                argument: Some("https://example.com/@".to_string()),
2545            }),
2546            "Should parse URL ending with @ (even if URL is incomplete)"
2547        );
2548    }
2549
2550    #[gpui::test]
2551    async fn test_filter_sessions_by_query(cx: &mut TestAppContext) {
2552        let alpha = SessionMatch {
2553            session_id: acp::SessionId::new("session-alpha"),
2554            title: "Alpha Session".into(),
2555        };
2556        let beta = SessionMatch {
2557            session_id: acp::SessionId::new("session-beta"),
2558            title: "Beta Session".into(),
2559        };
2560
2561        let sessions = vec![alpha.clone(), beta];
2562
2563        let task = {
2564            let mut app = cx.app.borrow_mut();
2565            filter_sessions_by_query(
2566                "Alpha".into(),
2567                Arc::new(AtomicBool::default()),
2568                sessions,
2569                &mut app,
2570            )
2571        };
2572
2573        let results = task.await;
2574        assert_eq!(results.len(), 1);
2575        assert_eq!(results[0].session_id, alpha.session_id);
2576    }
2577
2578    #[gpui::test]
2579    async fn test_search_files_path_distance_ordering(cx: &mut TestAppContext) {
2580        use project::Project;
2581        use serde_json::json;
2582        use util::{path, rel_path::rel_path};
2583        use workspace::{AppState, MultiWorkspace};
2584
2585        let app_state = cx.update(|cx| {
2586            let state = AppState::test(cx);
2587            theme_settings::init(theme::LoadThemes::JustBase, cx);
2588            editor::init(cx);
2589            state
2590        });
2591
2592        app_state
2593            .fs
2594            .as_fake()
2595            .insert_tree(
2596                path!("/root"),
2597                json!({
2598                    "dir1": { "a.txt": "" },
2599                    "dir2": {
2600                        "a.txt": "",
2601                        "b.txt": ""
2602                    }
2603                }),
2604            )
2605            .await;
2606
2607        let project = Project::test(app_state.fs.clone(), [path!("/root").as_ref()], cx).await;
2608        let (multi_workspace, cx) =
2609            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
2610        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2611
2612        let worktree_id = cx.read(|cx| {
2613            let worktrees = workspace.read(cx).worktrees(cx).collect::<Vec<_>>();
2614            assert_eq!(worktrees.len(), 1);
2615            worktrees[0].read(cx).id()
2616        });
2617
2618        // Open a file in dir2 to create navigation history.
2619        // When searching for "a.txt", dir2/a.txt should be sorted first because
2620        // it is closer to the most recently opened file (dir2/b.txt).
2621        let b_path = ProjectPath {
2622            worktree_id,
2623            path: rel_path("dir2/b.txt").into(),
2624        };
2625        workspace
2626            .update_in(cx, |workspace, window, cx| {
2627                workspace.open_path(b_path, None, true, window, cx)
2628            })
2629            .await
2630            .unwrap();
2631
2632        let results = cx
2633            .update(|_window, cx| {
2634                search_files(
2635                    "a.txt".into(),
2636                    Arc::new(AtomicBool::default()),
2637                    &workspace,
2638                    cx,
2639                )
2640            })
2641            .await;
2642
2643        assert_eq!(results.len(), 2, "expected 2 matching files");
2644        assert_eq!(
2645            results[0].mat.path.as_ref(),
2646            rel_path("dir2/a.txt"),
2647            "dir2/a.txt should be first because it's closer to the recently opened dir2/b.txt"
2648        );
2649        assert_eq!(
2650            results[1].mat.path.as_ref(),
2651            rel_path("dir1/a.txt"),
2652            "dir1/a.txt should be second"
2653        );
2654    }
2655}