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