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