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, CodeLabelBuilder, 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;
  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 = CodeLabelBuilder::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.build()
 686}
 687
 688impl CompletionProvider for ContextPickerCompletionProvider {
 689    fn completions(
 690        &self,
 691        _excerpt_id: ExcerptId,
 692        buffer: &Entity<Buffer>,
 693        buffer_position: Anchor,
 694        _trigger: CompletionContext,
 695        _snippets_only: bool,
 696        _window: &mut Window,
 697        cx: &mut Context<Editor>,
 698    ) -> Task<Result<Vec<CompletionResponse>>> {
 699        let state = buffer.update(cx, |buffer, _cx| {
 700            let position = buffer_position.to_point(buffer);
 701            let line_start = Point::new(position.row, 0);
 702            let offset_to_line = buffer.point_to_offset(line_start);
 703            let mut lines = buffer.text_for_range(line_start..position).lines();
 704            let line = lines.next()?;
 705            ContextCompletion::try_parse(
 706                line,
 707                offset_to_line,
 708                self.prompt_capabilities.borrow().embedded_context,
 709            )
 710        });
 711        let Some(state) = state else {
 712            return Task::ready(Ok(Vec::new()));
 713        };
 714
 715        let Some(workspace) = self.workspace.upgrade() else {
 716            return Task::ready(Ok(Vec::new()));
 717        };
 718
 719        let project = workspace.read(cx).project().clone();
 720        let snapshot = buffer.read(cx).snapshot();
 721        let source_range = snapshot.anchor_before(state.source_range().start)
 722            ..snapshot.anchor_after(state.source_range().end);
 723
 724        let editor = self.message_editor.clone();
 725
 726        match state {
 727            ContextCompletion::SlashCommand(SlashCommandCompletion {
 728                command, argument, ..
 729            }) => {
 730                let search_task = self.search_slash_commands(command.unwrap_or_default(), cx);
 731                cx.background_spawn(async move {
 732                    let completions = search_task
 733                        .await
 734                        .into_iter()
 735                        .map(|command| {
 736                            let new_text = if let Some(argument) = argument.as_ref() {
 737                                format!("/{} {}", command.name, argument)
 738                            } else {
 739                                format!("/{} ", command.name)
 740                            };
 741
 742                            let is_missing_argument = argument.is_none() && command.input.is_some();
 743                            Completion {
 744                                replace_range: source_range.clone(),
 745                                new_text,
 746                                label: CodeLabel::plain(command.name.to_string(), None),
 747                                documentation: Some(CompletionDocumentation::MultiLinePlainText(
 748                                    command.description.into(),
 749                                )),
 750                                source: project::CompletionSource::Custom,
 751                                icon_path: None,
 752                                insert_text_mode: None,
 753                                confirm: Some(Arc::new({
 754                                    let editor = editor.clone();
 755                                    move |intent, _window, cx| {
 756                                        if !is_missing_argument {
 757                                            cx.defer({
 758                                                let editor = editor.clone();
 759                                                move |cx| {
 760                                                    editor
 761                                                        .update(cx, |editor, cx| {
 762                                                            match intent {
 763                                                                CompletionIntent::Complete
 764                                                                | CompletionIntent::CompleteWithInsert
 765                                                                | CompletionIntent::CompleteWithReplace => {
 766                                                                    if !is_missing_argument {
 767                                                                        editor.send(cx);
 768                                                                    }
 769                                                                }
 770                                                                CompletionIntent::Compose => {}
 771                                                            }
 772                                                        })
 773                                                        .ok();
 774                                                }
 775                                            });
 776                                        }
 777                                        false
 778                                    }
 779                                })),
 780                            }
 781                        })
 782                        .collect();
 783
 784                    Ok(vec![CompletionResponse {
 785                        completions,
 786                        display_options: CompletionDisplayOptions {
 787                            dynamic_width: true,
 788                        },
 789                        // Since this does its own filtering (see `filter_completions()` returns false),
 790                        // there is no benefit to computing whether this set of completions is incomplete.
 791                        is_incomplete: true,
 792                    }])
 793                })
 794            }
 795            ContextCompletion::Mention(MentionCompletion { mode, argument, .. }) => {
 796                let query = argument.unwrap_or_default();
 797                let search_task =
 798                    self.search_mentions(mode, query, Arc::<AtomicBool>::default(), cx);
 799
 800                cx.spawn(async move |_, cx| {
 801                    let matches = search_task.await;
 802
 803                    let completions = cx.update(|cx| {
 804                        matches
 805                            .into_iter()
 806                            .filter_map(|mat| match mat {
 807                                Match::File(FileMatch { mat, is_recent }) => {
 808                                    let project_path = ProjectPath {
 809                                        worktree_id: WorktreeId::from_usize(mat.worktree_id),
 810                                        path: mat.path.clone(),
 811                                    };
 812
 813                                    Self::completion_for_path(
 814                                        project_path,
 815                                        &mat.path_prefix,
 816                                        is_recent,
 817                                        mat.is_dir,
 818                                        source_range.clone(),
 819                                        editor.clone(),
 820                                        project.clone(),
 821                                        cx,
 822                                    )
 823                                }
 824
 825                                Match::Symbol(SymbolMatch { symbol, .. }) => {
 826                                    Self::completion_for_symbol(
 827                                        symbol,
 828                                        source_range.clone(),
 829                                        editor.clone(),
 830                                        workspace.clone(),
 831                                        cx,
 832                                    )
 833                                }
 834
 835                                Match::Thread(thread) => Some(Self::completion_for_thread(
 836                                    thread,
 837                                    source_range.clone(),
 838                                    false,
 839                                    editor.clone(),
 840                                    cx,
 841                                )),
 842
 843                                Match::RecentThread(thread) => Some(Self::completion_for_thread(
 844                                    thread,
 845                                    source_range.clone(),
 846                                    true,
 847                                    editor.clone(),
 848                                    cx,
 849                                )),
 850
 851                                Match::Rules(user_rules) => Some(Self::completion_for_rules(
 852                                    user_rules,
 853                                    source_range.clone(),
 854                                    editor.clone(),
 855                                    cx,
 856                                )),
 857
 858                                Match::Fetch(url) => Self::completion_for_fetch(
 859                                    source_range.clone(),
 860                                    url,
 861                                    editor.clone(),
 862                                    cx,
 863                                ),
 864
 865                                Match::Entry(EntryMatch { entry, .. }) => {
 866                                    Self::completion_for_entry(
 867                                        entry,
 868                                        source_range.clone(),
 869                                        editor.clone(),
 870                                        &workspace,
 871                                        cx,
 872                                    )
 873                                }
 874                            })
 875                            .collect()
 876                    })?;
 877
 878                    Ok(vec![CompletionResponse {
 879                        completions,
 880                        display_options: CompletionDisplayOptions {
 881                            dynamic_width: true,
 882                        },
 883                        // Since this does its own filtering (see `filter_completions()` returns false),
 884                        // there is no benefit to computing whether this set of completions is incomplete.
 885                        is_incomplete: true,
 886                    }])
 887                })
 888            }
 889        }
 890    }
 891
 892    fn is_completion_trigger(
 893        &self,
 894        buffer: &Entity<language::Buffer>,
 895        position: language::Anchor,
 896        _text: &str,
 897        _trigger_in_words: bool,
 898        _menu_is_open: bool,
 899        cx: &mut Context<Editor>,
 900    ) -> bool {
 901        let buffer = buffer.read(cx);
 902        let position = position.to_point(buffer);
 903        let line_start = Point::new(position.row, 0);
 904        let offset_to_line = buffer.point_to_offset(line_start);
 905        let mut lines = buffer.text_for_range(line_start..position).lines();
 906        if let Some(line) = lines.next() {
 907            ContextCompletion::try_parse(
 908                line,
 909                offset_to_line,
 910                self.prompt_capabilities.borrow().embedded_context,
 911            )
 912            .filter(|completion| {
 913                // Right now we don't support completing arguments of slash commands
 914                let is_slash_command_with_argument = matches!(
 915                    completion,
 916                    ContextCompletion::SlashCommand(SlashCommandCompletion {
 917                        argument: Some(_),
 918                        ..
 919                    })
 920                );
 921                !is_slash_command_with_argument
 922            })
 923            .map(|completion| {
 924                completion.source_range().start <= offset_to_line + position.column as usize
 925                    && completion.source_range().end >= offset_to_line + position.column as usize
 926            })
 927            .unwrap_or(false)
 928        } else {
 929            false
 930        }
 931    }
 932
 933    fn sort_completions(&self) -> bool {
 934        false
 935    }
 936
 937    fn filter_completions(&self) -> bool {
 938        false
 939    }
 940}
 941
 942pub(crate) fn search_threads(
 943    query: String,
 944    cancellation_flag: Arc<AtomicBool>,
 945    history_store: &Entity<HistoryStore>,
 946    cx: &mut App,
 947) -> Task<Vec<HistoryEntry>> {
 948    let threads = history_store.read(cx).entries().collect();
 949    if query.is_empty() {
 950        return Task::ready(threads);
 951    }
 952
 953    let executor = cx.background_executor().clone();
 954    cx.background_spawn(async move {
 955        let candidates = threads
 956            .iter()
 957            .enumerate()
 958            .map(|(id, thread)| StringMatchCandidate::new(id, thread.title()))
 959            .collect::<Vec<_>>();
 960        let matches = fuzzy::match_strings(
 961            &candidates,
 962            &query,
 963            false,
 964            true,
 965            100,
 966            &cancellation_flag,
 967            executor,
 968        )
 969        .await;
 970
 971        matches
 972            .into_iter()
 973            .map(|mat| threads[mat.candidate_id].clone())
 974            .collect()
 975    })
 976}
 977
 978fn confirm_completion_callback(
 979    crease_text: SharedString,
 980    start: Anchor,
 981    content_len: usize,
 982    message_editor: WeakEntity<MessageEditor>,
 983    mention_uri: MentionUri,
 984) -> Arc<dyn Fn(CompletionIntent, &mut Window, &mut App) -> bool + Send + Sync> {
 985    Arc::new(move |_, window, cx| {
 986        let message_editor = message_editor.clone();
 987        let crease_text = crease_text.clone();
 988        let mention_uri = mention_uri.clone();
 989        window.defer(cx, move |window, cx| {
 990            message_editor
 991                .clone()
 992                .update(cx, |message_editor, cx| {
 993                    message_editor
 994                        .confirm_mention_completion(
 995                            crease_text,
 996                            start,
 997                            content_len,
 998                            mention_uri,
 999                            window,
1000                            cx,
1001                        )
1002                        .detach();
1003                })
1004                .ok();
1005        });
1006        false
1007    })
1008}
1009
1010enum ContextCompletion {
1011    SlashCommand(SlashCommandCompletion),
1012    Mention(MentionCompletion),
1013}
1014
1015impl ContextCompletion {
1016    fn source_range(&self) -> Range<usize> {
1017        match self {
1018            Self::SlashCommand(completion) => completion.source_range.clone(),
1019            Self::Mention(completion) => completion.source_range.clone(),
1020        }
1021    }
1022
1023    fn try_parse(line: &str, offset_to_line: usize, allow_non_file_mentions: bool) -> Option<Self> {
1024        if let Some(command) = SlashCommandCompletion::try_parse(line, offset_to_line) {
1025            Some(Self::SlashCommand(command))
1026        } else if let Some(mention) =
1027            MentionCompletion::try_parse(allow_non_file_mentions, line, offset_to_line)
1028        {
1029            Some(Self::Mention(mention))
1030        } else {
1031            None
1032        }
1033    }
1034}
1035
1036#[derive(Debug, Default, PartialEq)]
1037pub struct SlashCommandCompletion {
1038    pub source_range: Range<usize>,
1039    pub command: Option<String>,
1040    pub argument: Option<String>,
1041}
1042
1043impl SlashCommandCompletion {
1044    pub fn try_parse(line: &str, offset_to_line: usize) -> Option<Self> {
1045        // If we decide to support commands that are not at the beginning of the prompt, we can remove this check
1046        if !line.starts_with('/') || offset_to_line != 0 {
1047            return None;
1048        }
1049
1050        let (prefix, last_command) = line.rsplit_once('/')?;
1051        if prefix.chars().last().is_some_and(|c| !c.is_whitespace())
1052            || last_command.starts_with(char::is_whitespace)
1053        {
1054            return None;
1055        }
1056
1057        let mut argument = None;
1058        let mut command = None;
1059        if let Some((command_text, args)) = last_command.split_once(char::is_whitespace) {
1060            if !args.is_empty() {
1061                argument = Some(args.trim_end().to_string());
1062            }
1063            command = Some(command_text.to_string());
1064        } else if !last_command.is_empty() {
1065            command = Some(last_command.to_string());
1066        };
1067
1068        Some(Self {
1069            source_range: prefix.len() + offset_to_line
1070                ..line
1071                    .rfind(|c: char| !c.is_whitespace())
1072                    .unwrap_or_else(|| line.len())
1073                    + 1
1074                    + offset_to_line,
1075            command,
1076            argument,
1077        })
1078    }
1079}
1080
1081#[derive(Debug, Default, PartialEq)]
1082struct MentionCompletion {
1083    source_range: Range<usize>,
1084    mode: Option<ContextPickerMode>,
1085    argument: Option<String>,
1086}
1087
1088impl MentionCompletion {
1089    fn try_parse(allow_non_file_mentions: bool, line: &str, offset_to_line: usize) -> Option<Self> {
1090        let last_mention_start = line.rfind('@')?;
1091
1092        // No whitespace immediately after '@'
1093        if line[last_mention_start + 1..]
1094            .chars()
1095            .next()
1096            .is_some_and(|c| c.is_whitespace())
1097        {
1098            return None;
1099        }
1100
1101        //  Must be a word boundary before '@'
1102        if last_mention_start > 0
1103            && line[..last_mention_start]
1104                .chars()
1105                .last()
1106                .is_some_and(|c| !c.is_whitespace())
1107        {
1108            return None;
1109        }
1110
1111        let rest_of_line = &line[last_mention_start + 1..];
1112
1113        let mut mode = None;
1114        let mut argument = None;
1115
1116        let mut parts = rest_of_line.split_whitespace();
1117        let mut end = last_mention_start + 1;
1118
1119        if let Some(mode_text) = parts.next() {
1120            // Safe since we check no leading whitespace above
1121            end += mode_text.len();
1122
1123            if let Some(parsed_mode) = ContextPickerMode::try_from(mode_text).ok()
1124                && (allow_non_file_mentions || matches!(parsed_mode, ContextPickerMode::File))
1125            {
1126                mode = Some(parsed_mode);
1127            } else {
1128                argument = Some(mode_text.to_string());
1129            }
1130            match rest_of_line[mode_text.len()..].find(|c: char| !c.is_whitespace()) {
1131                Some(whitespace_count) => {
1132                    if let Some(argument_text) = parts.next() {
1133                        // If mode wasn't recognized but we have an argument, don't suggest completions
1134                        // (e.g. '@something word')
1135                        if mode.is_none() && !argument_text.is_empty() {
1136                            return None;
1137                        }
1138
1139                        argument = Some(argument_text.to_string());
1140                        end += whitespace_count + argument_text.len();
1141                    }
1142                }
1143                None => {
1144                    // Rest of line is entirely whitespace
1145                    end += rest_of_line.len() - mode_text.len();
1146                }
1147            }
1148        }
1149
1150        Some(Self {
1151            source_range: last_mention_start + offset_to_line..end + offset_to_line,
1152            mode,
1153            argument,
1154        })
1155    }
1156}
1157
1158#[cfg(test)]
1159mod tests {
1160    use super::*;
1161
1162    #[test]
1163    fn test_slash_command_completion_parse() {
1164        assert_eq!(
1165            SlashCommandCompletion::try_parse("/", 0),
1166            Some(SlashCommandCompletion {
1167                source_range: 0..1,
1168                command: None,
1169                argument: None,
1170            })
1171        );
1172
1173        assert_eq!(
1174            SlashCommandCompletion::try_parse("/help", 0),
1175            Some(SlashCommandCompletion {
1176                source_range: 0..5,
1177                command: Some("help".to_string()),
1178                argument: None,
1179            })
1180        );
1181
1182        assert_eq!(
1183            SlashCommandCompletion::try_parse("/help ", 0),
1184            Some(SlashCommandCompletion {
1185                source_range: 0..5,
1186                command: Some("help".to_string()),
1187                argument: None,
1188            })
1189        );
1190
1191        assert_eq!(
1192            SlashCommandCompletion::try_parse("/help arg1", 0),
1193            Some(SlashCommandCompletion {
1194                source_range: 0..10,
1195                command: Some("help".to_string()),
1196                argument: Some("arg1".to_string()),
1197            })
1198        );
1199
1200        assert_eq!(
1201            SlashCommandCompletion::try_parse("/help arg1 arg2", 0),
1202            Some(SlashCommandCompletion {
1203                source_range: 0..15,
1204                command: Some("help".to_string()),
1205                argument: Some("arg1 arg2".to_string()),
1206            })
1207        );
1208
1209        assert_eq!(
1210            SlashCommandCompletion::try_parse("/拿不到命令 拿不到命令 ", 0),
1211            Some(SlashCommandCompletion {
1212                source_range: 0..30,
1213                command: Some("拿不到命令".to_string()),
1214                argument: Some("拿不到命令".to_string()),
1215            })
1216        );
1217
1218        assert_eq!(SlashCommandCompletion::try_parse("Lorem Ipsum", 0), None);
1219
1220        assert_eq!(SlashCommandCompletion::try_parse("Lorem /", 0), None);
1221
1222        assert_eq!(SlashCommandCompletion::try_parse("Lorem /help", 0), None);
1223
1224        assert_eq!(SlashCommandCompletion::try_parse("Lorem/", 0), None);
1225
1226        assert_eq!(SlashCommandCompletion::try_parse("/ ", 0), None);
1227    }
1228
1229    #[test]
1230    fn test_mention_completion_parse() {
1231        assert_eq!(MentionCompletion::try_parse(true, "Lorem Ipsum", 0), None);
1232
1233        assert_eq!(
1234            MentionCompletion::try_parse(true, "Lorem @", 0),
1235            Some(MentionCompletion {
1236                source_range: 6..7,
1237                mode: None,
1238                argument: None,
1239            })
1240        );
1241
1242        assert_eq!(
1243            MentionCompletion::try_parse(true, "Lorem @file", 0),
1244            Some(MentionCompletion {
1245                source_range: 6..11,
1246                mode: Some(ContextPickerMode::File),
1247                argument: None,
1248            })
1249        );
1250
1251        assert_eq!(
1252            MentionCompletion::try_parse(true, "Lorem @file ", 0),
1253            Some(MentionCompletion {
1254                source_range: 6..12,
1255                mode: Some(ContextPickerMode::File),
1256                argument: None,
1257            })
1258        );
1259
1260        assert_eq!(
1261            MentionCompletion::try_parse(true, "Lorem @file main.rs", 0),
1262            Some(MentionCompletion {
1263                source_range: 6..19,
1264                mode: Some(ContextPickerMode::File),
1265                argument: Some("main.rs".to_string()),
1266            })
1267        );
1268
1269        assert_eq!(
1270            MentionCompletion::try_parse(true, "Lorem @file main.rs ", 0),
1271            Some(MentionCompletion {
1272                source_range: 6..19,
1273                mode: Some(ContextPickerMode::File),
1274                argument: Some("main.rs".to_string()),
1275            })
1276        );
1277
1278        assert_eq!(
1279            MentionCompletion::try_parse(true, "Lorem @file main.rs Ipsum", 0),
1280            Some(MentionCompletion {
1281                source_range: 6..19,
1282                mode: Some(ContextPickerMode::File),
1283                argument: Some("main.rs".to_string()),
1284            })
1285        );
1286
1287        assert_eq!(
1288            MentionCompletion::try_parse(true, "Lorem @main", 0),
1289            Some(MentionCompletion {
1290                source_range: 6..11,
1291                mode: None,
1292                argument: Some("main".to_string()),
1293            })
1294        );
1295
1296        assert_eq!(
1297            MentionCompletion::try_parse(true, "Lorem @main ", 0),
1298            Some(MentionCompletion {
1299                source_range: 6..12,
1300                mode: None,
1301                argument: Some("main".to_string()),
1302            })
1303        );
1304
1305        assert_eq!(MentionCompletion::try_parse(true, "Lorem @main m", 0), None);
1306
1307        assert_eq!(MentionCompletion::try_parse(true, "test@", 0), None);
1308
1309        // Allowed non-file mentions
1310
1311        assert_eq!(
1312            MentionCompletion::try_parse(true, "Lorem @symbol main", 0),
1313            Some(MentionCompletion {
1314                source_range: 6..18,
1315                mode: Some(ContextPickerMode::Symbol),
1316                argument: Some("main".to_string()),
1317            })
1318        );
1319
1320        // Disallowed non-file mentions
1321        assert_eq!(
1322            MentionCompletion::try_parse(false, "Lorem @symbol main", 0),
1323            None
1324        );
1325
1326        assert_eq!(
1327            MentionCompletion::try_parse(true, "Lorem@symbol", 0),
1328            None,
1329            "Should not parse mention inside word"
1330        );
1331
1332        assert_eq!(
1333            MentionCompletion::try_parse(true, "Lorem @ file", 0),
1334            None,
1335            "Should not parse with a space after @"
1336        );
1337
1338        assert_eq!(
1339            MentionCompletion::try_parse(true, "@ file", 0),
1340            None,
1341            "Should not parse with a space after @ at the start of the line"
1342        );
1343    }
1344}