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::{HistoryStore, outline};
7use agent_client_protocol as acp;
8use agent_servers::{AgentServer, AgentServerDelegate};
9use anyhow::{Result, anyhow};
10use assistant_slash_commands::codeblock_fence_for_path;
11use collections::{HashMap, HashSet};
12use editor::{
13 Addon, Anchor, AnchorRangeExt, ContextMenuOptions, ContextMenuPlacement, Editor, EditorElement,
14 EditorEvent, EditorMode, EditorSnapshot, EditorStyle, ExcerptId, FoldPlaceholder, Inlay,
15 MultiBuffer, ToOffset,
16 actions::Paste,
17 display_map::{Crease, CreaseId, FoldId},
18};
19use futures::{
20 FutureExt as _,
21 future::{Shared, join_all},
22};
23use gpui::{
24 Animation, AnimationExt as _, AppContext, ClipboardEntry, Context, Entity, EntityId,
25 EventEmitter, FocusHandle, Focusable, Image, ImageFormat, Img, KeyContext, SharedString,
26 Subscription, Task, TextStyle, WeakEntity, pulsating_between,
27};
28use language::{Buffer, Language, language_settings::InlayHintKind};
29use language_model::LanguageModelImage;
30use postage::stream::Stream as _;
31use project::{
32 CompletionIntent, InlayHint, InlayHintLabel, InlayId, Project, ProjectItem, ProjectPath,
33 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: InlayId = InlayId::Hint(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 &[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: agent::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(agent::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::<agent::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 text_thread_task = self.history_store.update(cx, |store, cx| {
633 store.load_text_thread(path.as_path().into(), cx)
634 });
635 cx.spawn(async move |_, cx| {
636 let text_thread = text_thread_task.await?;
637 let xml = text_thread.update(cx, |text_thread, cx| text_thread.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::{HistoryStore, outline};
1593 use agent_client_protocol as acp;
1594 use assistant_text_thread::TextThreadStore;
1595 use editor::{AnchorRangeExt as _, Editor, EditorMode};
1596 use fs::FakeFs;
1597 use futures::StreamExt as _;
1598 use gpui::{
1599 AppContext, Entity, EventEmitter, FocusHandle, Focusable, TestAppContext, VisualTestContext,
1600 };
1601 use lsp::{CompletionContext, CompletionTriggerKind};
1602 use project::{CompletionIntent, Project, ProjectPath};
1603 use serde_json::json;
1604 use text::Point;
1605 use ui::{App, Context, IntoElement, Render, SharedString, Window};
1606 use util::{path, paths::PathStyle, rel_path::rel_path};
1607 use workspace::{AppState, Item, Workspace};
1608
1609 use crate::acp::{
1610 message_editor::{Mention, MessageEditor},
1611 thread_view::tests::init_test,
1612 };
1613
1614 #[gpui::test]
1615 async fn test_at_mention_removal(cx: &mut TestAppContext) {
1616 init_test(cx);
1617
1618 let fs = FakeFs::new(cx.executor());
1619 fs.insert_tree("/project", json!({"file": ""})).await;
1620 let project = Project::test(fs, [Path::new(path!("/project"))], cx).await;
1621
1622 let (workspace, cx) =
1623 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1624
1625 let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
1626 let history_store = cx.new(|cx| HistoryStore::new(text_thread_store, cx));
1627
1628 let message_editor = cx.update(|window, cx| {
1629 cx.new(|cx| {
1630 MessageEditor::new(
1631 workspace.downgrade(),
1632 project.clone(),
1633 history_store.clone(),
1634 None,
1635 Default::default(),
1636 Default::default(),
1637 "Test Agent".into(),
1638 "Test",
1639 EditorMode::AutoHeight {
1640 min_lines: 1,
1641 max_lines: None,
1642 },
1643 window,
1644 cx,
1645 )
1646 })
1647 });
1648 let editor = message_editor.update(cx, |message_editor, _| message_editor.editor.clone());
1649
1650 cx.run_until_parked();
1651
1652 let excerpt_id = editor.update(cx, |editor, cx| {
1653 editor
1654 .buffer()
1655 .read(cx)
1656 .excerpt_ids()
1657 .into_iter()
1658 .next()
1659 .unwrap()
1660 });
1661 let completions = editor.update_in(cx, |editor, window, cx| {
1662 editor.set_text("Hello @file ", window, cx);
1663 let buffer = editor.buffer().read(cx).as_singleton().unwrap();
1664 let completion_provider = editor.completion_provider().unwrap();
1665 completion_provider.completions(
1666 excerpt_id,
1667 &buffer,
1668 text::Anchor::MAX,
1669 CompletionContext {
1670 trigger_kind: CompletionTriggerKind::TRIGGER_CHARACTER,
1671 trigger_character: Some("@".into()),
1672 },
1673 window,
1674 cx,
1675 )
1676 });
1677 let [_, completion]: [_; 2] = completions
1678 .await
1679 .unwrap()
1680 .into_iter()
1681 .flat_map(|response| response.completions)
1682 .collect::<Vec<_>>()
1683 .try_into()
1684 .unwrap();
1685
1686 editor.update_in(cx, |editor, window, cx| {
1687 let snapshot = editor.buffer().read(cx).snapshot(cx);
1688 let range = snapshot
1689 .anchor_range_in_excerpt(excerpt_id, completion.replace_range)
1690 .unwrap();
1691 editor.edit([(range, completion.new_text)], cx);
1692 (completion.confirm.unwrap())(CompletionIntent::Complete, window, cx);
1693 });
1694
1695 cx.run_until_parked();
1696
1697 // Backspace over the inserted crease (and the following space).
1698 editor.update_in(cx, |editor, window, cx| {
1699 editor.backspace(&Default::default(), window, cx);
1700 editor.backspace(&Default::default(), window, cx);
1701 });
1702
1703 let (content, _) = message_editor
1704 .update(cx, |message_editor, cx| message_editor.contents(false, cx))
1705 .await
1706 .unwrap();
1707
1708 // We don't send a resource link for the deleted crease.
1709 pretty_assertions::assert_matches!(content.as_slice(), [acp::ContentBlock::Text { .. }]);
1710 }
1711
1712 #[gpui::test]
1713 async fn test_slash_command_validation(cx: &mut gpui::TestAppContext) {
1714 init_test(cx);
1715 let fs = FakeFs::new(cx.executor());
1716 fs.insert_tree(
1717 "/test",
1718 json!({
1719 ".zed": {
1720 "tasks.json": r#"[{"label": "test", "command": "echo"}]"#
1721 },
1722 "src": {
1723 "main.rs": "fn main() {}",
1724 },
1725 }),
1726 )
1727 .await;
1728
1729 let project = Project::test(fs.clone(), ["/test".as_ref()], cx).await;
1730 let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
1731 let history_store = cx.new(|cx| HistoryStore::new(text_thread_store, cx));
1732 let prompt_capabilities = Rc::new(RefCell::new(acp::PromptCapabilities::default()));
1733 // Start with no available commands - simulating Claude which doesn't support slash commands
1734 let available_commands = Rc::new(RefCell::new(vec![]));
1735
1736 let (workspace, cx) =
1737 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1738 let workspace_handle = workspace.downgrade();
1739 let message_editor = workspace.update_in(cx, |_, window, cx| {
1740 cx.new(|cx| {
1741 MessageEditor::new(
1742 workspace_handle.clone(),
1743 project.clone(),
1744 history_store.clone(),
1745 None,
1746 prompt_capabilities.clone(),
1747 available_commands.clone(),
1748 "Claude Code".into(),
1749 "Test",
1750 EditorMode::AutoHeight {
1751 min_lines: 1,
1752 max_lines: None,
1753 },
1754 window,
1755 cx,
1756 )
1757 })
1758 });
1759 let editor = message_editor.update(cx, |message_editor, _| message_editor.editor.clone());
1760
1761 // Test that slash commands fail when no available_commands are set (empty list means no commands supported)
1762 editor.update_in(cx, |editor, window, cx| {
1763 editor.set_text("/file test.txt", window, cx);
1764 });
1765
1766 let contents_result = message_editor
1767 .update(cx, |message_editor, cx| message_editor.contents(false, cx))
1768 .await;
1769
1770 // Should fail because available_commands is empty (no commands supported)
1771 assert!(contents_result.is_err());
1772 let error_message = contents_result.unwrap_err().to_string();
1773 assert!(error_message.contains("not supported by Claude Code"));
1774 assert!(error_message.contains("Available commands: none"));
1775
1776 // Now simulate Claude providing its list of available commands (which doesn't include file)
1777 available_commands.replace(vec![acp::AvailableCommand {
1778 name: "help".to_string(),
1779 description: "Get help".to_string(),
1780 input: None,
1781 meta: None,
1782 }]);
1783
1784 // Test that unsupported slash commands trigger an error when we have a list of available commands
1785 editor.update_in(cx, |editor, window, cx| {
1786 editor.set_text("/file test.txt", window, cx);
1787 });
1788
1789 let contents_result = message_editor
1790 .update(cx, |message_editor, cx| message_editor.contents(false, cx))
1791 .await;
1792
1793 assert!(contents_result.is_err());
1794 let error_message = contents_result.unwrap_err().to_string();
1795 assert!(error_message.contains("not supported by Claude Code"));
1796 assert!(error_message.contains("/file"));
1797 assert!(error_message.contains("Available commands: /help"));
1798
1799 // Test that supported commands work fine
1800 editor.update_in(cx, |editor, window, cx| {
1801 editor.set_text("/help", window, cx);
1802 });
1803
1804 let contents_result = message_editor
1805 .update(cx, |message_editor, cx| message_editor.contents(false, cx))
1806 .await;
1807
1808 // Should succeed because /help is in available_commands
1809 assert!(contents_result.is_ok());
1810
1811 // Test that regular text works fine
1812 editor.update_in(cx, |editor, window, cx| {
1813 editor.set_text("Hello Claude!", window, cx);
1814 });
1815
1816 let (content, _) = message_editor
1817 .update(cx, |message_editor, cx| message_editor.contents(false, cx))
1818 .await
1819 .unwrap();
1820
1821 assert_eq!(content.len(), 1);
1822 if let acp::ContentBlock::Text(text) = &content[0] {
1823 assert_eq!(text.text, "Hello Claude!");
1824 } else {
1825 panic!("Expected ContentBlock::Text");
1826 }
1827
1828 // Test that @ mentions still work
1829 editor.update_in(cx, |editor, window, cx| {
1830 editor.set_text("Check this @", window, cx);
1831 });
1832
1833 // The @ mention functionality should not be affected
1834 let (content, _) = message_editor
1835 .update(cx, |message_editor, cx| message_editor.contents(false, cx))
1836 .await
1837 .unwrap();
1838
1839 assert_eq!(content.len(), 1);
1840 if let acp::ContentBlock::Text(text) = &content[0] {
1841 assert_eq!(text.text, "Check this @");
1842 } else {
1843 panic!("Expected ContentBlock::Text");
1844 }
1845 }
1846
1847 struct MessageEditorItem(Entity<MessageEditor>);
1848
1849 impl Item for MessageEditorItem {
1850 type Event = ();
1851
1852 fn include_in_nav_history() -> bool {
1853 false
1854 }
1855
1856 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
1857 "Test".into()
1858 }
1859 }
1860
1861 impl EventEmitter<()> for MessageEditorItem {}
1862
1863 impl Focusable for MessageEditorItem {
1864 fn focus_handle(&self, cx: &App) -> FocusHandle {
1865 self.0.read(cx).focus_handle(cx)
1866 }
1867 }
1868
1869 impl Render for MessageEditorItem {
1870 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
1871 self.0.clone().into_any_element()
1872 }
1873 }
1874
1875 #[gpui::test]
1876 async fn test_completion_provider_commands(cx: &mut TestAppContext) {
1877 init_test(cx);
1878
1879 let app_state = cx.update(AppState::test);
1880
1881 cx.update(|cx| {
1882 language::init(cx);
1883 editor::init(cx);
1884 workspace::init(app_state.clone(), cx);
1885 Project::init_settings(cx);
1886 });
1887
1888 let project = Project::test(app_state.fs.clone(), [path!("/dir").as_ref()], cx).await;
1889 let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
1890 let workspace = window.root(cx).unwrap();
1891
1892 let mut cx = VisualTestContext::from_window(*window, cx);
1893
1894 let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
1895 let history_store = cx.new(|cx| HistoryStore::new(text_thread_store, cx));
1896 let prompt_capabilities = Rc::new(RefCell::new(acp::PromptCapabilities::default()));
1897 let available_commands = Rc::new(RefCell::new(vec![
1898 acp::AvailableCommand {
1899 name: "quick-math".to_string(),
1900 description: "2 + 2 = 4 - 1 = 3".to_string(),
1901 input: None,
1902 meta: None,
1903 },
1904 acp::AvailableCommand {
1905 name: "say-hello".to_string(),
1906 description: "Say hello to whoever you want".to_string(),
1907 input: Some(acp::AvailableCommandInput::Unstructured {
1908 hint: "<name>".to_string(),
1909 }),
1910 meta: None,
1911 },
1912 ]));
1913
1914 let editor = workspace.update_in(&mut cx, |workspace, window, cx| {
1915 let workspace_handle = cx.weak_entity();
1916 let message_editor = cx.new(|cx| {
1917 MessageEditor::new(
1918 workspace_handle,
1919 project.clone(),
1920 history_store.clone(),
1921 None,
1922 prompt_capabilities.clone(),
1923 available_commands.clone(),
1924 "Test Agent".into(),
1925 "Test",
1926 EditorMode::AutoHeight {
1927 max_lines: None,
1928 min_lines: 1,
1929 },
1930 window,
1931 cx,
1932 )
1933 });
1934 workspace.active_pane().update(cx, |pane, cx| {
1935 pane.add_item(
1936 Box::new(cx.new(|_| MessageEditorItem(message_editor.clone()))),
1937 true,
1938 true,
1939 None,
1940 window,
1941 cx,
1942 );
1943 });
1944 message_editor.read(cx).focus_handle(cx).focus(window);
1945 message_editor.read(cx).editor().clone()
1946 });
1947
1948 cx.simulate_input("/");
1949
1950 editor.update_in(&mut cx, |editor, window, cx| {
1951 assert_eq!(editor.text(cx), "/");
1952 assert!(editor.has_visible_completions_menu());
1953
1954 assert_eq!(
1955 current_completion_labels_with_documentation(editor),
1956 &[
1957 ("quick-math".into(), "2 + 2 = 4 - 1 = 3".into()),
1958 ("say-hello".into(), "Say hello to whoever you want".into())
1959 ]
1960 );
1961 editor.set_text("", window, cx);
1962 });
1963
1964 cx.simulate_input("/qui");
1965
1966 editor.update_in(&mut cx, |editor, window, cx| {
1967 assert_eq!(editor.text(cx), "/qui");
1968 assert!(editor.has_visible_completions_menu());
1969
1970 assert_eq!(
1971 current_completion_labels_with_documentation(editor),
1972 &[("quick-math".into(), "2 + 2 = 4 - 1 = 3".into())]
1973 );
1974 editor.set_text("", window, cx);
1975 });
1976
1977 editor.update_in(&mut cx, |editor, window, cx| {
1978 assert!(editor.has_visible_completions_menu());
1979 editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
1980 });
1981
1982 cx.run_until_parked();
1983
1984 editor.update_in(&mut cx, |editor, window, cx| {
1985 assert_eq!(editor.display_text(cx), "/quick-math ");
1986 assert!(!editor.has_visible_completions_menu());
1987 editor.set_text("", window, cx);
1988 });
1989
1990 cx.simulate_input("/say");
1991
1992 editor.update_in(&mut cx, |editor, _window, cx| {
1993 assert_eq!(editor.display_text(cx), "/say");
1994 assert!(editor.has_visible_completions_menu());
1995
1996 assert_eq!(
1997 current_completion_labels_with_documentation(editor),
1998 &[("say-hello".into(), "Say hello to whoever you want".into())]
1999 );
2000 });
2001
2002 editor.update_in(&mut cx, |editor, window, cx| {
2003 assert!(editor.has_visible_completions_menu());
2004 editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
2005 });
2006
2007 cx.run_until_parked();
2008
2009 editor.update_in(&mut cx, |editor, _window, cx| {
2010 assert_eq!(editor.text(cx), "/say-hello ");
2011 assert_eq!(editor.display_text(cx), "/say-hello <name>");
2012 assert!(!editor.has_visible_completions_menu());
2013 });
2014
2015 cx.simulate_input("GPT5");
2016
2017 cx.run_until_parked();
2018
2019 editor.update_in(&mut cx, |editor, window, cx| {
2020 assert_eq!(editor.text(cx), "/say-hello GPT5");
2021 assert_eq!(editor.display_text(cx), "/say-hello GPT5");
2022 assert!(!editor.has_visible_completions_menu());
2023
2024 // Delete argument
2025 for _ in 0..5 {
2026 editor.backspace(&editor::actions::Backspace, window, cx);
2027 }
2028 });
2029
2030 cx.run_until_parked();
2031
2032 editor.update_in(&mut cx, |editor, window, cx| {
2033 assert_eq!(editor.text(cx), "/say-hello");
2034 // Hint is visible because argument was deleted
2035 assert_eq!(editor.display_text(cx), "/say-hello <name>");
2036
2037 // Delete last command letter
2038 editor.backspace(&editor::actions::Backspace, window, cx);
2039 });
2040
2041 cx.run_until_parked();
2042
2043 editor.update_in(&mut cx, |editor, _window, cx| {
2044 // Hint goes away once command no longer matches an available one
2045 assert_eq!(editor.text(cx), "/say-hell");
2046 assert_eq!(editor.display_text(cx), "/say-hell");
2047 assert!(!editor.has_visible_completions_menu());
2048 });
2049 }
2050
2051 #[gpui::test]
2052 async fn test_context_completion_provider_mentions(cx: &mut TestAppContext) {
2053 init_test(cx);
2054
2055 let app_state = cx.update(AppState::test);
2056
2057 cx.update(|cx| {
2058 language::init(cx);
2059 editor::init(cx);
2060 workspace::init(app_state.clone(), cx);
2061 Project::init_settings(cx);
2062 });
2063
2064 app_state
2065 .fs
2066 .as_fake()
2067 .insert_tree(
2068 path!("/dir"),
2069 json!({
2070 "editor": "",
2071 "a": {
2072 "one.txt": "1",
2073 "two.txt": "2",
2074 "three.txt": "3",
2075 "four.txt": "4"
2076 },
2077 "b": {
2078 "five.txt": "5",
2079 "six.txt": "6",
2080 "seven.txt": "7",
2081 "eight.txt": "8",
2082 },
2083 "x.png": "",
2084 }),
2085 )
2086 .await;
2087
2088 let project = Project::test(app_state.fs.clone(), [path!("/dir").as_ref()], cx).await;
2089 let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
2090 let workspace = window.root(cx).unwrap();
2091
2092 let worktree = project.update(cx, |project, cx| {
2093 let mut worktrees = project.worktrees(cx).collect::<Vec<_>>();
2094 assert_eq!(worktrees.len(), 1);
2095 worktrees.pop().unwrap()
2096 });
2097 let worktree_id = worktree.read_with(cx, |worktree, _| worktree.id());
2098
2099 let mut cx = VisualTestContext::from_window(*window, cx);
2100
2101 let paths = vec![
2102 rel_path("a/one.txt"),
2103 rel_path("a/two.txt"),
2104 rel_path("a/three.txt"),
2105 rel_path("a/four.txt"),
2106 rel_path("b/five.txt"),
2107 rel_path("b/six.txt"),
2108 rel_path("b/seven.txt"),
2109 rel_path("b/eight.txt"),
2110 ];
2111
2112 let slash = PathStyle::local().separator();
2113
2114 let mut opened_editors = Vec::new();
2115 for path in paths {
2116 let buffer = workspace
2117 .update_in(&mut cx, |workspace, window, cx| {
2118 workspace.open_path(
2119 ProjectPath {
2120 worktree_id,
2121 path: path.into(),
2122 },
2123 None,
2124 false,
2125 window,
2126 cx,
2127 )
2128 })
2129 .await
2130 .unwrap();
2131 opened_editors.push(buffer);
2132 }
2133
2134 let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
2135 let history_store = cx.new(|cx| HistoryStore::new(text_thread_store, cx));
2136 let prompt_capabilities = Rc::new(RefCell::new(acp::PromptCapabilities::default()));
2137
2138 let (message_editor, editor) = workspace.update_in(&mut cx, |workspace, window, cx| {
2139 let workspace_handle = cx.weak_entity();
2140 let message_editor = cx.new(|cx| {
2141 MessageEditor::new(
2142 workspace_handle,
2143 project.clone(),
2144 history_store.clone(),
2145 None,
2146 prompt_capabilities.clone(),
2147 Default::default(),
2148 "Test Agent".into(),
2149 "Test",
2150 EditorMode::AutoHeight {
2151 max_lines: None,
2152 min_lines: 1,
2153 },
2154 window,
2155 cx,
2156 )
2157 });
2158 workspace.active_pane().update(cx, |pane, cx| {
2159 pane.add_item(
2160 Box::new(cx.new(|_| MessageEditorItem(message_editor.clone()))),
2161 true,
2162 true,
2163 None,
2164 window,
2165 cx,
2166 );
2167 });
2168 message_editor.read(cx).focus_handle(cx).focus(window);
2169 let editor = message_editor.read(cx).editor().clone();
2170 (message_editor, editor)
2171 });
2172
2173 cx.simulate_input("Lorem @");
2174
2175 editor.update_in(&mut cx, |editor, window, cx| {
2176 assert_eq!(editor.text(cx), "Lorem @");
2177 assert!(editor.has_visible_completions_menu());
2178
2179 assert_eq!(
2180 current_completion_labels(editor),
2181 &[
2182 format!("eight.txt dir{slash}b{slash}"),
2183 format!("seven.txt dir{slash}b{slash}"),
2184 format!("six.txt dir{slash}b{slash}"),
2185 format!("five.txt dir{slash}b{slash}"),
2186 ]
2187 );
2188 editor.set_text("", window, cx);
2189 });
2190
2191 prompt_capabilities.replace(acp::PromptCapabilities {
2192 image: true,
2193 audio: true,
2194 embedded_context: true,
2195 meta: None,
2196 });
2197
2198 cx.simulate_input("Lorem ");
2199
2200 editor.update(&mut cx, |editor, cx| {
2201 assert_eq!(editor.text(cx), "Lorem ");
2202 assert!(!editor.has_visible_completions_menu());
2203 });
2204
2205 cx.simulate_input("@");
2206
2207 editor.update(&mut cx, |editor, cx| {
2208 assert_eq!(editor.text(cx), "Lorem @");
2209 assert!(editor.has_visible_completions_menu());
2210 assert_eq!(
2211 current_completion_labels(editor),
2212 &[
2213 format!("eight.txt dir{slash}b{slash}"),
2214 format!("seven.txt dir{slash}b{slash}"),
2215 format!("six.txt dir{slash}b{slash}"),
2216 format!("five.txt dir{slash}b{slash}"),
2217 "Files & Directories".into(),
2218 "Symbols".into(),
2219 "Threads".into(),
2220 "Fetch".into()
2221 ]
2222 );
2223 });
2224
2225 // Select and confirm "File"
2226 editor.update_in(&mut cx, |editor, window, cx| {
2227 assert!(editor.has_visible_completions_menu());
2228 editor.context_menu_next(&editor::actions::ContextMenuNext, window, cx);
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.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
2233 });
2234
2235 cx.run_until_parked();
2236
2237 editor.update(&mut cx, |editor, cx| {
2238 assert_eq!(editor.text(cx), "Lorem @file ");
2239 assert!(editor.has_visible_completions_menu());
2240 });
2241
2242 cx.simulate_input("one");
2243
2244 editor.update(&mut cx, |editor, cx| {
2245 assert_eq!(editor.text(cx), "Lorem @file one");
2246 assert!(editor.has_visible_completions_menu());
2247 assert_eq!(
2248 current_completion_labels(editor),
2249 vec![format!("one.txt dir{slash}a{slash}")]
2250 );
2251 });
2252
2253 editor.update_in(&mut cx, |editor, window, cx| {
2254 assert!(editor.has_visible_completions_menu());
2255 editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
2256 });
2257
2258 let url_one = MentionUri::File {
2259 abs_path: path!("/dir/a/one.txt").into(),
2260 }
2261 .to_uri()
2262 .to_string();
2263 editor.update(&mut cx, |editor, cx| {
2264 let text = editor.text(cx);
2265 assert_eq!(text, format!("Lorem [@one.txt]({url_one}) "));
2266 assert!(!editor.has_visible_completions_menu());
2267 assert_eq!(fold_ranges(editor, cx).len(), 1);
2268 });
2269
2270 let all_prompt_capabilities = acp::PromptCapabilities {
2271 image: true,
2272 audio: true,
2273 embedded_context: true,
2274 meta: None,
2275 };
2276
2277 let contents = message_editor
2278 .update(&mut cx, |message_editor, cx| {
2279 message_editor.mention_set().contents(
2280 &all_prompt_capabilities,
2281 false,
2282 project.clone(),
2283 cx,
2284 )
2285 })
2286 .await
2287 .unwrap()
2288 .into_values()
2289 .collect::<Vec<_>>();
2290
2291 {
2292 let [(uri, Mention::Text { content, .. })] = contents.as_slice() else {
2293 panic!("Unexpected mentions");
2294 };
2295 pretty_assertions::assert_eq!(content, "1");
2296 pretty_assertions::assert_eq!(uri, &url_one.parse::<MentionUri>().unwrap());
2297 }
2298
2299 let contents = message_editor
2300 .update(&mut cx, |message_editor, cx| {
2301 message_editor.mention_set().contents(
2302 &acp::PromptCapabilities::default(),
2303 false,
2304 project.clone(),
2305 cx,
2306 )
2307 })
2308 .await
2309 .unwrap()
2310 .into_values()
2311 .collect::<Vec<_>>();
2312
2313 {
2314 let [(uri, Mention::UriOnly)] = contents.as_slice() else {
2315 panic!("Unexpected mentions");
2316 };
2317 pretty_assertions::assert_eq!(uri, &url_one.parse::<MentionUri>().unwrap());
2318 }
2319
2320 cx.simulate_input(" ");
2321
2322 editor.update(&mut cx, |editor, cx| {
2323 let text = editor.text(cx);
2324 assert_eq!(text, format!("Lorem [@one.txt]({url_one}) "));
2325 assert!(!editor.has_visible_completions_menu());
2326 assert_eq!(fold_ranges(editor, cx).len(), 1);
2327 });
2328
2329 cx.simulate_input("Ipsum ");
2330
2331 editor.update(&mut cx, |editor, cx| {
2332 let text = editor.text(cx);
2333 assert_eq!(text, format!("Lorem [@one.txt]({url_one}) Ipsum "),);
2334 assert!(!editor.has_visible_completions_menu());
2335 assert_eq!(fold_ranges(editor, cx).len(), 1);
2336 });
2337
2338 cx.simulate_input("@file ");
2339
2340 editor.update(&mut cx, |editor, cx| {
2341 let text = editor.text(cx);
2342 assert_eq!(text, format!("Lorem [@one.txt]({url_one}) Ipsum @file "),);
2343 assert!(editor.has_visible_completions_menu());
2344 assert_eq!(fold_ranges(editor, cx).len(), 1);
2345 });
2346
2347 editor.update_in(&mut cx, |editor, window, cx| {
2348 editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
2349 });
2350
2351 cx.run_until_parked();
2352
2353 let contents = message_editor
2354 .update(&mut cx, |message_editor, cx| {
2355 message_editor.mention_set().contents(
2356 &all_prompt_capabilities,
2357 false,
2358 project.clone(),
2359 cx,
2360 )
2361 })
2362 .await
2363 .unwrap()
2364 .into_values()
2365 .collect::<Vec<_>>();
2366
2367 let url_eight = MentionUri::File {
2368 abs_path: path!("/dir/b/eight.txt").into(),
2369 }
2370 .to_uri()
2371 .to_string();
2372
2373 {
2374 let [_, (uri, Mention::Text { content, .. })] = contents.as_slice() else {
2375 panic!("Unexpected mentions");
2376 };
2377 pretty_assertions::assert_eq!(content, "8");
2378 pretty_assertions::assert_eq!(uri, &url_eight.parse::<MentionUri>().unwrap());
2379 }
2380
2381 editor.update(&mut cx, |editor, cx| {
2382 assert_eq!(
2383 editor.text(cx),
2384 format!("Lorem [@one.txt]({url_one}) Ipsum [@eight.txt]({url_eight}) ")
2385 );
2386 assert!(!editor.has_visible_completions_menu());
2387 assert_eq!(fold_ranges(editor, cx).len(), 2);
2388 });
2389
2390 let plain_text_language = Arc::new(language::Language::new(
2391 language::LanguageConfig {
2392 name: "Plain Text".into(),
2393 matcher: language::LanguageMatcher {
2394 path_suffixes: vec!["txt".to_string()],
2395 ..Default::default()
2396 },
2397 ..Default::default()
2398 },
2399 None,
2400 ));
2401
2402 // Register the language and fake LSP
2403 let language_registry = project.read_with(&cx, |project, _| project.languages().clone());
2404 language_registry.add(plain_text_language);
2405
2406 let mut fake_language_servers = language_registry.register_fake_lsp(
2407 "Plain Text",
2408 language::FakeLspAdapter {
2409 capabilities: lsp::ServerCapabilities {
2410 workspace_symbol_provider: Some(lsp::OneOf::Left(true)),
2411 ..Default::default()
2412 },
2413 ..Default::default()
2414 },
2415 );
2416
2417 // Open the buffer to trigger LSP initialization
2418 let buffer = project
2419 .update(&mut cx, |project, cx| {
2420 project.open_local_buffer(path!("/dir/a/one.txt"), cx)
2421 })
2422 .await
2423 .unwrap();
2424
2425 // Register the buffer with language servers
2426 let _handle = project.update(&mut cx, |project, cx| {
2427 project.register_buffer_with_language_servers(&buffer, cx)
2428 });
2429
2430 cx.run_until_parked();
2431
2432 let fake_language_server = fake_language_servers.next().await.unwrap();
2433 fake_language_server.set_request_handler::<lsp::WorkspaceSymbolRequest, _, _>(
2434 move |_, _| async move {
2435 Ok(Some(lsp::WorkspaceSymbolResponse::Flat(vec![
2436 #[allow(deprecated)]
2437 lsp::SymbolInformation {
2438 name: "MySymbol".into(),
2439 location: lsp::Location {
2440 uri: lsp::Uri::from_file_path(path!("/dir/a/one.txt")).unwrap(),
2441 range: lsp::Range::new(
2442 lsp::Position::new(0, 0),
2443 lsp::Position::new(0, 1),
2444 ),
2445 },
2446 kind: lsp::SymbolKind::CONSTANT,
2447 tags: None,
2448 container_name: None,
2449 deprecated: None,
2450 },
2451 ])))
2452 },
2453 );
2454
2455 cx.simulate_input("@symbol ");
2456
2457 editor.update(&mut cx, |editor, cx| {
2458 assert_eq!(
2459 editor.text(cx),
2460 format!("Lorem [@one.txt]({url_one}) Ipsum [@eight.txt]({url_eight}) @symbol ")
2461 );
2462 assert!(editor.has_visible_completions_menu());
2463 assert_eq!(current_completion_labels(editor), &["MySymbol"]);
2464 });
2465
2466 editor.update_in(&mut cx, |editor, window, cx| {
2467 editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
2468 });
2469
2470 let symbol = MentionUri::Symbol {
2471 abs_path: path!("/dir/a/one.txt").into(),
2472 name: "MySymbol".into(),
2473 line_range: 0..=0,
2474 };
2475
2476 let contents = message_editor
2477 .update(&mut cx, |message_editor, cx| {
2478 message_editor.mention_set().contents(
2479 &all_prompt_capabilities,
2480 false,
2481 project.clone(),
2482 cx,
2483 )
2484 })
2485 .await
2486 .unwrap()
2487 .into_values()
2488 .collect::<Vec<_>>();
2489
2490 {
2491 let [_, _, (uri, Mention::Text { content, .. })] = contents.as_slice() else {
2492 panic!("Unexpected mentions");
2493 };
2494 pretty_assertions::assert_eq!(content, "1");
2495 pretty_assertions::assert_eq!(uri, &symbol);
2496 }
2497
2498 cx.run_until_parked();
2499
2500 editor.read_with(&cx, |editor, cx| {
2501 assert_eq!(
2502 editor.text(cx),
2503 format!(
2504 "Lorem [@one.txt]({url_one}) Ipsum [@eight.txt]({url_eight}) [@MySymbol]({}) ",
2505 symbol.to_uri(),
2506 )
2507 );
2508 });
2509
2510 // Try to mention an "image" file that will fail to load
2511 cx.simulate_input("@file x.png");
2512
2513 editor.update(&mut cx, |editor, cx| {
2514 assert_eq!(
2515 editor.text(cx),
2516 format!("Lorem [@one.txt]({url_one}) Ipsum [@eight.txt]({url_eight}) [@MySymbol]({}) @file x.png", symbol.to_uri())
2517 );
2518 assert!(editor.has_visible_completions_menu());
2519 assert_eq!(current_completion_labels(editor), &[format!("x.png dir{slash}")]);
2520 });
2521
2522 editor.update_in(&mut cx, |editor, window, cx| {
2523 editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
2524 });
2525
2526 // Getting the message contents fails
2527 message_editor
2528 .update(&mut cx, |message_editor, cx| {
2529 message_editor.mention_set().contents(
2530 &all_prompt_capabilities,
2531 false,
2532 project.clone(),
2533 cx,
2534 )
2535 })
2536 .await
2537 .expect_err("Should fail to load x.png");
2538
2539 cx.run_until_parked();
2540
2541 // Mention was removed
2542 editor.read_with(&cx, |editor, cx| {
2543 assert_eq!(
2544 editor.text(cx),
2545 format!(
2546 "Lorem [@one.txt]({url_one}) Ipsum [@eight.txt]({url_eight}) [@MySymbol]({}) ",
2547 symbol.to_uri()
2548 )
2549 );
2550 });
2551
2552 // Once more
2553 cx.simulate_input("@file x.png");
2554
2555 editor.update(&mut cx, |editor, cx| {
2556 assert_eq!(
2557 editor.text(cx),
2558 format!("Lorem [@one.txt]({url_one}) Ipsum [@eight.txt]({url_eight}) [@MySymbol]({}) @file x.png", symbol.to_uri())
2559 );
2560 assert!(editor.has_visible_completions_menu());
2561 assert_eq!(current_completion_labels(editor), &[format!("x.png dir{slash}")]);
2562 });
2563
2564 editor.update_in(&mut cx, |editor, window, cx| {
2565 editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
2566 });
2567
2568 // This time don't immediately get the contents, just let the confirmed completion settle
2569 cx.run_until_parked();
2570
2571 // Mention was removed
2572 editor.read_with(&cx, |editor, cx| {
2573 assert_eq!(
2574 editor.text(cx),
2575 format!(
2576 "Lorem [@one.txt]({url_one}) Ipsum [@eight.txt]({url_eight}) [@MySymbol]({}) ",
2577 symbol.to_uri()
2578 )
2579 );
2580 });
2581
2582 // Now getting the contents succeeds, because the invalid mention was removed
2583 let contents = message_editor
2584 .update(&mut cx, |message_editor, cx| {
2585 message_editor.mention_set().contents(
2586 &all_prompt_capabilities,
2587 false,
2588 project.clone(),
2589 cx,
2590 )
2591 })
2592 .await
2593 .unwrap();
2594 assert_eq!(contents.len(), 3);
2595 }
2596
2597 fn fold_ranges(editor: &Editor, cx: &mut App) -> Vec<Range<Point>> {
2598 let snapshot = editor.buffer().read(cx).snapshot(cx);
2599 editor.display_map.update(cx, |display_map, cx| {
2600 display_map
2601 .snapshot(cx)
2602 .folds_in_range(0..snapshot.len())
2603 .map(|fold| fold.range.to_point(&snapshot))
2604 .collect()
2605 })
2606 }
2607
2608 fn current_completion_labels(editor: &Editor) -> Vec<String> {
2609 let completions = editor.current_completions().expect("Missing completions");
2610 completions
2611 .into_iter()
2612 .map(|completion| completion.label.text)
2613 .collect::<Vec<_>>()
2614 }
2615
2616 fn current_completion_labels_with_documentation(editor: &Editor) -> Vec<(String, String)> {
2617 let completions = editor.current_completions().expect("Missing completions");
2618 completions
2619 .into_iter()
2620 .map(|completion| {
2621 (
2622 completion.label.text,
2623 completion
2624 .documentation
2625 .map(|d| d.text().to_string())
2626 .unwrap_or_default(),
2627 )
2628 })
2629 .collect::<Vec<_>>()
2630 }
2631
2632 #[gpui::test]
2633 async fn test_large_file_mention_uses_outline(cx: &mut TestAppContext) {
2634 init_test(cx);
2635
2636 let fs = FakeFs::new(cx.executor());
2637
2638 // Create a large file that exceeds AUTO_OUTLINE_SIZE
2639 const LINE: &str = "fn example_function() { /* some code */ }\n";
2640 let large_content = LINE.repeat(2 * (outline::AUTO_OUTLINE_SIZE / LINE.len()));
2641 assert!(large_content.len() > outline::AUTO_OUTLINE_SIZE);
2642
2643 // Create a small file that doesn't exceed AUTO_OUTLINE_SIZE
2644 let small_content = "fn small_function() { /* small */ }\n";
2645 assert!(small_content.len() < outline::AUTO_OUTLINE_SIZE);
2646
2647 fs.insert_tree(
2648 "/project",
2649 json!({
2650 "large_file.rs": large_content.clone(),
2651 "small_file.rs": small_content,
2652 }),
2653 )
2654 .await;
2655
2656 let project = Project::test(fs, [Path::new(path!("/project"))], cx).await;
2657
2658 let (workspace, cx) =
2659 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2660
2661 let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
2662 let history_store = cx.new(|cx| HistoryStore::new(text_thread_store, cx));
2663
2664 let message_editor = cx.update(|window, cx| {
2665 cx.new(|cx| {
2666 let editor = MessageEditor::new(
2667 workspace.downgrade(),
2668 project.clone(),
2669 history_store.clone(),
2670 None,
2671 Default::default(),
2672 Default::default(),
2673 "Test Agent".into(),
2674 "Test",
2675 EditorMode::AutoHeight {
2676 min_lines: 1,
2677 max_lines: None,
2678 },
2679 window,
2680 cx,
2681 );
2682 // Enable embedded context so files are actually included
2683 editor.prompt_capabilities.replace(acp::PromptCapabilities {
2684 embedded_context: true,
2685 meta: None,
2686 ..Default::default()
2687 });
2688 editor
2689 })
2690 });
2691
2692 // Test large file mention
2693 // Get the absolute path using the project's worktree
2694 let large_file_abs_path = project.read_with(cx, |project, cx| {
2695 let worktree = project.worktrees(cx).next().unwrap();
2696 let worktree_root = worktree.read(cx).abs_path();
2697 worktree_root.join("large_file.rs")
2698 });
2699 let large_file_task = message_editor.update(cx, |editor, cx| {
2700 editor.confirm_mention_for_file(large_file_abs_path, cx)
2701 });
2702
2703 let large_file_mention = large_file_task.await.unwrap();
2704 match large_file_mention {
2705 Mention::Text { content, .. } => {
2706 // Should contain outline header for large files
2707 assert!(content.contains("File outline for"));
2708 assert!(content.contains("file too large to show full content"));
2709 // Should not contain the full repeated content
2710 assert!(!content.contains(&LINE.repeat(100)));
2711 }
2712 _ => panic!("Expected Text mention for large file"),
2713 }
2714
2715 // Test small file mention
2716 // Get the absolute path using the project's worktree
2717 let small_file_abs_path = project.read_with(cx, |project, cx| {
2718 let worktree = project.worktrees(cx).next().unwrap();
2719 let worktree_root = worktree.read(cx).abs_path();
2720 worktree_root.join("small_file.rs")
2721 });
2722 let small_file_task = message_editor.update(cx, |editor, cx| {
2723 editor.confirm_mention_for_file(small_file_abs_path, cx)
2724 });
2725
2726 let small_file_mention = small_file_task.await.unwrap();
2727 match small_file_mention {
2728 Mention::Text { content, .. } => {
2729 // Should contain the actual content
2730 assert_eq!(content, small_content);
2731 // Should not contain outline header
2732 assert!(!content.contains("File outline for"));
2733 }
2734 _ => panic!("Expected Text mention for small file"),
2735 }
2736 }
2737}