1use std::ops::Range;
2use std::path::{Path, PathBuf};
3use std::sync::Arc;
4use std::sync::atomic::AtomicBool;
5
6use agent::context_store::ContextStore;
7use anyhow::Result;
8use editor::{CompletionProvider, Editor, ExcerptId, ToOffset as _};
9use file_icons::FileIcons;
10use fuzzy::{StringMatch, StringMatchCandidate};
11use gpui::{App, Entity, Task, WeakEntity};
12use http_client::HttpClientWithUrl;
13use itertools::Itertools;
14use language::{Buffer, CodeLabel, CodeLabelBuilder, HighlightId};
15use lsp::CompletionContext;
16use project::lsp_store::SymbolLocation;
17use project::{
18 Completion, CompletionDisplayOptions, CompletionIntent, CompletionResponse, ProjectPath,
19 Symbol, WorktreeId,
20};
21use prompt_store::PromptStore;
22use rope::Point;
23use text::{Anchor, OffsetRangeExt, ToPoint};
24use ui::prelude::*;
25use util::ResultExt as _;
26use util::paths::PathStyle;
27use util::rel_path::RelPath;
28use workspace::Workspace;
29
30use agent::{
31 Thread,
32 context::{AgentContextHandle, AgentContextKey, RULES_ICON},
33 thread_store::{TextThreadStore, ThreadStore},
34};
35
36use super::fetch_context_picker::fetch_url_content;
37use super::file_context_picker::{FileMatch, search_files};
38use super::rules_context_picker::{RulesContextEntry, search_rules};
39use super::symbol_context_picker::SymbolMatch;
40use super::symbol_context_picker::search_symbols;
41use super::thread_context_picker::{ThreadContextEntry, ThreadMatch, search_threads};
42use super::{
43 ContextPickerAction, ContextPickerEntry, ContextPickerMode, MentionLink, RecentEntry,
44 available_context_picker_entries, recent_context_picker_entries_with_store, selection_ranges,
45};
46use crate::message_editor::ContextCreasesAddon;
47
48pub(crate) enum Match {
49 File(FileMatch),
50 Symbol(SymbolMatch),
51 Thread(ThreadMatch),
52 Fetch(SharedString),
53 Rules(RulesContextEntry),
54 Entry(EntryMatch),
55}
56
57pub struct EntryMatch {
58 mat: Option<StringMatch>,
59 entry: ContextPickerEntry,
60}
61
62impl Match {
63 pub fn score(&self) -> f64 {
64 match self {
65 Match::File(file) => file.mat.score,
66 Match::Entry(mode) => mode.mat.as_ref().map(|mat| mat.score).unwrap_or(1.),
67 Match::Thread(_) => 1.,
68 Match::Symbol(_) => 1.,
69 Match::Fetch(_) => 1.,
70 Match::Rules(_) => 1.,
71 }
72 }
73}
74
75fn search(
76 mode: Option<ContextPickerMode>,
77 query: String,
78 cancellation_flag: Arc<AtomicBool>,
79 recent_entries: Vec<RecentEntry>,
80 prompt_store: Option<Entity<PromptStore>>,
81 thread_store: Option<WeakEntity<ThreadStore>>,
82 text_thread_context_store: Option<WeakEntity<assistant_context::ContextStore>>,
83 workspace: Entity<Workspace>,
84 cx: &mut App,
85) -> Task<Vec<Match>> {
86 match mode {
87 Some(ContextPickerMode::File) => {
88 let search_files_task = search_files(query, cancellation_flag, &workspace, cx);
89 cx.background_spawn(async move {
90 search_files_task
91 .await
92 .into_iter()
93 .map(Match::File)
94 .collect()
95 })
96 }
97
98 Some(ContextPickerMode::Symbol) => {
99 let search_symbols_task = search_symbols(query, cancellation_flag, &workspace, cx);
100 cx.background_spawn(async move {
101 search_symbols_task
102 .await
103 .into_iter()
104 .map(Match::Symbol)
105 .collect()
106 })
107 }
108
109 Some(ContextPickerMode::Thread) => {
110 if let Some((thread_store, context_store)) = thread_store
111 .as_ref()
112 .and_then(|t| t.upgrade())
113 .zip(text_thread_context_store.as_ref().and_then(|t| t.upgrade()))
114 {
115 let search_threads_task =
116 search_threads(query, cancellation_flag, thread_store, context_store, cx);
117 cx.background_spawn(async move {
118 search_threads_task
119 .await
120 .into_iter()
121 .map(Match::Thread)
122 .collect()
123 })
124 } else {
125 Task::ready(Vec::new())
126 }
127 }
128
129 Some(ContextPickerMode::Fetch) => {
130 if !query.is_empty() {
131 Task::ready(vec![Match::Fetch(query.into())])
132 } else {
133 Task::ready(Vec::new())
134 }
135 }
136
137 Some(ContextPickerMode::Rules) => {
138 if let Some(prompt_store) = prompt_store.as_ref() {
139 let search_rules_task = search_rules(query, cancellation_flag, prompt_store, cx);
140 cx.background_spawn(async move {
141 search_rules_task
142 .await
143 .into_iter()
144 .map(Match::Rules)
145 .collect::<Vec<_>>()
146 })
147 } else {
148 Task::ready(Vec::new())
149 }
150 }
151
152 None => {
153 if query.is_empty() {
154 let mut matches = recent_entries
155 .into_iter()
156 .map(|entry| match entry {
157 super::RecentEntry::File {
158 project_path,
159 path_prefix,
160 } => Match::File(FileMatch {
161 mat: fuzzy::PathMatch {
162 score: 1.,
163 positions: Vec::new(),
164 worktree_id: project_path.worktree_id.to_usize(),
165 path: project_path.path,
166 path_prefix,
167 is_dir: false,
168 distance_to_relative_ancestor: 0,
169 },
170 is_recent: true,
171 }),
172 super::RecentEntry::Thread(thread_context_entry) => {
173 Match::Thread(ThreadMatch {
174 thread: thread_context_entry,
175 is_recent: true,
176 })
177 }
178 })
179 .collect::<Vec<_>>();
180
181 matches.extend(
182 available_context_picker_entries(&prompt_store, &thread_store, &workspace, cx)
183 .into_iter()
184 .map(|mode| {
185 Match::Entry(EntryMatch {
186 entry: mode,
187 mat: None,
188 })
189 }),
190 );
191
192 Task::ready(matches)
193 } else {
194 let executor = cx.background_executor().clone();
195
196 let search_files_task =
197 search_files(query.clone(), cancellation_flag, &workspace, cx);
198
199 let entries =
200 available_context_picker_entries(&prompt_store, &thread_store, &workspace, cx);
201 let entry_candidates = entries
202 .iter()
203 .enumerate()
204 .map(|(ix, entry)| StringMatchCandidate::new(ix, entry.keyword()))
205 .collect::<Vec<_>>();
206
207 cx.background_spawn(async move {
208 let mut matches = search_files_task
209 .await
210 .into_iter()
211 .map(Match::File)
212 .collect::<Vec<_>>();
213
214 let entry_matches = fuzzy::match_strings(
215 &entry_candidates,
216 &query,
217 false,
218 true,
219 100,
220 &Arc::new(AtomicBool::default()),
221 executor,
222 )
223 .await;
224
225 matches.extend(entry_matches.into_iter().map(|mat| {
226 Match::Entry(EntryMatch {
227 entry: entries[mat.candidate_id],
228 mat: Some(mat),
229 })
230 }));
231
232 matches.sort_by(|a, b| {
233 b.score()
234 .partial_cmp(&a.score())
235 .unwrap_or(std::cmp::Ordering::Equal)
236 });
237
238 matches
239 })
240 }
241 }
242 }
243}
244
245pub struct ContextPickerCompletionProvider {
246 workspace: WeakEntity<Workspace>,
247 context_store: WeakEntity<ContextStore>,
248 thread_store: Option<WeakEntity<ThreadStore>>,
249 text_thread_store: Option<WeakEntity<TextThreadStore>>,
250 editor: WeakEntity<Editor>,
251 excluded_buffer: Option<WeakEntity<Buffer>>,
252}
253
254impl ContextPickerCompletionProvider {
255 pub fn new(
256 workspace: WeakEntity<Workspace>,
257 context_store: WeakEntity<ContextStore>,
258 thread_store: Option<WeakEntity<ThreadStore>>,
259 text_thread_store: Option<WeakEntity<TextThreadStore>>,
260 editor: WeakEntity<Editor>,
261 exclude_buffer: Option<WeakEntity<Buffer>>,
262 ) -> Self {
263 Self {
264 workspace,
265 context_store,
266 thread_store,
267 text_thread_store,
268 editor,
269 excluded_buffer: exclude_buffer,
270 }
271 }
272
273 fn completion_for_entry(
274 entry: ContextPickerEntry,
275 excerpt_id: ExcerptId,
276 source_range: Range<Anchor>,
277 editor: Entity<Editor>,
278 context_store: Entity<ContextStore>,
279 workspace: &Entity<Workspace>,
280 cx: &mut App,
281 ) -> Option<Completion> {
282 match entry {
283 ContextPickerEntry::Mode(mode) => Some(Completion {
284 replace_range: source_range,
285 new_text: format!("@{} ", mode.keyword()),
286 label: CodeLabel::plain(mode.label().to_string(), None),
287 icon_path: Some(mode.icon().path().into()),
288 documentation: None,
289 source: project::CompletionSource::Custom,
290 insert_text_mode: None,
291 // This ensures that when a user accepts this completion, the
292 // completion menu will still be shown after "@category " is
293 // inserted
294 confirm: Some(Arc::new(|_, _, _| true)),
295 }),
296 ContextPickerEntry::Action(action) => {
297 let (new_text, on_action) = match action {
298 ContextPickerAction::AddSelections => {
299 let selections = selection_ranges(workspace, cx);
300
301 let selection_infos = selections
302 .iter()
303 .map(|(buffer, range)| {
304 let full_path = buffer
305 .read(cx)
306 .file()
307 .map(|file| file.full_path(cx))
308 .unwrap_or_else(|| PathBuf::from("untitled"));
309 let file_name = full_path
310 .file_name()
311 .unwrap_or_default()
312 .to_string_lossy()
313 .to_string();
314 let line_range = range.to_point(&buffer.read(cx).snapshot());
315
316 let link = MentionLink::for_selection(
317 &file_name,
318 &full_path.to_string_lossy(),
319 line_range.start.row as usize..line_range.end.row as usize,
320 );
321 (file_name, link, line_range)
322 })
323 .collect::<Vec<_>>();
324
325 let new_text = format!(
326 "{} ",
327 selection_infos.iter().map(|(_, link, _)| link).join(" ")
328 );
329
330 let callback = Arc::new({
331 move |_, window: &mut Window, cx: &mut App| {
332 context_store.update(cx, |context_store, cx| {
333 for (buffer, range) in &selections {
334 context_store.add_selection(
335 buffer.clone(),
336 range.clone(),
337 cx,
338 );
339 }
340 });
341
342 let editor = editor.clone();
343 let selection_infos = selection_infos.clone();
344 window.defer(cx, move |window, cx| {
345 let mut current_offset = 0;
346 for (file_name, link, line_range) in selection_infos.iter() {
347 let snapshot =
348 editor.read(cx).buffer().read(cx).snapshot(cx);
349 let Some(start) = snapshot
350 .anchor_in_excerpt(excerpt_id, source_range.start)
351 else {
352 return;
353 };
354
355 let offset = start.to_offset(&snapshot) + current_offset;
356 let text_len = link.len();
357
358 let range = snapshot.anchor_after(offset)
359 ..snapshot.anchor_after(offset + text_len);
360
361 let crease = super::crease_for_mention(
362 format!(
363 "{} ({}-{})",
364 file_name,
365 line_range.start.row + 1,
366 line_range.end.row + 1
367 )
368 .into(),
369 IconName::Reader.path().into(),
370 range,
371 editor.downgrade(),
372 );
373
374 editor.update(cx, |editor, cx| {
375 editor.insert_creases(vec![crease.clone()], cx);
376 editor.fold_creases(vec![crease], false, window, cx);
377 });
378
379 current_offset += text_len + 1;
380 }
381 });
382
383 false
384 }
385 });
386
387 (new_text, callback)
388 }
389 };
390
391 Some(Completion {
392 replace_range: source_range.clone(),
393 new_text,
394 label: CodeLabel::plain(action.label().to_string(), None),
395 icon_path: Some(action.icon().path().into()),
396 documentation: None,
397 source: project::CompletionSource::Custom,
398 insert_text_mode: None,
399 // This ensures that when a user accepts this completion, the
400 // completion menu will still be shown after "@category " is
401 // inserted
402 confirm: Some(on_action),
403 })
404 }
405 }
406 }
407
408 fn completion_for_thread(
409 thread_entry: ThreadContextEntry,
410 excerpt_id: ExcerptId,
411 source_range: Range<Anchor>,
412 recent: bool,
413 editor: Entity<Editor>,
414 context_store: Entity<ContextStore>,
415 thread_store: Entity<ThreadStore>,
416 text_thread_store: Entity<TextThreadStore>,
417 ) -> Completion {
418 let icon_for_completion = if recent {
419 IconName::HistoryRerun
420 } else {
421 IconName::Thread
422 };
423 let new_text = format!("{} ", MentionLink::for_thread(&thread_entry));
424 let new_text_len = new_text.len();
425 Completion {
426 replace_range: source_range.clone(),
427 new_text,
428 label: CodeLabel::plain(thread_entry.title().to_string(), None),
429 documentation: None,
430 insert_text_mode: None,
431 source: project::CompletionSource::Custom,
432 icon_path: Some(icon_for_completion.path().into()),
433 confirm: Some(confirm_completion_callback(
434 IconName::Thread.path().into(),
435 thread_entry.title().clone(),
436 excerpt_id,
437 source_range.start,
438 new_text_len - 1,
439 editor,
440 context_store.clone(),
441 move |window, cx| match &thread_entry {
442 ThreadContextEntry::Thread { id, .. } => {
443 let thread_id = id.clone();
444 let context_store = context_store.clone();
445 let thread_store = thread_store.clone();
446 window.spawn::<_, Option<_>>(cx, async move |cx| {
447 let thread: Entity<Thread> = thread_store
448 .update_in(cx, |thread_store, window, cx| {
449 thread_store.open_thread(&thread_id, window, cx)
450 })
451 .ok()?
452 .await
453 .log_err()?;
454 let context = context_store
455 .update(cx, |context_store, cx| {
456 context_store.add_thread(thread, false, cx)
457 })
458 .ok()??;
459 Some(context)
460 })
461 }
462 ThreadContextEntry::Context { path, .. } => {
463 let path = path.clone();
464 let context_store = context_store.clone();
465 let text_thread_store = text_thread_store.clone();
466 cx.spawn::<_, Option<_>>(async move |cx| {
467 let thread = text_thread_store
468 .update(cx, |store, cx| store.open_local_context(path, cx))
469 .ok()?
470 .await
471 .log_err()?;
472 let context = context_store
473 .update(cx, |context_store, cx| {
474 context_store.add_text_thread(thread, false, cx)
475 })
476 .ok()??;
477 Some(context)
478 })
479 }
480 },
481 )),
482 }
483 }
484
485 fn completion_for_rules(
486 rules: RulesContextEntry,
487 excerpt_id: ExcerptId,
488 source_range: Range<Anchor>,
489 editor: Entity<Editor>,
490 context_store: Entity<ContextStore>,
491 ) -> Completion {
492 let new_text = format!("{} ", MentionLink::for_rule(&rules));
493 let new_text_len = new_text.len();
494 Completion {
495 replace_range: source_range.clone(),
496 new_text,
497 label: CodeLabel::plain(rules.title.to_string(), None),
498 documentation: None,
499 insert_text_mode: None,
500 source: project::CompletionSource::Custom,
501 icon_path: Some(RULES_ICON.path().into()),
502 confirm: Some(confirm_completion_callback(
503 RULES_ICON.path().into(),
504 rules.title.clone(),
505 excerpt_id,
506 source_range.start,
507 new_text_len - 1,
508 editor,
509 context_store.clone(),
510 move |_, cx| {
511 let user_prompt_id = rules.prompt_id;
512 let context = context_store.update(cx, |context_store, cx| {
513 context_store.add_rules(user_prompt_id, false, cx)
514 });
515 Task::ready(context)
516 },
517 )),
518 }
519 }
520
521 fn completion_for_fetch(
522 source_range: Range<Anchor>,
523 url_to_fetch: SharedString,
524 excerpt_id: ExcerptId,
525 editor: Entity<Editor>,
526 context_store: Entity<ContextStore>,
527 http_client: Arc<HttpClientWithUrl>,
528 ) -> Completion {
529 let new_text = format!("{} ", MentionLink::for_fetch(&url_to_fetch));
530 let new_text_len = new_text.len();
531 Completion {
532 replace_range: source_range.clone(),
533 new_text,
534 label: CodeLabel::plain(url_to_fetch.to_string(), None),
535 documentation: None,
536 source: project::CompletionSource::Custom,
537 icon_path: Some(IconName::ToolWeb.path().into()),
538 insert_text_mode: None,
539 confirm: Some(confirm_completion_callback(
540 IconName::ToolWeb.path().into(),
541 url_to_fetch.clone(),
542 excerpt_id,
543 source_range.start,
544 new_text_len - 1,
545 editor,
546 context_store.clone(),
547 move |_, cx| {
548 let context_store = context_store.clone();
549 let http_client = http_client.clone();
550 let url_to_fetch = url_to_fetch.clone();
551 cx.spawn(async move |cx| {
552 if let Some(context) = context_store
553 .read_with(cx, |context_store, _| {
554 context_store.get_url_context(url_to_fetch.clone())
555 })
556 .ok()?
557 {
558 return Some(context);
559 }
560 let content = cx
561 .background_spawn(fetch_url_content(
562 http_client,
563 url_to_fetch.to_string(),
564 ))
565 .await
566 .log_err()?;
567 context_store
568 .update(cx, |context_store, cx| {
569 context_store.add_fetched_url(url_to_fetch.to_string(), content, cx)
570 })
571 .ok()
572 })
573 },
574 )),
575 }
576 }
577
578 fn completion_for_path(
579 project_path: ProjectPath,
580 path_prefix: &RelPath,
581 is_recent: bool,
582 is_directory: bool,
583 excerpt_id: ExcerptId,
584 source_range: Range<Anchor>,
585 path_style: PathStyle,
586 editor: Entity<Editor>,
587 context_store: Entity<ContextStore>,
588 cx: &App,
589 ) -> Completion {
590 let (file_name, directory) = super::file_context_picker::extract_file_name_and_directory(
591 &project_path.path,
592 path_prefix,
593 path_style,
594 );
595
596 let label =
597 build_code_label_for_full_path(&file_name, directory.as_ref().map(|s| s.as_ref()), cx);
598 let full_path = if let Some(directory) = directory {
599 format!("{}{}", directory, file_name)
600 } else {
601 file_name.to_string()
602 };
603
604 let path = Path::new(&full_path);
605 let crease_icon_path = if is_directory {
606 FileIcons::get_folder_icon(false, path, cx)
607 .unwrap_or_else(|| IconName::Folder.path().into())
608 } else {
609 FileIcons::get_icon(path, cx).unwrap_or_else(|| IconName::File.path().into())
610 };
611 let completion_icon_path = if is_recent {
612 IconName::HistoryRerun.path().into()
613 } else {
614 crease_icon_path.clone()
615 };
616
617 let new_text = format!("{} ", MentionLink::for_file(&file_name, &full_path));
618 let new_text_len = new_text.len();
619 Completion {
620 replace_range: source_range.clone(),
621 new_text,
622 label,
623 documentation: None,
624 source: project::CompletionSource::Custom,
625 icon_path: Some(completion_icon_path),
626 insert_text_mode: None,
627 confirm: Some(confirm_completion_callback(
628 crease_icon_path,
629 file_name,
630 excerpt_id,
631 source_range.start,
632 new_text_len - 1,
633 editor,
634 context_store.clone(),
635 move |_, cx| {
636 if is_directory {
637 Task::ready(
638 context_store
639 .update(cx, |context_store, cx| {
640 context_store.add_directory(&project_path, false, cx)
641 })
642 .log_err()
643 .flatten(),
644 )
645 } else {
646 let result = context_store.update(cx, |context_store, cx| {
647 context_store.add_file_from_path(project_path.clone(), false, cx)
648 });
649 cx.spawn(async move |_| result.await.log_err().flatten())
650 }
651 },
652 )),
653 }
654 }
655
656 fn completion_for_symbol(
657 symbol: Symbol,
658 excerpt_id: ExcerptId,
659 source_range: Range<Anchor>,
660 editor: Entity<Editor>,
661 context_store: Entity<ContextStore>,
662 workspace: Entity<Workspace>,
663 cx: &mut App,
664 ) -> Option<Completion> {
665 let path_style = workspace.read(cx).path_style(cx);
666 let SymbolLocation::InProject(symbol_path) = &symbol.path else {
667 return None;
668 };
669 let path_prefix = workspace
670 .read(cx)
671 .project()
672 .read(cx)
673 .worktree_for_id(symbol_path.worktree_id, cx)?
674 .read(cx)
675 .root_name();
676
677 let (file_name, directory) = super::file_context_picker::extract_file_name_and_directory(
678 &symbol_path.path,
679 path_prefix,
680 path_style,
681 );
682 let full_path = if let Some(directory) = directory {
683 format!("{}{}", directory, file_name)
684 } else {
685 file_name.to_string()
686 };
687
688 let comment_id = cx.theme().syntax().highlight_id("comment").map(HighlightId);
689 let mut label = CodeLabelBuilder::default();
690 label.push_str(&symbol.name, None);
691 label.push_str(" ", None);
692 label.push_str(&file_name, comment_id);
693 label.push_str(&format!(" L{}", symbol.range.start.0.row + 1), comment_id);
694
695 let new_text = format!("{} ", MentionLink::for_symbol(&symbol.name, &full_path));
696 let new_text_len = new_text.len();
697 Some(Completion {
698 replace_range: source_range.clone(),
699 new_text,
700 label: label.build(),
701 documentation: None,
702 source: project::CompletionSource::Custom,
703 icon_path: Some(IconName::Code.path().into()),
704 insert_text_mode: None,
705 confirm: Some(confirm_completion_callback(
706 IconName::Code.path().into(),
707 symbol.name.clone().into(),
708 excerpt_id,
709 source_range.start,
710 new_text_len - 1,
711 editor,
712 context_store.clone(),
713 move |_, cx| {
714 let symbol = symbol.clone();
715 let context_store = context_store.clone();
716 let workspace = workspace.clone();
717 let result = super::symbol_context_picker::add_symbol(
718 symbol,
719 false,
720 workspace,
721 context_store.downgrade(),
722 cx,
723 );
724 cx.spawn(async move |_| result.await.log_err()?.0)
725 },
726 )),
727 })
728 }
729}
730
731fn build_code_label_for_full_path(file_name: &str, directory: Option<&str>, cx: &App) -> CodeLabel {
732 let comment_id = cx.theme().syntax().highlight_id("comment").map(HighlightId);
733 let mut label = CodeLabelBuilder::default();
734
735 label.push_str(file_name, None);
736 label.push_str(" ", None);
737
738 if let Some(directory) = directory {
739 label.push_str(directory, comment_id);
740 }
741
742 label.build()
743}
744
745impl CompletionProvider for ContextPickerCompletionProvider {
746 fn completions(
747 &self,
748 excerpt_id: ExcerptId,
749 buffer: &Entity<Buffer>,
750 buffer_position: Anchor,
751 _trigger: CompletionContext,
752 _window: &mut Window,
753 cx: &mut Context<Editor>,
754 ) -> Task<Result<Vec<CompletionResponse>>> {
755 let snapshot = buffer.read(cx).snapshot();
756 let position = buffer_position.to_point(&snapshot);
757 let line_start = Point::new(position.row, 0);
758 let offset_to_line = snapshot.point_to_offset(line_start);
759 let mut lines = snapshot.text_for_range(line_start..position).lines();
760 let Some(line) = lines.next() else {
761 return Task::ready(Ok(Vec::new()));
762 };
763 let Some(state) = MentionCompletion::try_parse(line, offset_to_line) else {
764 return Task::ready(Ok(Vec::new()));
765 };
766
767 let Some((workspace, context_store)) =
768 self.workspace.upgrade().zip(self.context_store.upgrade())
769 else {
770 return Task::ready(Ok(Vec::new()));
771 };
772
773 let source_range = snapshot.anchor_before(state.source_range.start)
774 ..snapshot.anchor_after(state.source_range.end);
775
776 let thread_store = self.thread_store.clone();
777 let text_thread_store = self.text_thread_store.clone();
778 let editor = self.editor.clone();
779 let http_client = workspace.read(cx).client().http_client();
780 let path_style = workspace.read(cx).path_style(cx);
781
782 let MentionCompletion { mode, argument, .. } = state;
783 let query = argument.unwrap_or_else(|| "".to_string());
784
785 let excluded_path = self
786 .excluded_buffer
787 .as_ref()
788 .and_then(WeakEntity::upgrade)
789 .and_then(|b| b.read(cx).file())
790 .map(|file| ProjectPath::from_file(file.as_ref(), cx));
791
792 let recent_entries = recent_context_picker_entries_with_store(
793 context_store.clone(),
794 thread_store.clone(),
795 text_thread_store.clone(),
796 workspace.clone(),
797 excluded_path.clone(),
798 cx,
799 );
800
801 let prompt_store = thread_store.as_ref().and_then(|thread_store| {
802 thread_store
803 .read_with(cx, |thread_store, _cx| thread_store.prompt_store().clone())
804 .ok()
805 .flatten()
806 });
807
808 let search_task = search(
809 mode,
810 query,
811 Arc::<AtomicBool>::default(),
812 recent_entries,
813 prompt_store,
814 thread_store.clone(),
815 text_thread_store.clone(),
816 workspace.clone(),
817 cx,
818 );
819
820 cx.spawn(async move |_, cx| {
821 let matches = search_task.await;
822 let Some(editor) = editor.upgrade() else {
823 return Ok(Vec::new());
824 };
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 excluded_path.as_ref() == Some(&project_path) {
837 return None;
838 }
839
840 Some(Self::completion_for_path(
841 project_path,
842 &mat.path_prefix,
843 is_recent,
844 mat.is_dir,
845 excerpt_id,
846 source_range.clone(),
847 path_style,
848 editor.clone(),
849 context_store.clone(),
850 cx,
851 ))
852 }
853
854 Match::Symbol(SymbolMatch { symbol, .. }) => Self::completion_for_symbol(
855 symbol,
856 excerpt_id,
857 source_range.clone(),
858 editor.clone(),
859 context_store.clone(),
860 workspace.clone(),
861 cx,
862 ),
863
864 Match::Thread(ThreadMatch {
865 thread, is_recent, ..
866 }) => {
867 let thread_store = thread_store.as_ref().and_then(|t| t.upgrade())?;
868 let text_thread_store =
869 text_thread_store.as_ref().and_then(|t| t.upgrade())?;
870 Some(Self::completion_for_thread(
871 thread,
872 excerpt_id,
873 source_range.clone(),
874 is_recent,
875 editor.clone(),
876 context_store.clone(),
877 thread_store,
878 text_thread_store,
879 ))
880 }
881
882 Match::Rules(user_rules) => Some(Self::completion_for_rules(
883 user_rules,
884 excerpt_id,
885 source_range.clone(),
886 editor.clone(),
887 context_store.clone(),
888 )),
889
890 Match::Fetch(url) => Some(Self::completion_for_fetch(
891 source_range.clone(),
892 url,
893 excerpt_id,
894 editor.clone(),
895 context_store.clone(),
896 http_client.clone(),
897 )),
898
899 Match::Entry(EntryMatch { entry, .. }) => Self::completion_for_entry(
900 entry,
901 excerpt_id,
902 source_range.clone(),
903 editor.clone(),
904 context_store.clone(),
905 &workspace,
906 cx,
907 ),
908 })
909 .collect()
910 })?;
911
912 Ok(vec![CompletionResponse {
913 completions,
914 display_options: CompletionDisplayOptions::default(),
915 // Since this does its own filtering (see `filter_completions()` returns false),
916 // there is no benefit to computing whether this set of completions is incomplete.
917 is_incomplete: true,
918 }])
919 })
920 }
921
922 fn is_completion_trigger(
923 &self,
924 buffer: &Entity<language::Buffer>,
925 position: language::Anchor,
926 _text: &str,
927 _trigger_in_words: bool,
928 _menu_is_open: bool,
929 cx: &mut Context<Editor>,
930 ) -> bool {
931 let buffer = buffer.read(cx);
932 let position = position.to_point(buffer);
933 let line_start = Point::new(position.row, 0);
934 let offset_to_line = buffer.point_to_offset(line_start);
935 let mut lines = buffer.text_for_range(line_start..position).lines();
936 if let Some(line) = lines.next() {
937 MentionCompletion::try_parse(line, offset_to_line)
938 .map(|completion| {
939 completion.source_range.start <= offset_to_line + position.column as usize
940 && completion.source_range.end >= offset_to_line + position.column as usize
941 })
942 .unwrap_or(false)
943 } else {
944 false
945 }
946 }
947
948 fn sort_completions(&self) -> bool {
949 false
950 }
951
952 fn filter_completions(&self) -> bool {
953 false
954 }
955}
956
957fn confirm_completion_callback(
958 crease_icon_path: SharedString,
959 crease_text: SharedString,
960 excerpt_id: ExcerptId,
961 start: Anchor,
962 content_len: usize,
963 editor: Entity<Editor>,
964 context_store: Entity<ContextStore>,
965 add_context_fn: impl Fn(&mut Window, &mut App) -> Task<Option<AgentContextHandle>>
966 + Send
967 + Sync
968 + 'static,
969) -> Arc<dyn Fn(CompletionIntent, &mut Window, &mut App) -> bool + Send + Sync> {
970 Arc::new(move |_, window, cx| {
971 let context = add_context_fn(window, cx);
972
973 let crease_text = crease_text.clone();
974 let crease_icon_path = crease_icon_path.clone();
975 let editor = editor.clone();
976 let context_store = context_store.clone();
977 window.defer(cx, move |window, cx| {
978 let crease_id = crate::context_picker::insert_crease_for_mention(
979 excerpt_id,
980 start,
981 content_len,
982 crease_text.clone(),
983 crease_icon_path,
984 editor.clone(),
985 window,
986 cx,
987 );
988 cx.spawn(async move |cx| {
989 let crease_id = crease_id?;
990 let context = context.await?;
991 editor
992 .update(cx, |editor, cx| {
993 if let Some(addon) = editor.addon_mut::<ContextCreasesAddon>() {
994 addon.add_creases(
995 &context_store,
996 AgentContextKey(context),
997 [(crease_id, crease_text)],
998 cx,
999 );
1000 }
1001 })
1002 .ok()
1003 })
1004 .detach();
1005 });
1006 false
1007 })
1008}
1009
1010#[derive(Debug, Default, PartialEq)]
1011struct MentionCompletion {
1012 source_range: Range<usize>,
1013 mode: Option<ContextPickerMode>,
1014 argument: Option<String>,
1015}
1016
1017impl MentionCompletion {
1018 fn try_parse(line: &str, offset_to_line: usize) -> Option<Self> {
1019 let last_mention_start = line.rfind('@')?;
1020 if last_mention_start >= line.len() {
1021 return Some(Self::default());
1022 }
1023 if last_mention_start > 0
1024 && line
1025 .chars()
1026 .nth(last_mention_start - 1)
1027 .is_some_and(|c| !c.is_whitespace())
1028 {
1029 return None;
1030 }
1031
1032 let rest_of_line = &line[last_mention_start + 1..];
1033
1034 let mut mode = None;
1035 let mut argument = None;
1036
1037 let mut parts = rest_of_line.split_whitespace();
1038 let mut end = last_mention_start + 1;
1039 if let Some(mode_text) = parts.next() {
1040 end += mode_text.len();
1041
1042 if let Some(parsed_mode) = ContextPickerMode::try_from(mode_text).ok() {
1043 mode = Some(parsed_mode);
1044 } else {
1045 argument = Some(mode_text.to_string());
1046 }
1047 match rest_of_line[mode_text.len()..].find(|c: char| !c.is_whitespace()) {
1048 Some(whitespace_count) => {
1049 if let Some(argument_text) = parts.next() {
1050 argument = Some(argument_text.to_string());
1051 end += whitespace_count + argument_text.len();
1052 }
1053 }
1054 None => {
1055 // Rest of line is entirely whitespace
1056 end += rest_of_line.len() - mode_text.len();
1057 }
1058 }
1059 }
1060
1061 Some(Self {
1062 source_range: last_mention_start + offset_to_line..end + offset_to_line,
1063 mode,
1064 argument,
1065 })
1066 }
1067}
1068
1069#[cfg(test)]
1070mod tests {
1071 use super::*;
1072 use editor::AnchorRangeExt;
1073 use gpui::{EventEmitter, FocusHandle, Focusable, TestAppContext, VisualTestContext};
1074 use project::{Project, ProjectPath};
1075 use serde_json::json;
1076 use settings::SettingsStore;
1077 use std::{ops::Deref, rc::Rc};
1078 use util::{path, rel_path::rel_path};
1079 use workspace::{AppState, Item};
1080
1081 #[test]
1082 fn test_mention_completion_parse() {
1083 assert_eq!(MentionCompletion::try_parse("Lorem Ipsum", 0), None);
1084
1085 assert_eq!(
1086 MentionCompletion::try_parse("Lorem @", 0),
1087 Some(MentionCompletion {
1088 source_range: 6..7,
1089 mode: None,
1090 argument: None,
1091 })
1092 );
1093
1094 assert_eq!(
1095 MentionCompletion::try_parse("Lorem @file", 0),
1096 Some(MentionCompletion {
1097 source_range: 6..11,
1098 mode: Some(ContextPickerMode::File),
1099 argument: None,
1100 })
1101 );
1102
1103 assert_eq!(
1104 MentionCompletion::try_parse("Lorem @file ", 0),
1105 Some(MentionCompletion {
1106 source_range: 6..12,
1107 mode: Some(ContextPickerMode::File),
1108 argument: None,
1109 })
1110 );
1111
1112 assert_eq!(
1113 MentionCompletion::try_parse("Lorem @file main.rs", 0),
1114 Some(MentionCompletion {
1115 source_range: 6..19,
1116 mode: Some(ContextPickerMode::File),
1117 argument: Some("main.rs".to_string()),
1118 })
1119 );
1120
1121 assert_eq!(
1122 MentionCompletion::try_parse("Lorem @file main.rs ", 0),
1123 Some(MentionCompletion {
1124 source_range: 6..19,
1125 mode: Some(ContextPickerMode::File),
1126 argument: Some("main.rs".to_string()),
1127 })
1128 );
1129
1130 assert_eq!(
1131 MentionCompletion::try_parse("Lorem @file main.rs Ipsum", 0),
1132 Some(MentionCompletion {
1133 source_range: 6..19,
1134 mode: Some(ContextPickerMode::File),
1135 argument: Some("main.rs".to_string()),
1136 })
1137 );
1138
1139 assert_eq!(
1140 MentionCompletion::try_parse("Lorem @main", 0),
1141 Some(MentionCompletion {
1142 source_range: 6..11,
1143 mode: None,
1144 argument: Some("main".to_string()),
1145 })
1146 );
1147
1148 assert_eq!(MentionCompletion::try_parse("test@", 0), None);
1149 }
1150
1151 struct AtMentionEditor(Entity<Editor>);
1152
1153 impl Item for AtMentionEditor {
1154 type Event = ();
1155
1156 fn include_in_nav_history() -> bool {
1157 false
1158 }
1159
1160 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
1161 "Test".into()
1162 }
1163 }
1164
1165 impl EventEmitter<()> for AtMentionEditor {}
1166
1167 impl Focusable for AtMentionEditor {
1168 fn focus_handle(&self, cx: &App) -> FocusHandle {
1169 self.0.read(cx).focus_handle(cx)
1170 }
1171 }
1172
1173 impl Render for AtMentionEditor {
1174 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
1175 self.0.clone().into_any_element()
1176 }
1177 }
1178
1179 #[gpui::test]
1180 async fn test_context_completion_provider(cx: &mut TestAppContext) {
1181 init_test(cx);
1182
1183 let app_state = cx.update(AppState::test);
1184
1185 cx.update(|cx| {
1186 language::init(cx);
1187 editor::init(cx);
1188 workspace::init(app_state.clone(), cx);
1189 Project::init_settings(cx);
1190 });
1191
1192 app_state
1193 .fs
1194 .as_fake()
1195 .insert_tree(
1196 path!("/dir"),
1197 json!({
1198 "editor": "",
1199 "a": {
1200 "one.txt": "",
1201 "two.txt": "",
1202 "three.txt": "",
1203 "four.txt": ""
1204 },
1205 "b": {
1206 "five.txt": "",
1207 "six.txt": "",
1208 "seven.txt": "",
1209 "eight.txt": "",
1210 }
1211 }),
1212 )
1213 .await;
1214
1215 let project = Project::test(app_state.fs.clone(), [path!("/dir").as_ref()], cx).await;
1216 let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
1217 let workspace = window.root(cx).unwrap();
1218
1219 let worktree = project.update(cx, |project, cx| {
1220 let mut worktrees = project.worktrees(cx).collect::<Vec<_>>();
1221 assert_eq!(worktrees.len(), 1);
1222 worktrees.pop().unwrap()
1223 });
1224 let worktree_id = worktree.read_with(cx, |worktree, _| worktree.id());
1225
1226 let mut cx = VisualTestContext::from_window(*window.deref(), cx);
1227
1228 let paths = vec![
1229 rel_path("a/one.txt"),
1230 rel_path("a/two.txt"),
1231 rel_path("a/three.txt"),
1232 rel_path("a/four.txt"),
1233 rel_path("b/five.txt"),
1234 rel_path("b/six.txt"),
1235 rel_path("b/seven.txt"),
1236 rel_path("b/eight.txt"),
1237 ];
1238
1239 let slash = PathStyle::local().separator();
1240
1241 let mut opened_editors = Vec::new();
1242 for path in paths {
1243 let buffer = workspace
1244 .update_in(&mut cx, |workspace, window, cx| {
1245 workspace.open_path(
1246 ProjectPath {
1247 worktree_id,
1248 path: path.into(),
1249 },
1250 None,
1251 false,
1252 window,
1253 cx,
1254 )
1255 })
1256 .await
1257 .unwrap();
1258 opened_editors.push(buffer);
1259 }
1260
1261 let editor = workspace.update_in(&mut cx, |workspace, window, cx| {
1262 let editor = cx.new(|cx| {
1263 Editor::new(
1264 editor::EditorMode::full(),
1265 multi_buffer::MultiBuffer::build_simple("", cx),
1266 None,
1267 window,
1268 cx,
1269 )
1270 });
1271 workspace.active_pane().update(cx, |pane, cx| {
1272 pane.add_item(
1273 Box::new(cx.new(|_| AtMentionEditor(editor.clone()))),
1274 true,
1275 true,
1276 None,
1277 window,
1278 cx,
1279 );
1280 });
1281 editor
1282 });
1283
1284 let context_store = cx.new(|_| ContextStore::new(project.downgrade(), None));
1285
1286 let editor_entity = editor.downgrade();
1287 editor.update_in(&mut cx, |editor, window, cx| {
1288 let last_opened_buffer = opened_editors.last().and_then(|editor| {
1289 editor
1290 .downcast::<Editor>()?
1291 .read(cx)
1292 .buffer()
1293 .read(cx)
1294 .as_singleton()
1295 .as_ref()
1296 .map(Entity::downgrade)
1297 });
1298 window.focus(&editor.focus_handle(cx));
1299 editor.set_completion_provider(Some(Rc::new(ContextPickerCompletionProvider::new(
1300 workspace.downgrade(),
1301 context_store.downgrade(),
1302 None,
1303 None,
1304 editor_entity,
1305 last_opened_buffer,
1306 ))));
1307 });
1308
1309 cx.simulate_input("Lorem ");
1310
1311 editor.update(&mut cx, |editor, cx| {
1312 assert_eq!(editor.text(cx), "Lorem ");
1313 assert!(!editor.has_visible_completions_menu());
1314 });
1315
1316 cx.simulate_input("@");
1317
1318 editor.update(&mut cx, |editor, cx| {
1319 assert_eq!(editor.text(cx), "Lorem @");
1320 assert!(editor.has_visible_completions_menu());
1321 assert_eq!(
1322 current_completion_labels(editor),
1323 &[
1324 format!("seven.txt dir{slash}b{slash}"),
1325 format!("six.txt dir{slash}b{slash}"),
1326 format!("five.txt dir{slash}b{slash}"),
1327 format!("four.txt dir{slash}a{slash}"),
1328 "Files & Directories".into(),
1329 "Symbols".into(),
1330 "Fetch".into()
1331 ]
1332 );
1333 });
1334
1335 // Select and confirm "File"
1336 editor.update_in(&mut cx, |editor, window, cx| {
1337 assert!(editor.has_visible_completions_menu());
1338 editor.context_menu_next(&editor::actions::ContextMenuNext, window, cx);
1339 editor.context_menu_next(&editor::actions::ContextMenuNext, window, cx);
1340 editor.context_menu_next(&editor::actions::ContextMenuNext, window, cx);
1341 editor.context_menu_next(&editor::actions::ContextMenuNext, window, cx);
1342 editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
1343 });
1344
1345 cx.run_until_parked();
1346
1347 editor.update(&mut cx, |editor, cx| {
1348 assert_eq!(editor.text(cx), "Lorem @file ");
1349 assert!(editor.has_visible_completions_menu());
1350 });
1351
1352 cx.simulate_input("one");
1353
1354 editor.update(&mut cx, |editor, cx| {
1355 assert_eq!(editor.text(cx), "Lorem @file one");
1356 assert!(editor.has_visible_completions_menu());
1357 assert_eq!(
1358 current_completion_labels(editor),
1359 vec![format!("one.txt dir{slash}a{slash}")]
1360 );
1361 });
1362
1363 editor.update_in(&mut cx, |editor, window, cx| {
1364 assert!(editor.has_visible_completions_menu());
1365 editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
1366 });
1367
1368 editor.update(&mut cx, |editor, cx| {
1369 assert_eq!(
1370 editor.text(cx),
1371 format!("Lorem [@one.txt](@file:dir{slash}a{slash}one.txt) ")
1372 );
1373 assert!(!editor.has_visible_completions_menu());
1374 assert_eq!(
1375 fold_ranges(editor, cx),
1376 vec![Point::new(0, 6)..Point::new(0, 37)]
1377 );
1378 });
1379
1380 cx.simulate_input(" ");
1381
1382 editor.update(&mut cx, |editor, cx| {
1383 assert_eq!(
1384 editor.text(cx),
1385 format!("Lorem [@one.txt](@file:dir{slash}a{slash}one.txt) ")
1386 );
1387 assert!(!editor.has_visible_completions_menu());
1388 assert_eq!(
1389 fold_ranges(editor, cx),
1390 vec![Point::new(0, 6)..Point::new(0, 37)]
1391 );
1392 });
1393
1394 cx.simulate_input("Ipsum ");
1395
1396 editor.update(&mut cx, |editor, cx| {
1397 assert_eq!(
1398 editor.text(cx),
1399 format!("Lorem [@one.txt](@file:dir{slash}a{slash}one.txt) Ipsum "),
1400 );
1401 assert!(!editor.has_visible_completions_menu());
1402 assert_eq!(
1403 fold_ranges(editor, cx),
1404 vec![Point::new(0, 6)..Point::new(0, 37)]
1405 );
1406 });
1407
1408 cx.simulate_input("@file ");
1409
1410 editor.update(&mut cx, |editor, cx| {
1411 assert_eq!(
1412 editor.text(cx),
1413 format!("Lorem [@one.txt](@file:dir{slash}a{slash}one.txt) Ipsum @file "),
1414 );
1415 assert!(editor.has_visible_completions_menu());
1416 assert_eq!(
1417 fold_ranges(editor, cx),
1418 vec![Point::new(0, 6)..Point::new(0, 37)]
1419 );
1420 });
1421
1422 editor.update_in(&mut cx, |editor, window, cx| {
1423 editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
1424 });
1425
1426 cx.run_until_parked();
1427
1428 editor.update(&mut cx, |editor, cx| {
1429 assert_eq!(
1430 editor.text(cx),
1431 format!("Lorem [@one.txt](@file:dir{slash}a{slash}one.txt) Ipsum [@seven.txt](@file:dir{slash}b{slash}seven.txt) ")
1432 );
1433 assert!(!editor.has_visible_completions_menu());
1434 assert_eq!(
1435 fold_ranges(editor, cx),
1436 vec![
1437 Point::new(0, 6)..Point::new(0, 37),
1438 Point::new(0, 45)..Point::new(0, 80)
1439 ]
1440 );
1441 });
1442
1443 cx.simulate_input("\n@");
1444
1445 editor.update(&mut cx, |editor, cx| {
1446 assert_eq!(
1447 editor.text(cx),
1448 format!("Lorem [@one.txt](@file:dir{slash}a{slash}one.txt) Ipsum [@seven.txt](@file:dir{slash}b{slash}seven.txt) \n@")
1449 );
1450 assert!(editor.has_visible_completions_menu());
1451 assert_eq!(
1452 fold_ranges(editor, cx),
1453 vec![
1454 Point::new(0, 6)..Point::new(0, 37),
1455 Point::new(0, 45)..Point::new(0, 80)
1456 ]
1457 );
1458 });
1459
1460 editor.update_in(&mut cx, |editor, window, cx| {
1461 editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
1462 });
1463
1464 cx.run_until_parked();
1465
1466 editor.update(&mut cx, |editor, cx| {
1467 assert_eq!(
1468 editor.text(cx),
1469 format!("Lorem [@one.txt](@file:dir{slash}a{slash}one.txt) Ipsum [@seven.txt](@file:dir{slash}b{slash}seven.txt) \n[@six.txt](@file:dir{slash}b{slash}six.txt) ")
1470 );
1471 assert!(!editor.has_visible_completions_menu());
1472 assert_eq!(
1473 fold_ranges(editor, cx),
1474 vec![
1475 Point::new(0, 6)..Point::new(0, 37),
1476 Point::new(0, 45)..Point::new(0, 80),
1477 Point::new(1, 0)..Point::new(1, 31)
1478 ]
1479 );
1480 });
1481 }
1482
1483 fn fold_ranges(editor: &Editor, cx: &mut App) -> Vec<Range<Point>> {
1484 let snapshot = editor.buffer().read(cx).snapshot(cx);
1485 editor.display_map.update(cx, |display_map, cx| {
1486 display_map
1487 .snapshot(cx)
1488 .folds_in_range(0..snapshot.len())
1489 .map(|fold| fold.range.to_point(&snapshot))
1490 .collect()
1491 })
1492 }
1493
1494 fn current_completion_labels(editor: &Editor) -> Vec<String> {
1495 let completions = editor.current_completions().expect("Missing completions");
1496 completions
1497 .into_iter()
1498 .map(|completion| completion.label.text)
1499 .collect::<Vec<_>>()
1500 }
1501
1502 pub(crate) fn init_test(cx: &mut TestAppContext) {
1503 cx.update(|cx| {
1504 let store = SettingsStore::test(cx);
1505 cx.set_global(store);
1506 theme::init(theme::LoadThemes::JustBase, cx);
1507 client::init_settings(cx);
1508 language::init(cx);
1509 Project::init_settings(cx);
1510 workspace::init_settings(cx);
1511 editor::init_settings(cx);
1512 });
1513 }
1514}