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