completion_provider.rs

   1use std::cell::RefCell;
   2use std::ops::Range;
   3use std::path::PathBuf;
   4use std::rc::Rc;
   5use std::sync::Arc;
   6use std::sync::atomic::AtomicBool;
   7
   8use acp_thread::MentionUri;
   9use agent_client_protocol as acp;
  10use agent2::{HistoryEntry, HistoryStore};
  11use anyhow::Result;
  12use editor::{CompletionProvider, Editor, ExcerptId};
  13use fuzzy::{StringMatch, StringMatchCandidate};
  14use gpui::{App, Entity, Task, WeakEntity};
  15use language::{Buffer, CodeLabel, HighlightId};
  16use lsp::CompletionContext;
  17use project::lsp_store::{CompletionDocumentation, SymbolLocation};
  18use project::{
  19    Completion, CompletionDisplayOptions, CompletionIntent, CompletionResponse, Project,
  20    ProjectPath, Symbol, WorktreeId,
  21};
  22use prompt_store::PromptStore;
  23use rope::Point;
  24use text::{Anchor, ToPoint as _};
  25use ui::prelude::*;
  26use util::rel_path::RelPath;
  27use workspace::Workspace;
  28
  29use crate::AgentPanel;
  30use crate::acp::message_editor::{MessageEditor, MessageEditorEvent};
  31use crate::context_picker::file_context_picker::{FileMatch, search_files};
  32use crate::context_picker::rules_context_picker::{RulesContextEntry, search_rules};
  33use crate::context_picker::symbol_context_picker::SymbolMatch;
  34use crate::context_picker::symbol_context_picker::search_symbols;
  35use crate::context_picker::{
  36    ContextPickerAction, ContextPickerEntry, ContextPickerMode, selection_ranges,
  37};
  38
  39pub(crate) enum Match {
  40    File(FileMatch),
  41    Symbol(SymbolMatch),
  42    Thread(HistoryEntry),
  43    RecentThread(HistoryEntry),
  44    Fetch(SharedString),
  45    Rules(RulesContextEntry),
  46    Entry(EntryMatch),
  47}
  48
  49pub struct EntryMatch {
  50    mat: Option<StringMatch>,
  51    entry: ContextPickerEntry,
  52}
  53
  54impl Match {
  55    pub fn score(&self) -> f64 {
  56        match self {
  57            Match::File(file) => file.mat.score,
  58            Match::Entry(mode) => mode.mat.as_ref().map(|mat| mat.score).unwrap_or(1.),
  59            Match::Thread(_) => 1.,
  60            Match::RecentThread(_) => 1.,
  61            Match::Symbol(_) => 1.,
  62            Match::Rules(_) => 1.,
  63            Match::Fetch(_) => 1.,
  64        }
  65    }
  66}
  67
  68pub struct ContextPickerCompletionProvider {
  69    message_editor: WeakEntity<MessageEditor>,
  70    workspace: WeakEntity<Workspace>,
  71    history_store: Entity<HistoryStore>,
  72    prompt_store: Option<Entity<PromptStore>>,
  73    prompt_capabilities: Rc<RefCell<acp::PromptCapabilities>>,
  74    available_commands: Rc<RefCell<Vec<acp::AvailableCommand>>>,
  75}
  76
  77impl ContextPickerCompletionProvider {
  78    pub fn new(
  79        message_editor: WeakEntity<MessageEditor>,
  80        workspace: WeakEntity<Workspace>,
  81        history_store: Entity<HistoryStore>,
  82        prompt_store: Option<Entity<PromptStore>>,
  83        prompt_capabilities: Rc<RefCell<acp::PromptCapabilities>>,
  84        available_commands: Rc<RefCell<Vec<acp::AvailableCommand>>>,
  85    ) -> Self {
  86        Self {
  87            message_editor,
  88            workspace,
  89            history_store,
  90            prompt_store,
  91            prompt_capabilities,
  92            available_commands,
  93        }
  94    }
  95
  96    fn completion_for_entry(
  97        entry: ContextPickerEntry,
  98        source_range: Range<Anchor>,
  99        message_editor: WeakEntity<MessageEditor>,
 100        workspace: &Entity<Workspace>,
 101        cx: &mut App,
 102    ) -> Option<Completion> {
 103        match entry {
 104            ContextPickerEntry::Mode(mode) => Some(Completion {
 105                replace_range: source_range,
 106                new_text: format!("@{} ", mode.keyword()),
 107                label: CodeLabel::plain(mode.label().to_string(), None),
 108                icon_path: Some(mode.icon().path().into()),
 109                documentation: None,
 110                source: project::CompletionSource::Custom,
 111                insert_text_mode: None,
 112                // This ensures that when a user accepts this completion, the
 113                // completion menu will still be shown after "@category " is
 114                // inserted
 115                confirm: Some(Arc::new(|_, _, _| true)),
 116            }),
 117            ContextPickerEntry::Action(action) => {
 118                Self::completion_for_action(action, source_range, message_editor, workspace, cx)
 119            }
 120        }
 121    }
 122
 123    fn completion_for_thread(
 124        thread_entry: HistoryEntry,
 125        source_range: Range<Anchor>,
 126        recent: bool,
 127        editor: WeakEntity<MessageEditor>,
 128        cx: &mut App,
 129    ) -> Completion {
 130        let uri = thread_entry.mention_uri();
 131
 132        let icon_for_completion = if recent {
 133            IconName::HistoryRerun.path().into()
 134        } else {
 135            uri.icon_path(cx)
 136        };
 137
 138        let new_text = format!("{} ", uri.as_link());
 139
 140        let new_text_len = new_text.len();
 141        Completion {
 142            replace_range: source_range.clone(),
 143            new_text,
 144            label: CodeLabel::plain(thread_entry.title().to_string(), None),
 145            documentation: None,
 146            insert_text_mode: None,
 147            source: project::CompletionSource::Custom,
 148            icon_path: Some(icon_for_completion),
 149            confirm: Some(confirm_completion_callback(
 150                thread_entry.title().clone(),
 151                source_range.start,
 152                new_text_len - 1,
 153                editor,
 154                uri,
 155            )),
 156        }
 157    }
 158
 159    fn completion_for_rules(
 160        rule: RulesContextEntry,
 161        source_range: Range<Anchor>,
 162        editor: WeakEntity<MessageEditor>,
 163        cx: &mut App,
 164    ) -> Completion {
 165        let uri = MentionUri::Rule {
 166            id: rule.prompt_id.into(),
 167            name: rule.title.to_string(),
 168        };
 169        let new_text = format!("{} ", uri.as_link());
 170        let new_text_len = new_text.len();
 171        let icon_path = uri.icon_path(cx);
 172        Completion {
 173            replace_range: source_range.clone(),
 174            new_text,
 175            label: CodeLabel::plain(rule.title.to_string(), None),
 176            documentation: None,
 177            insert_text_mode: None,
 178            source: project::CompletionSource::Custom,
 179            icon_path: Some(icon_path),
 180            confirm: Some(confirm_completion_callback(
 181                rule.title,
 182                source_range.start,
 183                new_text_len - 1,
 184                editor,
 185                uri,
 186            )),
 187        }
 188    }
 189
 190    pub(crate) fn completion_for_path(
 191        project_path: ProjectPath,
 192        path_prefix: &RelPath,
 193        is_recent: bool,
 194        is_directory: bool,
 195        source_range: Range<Anchor>,
 196        message_editor: WeakEntity<MessageEditor>,
 197        project: Entity<Project>,
 198        cx: &mut App,
 199    ) -> Option<Completion> {
 200        let path_style = project.read(cx).path_style(cx);
 201        let (file_name, directory) =
 202            crate::context_picker::file_context_picker::extract_file_name_and_directory(
 203                &project_path.path,
 204                path_prefix,
 205                path_style,
 206            );
 207
 208        let label =
 209            build_code_label_for_full_path(&file_name, directory.as_ref().map(|s| s.as_ref()), cx);
 210
 211        let abs_path = project.read(cx).absolute_path(&project_path, cx)?;
 212
 213        let uri = if is_directory {
 214            MentionUri::Directory { abs_path }
 215        } else {
 216            MentionUri::File { abs_path }
 217        };
 218
 219        let crease_icon_path = uri.icon_path(cx);
 220        let completion_icon_path = if is_recent {
 221            IconName::HistoryRerun.path().into()
 222        } else {
 223            crease_icon_path
 224        };
 225
 226        let new_text = format!("{} ", uri.as_link());
 227        let new_text_len = new_text.len();
 228        Some(Completion {
 229            replace_range: source_range.clone(),
 230            new_text,
 231            label,
 232            documentation: None,
 233            source: project::CompletionSource::Custom,
 234            icon_path: Some(completion_icon_path),
 235            insert_text_mode: None,
 236            confirm: Some(confirm_completion_callback(
 237                file_name,
 238                source_range.start,
 239                new_text_len - 1,
 240                message_editor,
 241                uri,
 242            )),
 243        })
 244    }
 245
 246    fn completion_for_symbol(
 247        symbol: Symbol,
 248        source_range: Range<Anchor>,
 249        message_editor: WeakEntity<MessageEditor>,
 250        workspace: Entity<Workspace>,
 251        cx: &mut App,
 252    ) -> Option<Completion> {
 253        let project = workspace.read(cx).project().clone();
 254
 255        let label = CodeLabel::plain(symbol.name.clone(), None);
 256
 257        let abs_path = match &symbol.path {
 258            SymbolLocation::InProject(project_path) => {
 259                project.read(cx).absolute_path(&project_path, cx)?
 260            }
 261            SymbolLocation::OutsideProject {
 262                abs_path,
 263                signature: _,
 264            } => PathBuf::from(abs_path.as_ref()),
 265        };
 266        let uri = MentionUri::Symbol {
 267            abs_path,
 268            name: symbol.name.clone(),
 269            line_range: symbol.range.start.0.row..=symbol.range.end.0.row,
 270        };
 271        let new_text = format!("{} ", uri.as_link());
 272        let new_text_len = new_text.len();
 273        let icon_path = uri.icon_path(cx);
 274        Some(Completion {
 275            replace_range: source_range.clone(),
 276            new_text,
 277            label,
 278            documentation: None,
 279            source: project::CompletionSource::Custom,
 280            icon_path: Some(icon_path),
 281            insert_text_mode: None,
 282            confirm: Some(confirm_completion_callback(
 283                symbol.name.into(),
 284                source_range.start,
 285                new_text_len - 1,
 286                message_editor,
 287                uri,
 288            )),
 289        })
 290    }
 291
 292    fn completion_for_fetch(
 293        source_range: Range<Anchor>,
 294        url_to_fetch: SharedString,
 295        message_editor: WeakEntity<MessageEditor>,
 296        cx: &mut App,
 297    ) -> Option<Completion> {
 298        let new_text = format!("@fetch {} ", url_to_fetch);
 299        let url_to_fetch = url::Url::parse(url_to_fetch.as_ref())
 300            .or_else(|_| url::Url::parse(&format!("https://{url_to_fetch}")))
 301            .ok()?;
 302        let mention_uri = MentionUri::Fetch {
 303            url: url_to_fetch.clone(),
 304        };
 305        let icon_path = mention_uri.icon_path(cx);
 306        Some(Completion {
 307            replace_range: source_range.clone(),
 308            new_text: new_text.clone(),
 309            label: CodeLabel::plain(url_to_fetch.to_string(), None),
 310            documentation: None,
 311            source: project::CompletionSource::Custom,
 312            icon_path: Some(icon_path),
 313            insert_text_mode: None,
 314            confirm: Some(confirm_completion_callback(
 315                url_to_fetch.to_string().into(),
 316                source_range.start,
 317                new_text.len() - 1,
 318                message_editor,
 319                mention_uri,
 320            )),
 321        })
 322    }
 323
 324    pub(crate) fn completion_for_action(
 325        action: ContextPickerAction,
 326        source_range: Range<Anchor>,
 327        message_editor: WeakEntity<MessageEditor>,
 328        workspace: &Entity<Workspace>,
 329        cx: &mut App,
 330    ) -> Option<Completion> {
 331        let (new_text, on_action) = match action {
 332            ContextPickerAction::AddSelections => {
 333                const PLACEHOLDER: &str = "selection ";
 334                let selections = selection_ranges(workspace, cx)
 335                    .into_iter()
 336                    .enumerate()
 337                    .map(|(ix, (buffer, range))| {
 338                        (
 339                            buffer,
 340                            range,
 341                            (PLACEHOLDER.len() * ix)..(PLACEHOLDER.len() * (ix + 1) - 1),
 342                        )
 343                    })
 344                    .collect::<Vec<_>>();
 345
 346                let new_text: String = PLACEHOLDER.repeat(selections.len());
 347
 348                let callback = Arc::new({
 349                    let source_range = source_range.clone();
 350                    move |_, window: &mut Window, cx: &mut App| {
 351                        let selections = selections.clone();
 352                        let message_editor = message_editor.clone();
 353                        let source_range = source_range.clone();
 354                        window.defer(cx, move |window, cx| {
 355                            message_editor
 356                                .update(cx, |message_editor, cx| {
 357                                    message_editor.confirm_mention_for_selection(
 358                                        source_range,
 359                                        selections,
 360                                        window,
 361                                        cx,
 362                                    )
 363                                })
 364                                .ok();
 365                        });
 366                        false
 367                    }
 368                });
 369
 370                (new_text, callback)
 371            }
 372        };
 373
 374        Some(Completion {
 375            replace_range: source_range,
 376            new_text,
 377            label: CodeLabel::plain(action.label().to_string(), None),
 378            icon_path: Some(action.icon().path().into()),
 379            documentation: None,
 380            source: project::CompletionSource::Custom,
 381            insert_text_mode: None,
 382            // This ensures that when a user accepts this completion, the
 383            // completion menu will still be shown after "@category " is
 384            // inserted
 385            confirm: Some(on_action),
 386        })
 387    }
 388
 389    fn search_slash_commands(
 390        &self,
 391        query: String,
 392        cx: &mut App,
 393    ) -> Task<Vec<acp::AvailableCommand>> {
 394        let commands = self.available_commands.borrow().clone();
 395        if commands.is_empty() {
 396            return Task::ready(Vec::new());
 397        }
 398
 399        cx.spawn(async move |cx| {
 400            let candidates = commands
 401                .iter()
 402                .enumerate()
 403                .map(|(id, command)| StringMatchCandidate::new(id, &command.name))
 404                .collect::<Vec<_>>();
 405
 406            let matches = fuzzy::match_strings(
 407                &candidates,
 408                &query,
 409                false,
 410                true,
 411                100,
 412                &Arc::new(AtomicBool::default()),
 413                cx.background_executor().clone(),
 414            )
 415            .await;
 416
 417            matches
 418                .into_iter()
 419                .map(|mat| commands[mat.candidate_id].clone())
 420                .collect()
 421        })
 422    }
 423
 424    fn search_mentions(
 425        &self,
 426        mode: Option<ContextPickerMode>,
 427        query: String,
 428        cancellation_flag: Arc<AtomicBool>,
 429        cx: &mut App,
 430    ) -> Task<Vec<Match>> {
 431        let Some(workspace) = self.workspace.upgrade() else {
 432            return Task::ready(Vec::default());
 433        };
 434        match mode {
 435            Some(ContextPickerMode::File) => {
 436                let search_files_task = search_files(query, cancellation_flag, &workspace, cx);
 437                cx.background_spawn(async move {
 438                    search_files_task
 439                        .await
 440                        .into_iter()
 441                        .map(Match::File)
 442                        .collect()
 443                })
 444            }
 445
 446            Some(ContextPickerMode::Symbol) => {
 447                let search_symbols_task = search_symbols(query, cancellation_flag, &workspace, cx);
 448                cx.background_spawn(async move {
 449                    search_symbols_task
 450                        .await
 451                        .into_iter()
 452                        .map(Match::Symbol)
 453                        .collect()
 454                })
 455            }
 456
 457            Some(ContextPickerMode::Thread) => {
 458                let search_threads_task =
 459                    search_threads(query, cancellation_flag, &self.history_store, cx);
 460                cx.background_spawn(async move {
 461                    search_threads_task
 462                        .await
 463                        .into_iter()
 464                        .map(Match::Thread)
 465                        .collect()
 466                })
 467            }
 468
 469            Some(ContextPickerMode::Fetch) => {
 470                if !query.is_empty() {
 471                    Task::ready(vec![Match::Fetch(query.into())])
 472                } else {
 473                    Task::ready(Vec::new())
 474                }
 475            }
 476
 477            Some(ContextPickerMode::Rules) => {
 478                if let Some(prompt_store) = self.prompt_store.as_ref() {
 479                    let search_rules_task =
 480                        search_rules(query, cancellation_flag, prompt_store, cx);
 481                    cx.background_spawn(async move {
 482                        search_rules_task
 483                            .await
 484                            .into_iter()
 485                            .map(Match::Rules)
 486                            .collect::<Vec<_>>()
 487                    })
 488                } else {
 489                    Task::ready(Vec::new())
 490                }
 491            }
 492
 493            None if query.is_empty() => {
 494                let mut matches = self.recent_context_picker_entries(&workspace, cx);
 495
 496                matches.extend(
 497                    self.available_context_picker_entries(&workspace, cx)
 498                        .into_iter()
 499                        .map(|mode| {
 500                            Match::Entry(EntryMatch {
 501                                entry: mode,
 502                                mat: None,
 503                            })
 504                        }),
 505                );
 506
 507                Task::ready(matches)
 508            }
 509            None => {
 510                let executor = cx.background_executor().clone();
 511
 512                let search_files_task =
 513                    search_files(query.clone(), cancellation_flag, &workspace, cx);
 514
 515                let entries = self.available_context_picker_entries(&workspace, cx);
 516                let entry_candidates = entries
 517                    .iter()
 518                    .enumerate()
 519                    .map(|(ix, entry)| StringMatchCandidate::new(ix, entry.keyword()))
 520                    .collect::<Vec<_>>();
 521
 522                cx.background_spawn(async move {
 523                    let mut matches = search_files_task
 524                        .await
 525                        .into_iter()
 526                        .map(Match::File)
 527                        .collect::<Vec<_>>();
 528
 529                    let entry_matches = fuzzy::match_strings(
 530                        &entry_candidates,
 531                        &query,
 532                        false,
 533                        true,
 534                        100,
 535                        &Arc::new(AtomicBool::default()),
 536                        executor,
 537                    )
 538                    .await;
 539
 540                    matches.extend(entry_matches.into_iter().map(|mat| {
 541                        Match::Entry(EntryMatch {
 542                            entry: entries[mat.candidate_id],
 543                            mat: Some(mat),
 544                        })
 545                    }));
 546
 547                    matches.sort_by(|a, b| {
 548                        b.score()
 549                            .partial_cmp(&a.score())
 550                            .unwrap_or(std::cmp::Ordering::Equal)
 551                    });
 552
 553                    matches
 554                })
 555            }
 556        }
 557    }
 558
 559    fn recent_context_picker_entries(
 560        &self,
 561        workspace: &Entity<Workspace>,
 562        cx: &mut App,
 563    ) -> Vec<Match> {
 564        let mut recent = Vec::with_capacity(6);
 565
 566        let mut mentions = self
 567            .message_editor
 568            .read_with(cx, |message_editor, _cx| message_editor.mentions())
 569            .unwrap_or_default();
 570        let workspace = workspace.read(cx);
 571        let project = workspace.project().read(cx);
 572
 573        if let Some(agent_panel) = workspace.panel::<AgentPanel>(cx)
 574            && let Some(thread) = agent_panel.read(cx).active_agent_thread(cx)
 575        {
 576            let thread = thread.read(cx);
 577            mentions.insert(MentionUri::Thread {
 578                id: thread.session_id().clone(),
 579                name: thread.title().into(),
 580            });
 581        }
 582
 583        recent.extend(
 584            workspace
 585                .recent_navigation_history_iter(cx)
 586                .filter(|(_, abs_path)| {
 587                    abs_path.as_ref().is_none_or(|path| {
 588                        !mentions.contains(&MentionUri::File {
 589                            abs_path: path.clone(),
 590                        })
 591                    })
 592                })
 593                .take(4)
 594                .filter_map(|(project_path, _)| {
 595                    project
 596                        .worktree_for_id(project_path.worktree_id, cx)
 597                        .map(|worktree| {
 598                            let path_prefix = worktree.read(cx).root_name().into();
 599                            Match::File(FileMatch {
 600                                mat: fuzzy::PathMatch {
 601                                    score: 1.,
 602                                    positions: Vec::new(),
 603                                    worktree_id: project_path.worktree_id.to_usize(),
 604                                    path: project_path.path,
 605                                    path_prefix,
 606                                    is_dir: false,
 607                                    distance_to_relative_ancestor: 0,
 608                                },
 609                                is_recent: true,
 610                            })
 611                        })
 612                }),
 613        );
 614
 615        if self.prompt_capabilities.borrow().embedded_context {
 616            const RECENT_COUNT: usize = 2;
 617            let threads = self
 618                .history_store
 619                .read(cx)
 620                .recently_opened_entries(cx)
 621                .into_iter()
 622                .filter(|thread| !mentions.contains(&thread.mention_uri()))
 623                .take(RECENT_COUNT)
 624                .collect::<Vec<_>>();
 625
 626            recent.extend(threads.into_iter().map(Match::RecentThread));
 627        }
 628
 629        recent
 630    }
 631
 632    fn available_context_picker_entries(
 633        &self,
 634        workspace: &Entity<Workspace>,
 635        cx: &mut App,
 636    ) -> Vec<ContextPickerEntry> {
 637        let embedded_context = self.prompt_capabilities.borrow().embedded_context;
 638        let mut entries = if embedded_context {
 639            vec![
 640                ContextPickerEntry::Mode(ContextPickerMode::File),
 641                ContextPickerEntry::Mode(ContextPickerMode::Symbol),
 642                ContextPickerEntry::Mode(ContextPickerMode::Thread),
 643            ]
 644        } else {
 645            // File is always available, but we don't need a mode entry
 646            vec![]
 647        };
 648
 649        let has_selection = workspace
 650            .read(cx)
 651            .active_item(cx)
 652            .and_then(|item| item.downcast::<Editor>())
 653            .is_some_and(|editor| {
 654                editor.update(cx, |editor, cx| editor.has_non_empty_selection(cx))
 655            });
 656        if has_selection {
 657            entries.push(ContextPickerEntry::Action(
 658                ContextPickerAction::AddSelections,
 659            ));
 660        }
 661
 662        if embedded_context {
 663            if self.prompt_store.is_some() {
 664                entries.push(ContextPickerEntry::Mode(ContextPickerMode::Rules));
 665            }
 666
 667            entries.push(ContextPickerEntry::Mode(ContextPickerMode::Fetch));
 668        }
 669
 670        entries
 671    }
 672}
 673
 674fn build_code_label_for_full_path(file_name: &str, directory: Option<&str>, cx: &App) -> CodeLabel {
 675    let comment_id = cx.theme().syntax().highlight_id("comment").map(HighlightId);
 676    let mut label = CodeLabel::default();
 677
 678    label.push_str(file_name, None);
 679    label.push_str(" ", None);
 680
 681    if let Some(directory) = directory {
 682        label.push_str(directory, comment_id);
 683    }
 684
 685    label.filter_range = 0..label.text().len();
 686
 687    label
 688}
 689
 690impl CompletionProvider for ContextPickerCompletionProvider {
 691    fn completions(
 692        &self,
 693        _excerpt_id: ExcerptId,
 694        buffer: &Entity<Buffer>,
 695        buffer_position: Anchor,
 696        _trigger: CompletionContext,
 697        _window: &mut Window,
 698        cx: &mut Context<Editor>,
 699    ) -> Task<Result<Vec<CompletionResponse>>> {
 700        let state = buffer.update(cx, |buffer, _cx| {
 701            let position = buffer_position.to_point(buffer);
 702            let line_start = Point::new(position.row, 0);
 703            let offset_to_line = buffer.point_to_offset(line_start);
 704            let mut lines = buffer.text_for_range(line_start..position).lines();
 705            let line = lines.next()?;
 706            ContextCompletion::try_parse(
 707                line,
 708                offset_to_line,
 709                self.prompt_capabilities.borrow().embedded_context,
 710            )
 711        });
 712        let Some(state) = state else {
 713            return Task::ready(Ok(Vec::new()));
 714        };
 715
 716        let Some(workspace) = self.workspace.upgrade() else {
 717            return Task::ready(Ok(Vec::new()));
 718        };
 719
 720        let project = workspace.read(cx).project().clone();
 721        let snapshot = buffer.read(cx).snapshot();
 722        let source_range = snapshot.anchor_before(state.source_range().start)
 723            ..snapshot.anchor_after(state.source_range().end);
 724
 725        let editor = self.message_editor.clone();
 726
 727        match state {
 728            ContextCompletion::SlashCommand(SlashCommandCompletion {
 729                command, argument, ..
 730            }) => {
 731                let search_task = self.search_slash_commands(command.unwrap_or_default(), cx);
 732                cx.background_spawn(async move {
 733                    let completions = search_task
 734                        .await
 735                        .into_iter()
 736                        .map(|command| {
 737                            let new_text = if let Some(argument) = argument.as_ref() {
 738                                format!("/{} {}", command.name, argument)
 739                            } else {
 740                                format!("/{} ", command.name)
 741                            };
 742
 743                            let is_missing_argument = argument.is_none() && command.input.is_some();
 744                            Completion {
 745                                replace_range: source_range.clone(),
 746                                new_text,
 747                                label: CodeLabel::plain(command.name.to_string(), None),
 748                                documentation: Some(CompletionDocumentation::MultiLinePlainText(
 749                                    command.description.into(),
 750                                )),
 751                                source: project::CompletionSource::Custom,
 752                                icon_path: None,
 753                                insert_text_mode: None,
 754                                confirm: Some(Arc::new({
 755                                    let editor = editor.clone();
 756                                    move |intent, _window, cx| {
 757                                        if !is_missing_argument {
 758                                            cx.defer({
 759                                                let editor = editor.clone();
 760                                                move |cx| {
 761                                                    editor
 762                                                        .update(cx, |_editor, cx| {
 763                                                            match intent {
 764                                                                CompletionIntent::Complete
 765                                                                | CompletionIntent::CompleteWithInsert
 766                                                                | CompletionIntent::CompleteWithReplace => {
 767                                                                    if !is_missing_argument {
 768                                                                        cx.emit(MessageEditorEvent::Send);
 769                                                                    }
 770                                                                }
 771                                                                CompletionIntent::Compose => {}
 772                                                            }
 773                                                        })
 774                                                        .ok();
 775                                                }
 776                                            });
 777                                        }
 778                                        is_missing_argument
 779                                    }
 780                                })),
 781                            }
 782                        })
 783                        .collect();
 784
 785                    Ok(vec![CompletionResponse {
 786                        completions,
 787                        display_options: CompletionDisplayOptions {
 788                            dynamic_width: true,
 789                        },
 790                        // Since this does its own filtering (see `filter_completions()` returns false),
 791                        // there is no benefit to computing whether this set of completions is incomplete.
 792                        is_incomplete: true,
 793                    }])
 794                })
 795            }
 796            ContextCompletion::Mention(MentionCompletion { mode, argument, .. }) => {
 797                let query = argument.unwrap_or_default();
 798                let search_task =
 799                    self.search_mentions(mode, query, Arc::<AtomicBool>::default(), cx);
 800
 801                cx.spawn(async move |_, cx| {
 802                    let matches = search_task.await;
 803
 804                    let completions = cx.update(|cx| {
 805                        matches
 806                            .into_iter()
 807                            .filter_map(|mat| match mat {
 808                                Match::File(FileMatch { mat, is_recent }) => {
 809                                    let project_path = ProjectPath {
 810                                        worktree_id: WorktreeId::from_usize(mat.worktree_id),
 811                                        path: mat.path.clone(),
 812                                    };
 813
 814                                    Self::completion_for_path(
 815                                        project_path,
 816                                        &mat.path_prefix,
 817                                        is_recent,
 818                                        mat.is_dir,
 819                                        source_range.clone(),
 820                                        editor.clone(),
 821                                        project.clone(),
 822                                        cx,
 823                                    )
 824                                }
 825
 826                                Match::Symbol(SymbolMatch { symbol, .. }) => {
 827                                    Self::completion_for_symbol(
 828                                        symbol,
 829                                        source_range.clone(),
 830                                        editor.clone(),
 831                                        workspace.clone(),
 832                                        cx,
 833                                    )
 834                                }
 835
 836                                Match::Thread(thread) => Some(Self::completion_for_thread(
 837                                    thread,
 838                                    source_range.clone(),
 839                                    false,
 840                                    editor.clone(),
 841                                    cx,
 842                                )),
 843
 844                                Match::RecentThread(thread) => Some(Self::completion_for_thread(
 845                                    thread,
 846                                    source_range.clone(),
 847                                    true,
 848                                    editor.clone(),
 849                                    cx,
 850                                )),
 851
 852                                Match::Rules(user_rules) => Some(Self::completion_for_rules(
 853                                    user_rules,
 854                                    source_range.clone(),
 855                                    editor.clone(),
 856                                    cx,
 857                                )),
 858
 859                                Match::Fetch(url) => Self::completion_for_fetch(
 860                                    source_range.clone(),
 861                                    url,
 862                                    editor.clone(),
 863                                    cx,
 864                                ),
 865
 866                                Match::Entry(EntryMatch { entry, .. }) => {
 867                                    Self::completion_for_entry(
 868                                        entry,
 869                                        source_range.clone(),
 870                                        editor.clone(),
 871                                        &workspace,
 872                                        cx,
 873                                    )
 874                                }
 875                            })
 876                            .collect()
 877                    })?;
 878
 879                    Ok(vec![CompletionResponse {
 880                        completions,
 881                        display_options: CompletionDisplayOptions {
 882                            dynamic_width: true,
 883                        },
 884                        // Since this does its own filtering (see `filter_completions()` returns false),
 885                        // there is no benefit to computing whether this set of completions is incomplete.
 886                        is_incomplete: true,
 887                    }])
 888                })
 889            }
 890        }
 891    }
 892
 893    fn is_completion_trigger(
 894        &self,
 895        buffer: &Entity<language::Buffer>,
 896        position: language::Anchor,
 897        _text: &str,
 898        _trigger_in_words: bool,
 899        _menu_is_open: bool,
 900        cx: &mut Context<Editor>,
 901    ) -> bool {
 902        let buffer = buffer.read(cx);
 903        let position = position.to_point(buffer);
 904        let line_start = Point::new(position.row, 0);
 905        let offset_to_line = buffer.point_to_offset(line_start);
 906        let mut lines = buffer.text_for_range(line_start..position).lines();
 907        if let Some(line) = lines.next() {
 908            ContextCompletion::try_parse(
 909                line,
 910                offset_to_line,
 911                self.prompt_capabilities.borrow().embedded_context,
 912            )
 913            .map(|completion| {
 914                completion.source_range().start <= offset_to_line + position.column as usize
 915                    && completion.source_range().end >= offset_to_line + position.column as usize
 916            })
 917            .unwrap_or(false)
 918        } else {
 919            false
 920        }
 921    }
 922
 923    fn sort_completions(&self) -> bool {
 924        false
 925    }
 926
 927    fn filter_completions(&self) -> bool {
 928        false
 929    }
 930}
 931
 932pub(crate) fn search_threads(
 933    query: String,
 934    cancellation_flag: Arc<AtomicBool>,
 935    history_store: &Entity<HistoryStore>,
 936    cx: &mut App,
 937) -> Task<Vec<HistoryEntry>> {
 938    let threads = history_store.read(cx).entries().collect();
 939    if query.is_empty() {
 940        return Task::ready(threads);
 941    }
 942
 943    let executor = cx.background_executor().clone();
 944    cx.background_spawn(async move {
 945        let candidates = threads
 946            .iter()
 947            .enumerate()
 948            .map(|(id, thread)| StringMatchCandidate::new(id, thread.title()))
 949            .collect::<Vec<_>>();
 950        let matches = fuzzy::match_strings(
 951            &candidates,
 952            &query,
 953            false,
 954            true,
 955            100,
 956            &cancellation_flag,
 957            executor,
 958        )
 959        .await;
 960
 961        matches
 962            .into_iter()
 963            .map(|mat| threads[mat.candidate_id].clone())
 964            .collect()
 965    })
 966}
 967
 968fn confirm_completion_callback(
 969    crease_text: SharedString,
 970    start: Anchor,
 971    content_len: usize,
 972    message_editor: WeakEntity<MessageEditor>,
 973    mention_uri: MentionUri,
 974) -> Arc<dyn Fn(CompletionIntent, &mut Window, &mut App) -> bool + Send + Sync> {
 975    Arc::new(move |_, window, cx| {
 976        let message_editor = message_editor.clone();
 977        let crease_text = crease_text.clone();
 978        let mention_uri = mention_uri.clone();
 979        window.defer(cx, move |window, cx| {
 980            message_editor
 981                .clone()
 982                .update(cx, |message_editor, cx| {
 983                    message_editor
 984                        .confirm_mention_completion(
 985                            crease_text,
 986                            start,
 987                            content_len,
 988                            mention_uri,
 989                            window,
 990                            cx,
 991                        )
 992                        .detach();
 993                })
 994                .ok();
 995        });
 996        false
 997    })
 998}
 999
1000enum ContextCompletion {
1001    SlashCommand(SlashCommandCompletion),
1002    Mention(MentionCompletion),
1003}
1004
1005impl ContextCompletion {
1006    fn source_range(&self) -> Range<usize> {
1007        match self {
1008            Self::SlashCommand(completion) => completion.source_range.clone(),
1009            Self::Mention(completion) => completion.source_range.clone(),
1010        }
1011    }
1012
1013    fn try_parse(line: &str, offset_to_line: usize, allow_non_file_mentions: bool) -> Option<Self> {
1014        if let Some(command) = SlashCommandCompletion::try_parse(line, offset_to_line) {
1015            Some(Self::SlashCommand(command))
1016        } else if let Some(mention) =
1017            MentionCompletion::try_parse(allow_non_file_mentions, line, offset_to_line)
1018        {
1019            Some(Self::Mention(mention))
1020        } else {
1021            None
1022        }
1023    }
1024}
1025
1026#[derive(Debug, Default, PartialEq)]
1027pub struct SlashCommandCompletion {
1028    pub source_range: Range<usize>,
1029    pub command: Option<String>,
1030    pub argument: Option<String>,
1031}
1032
1033impl SlashCommandCompletion {
1034    pub fn try_parse(line: &str, offset_to_line: usize) -> Option<Self> {
1035        // If we decide to support commands that are not at the beginning of the prompt, we can remove this check
1036        if !line.starts_with('/') || offset_to_line != 0 {
1037            return None;
1038        }
1039
1040        let (prefix, last_command) = line.rsplit_once('/')?;
1041        if prefix.chars().last().is_some_and(|c| !c.is_whitespace())
1042            || last_command.starts_with(char::is_whitespace)
1043        {
1044            return None;
1045        }
1046
1047        let mut argument = None;
1048        let mut command = None;
1049        if let Some((command_text, args)) = last_command.split_once(char::is_whitespace) {
1050            // If the args start with '@', treat this as a mention completion, not a slash command argument.
1051            // Early-return None to let MentionCompletion::try_parse handle it.
1052            if args.trim_start().starts_with('@') {
1053                return None;
1054            }
1055
1056            if !args.is_empty() {
1057                argument = Some(args.trim_end().to_string());
1058            }
1059            command = Some(command_text.to_string());
1060        } else if !last_command.is_empty() {
1061            command = Some(last_command.to_string());
1062        };
1063
1064        Some(Self {
1065            source_range: prefix.len() + offset_to_line
1066                ..line
1067                    .rfind(|c: char| !c.is_whitespace())
1068                    .unwrap_or_else(|| line.len())
1069                    + 1
1070                    + offset_to_line,
1071            command,
1072            argument,
1073        })
1074    }
1075}
1076
1077#[derive(Debug, Default, PartialEq)]
1078struct MentionCompletion {
1079    source_range: Range<usize>,
1080    mode: Option<ContextPickerMode>,
1081    argument: Option<String>,
1082}
1083
1084impl MentionCompletion {
1085    fn try_parse(allow_non_file_mentions: bool, line: &str, offset_to_line: usize) -> Option<Self> {
1086        let last_mention_start = line.rfind('@')?;
1087
1088        // No whitespace immediately after '@'
1089        if line[last_mention_start + 1..]
1090            .chars()
1091            .next()
1092            .is_some_and(|c| c.is_whitespace())
1093        {
1094            return None;
1095        }
1096
1097        //  Must be a word boundary before '@'
1098        if last_mention_start > 0
1099            && line[..last_mention_start]
1100                .chars()
1101                .last()
1102                .is_some_and(|c| !c.is_whitespace())
1103        {
1104            return None;
1105        }
1106
1107        let rest_of_line = &line[last_mention_start + 1..];
1108
1109        let mut mode = None;
1110        let mut argument = None;
1111
1112        let mut parts = rest_of_line.split_whitespace();
1113        let mut end = last_mention_start + 1;
1114
1115        if let Some(mode_text) = parts.next() {
1116            // Safe since we check no leading whitespace above
1117            end += mode_text.len();
1118
1119            if let Some(parsed_mode) = ContextPickerMode::try_from(mode_text).ok()
1120                && (allow_non_file_mentions || matches!(parsed_mode, ContextPickerMode::File))
1121            {
1122                mode = Some(parsed_mode);
1123            } else {
1124                argument = Some(mode_text.to_string());
1125            }
1126            match rest_of_line[mode_text.len()..].find(|c: char| !c.is_whitespace()) {
1127                Some(whitespace_count) => {
1128                    if let Some(argument_text) = parts.next() {
1129                        // If mode wasn't recognized but we have an argument, don't suggest completions
1130                        // (e.g. '@something word')
1131                        if mode.is_none() && !argument_text.is_empty() {
1132                            return None;
1133                        }
1134
1135                        argument = Some(argument_text.to_string());
1136                        end += whitespace_count + argument_text.len();
1137                    }
1138                }
1139                None => {
1140                    // Rest of line is entirely whitespace
1141                    end += rest_of_line.len() - mode_text.len();
1142                }
1143            }
1144        }
1145
1146        Some(Self {
1147            source_range: last_mention_start + offset_to_line..end + offset_to_line,
1148            mode,
1149            argument,
1150        })
1151    }
1152}
1153
1154#[cfg(test)]
1155mod tests {
1156    use super::*;
1157
1158    #[test]
1159    fn test_slash_command_completion_parse() {
1160        assert_eq!(
1161            SlashCommandCompletion::try_parse("/", 0),
1162            Some(SlashCommandCompletion {
1163                source_range: 0..1,
1164                command: None,
1165                argument: None,
1166            })
1167        );
1168
1169        assert_eq!(
1170            SlashCommandCompletion::try_parse("/help", 0),
1171            Some(SlashCommandCompletion {
1172                source_range: 0..5,
1173                command: Some("help".to_string()),
1174                argument: None,
1175            })
1176        );
1177
1178        assert_eq!(
1179            SlashCommandCompletion::try_parse("/help ", 0),
1180            Some(SlashCommandCompletion {
1181                source_range: 0..5,
1182                command: Some("help".to_string()),
1183                argument: None,
1184            })
1185        );
1186
1187        assert_eq!(
1188            SlashCommandCompletion::try_parse("/help arg1", 0),
1189            Some(SlashCommandCompletion {
1190                source_range: 0..10,
1191                command: Some("help".to_string()),
1192                argument: Some("arg1".to_string()),
1193            })
1194        );
1195
1196        assert_eq!(
1197            SlashCommandCompletion::try_parse("/help arg1 arg2", 0),
1198            Some(SlashCommandCompletion {
1199                source_range: 0..15,
1200                command: Some("help".to_string()),
1201                argument: Some("arg1 arg2".to_string()),
1202            })
1203        );
1204
1205        assert_eq!(
1206            SlashCommandCompletion::try_parse("/拿不到命令 拿不到命令 ", 0),
1207            Some(SlashCommandCompletion {
1208                source_range: 0..30,
1209                command: Some("拿不到命令".to_string()),
1210                argument: Some("拿不到命令".to_string()),
1211            })
1212        );
1213
1214        assert_eq!(SlashCommandCompletion::try_parse("Lorem Ipsum", 0), None);
1215
1216        assert_eq!(SlashCommandCompletion::try_parse("Lorem /", 0), None);
1217
1218        assert_eq!(SlashCommandCompletion::try_parse("Lorem /help", 0), None);
1219
1220        assert_eq!(SlashCommandCompletion::try_parse("Lorem/", 0), None);
1221
1222        assert_eq!(SlashCommandCompletion::try_parse("/ ", 0), None);
1223
1224        // Slash commands should not consume @ symbols that could be mention triggers
1225        assert_eq!(SlashCommandCompletion::try_parse("/init @", 0), None);
1226
1227        assert_eq!(SlashCommandCompletion::try_parse("/help @file", 0), None);
1228
1229        // @ with whitespace before it should also not be consumed
1230        assert_eq!(SlashCommandCompletion::try_parse("/command  @", 0), None);
1231    }
1232
1233    #[test]
1234    fn test_mention_completion_parse() {
1235        assert_eq!(MentionCompletion::try_parse(true, "Lorem Ipsum", 0), None);
1236
1237        assert_eq!(
1238            MentionCompletion::try_parse(true, "Lorem @", 0),
1239            Some(MentionCompletion {
1240                source_range: 6..7,
1241                mode: None,
1242                argument: None,
1243            })
1244        );
1245
1246        assert_eq!(
1247            MentionCompletion::try_parse(true, "Lorem @file", 0),
1248            Some(MentionCompletion {
1249                source_range: 6..11,
1250                mode: Some(ContextPickerMode::File),
1251                argument: None,
1252            })
1253        );
1254
1255        assert_eq!(
1256            MentionCompletion::try_parse(true, "Lorem @file ", 0),
1257            Some(MentionCompletion {
1258                source_range: 6..12,
1259                mode: Some(ContextPickerMode::File),
1260                argument: None,
1261            })
1262        );
1263
1264        assert_eq!(
1265            MentionCompletion::try_parse(true, "Lorem @file main.rs", 0),
1266            Some(MentionCompletion {
1267                source_range: 6..19,
1268                mode: Some(ContextPickerMode::File),
1269                argument: Some("main.rs".to_string()),
1270            })
1271        );
1272
1273        assert_eq!(
1274            MentionCompletion::try_parse(true, "Lorem @file main.rs ", 0),
1275            Some(MentionCompletion {
1276                source_range: 6..19,
1277                mode: Some(ContextPickerMode::File),
1278                argument: Some("main.rs".to_string()),
1279            })
1280        );
1281
1282        assert_eq!(
1283            MentionCompletion::try_parse(true, "Lorem @file main.rs Ipsum", 0),
1284            Some(MentionCompletion {
1285                source_range: 6..19,
1286                mode: Some(ContextPickerMode::File),
1287                argument: Some("main.rs".to_string()),
1288            })
1289        );
1290
1291        assert_eq!(
1292            MentionCompletion::try_parse(true, "Lorem @main", 0),
1293            Some(MentionCompletion {
1294                source_range: 6..11,
1295                mode: None,
1296                argument: Some("main".to_string()),
1297            })
1298        );
1299
1300        assert_eq!(
1301            MentionCompletion::try_parse(true, "Lorem @main ", 0),
1302            Some(MentionCompletion {
1303                source_range: 6..12,
1304                mode: None,
1305                argument: Some("main".to_string()),
1306            })
1307        );
1308
1309        assert_eq!(MentionCompletion::try_parse(true, "Lorem @main m", 0), None);
1310
1311        assert_eq!(MentionCompletion::try_parse(true, "test@", 0), None);
1312
1313        // Allowed non-file mentions
1314
1315        assert_eq!(
1316            MentionCompletion::try_parse(true, "Lorem @symbol main", 0),
1317            Some(MentionCompletion {
1318                source_range: 6..18,
1319                mode: Some(ContextPickerMode::Symbol),
1320                argument: Some("main".to_string()),
1321            })
1322        );
1323
1324        // Disallowed non-file mentions
1325        assert_eq!(
1326            MentionCompletion::try_parse(false, "Lorem @symbol main", 0),
1327            None
1328        );
1329
1330        assert_eq!(
1331            MentionCompletion::try_parse(true, "Lorem@symbol", 0),
1332            None,
1333            "Should not parse mention inside word"
1334        );
1335
1336        assert_eq!(
1337            MentionCompletion::try_parse(true, "Lorem @ file", 0),
1338            None,
1339            "Should not parse with a space after @"
1340        );
1341
1342        assert_eq!(
1343            MentionCompletion::try_parse(true, "@ file", 0),
1344            None,
1345            "Should not parse with a space after @ at the start of the line"
1346        );
1347    }
1348}