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