1use std::cmp::Reverse;
2use std::ops::Range;
3use std::path::PathBuf;
4use std::sync::Arc;
5use std::sync::atomic::AtomicBool;
6
7use crate::ThreadHistory;
8use acp_thread::MentionUri;
9use agent_client_protocol as acp;
10use anyhow::Result;
11use editor::{
12 CompletionProvider, Editor, ExcerptId, code_context_menus::COMPLETION_MENU_MAX_WIDTH,
13};
14use futures::FutureExt as _;
15use fuzzy::{PathMatch, StringMatch, StringMatchCandidate};
16use gpui::{App, BackgroundExecutor, Entity, SharedString, Task, WeakEntity};
17use language::{Buffer, CodeLabel, CodeLabelBuilder, HighlightId};
18use lsp::CompletionContext;
19use multi_buffer::ToOffset as _;
20use ordered_float::OrderedFloat;
21use project::lsp_store::{CompletionDocumentation, SymbolLocation};
22use project::{
23 Completion, CompletionDisplayOptions, CompletionIntent, CompletionResponse, DiagnosticSummary,
24 PathMatchCandidateSet, Project, ProjectPath, Symbol, WorktreeId,
25};
26use prompt_store::{PromptStore, UserPromptId};
27use rope::Point;
28use settings::{Settings, TerminalDockPosition};
29use terminal::terminal_settings::TerminalSettings;
30use terminal_view::terminal_panel::TerminalPanel;
31use text::{Anchor, ToOffset as _, ToPoint as _};
32use ui::IconName;
33use ui::prelude::*;
34use util::ResultExt as _;
35use util::paths::PathStyle;
36use util::rel_path::RelPath;
37use util::truncate_and_remove_front;
38use workspace::Workspace;
39use workspace::dock::DockPosition;
40
41use crate::AgentPanel;
42use crate::mention_set::MentionSet;
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub(crate) enum PromptContextEntry {
46 Mode(PromptContextType),
47 Action(PromptContextAction),
48}
49
50impl PromptContextEntry {
51 pub fn keyword(&self) -> &'static str {
52 match self {
53 Self::Mode(mode) => mode.keyword(),
54 Self::Action(action) => action.keyword(),
55 }
56 }
57}
58
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub(crate) enum PromptContextType {
61 File,
62 Symbol,
63 Fetch,
64 Thread,
65 Rules,
66 Diagnostics,
67 BranchDiff,
68}
69
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub(crate) enum PromptContextAction {
72 AddSelections,
73}
74
75impl PromptContextAction {
76 pub fn keyword(&self) -> &'static str {
77 match self {
78 Self::AddSelections => "selection",
79 }
80 }
81
82 pub fn label(&self) -> &'static str {
83 match self {
84 Self::AddSelections => "Selection",
85 }
86 }
87
88 pub fn icon(&self) -> IconName {
89 match self {
90 Self::AddSelections => IconName::Reader,
91 }
92 }
93}
94
95impl TryFrom<&str> for PromptContextType {
96 type Error = String;
97
98 fn try_from(value: &str) -> Result<Self, Self::Error> {
99 match value {
100 "file" => Ok(Self::File),
101 "symbol" => Ok(Self::Symbol),
102 "fetch" => Ok(Self::Fetch),
103 "thread" => Ok(Self::Thread),
104 "rule" => Ok(Self::Rules),
105 "diagnostics" => Ok(Self::Diagnostics),
106 "diff" => Ok(Self::BranchDiff),
107 _ => Err(format!("Invalid context picker mode: {}", value)),
108 }
109 }
110}
111
112impl PromptContextType {
113 pub fn keyword(&self) -> &'static str {
114 match self {
115 Self::File => "file",
116 Self::Symbol => "symbol",
117 Self::Fetch => "fetch",
118 Self::Thread => "thread",
119 Self::Rules => "rule",
120 Self::Diagnostics => "diagnostics",
121 Self::BranchDiff => "branch diff",
122 }
123 }
124
125 pub fn label(&self) -> &'static str {
126 match self {
127 Self::File => "Files & Directories",
128 Self::Symbol => "Symbols",
129 Self::Fetch => "Fetch",
130 Self::Thread => "Threads",
131 Self::Rules => "Rules",
132 Self::Diagnostics => "Diagnostics",
133 Self::BranchDiff => "Branch Diff",
134 }
135 }
136
137 pub fn icon(&self) -> IconName {
138 match self {
139 Self::File => IconName::File,
140 Self::Symbol => IconName::Code,
141 Self::Fetch => IconName::ToolWeb,
142 Self::Thread => IconName::Thread,
143 Self::Rules => IconName::Reader,
144 Self::Diagnostics => IconName::Warning,
145 Self::BranchDiff => IconName::GitBranch,
146 }
147 }
148}
149
150pub(crate) enum Match {
151 File(FileMatch),
152 Symbol(SymbolMatch),
153 Thread(SessionMatch),
154 RecentThread(SessionMatch),
155 Fetch(SharedString),
156 Rules(RulesContextEntry),
157 Entry(EntryMatch),
158 BranchDiff(BranchDiffMatch),
159}
160
161#[derive(Debug, Clone)]
162pub struct BranchDiffMatch {
163 pub base_ref: SharedString,
164}
165
166impl Match {
167 pub fn score(&self) -> f64 {
168 match self {
169 Match::File(file) => file.mat.score,
170 Match::Entry(mode) => mode.mat.as_ref().map(|mat| mat.score).unwrap_or(1.),
171 Match::Thread(_) => 1.,
172 Match::RecentThread(_) => 1.,
173 Match::Symbol(_) => 1.,
174 Match::Rules(_) => 1.,
175 Match::Fetch(_) => 1.,
176 Match::BranchDiff(_) => 1.,
177 }
178 }
179}
180
181#[derive(Debug, Clone)]
182pub struct SessionMatch {
183 session_id: acp::SessionId,
184 title: SharedString,
185}
186
187pub struct EntryMatch {
188 mat: Option<StringMatch>,
189 entry: PromptContextEntry,
190}
191
192fn session_title(title: Option<SharedString>) -> SharedString {
193 title
194 .filter(|title| !title.is_empty())
195 .unwrap_or_else(|| SharedString::new_static("New Thread"))
196}
197
198#[derive(Debug, Clone)]
199pub struct RulesContextEntry {
200 pub prompt_id: UserPromptId,
201 pub title: SharedString,
202}
203
204#[derive(Debug, Clone)]
205pub struct AvailableCommand {
206 pub name: Arc<str>,
207 pub description: Arc<str>,
208 pub requires_argument: bool,
209}
210
211pub trait PromptCompletionProviderDelegate: Send + Sync + 'static {
212 fn supports_context(&self, mode: PromptContextType, cx: &App) -> bool {
213 self.supported_modes(cx).contains(&mode)
214 }
215 fn supported_modes(&self, cx: &App) -> Vec<PromptContextType>;
216 fn supports_images(&self, cx: &App) -> bool;
217
218 fn available_commands(&self, cx: &App) -> Vec<AvailableCommand>;
219 fn confirm_command(&self, cx: &mut App);
220}
221
222pub struct PromptCompletionProvider<T: PromptCompletionProviderDelegate> {
223 source: Arc<T>,
224 editor: WeakEntity<Editor>,
225 mention_set: Entity<MentionSet>,
226 history: Option<WeakEntity<ThreadHistory>>,
227 prompt_store: Option<Entity<PromptStore>>,
228 workspace: WeakEntity<Workspace>,
229}
230
231impl<T: PromptCompletionProviderDelegate> PromptCompletionProvider<T> {
232 pub fn new(
233 source: T,
234 editor: WeakEntity<Editor>,
235 mention_set: Entity<MentionSet>,
236 history: Option<WeakEntity<ThreadHistory>>,
237 prompt_store: Option<Entity<PromptStore>>,
238 workspace: WeakEntity<Workspace>,
239 ) -> Self {
240 Self {
241 source: Arc::new(source),
242 editor,
243 mention_set,
244 workspace,
245 history,
246 prompt_store,
247 }
248 }
249
250 fn completion_for_entry(
251 entry: PromptContextEntry,
252 source_range: Range<Anchor>,
253 editor: WeakEntity<Editor>,
254 mention_set: WeakEntity<MentionSet>,
255 workspace: &Entity<Workspace>,
256 cx: &mut App,
257 ) -> Option<Completion> {
258 match entry {
259 PromptContextEntry::Mode(mode) => Some(Completion {
260 replace_range: source_range,
261 new_text: format!("@{} ", mode.keyword()),
262 label: CodeLabel::plain(mode.label().to_string(), None),
263 icon_path: Some(mode.icon().path().into()),
264 documentation: None,
265 source: project::CompletionSource::Custom,
266 match_start: None,
267 snippet_deduplication_key: None,
268 insert_text_mode: None,
269 // This ensures that when a user accepts this completion, the
270 // completion menu will still be shown after "@category " is
271 // inserted
272 confirm: Some(Arc::new(|_, _, _| true)),
273 }),
274 PromptContextEntry::Action(action) => Self::completion_for_action(
275 action,
276 source_range,
277 editor,
278 mention_set,
279 workspace,
280 cx,
281 ),
282 }
283 }
284
285 fn completion_for_thread(
286 session_id: acp::SessionId,
287 title: Option<SharedString>,
288 source_range: Range<Anchor>,
289 recent: bool,
290 source: Arc<T>,
291 editor: WeakEntity<Editor>,
292 mention_set: WeakEntity<MentionSet>,
293 workspace: Entity<Workspace>,
294 cx: &mut App,
295 ) -> Completion {
296 let title = session_title(title);
297 let uri = MentionUri::Thread {
298 id: session_id,
299 name: title.to_string(),
300 };
301
302 let icon_for_completion = if recent {
303 IconName::HistoryRerun.path().into()
304 } else {
305 uri.icon_path(cx)
306 };
307
308 let new_text = format!("{} ", uri.as_link());
309
310 let new_text_len = new_text.len();
311 Completion {
312 replace_range: source_range.clone(),
313 new_text,
314 label: CodeLabel::plain(title.to_string(), None),
315 documentation: None,
316 insert_text_mode: None,
317 source: project::CompletionSource::Custom,
318 match_start: None,
319 snippet_deduplication_key: None,
320 icon_path: Some(icon_for_completion),
321 confirm: Some(confirm_completion_callback(
322 title,
323 source_range.start,
324 new_text_len - 1,
325 uri,
326 source,
327 editor,
328 mention_set,
329 workspace,
330 )),
331 }
332 }
333
334 fn completion_for_rules(
335 rule: RulesContextEntry,
336 source_range: Range<Anchor>,
337 source: Arc<T>,
338 editor: WeakEntity<Editor>,
339 mention_set: WeakEntity<MentionSet>,
340 workspace: Entity<Workspace>,
341 cx: &mut App,
342 ) -> Completion {
343 let uri = MentionUri::Rule {
344 id: rule.prompt_id.into(),
345 name: rule.title.to_string(),
346 };
347 let new_text = format!("{} ", uri.as_link());
348 let new_text_len = new_text.len();
349 let icon_path = uri.icon_path(cx);
350 Completion {
351 replace_range: source_range.clone(),
352 new_text,
353 label: CodeLabel::plain(rule.title.to_string(), None),
354 documentation: None,
355 insert_text_mode: None,
356 source: project::CompletionSource::Custom,
357 match_start: None,
358 snippet_deduplication_key: None,
359 icon_path: Some(icon_path),
360 confirm: Some(confirm_completion_callback(
361 rule.title,
362 source_range.start,
363 new_text_len - 1,
364 uri,
365 source,
366 editor,
367 mention_set,
368 workspace,
369 )),
370 }
371 }
372
373 pub(crate) fn completion_for_path(
374 project_path: ProjectPath,
375 path_prefix: &RelPath,
376 is_recent: bool,
377 is_directory: bool,
378 source_range: Range<Anchor>,
379 source: Arc<T>,
380 editor: WeakEntity<Editor>,
381 mention_set: WeakEntity<MentionSet>,
382 workspace: Entity<Workspace>,
383 project: Entity<Project>,
384 label_max_chars: usize,
385 cx: &mut App,
386 ) -> Option<Completion> {
387 let path_style = project.read(cx).path_style(cx);
388 let (file_name, directory) =
389 extract_file_name_and_directory(&project_path.path, path_prefix, path_style);
390
391 let label = build_code_label_for_path(
392 &file_name,
393 directory.as_ref().map(|s| s.as_ref()),
394 None,
395 label_max_chars,
396 cx,
397 );
398
399 let abs_path = project.read(cx).absolute_path(&project_path, cx)?;
400
401 let uri = if is_directory {
402 MentionUri::Directory { abs_path }
403 } else {
404 MentionUri::File { abs_path }
405 };
406
407 let crease_icon_path = uri.icon_path(cx);
408 let completion_icon_path = if is_recent {
409 IconName::HistoryRerun.path().into()
410 } else {
411 crease_icon_path
412 };
413
414 let new_text = format!("{} ", uri.as_link());
415 let new_text_len = new_text.len();
416 Some(Completion {
417 replace_range: source_range.clone(),
418 new_text,
419 label,
420 documentation: None,
421 source: project::CompletionSource::Custom,
422 icon_path: Some(completion_icon_path),
423 match_start: None,
424 snippet_deduplication_key: None,
425 insert_text_mode: None,
426 confirm: Some(confirm_completion_callback(
427 file_name,
428 source_range.start,
429 new_text_len - 1,
430 uri,
431 source,
432 editor,
433 mention_set,
434 workspace,
435 )),
436 })
437 }
438
439 fn completion_for_symbol(
440 symbol: Symbol,
441 source_range: Range<Anchor>,
442 source: Arc<T>,
443 editor: WeakEntity<Editor>,
444 mention_set: WeakEntity<MentionSet>,
445 workspace: Entity<Workspace>,
446 label_max_chars: usize,
447 cx: &mut App,
448 ) -> Option<Completion> {
449 let project = workspace.read(cx).project().clone();
450
451 let (abs_path, file_name) = match &symbol.path {
452 SymbolLocation::InProject(project_path) => (
453 project.read(cx).absolute_path(&project_path, cx)?,
454 project_path.path.file_name()?.to_string().into(),
455 ),
456 SymbolLocation::OutsideProject {
457 abs_path,
458 signature: _,
459 } => (
460 PathBuf::from(abs_path.as_ref()),
461 abs_path.file_name().map(|f| f.to_string_lossy())?,
462 ),
463 };
464
465 let label = build_code_label_for_path(
466 &symbol.name,
467 Some(&file_name),
468 Some(symbol.range.start.0.row + 1),
469 label_max_chars,
470 cx,
471 );
472
473 let uri = MentionUri::Symbol {
474 abs_path,
475 name: symbol.name.clone(),
476 line_range: symbol.range.start.0.row..=symbol.range.end.0.row,
477 };
478 let new_text = format!("{} ", uri.as_link());
479 let new_text_len = new_text.len();
480 let icon_path = uri.icon_path(cx);
481 Some(Completion {
482 replace_range: source_range.clone(),
483 new_text,
484 label,
485 documentation: None,
486 source: project::CompletionSource::Custom,
487 icon_path: Some(icon_path),
488 match_start: None,
489 snippet_deduplication_key: None,
490 insert_text_mode: None,
491 confirm: Some(confirm_completion_callback(
492 symbol.name.into(),
493 source_range.start,
494 new_text_len - 1,
495 uri,
496 source,
497 editor,
498 mention_set,
499 workspace,
500 )),
501 })
502 }
503
504 fn completion_for_fetch(
505 source_range: Range<Anchor>,
506 url_to_fetch: SharedString,
507 source: Arc<T>,
508 editor: WeakEntity<Editor>,
509 mention_set: WeakEntity<MentionSet>,
510 workspace: Entity<Workspace>,
511 cx: &mut App,
512 ) -> Option<Completion> {
513 let new_text = format!("@fetch {} ", url_to_fetch);
514 let url_to_fetch = url::Url::parse(url_to_fetch.as_ref())
515 .or_else(|_| url::Url::parse(&format!("https://{url_to_fetch}")))
516 .ok()?;
517 let mention_uri = MentionUri::Fetch {
518 url: url_to_fetch.clone(),
519 };
520 let icon_path = mention_uri.icon_path(cx);
521 Some(Completion {
522 replace_range: source_range.clone(),
523 new_text: new_text.clone(),
524 label: CodeLabel::plain(url_to_fetch.to_string(), None),
525 documentation: None,
526 source: project::CompletionSource::Custom,
527 icon_path: Some(icon_path),
528 match_start: None,
529 snippet_deduplication_key: None,
530 insert_text_mode: None,
531 confirm: Some(confirm_completion_callback(
532 url_to_fetch.to_string().into(),
533 source_range.start,
534 new_text.len() - 1,
535 mention_uri,
536 source,
537 editor,
538 mention_set,
539 workspace,
540 )),
541 })
542 }
543
544 pub(crate) fn completion_for_action(
545 action: PromptContextAction,
546 source_range: Range<Anchor>,
547 editor: WeakEntity<Editor>,
548 mention_set: WeakEntity<MentionSet>,
549 workspace: &Entity<Workspace>,
550 cx: &mut App,
551 ) -> Option<Completion> {
552 let (new_text, on_action) = match action {
553 PromptContextAction::AddSelections => {
554 // Collect non-empty editor selections
555 let editor_selections: Vec<_> = selection_ranges(workspace, cx)
556 .into_iter()
557 .filter(|(buffer, range)| {
558 let snapshot = buffer.read(cx).snapshot();
559 range.start.to_offset(&snapshot) != range.end.to_offset(&snapshot)
560 })
561 .collect();
562
563 // Collect terminal selections from all terminal views if the terminal panel is visible
564 let terminal_selections: Vec<String> =
565 terminal_selections_if_panel_open(workspace, cx);
566
567 const EDITOR_PLACEHOLDER: &str = "selection ";
568 const TERMINAL_PLACEHOLDER: &str = "terminal ";
569
570 let selections = editor_selections
571 .into_iter()
572 .enumerate()
573 .map(|(ix, (buffer, range))| {
574 (
575 buffer,
576 range,
577 (EDITOR_PLACEHOLDER.len() * ix)
578 ..(EDITOR_PLACEHOLDER.len() * (ix + 1) - 1),
579 )
580 })
581 .collect::<Vec<_>>();
582
583 let mut new_text: String = EDITOR_PLACEHOLDER.repeat(selections.len());
584
585 // Add terminal placeholders for each terminal selection
586 let terminal_ranges: Vec<(String, std::ops::Range<usize>)> = terminal_selections
587 .into_iter()
588 .map(|text| {
589 let start = new_text.len();
590 new_text.push_str(TERMINAL_PLACEHOLDER);
591 (text, start..(new_text.len() - 1))
592 })
593 .collect();
594
595 let callback = Arc::new({
596 let source_range = source_range.clone();
597 move |_: CompletionIntent, window: &mut Window, cx: &mut App| {
598 let editor = editor.clone();
599 let selections = selections.clone();
600 let mention_set = mention_set.clone();
601 let source_range = source_range.clone();
602 let terminal_ranges = terminal_ranges.clone();
603 window.defer(cx, move |window, cx| {
604 if let Some(editor) = editor.upgrade() {
605 // Insert editor selections
606 if !selections.is_empty() {
607 mention_set
608 .update(cx, |store, cx| {
609 store.confirm_mention_for_selection(
610 source_range.clone(),
611 selections,
612 editor.clone(),
613 window,
614 cx,
615 )
616 })
617 .ok();
618 }
619
620 // Insert terminal selections
621 for (terminal_text, terminal_range) in terminal_ranges {
622 let snapshot = editor.read(cx).buffer().read(cx).snapshot(cx);
623 let Some(start) =
624 snapshot.as_singleton_anchor(source_range.start)
625 else {
626 return;
627 };
628 let offset = start.to_offset(&snapshot);
629
630 let line_count = terminal_text.lines().count() as u32;
631 let mention_uri = MentionUri::TerminalSelection { line_count };
632 let range = snapshot.anchor_after(offset + terminal_range.start)
633 ..snapshot.anchor_after(offset + terminal_range.end);
634
635 let crease = crate::mention_set::crease_for_mention(
636 mention_uri.name().into(),
637 mention_uri.icon_path(cx),
638 None,
639 range,
640 editor.downgrade(),
641 );
642
643 let crease_id = editor.update(cx, |editor, cx| {
644 let crease_ids =
645 editor.insert_creases(vec![crease.clone()], cx);
646 editor.fold_creases(vec![crease], false, window, cx);
647 crease_ids.first().copied().unwrap()
648 });
649
650 mention_set
651 .update(cx, |mention_set, _| {
652 mention_set.insert_mention(
653 crease_id,
654 mention_uri.clone(),
655 gpui::Task::ready(Ok(
656 crate::mention_set::Mention::Text {
657 content: terminal_text,
658 tracked_buffers: vec![],
659 },
660 ))
661 .shared(),
662 );
663 })
664 .ok();
665 }
666 }
667 });
668 false
669 }
670 });
671
672 (
673 new_text,
674 callback
675 as Arc<
676 dyn Fn(CompletionIntent, &mut Window, &mut App) -> bool + Send + Sync,
677 >,
678 )
679 }
680 };
681
682 Some(Completion {
683 replace_range: source_range,
684 new_text,
685 label: CodeLabel::plain(action.label().to_string(), None),
686 icon_path: Some(action.icon().path().into()),
687 documentation: None,
688 source: project::CompletionSource::Custom,
689 match_start: None,
690 snippet_deduplication_key: None,
691 insert_text_mode: None,
692 // This ensures that when a user accepts this completion, the
693 // completion menu will still be shown after "@category " is
694 // inserted
695 confirm: Some(on_action),
696 })
697 }
698
699 fn completion_for_diagnostics(
700 source_range: Range<Anchor>,
701 source: Arc<T>,
702 editor: WeakEntity<Editor>,
703 mention_set: WeakEntity<MentionSet>,
704 workspace: Entity<Workspace>,
705 cx: &mut App,
706 ) -> Vec<Completion> {
707 let summary = workspace
708 .read(cx)
709 .project()
710 .read(cx)
711 .diagnostic_summary(false, cx);
712 if summary.error_count == 0 && summary.warning_count == 0 {
713 return Vec::new();
714 }
715 let icon_path = MentionUri::Diagnostics {
716 include_errors: true,
717 include_warnings: false,
718 }
719 .icon_path(cx);
720
721 let mut completions = Vec::new();
722
723 let cases = [
724 (summary.error_count > 0, true, false),
725 (summary.warning_count > 0, false, true),
726 (
727 summary.error_count > 0 && summary.warning_count > 0,
728 true,
729 true,
730 ),
731 ];
732
733 for (condition, include_errors, include_warnings) in cases {
734 if condition {
735 completions.push(Self::build_diagnostics_completion(
736 diagnostics_submenu_label(summary, include_errors, include_warnings),
737 source_range.clone(),
738 source.clone(),
739 editor.clone(),
740 mention_set.clone(),
741 workspace.clone(),
742 icon_path.clone(),
743 include_errors,
744 include_warnings,
745 summary,
746 ));
747 }
748 }
749
750 completions
751 }
752
753 fn build_diagnostics_completion(
754 menu_label: String,
755 source_range: Range<Anchor>,
756 source: Arc<T>,
757 editor: WeakEntity<Editor>,
758 mention_set: WeakEntity<MentionSet>,
759 workspace: Entity<Workspace>,
760 icon_path: SharedString,
761 include_errors: bool,
762 include_warnings: bool,
763 summary: DiagnosticSummary,
764 ) -> Completion {
765 let uri = MentionUri::Diagnostics {
766 include_errors,
767 include_warnings,
768 };
769 let crease_text = diagnostics_crease_label(summary, include_errors, include_warnings);
770 let display_text = format!("@{}", crease_text);
771 let new_text = format!("[{}]({}) ", display_text, uri.to_uri());
772 let new_text_len = new_text.len();
773 Completion {
774 replace_range: source_range.clone(),
775 new_text,
776 label: CodeLabel::plain(menu_label, None),
777 documentation: None,
778 source: project::CompletionSource::Custom,
779 icon_path: Some(icon_path),
780 match_start: None,
781 snippet_deduplication_key: None,
782 insert_text_mode: None,
783 confirm: Some(confirm_completion_callback(
784 crease_text,
785 source_range.start,
786 new_text_len - 1,
787 uri,
788 source,
789 editor,
790 mention_set,
791 workspace,
792 )),
793 }
794 }
795
796 fn build_branch_diff_completion(
797 base_ref: SharedString,
798 source_range: Range<Anchor>,
799 source: Arc<T>,
800 editor: WeakEntity<Editor>,
801 mention_set: WeakEntity<MentionSet>,
802 workspace: Entity<Workspace>,
803 cx: &mut App,
804 ) -> Completion {
805 let uri = MentionUri::GitDiff {
806 base_ref: base_ref.to_string(),
807 };
808 let crease_text: SharedString = format!("Branch Diff (vs {})", base_ref).into();
809 let display_text = format!("@{}", crease_text);
810 let new_text = format!("[{}]({}) ", display_text, uri.to_uri());
811 let new_text_len = new_text.len();
812 let icon_path = uri.icon_path(cx);
813
814 Completion {
815 replace_range: source_range.clone(),
816 new_text,
817 label: CodeLabel::plain(crease_text.to_string(), None),
818 documentation: None,
819 source: project::CompletionSource::Custom,
820 icon_path: Some(icon_path),
821 match_start: None,
822 snippet_deduplication_key: None,
823 insert_text_mode: None,
824 confirm: Some(confirm_completion_callback(
825 crease_text,
826 source_range.start,
827 new_text_len - 1,
828 uri,
829 source,
830 editor,
831 mention_set,
832 workspace,
833 )),
834 }
835 }
836
837 fn search_slash_commands(&self, query: String, cx: &mut App) -> Task<Vec<AvailableCommand>> {
838 let commands = self.source.available_commands(cx);
839 if commands.is_empty() {
840 return Task::ready(Vec::new());
841 }
842
843 cx.spawn(async move |cx| {
844 let candidates = commands
845 .iter()
846 .enumerate()
847 .map(|(id, command)| StringMatchCandidate::new(id, &command.name))
848 .collect::<Vec<_>>();
849
850 let matches = fuzzy::match_strings(
851 &candidates,
852 &query,
853 false,
854 true,
855 100,
856 &Arc::new(AtomicBool::default()),
857 cx.background_executor().clone(),
858 )
859 .await;
860
861 matches
862 .into_iter()
863 .map(|mat| commands[mat.candidate_id].clone())
864 .collect()
865 })
866 }
867
868 fn fetch_branch_diff_match(
869 &self,
870 workspace: &Entity<Workspace>,
871 cx: &mut App,
872 ) -> Option<Task<Option<BranchDiffMatch>>> {
873 let project = workspace.read(cx).project().clone();
874 let repo = project.read(cx).active_repository(cx)?;
875
876 let default_branch_receiver = repo.update(cx, |repo, _| repo.default_branch(false));
877
878 Some(cx.spawn(async move |_cx| {
879 let base_ref = default_branch_receiver
880 .await
881 .ok()
882 .and_then(|r| r.ok())
883 .flatten()?;
884
885 Some(BranchDiffMatch { base_ref })
886 }))
887 }
888
889 fn search_mentions(
890 &self,
891 mode: Option<PromptContextType>,
892 query: String,
893 cancellation_flag: Arc<AtomicBool>,
894 cx: &mut App,
895 ) -> Task<Vec<Match>> {
896 let Some(workspace) = self.workspace.upgrade() else {
897 return Task::ready(Vec::default());
898 };
899 match mode {
900 Some(PromptContextType::File) => {
901 let search_files_task = search_files(query, cancellation_flag, &workspace, cx);
902 cx.background_spawn(async move {
903 search_files_task
904 .await
905 .into_iter()
906 .map(Match::File)
907 .collect()
908 })
909 }
910
911 Some(PromptContextType::Symbol) => {
912 let search_symbols_task = search_symbols(query, cancellation_flag, &workspace, cx);
913 cx.background_spawn(async move {
914 search_symbols_task
915 .await
916 .into_iter()
917 .map(Match::Symbol)
918 .collect()
919 })
920 }
921
922 Some(PromptContextType::Thread) => {
923 if let Some(history) = self.history.as_ref().and_then(|h| h.upgrade()) {
924 let sessions = history
925 .read(cx)
926 .sessions()
927 .iter()
928 .map(|session| SessionMatch {
929 session_id: session.session_id.clone(),
930 title: session_title(session.title.clone()),
931 })
932 .collect::<Vec<_>>();
933 let search_task =
934 filter_sessions_by_query(query, cancellation_flag, sessions, cx);
935 cx.spawn(async move |_cx| {
936 search_task.await.into_iter().map(Match::Thread).collect()
937 })
938 } else {
939 Task::ready(Vec::new())
940 }
941 }
942
943 Some(PromptContextType::Fetch) => {
944 if !query.is_empty() {
945 Task::ready(vec![Match::Fetch(query.into())])
946 } else {
947 Task::ready(Vec::new())
948 }
949 }
950
951 Some(PromptContextType::Rules) => {
952 if let Some(prompt_store) = self.prompt_store.as_ref() {
953 let search_rules_task =
954 search_rules(query, cancellation_flag, prompt_store, cx);
955 cx.background_spawn(async move {
956 search_rules_task
957 .await
958 .into_iter()
959 .map(Match::Rules)
960 .collect::<Vec<_>>()
961 })
962 } else {
963 Task::ready(Vec::new())
964 }
965 }
966
967 Some(PromptContextType::Diagnostics) => Task::ready(Vec::new()),
968
969 Some(PromptContextType::BranchDiff) => Task::ready(Vec::new()),
970
971 None if query.is_empty() => {
972 let recent_task = self.recent_context_picker_entries(&workspace, cx);
973 let entries = self
974 .available_context_picker_entries(&workspace, cx)
975 .into_iter()
976 .map(|mode| {
977 Match::Entry(EntryMatch {
978 entry: mode,
979 mat: None,
980 })
981 })
982 .collect::<Vec<_>>();
983
984 let branch_diff_task = if self
985 .source
986 .supports_context(PromptContextType::BranchDiff, cx)
987 {
988 self.fetch_branch_diff_match(&workspace, cx)
989 } else {
990 None
991 };
992
993 cx.spawn(async move |_cx| {
994 let mut matches = recent_task.await;
995 matches.extend(entries);
996
997 if let Some(branch_diff_task) = branch_diff_task {
998 if let Some(branch_diff_match) = branch_diff_task.await {
999 matches.push(Match::BranchDiff(branch_diff_match));
1000 }
1001 }
1002
1003 matches
1004 })
1005 }
1006 None => {
1007 let executor = cx.background_executor().clone();
1008
1009 let search_files_task =
1010 search_files(query.clone(), cancellation_flag, &workspace, cx);
1011
1012 let entries = self.available_context_picker_entries(&workspace, cx);
1013 let entry_candidates = entries
1014 .iter()
1015 .enumerate()
1016 .map(|(ix, entry)| StringMatchCandidate::new(ix, entry.keyword()))
1017 .collect::<Vec<_>>();
1018
1019 let branch_diff_task = if self
1020 .source
1021 .supports_context(PromptContextType::BranchDiff, cx)
1022 {
1023 self.fetch_branch_diff_match(&workspace, cx)
1024 } else {
1025 None
1026 };
1027
1028 cx.spawn(async move |cx| {
1029 let mut matches = search_files_task
1030 .await
1031 .into_iter()
1032 .map(Match::File)
1033 .collect::<Vec<_>>();
1034
1035 let entry_matches = fuzzy::match_strings(
1036 &entry_candidates,
1037 &query,
1038 false,
1039 true,
1040 100,
1041 &Arc::new(AtomicBool::default()),
1042 executor,
1043 )
1044 .await;
1045
1046 matches.extend(entry_matches.into_iter().map(|mat| {
1047 Match::Entry(EntryMatch {
1048 entry: entries[mat.candidate_id],
1049 mat: Some(mat),
1050 })
1051 }));
1052
1053 if let Some(branch_diff_task) = branch_diff_task {
1054 let branch_diff_keyword = PromptContextType::BranchDiff.keyword();
1055 let branch_diff_matches = fuzzy::match_strings(
1056 &[StringMatchCandidate::new(0, branch_diff_keyword)],
1057 &query,
1058 false,
1059 true,
1060 1,
1061 &Arc::new(AtomicBool::default()),
1062 cx.background_executor().clone(),
1063 )
1064 .await;
1065
1066 if !branch_diff_matches.is_empty() {
1067 if let Some(branch_diff_match) = branch_diff_task.await {
1068 matches.push(Match::BranchDiff(branch_diff_match));
1069 }
1070 }
1071 }
1072
1073 matches.sort_by(|a, b| {
1074 b.score()
1075 .partial_cmp(&a.score())
1076 .unwrap_or(std::cmp::Ordering::Equal)
1077 });
1078
1079 matches
1080 })
1081 }
1082 }
1083 }
1084
1085 fn recent_context_picker_entries(
1086 &self,
1087 workspace: &Entity<Workspace>,
1088 cx: &mut App,
1089 ) -> Task<Vec<Match>> {
1090 let mut recent = Vec::with_capacity(6);
1091
1092 let mut mentions = self
1093 .mention_set
1094 .read_with(cx, |store, _cx| store.mentions());
1095 let workspace = workspace.read(cx);
1096 let project = workspace.project().read(cx);
1097 let include_root_name = workspace.visible_worktrees(cx).count() > 1;
1098
1099 if let Some(agent_panel) = workspace.panel::<AgentPanel>(cx)
1100 && let Some(thread) = agent_panel.read(cx).active_agent_thread(cx)
1101 {
1102 let thread = thread.read(cx);
1103 mentions.insert(MentionUri::Thread {
1104 id: thread.session_id().clone(),
1105 name: thread.title().into(),
1106 });
1107 }
1108
1109 recent.extend(
1110 workspace
1111 .recent_navigation_history_iter(cx)
1112 .filter(|(_, abs_path)| {
1113 abs_path.as_ref().is_none_or(|path| {
1114 !mentions.contains(&MentionUri::File {
1115 abs_path: path.clone(),
1116 })
1117 })
1118 })
1119 .take(4)
1120 .filter_map(|(project_path, _)| {
1121 project
1122 .worktree_for_id(project_path.worktree_id, cx)
1123 .map(|worktree| {
1124 let path_prefix = if include_root_name {
1125 worktree.read(cx).root_name().into()
1126 } else {
1127 RelPath::empty().into()
1128 };
1129 Match::File(FileMatch {
1130 mat: fuzzy::PathMatch {
1131 score: 1.,
1132 positions: Vec::new(),
1133 worktree_id: project_path.worktree_id.to_usize(),
1134 path: project_path.path,
1135 path_prefix,
1136 is_dir: false,
1137 distance_to_relative_ancestor: 0,
1138 },
1139 is_recent: true,
1140 })
1141 })
1142 }),
1143 );
1144
1145 if !self.source.supports_context(PromptContextType::Thread, cx) {
1146 return Task::ready(recent);
1147 }
1148
1149 if let Some(history) = self.history.as_ref().and_then(|h| h.upgrade()) {
1150 const RECENT_COUNT: usize = 2;
1151 recent.extend(
1152 history
1153 .read(cx)
1154 .sessions()
1155 .into_iter()
1156 .map(|session| SessionMatch {
1157 session_id: session.session_id.clone(),
1158 title: session_title(session.title.clone()),
1159 })
1160 .filter(|session| {
1161 let uri = MentionUri::Thread {
1162 id: session.session_id.clone(),
1163 name: session.title.to_string(),
1164 };
1165 !mentions.contains(&uri)
1166 })
1167 .take(RECENT_COUNT)
1168 .map(Match::RecentThread),
1169 );
1170 return Task::ready(recent);
1171 }
1172
1173 Task::ready(recent)
1174 }
1175
1176 fn available_context_picker_entries(
1177 &self,
1178 workspace: &Entity<Workspace>,
1179 cx: &mut App,
1180 ) -> Vec<PromptContextEntry> {
1181 let mut entries = vec![
1182 PromptContextEntry::Mode(PromptContextType::File),
1183 PromptContextEntry::Mode(PromptContextType::Symbol),
1184 ];
1185
1186 if self.source.supports_context(PromptContextType::Thread, cx) {
1187 entries.push(PromptContextEntry::Mode(PromptContextType::Thread));
1188 }
1189
1190 let has_editor_selection = workspace
1191 .read(cx)
1192 .active_item(cx)
1193 .and_then(|item| item.downcast::<Editor>())
1194 .is_some_and(|editor| {
1195 editor.update(cx, |editor, cx| {
1196 editor.has_non_empty_selection(&editor.display_snapshot(cx))
1197 })
1198 });
1199
1200 let has_terminal_selection = !terminal_selections_if_panel_open(workspace, cx).is_empty();
1201
1202 if has_editor_selection || has_terminal_selection {
1203 entries.push(PromptContextEntry::Action(
1204 PromptContextAction::AddSelections,
1205 ));
1206 }
1207
1208 if self.prompt_store.is_some() && self.source.supports_context(PromptContextType::Rules, cx)
1209 {
1210 entries.push(PromptContextEntry::Mode(PromptContextType::Rules));
1211 }
1212
1213 if self.source.supports_context(PromptContextType::Fetch, cx) {
1214 entries.push(PromptContextEntry::Mode(PromptContextType::Fetch));
1215 }
1216
1217 if self
1218 .source
1219 .supports_context(PromptContextType::Diagnostics, cx)
1220 {
1221 let summary = workspace
1222 .read(cx)
1223 .project()
1224 .read(cx)
1225 .diagnostic_summary(false, cx);
1226 if summary.error_count > 0 || summary.warning_count > 0 {
1227 entries.push(PromptContextEntry::Mode(PromptContextType::Diagnostics));
1228 }
1229 }
1230
1231 entries
1232 }
1233}
1234
1235impl<T: PromptCompletionProviderDelegate> CompletionProvider for PromptCompletionProvider<T> {
1236 fn completions(
1237 &self,
1238 _excerpt_id: ExcerptId,
1239 buffer: &Entity<Buffer>,
1240 buffer_position: Anchor,
1241 _trigger: CompletionContext,
1242 window: &mut Window,
1243 cx: &mut Context<Editor>,
1244 ) -> Task<Result<Vec<CompletionResponse>>> {
1245 let state = buffer.update(cx, |buffer, cx| {
1246 let position = buffer_position.to_point(buffer);
1247 let line_start = Point::new(position.row, 0);
1248 let offset_to_line = buffer.point_to_offset(line_start);
1249 let mut lines = buffer.text_for_range(line_start..position).lines();
1250 let line = lines.next()?;
1251 PromptCompletion::try_parse(line, offset_to_line, &self.source.supported_modes(cx))
1252 });
1253 let Some(state) = state else {
1254 return Task::ready(Ok(Vec::new()));
1255 };
1256
1257 let Some(workspace) = self.workspace.upgrade() else {
1258 return Task::ready(Ok(Vec::new()));
1259 };
1260
1261 let project = workspace.read(cx).project().clone();
1262 let snapshot = buffer.read(cx).snapshot();
1263 let source_range = snapshot.anchor_before(state.source_range().start)
1264 ..snapshot.anchor_after(state.source_range().end);
1265
1266 let source = self.source.clone();
1267 let editor = self.editor.clone();
1268 let mention_set = self.mention_set.downgrade();
1269 match state {
1270 PromptCompletion::SlashCommand(SlashCommandCompletion {
1271 command, argument, ..
1272 }) => {
1273 let search_task = self.search_slash_commands(command.unwrap_or_default(), cx);
1274 cx.background_spawn(async move {
1275 let completions = search_task
1276 .await
1277 .into_iter()
1278 .map(|command| {
1279 let new_text = if let Some(argument) = argument.as_ref() {
1280 format!("/{} {}", command.name, argument)
1281 } else {
1282 format!("/{} ", command.name)
1283 };
1284
1285 let is_missing_argument =
1286 command.requires_argument && argument.is_none();
1287
1288 Completion {
1289 replace_range: source_range.clone(),
1290 new_text,
1291 label: CodeLabel::plain(command.name.to_string(), None),
1292 documentation: Some(CompletionDocumentation::MultiLinePlainText(
1293 command.description.into(),
1294 )),
1295 source: project::CompletionSource::Custom,
1296 icon_path: None,
1297 match_start: None,
1298 snippet_deduplication_key: None,
1299 insert_text_mode: None,
1300 confirm: Some(Arc::new({
1301 let source = source.clone();
1302 move |intent, _window, cx| {
1303 if !is_missing_argument {
1304 cx.defer({
1305 let source = source.clone();
1306 move |cx| match intent {
1307 CompletionIntent::Complete
1308 | CompletionIntent::CompleteWithInsert
1309 | CompletionIntent::CompleteWithReplace => {
1310 source.confirm_command(cx);
1311 }
1312 CompletionIntent::Compose => {}
1313 }
1314 });
1315 }
1316 false
1317 }
1318 })),
1319 }
1320 })
1321 .collect();
1322
1323 Ok(vec![CompletionResponse {
1324 completions,
1325 display_options: CompletionDisplayOptions {
1326 dynamic_width: true,
1327 },
1328 // Since this does its own filtering (see `filter_completions()` returns false),
1329 // there is no benefit to computing whether this set of completions is incomplete.
1330 is_incomplete: true,
1331 }])
1332 })
1333 }
1334 PromptCompletion::Mention(MentionCompletion { mode, argument, .. }) => {
1335 if let Some(PromptContextType::Diagnostics) = mode {
1336 if argument.is_some() {
1337 return Task::ready(Ok(Vec::new()));
1338 }
1339
1340 let completions = Self::completion_for_diagnostics(
1341 source_range.clone(),
1342 source.clone(),
1343 editor.clone(),
1344 mention_set.clone(),
1345 workspace.clone(),
1346 cx,
1347 );
1348 if !completions.is_empty() {
1349 return Task::ready(Ok(vec![CompletionResponse {
1350 completions,
1351 display_options: CompletionDisplayOptions::default(),
1352 is_incomplete: false,
1353 }]));
1354 }
1355 }
1356
1357 let query = argument.unwrap_or_default();
1358 let search_task =
1359 self.search_mentions(mode, query, Arc::<AtomicBool>::default(), cx);
1360
1361 // Calculate maximum characters available for the full label (file_name + space + directory)
1362 // based on maximum menu width after accounting for padding, spacing, and icon width
1363 let label_max_chars = {
1364 // Base06 left padding + Base06 gap + Base06 right padding + icon width
1365 let used_pixels = DynamicSpacing::Base06.px(cx) * 3.0
1366 + IconSize::XSmall.rems() * window.rem_size();
1367
1368 let style = window.text_style();
1369 let font_id = window.text_system().resolve_font(&style.font());
1370 let font_size = TextSize::Small.rems(cx).to_pixels(window.rem_size());
1371
1372 // Fallback em_width of 10px matches file_finder.rs fallback for TextSize::Small
1373 let em_width = cx
1374 .text_system()
1375 .em_width(font_id, font_size)
1376 .unwrap_or(px(10.0));
1377
1378 // Calculate available pixels for text (file_name + directory)
1379 // Using max width since dynamic_width allows the menu to expand up to this
1380 let available_pixels = COMPLETION_MENU_MAX_WIDTH - used_pixels;
1381
1382 // Convert to character count (total available for file_name + directory)
1383 (f32::from(available_pixels) / f32::from(em_width)) as usize
1384 };
1385
1386 cx.spawn(async move |_, cx| {
1387 let matches = search_task.await;
1388
1389 let completions = cx.update(|cx| {
1390 matches
1391 .into_iter()
1392 .filter_map(|mat| match mat {
1393 Match::File(FileMatch { mat, is_recent }) => {
1394 let project_path = ProjectPath {
1395 worktree_id: WorktreeId::from_usize(mat.worktree_id),
1396 path: mat.path.clone(),
1397 };
1398
1399 // If path is empty, this means we're matching with the root directory itself
1400 // so we use the path_prefix as the name
1401 let path_prefix = if mat.path.is_empty() {
1402 project
1403 .read(cx)
1404 .worktree_for_id(project_path.worktree_id, cx)
1405 .map(|wt| wt.read(cx).root_name().into())
1406 .unwrap_or_else(|| mat.path_prefix.clone())
1407 } else {
1408 mat.path_prefix.clone()
1409 };
1410
1411 Self::completion_for_path(
1412 project_path,
1413 &path_prefix,
1414 is_recent,
1415 mat.is_dir,
1416 source_range.clone(),
1417 source.clone(),
1418 editor.clone(),
1419 mention_set.clone(),
1420 workspace.clone(),
1421 project.clone(),
1422 label_max_chars,
1423 cx,
1424 )
1425 }
1426 Match::Symbol(SymbolMatch { symbol, .. }) => {
1427 Self::completion_for_symbol(
1428 symbol,
1429 source_range.clone(),
1430 source.clone(),
1431 editor.clone(),
1432 mention_set.clone(),
1433 workspace.clone(),
1434 label_max_chars,
1435 cx,
1436 )
1437 }
1438 Match::Thread(thread) => Some(Self::completion_for_thread(
1439 thread.session_id,
1440 Some(thread.title),
1441 source_range.clone(),
1442 false,
1443 source.clone(),
1444 editor.clone(),
1445 mention_set.clone(),
1446 workspace.clone(),
1447 cx,
1448 )),
1449 Match::RecentThread(thread) => Some(Self::completion_for_thread(
1450 thread.session_id,
1451 Some(thread.title),
1452 source_range.clone(),
1453 true,
1454 source.clone(),
1455 editor.clone(),
1456 mention_set.clone(),
1457 workspace.clone(),
1458 cx,
1459 )),
1460 Match::Rules(user_rules) => Some(Self::completion_for_rules(
1461 user_rules,
1462 source_range.clone(),
1463 source.clone(),
1464 editor.clone(),
1465 mention_set.clone(),
1466 workspace.clone(),
1467 cx,
1468 )),
1469 Match::Fetch(url) => Self::completion_for_fetch(
1470 source_range.clone(),
1471 url,
1472 source.clone(),
1473 editor.clone(),
1474 mention_set.clone(),
1475 workspace.clone(),
1476 cx,
1477 ),
1478 Match::Entry(EntryMatch { entry, .. }) => {
1479 Self::completion_for_entry(
1480 entry,
1481 source_range.clone(),
1482 editor.clone(),
1483 mention_set.clone(),
1484 &workspace,
1485 cx,
1486 )
1487 }
1488 Match::BranchDiff(branch_diff) => {
1489 Some(Self::build_branch_diff_completion(
1490 branch_diff.base_ref,
1491 source_range.clone(),
1492 source.clone(),
1493 editor.clone(),
1494 mention_set.clone(),
1495 workspace.clone(),
1496 cx,
1497 ))
1498 }
1499 })
1500 .collect::<Vec<_>>()
1501 });
1502
1503 Ok(vec![CompletionResponse {
1504 completions,
1505 display_options: CompletionDisplayOptions {
1506 dynamic_width: true,
1507 },
1508 // Since this does its own filtering (see `filter_completions()` returns false),
1509 // there is no benefit to computing whether this set of completions is incomplete.
1510 is_incomplete: true,
1511 }])
1512 })
1513 }
1514 }
1515 }
1516
1517 fn is_completion_trigger(
1518 &self,
1519 buffer: &Entity<language::Buffer>,
1520 position: language::Anchor,
1521 _text: &str,
1522 _trigger_in_words: bool,
1523 cx: &mut Context<Editor>,
1524 ) -> bool {
1525 let buffer = buffer.read(cx);
1526 let position = position.to_point(buffer);
1527 let line_start = Point::new(position.row, 0);
1528 let offset_to_line = buffer.point_to_offset(line_start);
1529 let mut lines = buffer.text_for_range(line_start..position).lines();
1530 if let Some(line) = lines.next() {
1531 PromptCompletion::try_parse(line, offset_to_line, &self.source.supported_modes(cx))
1532 .filter(|completion| {
1533 // Right now we don't support completing arguments of slash commands
1534 let is_slash_command_with_argument = matches!(
1535 completion,
1536 PromptCompletion::SlashCommand(SlashCommandCompletion {
1537 argument: Some(_),
1538 ..
1539 })
1540 );
1541 !is_slash_command_with_argument
1542 })
1543 .map(|completion| {
1544 completion.source_range().start <= offset_to_line + position.column as usize
1545 && completion.source_range().end
1546 >= offset_to_line + position.column as usize
1547 })
1548 .unwrap_or(false)
1549 } else {
1550 false
1551 }
1552 }
1553
1554 fn sort_completions(&self) -> bool {
1555 false
1556 }
1557
1558 fn filter_completions(&self) -> bool {
1559 false
1560 }
1561}
1562
1563fn confirm_completion_callback<T: PromptCompletionProviderDelegate>(
1564 crease_text: SharedString,
1565 start: Anchor,
1566 content_len: usize,
1567 mention_uri: MentionUri,
1568 source: Arc<T>,
1569 editor: WeakEntity<Editor>,
1570 mention_set: WeakEntity<MentionSet>,
1571 workspace: Entity<Workspace>,
1572) -> Arc<dyn Fn(CompletionIntent, &mut Window, &mut App) -> bool + Send + Sync> {
1573 Arc::new(move |_, window, cx| {
1574 let source = source.clone();
1575 let editor = editor.clone();
1576 let mention_set = mention_set.clone();
1577 let crease_text = crease_text.clone();
1578 let mention_uri = mention_uri.clone();
1579 let workspace = workspace.clone();
1580 window.defer(cx, move |window, cx| {
1581 if let Some(editor) = editor.upgrade() {
1582 mention_set
1583 .clone()
1584 .update(cx, |mention_set, cx| {
1585 mention_set
1586 .confirm_mention_completion(
1587 crease_text,
1588 start,
1589 content_len,
1590 mention_uri,
1591 source.supports_images(cx),
1592 editor,
1593 &workspace,
1594 window,
1595 cx,
1596 )
1597 .detach();
1598 })
1599 .ok();
1600 }
1601 });
1602 false
1603 })
1604}
1605
1606#[derive(Debug, PartialEq)]
1607enum PromptCompletion {
1608 SlashCommand(SlashCommandCompletion),
1609 Mention(MentionCompletion),
1610}
1611
1612impl PromptCompletion {
1613 fn source_range(&self) -> Range<usize> {
1614 match self {
1615 Self::SlashCommand(completion) => completion.source_range.clone(),
1616 Self::Mention(completion) => completion.source_range.clone(),
1617 }
1618 }
1619
1620 fn try_parse(
1621 line: &str,
1622 offset_to_line: usize,
1623 supported_modes: &[PromptContextType],
1624 ) -> Option<Self> {
1625 if line.contains('@') {
1626 if let Some(mention) =
1627 MentionCompletion::try_parse(line, offset_to_line, supported_modes)
1628 {
1629 return Some(Self::Mention(mention));
1630 }
1631 }
1632 SlashCommandCompletion::try_parse(line, offset_to_line).map(Self::SlashCommand)
1633 }
1634}
1635
1636#[derive(Debug, Default, PartialEq)]
1637pub struct SlashCommandCompletion {
1638 pub source_range: Range<usize>,
1639 pub command: Option<String>,
1640 pub argument: Option<String>,
1641}
1642
1643impl SlashCommandCompletion {
1644 pub fn try_parse(line: &str, offset_to_line: usize) -> Option<Self> {
1645 // If we decide to support commands that are not at the beginning of the prompt, we can remove this check
1646 if !line.starts_with('/') || offset_to_line != 0 {
1647 return None;
1648 }
1649
1650 let (prefix, last_command) = line.rsplit_once('/')?;
1651 if prefix.chars().last().is_some_and(|c| !c.is_whitespace())
1652 || last_command.starts_with(char::is_whitespace)
1653 {
1654 return None;
1655 }
1656
1657 let mut argument = None;
1658 let mut command = None;
1659 if let Some((command_text, args)) = last_command.split_once(char::is_whitespace) {
1660 if !args.is_empty() {
1661 argument = Some(args.trim_end().to_string());
1662 }
1663 command = Some(command_text.to_string());
1664 } else if !last_command.is_empty() {
1665 command = Some(last_command.to_string());
1666 };
1667
1668 Some(Self {
1669 source_range: prefix.len() + offset_to_line
1670 ..line
1671 .rfind(|c: char| !c.is_whitespace())
1672 .unwrap_or_else(|| line.len())
1673 + 1
1674 + offset_to_line,
1675 command,
1676 argument,
1677 })
1678 }
1679}
1680
1681#[derive(Debug, Default, PartialEq)]
1682struct MentionCompletion {
1683 source_range: Range<usize>,
1684 mode: Option<PromptContextType>,
1685 argument: Option<String>,
1686}
1687
1688impl MentionCompletion {
1689 fn try_parse(
1690 line: &str,
1691 offset_to_line: usize,
1692 supported_modes: &[PromptContextType],
1693 ) -> Option<Self> {
1694 // Find the rightmost '@' that has a word boundary before it and no whitespace immediately after
1695 let mut last_mention_start = None;
1696 for (idx, _) in line.rmatch_indices('@') {
1697 // No whitespace immediately after '@'
1698 if line[idx + 1..]
1699 .chars()
1700 .next()
1701 .is_some_and(|c| c.is_whitespace())
1702 {
1703 continue;
1704 }
1705
1706 // Must be a word boundary before '@'
1707 if idx > 0
1708 && line[..idx]
1709 .chars()
1710 .last()
1711 .is_some_and(|c| !c.is_whitespace())
1712 {
1713 continue;
1714 }
1715
1716 last_mention_start = Some(idx);
1717 break;
1718 }
1719
1720 let last_mention_start = last_mention_start?;
1721
1722 let rest_of_line = &line[last_mention_start + 1..];
1723
1724 let mut mode = None;
1725 let mut argument = None;
1726
1727 let mut parts = rest_of_line.split_whitespace();
1728 let mut end = last_mention_start + 1;
1729
1730 if let Some(mode_text) = parts.next() {
1731 // Safe since we check no leading whitespace above
1732 end += mode_text.len();
1733
1734 if let Some(parsed_mode) = PromptContextType::try_from(mode_text).ok()
1735 && supported_modes.contains(&parsed_mode)
1736 {
1737 mode = Some(parsed_mode);
1738 } else {
1739 argument = Some(mode_text.to_string());
1740 }
1741 match rest_of_line[mode_text.len()..].find(|c: char| !c.is_whitespace()) {
1742 Some(whitespace_count) => {
1743 if let Some(argument_text) = parts.next() {
1744 // If mode wasn't recognized but we have an argument, don't suggest completions
1745 // (e.g. '@something word')
1746 if mode.is_none() && !argument_text.is_empty() {
1747 return None;
1748 }
1749
1750 argument = Some(argument_text.to_string());
1751 end += whitespace_count + argument_text.len();
1752 }
1753 }
1754 None => {
1755 // Rest of line is entirely whitespace
1756 end += rest_of_line.len() - mode_text.len();
1757 }
1758 }
1759 }
1760
1761 Some(Self {
1762 source_range: last_mention_start + offset_to_line..end + offset_to_line,
1763 mode,
1764 argument,
1765 })
1766 }
1767}
1768
1769fn diagnostics_label(
1770 summary: DiagnosticSummary,
1771 include_errors: bool,
1772 include_warnings: bool,
1773) -> String {
1774 let mut parts = Vec::new();
1775
1776 if include_errors && summary.error_count > 0 {
1777 parts.push(format!(
1778 "{} {}",
1779 summary.error_count,
1780 pluralize("error", summary.error_count)
1781 ));
1782 }
1783
1784 if include_warnings && summary.warning_count > 0 {
1785 parts.push(format!(
1786 "{} {}",
1787 summary.warning_count,
1788 pluralize("warning", summary.warning_count)
1789 ));
1790 }
1791
1792 if parts.is_empty() {
1793 return "Diagnostics".into();
1794 }
1795
1796 let body = if parts.len() == 2 {
1797 format!("{} and {}", parts[0], parts[1])
1798 } else {
1799 parts
1800 .pop()
1801 .expect("at least one part present after non-empty check")
1802 };
1803
1804 format!("Diagnostics: {body}")
1805}
1806
1807fn diagnostics_submenu_label(
1808 summary: DiagnosticSummary,
1809 include_errors: bool,
1810 include_warnings: bool,
1811) -> String {
1812 match (include_errors, include_warnings) {
1813 (true, true) => format!(
1814 "{} {} & {} {}",
1815 summary.error_count,
1816 pluralize("error", summary.error_count),
1817 summary.warning_count,
1818 pluralize("warning", summary.warning_count)
1819 ),
1820 (true, _) => format!(
1821 "{} {}",
1822 summary.error_count,
1823 pluralize("error", summary.error_count)
1824 ),
1825 (_, true) => format!(
1826 "{} {}",
1827 summary.warning_count,
1828 pluralize("warning", summary.warning_count)
1829 ),
1830 _ => "Diagnostics".into(),
1831 }
1832}
1833
1834fn diagnostics_crease_label(
1835 summary: DiagnosticSummary,
1836 include_errors: bool,
1837 include_warnings: bool,
1838) -> SharedString {
1839 diagnostics_label(summary, include_errors, include_warnings).into()
1840}
1841
1842fn pluralize(noun: &str, count: usize) -> String {
1843 if count == 1 {
1844 noun.to_string()
1845 } else {
1846 format!("{noun}s")
1847 }
1848}
1849
1850pub(crate) fn search_files(
1851 query: String,
1852 cancellation_flag: Arc<AtomicBool>,
1853 workspace: &Entity<Workspace>,
1854 cx: &App,
1855) -> Task<Vec<FileMatch>> {
1856 if query.is_empty() {
1857 let workspace = workspace.read(cx);
1858 let project = workspace.project().read(cx);
1859 let visible_worktrees = workspace.visible_worktrees(cx).collect::<Vec<_>>();
1860 let include_root_name = visible_worktrees.len() > 1;
1861
1862 let recent_matches = workspace
1863 .recent_navigation_history(Some(10), cx)
1864 .into_iter()
1865 .map(|(project_path, _)| {
1866 let path_prefix = if include_root_name {
1867 project
1868 .worktree_for_id(project_path.worktree_id, cx)
1869 .map(|wt| wt.read(cx).root_name().into())
1870 .unwrap_or_else(|| RelPath::empty().into())
1871 } else {
1872 RelPath::empty().into()
1873 };
1874
1875 FileMatch {
1876 mat: PathMatch {
1877 score: 0.,
1878 positions: Vec::new(),
1879 worktree_id: project_path.worktree_id.to_usize(),
1880 path: project_path.path,
1881 path_prefix,
1882 distance_to_relative_ancestor: 0,
1883 is_dir: false,
1884 },
1885 is_recent: true,
1886 }
1887 });
1888
1889 let file_matches = visible_worktrees.into_iter().flat_map(|worktree| {
1890 let worktree = worktree.read(cx);
1891 let path_prefix: Arc<RelPath> = if include_root_name {
1892 worktree.root_name().into()
1893 } else {
1894 RelPath::empty().into()
1895 };
1896 worktree.entries(false, 0).map(move |entry| FileMatch {
1897 mat: PathMatch {
1898 score: 0.,
1899 positions: Vec::new(),
1900 worktree_id: worktree.id().to_usize(),
1901 path: entry.path.clone(),
1902 path_prefix: path_prefix.clone(),
1903 distance_to_relative_ancestor: 0,
1904 is_dir: entry.is_dir(),
1905 },
1906 is_recent: false,
1907 })
1908 });
1909
1910 Task::ready(recent_matches.chain(file_matches).collect())
1911 } else {
1912 let workspace = workspace.read(cx);
1913 let relative_to = workspace
1914 .recent_navigation_history_iter(cx)
1915 .next()
1916 .map(|(path, _)| path.path);
1917 let worktrees = workspace.visible_worktrees(cx).collect::<Vec<_>>();
1918 let include_root_name = worktrees.len() > 1;
1919 let candidate_sets = worktrees
1920 .into_iter()
1921 .map(|worktree| {
1922 let worktree = worktree.read(cx);
1923
1924 PathMatchCandidateSet {
1925 snapshot: worktree.snapshot(),
1926 include_ignored: worktree.root_entry().is_some_and(|entry| entry.is_ignored),
1927 include_root_name,
1928 candidates: project::Candidates::Entries,
1929 }
1930 })
1931 .collect::<Vec<_>>();
1932
1933 let executor = cx.background_executor().clone();
1934 cx.foreground_executor().spawn(async move {
1935 fuzzy::match_path_sets(
1936 candidate_sets.as_slice(),
1937 query.as_str(),
1938 &relative_to,
1939 false,
1940 100,
1941 &cancellation_flag,
1942 executor,
1943 )
1944 .await
1945 .into_iter()
1946 .map(|mat| FileMatch {
1947 mat,
1948 is_recent: false,
1949 })
1950 .collect::<Vec<_>>()
1951 })
1952 }
1953}
1954
1955pub(crate) fn search_symbols(
1956 query: String,
1957 cancellation_flag: Arc<AtomicBool>,
1958 workspace: &Entity<Workspace>,
1959 cx: &mut App,
1960) -> Task<Vec<SymbolMatch>> {
1961 let symbols_task = workspace.update(cx, |workspace, cx| {
1962 workspace
1963 .project()
1964 .update(cx, |project, cx| project.symbols(&query, cx))
1965 });
1966 let project = workspace.read(cx).project().clone();
1967 cx.spawn(async move |cx| {
1968 let Some(symbols) = symbols_task.await.log_err() else {
1969 return Vec::new();
1970 };
1971 let (visible_match_candidates, external_match_candidates): (Vec<_>, Vec<_>) = project
1972 .update(cx, |project, cx| {
1973 symbols
1974 .iter()
1975 .enumerate()
1976 .map(|(id, symbol)| StringMatchCandidate::new(id, symbol.label.filter_text()))
1977 .partition(|candidate| match &symbols[candidate.id].path {
1978 SymbolLocation::InProject(project_path) => project
1979 .entry_for_path(project_path, cx)
1980 .is_some_and(|e| !e.is_ignored),
1981 SymbolLocation::OutsideProject { .. } => false,
1982 })
1983 });
1984 // Try to support rust-analyzer's path based symbols feature which
1985 // allows to search by rust path syntax, in that case we only want to
1986 // filter names by the last segment
1987 // Ideally this was a first class LSP feature (rich queries)
1988 let query = query
1989 .rsplit_once("::")
1990 .map_or(&*query, |(_, suffix)| suffix)
1991 .to_owned();
1992 // Note if you make changes to this filtering below, also change `project_symbols::ProjectSymbolsDelegate::filter`
1993 const MAX_MATCHES: usize = 100;
1994 let mut visible_matches = cx.foreground_executor().block_on(fuzzy::match_strings(
1995 &visible_match_candidates,
1996 &query,
1997 false,
1998 true,
1999 MAX_MATCHES,
2000 &cancellation_flag,
2001 cx.background_executor().clone(),
2002 ));
2003 let mut external_matches = cx.foreground_executor().block_on(fuzzy::match_strings(
2004 &external_match_candidates,
2005 &query,
2006 false,
2007 true,
2008 MAX_MATCHES - visible_matches.len().min(MAX_MATCHES),
2009 &cancellation_flag,
2010 cx.background_executor().clone(),
2011 ));
2012 let sort_key_for_match = |mat: &StringMatch| {
2013 let symbol = &symbols[mat.candidate_id];
2014 (Reverse(OrderedFloat(mat.score)), symbol.label.filter_text())
2015 };
2016
2017 visible_matches.sort_unstable_by_key(sort_key_for_match);
2018 external_matches.sort_unstable_by_key(sort_key_for_match);
2019 let mut matches = visible_matches;
2020 matches.append(&mut external_matches);
2021
2022 matches
2023 .into_iter()
2024 .map(|mut mat| {
2025 let symbol = symbols[mat.candidate_id].clone();
2026 let filter_start = symbol.label.filter_range.start;
2027 for position in &mut mat.positions {
2028 *position += filter_start;
2029 }
2030 SymbolMatch { symbol }
2031 })
2032 .collect()
2033 })
2034}
2035
2036fn filter_sessions_by_query(
2037 query: String,
2038 cancellation_flag: Arc<AtomicBool>,
2039 sessions: Vec<SessionMatch>,
2040 cx: &mut App,
2041) -> Task<Vec<SessionMatch>> {
2042 if query.is_empty() {
2043 return Task::ready(sessions);
2044 }
2045 let executor = cx.background_executor().clone();
2046 cx.background_spawn(async move {
2047 filter_sessions(query, cancellation_flag, sessions, executor).await
2048 })
2049}
2050
2051async fn filter_sessions(
2052 query: String,
2053 cancellation_flag: Arc<AtomicBool>,
2054 sessions: Vec<SessionMatch>,
2055 executor: BackgroundExecutor,
2056) -> Vec<SessionMatch> {
2057 let titles = sessions
2058 .iter()
2059 .map(|session| session.title.clone())
2060 .collect::<Vec<_>>();
2061 let candidates = titles
2062 .iter()
2063 .enumerate()
2064 .map(|(id, title)| StringMatchCandidate::new(id, title.as_ref()))
2065 .collect::<Vec<_>>();
2066 let matches = fuzzy::match_strings(
2067 &candidates,
2068 &query,
2069 false,
2070 true,
2071 100,
2072 &cancellation_flag,
2073 executor,
2074 )
2075 .await;
2076
2077 matches
2078 .into_iter()
2079 .map(|mat| sessions[mat.candidate_id].clone())
2080 .collect()
2081}
2082
2083pub(crate) fn search_rules(
2084 query: String,
2085 cancellation_flag: Arc<AtomicBool>,
2086 prompt_store: &Entity<PromptStore>,
2087 cx: &mut App,
2088) -> Task<Vec<RulesContextEntry>> {
2089 let search_task = prompt_store.read(cx).search(query, cancellation_flag, cx);
2090 cx.background_spawn(async move {
2091 search_task
2092 .await
2093 .into_iter()
2094 .flat_map(|metadata| {
2095 // Default prompts are filtered out as they are automatically included.
2096 if metadata.default {
2097 None
2098 } else {
2099 Some(RulesContextEntry {
2100 prompt_id: metadata.id.as_user()?,
2101 title: metadata.title?,
2102 })
2103 }
2104 })
2105 .collect::<Vec<_>>()
2106 })
2107}
2108
2109pub struct SymbolMatch {
2110 pub symbol: Symbol,
2111}
2112
2113pub struct FileMatch {
2114 pub mat: PathMatch,
2115 pub is_recent: bool,
2116}
2117
2118pub fn extract_file_name_and_directory(
2119 path: &RelPath,
2120 path_prefix: &RelPath,
2121 path_style: PathStyle,
2122) -> (SharedString, Option<SharedString>) {
2123 // If path is empty, this means we're matching with the root directory itself
2124 // so we use the path_prefix as the name
2125 if path.is_empty() && !path_prefix.is_empty() {
2126 return (path_prefix.display(path_style).to_string().into(), None);
2127 }
2128
2129 let full_path = path_prefix.join(path);
2130 let file_name = full_path.file_name().unwrap_or_default();
2131 let display_path = full_path.display(path_style);
2132 let (directory, file_name) = display_path.split_at(display_path.len() - file_name.len());
2133 (
2134 file_name.to_string().into(),
2135 Some(SharedString::new(directory)).filter(|dir| !dir.is_empty()),
2136 )
2137}
2138
2139fn build_code_label_for_path(
2140 file: &str,
2141 directory: Option<&str>,
2142 line_number: Option<u32>,
2143 label_max_chars: usize,
2144 cx: &App,
2145) -> CodeLabel {
2146 let variable_highlight_id = cx
2147 .theme()
2148 .syntax()
2149 .highlight_id("variable")
2150 .map(HighlightId);
2151 let mut label = CodeLabelBuilder::default();
2152
2153 label.push_str(file, None);
2154 label.push_str(" ", None);
2155
2156 if let Some(directory) = directory {
2157 let file_name_chars = file.chars().count();
2158 // Account for: file_name + space (ellipsis is handled by truncate_and_remove_front)
2159 let directory_max_chars = label_max_chars
2160 .saturating_sub(file_name_chars)
2161 .saturating_sub(1);
2162 let truncated_directory = truncate_and_remove_front(directory, directory_max_chars.max(5));
2163 label.push_str(&truncated_directory, variable_highlight_id);
2164 }
2165 if let Some(line_number) = line_number {
2166 label.push_str(&format!(" L{}", line_number), variable_highlight_id);
2167 }
2168 label.build()
2169}
2170
2171/// Returns terminal selections from all terminal views if the terminal panel is open.
2172fn terminal_selections_if_panel_open(workspace: &Entity<Workspace>, cx: &App) -> Vec<String> {
2173 let Some(panel) = workspace.read(cx).panel::<TerminalPanel>(cx) else {
2174 return Vec::new();
2175 };
2176
2177 // Check if the dock containing this panel is open
2178 let position = match TerminalSettings::get_global(cx).dock {
2179 TerminalDockPosition::Left => DockPosition::Left,
2180 TerminalDockPosition::Bottom => DockPosition::Bottom,
2181 TerminalDockPosition::Right => DockPosition::Right,
2182 };
2183 let dock_is_open = workspace
2184 .read(cx)
2185 .dock_at_position(position)
2186 .read(cx)
2187 .is_open();
2188 if !dock_is_open {
2189 return Vec::new();
2190 }
2191
2192 panel.read(cx).terminal_selections(cx)
2193}
2194
2195fn selection_ranges(
2196 workspace: &Entity<Workspace>,
2197 cx: &mut App,
2198) -> Vec<(Entity<Buffer>, Range<text::Anchor>)> {
2199 let Some(editor) = workspace
2200 .read(cx)
2201 .active_item(cx)
2202 .and_then(|item| item.act_as::<Editor>(cx))
2203 else {
2204 return Vec::new();
2205 };
2206
2207 editor.update(cx, |editor, cx| {
2208 let selections = editor.selections.all_adjusted(&editor.display_snapshot(cx));
2209
2210 let buffer = editor.buffer().clone().read(cx);
2211 let snapshot = buffer.snapshot(cx);
2212
2213 selections
2214 .into_iter()
2215 .map(|s| {
2216 let (start, end) = if s.is_empty() {
2217 let row = multi_buffer::MultiBufferRow(s.start.row);
2218 let line_start = text::Point::new(s.start.row, 0);
2219 let line_end = text::Point::new(s.start.row, snapshot.line_len(row));
2220 (line_start, line_end)
2221 } else {
2222 (s.start, s.end)
2223 };
2224 snapshot.anchor_after(start)..snapshot.anchor_before(end)
2225 })
2226 .flat_map(|range| {
2227 let (start_buffer, start) = buffer.text_anchor_for_position(range.start, cx)?;
2228 let (end_buffer, end) = buffer.text_anchor_for_position(range.end, cx)?;
2229 if start_buffer != end_buffer {
2230 return None;
2231 }
2232 Some((start_buffer, start..end))
2233 })
2234 .collect::<Vec<_>>()
2235 })
2236}
2237
2238#[cfg(test)]
2239mod tests {
2240 use super::*;
2241 use gpui::TestAppContext;
2242
2243 #[test]
2244 fn test_prompt_completion_parse() {
2245 let supported_modes = vec![PromptContextType::File, PromptContextType::Symbol];
2246
2247 assert_eq!(
2248 PromptCompletion::try_parse("/", 0, &supported_modes),
2249 Some(PromptCompletion::SlashCommand(SlashCommandCompletion {
2250 source_range: 0..1,
2251 command: None,
2252 argument: None,
2253 }))
2254 );
2255
2256 assert_eq!(
2257 PromptCompletion::try_parse("@", 0, &supported_modes),
2258 Some(PromptCompletion::Mention(MentionCompletion {
2259 source_range: 0..1,
2260 mode: None,
2261 argument: None,
2262 }))
2263 );
2264
2265 assert_eq!(
2266 PromptCompletion::try_parse("/test @file", 0, &supported_modes),
2267 Some(PromptCompletion::Mention(MentionCompletion {
2268 source_range: 6..11,
2269 mode: Some(PromptContextType::File),
2270 argument: None,
2271 }))
2272 );
2273 }
2274
2275 #[test]
2276 fn test_slash_command_completion_parse() {
2277 assert_eq!(
2278 SlashCommandCompletion::try_parse("/", 0),
2279 Some(SlashCommandCompletion {
2280 source_range: 0..1,
2281 command: None,
2282 argument: None,
2283 })
2284 );
2285
2286 assert_eq!(
2287 SlashCommandCompletion::try_parse("/help", 0),
2288 Some(SlashCommandCompletion {
2289 source_range: 0..5,
2290 command: Some("help".to_string()),
2291 argument: None,
2292 })
2293 );
2294
2295 assert_eq!(
2296 SlashCommandCompletion::try_parse("/help ", 0),
2297 Some(SlashCommandCompletion {
2298 source_range: 0..5,
2299 command: Some("help".to_string()),
2300 argument: None,
2301 })
2302 );
2303
2304 assert_eq!(
2305 SlashCommandCompletion::try_parse("/help arg1", 0),
2306 Some(SlashCommandCompletion {
2307 source_range: 0..10,
2308 command: Some("help".to_string()),
2309 argument: Some("arg1".to_string()),
2310 })
2311 );
2312
2313 assert_eq!(
2314 SlashCommandCompletion::try_parse("/help arg1 arg2", 0),
2315 Some(SlashCommandCompletion {
2316 source_range: 0..15,
2317 command: Some("help".to_string()),
2318 argument: Some("arg1 arg2".to_string()),
2319 })
2320 );
2321
2322 assert_eq!(
2323 SlashCommandCompletion::try_parse("/拿不到命令 拿不到命令 ", 0),
2324 Some(SlashCommandCompletion {
2325 source_range: 0..30,
2326 command: Some("拿不到命令".to_string()),
2327 argument: Some("拿不到命令".to_string()),
2328 })
2329 );
2330
2331 assert_eq!(SlashCommandCompletion::try_parse("Lorem Ipsum", 0), None);
2332
2333 assert_eq!(SlashCommandCompletion::try_parse("Lorem /", 0), None);
2334
2335 assert_eq!(SlashCommandCompletion::try_parse("Lorem /help", 0), None);
2336
2337 assert_eq!(SlashCommandCompletion::try_parse("Lorem/", 0), None);
2338
2339 assert_eq!(SlashCommandCompletion::try_parse("/ ", 0), None);
2340 }
2341
2342 #[test]
2343 fn test_mention_completion_parse() {
2344 let supported_modes = vec![PromptContextType::File, PromptContextType::Symbol];
2345 let supported_modes_with_diagnostics = vec![
2346 PromptContextType::File,
2347 PromptContextType::Symbol,
2348 PromptContextType::Diagnostics,
2349 ];
2350
2351 assert_eq!(
2352 MentionCompletion::try_parse("Lorem Ipsum", 0, &supported_modes),
2353 None
2354 );
2355
2356 assert_eq!(
2357 MentionCompletion::try_parse("Lorem @", 0, &supported_modes),
2358 Some(MentionCompletion {
2359 source_range: 6..7,
2360 mode: None,
2361 argument: None,
2362 })
2363 );
2364
2365 assert_eq!(
2366 MentionCompletion::try_parse("Lorem @file", 0, &supported_modes),
2367 Some(MentionCompletion {
2368 source_range: 6..11,
2369 mode: Some(PromptContextType::File),
2370 argument: None,
2371 })
2372 );
2373
2374 assert_eq!(
2375 MentionCompletion::try_parse("Lorem @file ", 0, &supported_modes),
2376 Some(MentionCompletion {
2377 source_range: 6..12,
2378 mode: Some(PromptContextType::File),
2379 argument: None,
2380 })
2381 );
2382
2383 assert_eq!(
2384 MentionCompletion::try_parse("Lorem @file main.rs", 0, &supported_modes),
2385 Some(MentionCompletion {
2386 source_range: 6..19,
2387 mode: Some(PromptContextType::File),
2388 argument: Some("main.rs".to_string()),
2389 })
2390 );
2391
2392 assert_eq!(
2393 MentionCompletion::try_parse("Lorem @file main.rs ", 0, &supported_modes),
2394 Some(MentionCompletion {
2395 source_range: 6..19,
2396 mode: Some(PromptContextType::File),
2397 argument: Some("main.rs".to_string()),
2398 })
2399 );
2400
2401 assert_eq!(
2402 MentionCompletion::try_parse("Lorem @file main.rs Ipsum", 0, &supported_modes),
2403 Some(MentionCompletion {
2404 source_range: 6..19,
2405 mode: Some(PromptContextType::File),
2406 argument: Some("main.rs".to_string()),
2407 })
2408 );
2409
2410 assert_eq!(
2411 MentionCompletion::try_parse("Lorem @main", 0, &supported_modes),
2412 Some(MentionCompletion {
2413 source_range: 6..11,
2414 mode: None,
2415 argument: Some("main".to_string()),
2416 })
2417 );
2418
2419 assert_eq!(
2420 MentionCompletion::try_parse("Lorem @main ", 0, &supported_modes),
2421 Some(MentionCompletion {
2422 source_range: 6..12,
2423 mode: None,
2424 argument: Some("main".to_string()),
2425 })
2426 );
2427
2428 assert_eq!(
2429 MentionCompletion::try_parse("Lorem @main m", 0, &supported_modes),
2430 None
2431 );
2432
2433 assert_eq!(
2434 MentionCompletion::try_parse("test@", 0, &supported_modes),
2435 None
2436 );
2437
2438 // Allowed non-file mentions
2439
2440 assert_eq!(
2441 MentionCompletion::try_parse("Lorem @symbol main", 0, &supported_modes),
2442 Some(MentionCompletion {
2443 source_range: 6..18,
2444 mode: Some(PromptContextType::Symbol),
2445 argument: Some("main".to_string()),
2446 })
2447 );
2448
2449 assert_eq!(
2450 MentionCompletion::try_parse(
2451 "Lorem @symbol agent_ui::completion_provider",
2452 0,
2453 &supported_modes
2454 ),
2455 Some(MentionCompletion {
2456 source_range: 6..43,
2457 mode: Some(PromptContextType::Symbol),
2458 argument: Some("agent_ui::completion_provider".to_string()),
2459 })
2460 );
2461
2462 assert_eq!(
2463 MentionCompletion::try_parse(
2464 "Lorem @diagnostics",
2465 0,
2466 &supported_modes_with_diagnostics
2467 ),
2468 Some(MentionCompletion {
2469 source_range: 6..18,
2470 mode: Some(PromptContextType::Diagnostics),
2471 argument: None,
2472 })
2473 );
2474
2475 // Disallowed non-file mentions
2476 assert_eq!(
2477 MentionCompletion::try_parse("Lorem @symbol main", 0, &[PromptContextType::File]),
2478 None
2479 );
2480
2481 assert_eq!(
2482 MentionCompletion::try_parse("Lorem@symbol", 0, &supported_modes),
2483 None,
2484 "Should not parse mention inside word"
2485 );
2486
2487 assert_eq!(
2488 MentionCompletion::try_parse("Lorem @ file", 0, &supported_modes),
2489 None,
2490 "Should not parse with a space after @"
2491 );
2492
2493 assert_eq!(
2494 MentionCompletion::try_parse("@ file", 0, &supported_modes),
2495 None,
2496 "Should not parse with a space after @ at the start of the line"
2497 );
2498
2499 assert_eq!(
2500 MentionCompletion::try_parse(
2501 "@fetch https://www.npmjs.com/package/@matterport/sdk",
2502 0,
2503 &[PromptContextType::Fetch]
2504 ),
2505 Some(MentionCompletion {
2506 source_range: 0..52,
2507 mode: Some(PromptContextType::Fetch),
2508 argument: Some("https://www.npmjs.com/package/@matterport/sdk".to_string()),
2509 }),
2510 "Should handle URLs with @ in the path"
2511 );
2512
2513 assert_eq!(
2514 MentionCompletion::try_parse(
2515 "@fetch https://example.com/@org/@repo/file",
2516 0,
2517 &[PromptContextType::Fetch]
2518 ),
2519 Some(MentionCompletion {
2520 source_range: 0..42,
2521 mode: Some(PromptContextType::Fetch),
2522 argument: Some("https://example.com/@org/@repo/file".to_string()),
2523 }),
2524 "Should handle URLs with multiple @ characters"
2525 );
2526
2527 assert_eq!(
2528 MentionCompletion::try_parse(
2529 "@fetch https://example.com/@",
2530 0,
2531 &[PromptContextType::Fetch]
2532 ),
2533 Some(MentionCompletion {
2534 source_range: 0..28,
2535 mode: Some(PromptContextType::Fetch),
2536 argument: Some("https://example.com/@".to_string()),
2537 }),
2538 "Should parse URL ending with @ (even if URL is incomplete)"
2539 );
2540 }
2541
2542 #[gpui::test]
2543 async fn test_filter_sessions_by_query(cx: &mut TestAppContext) {
2544 let alpha = SessionMatch {
2545 session_id: acp::SessionId::new("session-alpha"),
2546 title: "Alpha Session".into(),
2547 };
2548 let beta = SessionMatch {
2549 session_id: acp::SessionId::new("session-beta"),
2550 title: "Beta Session".into(),
2551 };
2552
2553 let sessions = vec![alpha.clone(), beta];
2554
2555 let task = {
2556 let mut app = cx.app.borrow_mut();
2557 filter_sessions_by_query(
2558 "Alpha".into(),
2559 Arc::new(AtomicBool::default()),
2560 sessions,
2561 &mut app,
2562 )
2563 };
2564
2565 let results = task.await;
2566 assert_eq!(results.len(), 1);
2567 assert_eq!(results[0].session_id, alpha.session_id);
2568 }
2569
2570 #[gpui::test]
2571 async fn test_search_files_path_distance_ordering(cx: &mut TestAppContext) {
2572 use project::Project;
2573 use serde_json::json;
2574 use util::{path, rel_path::rel_path};
2575 use workspace::{AppState, MultiWorkspace};
2576
2577 let app_state = cx.update(|cx| {
2578 let state = AppState::test(cx);
2579 theme::init(theme::LoadThemes::JustBase, cx);
2580 editor::init(cx);
2581 state
2582 });
2583
2584 app_state
2585 .fs
2586 .as_fake()
2587 .insert_tree(
2588 path!("/root"),
2589 json!({
2590 "dir1": { "a.txt": "" },
2591 "dir2": {
2592 "a.txt": "",
2593 "b.txt": ""
2594 }
2595 }),
2596 )
2597 .await;
2598
2599 let project = Project::test(app_state.fs.clone(), [path!("/root").as_ref()], cx).await;
2600 let (multi_workspace, cx) =
2601 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
2602 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2603
2604 let worktree_id = cx.read(|cx| {
2605 let worktrees = workspace.read(cx).worktrees(cx).collect::<Vec<_>>();
2606 assert_eq!(worktrees.len(), 1);
2607 worktrees[0].read(cx).id()
2608 });
2609
2610 // Open a file in dir2 to create navigation history.
2611 // When searching for "a.txt", dir2/a.txt should be sorted first because
2612 // it is closer to the most recently opened file (dir2/b.txt).
2613 let b_path = ProjectPath {
2614 worktree_id,
2615 path: rel_path("dir2/b.txt").into(),
2616 };
2617 workspace
2618 .update_in(cx, |workspace, window, cx| {
2619 workspace.open_path(b_path, None, true, window, cx)
2620 })
2621 .await
2622 .unwrap();
2623
2624 let results = cx
2625 .update(|_window, cx| {
2626 search_files(
2627 "a.txt".into(),
2628 Arc::new(AtomicBool::default()),
2629 &workspace,
2630 cx,
2631 )
2632 })
2633 .await;
2634
2635 assert_eq!(results.len(), 2, "expected 2 matching files");
2636 assert_eq!(
2637 results[0].mat.path.as_ref(),
2638 rel_path("dir2/a.txt"),
2639 "dir2/a.txt should be first because it's closer to the recently opened dir2/b.txt"
2640 );
2641 assert_eq!(
2642 results[1].mat.path.as_ref(),
2643 rel_path("dir1/a.txt"),
2644 "dir1/a.txt should be second"
2645 );
2646 }
2647}