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