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