completion_provider.rs

   1use std::cell::Cell;
   2use std::ops::Range;
   3use std::rc::Rc;
   4use std::sync::Arc;
   5use std::sync::atomic::AtomicBool;
   6
   7use acp_thread::MentionUri;
   8use agent_client_protocol as acp;
   9use agent2::{HistoryEntry, HistoryStore};
  10use anyhow::Result;
  11use editor::{CompletionProvider, Editor, ExcerptId};
  12use fuzzy::{StringMatch, StringMatchCandidate};
  13use gpui::{App, Entity, Task, WeakEntity};
  14use language::{Buffer, CodeLabel, HighlightId};
  15use lsp::CompletionContext;
  16use project::{
  17    Completion, CompletionIntent, CompletionResponse, Project, ProjectPath, Symbol, WorktreeId,
  18};
  19use prompt_store::PromptStore;
  20use rope::Point;
  21use text::{Anchor, ToPoint as _};
  22use ui::prelude::*;
  23use workspace::Workspace;
  24
  25use crate::AgentPanel;
  26use crate::acp::message_editor::MessageEditor;
  27use crate::context_picker::file_context_picker::{FileMatch, search_files};
  28use crate::context_picker::rules_context_picker::{RulesContextEntry, search_rules};
  29use crate::context_picker::symbol_context_picker::SymbolMatch;
  30use crate::context_picker::symbol_context_picker::search_symbols;
  31use crate::context_picker::{
  32    ContextPickerAction, ContextPickerEntry, ContextPickerMode, selection_ranges,
  33};
  34
  35pub(crate) enum Match {
  36    File(FileMatch),
  37    Symbol(SymbolMatch),
  38    Thread(HistoryEntry),
  39    RecentThread(HistoryEntry),
  40    Fetch(SharedString),
  41    Rules(RulesContextEntry),
  42    Entry(EntryMatch),
  43}
  44
  45pub struct EntryMatch {
  46    mat: Option<StringMatch>,
  47    entry: ContextPickerEntry,
  48}
  49
  50impl Match {
  51    pub fn score(&self) -> f64 {
  52        match self {
  53            Match::File(file) => file.mat.score,
  54            Match::Entry(mode) => mode.mat.as_ref().map(|mat| mat.score).unwrap_or(1.),
  55            Match::Thread(_) => 1.,
  56            Match::RecentThread(_) => 1.,
  57            Match::Symbol(_) => 1.,
  58            Match::Rules(_) => 1.,
  59            Match::Fetch(_) => 1.,
  60        }
  61    }
  62}
  63
  64pub struct ContextPickerCompletionProvider {
  65    message_editor: WeakEntity<MessageEditor>,
  66    workspace: WeakEntity<Workspace>,
  67    history_store: Entity<HistoryStore>,
  68    prompt_store: Option<Entity<PromptStore>>,
  69    prompt_capabilities: Rc<Cell<acp::PromptCapabilities>>,
  70}
  71
  72impl ContextPickerCompletionProvider {
  73    pub fn new(
  74        message_editor: WeakEntity<MessageEditor>,
  75        workspace: WeakEntity<Workspace>,
  76        history_store: Entity<HistoryStore>,
  77        prompt_store: Option<Entity<PromptStore>>,
  78        prompt_capabilities: Rc<Cell<acp::PromptCapabilities>>,
  79    ) -> Self {
  80        Self {
  81            message_editor,
  82            workspace,
  83            history_store,
  84            prompt_store,
  85            prompt_capabilities,
  86        }
  87    }
  88
  89    fn completion_for_entry(
  90        entry: ContextPickerEntry,
  91        source_range: Range<Anchor>,
  92        message_editor: WeakEntity<MessageEditor>,
  93        workspace: &Entity<Workspace>,
  94        cx: &mut App,
  95    ) -> Option<Completion> {
  96        match entry {
  97            ContextPickerEntry::Mode(mode) => Some(Completion {
  98                replace_range: source_range,
  99                new_text: format!("@{} ", mode.keyword()),
 100                label: CodeLabel::plain(mode.label().to_string(), None),
 101                icon_path: Some(mode.icon().path().into()),
 102                documentation: None,
 103                source: project::CompletionSource::Custom,
 104                insert_text_mode: None,
 105                // This ensures that when a user accepts this completion, the
 106                // completion menu will still be shown after "@category " is
 107                // inserted
 108                confirm: Some(Arc::new(|_, _, _| true)),
 109            }),
 110            ContextPickerEntry::Action(action) => {
 111                let (new_text, on_action) = match action {
 112                    ContextPickerAction::AddSelections => {
 113                        const PLACEHOLDER: &str = "selection ";
 114                        let selections = selection_ranges(workspace, cx)
 115                            .into_iter()
 116                            .enumerate()
 117                            .map(|(ix, (buffer, range))| {
 118                                (
 119                                    buffer,
 120                                    range,
 121                                    (PLACEHOLDER.len() * ix)..(PLACEHOLDER.len() * (ix + 1) - 1),
 122                                )
 123                            })
 124                            .collect::<Vec<_>>();
 125
 126                        let new_text: String = PLACEHOLDER.repeat(selections.len());
 127
 128                        let callback = Arc::new({
 129                            let source_range = source_range.clone();
 130                            move |_, window: &mut Window, cx: &mut App| {
 131                                let selections = selections.clone();
 132                                let message_editor = message_editor.clone();
 133                                let source_range = source_range.clone();
 134                                window.defer(cx, move |window, cx| {
 135                                    message_editor
 136                                        .update(cx, |message_editor, cx| {
 137                                            message_editor.confirm_mention_for_selection(
 138                                                source_range,
 139                                                selections,
 140                                                window,
 141                                                cx,
 142                                            )
 143                                        })
 144                                        .ok();
 145                                });
 146                                false
 147                            }
 148                        });
 149
 150                        (new_text, callback)
 151                    }
 152                };
 153
 154                Some(Completion {
 155                    replace_range: source_range,
 156                    new_text,
 157                    label: CodeLabel::plain(action.label().to_string(), None),
 158                    icon_path: Some(action.icon().path().into()),
 159                    documentation: None,
 160                    source: project::CompletionSource::Custom,
 161                    insert_text_mode: None,
 162                    // This ensures that when a user accepts this completion, the
 163                    // completion menu will still be shown after "@category " is
 164                    // inserted
 165                    confirm: Some(on_action),
 166                })
 167            }
 168        }
 169    }
 170
 171    fn completion_for_thread(
 172        thread_entry: HistoryEntry,
 173        source_range: Range<Anchor>,
 174        recent: bool,
 175        editor: WeakEntity<MessageEditor>,
 176        cx: &mut App,
 177    ) -> Completion {
 178        let uri = thread_entry.mention_uri();
 179
 180        let icon_for_completion = if recent {
 181            IconName::HistoryRerun.path().into()
 182        } else {
 183            uri.icon_path(cx)
 184        };
 185
 186        let new_text = format!("{} ", uri.as_link());
 187
 188        let new_text_len = new_text.len();
 189        Completion {
 190            replace_range: source_range.clone(),
 191            new_text,
 192            label: CodeLabel::plain(thread_entry.title().to_string(), None),
 193            documentation: None,
 194            insert_text_mode: None,
 195            source: project::CompletionSource::Custom,
 196            icon_path: Some(icon_for_completion),
 197            confirm: Some(confirm_completion_callback(
 198                thread_entry.title().clone(),
 199                source_range.start,
 200                new_text_len - 1,
 201                editor,
 202                uri,
 203            )),
 204        }
 205    }
 206
 207    fn completion_for_rules(
 208        rule: RulesContextEntry,
 209        source_range: Range<Anchor>,
 210        editor: WeakEntity<MessageEditor>,
 211        cx: &mut App,
 212    ) -> Completion {
 213        let uri = MentionUri::Rule {
 214            id: rule.prompt_id.into(),
 215            name: rule.title.to_string(),
 216        };
 217        let new_text = format!("{} ", uri.as_link());
 218        let new_text_len = new_text.len();
 219        let icon_path = uri.icon_path(cx);
 220        Completion {
 221            replace_range: source_range.clone(),
 222            new_text,
 223            label: CodeLabel::plain(rule.title.to_string(), None),
 224            documentation: None,
 225            insert_text_mode: None,
 226            source: project::CompletionSource::Custom,
 227            icon_path: Some(icon_path),
 228            confirm: Some(confirm_completion_callback(
 229                rule.title,
 230                source_range.start,
 231                new_text_len - 1,
 232                editor,
 233                uri,
 234            )),
 235        }
 236    }
 237
 238    pub(crate) fn completion_for_path(
 239        project_path: ProjectPath,
 240        path_prefix: &str,
 241        is_recent: bool,
 242        is_directory: bool,
 243        source_range: Range<Anchor>,
 244        message_editor: WeakEntity<MessageEditor>,
 245        project: Entity<Project>,
 246        cx: &mut App,
 247    ) -> Option<Completion> {
 248        let (file_name, directory) =
 249            crate::context_picker::file_context_picker::extract_file_name_and_directory(
 250                &project_path.path,
 251                path_prefix,
 252            );
 253
 254        let label =
 255            build_code_label_for_full_path(&file_name, directory.as_ref().map(|s| s.as_ref()), cx);
 256
 257        let abs_path = project.read(cx).absolute_path(&project_path, cx)?;
 258
 259        let uri = if is_directory {
 260            MentionUri::Directory { abs_path }
 261        } else {
 262            MentionUri::File { abs_path }
 263        };
 264
 265        let crease_icon_path = uri.icon_path(cx);
 266        let completion_icon_path = if is_recent {
 267            IconName::HistoryRerun.path().into()
 268        } else {
 269            crease_icon_path
 270        };
 271
 272        let new_text = format!("{} ", uri.as_link());
 273        let new_text_len = new_text.len();
 274        Some(Completion {
 275            replace_range: source_range.clone(),
 276            new_text,
 277            label,
 278            documentation: None,
 279            source: project::CompletionSource::Custom,
 280            icon_path: Some(completion_icon_path),
 281            insert_text_mode: None,
 282            confirm: Some(confirm_completion_callback(
 283                file_name,
 284                source_range.start,
 285                new_text_len - 1,
 286                message_editor,
 287                uri,
 288            )),
 289        })
 290    }
 291
 292    fn completion_for_symbol(
 293        symbol: Symbol,
 294        source_range: Range<Anchor>,
 295        message_editor: WeakEntity<MessageEditor>,
 296        workspace: Entity<Workspace>,
 297        cx: &mut App,
 298    ) -> Option<Completion> {
 299        let project = workspace.read(cx).project().clone();
 300
 301        let label = CodeLabel::plain(symbol.name.clone(), None);
 302
 303        let abs_path = project.read(cx).absolute_path(&symbol.path, cx)?;
 304        let uri = MentionUri::Symbol {
 305            path: abs_path,
 306            name: symbol.name.clone(),
 307            line_range: symbol.range.start.0.row..symbol.range.end.0.row,
 308        };
 309        let new_text = format!("{} ", uri.as_link());
 310        let new_text_len = new_text.len();
 311        let icon_path = uri.icon_path(cx);
 312        Some(Completion {
 313            replace_range: source_range.clone(),
 314            new_text,
 315            label,
 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                symbol.name.into(),
 322                source_range.start,
 323                new_text_len - 1,
 324                message_editor,
 325                uri,
 326            )),
 327        })
 328    }
 329
 330    fn completion_for_fetch(
 331        source_range: Range<Anchor>,
 332        url_to_fetch: SharedString,
 333        message_editor: WeakEntity<MessageEditor>,
 334        cx: &mut App,
 335    ) -> Option<Completion> {
 336        let new_text = format!("@fetch {} ", url_to_fetch);
 337        let url_to_fetch = url::Url::parse(url_to_fetch.as_ref())
 338            .or_else(|_| url::Url::parse(&format!("https://{url_to_fetch}")))
 339            .ok()?;
 340        let mention_uri = MentionUri::Fetch {
 341            url: url_to_fetch.clone(),
 342        };
 343        let icon_path = mention_uri.icon_path(cx);
 344        Some(Completion {
 345            replace_range: source_range.clone(),
 346            new_text: new_text.clone(),
 347            label: CodeLabel::plain(url_to_fetch.to_string(), None),
 348            documentation: None,
 349            source: project::CompletionSource::Custom,
 350            icon_path: Some(icon_path),
 351            insert_text_mode: None,
 352            confirm: Some(confirm_completion_callback(
 353                url_to_fetch.to_string().into(),
 354                source_range.start,
 355                new_text.len() - 1,
 356                message_editor,
 357                mention_uri,
 358            )),
 359        })
 360    }
 361
 362    fn search(
 363        &self,
 364        mode: Option<ContextPickerMode>,
 365        query: String,
 366        cancellation_flag: Arc<AtomicBool>,
 367        cx: &mut App,
 368    ) -> Task<Vec<Match>> {
 369        let Some(workspace) = self.workspace.upgrade() else {
 370            return Task::ready(Vec::default());
 371        };
 372        match mode {
 373            Some(ContextPickerMode::File) => {
 374                let search_files_task = search_files(query, cancellation_flag, &workspace, cx);
 375                cx.background_spawn(async move {
 376                    search_files_task
 377                        .await
 378                        .into_iter()
 379                        .map(Match::File)
 380                        .collect()
 381                })
 382            }
 383
 384            Some(ContextPickerMode::Symbol) => {
 385                let search_symbols_task = search_symbols(query, cancellation_flag, &workspace, cx);
 386                cx.background_spawn(async move {
 387                    search_symbols_task
 388                        .await
 389                        .into_iter()
 390                        .map(Match::Symbol)
 391                        .collect()
 392                })
 393            }
 394
 395            Some(ContextPickerMode::Thread) => {
 396                let search_threads_task =
 397                    search_threads(query, cancellation_flag, &self.history_store, cx);
 398                cx.background_spawn(async move {
 399                    search_threads_task
 400                        .await
 401                        .into_iter()
 402                        .map(Match::Thread)
 403                        .collect()
 404                })
 405            }
 406
 407            Some(ContextPickerMode::Fetch) => {
 408                if !query.is_empty() {
 409                    Task::ready(vec![Match::Fetch(query.into())])
 410                } else {
 411                    Task::ready(Vec::new())
 412                }
 413            }
 414
 415            Some(ContextPickerMode::Rules) => {
 416                if let Some(prompt_store) = self.prompt_store.as_ref() {
 417                    let search_rules_task =
 418                        search_rules(query, cancellation_flag, prompt_store, cx);
 419                    cx.background_spawn(async move {
 420                        search_rules_task
 421                            .await
 422                            .into_iter()
 423                            .map(Match::Rules)
 424                            .collect::<Vec<_>>()
 425                    })
 426                } else {
 427                    Task::ready(Vec::new())
 428                }
 429            }
 430
 431            None if query.is_empty() => {
 432                let mut matches = self.recent_context_picker_entries(&workspace, cx);
 433
 434                matches.extend(
 435                    self.available_context_picker_entries(&workspace, cx)
 436                        .into_iter()
 437                        .map(|mode| {
 438                            Match::Entry(EntryMatch {
 439                                entry: mode,
 440                                mat: None,
 441                            })
 442                        }),
 443                );
 444
 445                Task::ready(matches)
 446            }
 447            None => {
 448                let executor = cx.background_executor().clone();
 449
 450                let search_files_task =
 451                    search_files(query.clone(), cancellation_flag, &workspace, cx);
 452
 453                let entries = self.available_context_picker_entries(&workspace, cx);
 454                let entry_candidates = entries
 455                    .iter()
 456                    .enumerate()
 457                    .map(|(ix, entry)| StringMatchCandidate::new(ix, entry.keyword()))
 458                    .collect::<Vec<_>>();
 459
 460                cx.background_spawn(async move {
 461                    let mut matches = search_files_task
 462                        .await
 463                        .into_iter()
 464                        .map(Match::File)
 465                        .collect::<Vec<_>>();
 466
 467                    let entry_matches = fuzzy::match_strings(
 468                        &entry_candidates,
 469                        &query,
 470                        false,
 471                        true,
 472                        100,
 473                        &Arc::new(AtomicBool::default()),
 474                        executor,
 475                    )
 476                    .await;
 477
 478                    matches.extend(entry_matches.into_iter().map(|mat| {
 479                        Match::Entry(EntryMatch {
 480                            entry: entries[mat.candidate_id],
 481                            mat: Some(mat),
 482                        })
 483                    }));
 484
 485                    matches.sort_by(|a, b| {
 486                        b.score()
 487                            .partial_cmp(&a.score())
 488                            .unwrap_or(std::cmp::Ordering::Equal)
 489                    });
 490
 491                    matches
 492                })
 493            }
 494        }
 495    }
 496
 497    fn recent_context_picker_entries(
 498        &self,
 499        workspace: &Entity<Workspace>,
 500        cx: &mut App,
 501    ) -> Vec<Match> {
 502        let mut recent = Vec::with_capacity(6);
 503
 504        let mut mentions = self
 505            .message_editor
 506            .read_with(cx, |message_editor, _cx| message_editor.mentions())
 507            .unwrap_or_default();
 508        let workspace = workspace.read(cx);
 509        let project = workspace.project().read(cx);
 510
 511        if let Some(agent_panel) = workspace.panel::<AgentPanel>(cx)
 512            && let Some(thread) = agent_panel.read(cx).active_agent_thread(cx)
 513        {
 514            let thread = thread.read(cx);
 515            mentions.insert(MentionUri::Thread {
 516                id: thread.session_id().clone(),
 517                name: thread.title().into(),
 518            });
 519        }
 520
 521        recent.extend(
 522            workspace
 523                .recent_navigation_history_iter(cx)
 524                .filter(|(_, abs_path)| {
 525                    abs_path.as_ref().is_none_or(|path| {
 526                        !mentions.contains(&MentionUri::File {
 527                            abs_path: path.clone(),
 528                        })
 529                    })
 530                })
 531                .take(4)
 532                .filter_map(|(project_path, _)| {
 533                    project
 534                        .worktree_for_id(project_path.worktree_id, cx)
 535                        .map(|worktree| {
 536                            let path_prefix = worktree.read(cx).root_name().into();
 537                            Match::File(FileMatch {
 538                                mat: fuzzy::PathMatch {
 539                                    score: 1.,
 540                                    positions: Vec::new(),
 541                                    worktree_id: project_path.worktree_id.to_usize(),
 542                                    path: project_path.path,
 543                                    path_prefix,
 544                                    is_dir: false,
 545                                    distance_to_relative_ancestor: 0,
 546                                },
 547                                is_recent: true,
 548                            })
 549                        })
 550                }),
 551        );
 552
 553        if self.prompt_capabilities.get().embedded_context {
 554            const RECENT_COUNT: usize = 2;
 555            let threads = self
 556                .history_store
 557                .read(cx)
 558                .recently_opened_entries(cx)
 559                .into_iter()
 560                .filter(|thread| !mentions.contains(&thread.mention_uri()))
 561                .take(RECENT_COUNT)
 562                .collect::<Vec<_>>();
 563
 564            recent.extend(threads.into_iter().map(Match::RecentThread));
 565        }
 566
 567        recent
 568    }
 569
 570    fn available_context_picker_entries(
 571        &self,
 572        workspace: &Entity<Workspace>,
 573        cx: &mut App,
 574    ) -> Vec<ContextPickerEntry> {
 575        let embedded_context = self.prompt_capabilities.get().embedded_context;
 576        let mut entries = if embedded_context {
 577            vec![
 578                ContextPickerEntry::Mode(ContextPickerMode::File),
 579                ContextPickerEntry::Mode(ContextPickerMode::Symbol),
 580                ContextPickerEntry::Mode(ContextPickerMode::Thread),
 581            ]
 582        } else {
 583            // File is always available, but we don't need a mode entry
 584            vec![]
 585        };
 586
 587        let has_selection = workspace
 588            .read(cx)
 589            .active_item(cx)
 590            .and_then(|item| item.downcast::<Editor>())
 591            .is_some_and(|editor| {
 592                editor.update(cx, |editor, cx| editor.has_non_empty_selection(cx))
 593            });
 594        if has_selection {
 595            entries.push(ContextPickerEntry::Action(
 596                ContextPickerAction::AddSelections,
 597            ));
 598        }
 599
 600        if embedded_context {
 601            if self.prompt_store.is_some() {
 602                entries.push(ContextPickerEntry::Mode(ContextPickerMode::Rules));
 603            }
 604
 605            entries.push(ContextPickerEntry::Mode(ContextPickerMode::Fetch));
 606        }
 607
 608        entries
 609    }
 610}
 611
 612fn build_code_label_for_full_path(file_name: &str, directory: Option<&str>, cx: &App) -> CodeLabel {
 613    let comment_id = cx.theme().syntax().highlight_id("comment").map(HighlightId);
 614    let mut label = CodeLabel::default();
 615
 616    label.push_str(file_name, None);
 617    label.push_str(" ", None);
 618
 619    if let Some(directory) = directory {
 620        label.push_str(directory, comment_id);
 621    }
 622
 623    label.filter_range = 0..label.text().len();
 624
 625    label
 626}
 627
 628impl CompletionProvider for ContextPickerCompletionProvider {
 629    fn completions(
 630        &self,
 631        _excerpt_id: ExcerptId,
 632        buffer: &Entity<Buffer>,
 633        buffer_position: Anchor,
 634        _trigger: CompletionContext,
 635        _window: &mut Window,
 636        cx: &mut Context<Editor>,
 637    ) -> Task<Result<Vec<CompletionResponse>>> {
 638        let state = buffer.update(cx, |buffer, _cx| {
 639            let position = buffer_position.to_point(buffer);
 640            let line_start = Point::new(position.row, 0);
 641            let offset_to_line = buffer.point_to_offset(line_start);
 642            let mut lines = buffer.text_for_range(line_start..position).lines();
 643            let line = lines.next()?;
 644            MentionCompletion::try_parse(
 645                self.prompt_capabilities.get().embedded_context,
 646                line,
 647                offset_to_line,
 648            )
 649        });
 650        let Some(state) = state else {
 651            return Task::ready(Ok(Vec::new()));
 652        };
 653
 654        let Some(workspace) = self.workspace.upgrade() else {
 655            return Task::ready(Ok(Vec::new()));
 656        };
 657
 658        let project = workspace.read(cx).project().clone();
 659        let snapshot = buffer.read(cx).snapshot();
 660        let source_range = snapshot.anchor_before(state.source_range.start)
 661            ..snapshot.anchor_after(state.source_range.end);
 662
 663        let editor = self.message_editor.clone();
 664
 665        let MentionCompletion { mode, argument, .. } = state;
 666        let query = argument.unwrap_or_else(|| "".to_string());
 667
 668        let search_task = self.search(mode, query, Arc::<AtomicBool>::default(), cx);
 669
 670        cx.spawn(async move |_, cx| {
 671            let matches = search_task.await;
 672
 673            let completions = cx.update(|cx| {
 674                matches
 675                    .into_iter()
 676                    .filter_map(|mat| match mat {
 677                        Match::File(FileMatch { mat, is_recent }) => {
 678                            let project_path = ProjectPath {
 679                                worktree_id: WorktreeId::from_usize(mat.worktree_id),
 680                                path: mat.path.clone(),
 681                            };
 682
 683                            Self::completion_for_path(
 684                                project_path,
 685                                &mat.path_prefix,
 686                                is_recent,
 687                                mat.is_dir,
 688                                source_range.clone(),
 689                                editor.clone(),
 690                                project.clone(),
 691                                cx,
 692                            )
 693                        }
 694
 695                        Match::Symbol(SymbolMatch { symbol, .. }) => Self::completion_for_symbol(
 696                            symbol,
 697                            source_range.clone(),
 698                            editor.clone(),
 699                            workspace.clone(),
 700                            cx,
 701                        ),
 702
 703                        Match::Thread(thread) => Some(Self::completion_for_thread(
 704                            thread,
 705                            source_range.clone(),
 706                            false,
 707                            editor.clone(),
 708                            cx,
 709                        )),
 710
 711                        Match::RecentThread(thread) => Some(Self::completion_for_thread(
 712                            thread,
 713                            source_range.clone(),
 714                            true,
 715                            editor.clone(),
 716                            cx,
 717                        )),
 718
 719                        Match::Rules(user_rules) => Some(Self::completion_for_rules(
 720                            user_rules,
 721                            source_range.clone(),
 722                            editor.clone(),
 723                            cx,
 724                        )),
 725
 726                        Match::Fetch(url) => Self::completion_for_fetch(
 727                            source_range.clone(),
 728                            url,
 729                            editor.clone(),
 730                            cx,
 731                        ),
 732
 733                        Match::Entry(EntryMatch { entry, .. }) => Self::completion_for_entry(
 734                            entry,
 735                            source_range.clone(),
 736                            editor.clone(),
 737                            &workspace,
 738                            cx,
 739                        ),
 740                    })
 741                    .collect()
 742            })?;
 743
 744            Ok(vec![CompletionResponse {
 745                completions,
 746                // Since this does its own filtering (see `filter_completions()` returns false),
 747                // there is no benefit to computing whether this set of completions is incomplete.
 748                is_incomplete: true,
 749            }])
 750        })
 751    }
 752
 753    fn is_completion_trigger(
 754        &self,
 755        buffer: &Entity<language::Buffer>,
 756        position: language::Anchor,
 757        _text: &str,
 758        _trigger_in_words: bool,
 759        _menu_is_open: bool,
 760        cx: &mut Context<Editor>,
 761    ) -> bool {
 762        let buffer = buffer.read(cx);
 763        let position = position.to_point(buffer);
 764        let line_start = Point::new(position.row, 0);
 765        let offset_to_line = buffer.point_to_offset(line_start);
 766        let mut lines = buffer.text_for_range(line_start..position).lines();
 767        if let Some(line) = lines.next() {
 768            MentionCompletion::try_parse(
 769                self.prompt_capabilities.get().embedded_context,
 770                line,
 771                offset_to_line,
 772            )
 773            .map(|completion| {
 774                completion.source_range.start <= offset_to_line + position.column as usize
 775                    && completion.source_range.end >= offset_to_line + position.column as usize
 776            })
 777            .unwrap_or(false)
 778        } else {
 779            false
 780        }
 781    }
 782
 783    fn sort_completions(&self) -> bool {
 784        false
 785    }
 786
 787    fn filter_completions(&self) -> bool {
 788        false
 789    }
 790}
 791
 792pub(crate) fn search_threads(
 793    query: String,
 794    cancellation_flag: Arc<AtomicBool>,
 795    history_store: &Entity<HistoryStore>,
 796    cx: &mut App,
 797) -> Task<Vec<HistoryEntry>> {
 798    let threads = history_store.read(cx).entries(cx);
 799    if query.is_empty() {
 800        return Task::ready(threads);
 801    }
 802
 803    let executor = cx.background_executor().clone();
 804    cx.background_spawn(async move {
 805        let candidates = threads
 806            .iter()
 807            .enumerate()
 808            .map(|(id, thread)| StringMatchCandidate::new(id, thread.title()))
 809            .collect::<Vec<_>>();
 810        let matches = fuzzy::match_strings(
 811            &candidates,
 812            &query,
 813            false,
 814            true,
 815            100,
 816            &cancellation_flag,
 817            executor,
 818        )
 819        .await;
 820
 821        matches
 822            .into_iter()
 823            .map(|mat| threads[mat.candidate_id].clone())
 824            .collect()
 825    })
 826}
 827
 828fn confirm_completion_callback(
 829    crease_text: SharedString,
 830    start: Anchor,
 831    content_len: usize,
 832    message_editor: WeakEntity<MessageEditor>,
 833    mention_uri: MentionUri,
 834) -> Arc<dyn Fn(CompletionIntent, &mut Window, &mut App) -> bool + Send + Sync> {
 835    Arc::new(move |_, window, cx| {
 836        let message_editor = message_editor.clone();
 837        let crease_text = crease_text.clone();
 838        let mention_uri = mention_uri.clone();
 839        window.defer(cx, move |window, cx| {
 840            message_editor
 841                .clone()
 842                .update(cx, |message_editor, cx| {
 843                    message_editor
 844                        .confirm_completion(
 845                            crease_text,
 846                            start,
 847                            content_len,
 848                            mention_uri,
 849                            window,
 850                            cx,
 851                        )
 852                        .detach();
 853                })
 854                .ok();
 855        });
 856        false
 857    })
 858}
 859
 860#[derive(Debug, Default, PartialEq)]
 861struct MentionCompletion {
 862    source_range: Range<usize>,
 863    mode: Option<ContextPickerMode>,
 864    argument: Option<String>,
 865}
 866
 867impl MentionCompletion {
 868    fn try_parse(allow_non_file_mentions: bool, line: &str, offset_to_line: usize) -> Option<Self> {
 869        let last_mention_start = line.rfind('@')?;
 870        if last_mention_start >= line.len() {
 871            return Some(Self::default());
 872        }
 873        if last_mention_start > 0
 874            && line
 875                .chars()
 876                .nth(last_mention_start - 1)
 877                .is_some_and(|c| !c.is_whitespace())
 878        {
 879            return None;
 880        }
 881
 882        let rest_of_line = &line[last_mention_start + 1..];
 883
 884        let mut mode = None;
 885        let mut argument = None;
 886
 887        let mut parts = rest_of_line.split_whitespace();
 888        let mut end = last_mention_start + 1;
 889        if let Some(mode_text) = parts.next() {
 890            end += mode_text.len();
 891
 892            if let Some(parsed_mode) = ContextPickerMode::try_from(mode_text).ok()
 893                && (allow_non_file_mentions || matches!(parsed_mode, ContextPickerMode::File))
 894            {
 895                mode = Some(parsed_mode);
 896            } else {
 897                argument = Some(mode_text.to_string());
 898            }
 899            match rest_of_line[mode_text.len()..].find(|c: char| !c.is_whitespace()) {
 900                Some(whitespace_count) => {
 901                    if let Some(argument_text) = parts.next() {
 902                        argument = Some(argument_text.to_string());
 903                        end += whitespace_count + argument_text.len();
 904                    }
 905                }
 906                None => {
 907                    // Rest of line is entirely whitespace
 908                    end += rest_of_line.len() - mode_text.len();
 909                }
 910            }
 911        }
 912
 913        Some(Self {
 914            source_range: last_mention_start + offset_to_line..end + offset_to_line,
 915            mode,
 916            argument,
 917        })
 918    }
 919}
 920
 921#[cfg(test)]
 922mod tests {
 923    use super::*;
 924
 925    #[test]
 926    fn test_mention_completion_parse() {
 927        assert_eq!(MentionCompletion::try_parse(true, "Lorem Ipsum", 0), None);
 928
 929        assert_eq!(
 930            MentionCompletion::try_parse(true, "Lorem @", 0),
 931            Some(MentionCompletion {
 932                source_range: 6..7,
 933                mode: None,
 934                argument: None,
 935            })
 936        );
 937
 938        assert_eq!(
 939            MentionCompletion::try_parse(true, "Lorem @file", 0),
 940            Some(MentionCompletion {
 941                source_range: 6..11,
 942                mode: Some(ContextPickerMode::File),
 943                argument: None,
 944            })
 945        );
 946
 947        assert_eq!(
 948            MentionCompletion::try_parse(true, "Lorem @file ", 0),
 949            Some(MentionCompletion {
 950                source_range: 6..12,
 951                mode: Some(ContextPickerMode::File),
 952                argument: None,
 953            })
 954        );
 955
 956        assert_eq!(
 957            MentionCompletion::try_parse(true, "Lorem @file main.rs", 0),
 958            Some(MentionCompletion {
 959                source_range: 6..19,
 960                mode: Some(ContextPickerMode::File),
 961                argument: Some("main.rs".to_string()),
 962            })
 963        );
 964
 965        assert_eq!(
 966            MentionCompletion::try_parse(true, "Lorem @file main.rs ", 0),
 967            Some(MentionCompletion {
 968                source_range: 6..19,
 969                mode: Some(ContextPickerMode::File),
 970                argument: Some("main.rs".to_string()),
 971            })
 972        );
 973
 974        assert_eq!(
 975            MentionCompletion::try_parse(true, "Lorem @file main.rs Ipsum", 0),
 976            Some(MentionCompletion {
 977                source_range: 6..19,
 978                mode: Some(ContextPickerMode::File),
 979                argument: Some("main.rs".to_string()),
 980            })
 981        );
 982
 983        assert_eq!(
 984            MentionCompletion::try_parse(true, "Lorem @main", 0),
 985            Some(MentionCompletion {
 986                source_range: 6..11,
 987                mode: None,
 988                argument: Some("main".to_string()),
 989            })
 990        );
 991
 992        assert_eq!(MentionCompletion::try_parse(true, "test@", 0), None);
 993
 994        // Allowed non-file mentions
 995
 996        assert_eq!(
 997            MentionCompletion::try_parse(true, "Lorem @symbol main", 0),
 998            Some(MentionCompletion {
 999                source_range: 6..18,
1000                mode: Some(ContextPickerMode::Symbol),
1001                argument: Some("main".to_string()),
1002            })
1003        );
1004
1005        // Disallowed non-file mentions
1006
1007        assert_eq!(
1008            MentionCompletion::try_parse(false, "Lorem @symbol main", 0),
1009            Some(MentionCompletion {
1010                source_range: 6..18,
1011                mode: None,
1012                argument: Some("main".to_string()),
1013            })
1014        );
1015    }
1016}