completion_provider.rs

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