1use crate::{
2 acp::completion_provider::{ContextPickerCompletionProvider, SlashCommandCompletion},
3 context_picker::{ContextPickerAction, fetch_context_picker::fetch_url_content},
4};
5use acp_thread::{MentionUri, selection_name};
6use agent_client_protocol as acp;
7use agent_servers::{AgentServer, AgentServerDelegate};
8use agent2::HistoryStore;
9use anyhow::{Result, anyhow};
10use assistant_slash_commands::codeblock_fence_for_path;
11use assistant_tool::outline;
12use collections::{HashMap, HashSet};
13use editor::{
14 Addon, Anchor, AnchorRangeExt, ContextMenuOptions, ContextMenuPlacement, Editor, EditorElement,
15 EditorEvent, EditorMode, EditorSnapshot, EditorStyle, ExcerptId, FoldPlaceholder, InlayId,
16 MultiBuffer, ToOffset,
17 actions::Paste,
18 display_map::{Crease, CreaseId, FoldId, Inlay},
19};
20use futures::{
21 FutureExt as _,
22 future::{Shared, join_all},
23};
24use gpui::{
25 Animation, AnimationExt as _, AppContext, ClipboardEntry, Context, Entity, EntityId,
26 EventEmitter, FocusHandle, Focusable, Image, ImageFormat, Img, KeyContext, SharedString,
27 Subscription, Task, TextStyle, WeakEntity, pulsating_between,
28};
29use language::{Buffer, Language, language_settings::InlayHintKind};
30use language_model::LanguageModelImage;
31use postage::stream::Stream as _;
32use project::{
33 CompletionIntent, InlayHint, InlayHintLabel, Project, ProjectItem, ProjectPath, Worktree,
34};
35use prompt_store::{PromptId, PromptStore};
36use rope::Point;
37use settings::Settings;
38use std::{
39 cell::RefCell,
40 ffi::OsStr,
41 fmt::Write,
42 ops::{Range, RangeInclusive},
43 path::{Path, PathBuf},
44 rc::Rc,
45 sync::Arc,
46 time::Duration,
47};
48use text::OffsetRangeExt;
49use theme::ThemeSettings;
50use ui::{ButtonLike, TintColor, Toggleable, prelude::*};
51use util::{ResultExt, debug_panic, rel_path::RelPath};
52use workspace::{Workspace, notifications::NotifyResultExt as _};
53use zed_actions::agent::Chat;
54
55pub struct MessageEditor {
56 mention_set: MentionSet,
57 editor: Entity<Editor>,
58 project: Entity<Project>,
59 workspace: WeakEntity<Workspace>,
60 history_store: Entity<HistoryStore>,
61 prompt_store: Option<Entity<PromptStore>>,
62 prompt_capabilities: Rc<RefCell<acp::PromptCapabilities>>,
63 available_commands: Rc<RefCell<Vec<acp::AvailableCommand>>>,
64 agent_name: SharedString,
65 _subscriptions: Vec<Subscription>,
66 _parse_slash_command_task: Task<()>,
67}
68
69#[derive(Clone, Copy, Debug)]
70pub enum MessageEditorEvent {
71 Send,
72 Cancel,
73 Focus,
74 LostFocus,
75}
76
77impl EventEmitter<MessageEditorEvent> for MessageEditor {}
78
79const COMMAND_HINT_INLAY_ID: u32 = 0;
80
81impl MessageEditor {
82 pub fn new(
83 workspace: WeakEntity<Workspace>,
84 project: Entity<Project>,
85 history_store: Entity<HistoryStore>,
86 prompt_store: Option<Entity<PromptStore>>,
87 prompt_capabilities: Rc<RefCell<acp::PromptCapabilities>>,
88 available_commands: Rc<RefCell<Vec<acp::AvailableCommand>>>,
89 agent_name: SharedString,
90 placeholder: &str,
91 mode: EditorMode,
92 window: &mut Window,
93 cx: &mut Context<Self>,
94 ) -> Self {
95 let language = Language::new(
96 language::LanguageConfig {
97 completion_query_characters: HashSet::from_iter(['.', '-', '_', '@']),
98 ..Default::default()
99 },
100 None,
101 );
102 let completion_provider = Rc::new(ContextPickerCompletionProvider::new(
103 cx.weak_entity(),
104 workspace.clone(),
105 history_store.clone(),
106 prompt_store.clone(),
107 prompt_capabilities.clone(),
108 available_commands.clone(),
109 ));
110 let mention_set = MentionSet::default();
111 let editor = cx.new(|cx| {
112 let buffer = cx.new(|cx| Buffer::local("", cx).with_language(Arc::new(language), cx));
113 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
114
115 let mut editor = Editor::new(mode, buffer, None, window, cx);
116 editor.set_placeholder_text(placeholder, window, cx);
117 editor.set_show_indent_guides(false, cx);
118 editor.set_soft_wrap();
119 editor.set_use_modal_editing(true);
120 editor.set_completion_provider(Some(completion_provider.clone()));
121 editor.set_context_menu_options(ContextMenuOptions {
122 min_entries_visible: 12,
123 max_entries_visible: 12,
124 placement: Some(ContextMenuPlacement::Above),
125 });
126 editor.register_addon(MessageEditorAddon::new());
127 editor
128 });
129
130 cx.on_focus_in(&editor.focus_handle(cx), window, |_, _, cx| {
131 cx.emit(MessageEditorEvent::Focus)
132 })
133 .detach();
134 cx.on_focus_out(&editor.focus_handle(cx), window, |_, _, _, cx| {
135 cx.emit(MessageEditorEvent::LostFocus)
136 })
137 .detach();
138
139 let mut has_hint = false;
140 let mut subscriptions = Vec::new();
141
142 subscriptions.push(cx.subscribe_in(&editor, window, {
143 move |this, editor, event, window, cx| {
144 if let EditorEvent::Edited { .. } = event
145 && !editor.read(cx).read_only(cx)
146 {
147 let snapshot = editor.update(cx, |editor, cx| {
148 let new_hints = this
149 .command_hint(editor.buffer(), cx)
150 .into_iter()
151 .collect::<Vec<_>>();
152 let has_new_hint = !new_hints.is_empty();
153 editor.splice_inlays(
154 if has_hint {
155 &[InlayId::Hint(COMMAND_HINT_INLAY_ID)]
156 } else {
157 &[]
158 },
159 new_hints,
160 cx,
161 );
162 has_hint = has_new_hint;
163
164 editor.snapshot(window, cx)
165 });
166 this.mention_set.remove_invalid(snapshot);
167
168 cx.notify();
169 }
170 }
171 }));
172
173 Self {
174 editor,
175 project,
176 mention_set,
177 workspace,
178 history_store,
179 prompt_store,
180 prompt_capabilities,
181 available_commands,
182 agent_name,
183 _subscriptions: subscriptions,
184 _parse_slash_command_task: Task::ready(()),
185 }
186 }
187
188 fn command_hint(&self, buffer: &Entity<MultiBuffer>, cx: &App) -> Option<Inlay> {
189 let available_commands = self.available_commands.borrow();
190 if available_commands.is_empty() {
191 return None;
192 }
193
194 let snapshot = buffer.read(cx).snapshot(cx);
195 let parsed_command = SlashCommandCompletion::try_parse(&snapshot.text(), 0)?;
196 if parsed_command.argument.is_some() {
197 return None;
198 }
199
200 let command_name = parsed_command.command?;
201 let available_command = available_commands
202 .iter()
203 .find(|command| command.name == command_name)?;
204
205 let acp::AvailableCommandInput::Unstructured { mut hint } =
206 available_command.input.clone()?;
207
208 let mut hint_pos = parsed_command.source_range.end + 1;
209 if hint_pos > snapshot.len() {
210 hint_pos = snapshot.len();
211 hint.insert(0, ' ');
212 }
213
214 let hint_pos = snapshot.anchor_after(hint_pos);
215
216 Some(Inlay::hint(
217 COMMAND_HINT_INLAY_ID,
218 hint_pos,
219 &InlayHint {
220 position: hint_pos.text_anchor,
221 label: InlayHintLabel::String(hint),
222 kind: Some(InlayHintKind::Parameter),
223 padding_left: false,
224 padding_right: false,
225 tooltip: None,
226 resolve_state: project::ResolveState::Resolved,
227 },
228 ))
229 }
230
231 pub fn insert_thread_summary(
232 &mut self,
233 thread: agent2::DbThreadMetadata,
234 window: &mut Window,
235 cx: &mut Context<Self>,
236 ) {
237 let start = self.editor.update(cx, |editor, cx| {
238 editor.set_text(format!("{}\n", thread.title), window, cx);
239 editor
240 .buffer()
241 .read(cx)
242 .snapshot(cx)
243 .anchor_before(Point::zero())
244 .text_anchor
245 });
246
247 self.confirm_mention_completion(
248 thread.title.clone(),
249 start,
250 thread.title.len(),
251 MentionUri::Thread {
252 id: thread.id.clone(),
253 name: thread.title.to_string(),
254 },
255 window,
256 cx,
257 )
258 .detach();
259 }
260
261 #[cfg(test)]
262 pub(crate) fn editor(&self) -> &Entity<Editor> {
263 &self.editor
264 }
265
266 #[cfg(test)]
267 pub(crate) fn mention_set(&mut self) -> &mut MentionSet {
268 &mut self.mention_set
269 }
270
271 pub fn is_empty(&self, cx: &App) -> bool {
272 self.editor.read(cx).is_empty(cx)
273 }
274
275 pub fn mentions(&self) -> HashSet<MentionUri> {
276 self.mention_set
277 .mentions
278 .values()
279 .map(|(uri, _)| uri.clone())
280 .collect()
281 }
282
283 pub fn confirm_mention_completion(
284 &mut self,
285 crease_text: SharedString,
286 start: text::Anchor,
287 content_len: usize,
288 mention_uri: MentionUri,
289 window: &mut Window,
290 cx: &mut Context<Self>,
291 ) -> Task<()> {
292 let snapshot = self
293 .editor
294 .update(cx, |editor, cx| editor.snapshot(window, cx));
295 let Some(start_anchor) = snapshot.buffer_snapshot().as_singleton_anchor(start) else {
296 return Task::ready(());
297 };
298 let excerpt_id = start_anchor.excerpt_id;
299 let end_anchor = snapshot
300 .buffer_snapshot()
301 .anchor_before(start_anchor.to_offset(&snapshot.buffer_snapshot()) + content_len + 1);
302
303 let crease = if let MentionUri::File { abs_path } = &mention_uri
304 && let Some(extension) = abs_path.extension()
305 && let Some(extension) = extension.to_str()
306 && Img::extensions().contains(&extension)
307 && !extension.contains("svg")
308 {
309 let Some(project_path) = self
310 .project
311 .read(cx)
312 .project_path_for_absolute_path(&abs_path, cx)
313 else {
314 log::error!("project path not found");
315 return Task::ready(());
316 };
317 let image = self
318 .project
319 .update(cx, |project, cx| project.open_image(project_path, cx));
320 let image = cx
321 .spawn(async move |_, cx| {
322 let image = image.await.map_err(|e| e.to_string())?;
323 let image = image
324 .update(cx, |image, _| image.image.clone())
325 .map_err(|e| e.to_string())?;
326 Ok(image)
327 })
328 .shared();
329 insert_crease_for_mention(
330 excerpt_id,
331 start,
332 content_len,
333 mention_uri.name().into(),
334 IconName::Image.path().into(),
335 Some(image),
336 self.editor.clone(),
337 window,
338 cx,
339 )
340 } else {
341 insert_crease_for_mention(
342 excerpt_id,
343 start,
344 content_len,
345 crease_text,
346 mention_uri.icon_path(cx),
347 None,
348 self.editor.clone(),
349 window,
350 cx,
351 )
352 };
353 let Some((crease_id, tx)) = crease else {
354 return Task::ready(());
355 };
356
357 let task = match mention_uri.clone() {
358 MentionUri::Fetch { url } => self.confirm_mention_for_fetch(url, cx),
359 MentionUri::Directory { .. } => Task::ready(Ok(Mention::UriOnly)),
360 MentionUri::Thread { id, .. } => self.confirm_mention_for_thread(id, cx),
361 MentionUri::TextThread { path, .. } => self.confirm_mention_for_text_thread(path, cx),
362 MentionUri::File { abs_path } => self.confirm_mention_for_file(abs_path, cx),
363 MentionUri::Symbol {
364 abs_path,
365 line_range,
366 ..
367 } => self.confirm_mention_for_symbol(abs_path, line_range, cx),
368 MentionUri::Rule { id, .. } => self.confirm_mention_for_rule(id, cx),
369 MentionUri::PastedImage => {
370 debug_panic!("pasted image URI should not be included in completions");
371 Task::ready(Err(anyhow!(
372 "pasted imaged URI should not be included in completions"
373 )))
374 }
375 MentionUri::Selection { .. } => {
376 // Handled elsewhere
377 debug_panic!("unexpected selection URI");
378 Task::ready(Err(anyhow!("unexpected selection URI")))
379 }
380 };
381 let task = cx
382 .spawn(async move |_, _| task.await.map_err(|e| e.to_string()))
383 .shared();
384 self.mention_set
385 .mentions
386 .insert(crease_id, (mention_uri, task.clone()));
387
388 // Notify the user if we failed to load the mentioned context
389 cx.spawn_in(window, async move |this, cx| {
390 let result = task.await.notify_async_err(cx);
391 drop(tx);
392 if result.is_none() {
393 this.update(cx, |this, cx| {
394 this.editor.update(cx, |editor, cx| {
395 // Remove mention
396 editor.edit([(start_anchor..end_anchor, "")], cx);
397 });
398 this.mention_set.mentions.remove(&crease_id);
399 })
400 .ok();
401 }
402 })
403 }
404
405 fn confirm_mention_for_file(
406 &mut self,
407 abs_path: PathBuf,
408 cx: &mut Context<Self>,
409 ) -> Task<Result<Mention>> {
410 let Some(project_path) = self
411 .project
412 .read(cx)
413 .project_path_for_absolute_path(&abs_path, cx)
414 else {
415 return Task::ready(Err(anyhow!("project path not found")));
416 };
417 let extension = abs_path
418 .extension()
419 .and_then(OsStr::to_str)
420 .unwrap_or_default();
421
422 if Img::extensions().contains(&extension) && !extension.contains("svg") {
423 if !self.prompt_capabilities.borrow().image {
424 return Task::ready(Err(anyhow!("This model does not support images yet")));
425 }
426 let task = self
427 .project
428 .update(cx, |project, cx| project.open_image(project_path, cx));
429 return cx.spawn(async move |_, cx| {
430 let image = task.await?;
431 let image = image.update(cx, |image, _| image.image.clone())?;
432 let format = image.format;
433 let image = cx
434 .update(|cx| LanguageModelImage::from_image(image, cx))?
435 .await;
436 if let Some(image) = image {
437 Ok(Mention::Image(MentionImage {
438 data: image.source,
439 format,
440 }))
441 } else {
442 Err(anyhow!("Failed to convert image"))
443 }
444 });
445 }
446
447 let buffer = self
448 .project
449 .update(cx, |project, cx| project.open_buffer(project_path, cx));
450 cx.spawn(async move |_, cx| {
451 let buffer = buffer.await?;
452 let buffer_content = outline::get_buffer_content_or_outline(
453 buffer.clone(),
454 Some(&abs_path.to_string_lossy()),
455 &cx,
456 )
457 .await?;
458
459 Ok(Mention::Text {
460 content: buffer_content.text,
461 tracked_buffers: vec![buffer],
462 })
463 })
464 }
465
466 fn confirm_mention_for_fetch(
467 &mut self,
468 url: url::Url,
469 cx: &mut Context<Self>,
470 ) -> Task<Result<Mention>> {
471 let http_client = match self
472 .workspace
473 .update(cx, |workspace, _| workspace.client().http_client())
474 {
475 Ok(http_client) => http_client,
476 Err(e) => return Task::ready(Err(e)),
477 };
478 cx.background_executor().spawn(async move {
479 let content = fetch_url_content(http_client, url.to_string()).await?;
480 Ok(Mention::Text {
481 content,
482 tracked_buffers: Vec::new(),
483 })
484 })
485 }
486
487 fn confirm_mention_for_symbol(
488 &mut self,
489 abs_path: PathBuf,
490 line_range: RangeInclusive<u32>,
491 cx: &mut Context<Self>,
492 ) -> Task<Result<Mention>> {
493 let Some(project_path) = self
494 .project
495 .read(cx)
496 .project_path_for_absolute_path(&abs_path, cx)
497 else {
498 return Task::ready(Err(anyhow!("project path not found")));
499 };
500 let buffer = self
501 .project
502 .update(cx, |project, cx| project.open_buffer(project_path, cx));
503 cx.spawn(async move |_, cx| {
504 let buffer = buffer.await?;
505 let mention = buffer.update(cx, |buffer, cx| {
506 let start = Point::new(*line_range.start(), 0).min(buffer.max_point());
507 let end = Point::new(*line_range.end() + 1, 0).min(buffer.max_point());
508 let content = buffer.text_for_range(start..end).collect();
509 Mention::Text {
510 content,
511 tracked_buffers: vec![cx.entity()],
512 }
513 })?;
514 anyhow::Ok(mention)
515 })
516 }
517
518 fn confirm_mention_for_rule(
519 &mut self,
520 id: PromptId,
521 cx: &mut Context<Self>,
522 ) -> Task<Result<Mention>> {
523 let Some(prompt_store) = self.prompt_store.clone() else {
524 return Task::ready(Err(anyhow!("missing prompt store")));
525 };
526 let prompt = prompt_store.read(cx).load(id, cx);
527 cx.spawn(async move |_, _| {
528 let prompt = prompt.await?;
529 Ok(Mention::Text {
530 content: prompt,
531 tracked_buffers: Vec::new(),
532 })
533 })
534 }
535
536 pub fn confirm_mention_for_selection(
537 &mut self,
538 source_range: Range<text::Anchor>,
539 selections: Vec<(Entity<Buffer>, Range<text::Anchor>, Range<usize>)>,
540 window: &mut Window,
541 cx: &mut Context<Self>,
542 ) {
543 let snapshot = self.editor.read(cx).buffer().read(cx).snapshot(cx);
544 let Some(start) = snapshot.as_singleton_anchor(source_range.start) else {
545 return;
546 };
547
548 let offset = start.to_offset(&snapshot);
549
550 for (buffer, selection_range, range_to_fold) in selections {
551 let range = snapshot.anchor_after(offset + range_to_fold.start)
552 ..snapshot.anchor_after(offset + range_to_fold.end);
553
554 let abs_path = buffer
555 .read(cx)
556 .project_path(cx)
557 .and_then(|project_path| self.project.read(cx).absolute_path(&project_path, cx));
558 let snapshot = buffer.read(cx).snapshot();
559
560 let text = snapshot
561 .text_for_range(selection_range.clone())
562 .collect::<String>();
563 let point_range = selection_range.to_point(&snapshot);
564 let line_range = point_range.start.row..=point_range.end.row;
565
566 let uri = MentionUri::Selection {
567 abs_path: abs_path.clone(),
568 line_range: line_range.clone(),
569 };
570 let crease = crate::context_picker::crease_for_mention(
571 selection_name(abs_path.as_deref(), &line_range).into(),
572 uri.icon_path(cx),
573 range,
574 self.editor.downgrade(),
575 );
576
577 let crease_id = self.editor.update(cx, |editor, cx| {
578 let crease_ids = editor.insert_creases(vec![crease.clone()], cx);
579 editor.fold_creases(vec![crease], false, window, cx);
580 crease_ids.first().copied().unwrap()
581 });
582
583 self.mention_set.mentions.insert(
584 crease_id,
585 (
586 uri,
587 Task::ready(Ok(Mention::Text {
588 content: text,
589 tracked_buffers: vec![buffer],
590 }))
591 .shared(),
592 ),
593 );
594 }
595 }
596
597 fn confirm_mention_for_thread(
598 &mut self,
599 id: acp::SessionId,
600 cx: &mut Context<Self>,
601 ) -> Task<Result<Mention>> {
602 let server = Rc::new(agent2::NativeAgentServer::new(
603 self.project.read(cx).fs().clone(),
604 self.history_store.clone(),
605 ));
606 let delegate = AgentServerDelegate::new(
607 self.project.read(cx).agent_server_store().clone(),
608 self.project.clone(),
609 None,
610 None,
611 );
612 let connection = server.connect(None, delegate, cx);
613 cx.spawn(async move |_, cx| {
614 let (agent, _) = connection.await?;
615 let agent = agent.downcast::<agent2::NativeAgentConnection>().unwrap();
616 let summary = agent
617 .0
618 .update(cx, |agent, cx| agent.thread_summary(id, cx))?
619 .await?;
620 anyhow::Ok(Mention::Text {
621 content: summary.to_string(),
622 tracked_buffers: Vec::new(),
623 })
624 })
625 }
626
627 fn confirm_mention_for_text_thread(
628 &mut self,
629 path: PathBuf,
630 cx: &mut Context<Self>,
631 ) -> Task<Result<Mention>> {
632 let context = self.history_store.update(cx, |text_thread_store, cx| {
633 text_thread_store.load_text_thread(path.as_path().into(), cx)
634 });
635 cx.spawn(async move |_, cx| {
636 let context = context.await?;
637 let xml = context.update(cx, |context, cx| context.to_xml(cx))?;
638 Ok(Mention::Text {
639 content: xml,
640 tracked_buffers: Vec::new(),
641 })
642 })
643 }
644
645 fn validate_slash_commands(
646 text: &str,
647 available_commands: &[acp::AvailableCommand],
648 agent_name: &str,
649 ) -> Result<()> {
650 if let Some(parsed_command) = SlashCommandCompletion::try_parse(text, 0) {
651 if let Some(command_name) = parsed_command.command {
652 // Check if this command is in the list of available commands from the server
653 let is_supported = available_commands
654 .iter()
655 .any(|cmd| cmd.name == command_name);
656
657 if !is_supported {
658 return Err(anyhow!(
659 "The /{} command is not supported by {}.\n\nAvailable commands: {}",
660 command_name,
661 agent_name,
662 if available_commands.is_empty() {
663 "none".to_string()
664 } else {
665 available_commands
666 .iter()
667 .map(|cmd| format!("/{}", cmd.name))
668 .collect::<Vec<_>>()
669 .join(", ")
670 }
671 ));
672 }
673 }
674 }
675 Ok(())
676 }
677
678 pub fn contents(
679 &self,
680 full_mention_content: bool,
681 cx: &mut Context<Self>,
682 ) -> Task<Result<(Vec<acp::ContentBlock>, Vec<Entity<Buffer>>)>> {
683 // Check for unsupported slash commands before spawning async task
684 let text = self.editor.read(cx).text(cx);
685 let available_commands = self.available_commands.borrow().clone();
686 if let Err(err) =
687 Self::validate_slash_commands(&text, &available_commands, &self.agent_name)
688 {
689 return Task::ready(Err(err));
690 }
691
692 let contents = self.mention_set.contents(
693 &self.prompt_capabilities.borrow(),
694 full_mention_content,
695 self.project.clone(),
696 cx,
697 );
698 let editor = self.editor.clone();
699
700 cx.spawn(async move |_, cx| {
701 let contents = contents.await?;
702 let mut all_tracked_buffers = Vec::new();
703
704 let result = editor.update(cx, |editor, cx| {
705 let mut ix = 0;
706 let mut chunks: Vec<acp::ContentBlock> = Vec::new();
707 let text = editor.text(cx);
708 editor.display_map.update(cx, |map, cx| {
709 let snapshot = map.snapshot(cx);
710 for (crease_id, crease) in snapshot.crease_snapshot.creases() {
711 let Some((uri, mention)) = contents.get(&crease_id) else {
712 continue;
713 };
714
715 let crease_range = crease.range().to_offset(&snapshot.buffer_snapshot());
716 if crease_range.start > ix {
717 //todo(): Custom slash command ContentBlock?
718 // let chunk = if prevent_slash_commands
719 // && ix == 0
720 // && parse_slash_command(&text[ix..]).is_some()
721 // {
722 // format!(" {}", &text[ix..crease_range.start]).into()
723 // } else {
724 // text[ix..crease_range.start].into()
725 // };
726 let chunk = text[ix..crease_range.start].into();
727 chunks.push(chunk);
728 }
729 let chunk = match mention {
730 Mention::Text {
731 content,
732 tracked_buffers,
733 } => {
734 all_tracked_buffers.extend(tracked_buffers.iter().cloned());
735 acp::ContentBlock::Resource(acp::EmbeddedResource {
736 annotations: None,
737 resource: acp::EmbeddedResourceResource::TextResourceContents(
738 acp::TextResourceContents {
739 mime_type: None,
740 text: content.clone(),
741 uri: uri.to_uri().to_string(),
742 meta: None,
743 },
744 ),
745 meta: None,
746 })
747 }
748 Mention::Image(mention_image) => {
749 let uri = match uri {
750 MentionUri::File { .. } => Some(uri.to_uri().to_string()),
751 MentionUri::PastedImage => None,
752 other => {
753 debug_panic!(
754 "unexpected mention uri for image: {:?}",
755 other
756 );
757 None
758 }
759 };
760 acp::ContentBlock::Image(acp::ImageContent {
761 annotations: None,
762 data: mention_image.data.to_string(),
763 mime_type: mention_image.format.mime_type().into(),
764 uri,
765 meta: None,
766 })
767 }
768 Mention::UriOnly => {
769 acp::ContentBlock::ResourceLink(acp::ResourceLink {
770 name: uri.name(),
771 uri: uri.to_uri().to_string(),
772 annotations: None,
773 description: None,
774 mime_type: None,
775 size: None,
776 title: None,
777 meta: None,
778 })
779 }
780 };
781 chunks.push(chunk);
782 ix = crease_range.end;
783 }
784
785 if ix < text.len() {
786 //todo(): Custom slash command ContentBlock?
787 // let last_chunk = if prevent_slash_commands
788 // && ix == 0
789 // && parse_slash_command(&text[ix..]).is_some()
790 // {
791 // format!(" {}", text[ix..].trim_end())
792 // } else {
793 // text[ix..].trim_end().to_owned()
794 // };
795 let last_chunk = text[ix..].trim_end().to_owned();
796 if !last_chunk.is_empty() {
797 chunks.push(last_chunk.into());
798 }
799 }
800 });
801 Ok((chunks, all_tracked_buffers))
802 })?;
803 result
804 })
805 }
806
807 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
808 self.editor.update(cx, |editor, cx| {
809 editor.clear(window, cx);
810 editor.remove_creases(
811 self.mention_set
812 .mentions
813 .drain()
814 .map(|(crease_id, _)| crease_id),
815 cx,
816 )
817 });
818 }
819
820 pub fn send(&mut self, cx: &mut Context<Self>) {
821 if self.is_empty(cx) {
822 return;
823 }
824 self.editor.update(cx, |editor, cx| {
825 editor.clear_inlay_hints(cx);
826 });
827 cx.emit(MessageEditorEvent::Send)
828 }
829
830 fn chat(&mut self, _: &Chat, _: &mut Window, cx: &mut Context<Self>) {
831 self.send(cx);
832 }
833
834 fn cancel(&mut self, _: &editor::actions::Cancel, _: &mut Window, cx: &mut Context<Self>) {
835 cx.emit(MessageEditorEvent::Cancel)
836 }
837
838 fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
839 if !self.prompt_capabilities.borrow().image {
840 return;
841 }
842
843 let images = cx
844 .read_from_clipboard()
845 .map(|item| {
846 item.into_entries()
847 .filter_map(|entry| {
848 if let ClipboardEntry::Image(image) = entry {
849 Some(image)
850 } else {
851 None
852 }
853 })
854 .collect::<Vec<_>>()
855 })
856 .unwrap_or_default();
857
858 if images.is_empty() {
859 return;
860 }
861 cx.stop_propagation();
862
863 let replacement_text = MentionUri::PastedImage.as_link().to_string();
864 for image in images {
865 let (excerpt_id, text_anchor, multibuffer_anchor) =
866 self.editor.update(cx, |message_editor, cx| {
867 let snapshot = message_editor.snapshot(window, cx);
868 let (excerpt_id, _, buffer_snapshot) =
869 snapshot.buffer_snapshot().as_singleton().unwrap();
870
871 let text_anchor = buffer_snapshot.anchor_before(buffer_snapshot.len());
872 let multibuffer_anchor = snapshot
873 .buffer_snapshot()
874 .anchor_in_excerpt(*excerpt_id, text_anchor);
875 message_editor.edit(
876 [(
877 multi_buffer::Anchor::max()..multi_buffer::Anchor::max(),
878 format!("{replacement_text} "),
879 )],
880 cx,
881 );
882 (*excerpt_id, text_anchor, multibuffer_anchor)
883 });
884
885 let content_len = replacement_text.len();
886 let Some(start_anchor) = multibuffer_anchor else {
887 continue;
888 };
889 let end_anchor = self.editor.update(cx, |editor, cx| {
890 let snapshot = editor.buffer().read(cx).snapshot(cx);
891 snapshot.anchor_before(start_anchor.to_offset(&snapshot) + content_len)
892 });
893 let image = Arc::new(image);
894 let Some((crease_id, tx)) = insert_crease_for_mention(
895 excerpt_id,
896 text_anchor,
897 content_len,
898 MentionUri::PastedImage.name().into(),
899 IconName::Image.path().into(),
900 Some(Task::ready(Ok(image.clone())).shared()),
901 self.editor.clone(),
902 window,
903 cx,
904 ) else {
905 continue;
906 };
907 let task = cx
908 .spawn_in(window, {
909 async move |_, cx| {
910 let format = image.format;
911 let image = cx
912 .update(|_, cx| LanguageModelImage::from_image(image, cx))
913 .map_err(|e| e.to_string())?
914 .await;
915 drop(tx);
916 if let Some(image) = image {
917 Ok(Mention::Image(MentionImage {
918 data: image.source,
919 format,
920 }))
921 } else {
922 Err("Failed to convert image".into())
923 }
924 }
925 })
926 .shared();
927
928 self.mention_set
929 .mentions
930 .insert(crease_id, (MentionUri::PastedImage, task.clone()));
931
932 cx.spawn_in(window, async move |this, cx| {
933 if task.await.notify_async_err(cx).is_none() {
934 this.update(cx, |this, cx| {
935 this.editor.update(cx, |editor, cx| {
936 editor.edit([(start_anchor..end_anchor, "")], cx);
937 });
938 this.mention_set.mentions.remove(&crease_id);
939 })
940 .ok();
941 }
942 })
943 .detach();
944 }
945 }
946
947 pub fn insert_dragged_files(
948 &mut self,
949 paths: Vec<project::ProjectPath>,
950 added_worktrees: Vec<Entity<Worktree>>,
951 window: &mut Window,
952 cx: &mut Context<Self>,
953 ) {
954 let path_style = self.project.read(cx).path_style(cx);
955 let buffer = self.editor.read(cx).buffer().clone();
956 let Some(buffer) = buffer.read(cx).as_singleton() else {
957 return;
958 };
959 let mut tasks = Vec::new();
960 for path in paths {
961 let Some(entry) = self.project.read(cx).entry_for_path(&path, cx) else {
962 continue;
963 };
964 let Some(worktree) = self.project.read(cx).worktree_for_id(path.worktree_id, cx) else {
965 continue;
966 };
967 let abs_path = worktree.read(cx).absolutize(&path.path);
968 let (file_name, _) =
969 crate::context_picker::file_context_picker::extract_file_name_and_directory(
970 &path.path,
971 worktree.read(cx).root_name(),
972 path_style,
973 );
974
975 let uri = if entry.is_dir() {
976 MentionUri::Directory { abs_path }
977 } else {
978 MentionUri::File { abs_path }
979 };
980
981 let new_text = format!("{} ", uri.as_link());
982 let content_len = new_text.len() - 1;
983
984 let anchor = buffer.update(cx, |buffer, _cx| buffer.anchor_before(buffer.len()));
985
986 self.editor.update(cx, |message_editor, cx| {
987 message_editor.edit(
988 [(
989 multi_buffer::Anchor::max()..multi_buffer::Anchor::max(),
990 new_text,
991 )],
992 cx,
993 );
994 });
995 tasks.push(self.confirm_mention_completion(
996 file_name,
997 anchor,
998 content_len,
999 uri,
1000 window,
1001 cx,
1002 ));
1003 }
1004 cx.spawn(async move |_, _| {
1005 join_all(tasks).await;
1006 drop(added_worktrees);
1007 })
1008 .detach();
1009 }
1010
1011 pub fn insert_selections(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1012 let editor = self.editor.read(cx);
1013 let editor_buffer = editor.buffer().read(cx);
1014 let Some(buffer) = editor_buffer.as_singleton() else {
1015 return;
1016 };
1017 let cursor_anchor = editor.selections.newest_anchor().head();
1018 let cursor_offset = cursor_anchor.to_offset(&editor_buffer.snapshot(cx));
1019 let anchor = buffer.update(cx, |buffer, _cx| {
1020 buffer.anchor_before(cursor_offset.min(buffer.len()))
1021 });
1022 let Some(workspace) = self.workspace.upgrade() else {
1023 return;
1024 };
1025 let Some(completion) = ContextPickerCompletionProvider::completion_for_action(
1026 ContextPickerAction::AddSelections,
1027 anchor..anchor,
1028 cx.weak_entity(),
1029 &workspace,
1030 cx,
1031 ) else {
1032 return;
1033 };
1034
1035 self.editor.update(cx, |message_editor, cx| {
1036 message_editor.edit([(cursor_anchor..cursor_anchor, completion.new_text)], cx);
1037 });
1038 if let Some(confirm) = completion.confirm {
1039 confirm(CompletionIntent::Complete, window, cx);
1040 }
1041 }
1042
1043 pub fn set_read_only(&mut self, read_only: bool, cx: &mut Context<Self>) {
1044 self.editor.update(cx, |message_editor, cx| {
1045 message_editor.set_read_only(read_only);
1046 cx.notify()
1047 })
1048 }
1049
1050 pub fn set_mode(&mut self, mode: EditorMode, cx: &mut Context<Self>) {
1051 self.editor.update(cx, |editor, cx| {
1052 editor.set_mode(mode);
1053 cx.notify()
1054 });
1055 }
1056
1057 pub fn set_message(
1058 &mut self,
1059 message: Vec<acp::ContentBlock>,
1060 window: &mut Window,
1061 cx: &mut Context<Self>,
1062 ) {
1063 self.clear(window, cx);
1064
1065 let mut text = String::new();
1066 let mut mentions = Vec::new();
1067
1068 for chunk in message {
1069 match chunk {
1070 acp::ContentBlock::Text(text_content) => {
1071 text.push_str(&text_content.text);
1072 }
1073 acp::ContentBlock::Resource(acp::EmbeddedResource {
1074 resource: acp::EmbeddedResourceResource::TextResourceContents(resource),
1075 ..
1076 }) => {
1077 let Some(mention_uri) = MentionUri::parse(&resource.uri).log_err() else {
1078 continue;
1079 };
1080 let start = text.len();
1081 write!(&mut text, "{}", mention_uri.as_link()).ok();
1082 let end = text.len();
1083 mentions.push((
1084 start..end,
1085 mention_uri,
1086 Mention::Text {
1087 content: resource.text,
1088 tracked_buffers: Vec::new(),
1089 },
1090 ));
1091 }
1092 acp::ContentBlock::ResourceLink(resource) => {
1093 if let Some(mention_uri) = MentionUri::parse(&resource.uri).log_err() {
1094 let start = text.len();
1095 write!(&mut text, "{}", mention_uri.as_link()).ok();
1096 let end = text.len();
1097 mentions.push((start..end, mention_uri, Mention::UriOnly));
1098 }
1099 }
1100 acp::ContentBlock::Image(acp::ImageContent {
1101 uri,
1102 data,
1103 mime_type,
1104 annotations: _,
1105 meta: _,
1106 }) => {
1107 let mention_uri = if let Some(uri) = uri {
1108 MentionUri::parse(&uri)
1109 } else {
1110 Ok(MentionUri::PastedImage)
1111 };
1112 let Some(mention_uri) = mention_uri.log_err() else {
1113 continue;
1114 };
1115 let Some(format) = ImageFormat::from_mime_type(&mime_type) else {
1116 log::error!("failed to parse MIME type for image: {mime_type:?}");
1117 continue;
1118 };
1119 let start = text.len();
1120 write!(&mut text, "{}", mention_uri.as_link()).ok();
1121 let end = text.len();
1122 mentions.push((
1123 start..end,
1124 mention_uri,
1125 Mention::Image(MentionImage {
1126 data: data.into(),
1127 format,
1128 }),
1129 ));
1130 }
1131 acp::ContentBlock::Audio(_) | acp::ContentBlock::Resource(_) => {}
1132 }
1133 }
1134
1135 let snapshot = self.editor.update(cx, |editor, cx| {
1136 editor.set_text(text, window, cx);
1137 editor.buffer().read(cx).snapshot(cx)
1138 });
1139
1140 for (range, mention_uri, mention) in mentions {
1141 let anchor = snapshot.anchor_before(range.start);
1142 let Some((crease_id, tx)) = insert_crease_for_mention(
1143 anchor.excerpt_id,
1144 anchor.text_anchor,
1145 range.end - range.start,
1146 mention_uri.name().into(),
1147 mention_uri.icon_path(cx),
1148 None,
1149 self.editor.clone(),
1150 window,
1151 cx,
1152 ) else {
1153 continue;
1154 };
1155 drop(tx);
1156
1157 self.mention_set.mentions.insert(
1158 crease_id,
1159 (mention_uri.clone(), Task::ready(Ok(mention)).shared()),
1160 );
1161 }
1162 cx.notify();
1163 }
1164
1165 pub fn text(&self, cx: &App) -> String {
1166 self.editor.read(cx).text(cx)
1167 }
1168
1169 #[cfg(test)]
1170 pub fn set_text(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
1171 self.editor.update(cx, |editor, cx| {
1172 editor.set_text(text, window, cx);
1173 });
1174 }
1175}
1176
1177fn full_mention_for_directory(
1178 project: &Entity<Project>,
1179 abs_path: &Path,
1180 cx: &mut App,
1181) -> Task<Result<Mention>> {
1182 fn collect_files_in_path(worktree: &Worktree, path: &RelPath) -> Vec<(Arc<RelPath>, String)> {
1183 let mut files = Vec::new();
1184
1185 for entry in worktree.child_entries(path) {
1186 if entry.is_dir() {
1187 files.extend(collect_files_in_path(worktree, &entry.path));
1188 } else if entry.is_file() {
1189 files.push((
1190 entry.path.clone(),
1191 worktree
1192 .full_path(&entry.path)
1193 .to_string_lossy()
1194 .to_string(),
1195 ));
1196 }
1197 }
1198
1199 files
1200 }
1201
1202 let Some(project_path) = project
1203 .read(cx)
1204 .project_path_for_absolute_path(&abs_path, cx)
1205 else {
1206 return Task::ready(Err(anyhow!("project path not found")));
1207 };
1208 let Some(entry) = project.read(cx).entry_for_path(&project_path, cx) else {
1209 return Task::ready(Err(anyhow!("project entry not found")));
1210 };
1211 let directory_path = entry.path.clone();
1212 let worktree_id = project_path.worktree_id;
1213 let Some(worktree) = project.read(cx).worktree_for_id(worktree_id, cx) else {
1214 return Task::ready(Err(anyhow!("worktree not found")));
1215 };
1216 let project = project.clone();
1217 cx.spawn(async move |cx| {
1218 let file_paths = worktree.read_with(cx, |worktree, _cx| {
1219 collect_files_in_path(worktree, &directory_path)
1220 })?;
1221 let descendants_future = cx.update(|cx| {
1222 join_all(file_paths.into_iter().map(|(worktree_path, full_path)| {
1223 let rel_path = worktree_path
1224 .strip_prefix(&directory_path)
1225 .log_err()
1226 .map_or_else(|| worktree_path.clone(), |rel_path| rel_path.into());
1227
1228 let open_task = project.update(cx, |project, cx| {
1229 project.buffer_store().update(cx, |buffer_store, cx| {
1230 let project_path = ProjectPath {
1231 worktree_id,
1232 path: worktree_path,
1233 };
1234 buffer_store.open_buffer(project_path, cx)
1235 })
1236 });
1237
1238 cx.spawn(async move |cx| {
1239 let buffer = open_task.await.log_err()?;
1240 let buffer_content = outline::get_buffer_content_or_outline(
1241 buffer.clone(),
1242 Some(&full_path),
1243 &cx,
1244 )
1245 .await
1246 .ok()?;
1247
1248 Some((rel_path, full_path, buffer_content.text, buffer))
1249 })
1250 }))
1251 })?;
1252
1253 let contents = cx
1254 .background_spawn(async move {
1255 let (contents, tracked_buffers) = descendants_future
1256 .await
1257 .into_iter()
1258 .flatten()
1259 .map(|(rel_path, full_path, rope, buffer)| {
1260 ((rel_path, full_path, rope), buffer)
1261 })
1262 .unzip();
1263 Mention::Text {
1264 content: render_directory_contents(contents),
1265 tracked_buffers,
1266 }
1267 })
1268 .await;
1269 anyhow::Ok(contents)
1270 })
1271}
1272
1273fn render_directory_contents(entries: Vec<(Arc<RelPath>, String, String)>) -> String {
1274 let mut output = String::new();
1275 for (_relative_path, full_path, content) in entries {
1276 let fence = codeblock_fence_for_path(Some(&full_path), None);
1277 write!(output, "\n{fence}\n{content}\n```").unwrap();
1278 }
1279 output
1280}
1281
1282impl Focusable for MessageEditor {
1283 fn focus_handle(&self, cx: &App) -> FocusHandle {
1284 self.editor.focus_handle(cx)
1285 }
1286}
1287
1288impl Render for MessageEditor {
1289 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1290 div()
1291 .key_context("MessageEditor")
1292 .on_action(cx.listener(Self::chat))
1293 .on_action(cx.listener(Self::cancel))
1294 .capture_action(cx.listener(Self::paste))
1295 .flex_1()
1296 .child({
1297 let settings = ThemeSettings::get_global(cx);
1298
1299 let text_style = TextStyle {
1300 color: cx.theme().colors().text,
1301 font_family: settings.buffer_font.family.clone(),
1302 font_fallbacks: settings.buffer_font.fallbacks.clone(),
1303 font_features: settings.buffer_font.features.clone(),
1304 font_size: settings.agent_buffer_font_size(cx).into(),
1305 line_height: relative(settings.buffer_line_height.value()),
1306 ..Default::default()
1307 };
1308
1309 EditorElement::new(
1310 &self.editor,
1311 EditorStyle {
1312 background: cx.theme().colors().editor_background,
1313 local_player: cx.theme().players().local(),
1314 text: text_style,
1315 syntax: cx.theme().syntax().clone(),
1316 inlay_hints_style: editor::make_inlay_hints_style(cx),
1317 ..Default::default()
1318 },
1319 )
1320 })
1321 }
1322}
1323
1324pub(crate) fn insert_crease_for_mention(
1325 excerpt_id: ExcerptId,
1326 anchor: text::Anchor,
1327 content_len: usize,
1328 crease_label: SharedString,
1329 crease_icon: SharedString,
1330 // abs_path: Option<Arc<Path>>,
1331 image: Option<Shared<Task<Result<Arc<Image>, String>>>>,
1332 editor: Entity<Editor>,
1333 window: &mut Window,
1334 cx: &mut App,
1335) -> Option<(CreaseId, postage::barrier::Sender)> {
1336 let (tx, rx) = postage::barrier::channel();
1337
1338 let crease_id = editor.update(cx, |editor, cx| {
1339 let snapshot = editor.buffer().read(cx).snapshot(cx);
1340
1341 let start = snapshot.anchor_in_excerpt(excerpt_id, anchor)?;
1342
1343 let start = start.bias_right(&snapshot);
1344 let end = snapshot.anchor_before(start.to_offset(&snapshot) + content_len);
1345
1346 let placeholder = FoldPlaceholder {
1347 render: render_mention_fold_button(
1348 crease_label,
1349 crease_icon,
1350 start..end,
1351 rx,
1352 image,
1353 cx.weak_entity(),
1354 cx,
1355 ),
1356 merge_adjacent: false,
1357 ..Default::default()
1358 };
1359
1360 let crease = Crease::Inline {
1361 range: start..end,
1362 placeholder,
1363 render_toggle: None,
1364 render_trailer: None,
1365 metadata: None,
1366 };
1367
1368 let ids = editor.insert_creases(vec![crease.clone()], cx);
1369 editor.fold_creases(vec![crease], false, window, cx);
1370
1371 Some(ids[0])
1372 })?;
1373
1374 Some((crease_id, tx))
1375}
1376
1377fn render_mention_fold_button(
1378 label: SharedString,
1379 icon: SharedString,
1380 range: Range<Anchor>,
1381 mut loading_finished: postage::barrier::Receiver,
1382 image_task: Option<Shared<Task<Result<Arc<Image>, String>>>>,
1383 editor: WeakEntity<Editor>,
1384 cx: &mut App,
1385) -> Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut App) -> AnyElement> {
1386 let loading = cx.new(|cx| {
1387 let loading = cx.spawn(async move |this, cx| {
1388 loading_finished.recv().await;
1389 this.update(cx, |this: &mut LoadingContext, cx| {
1390 this.loading = None;
1391 cx.notify();
1392 })
1393 .ok();
1394 });
1395 LoadingContext {
1396 id: cx.entity_id(),
1397 label,
1398 icon,
1399 range,
1400 editor,
1401 loading: Some(loading),
1402 image: image_task.clone(),
1403 }
1404 });
1405 Arc::new(move |_fold_id, _fold_range, _cx| loading.clone().into_any_element())
1406}
1407
1408struct LoadingContext {
1409 id: EntityId,
1410 label: SharedString,
1411 icon: SharedString,
1412 range: Range<Anchor>,
1413 editor: WeakEntity<Editor>,
1414 loading: Option<Task<()>>,
1415 image: Option<Shared<Task<Result<Arc<Image>, String>>>>,
1416}
1417
1418impl Render for LoadingContext {
1419 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1420 let is_in_text_selection = self
1421 .editor
1422 .update(cx, |editor, cx| editor.is_range_selected(&self.range, cx))
1423 .unwrap_or_default();
1424 ButtonLike::new(("loading-context", self.id))
1425 .style(ButtonStyle::Filled)
1426 .selected_style(ButtonStyle::Tinted(TintColor::Accent))
1427 .toggle_state(is_in_text_selection)
1428 .when_some(self.image.clone(), |el, image_task| {
1429 el.hoverable_tooltip(move |_, cx| {
1430 let image = image_task.peek().cloned().transpose().ok().flatten();
1431 let image_task = image_task.clone();
1432 cx.new::<ImageHover>(|cx| ImageHover {
1433 image,
1434 _task: cx.spawn(async move |this, cx| {
1435 if let Ok(image) = image_task.clone().await {
1436 this.update(cx, |this, cx| {
1437 if this.image.replace(image).is_none() {
1438 cx.notify();
1439 }
1440 })
1441 .ok();
1442 }
1443 }),
1444 })
1445 .into()
1446 })
1447 })
1448 .child(
1449 h_flex()
1450 .gap_1()
1451 .child(
1452 Icon::from_path(self.icon.clone())
1453 .size(IconSize::XSmall)
1454 .color(Color::Muted),
1455 )
1456 .child(
1457 Label::new(self.label.clone())
1458 .size(LabelSize::Small)
1459 .buffer_font(cx)
1460 .single_line(),
1461 )
1462 .map(|el| {
1463 if self.loading.is_some() {
1464 el.with_animation(
1465 "loading-context-crease",
1466 Animation::new(Duration::from_secs(2))
1467 .repeat()
1468 .with_easing(pulsating_between(0.4, 0.8)),
1469 |label, delta| label.opacity(delta),
1470 )
1471 .into_any()
1472 } else {
1473 el.into_any()
1474 }
1475 }),
1476 )
1477 }
1478}
1479
1480struct ImageHover {
1481 image: Option<Arc<Image>>,
1482 _task: Task<()>,
1483}
1484
1485impl Render for ImageHover {
1486 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
1487 if let Some(image) = self.image.clone() {
1488 gpui::img(image).max_w_96().max_h_96().into_any_element()
1489 } else {
1490 gpui::Empty.into_any_element()
1491 }
1492 }
1493}
1494
1495#[derive(Debug, Clone, Eq, PartialEq)]
1496pub enum Mention {
1497 Text {
1498 content: String,
1499 tracked_buffers: Vec<Entity<Buffer>>,
1500 },
1501 Image(MentionImage),
1502 UriOnly,
1503}
1504
1505#[derive(Clone, Debug, Eq, PartialEq)]
1506pub struct MentionImage {
1507 pub data: SharedString,
1508 pub format: ImageFormat,
1509}
1510
1511#[derive(Default)]
1512pub struct MentionSet {
1513 mentions: HashMap<CreaseId, (MentionUri, Shared<Task<Result<Mention, String>>>)>,
1514}
1515
1516impl MentionSet {
1517 fn contents(
1518 &self,
1519 prompt_capabilities: &acp::PromptCapabilities,
1520 full_mention_content: bool,
1521 project: Entity<Project>,
1522 cx: &mut App,
1523 ) -> Task<Result<HashMap<CreaseId, (MentionUri, Mention)>>> {
1524 if !prompt_capabilities.embedded_context {
1525 let mentions = self
1526 .mentions
1527 .iter()
1528 .map(|(crease_id, (uri, _))| (*crease_id, (uri.clone(), Mention::UriOnly)))
1529 .collect();
1530
1531 return Task::ready(Ok(mentions));
1532 }
1533
1534 let mentions = self.mentions.clone();
1535 cx.spawn(async move |cx| {
1536 let mut contents = HashMap::default();
1537 for (crease_id, (mention_uri, task)) in mentions {
1538 let content = if full_mention_content
1539 && let MentionUri::Directory { abs_path } = &mention_uri
1540 {
1541 cx.update(|cx| full_mention_for_directory(&project, abs_path, cx))?
1542 .await?
1543 } else {
1544 task.await.map_err(|e| anyhow!("{e}"))?
1545 };
1546
1547 contents.insert(crease_id, (mention_uri, content));
1548 }
1549 Ok(contents)
1550 })
1551 }
1552
1553 fn remove_invalid(&mut self, snapshot: EditorSnapshot) {
1554 for (crease_id, crease) in snapshot.crease_snapshot.creases() {
1555 if !crease.range().start.is_valid(&snapshot.buffer_snapshot()) {
1556 self.mentions.remove(&crease_id);
1557 }
1558 }
1559 }
1560}
1561
1562pub struct MessageEditorAddon {}
1563
1564impl MessageEditorAddon {
1565 pub fn new() -> Self {
1566 Self {}
1567 }
1568}
1569
1570impl Addon for MessageEditorAddon {
1571 fn to_any(&self) -> &dyn std::any::Any {
1572 self
1573 }
1574
1575 fn to_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
1576 Some(self)
1577 }
1578
1579 fn extend_key_context(&self, key_context: &mut KeyContext, cx: &App) {
1580 let settings = agent_settings::AgentSettings::get_global(cx);
1581 if settings.use_modifier_to_send {
1582 key_context.add("use_modifier_to_send");
1583 }
1584 }
1585}
1586
1587#[cfg(test)]
1588mod tests {
1589 use std::{cell::RefCell, ops::Range, path::Path, rc::Rc, sync::Arc};
1590
1591 use acp_thread::MentionUri;
1592 use agent_client_protocol as acp;
1593 use agent2::HistoryStore;
1594 use assistant_context::ContextStore;
1595 use assistant_tool::outline;
1596 use editor::{AnchorRangeExt as _, Editor, EditorMode};
1597 use fs::FakeFs;
1598 use futures::StreamExt as _;
1599 use gpui::{
1600 AppContext, Entity, EventEmitter, FocusHandle, Focusable, TestAppContext, VisualTestContext,
1601 };
1602 use lsp::{CompletionContext, CompletionTriggerKind};
1603 use project::{CompletionIntent, Project, ProjectPath};
1604 use serde_json::json;
1605 use text::Point;
1606 use ui::{App, Context, IntoElement, Render, SharedString, Window};
1607 use util::{path, paths::PathStyle, rel_path::rel_path};
1608 use workspace::{AppState, Item, Workspace};
1609
1610 use crate::acp::{
1611 message_editor::{Mention, MessageEditor},
1612 thread_view::tests::init_test,
1613 };
1614
1615 #[gpui::test]
1616 async fn test_at_mention_removal(cx: &mut TestAppContext) {
1617 init_test(cx);
1618
1619 let fs = FakeFs::new(cx.executor());
1620 fs.insert_tree("/project", json!({"file": ""})).await;
1621 let project = Project::test(fs, [Path::new(path!("/project"))], cx).await;
1622
1623 let (workspace, cx) =
1624 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1625
1626 let context_store = cx.new(|cx| ContextStore::fake(project.clone(), cx));
1627 let history_store = cx.new(|cx| HistoryStore::new(context_store, cx));
1628
1629 let message_editor = cx.update(|window, cx| {
1630 cx.new(|cx| {
1631 MessageEditor::new(
1632 workspace.downgrade(),
1633 project.clone(),
1634 history_store.clone(),
1635 None,
1636 Default::default(),
1637 Default::default(),
1638 "Test Agent".into(),
1639 "Test",
1640 EditorMode::AutoHeight {
1641 min_lines: 1,
1642 max_lines: None,
1643 },
1644 window,
1645 cx,
1646 )
1647 })
1648 });
1649 let editor = message_editor.update(cx, |message_editor, _| message_editor.editor.clone());
1650
1651 cx.run_until_parked();
1652
1653 let excerpt_id = editor.update(cx, |editor, cx| {
1654 editor
1655 .buffer()
1656 .read(cx)
1657 .excerpt_ids()
1658 .into_iter()
1659 .next()
1660 .unwrap()
1661 });
1662 let completions = editor.update_in(cx, |editor, window, cx| {
1663 editor.set_text("Hello @file ", window, cx);
1664 let buffer = editor.buffer().read(cx).as_singleton().unwrap();
1665 let completion_provider = editor.completion_provider().unwrap();
1666 completion_provider.completions(
1667 excerpt_id,
1668 &buffer,
1669 text::Anchor::MAX,
1670 CompletionContext {
1671 trigger_kind: CompletionTriggerKind::TRIGGER_CHARACTER,
1672 trigger_character: Some("@".into()),
1673 },
1674 window,
1675 cx,
1676 )
1677 });
1678 let [_, completion]: [_; 2] = completions
1679 .await
1680 .unwrap()
1681 .into_iter()
1682 .flat_map(|response| response.completions)
1683 .collect::<Vec<_>>()
1684 .try_into()
1685 .unwrap();
1686
1687 editor.update_in(cx, |editor, window, cx| {
1688 let snapshot = editor.buffer().read(cx).snapshot(cx);
1689 let range = snapshot
1690 .anchor_range_in_excerpt(excerpt_id, completion.replace_range)
1691 .unwrap();
1692 editor.edit([(range, completion.new_text)], cx);
1693 (completion.confirm.unwrap())(CompletionIntent::Complete, window, cx);
1694 });
1695
1696 cx.run_until_parked();
1697
1698 // Backspace over the inserted crease (and the following space).
1699 editor.update_in(cx, |editor, window, cx| {
1700 editor.backspace(&Default::default(), window, cx);
1701 editor.backspace(&Default::default(), window, cx);
1702 });
1703
1704 let (content, _) = message_editor
1705 .update(cx, |message_editor, cx| message_editor.contents(false, cx))
1706 .await
1707 .unwrap();
1708
1709 // We don't send a resource link for the deleted crease.
1710 pretty_assertions::assert_matches!(content.as_slice(), [acp::ContentBlock::Text { .. }]);
1711 }
1712
1713 #[gpui::test]
1714 async fn test_slash_command_validation(cx: &mut gpui::TestAppContext) {
1715 init_test(cx);
1716 let fs = FakeFs::new(cx.executor());
1717 fs.insert_tree(
1718 "/test",
1719 json!({
1720 ".zed": {
1721 "tasks.json": r#"[{"label": "test", "command": "echo"}]"#
1722 },
1723 "src": {
1724 "main.rs": "fn main() {}",
1725 },
1726 }),
1727 )
1728 .await;
1729
1730 let project = Project::test(fs.clone(), ["/test".as_ref()], cx).await;
1731 let context_store = cx.new(|cx| ContextStore::fake(project.clone(), cx));
1732 let history_store = cx.new(|cx| HistoryStore::new(context_store, cx));
1733 let prompt_capabilities = Rc::new(RefCell::new(acp::PromptCapabilities::default()));
1734 // Start with no available commands - simulating Claude which doesn't support slash commands
1735 let available_commands = Rc::new(RefCell::new(vec![]));
1736
1737 let (workspace, cx) =
1738 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1739 let workspace_handle = workspace.downgrade();
1740 let message_editor = workspace.update_in(cx, |_, window, cx| {
1741 cx.new(|cx| {
1742 MessageEditor::new(
1743 workspace_handle.clone(),
1744 project.clone(),
1745 history_store.clone(),
1746 None,
1747 prompt_capabilities.clone(),
1748 available_commands.clone(),
1749 "Claude Code".into(),
1750 "Test",
1751 EditorMode::AutoHeight {
1752 min_lines: 1,
1753 max_lines: None,
1754 },
1755 window,
1756 cx,
1757 )
1758 })
1759 });
1760 let editor = message_editor.update(cx, |message_editor, _| message_editor.editor.clone());
1761
1762 // Test that slash commands fail when no available_commands are set (empty list means no commands supported)
1763 editor.update_in(cx, |editor, window, cx| {
1764 editor.set_text("/file test.txt", window, cx);
1765 });
1766
1767 let contents_result = message_editor
1768 .update(cx, |message_editor, cx| message_editor.contents(false, cx))
1769 .await;
1770
1771 // Should fail because available_commands is empty (no commands supported)
1772 assert!(contents_result.is_err());
1773 let error_message = contents_result.unwrap_err().to_string();
1774 assert!(error_message.contains("not supported by Claude Code"));
1775 assert!(error_message.contains("Available commands: none"));
1776
1777 // Now simulate Claude providing its list of available commands (which doesn't include file)
1778 available_commands.replace(vec![acp::AvailableCommand {
1779 name: "help".to_string(),
1780 description: "Get help".to_string(),
1781 input: None,
1782 meta: None,
1783 }]);
1784
1785 // Test that unsupported slash commands trigger an error when we have a list of available commands
1786 editor.update_in(cx, |editor, window, cx| {
1787 editor.set_text("/file test.txt", window, cx);
1788 });
1789
1790 let contents_result = message_editor
1791 .update(cx, |message_editor, cx| message_editor.contents(false, cx))
1792 .await;
1793
1794 assert!(contents_result.is_err());
1795 let error_message = contents_result.unwrap_err().to_string();
1796 assert!(error_message.contains("not supported by Claude Code"));
1797 assert!(error_message.contains("/file"));
1798 assert!(error_message.contains("Available commands: /help"));
1799
1800 // Test that supported commands work fine
1801 editor.update_in(cx, |editor, window, cx| {
1802 editor.set_text("/help", window, cx);
1803 });
1804
1805 let contents_result = message_editor
1806 .update(cx, |message_editor, cx| message_editor.contents(false, cx))
1807 .await;
1808
1809 // Should succeed because /help is in available_commands
1810 assert!(contents_result.is_ok());
1811
1812 // Test that regular text works fine
1813 editor.update_in(cx, |editor, window, cx| {
1814 editor.set_text("Hello Claude!", window, cx);
1815 });
1816
1817 let (content, _) = message_editor
1818 .update(cx, |message_editor, cx| message_editor.contents(false, cx))
1819 .await
1820 .unwrap();
1821
1822 assert_eq!(content.len(), 1);
1823 if let acp::ContentBlock::Text(text) = &content[0] {
1824 assert_eq!(text.text, "Hello Claude!");
1825 } else {
1826 panic!("Expected ContentBlock::Text");
1827 }
1828
1829 // Test that @ mentions still work
1830 editor.update_in(cx, |editor, window, cx| {
1831 editor.set_text("Check this @", window, cx);
1832 });
1833
1834 // The @ mention functionality should not be affected
1835 let (content, _) = message_editor
1836 .update(cx, |message_editor, cx| message_editor.contents(false, cx))
1837 .await
1838 .unwrap();
1839
1840 assert_eq!(content.len(), 1);
1841 if let acp::ContentBlock::Text(text) = &content[0] {
1842 assert_eq!(text.text, "Check this @");
1843 } else {
1844 panic!("Expected ContentBlock::Text");
1845 }
1846 }
1847
1848 struct MessageEditorItem(Entity<MessageEditor>);
1849
1850 impl Item for MessageEditorItem {
1851 type Event = ();
1852
1853 fn include_in_nav_history() -> bool {
1854 false
1855 }
1856
1857 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
1858 "Test".into()
1859 }
1860 }
1861
1862 impl EventEmitter<()> for MessageEditorItem {}
1863
1864 impl Focusable for MessageEditorItem {
1865 fn focus_handle(&self, cx: &App) -> FocusHandle {
1866 self.0.read(cx).focus_handle(cx)
1867 }
1868 }
1869
1870 impl Render for MessageEditorItem {
1871 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
1872 self.0.clone().into_any_element()
1873 }
1874 }
1875
1876 #[gpui::test]
1877 async fn test_completion_provider_commands(cx: &mut TestAppContext) {
1878 init_test(cx);
1879
1880 let app_state = cx.update(AppState::test);
1881
1882 cx.update(|cx| {
1883 language::init(cx);
1884 editor::init(cx);
1885 workspace::init(app_state.clone(), cx);
1886 Project::init_settings(cx);
1887 });
1888
1889 let project = Project::test(app_state.fs.clone(), [path!("/dir").as_ref()], cx).await;
1890 let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
1891 let workspace = window.root(cx).unwrap();
1892
1893 let mut cx = VisualTestContext::from_window(*window, cx);
1894
1895 let context_store = cx.new(|cx| ContextStore::fake(project.clone(), cx));
1896 let history_store = cx.new(|cx| HistoryStore::new(context_store, cx));
1897 let prompt_capabilities = Rc::new(RefCell::new(acp::PromptCapabilities::default()));
1898 let available_commands = Rc::new(RefCell::new(vec![
1899 acp::AvailableCommand {
1900 name: "quick-math".to_string(),
1901 description: "2 + 2 = 4 - 1 = 3".to_string(),
1902 input: None,
1903 meta: None,
1904 },
1905 acp::AvailableCommand {
1906 name: "say-hello".to_string(),
1907 description: "Say hello to whoever you want".to_string(),
1908 input: Some(acp::AvailableCommandInput::Unstructured {
1909 hint: "<name>".to_string(),
1910 }),
1911 meta: None,
1912 },
1913 ]));
1914
1915 let editor = workspace.update_in(&mut cx, |workspace, window, cx| {
1916 let workspace_handle = cx.weak_entity();
1917 let message_editor = cx.new(|cx| {
1918 MessageEditor::new(
1919 workspace_handle,
1920 project.clone(),
1921 history_store.clone(),
1922 None,
1923 prompt_capabilities.clone(),
1924 available_commands.clone(),
1925 "Test Agent".into(),
1926 "Test",
1927 EditorMode::AutoHeight {
1928 max_lines: None,
1929 min_lines: 1,
1930 },
1931 window,
1932 cx,
1933 )
1934 });
1935 workspace.active_pane().update(cx, |pane, cx| {
1936 pane.add_item(
1937 Box::new(cx.new(|_| MessageEditorItem(message_editor.clone()))),
1938 true,
1939 true,
1940 None,
1941 window,
1942 cx,
1943 );
1944 });
1945 message_editor.read(cx).focus_handle(cx).focus(window);
1946 message_editor.read(cx).editor().clone()
1947 });
1948
1949 cx.simulate_input("/");
1950
1951 editor.update_in(&mut cx, |editor, window, cx| {
1952 assert_eq!(editor.text(cx), "/");
1953 assert!(editor.has_visible_completions_menu());
1954
1955 assert_eq!(
1956 current_completion_labels_with_documentation(editor),
1957 &[
1958 ("quick-math".into(), "2 + 2 = 4 - 1 = 3".into()),
1959 ("say-hello".into(), "Say hello to whoever you want".into())
1960 ]
1961 );
1962 editor.set_text("", window, cx);
1963 });
1964
1965 cx.simulate_input("/qui");
1966
1967 editor.update_in(&mut cx, |editor, window, cx| {
1968 assert_eq!(editor.text(cx), "/qui");
1969 assert!(editor.has_visible_completions_menu());
1970
1971 assert_eq!(
1972 current_completion_labels_with_documentation(editor),
1973 &[("quick-math".into(), "2 + 2 = 4 - 1 = 3".into())]
1974 );
1975 editor.set_text("", window, cx);
1976 });
1977
1978 editor.update_in(&mut cx, |editor, window, cx| {
1979 assert!(editor.has_visible_completions_menu());
1980 editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
1981 });
1982
1983 cx.run_until_parked();
1984
1985 editor.update_in(&mut cx, |editor, window, cx| {
1986 assert_eq!(editor.display_text(cx), "/quick-math ");
1987 assert!(!editor.has_visible_completions_menu());
1988 editor.set_text("", window, cx);
1989 });
1990
1991 cx.simulate_input("/say");
1992
1993 editor.update_in(&mut cx, |editor, _window, cx| {
1994 assert_eq!(editor.display_text(cx), "/say");
1995 assert!(editor.has_visible_completions_menu());
1996
1997 assert_eq!(
1998 current_completion_labels_with_documentation(editor),
1999 &[("say-hello".into(), "Say hello to whoever you want".into())]
2000 );
2001 });
2002
2003 editor.update_in(&mut cx, |editor, window, cx| {
2004 assert!(editor.has_visible_completions_menu());
2005 editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
2006 });
2007
2008 cx.run_until_parked();
2009
2010 editor.update_in(&mut cx, |editor, _window, cx| {
2011 assert_eq!(editor.text(cx), "/say-hello ");
2012 assert_eq!(editor.display_text(cx), "/say-hello <name>");
2013 assert!(!editor.has_visible_completions_menu());
2014 });
2015
2016 cx.simulate_input("GPT5");
2017
2018 cx.run_until_parked();
2019
2020 editor.update_in(&mut cx, |editor, window, cx| {
2021 assert_eq!(editor.text(cx), "/say-hello GPT5");
2022 assert_eq!(editor.display_text(cx), "/say-hello GPT5");
2023 assert!(!editor.has_visible_completions_menu());
2024
2025 // Delete argument
2026 for _ in 0..5 {
2027 editor.backspace(&editor::actions::Backspace, window, cx);
2028 }
2029 });
2030
2031 cx.run_until_parked();
2032
2033 editor.update_in(&mut cx, |editor, window, cx| {
2034 assert_eq!(editor.text(cx), "/say-hello");
2035 // Hint is visible because argument was deleted
2036 assert_eq!(editor.display_text(cx), "/say-hello <name>");
2037
2038 // Delete last command letter
2039 editor.backspace(&editor::actions::Backspace, window, cx);
2040 });
2041
2042 cx.run_until_parked();
2043
2044 editor.update_in(&mut cx, |editor, _window, cx| {
2045 // Hint goes away once command no longer matches an available one
2046 assert_eq!(editor.text(cx), "/say-hell");
2047 assert_eq!(editor.display_text(cx), "/say-hell");
2048 assert!(!editor.has_visible_completions_menu());
2049 });
2050 }
2051
2052 #[gpui::test]
2053 async fn test_context_completion_provider_mentions(cx: &mut TestAppContext) {
2054 init_test(cx);
2055
2056 let app_state = cx.update(AppState::test);
2057
2058 cx.update(|cx| {
2059 language::init(cx);
2060 editor::init(cx);
2061 workspace::init(app_state.clone(), cx);
2062 Project::init_settings(cx);
2063 });
2064
2065 app_state
2066 .fs
2067 .as_fake()
2068 .insert_tree(
2069 path!("/dir"),
2070 json!({
2071 "editor": "",
2072 "a": {
2073 "one.txt": "1",
2074 "two.txt": "2",
2075 "three.txt": "3",
2076 "four.txt": "4"
2077 },
2078 "b": {
2079 "five.txt": "5",
2080 "six.txt": "6",
2081 "seven.txt": "7",
2082 "eight.txt": "8",
2083 },
2084 "x.png": "",
2085 }),
2086 )
2087 .await;
2088
2089 let project = Project::test(app_state.fs.clone(), [path!("/dir").as_ref()], cx).await;
2090 let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
2091 let workspace = window.root(cx).unwrap();
2092
2093 let worktree = project.update(cx, |project, cx| {
2094 let mut worktrees = project.worktrees(cx).collect::<Vec<_>>();
2095 assert_eq!(worktrees.len(), 1);
2096 worktrees.pop().unwrap()
2097 });
2098 let worktree_id = worktree.read_with(cx, |worktree, _| worktree.id());
2099
2100 let mut cx = VisualTestContext::from_window(*window, cx);
2101
2102 let paths = vec![
2103 rel_path("a/one.txt"),
2104 rel_path("a/two.txt"),
2105 rel_path("a/three.txt"),
2106 rel_path("a/four.txt"),
2107 rel_path("b/five.txt"),
2108 rel_path("b/six.txt"),
2109 rel_path("b/seven.txt"),
2110 rel_path("b/eight.txt"),
2111 ];
2112
2113 let slash = PathStyle::local().separator();
2114
2115 let mut opened_editors = Vec::new();
2116 for path in paths {
2117 let buffer = workspace
2118 .update_in(&mut cx, |workspace, window, cx| {
2119 workspace.open_path(
2120 ProjectPath {
2121 worktree_id,
2122 path: path.into(),
2123 },
2124 None,
2125 false,
2126 window,
2127 cx,
2128 )
2129 })
2130 .await
2131 .unwrap();
2132 opened_editors.push(buffer);
2133 }
2134
2135 let context_store = cx.new(|cx| ContextStore::fake(project.clone(), cx));
2136 let history_store = cx.new(|cx| HistoryStore::new(context_store, cx));
2137 let prompt_capabilities = Rc::new(RefCell::new(acp::PromptCapabilities::default()));
2138
2139 let (message_editor, editor) = workspace.update_in(&mut cx, |workspace, window, cx| {
2140 let workspace_handle = cx.weak_entity();
2141 let message_editor = cx.new(|cx| {
2142 MessageEditor::new(
2143 workspace_handle,
2144 project.clone(),
2145 history_store.clone(),
2146 None,
2147 prompt_capabilities.clone(),
2148 Default::default(),
2149 "Test Agent".into(),
2150 "Test",
2151 EditorMode::AutoHeight {
2152 max_lines: None,
2153 min_lines: 1,
2154 },
2155 window,
2156 cx,
2157 )
2158 });
2159 workspace.active_pane().update(cx, |pane, cx| {
2160 pane.add_item(
2161 Box::new(cx.new(|_| MessageEditorItem(message_editor.clone()))),
2162 true,
2163 true,
2164 None,
2165 window,
2166 cx,
2167 );
2168 });
2169 message_editor.read(cx).focus_handle(cx).focus(window);
2170 let editor = message_editor.read(cx).editor().clone();
2171 (message_editor, editor)
2172 });
2173
2174 cx.simulate_input("Lorem @");
2175
2176 editor.update_in(&mut cx, |editor, window, cx| {
2177 assert_eq!(editor.text(cx), "Lorem @");
2178 assert!(editor.has_visible_completions_menu());
2179
2180 assert_eq!(
2181 current_completion_labels(editor),
2182 &[
2183 format!("eight.txt dir{slash}b{slash}"),
2184 format!("seven.txt dir{slash}b{slash}"),
2185 format!("six.txt dir{slash}b{slash}"),
2186 format!("five.txt dir{slash}b{slash}"),
2187 ]
2188 );
2189 editor.set_text("", window, cx);
2190 });
2191
2192 prompt_capabilities.replace(acp::PromptCapabilities {
2193 image: true,
2194 audio: true,
2195 embedded_context: true,
2196 meta: None,
2197 });
2198
2199 cx.simulate_input("Lorem ");
2200
2201 editor.update(&mut cx, |editor, cx| {
2202 assert_eq!(editor.text(cx), "Lorem ");
2203 assert!(!editor.has_visible_completions_menu());
2204 });
2205
2206 cx.simulate_input("@");
2207
2208 editor.update(&mut cx, |editor, cx| {
2209 assert_eq!(editor.text(cx), "Lorem @");
2210 assert!(editor.has_visible_completions_menu());
2211 assert_eq!(
2212 current_completion_labels(editor),
2213 &[
2214 format!("eight.txt dir{slash}b{slash}"),
2215 format!("seven.txt dir{slash}b{slash}"),
2216 format!("six.txt dir{slash}b{slash}"),
2217 format!("five.txt dir{slash}b{slash}"),
2218 "Files & Directories".into(),
2219 "Symbols".into(),
2220 "Threads".into(),
2221 "Fetch".into()
2222 ]
2223 );
2224 });
2225
2226 // Select and confirm "File"
2227 editor.update_in(&mut cx, |editor, window, cx| {
2228 assert!(editor.has_visible_completions_menu());
2229 editor.context_menu_next(&editor::actions::ContextMenuNext, window, cx);
2230 editor.context_menu_next(&editor::actions::ContextMenuNext, window, cx);
2231 editor.context_menu_next(&editor::actions::ContextMenuNext, window, cx);
2232 editor.context_menu_next(&editor::actions::ContextMenuNext, window, cx);
2233 editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
2234 });
2235
2236 cx.run_until_parked();
2237
2238 editor.update(&mut cx, |editor, cx| {
2239 assert_eq!(editor.text(cx), "Lorem @file ");
2240 assert!(editor.has_visible_completions_menu());
2241 });
2242
2243 cx.simulate_input("one");
2244
2245 editor.update(&mut cx, |editor, cx| {
2246 assert_eq!(editor.text(cx), "Lorem @file one");
2247 assert!(editor.has_visible_completions_menu());
2248 assert_eq!(
2249 current_completion_labels(editor),
2250 vec![format!("one.txt dir{slash}a{slash}")]
2251 );
2252 });
2253
2254 editor.update_in(&mut cx, |editor, window, cx| {
2255 assert!(editor.has_visible_completions_menu());
2256 editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
2257 });
2258
2259 let url_one = MentionUri::File {
2260 abs_path: path!("/dir/a/one.txt").into(),
2261 }
2262 .to_uri()
2263 .to_string();
2264 editor.update(&mut cx, |editor, cx| {
2265 let text = editor.text(cx);
2266 assert_eq!(text, format!("Lorem [@one.txt]({url_one}) "));
2267 assert!(!editor.has_visible_completions_menu());
2268 assert_eq!(fold_ranges(editor, cx).len(), 1);
2269 });
2270
2271 let all_prompt_capabilities = acp::PromptCapabilities {
2272 image: true,
2273 audio: true,
2274 embedded_context: true,
2275 meta: None,
2276 };
2277
2278 let contents = message_editor
2279 .update(&mut cx, |message_editor, cx| {
2280 message_editor.mention_set().contents(
2281 &all_prompt_capabilities,
2282 false,
2283 project.clone(),
2284 cx,
2285 )
2286 })
2287 .await
2288 .unwrap()
2289 .into_values()
2290 .collect::<Vec<_>>();
2291
2292 {
2293 let [(uri, Mention::Text { content, .. })] = contents.as_slice() else {
2294 panic!("Unexpected mentions");
2295 };
2296 pretty_assertions::assert_eq!(content, "1");
2297 pretty_assertions::assert_eq!(uri, &url_one.parse::<MentionUri>().unwrap());
2298 }
2299
2300 let contents = message_editor
2301 .update(&mut cx, |message_editor, cx| {
2302 message_editor.mention_set().contents(
2303 &acp::PromptCapabilities::default(),
2304 false,
2305 project.clone(),
2306 cx,
2307 )
2308 })
2309 .await
2310 .unwrap()
2311 .into_values()
2312 .collect::<Vec<_>>();
2313
2314 {
2315 let [(uri, Mention::UriOnly)] = contents.as_slice() else {
2316 panic!("Unexpected mentions");
2317 };
2318 pretty_assertions::assert_eq!(uri, &url_one.parse::<MentionUri>().unwrap());
2319 }
2320
2321 cx.simulate_input(" ");
2322
2323 editor.update(&mut cx, |editor, cx| {
2324 let text = editor.text(cx);
2325 assert_eq!(text, format!("Lorem [@one.txt]({url_one}) "));
2326 assert!(!editor.has_visible_completions_menu());
2327 assert_eq!(fold_ranges(editor, cx).len(), 1);
2328 });
2329
2330 cx.simulate_input("Ipsum ");
2331
2332 editor.update(&mut cx, |editor, cx| {
2333 let text = editor.text(cx);
2334 assert_eq!(text, format!("Lorem [@one.txt]({url_one}) Ipsum "),);
2335 assert!(!editor.has_visible_completions_menu());
2336 assert_eq!(fold_ranges(editor, cx).len(), 1);
2337 });
2338
2339 cx.simulate_input("@file ");
2340
2341 editor.update(&mut cx, |editor, cx| {
2342 let text = editor.text(cx);
2343 assert_eq!(text, format!("Lorem [@one.txt]({url_one}) Ipsum @file "),);
2344 assert!(editor.has_visible_completions_menu());
2345 assert_eq!(fold_ranges(editor, cx).len(), 1);
2346 });
2347
2348 editor.update_in(&mut cx, |editor, window, cx| {
2349 editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
2350 });
2351
2352 cx.run_until_parked();
2353
2354 let contents = message_editor
2355 .update(&mut cx, |message_editor, cx| {
2356 message_editor.mention_set().contents(
2357 &all_prompt_capabilities,
2358 false,
2359 project.clone(),
2360 cx,
2361 )
2362 })
2363 .await
2364 .unwrap()
2365 .into_values()
2366 .collect::<Vec<_>>();
2367
2368 let url_eight = MentionUri::File {
2369 abs_path: path!("/dir/b/eight.txt").into(),
2370 }
2371 .to_uri()
2372 .to_string();
2373
2374 {
2375 let [_, (uri, Mention::Text { content, .. })] = contents.as_slice() else {
2376 panic!("Unexpected mentions");
2377 };
2378 pretty_assertions::assert_eq!(content, "8");
2379 pretty_assertions::assert_eq!(uri, &url_eight.parse::<MentionUri>().unwrap());
2380 }
2381
2382 editor.update(&mut cx, |editor, cx| {
2383 assert_eq!(
2384 editor.text(cx),
2385 format!("Lorem [@one.txt]({url_one}) Ipsum [@eight.txt]({url_eight}) ")
2386 );
2387 assert!(!editor.has_visible_completions_menu());
2388 assert_eq!(fold_ranges(editor, cx).len(), 2);
2389 });
2390
2391 let plain_text_language = Arc::new(language::Language::new(
2392 language::LanguageConfig {
2393 name: "Plain Text".into(),
2394 matcher: language::LanguageMatcher {
2395 path_suffixes: vec!["txt".to_string()],
2396 ..Default::default()
2397 },
2398 ..Default::default()
2399 },
2400 None,
2401 ));
2402
2403 // Register the language and fake LSP
2404 let language_registry = project.read_with(&cx, |project, _| project.languages().clone());
2405 language_registry.add(plain_text_language);
2406
2407 let mut fake_language_servers = language_registry.register_fake_lsp(
2408 "Plain Text",
2409 language::FakeLspAdapter {
2410 capabilities: lsp::ServerCapabilities {
2411 workspace_symbol_provider: Some(lsp::OneOf::Left(true)),
2412 ..Default::default()
2413 },
2414 ..Default::default()
2415 },
2416 );
2417
2418 // Open the buffer to trigger LSP initialization
2419 let buffer = project
2420 .update(&mut cx, |project, cx| {
2421 project.open_local_buffer(path!("/dir/a/one.txt"), cx)
2422 })
2423 .await
2424 .unwrap();
2425
2426 // Register the buffer with language servers
2427 let _handle = project.update(&mut cx, |project, cx| {
2428 project.register_buffer_with_language_servers(&buffer, cx)
2429 });
2430
2431 cx.run_until_parked();
2432
2433 let fake_language_server = fake_language_servers.next().await.unwrap();
2434 fake_language_server.set_request_handler::<lsp::WorkspaceSymbolRequest, _, _>(
2435 move |_, _| async move {
2436 Ok(Some(lsp::WorkspaceSymbolResponse::Flat(vec![
2437 #[allow(deprecated)]
2438 lsp::SymbolInformation {
2439 name: "MySymbol".into(),
2440 location: lsp::Location {
2441 uri: lsp::Uri::from_file_path(path!("/dir/a/one.txt")).unwrap(),
2442 range: lsp::Range::new(
2443 lsp::Position::new(0, 0),
2444 lsp::Position::new(0, 1),
2445 ),
2446 },
2447 kind: lsp::SymbolKind::CONSTANT,
2448 tags: None,
2449 container_name: None,
2450 deprecated: None,
2451 },
2452 ])))
2453 },
2454 );
2455
2456 cx.simulate_input("@symbol ");
2457
2458 editor.update(&mut cx, |editor, cx| {
2459 assert_eq!(
2460 editor.text(cx),
2461 format!("Lorem [@one.txt]({url_one}) Ipsum [@eight.txt]({url_eight}) @symbol ")
2462 );
2463 assert!(editor.has_visible_completions_menu());
2464 assert_eq!(current_completion_labels(editor), &["MySymbol"]);
2465 });
2466
2467 editor.update_in(&mut cx, |editor, window, cx| {
2468 editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
2469 });
2470
2471 let symbol = MentionUri::Symbol {
2472 abs_path: path!("/dir/a/one.txt").into(),
2473 name: "MySymbol".into(),
2474 line_range: 0..=0,
2475 };
2476
2477 let contents = message_editor
2478 .update(&mut cx, |message_editor, cx| {
2479 message_editor.mention_set().contents(
2480 &all_prompt_capabilities,
2481 false,
2482 project.clone(),
2483 cx,
2484 )
2485 })
2486 .await
2487 .unwrap()
2488 .into_values()
2489 .collect::<Vec<_>>();
2490
2491 {
2492 let [_, _, (uri, Mention::Text { content, .. })] = contents.as_slice() else {
2493 panic!("Unexpected mentions");
2494 };
2495 pretty_assertions::assert_eq!(content, "1");
2496 pretty_assertions::assert_eq!(uri, &symbol);
2497 }
2498
2499 cx.run_until_parked();
2500
2501 editor.read_with(&cx, |editor, cx| {
2502 assert_eq!(
2503 editor.text(cx),
2504 format!(
2505 "Lorem [@one.txt]({url_one}) Ipsum [@eight.txt]({url_eight}) [@MySymbol]({}) ",
2506 symbol.to_uri(),
2507 )
2508 );
2509 });
2510
2511 // Try to mention an "image" file that will fail to load
2512 cx.simulate_input("@file x.png");
2513
2514 editor.update(&mut cx, |editor, cx| {
2515 assert_eq!(
2516 editor.text(cx),
2517 format!("Lorem [@one.txt]({url_one}) Ipsum [@eight.txt]({url_eight}) [@MySymbol]({}) @file x.png", symbol.to_uri())
2518 );
2519 assert!(editor.has_visible_completions_menu());
2520 assert_eq!(current_completion_labels(editor), &[format!("x.png dir{slash}")]);
2521 });
2522
2523 editor.update_in(&mut cx, |editor, window, cx| {
2524 editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
2525 });
2526
2527 // Getting the message contents fails
2528 message_editor
2529 .update(&mut cx, |message_editor, cx| {
2530 message_editor.mention_set().contents(
2531 &all_prompt_capabilities,
2532 false,
2533 project.clone(),
2534 cx,
2535 )
2536 })
2537 .await
2538 .expect_err("Should fail to load x.png");
2539
2540 cx.run_until_parked();
2541
2542 // Mention was removed
2543 editor.read_with(&cx, |editor, cx| {
2544 assert_eq!(
2545 editor.text(cx),
2546 format!(
2547 "Lorem [@one.txt]({url_one}) Ipsum [@eight.txt]({url_eight}) [@MySymbol]({}) ",
2548 symbol.to_uri()
2549 )
2550 );
2551 });
2552
2553 // Once more
2554 cx.simulate_input("@file x.png");
2555
2556 editor.update(&mut cx, |editor, cx| {
2557 assert_eq!(
2558 editor.text(cx),
2559 format!("Lorem [@one.txt]({url_one}) Ipsum [@eight.txt]({url_eight}) [@MySymbol]({}) @file x.png", symbol.to_uri())
2560 );
2561 assert!(editor.has_visible_completions_menu());
2562 assert_eq!(current_completion_labels(editor), &[format!("x.png dir{slash}")]);
2563 });
2564
2565 editor.update_in(&mut cx, |editor, window, cx| {
2566 editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
2567 });
2568
2569 // This time don't immediately get the contents, just let the confirmed completion settle
2570 cx.run_until_parked();
2571
2572 // Mention was removed
2573 editor.read_with(&cx, |editor, cx| {
2574 assert_eq!(
2575 editor.text(cx),
2576 format!(
2577 "Lorem [@one.txt]({url_one}) Ipsum [@eight.txt]({url_eight}) [@MySymbol]({}) ",
2578 symbol.to_uri()
2579 )
2580 );
2581 });
2582
2583 // Now getting the contents succeeds, because the invalid mention was removed
2584 let contents = message_editor
2585 .update(&mut cx, |message_editor, cx| {
2586 message_editor.mention_set().contents(
2587 &all_prompt_capabilities,
2588 false,
2589 project.clone(),
2590 cx,
2591 )
2592 })
2593 .await
2594 .unwrap();
2595 assert_eq!(contents.len(), 3);
2596 }
2597
2598 fn fold_ranges(editor: &Editor, cx: &mut App) -> Vec<Range<Point>> {
2599 let snapshot = editor.buffer().read(cx).snapshot(cx);
2600 editor.display_map.update(cx, |display_map, cx| {
2601 display_map
2602 .snapshot(cx)
2603 .folds_in_range(0..snapshot.len())
2604 .map(|fold| fold.range.to_point(&snapshot))
2605 .collect()
2606 })
2607 }
2608
2609 fn current_completion_labels(editor: &Editor) -> Vec<String> {
2610 let completions = editor.current_completions().expect("Missing completions");
2611 completions
2612 .into_iter()
2613 .map(|completion| completion.label.text)
2614 .collect::<Vec<_>>()
2615 }
2616
2617 fn current_completion_labels_with_documentation(editor: &Editor) -> Vec<(String, String)> {
2618 let completions = editor.current_completions().expect("Missing completions");
2619 completions
2620 .into_iter()
2621 .map(|completion| {
2622 (
2623 completion.label.text,
2624 completion
2625 .documentation
2626 .map(|d| d.text().to_string())
2627 .unwrap_or_default(),
2628 )
2629 })
2630 .collect::<Vec<_>>()
2631 }
2632
2633 #[gpui::test]
2634 async fn test_large_file_mention_uses_outline(cx: &mut TestAppContext) {
2635 init_test(cx);
2636
2637 let fs = FakeFs::new(cx.executor());
2638
2639 // Create a large file that exceeds AUTO_OUTLINE_SIZE
2640 const LINE: &str = "fn example_function() { /* some code */ }\n";
2641 let large_content = LINE.repeat(2 * (outline::AUTO_OUTLINE_SIZE / LINE.len()));
2642 assert!(large_content.len() > outline::AUTO_OUTLINE_SIZE);
2643
2644 // Create a small file that doesn't exceed AUTO_OUTLINE_SIZE
2645 let small_content = "fn small_function() { /* small */ }\n";
2646 assert!(small_content.len() < outline::AUTO_OUTLINE_SIZE);
2647
2648 fs.insert_tree(
2649 "/project",
2650 json!({
2651 "large_file.rs": large_content.clone(),
2652 "small_file.rs": small_content,
2653 }),
2654 )
2655 .await;
2656
2657 let project = Project::test(fs, [Path::new(path!("/project"))], cx).await;
2658
2659 let (workspace, cx) =
2660 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2661
2662 let context_store = cx.new(|cx| ContextStore::fake(project.clone(), cx));
2663 let history_store = cx.new(|cx| HistoryStore::new(context_store, cx));
2664
2665 let message_editor = cx.update(|window, cx| {
2666 cx.new(|cx| {
2667 let editor = MessageEditor::new(
2668 workspace.downgrade(),
2669 project.clone(),
2670 history_store.clone(),
2671 None,
2672 Default::default(),
2673 Default::default(),
2674 "Test Agent".into(),
2675 "Test",
2676 EditorMode::AutoHeight {
2677 min_lines: 1,
2678 max_lines: None,
2679 },
2680 window,
2681 cx,
2682 );
2683 // Enable embedded context so files are actually included
2684 editor.prompt_capabilities.replace(acp::PromptCapabilities {
2685 embedded_context: true,
2686 meta: None,
2687 ..Default::default()
2688 });
2689 editor
2690 })
2691 });
2692
2693 // Test large file mention
2694 // Get the absolute path using the project's worktree
2695 let large_file_abs_path = project.read_with(cx, |project, cx| {
2696 let worktree = project.worktrees(cx).next().unwrap();
2697 let worktree_root = worktree.read(cx).abs_path();
2698 worktree_root.join("large_file.rs")
2699 });
2700 let large_file_task = message_editor.update(cx, |editor, cx| {
2701 editor.confirm_mention_for_file(large_file_abs_path, cx)
2702 });
2703
2704 let large_file_mention = large_file_task.await.unwrap();
2705 match large_file_mention {
2706 Mention::Text { content, .. } => {
2707 // Should contain outline header for large files
2708 assert!(content.contains("File outline for"));
2709 assert!(content.contains("file too large to show full content"));
2710 // Should not contain the full repeated content
2711 assert!(!content.contains(&LINE.repeat(100)));
2712 }
2713 _ => panic!("Expected Text mention for large file"),
2714 }
2715
2716 // Test small file mention
2717 // Get the absolute path using the project's worktree
2718 let small_file_abs_path = project.read_with(cx, |project, cx| {
2719 let worktree = project.worktrees(cx).next().unwrap();
2720 let worktree_root = worktree.read(cx).abs_path();
2721 worktree_root.join("small_file.rs")
2722 });
2723 let small_file_task = message_editor.update(cx, |editor, cx| {
2724 editor.confirm_mention_for_file(small_file_abs_path, cx)
2725 });
2726
2727 let small_file_mention = small_file_task.await.unwrap();
2728 match small_file_mention {
2729 Mention::Text { content, .. } => {
2730 // Should contain the actual content
2731 assert_eq!(content, small_content);
2732 // Should not contain outline header
2733 assert!(!content.contains("File outline for"));
2734 }
2735 _ => panic!("Expected Text mention for small file"),
2736 }
2737 }
2738}