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;
  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                                                                        editor.send(cx);
 769                                                                    }
 770                                                                }
 771                                                                CompletionIntent::Compose => {}
 772                                                            }
 773                                                        })
 774                                                        .ok();
 775                                                }
 776                                            });
 777                                        }
 778                                        false
 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            .filter(|completion| {
 914                // Right now we don't support completing arguments of slash commands
 915                let is_slash_command_with_argument = matches!(
 916                    completion,
 917                    ContextCompletion::SlashCommand(SlashCommandCompletion {
 918                        argument: Some(_),
 919                        ..
 920                    })
 921                );
 922                !is_slash_command_with_argument
 923            })
 924            .map(|completion| {
 925                completion.source_range().start <= offset_to_line + position.column as usize
 926                    && completion.source_range().end >= offset_to_line + position.column as usize
 927            })
 928            .unwrap_or(false)
 929        } else {
 930            false
 931        }
 932    }
 933
 934    fn sort_completions(&self) -> bool {
 935        false
 936    }
 937
 938    fn filter_completions(&self) -> bool {
 939        false
 940    }
 941}
 942
 943pub(crate) fn search_threads(
 944    query: String,
 945    cancellation_flag: Arc<AtomicBool>,
 946    history_store: &Entity<HistoryStore>,
 947    cx: &mut App,
 948) -> Task<Vec<HistoryEntry>> {
 949    let threads = history_store.read(cx).entries().collect();
 950    if query.is_empty() {
 951        return Task::ready(threads);
 952    }
 953
 954    let executor = cx.background_executor().clone();
 955    cx.background_spawn(async move {
 956        let candidates = threads
 957            .iter()
 958            .enumerate()
 959            .map(|(id, thread)| StringMatchCandidate::new(id, thread.title()))
 960            .collect::<Vec<_>>();
 961        let matches = fuzzy::match_strings(
 962            &candidates,
 963            &query,
 964            false,
 965            true,
 966            100,
 967            &cancellation_flag,
 968            executor,
 969        )
 970        .await;
 971
 972        matches
 973            .into_iter()
 974            .map(|mat| threads[mat.candidate_id].clone())
 975            .collect()
 976    })
 977}
 978
 979fn confirm_completion_callback(
 980    crease_text: SharedString,
 981    start: Anchor,
 982    content_len: usize,
 983    message_editor: WeakEntity<MessageEditor>,
 984    mention_uri: MentionUri,
 985) -> Arc<dyn Fn(CompletionIntent, &mut Window, &mut App) -> bool + Send + Sync> {
 986    Arc::new(move |_, window, cx| {
 987        let message_editor = message_editor.clone();
 988        let crease_text = crease_text.clone();
 989        let mention_uri = mention_uri.clone();
 990        window.defer(cx, move |window, cx| {
 991            message_editor
 992                .clone()
 993                .update(cx, |message_editor, cx| {
 994                    message_editor
 995                        .confirm_mention_completion(
 996                            crease_text,
 997                            start,
 998                            content_len,
 999                            mention_uri,
1000                            window,
1001                            cx,
1002                        )
1003                        .detach();
1004                })
1005                .ok();
1006        });
1007        false
1008    })
1009}
1010
1011enum ContextCompletion {
1012    SlashCommand(SlashCommandCompletion),
1013    Mention(MentionCompletion),
1014}
1015
1016impl ContextCompletion {
1017    fn source_range(&self) -> Range<usize> {
1018        match self {
1019            Self::SlashCommand(completion) => completion.source_range.clone(),
1020            Self::Mention(completion) => completion.source_range.clone(),
1021        }
1022    }
1023
1024    fn try_parse(line: &str, offset_to_line: usize, allow_non_file_mentions: bool) -> Option<Self> {
1025        if let Some(command) = SlashCommandCompletion::try_parse(line, offset_to_line) {
1026            Some(Self::SlashCommand(command))
1027        } else if let Some(mention) =
1028            MentionCompletion::try_parse(allow_non_file_mentions, line, offset_to_line)
1029        {
1030            Some(Self::Mention(mention))
1031        } else {
1032            None
1033        }
1034    }
1035}
1036
1037#[derive(Debug, Default, PartialEq)]
1038pub struct SlashCommandCompletion {
1039    pub source_range: Range<usize>,
1040    pub command: Option<String>,
1041    pub argument: Option<String>,
1042}
1043
1044impl SlashCommandCompletion {
1045    pub fn try_parse(line: &str, offset_to_line: usize) -> Option<Self> {
1046        // If we decide to support commands that are not at the beginning of the prompt, we can remove this check
1047        if !line.starts_with('/') || offset_to_line != 0 {
1048            return None;
1049        }
1050
1051        let (prefix, last_command) = line.rsplit_once('/')?;
1052        if prefix.chars().last().is_some_and(|c| !c.is_whitespace())
1053            || last_command.starts_with(char::is_whitespace)
1054        {
1055            return None;
1056        }
1057
1058        let mut argument = None;
1059        let mut command = None;
1060        if let Some((command_text, args)) = last_command.split_once(char::is_whitespace) {
1061            if !args.is_empty() {
1062                argument = Some(args.trim_end().to_string());
1063            }
1064            command = Some(command_text.to_string());
1065        } else if !last_command.is_empty() {
1066            command = Some(last_command.to_string());
1067        };
1068
1069        Some(Self {
1070            source_range: prefix.len() + offset_to_line
1071                ..line
1072                    .rfind(|c: char| !c.is_whitespace())
1073                    .unwrap_or_else(|| line.len())
1074                    + 1
1075                    + offset_to_line,
1076            command,
1077            argument,
1078        })
1079    }
1080}
1081
1082#[derive(Debug, Default, PartialEq)]
1083struct MentionCompletion {
1084    source_range: Range<usize>,
1085    mode: Option<ContextPickerMode>,
1086    argument: Option<String>,
1087}
1088
1089impl MentionCompletion {
1090    fn try_parse(allow_non_file_mentions: bool, line: &str, offset_to_line: usize) -> Option<Self> {
1091        let last_mention_start = line.rfind('@')?;
1092
1093        // No whitespace immediately after '@'
1094        if line[last_mention_start + 1..]
1095            .chars()
1096            .next()
1097            .is_some_and(|c| c.is_whitespace())
1098        {
1099            return None;
1100        }
1101
1102        //  Must be a word boundary before '@'
1103        if last_mention_start > 0
1104            && line[..last_mention_start]
1105                .chars()
1106                .last()
1107                .is_some_and(|c| !c.is_whitespace())
1108        {
1109            return None;
1110        }
1111
1112        let rest_of_line = &line[last_mention_start + 1..];
1113
1114        let mut mode = None;
1115        let mut argument = None;
1116
1117        let mut parts = rest_of_line.split_whitespace();
1118        let mut end = last_mention_start + 1;
1119
1120        if let Some(mode_text) = parts.next() {
1121            // Safe since we check no leading whitespace above
1122            end += mode_text.len();
1123
1124            if let Some(parsed_mode) = ContextPickerMode::try_from(mode_text).ok()
1125                && (allow_non_file_mentions || matches!(parsed_mode, ContextPickerMode::File))
1126            {
1127                mode = Some(parsed_mode);
1128            } else {
1129                argument = Some(mode_text.to_string());
1130            }
1131            match rest_of_line[mode_text.len()..].find(|c: char| !c.is_whitespace()) {
1132                Some(whitespace_count) => {
1133                    if let Some(argument_text) = parts.next() {
1134                        // If mode wasn't recognized but we have an argument, don't suggest completions
1135                        // (e.g. '@something word')
1136                        if mode.is_none() && !argument_text.is_empty() {
1137                            return None;
1138                        }
1139
1140                        argument = Some(argument_text.to_string());
1141                        end += whitespace_count + argument_text.len();
1142                    }
1143                }
1144                None => {
1145                    // Rest of line is entirely whitespace
1146                    end += rest_of_line.len() - mode_text.len();
1147                }
1148            }
1149        }
1150
1151        Some(Self {
1152            source_range: last_mention_start + offset_to_line..end + offset_to_line,
1153            mode,
1154            argument,
1155        })
1156    }
1157}
1158
1159#[cfg(test)]
1160mod tests {
1161    use super::*;
1162
1163    #[test]
1164    fn test_slash_command_completion_parse() {
1165        assert_eq!(
1166            SlashCommandCompletion::try_parse("/", 0),
1167            Some(SlashCommandCompletion {
1168                source_range: 0..1,
1169                command: None,
1170                argument: None,
1171            })
1172        );
1173
1174        assert_eq!(
1175            SlashCommandCompletion::try_parse("/help", 0),
1176            Some(SlashCommandCompletion {
1177                source_range: 0..5,
1178                command: Some("help".to_string()),
1179                argument: None,
1180            })
1181        );
1182
1183        assert_eq!(
1184            SlashCommandCompletion::try_parse("/help ", 0),
1185            Some(SlashCommandCompletion {
1186                source_range: 0..5,
1187                command: Some("help".to_string()),
1188                argument: None,
1189            })
1190        );
1191
1192        assert_eq!(
1193            SlashCommandCompletion::try_parse("/help arg1", 0),
1194            Some(SlashCommandCompletion {
1195                source_range: 0..10,
1196                command: Some("help".to_string()),
1197                argument: Some("arg1".to_string()),
1198            })
1199        );
1200
1201        assert_eq!(
1202            SlashCommandCompletion::try_parse("/help arg1 arg2", 0),
1203            Some(SlashCommandCompletion {
1204                source_range: 0..15,
1205                command: Some("help".to_string()),
1206                argument: Some("arg1 arg2".to_string()),
1207            })
1208        );
1209
1210        assert_eq!(
1211            SlashCommandCompletion::try_parse("/拿不到命令 拿不到命令 ", 0),
1212            Some(SlashCommandCompletion {
1213                source_range: 0..30,
1214                command: Some("拿不到命令".to_string()),
1215                argument: Some("拿不到命令".to_string()),
1216            })
1217        );
1218
1219        assert_eq!(SlashCommandCompletion::try_parse("Lorem Ipsum", 0), None);
1220
1221        assert_eq!(SlashCommandCompletion::try_parse("Lorem /", 0), None);
1222
1223        assert_eq!(SlashCommandCompletion::try_parse("Lorem /help", 0), None);
1224
1225        assert_eq!(SlashCommandCompletion::try_parse("Lorem/", 0), None);
1226
1227        assert_eq!(SlashCommandCompletion::try_parse("/ ", 0), None);
1228    }
1229
1230    #[test]
1231    fn test_mention_completion_parse() {
1232        assert_eq!(MentionCompletion::try_parse(true, "Lorem Ipsum", 0), None);
1233
1234        assert_eq!(
1235            MentionCompletion::try_parse(true, "Lorem @", 0),
1236            Some(MentionCompletion {
1237                source_range: 6..7,
1238                mode: None,
1239                argument: None,
1240            })
1241        );
1242
1243        assert_eq!(
1244            MentionCompletion::try_parse(true, "Lorem @file", 0),
1245            Some(MentionCompletion {
1246                source_range: 6..11,
1247                mode: Some(ContextPickerMode::File),
1248                argument: None,
1249            })
1250        );
1251
1252        assert_eq!(
1253            MentionCompletion::try_parse(true, "Lorem @file ", 0),
1254            Some(MentionCompletion {
1255                source_range: 6..12,
1256                mode: Some(ContextPickerMode::File),
1257                argument: None,
1258            })
1259        );
1260
1261        assert_eq!(
1262            MentionCompletion::try_parse(true, "Lorem @file main.rs", 0),
1263            Some(MentionCompletion {
1264                source_range: 6..19,
1265                mode: Some(ContextPickerMode::File),
1266                argument: Some("main.rs".to_string()),
1267            })
1268        );
1269
1270        assert_eq!(
1271            MentionCompletion::try_parse(true, "Lorem @file main.rs ", 0),
1272            Some(MentionCompletion {
1273                source_range: 6..19,
1274                mode: Some(ContextPickerMode::File),
1275                argument: Some("main.rs".to_string()),
1276            })
1277        );
1278
1279        assert_eq!(
1280            MentionCompletion::try_parse(true, "Lorem @file main.rs Ipsum", 0),
1281            Some(MentionCompletion {
1282                source_range: 6..19,
1283                mode: Some(ContextPickerMode::File),
1284                argument: Some("main.rs".to_string()),
1285            })
1286        );
1287
1288        assert_eq!(
1289            MentionCompletion::try_parse(true, "Lorem @main", 0),
1290            Some(MentionCompletion {
1291                source_range: 6..11,
1292                mode: None,
1293                argument: Some("main".to_string()),
1294            })
1295        );
1296
1297        assert_eq!(
1298            MentionCompletion::try_parse(true, "Lorem @main ", 0),
1299            Some(MentionCompletion {
1300                source_range: 6..12,
1301                mode: None,
1302                argument: Some("main".to_string()),
1303            })
1304        );
1305
1306        assert_eq!(MentionCompletion::try_parse(true, "Lorem @main m", 0), None);
1307
1308        assert_eq!(MentionCompletion::try_parse(true, "test@", 0), None);
1309
1310        // Allowed non-file mentions
1311
1312        assert_eq!(
1313            MentionCompletion::try_parse(true, "Lorem @symbol main", 0),
1314            Some(MentionCompletion {
1315                source_range: 6..18,
1316                mode: Some(ContextPickerMode::Symbol),
1317                argument: Some("main".to_string()),
1318            })
1319        );
1320
1321        // Disallowed non-file mentions
1322        assert_eq!(
1323            MentionCompletion::try_parse(false, "Lorem @symbol main", 0),
1324            None
1325        );
1326
1327        assert_eq!(
1328            MentionCompletion::try_parse(true, "Lorem@symbol", 0),
1329            None,
1330            "Should not parse mention inside word"
1331        );
1332
1333        assert_eq!(
1334            MentionCompletion::try_parse(true, "Lorem @ file", 0),
1335            None,
1336            "Should not parse with a space after @"
1337        );
1338
1339        assert_eq!(
1340            MentionCompletion::try_parse(true, "@ file", 0),
1341            None,
1342            "Should not parse with a space after @ at the start of the line"
1343        );
1344    }
1345}