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