1use crate::SendImmediately;
2use crate::ThreadHistory;
3use crate::{
4 ChatWithFollow,
5 completion_provider::{
6 PromptCompletionProvider, PromptCompletionProviderDelegate, PromptContextAction,
7 PromptContextType, SlashCommandCompletion,
8 },
9 mention_set::{
10 Mention, MentionImage, MentionSet, insert_crease_for_mention, paste_images_as_context,
11 },
12};
13use acp_thread::MentionUri;
14use agent::ThreadStore;
15use agent_client_protocol as acp;
16use anyhow::{Result, anyhow};
17use collections::HashSet;
18use editor::{
19 Addon, AnchorRangeExt, ContextMenuOptions, ContextMenuPlacement, Editor, EditorElement,
20 EditorEvent, EditorMode, EditorStyle, Inlay, MultiBuffer, MultiBufferOffset,
21 MultiBufferSnapshot, ToOffset, actions::Paste, code_context_menus::CodeContextMenu,
22 scroll::Autoscroll,
23};
24use futures::{FutureExt as _, future::join_all};
25use gpui::{
26 AppContext, ClipboardEntry, Context, Entity, EventEmitter, FocusHandle, Focusable, ImageFormat,
27 KeyContext, SharedString, Subscription, Task, TextStyle, WeakEntity,
28};
29use language::{Buffer, Language, language_settings::InlayHintKind};
30use project::{CompletionIntent, InlayHint, InlayHintLabel, InlayId, Project, Worktree};
31use prompt_store::PromptStore;
32use rope::Point;
33use settings::Settings;
34use std::{cell::RefCell, fmt::Write, ops::Range, rc::Rc, sync::Arc};
35use theme::ThemeSettings;
36use ui::{ButtonLike, ButtonStyle, ContextMenu, Disclosure, ElevationIndex, prelude::*};
37use util::paths::PathStyle;
38use util::{ResultExt, debug_panic};
39use workspace::{CollaboratorId, Workspace};
40use zed_actions::agent::{Chat, PasteRaw};
41
42pub struct MessageEditor {
43 mention_set: Entity<MentionSet>,
44 editor: Entity<Editor>,
45 workspace: WeakEntity<Workspace>,
46 prompt_capabilities: Rc<RefCell<acp::PromptCapabilities>>,
47 available_commands: Rc<RefCell<Vec<acp::AvailableCommand>>>,
48 agent_name: SharedString,
49 thread_store: Option<Entity<ThreadStore>>,
50 _subscriptions: Vec<Subscription>,
51 _parse_slash_command_task: Task<()>,
52}
53
54#[derive(Clone, Debug)]
55pub enum MessageEditorEvent {
56 Send,
57 SendImmediately,
58 Cancel,
59 Focus,
60 LostFocus,
61 InputAttempted(Arc<str>),
62}
63
64impl EventEmitter<MessageEditorEvent> for MessageEditor {}
65
66const COMMAND_HINT_INLAY_ID: InlayId = InlayId::Hint(0);
67
68impl PromptCompletionProviderDelegate for Entity<MessageEditor> {
69 fn supports_images(&self, cx: &App) -> bool {
70 self.read(cx).prompt_capabilities.borrow().image
71 }
72
73 fn supported_modes(&self, cx: &App) -> Vec<PromptContextType> {
74 let mut supported = vec![PromptContextType::File, PromptContextType::Symbol];
75 if self.read(cx).prompt_capabilities.borrow().embedded_context {
76 if self.read(cx).thread_store.is_some() {
77 supported.push(PromptContextType::Thread);
78 }
79 supported.extend(&[
80 PromptContextType::Diagnostics,
81 PromptContextType::Fetch,
82 PromptContextType::Rules,
83 PromptContextType::BranchDiff,
84 ]);
85 }
86 supported
87 }
88
89 fn available_commands(&self, cx: &App) -> Vec<crate::completion_provider::AvailableCommand> {
90 self.read(cx)
91 .available_commands
92 .borrow()
93 .iter()
94 .map(|cmd| crate::completion_provider::AvailableCommand {
95 name: cmd.name.clone().into(),
96 description: cmd.description.clone().into(),
97 requires_argument: cmd.input.is_some(),
98 })
99 .collect()
100 }
101
102 fn confirm_command(&self, cx: &mut App) {
103 self.update(cx, |this, cx| this.send(cx));
104 }
105}
106
107impl MessageEditor {
108 pub fn new(
109 workspace: WeakEntity<Workspace>,
110 project: WeakEntity<Project>,
111 thread_store: Option<Entity<ThreadStore>>,
112 history: WeakEntity<ThreadHistory>,
113 prompt_store: Option<Entity<PromptStore>>,
114 prompt_capabilities: Rc<RefCell<acp::PromptCapabilities>>,
115 available_commands: Rc<RefCell<Vec<acp::AvailableCommand>>>,
116 agent_name: SharedString,
117 placeholder: &str,
118 mode: EditorMode,
119 window: &mut Window,
120 cx: &mut Context<Self>,
121 ) -> Self {
122 let language = Language::new(
123 language::LanguageConfig {
124 completion_query_characters: HashSet::from_iter(['.', '-', '_', '@']),
125 ..Default::default()
126 },
127 None,
128 );
129
130 let editor = cx.new(|cx| {
131 let buffer = cx.new(|cx| Buffer::local("", cx).with_language(Arc::new(language), cx));
132 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
133
134 let mut editor = Editor::new(mode, buffer, None, window, cx);
135 editor.set_placeholder_text(placeholder, window, cx);
136 editor.set_show_indent_guides(false, cx);
137 editor.set_show_completions_on_input(Some(true));
138 editor.set_soft_wrap();
139 editor.set_use_modal_editing(true);
140 editor.set_context_menu_options(ContextMenuOptions {
141 min_entries_visible: 12,
142 max_entries_visible: 12,
143 placement: Some(ContextMenuPlacement::Above),
144 });
145 editor.register_addon(MessageEditorAddon::new());
146
147 editor.set_custom_context_menu(|editor, _point, window, cx| {
148 let has_selection = editor.has_non_empty_selection(&editor.display_snapshot(cx));
149
150 Some(ContextMenu::build(window, cx, |menu, _, _| {
151 menu.action("Cut", Box::new(editor::actions::Cut))
152 .action_disabled_when(
153 !has_selection,
154 "Copy",
155 Box::new(editor::actions::Copy),
156 )
157 .action("Paste", Box::new(editor::actions::Paste))
158 .action("Paste as Plain Text", Box::new(PasteRaw))
159 }))
160 });
161
162 editor
163 });
164 let mention_set =
165 cx.new(|_cx| MentionSet::new(project, thread_store.clone(), prompt_store.clone()));
166 let completion_provider = Rc::new(PromptCompletionProvider::new(
167 cx.entity(),
168 editor.downgrade(),
169 mention_set.clone(),
170 history,
171 prompt_store.clone(),
172 workspace.clone(),
173 ));
174 editor.update(cx, |editor, _cx| {
175 editor.set_completion_provider(Some(completion_provider.clone()))
176 });
177
178 cx.on_focus_in(&editor.focus_handle(cx), window, |_, _, cx| {
179 cx.emit(MessageEditorEvent::Focus)
180 })
181 .detach();
182 cx.on_focus_out(&editor.focus_handle(cx), window, |_, _, _, cx| {
183 cx.emit(MessageEditorEvent::LostFocus)
184 })
185 .detach();
186
187 let mut has_hint = false;
188 let mut subscriptions = Vec::new();
189
190 subscriptions.push(cx.subscribe_in(&editor, window, {
191 move |this, editor, event, window, cx| {
192 let input_attempted_text = match event {
193 EditorEvent::InputHandled { text, .. } => Some(text),
194 EditorEvent::InputIgnored { text } => Some(text),
195 _ => None,
196 };
197 if let Some(text) = input_attempted_text
198 && editor.read(cx).read_only(cx)
199 && !text.is_empty()
200 {
201 cx.emit(MessageEditorEvent::InputAttempted(text.clone()));
202 }
203
204 if let EditorEvent::Edited { .. } = event
205 && !editor.read(cx).read_only(cx)
206 {
207 editor.update(cx, |editor, cx| {
208 let snapshot = editor.snapshot(window, cx);
209 this.mention_set
210 .update(cx, |mention_set, _cx| mention_set.remove_invalid(&snapshot));
211
212 let new_hints = this
213 .command_hint(snapshot.buffer())
214 .into_iter()
215 .collect::<Vec<_>>();
216 let has_new_hint = !new_hints.is_empty();
217 editor.splice_inlays(
218 if has_hint {
219 &[COMMAND_HINT_INLAY_ID]
220 } else {
221 &[]
222 },
223 new_hints,
224 cx,
225 );
226 has_hint = has_new_hint;
227 });
228 cx.notify();
229 }
230 }
231 }));
232
233 Self {
234 editor,
235 mention_set,
236 workspace,
237 prompt_capabilities,
238 available_commands,
239 agent_name,
240 thread_store,
241 _subscriptions: subscriptions,
242 _parse_slash_command_task: Task::ready(()),
243 }
244 }
245
246 pub fn set_command_state(
247 &mut self,
248 prompt_capabilities: Rc<RefCell<acp::PromptCapabilities>>,
249 available_commands: Rc<RefCell<Vec<acp::AvailableCommand>>>,
250 _cx: &mut Context<Self>,
251 ) {
252 self.prompt_capabilities = prompt_capabilities;
253 self.available_commands = available_commands;
254 }
255
256 fn command_hint(&self, snapshot: &MultiBufferSnapshot) -> Option<Inlay> {
257 let available_commands = self.available_commands.borrow();
258 if available_commands.is_empty() {
259 return None;
260 }
261
262 let parsed_command = SlashCommandCompletion::try_parse(&snapshot.text(), 0)?;
263 if parsed_command.argument.is_some() {
264 return None;
265 }
266
267 let command_name = parsed_command.command?;
268 let available_command = available_commands
269 .iter()
270 .find(|command| command.name == command_name)?;
271
272 let acp::AvailableCommandInput::Unstructured(acp::UnstructuredCommandInput {
273 mut hint,
274 ..
275 }) = available_command.input.clone()?
276 else {
277 return None;
278 };
279
280 let mut hint_pos = MultiBufferOffset(parsed_command.source_range.end) + 1usize;
281 if hint_pos > snapshot.len() {
282 hint_pos = snapshot.len();
283 hint.insert(0, ' ');
284 }
285
286 let hint_pos = snapshot.anchor_after(hint_pos);
287
288 Some(Inlay::hint(
289 COMMAND_HINT_INLAY_ID,
290 hint_pos,
291 &InlayHint {
292 position: hint_pos.text_anchor,
293 label: InlayHintLabel::String(hint),
294 kind: Some(InlayHintKind::Parameter),
295 padding_left: false,
296 padding_right: false,
297 tooltip: None,
298 resolve_state: project::ResolveState::Resolved,
299 },
300 ))
301 }
302
303 pub fn insert_thread_summary(
304 &mut self,
305 session_id: acp::SessionId,
306 title: Option<SharedString>,
307 window: &mut Window,
308 cx: &mut Context<Self>,
309 ) {
310 if self.thread_store.is_none() {
311 return;
312 }
313 let Some(workspace) = self.workspace.upgrade() else {
314 return;
315 };
316 let thread_title = title
317 .filter(|title| !title.is_empty())
318 .unwrap_or_else(|| SharedString::new_static("New Thread"));
319 let uri = MentionUri::Thread {
320 id: session_id,
321 name: thread_title.to_string(),
322 };
323 let content = format!("{}\n", uri.as_link());
324
325 let content_len = content.len() - 1;
326
327 let start = self.editor.update(cx, |editor, cx| {
328 editor.set_text(content, window, cx);
329 editor
330 .buffer()
331 .read(cx)
332 .snapshot(cx)
333 .anchor_before(Point::zero())
334 .text_anchor
335 });
336
337 let supports_images = self.prompt_capabilities.borrow().image;
338
339 self.mention_set
340 .update(cx, |mention_set, cx| {
341 mention_set.confirm_mention_completion(
342 thread_title,
343 start,
344 content_len,
345 uri,
346 supports_images,
347 self.editor.clone(),
348 &workspace,
349 window,
350 cx,
351 )
352 })
353 .detach();
354 }
355
356 #[cfg(test)]
357 pub(crate) fn editor(&self) -> &Entity<Editor> {
358 &self.editor
359 }
360
361 pub fn is_empty(&self, cx: &App) -> bool {
362 self.editor.read(cx).is_empty(cx)
363 }
364
365 pub fn is_completions_menu_visible(&self, cx: &App) -> bool {
366 self.editor
367 .read(cx)
368 .context_menu()
369 .borrow()
370 .as_ref()
371 .is_some_and(|menu| matches!(menu, CodeContextMenu::Completions(_)) && menu.visible())
372 }
373
374 #[cfg(test)]
375 pub fn mention_set(&self) -> &Entity<MentionSet> {
376 &self.mention_set
377 }
378
379 fn validate_slash_commands(
380 text: &str,
381 available_commands: &[acp::AvailableCommand],
382 agent_name: &str,
383 ) -> Result<()> {
384 if let Some(parsed_command) = SlashCommandCompletion::try_parse(text, 0) {
385 if let Some(command_name) = parsed_command.command {
386 // Check if this command is in the list of available commands from the server
387 let is_supported = available_commands
388 .iter()
389 .any(|cmd| cmd.name == command_name);
390
391 if !is_supported {
392 return Err(anyhow!(
393 "The /{} command is not supported by {}.\n\nAvailable commands: {}",
394 command_name,
395 agent_name,
396 if available_commands.is_empty() {
397 "none".to_string()
398 } else {
399 available_commands
400 .iter()
401 .map(|cmd| format!("/{}", cmd.name))
402 .collect::<Vec<_>>()
403 .join(", ")
404 }
405 ));
406 }
407 }
408 }
409 Ok(())
410 }
411
412 pub fn contents(
413 &self,
414 full_mention_content: bool,
415 cx: &mut Context<Self>,
416 ) -> Task<Result<(Vec<acp::ContentBlock>, Vec<Entity<Buffer>>)>> {
417 let text = self.editor.read(cx).text(cx);
418 let available_commands = self.available_commands.borrow().clone();
419 let agent_name = self.agent_name.clone();
420 let build_task = self.build_content_blocks(full_mention_content, cx);
421
422 cx.spawn(async move |_, _cx| {
423 Self::validate_slash_commands(&text, &available_commands, &agent_name)?;
424 build_task.await
425 })
426 }
427
428 pub fn draft_contents(&self, cx: &mut Context<Self>) -> Task<Result<Vec<acp::ContentBlock>>> {
429 let build_task = self.build_content_blocks(false, cx);
430 cx.spawn(async move |_, _cx| {
431 let (blocks, _tracked_buffers) = build_task.await?;
432 Ok(blocks)
433 })
434 }
435
436 fn build_content_blocks(
437 &self,
438 full_mention_content: bool,
439 cx: &mut Context<Self>,
440 ) -> Task<Result<(Vec<acp::ContentBlock>, Vec<Entity<Buffer>>)>> {
441 let contents = self
442 .mention_set
443 .update(cx, |store, cx| store.contents(full_mention_content, cx));
444 let editor = self.editor.clone();
445 let supports_embedded_context = self.prompt_capabilities.borrow().embedded_context;
446
447 cx.spawn(async move |_, cx| {
448 let contents = contents.await?;
449 let mut all_tracked_buffers = Vec::new();
450
451 let result = editor.update(cx, |editor, cx| {
452 let text = editor.text(cx);
453 let (mut ix, _) = text
454 .char_indices()
455 .find(|(_, c)| !c.is_whitespace())
456 .unwrap_or((0, '\0'));
457 let mut chunks: Vec<acp::ContentBlock> = Vec::new();
458 editor.display_map.update(cx, |map, cx| {
459 let snapshot = map.snapshot(cx);
460 for (crease_id, crease) in snapshot.crease_snapshot.creases() {
461 let Some((uri, mention)) = contents.get(&crease_id) else {
462 continue;
463 };
464
465 let crease_range = crease.range().to_offset(&snapshot.buffer_snapshot());
466 if crease_range.start.0 > ix {
467 let chunk = text[ix..crease_range.start.0].into();
468 chunks.push(chunk);
469 }
470 let chunk = match mention {
471 Mention::Text {
472 content,
473 tracked_buffers,
474 } => {
475 all_tracked_buffers.extend(tracked_buffers.iter().cloned());
476 if supports_embedded_context {
477 acp::ContentBlock::Resource(acp::EmbeddedResource::new(
478 acp::EmbeddedResourceResource::TextResourceContents(
479 acp::TextResourceContents::new(
480 content.clone(),
481 uri.to_uri().to_string(),
482 ),
483 ),
484 ))
485 } else {
486 acp::ContentBlock::ResourceLink(acp::ResourceLink::new(
487 uri.name(),
488 uri.to_uri().to_string(),
489 ))
490 }
491 }
492 Mention::Image(mention_image) => acp::ContentBlock::Image(
493 acp::ImageContent::new(
494 mention_image.data.clone(),
495 mention_image.format.mime_type(),
496 )
497 .uri(match uri {
498 MentionUri::File { .. } => Some(uri.to_uri().to_string()),
499 MentionUri::PastedImage => None,
500 other => {
501 debug_panic!(
502 "unexpected mention uri for image: {:?}",
503 other
504 );
505 None
506 }
507 }),
508 ),
509 Mention::Link => acp::ContentBlock::ResourceLink(
510 acp::ResourceLink::new(uri.name(), uri.to_uri().to_string()),
511 ),
512 };
513 chunks.push(chunk);
514 ix = crease_range.end.0;
515 }
516
517 if ix < text.len() {
518 let last_chunk = text[ix..].trim_end().to_owned();
519 if !last_chunk.is_empty() {
520 chunks.push(last_chunk.into());
521 }
522 }
523 });
524 anyhow::Ok((chunks, all_tracked_buffers))
525 })?;
526 Ok(result)
527 })
528 }
529
530 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
531 self.editor.update(cx, |editor, cx| {
532 editor.clear(window, cx);
533 editor.remove_creases(
534 self.mention_set.update(cx, |mention_set, _cx| {
535 mention_set
536 .clear()
537 .map(|(crease_id, _)| crease_id)
538 .collect::<Vec<_>>()
539 }),
540 cx,
541 )
542 });
543 }
544
545 pub fn send(&mut self, cx: &mut Context<Self>) {
546 if !self.is_empty(cx) {
547 self.editor.update(cx, |editor, cx| {
548 editor.clear_inlay_hints(cx);
549 });
550 }
551 cx.emit(MessageEditorEvent::Send)
552 }
553
554 pub fn trigger_completion_menu(&mut self, window: &mut Window, cx: &mut Context<Self>) {
555 self.insert_context_prefix("@", window, cx);
556 }
557
558 pub fn insert_context_type(
559 &mut self,
560 context_keyword: &str,
561 window: &mut Window,
562 cx: &mut Context<Self>,
563 ) {
564 let prefix = format!("@{}", context_keyword);
565 self.insert_context_prefix(&prefix, window, cx);
566 }
567
568 fn insert_context_prefix(&mut self, prefix: &str, window: &mut Window, cx: &mut Context<Self>) {
569 let editor = self.editor.clone();
570 let prefix = prefix.to_string();
571
572 cx.spawn_in(window, async move |_, cx| {
573 editor
574 .update_in(cx, |editor, window, cx| {
575 let menu_is_open =
576 editor.context_menu().borrow().as_ref().is_some_and(|menu| {
577 matches!(menu, CodeContextMenu::Completions(_)) && menu.visible()
578 });
579
580 let has_prefix = {
581 let snapshot = editor.display_snapshot(cx);
582 let cursor = editor.selections.newest::<text::Point>(&snapshot).head();
583 let offset = cursor.to_offset(&snapshot);
584 let buffer_snapshot = snapshot.buffer_snapshot();
585 let prefix_char_count = prefix.chars().count();
586 buffer_snapshot
587 .reversed_chars_at(offset)
588 .take(prefix_char_count)
589 .eq(prefix.chars().rev())
590 };
591
592 if menu_is_open && has_prefix {
593 return;
594 }
595
596 editor.insert(&prefix, window, cx);
597 editor.show_completions(&editor::actions::ShowCompletions, window, cx);
598 })
599 .log_err();
600 })
601 .detach();
602 }
603
604 fn chat(&mut self, _: &Chat, _: &mut Window, cx: &mut Context<Self>) {
605 self.send(cx);
606 }
607
608 fn send_immediately(&mut self, _: &SendImmediately, _: &mut Window, cx: &mut Context<Self>) {
609 if self.is_empty(cx) {
610 return;
611 }
612
613 self.editor.update(cx, |editor, cx| {
614 editor.clear_inlay_hints(cx);
615 });
616
617 cx.emit(MessageEditorEvent::SendImmediately)
618 }
619
620 fn chat_with_follow(
621 &mut self,
622 _: &ChatWithFollow,
623 window: &mut Window,
624 cx: &mut Context<Self>,
625 ) {
626 self.workspace
627 .update(cx, |this, cx| {
628 this.follow(CollaboratorId::Agent, window, cx)
629 })
630 .log_err();
631
632 self.send(cx);
633 }
634
635 fn cancel(&mut self, _: &editor::actions::Cancel, _: &mut Window, cx: &mut Context<Self>) {
636 cx.emit(MessageEditorEvent::Cancel)
637 }
638
639 fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
640 let Some(workspace) = self.workspace.upgrade() else {
641 return;
642 };
643 let editor_clipboard_selections = cx
644 .read_from_clipboard()
645 .and_then(|item| item.entries().first().cloned())
646 .and_then(|entry| match entry {
647 ClipboardEntry::String(text) => {
648 text.metadata_json::<Vec<editor::ClipboardSelection>>()
649 }
650 _ => None,
651 });
652
653 // Insert creases for pasted clipboard selections that:
654 // 1. Contain exactly one selection
655 // 2. Have an associated file path
656 // 3. Span multiple lines (not single-line selections)
657 // 4. Belong to a file that exists in the current project
658 let should_insert_creases = util::maybe!({
659 let selections = editor_clipboard_selections.as_ref()?;
660 if selections.len() > 1 {
661 return Some(false);
662 }
663 let selection = selections.first()?;
664 let file_path = selection.file_path.as_ref()?;
665 let line_range = selection.line_range.as_ref()?;
666
667 if line_range.start() == line_range.end() {
668 return Some(false);
669 }
670
671 Some(
672 workspace
673 .read(cx)
674 .project()
675 .read(cx)
676 .project_path_for_absolute_path(file_path, cx)
677 .is_some(),
678 )
679 })
680 .unwrap_or(false);
681
682 if should_insert_creases && let Some(selections) = editor_clipboard_selections {
683 cx.stop_propagation();
684 let insertion_target = self
685 .editor
686 .read(cx)
687 .selections
688 .newest_anchor()
689 .start
690 .text_anchor;
691
692 let project = workspace.read(cx).project().clone();
693 for selection in selections {
694 if let (Some(file_path), Some(line_range)) =
695 (selection.file_path, selection.line_range)
696 {
697 let crease_text =
698 acp_thread::selection_name(Some(file_path.as_ref()), &line_range);
699
700 let mention_uri = MentionUri::Selection {
701 abs_path: Some(file_path.clone()),
702 line_range: line_range.clone(),
703 };
704
705 let mention_text = mention_uri.as_link().to_string();
706 let (excerpt_id, text_anchor, content_len) =
707 self.editor.update(cx, |editor, cx| {
708 let buffer = editor.buffer().read(cx);
709 let snapshot = buffer.snapshot(cx);
710 let (excerpt_id, _, buffer_snapshot) = snapshot.as_singleton().unwrap();
711 let text_anchor = insertion_target.bias_left(&buffer_snapshot);
712
713 editor.insert(&mention_text, window, cx);
714 editor.insert(" ", window, cx);
715
716 (excerpt_id, text_anchor, mention_text.len())
717 });
718
719 let Some((crease_id, tx)) = insert_crease_for_mention(
720 excerpt_id,
721 text_anchor,
722 content_len,
723 crease_text.into(),
724 mention_uri.icon_path(cx),
725 mention_uri.tooltip_text(),
726 Some(mention_uri.clone()),
727 Some(self.workspace.clone()),
728 None,
729 self.editor.clone(),
730 window,
731 cx,
732 ) else {
733 continue;
734 };
735 drop(tx);
736
737 let mention_task = cx
738 .spawn({
739 let project = project.clone();
740 async move |_, cx| {
741 let project_path = project
742 .update(cx, |project, cx| {
743 project.project_path_for_absolute_path(&file_path, cx)
744 })
745 .ok_or_else(|| "project path not found".to_string())?;
746
747 let buffer = project
748 .update(cx, |project, cx| project.open_buffer(project_path, cx))
749 .await
750 .map_err(|e| e.to_string())?;
751
752 Ok(buffer.update(cx, |buffer, cx| {
753 let start =
754 Point::new(*line_range.start(), 0).min(buffer.max_point());
755 let end = Point::new(*line_range.end() + 1, 0)
756 .min(buffer.max_point());
757 let content = buffer.text_for_range(start..end).collect();
758 Mention::Text {
759 content,
760 tracked_buffers: vec![cx.entity()],
761 }
762 }))
763 }
764 })
765 .shared();
766
767 self.mention_set.update(cx, |mention_set, _cx| {
768 mention_set.insert_mention(crease_id, mention_uri.clone(), mention_task)
769 });
770 }
771 }
772 return;
773 }
774 // Handle text paste with potential markdown mention links.
775 // This must be checked BEFORE paste_images_as_context because that function
776 // returns a task even when there are no images in the clipboard.
777 if let Some(clipboard_text) = cx
778 .read_from_clipboard()
779 .and_then(|item| item.entries().first().cloned())
780 .and_then(|entry| match entry {
781 ClipboardEntry::String(text) => Some(text.text().to_string()),
782 _ => None,
783 })
784 {
785 if clipboard_text.contains("[@") {
786 cx.stop_propagation();
787 let selections_before = self.editor.update(cx, |editor, cx| {
788 let snapshot = editor.buffer().read(cx).snapshot(cx);
789 editor
790 .selections
791 .disjoint_anchors()
792 .iter()
793 .map(|selection| {
794 (
795 selection.start.bias_left(&snapshot),
796 selection.end.bias_right(&snapshot),
797 )
798 })
799 .collect::<Vec<_>>()
800 });
801
802 self.editor.update(cx, |editor, cx| {
803 editor.insert(&clipboard_text, window, cx);
804 });
805
806 let snapshot = self.editor.read(cx).buffer().read(cx).snapshot(cx);
807 let path_style = workspace.read(cx).project().read(cx).path_style(cx);
808
809 let mut all_mentions = Vec::new();
810 for (start_anchor, end_anchor) in selections_before {
811 let start_offset = start_anchor.to_offset(&snapshot);
812 let end_offset = end_anchor.to_offset(&snapshot);
813
814 // Get the actual inserted text from the buffer (may differ due to auto-indent)
815 let inserted_text: String =
816 snapshot.text_for_range(start_offset..end_offset).collect();
817
818 let parsed_mentions = parse_mention_links(&inserted_text, path_style);
819 for (range, mention_uri) in parsed_mentions {
820 let mention_start_offset = MultiBufferOffset(start_offset.0 + range.start);
821 let anchor = snapshot.anchor_before(mention_start_offset);
822 let content_len = range.end - range.start;
823 all_mentions.push((anchor, content_len, mention_uri));
824 }
825 }
826
827 if !all_mentions.is_empty() {
828 let supports_images = self.prompt_capabilities.borrow().image;
829 let http_client = workspace.read(cx).client().http_client();
830
831 for (anchor, content_len, mention_uri) in all_mentions {
832 let Some((crease_id, tx)) = insert_crease_for_mention(
833 anchor.excerpt_id,
834 anchor.text_anchor,
835 content_len,
836 mention_uri.name().into(),
837 mention_uri.icon_path(cx),
838 mention_uri.tooltip_text(),
839 Some(mention_uri.clone()),
840 Some(self.workspace.clone()),
841 None,
842 self.editor.clone(),
843 window,
844 cx,
845 ) else {
846 continue;
847 };
848
849 // Create the confirmation task based on the mention URI type.
850 // This properly loads file content, fetches URLs, etc.
851 let task = self.mention_set.update(cx, |mention_set, cx| {
852 mention_set.confirm_mention_for_uri(
853 mention_uri.clone(),
854 supports_images,
855 http_client.clone(),
856 cx,
857 )
858 });
859 let task = cx
860 .spawn(async move |_, _| task.await.map_err(|e| e.to_string()))
861 .shared();
862
863 self.mention_set.update(cx, |mention_set, _cx| {
864 mention_set.insert_mention(crease_id, mention_uri.clone(), task.clone())
865 });
866
867 // Drop the tx after inserting to signal the crease is ready
868 drop(tx);
869 }
870 return;
871 }
872 }
873 }
874
875 if self.prompt_capabilities.borrow().image
876 && let Some(task) = paste_images_as_context(
877 self.editor.clone(),
878 self.mention_set.clone(),
879 self.workspace.clone(),
880 window,
881 cx,
882 )
883 {
884 task.detach();
885 return;
886 }
887
888 // Fall through to default editor paste
889 cx.propagate();
890 }
891
892 fn paste_raw(&mut self, _: &PasteRaw, window: &mut Window, cx: &mut Context<Self>) {
893 let editor = self.editor.clone();
894 window.defer(cx, move |window, cx| {
895 editor.update(cx, |editor, cx| editor.paste(&Paste, window, cx));
896 });
897 }
898
899 pub fn insert_dragged_files(
900 &mut self,
901 paths: Vec<project::ProjectPath>,
902 added_worktrees: Vec<Entity<Worktree>>,
903 window: &mut Window,
904 cx: &mut Context<Self>,
905 ) {
906 let Some(workspace) = self.workspace.upgrade() else {
907 return;
908 };
909 let project = workspace.read(cx).project().clone();
910 let path_style = project.read(cx).path_style(cx);
911 let buffer = self.editor.read(cx).buffer().clone();
912 let Some(buffer) = buffer.read(cx).as_singleton() else {
913 return;
914 };
915 let mut tasks = Vec::new();
916 for path in paths {
917 let Some(entry) = project.read(cx).entry_for_path(&path, cx) else {
918 continue;
919 };
920 let Some(worktree) = project.read(cx).worktree_for_id(path.worktree_id, cx) else {
921 continue;
922 };
923 let abs_path = worktree.read(cx).absolutize(&path.path);
924 let (file_name, _) = crate::completion_provider::extract_file_name_and_directory(
925 &path.path,
926 worktree.read(cx).root_name(),
927 path_style,
928 );
929
930 let uri = if entry.is_dir() {
931 MentionUri::Directory { abs_path }
932 } else {
933 MentionUri::File { abs_path }
934 };
935
936 let new_text = format!("{} ", uri.as_link());
937 let content_len = new_text.len() - 1;
938
939 let anchor = buffer.update(cx, |buffer, _cx| buffer.anchor_before(buffer.len()));
940
941 self.editor.update(cx, |message_editor, cx| {
942 message_editor.edit(
943 [(
944 multi_buffer::Anchor::max()..multi_buffer::Anchor::max(),
945 new_text,
946 )],
947 cx,
948 );
949 });
950 let supports_images = self.prompt_capabilities.borrow().image;
951 tasks.push(self.mention_set.update(cx, |mention_set, cx| {
952 mention_set.confirm_mention_completion(
953 file_name,
954 anchor,
955 content_len,
956 uri,
957 supports_images,
958 self.editor.clone(),
959 &workspace,
960 window,
961 cx,
962 )
963 }));
964 }
965 cx.spawn(async move |_, _| {
966 join_all(tasks).await;
967 drop(added_worktrees);
968 })
969 .detach();
970 }
971
972 /// Inserts code snippets as creases into the editor.
973 /// Each tuple contains (code_text, crease_title).
974 pub fn insert_code_creases(
975 &mut self,
976 creases: Vec<(String, String)>,
977 window: &mut Window,
978 cx: &mut Context<Self>,
979 ) {
980 self.editor.update(cx, |editor, cx| {
981 editor.insert("\n", window, cx);
982 });
983 for (text, crease_title) in creases {
984 self.insert_crease_impl(text, crease_title, IconName::TextSnippet, true, window, cx);
985 }
986 }
987
988 pub fn insert_terminal_crease(
989 &mut self,
990 text: String,
991 window: &mut Window,
992 cx: &mut Context<Self>,
993 ) {
994 let line_count = text.lines().count() as u32;
995 let mention_uri = MentionUri::TerminalSelection { line_count };
996 let mention_text = mention_uri.as_link().to_string();
997
998 let (excerpt_id, text_anchor, content_len) = self.editor.update(cx, |editor, cx| {
999 let buffer = editor.buffer().read(cx);
1000 let snapshot = buffer.snapshot(cx);
1001 let (excerpt_id, _, buffer_snapshot) = snapshot.as_singleton().unwrap();
1002 let text_anchor = editor
1003 .selections
1004 .newest_anchor()
1005 .start
1006 .text_anchor
1007 .bias_left(&buffer_snapshot);
1008
1009 editor.insert(&mention_text, window, cx);
1010 editor.insert(" ", window, cx);
1011
1012 (excerpt_id, text_anchor, mention_text.len())
1013 });
1014
1015 let Some((crease_id, tx)) = insert_crease_for_mention(
1016 excerpt_id,
1017 text_anchor,
1018 content_len,
1019 mention_uri.name().into(),
1020 mention_uri.icon_path(cx),
1021 mention_uri.tooltip_text(),
1022 Some(mention_uri.clone()),
1023 Some(self.workspace.clone()),
1024 None,
1025 self.editor.clone(),
1026 window,
1027 cx,
1028 ) else {
1029 return;
1030 };
1031 drop(tx);
1032
1033 let mention_task = Task::ready(Ok(Mention::Text {
1034 content: text,
1035 tracked_buffers: vec![],
1036 }))
1037 .shared();
1038
1039 self.mention_set.update(cx, |mention_set, _| {
1040 mention_set.insert_mention(crease_id, mention_uri, mention_task);
1041 });
1042 }
1043
1044 fn insert_crease_impl(
1045 &mut self,
1046 text: String,
1047 title: String,
1048 icon: IconName,
1049 add_trailing_newline: bool,
1050 window: &mut Window,
1051 cx: &mut Context<Self>,
1052 ) {
1053 use editor::display_map::{Crease, FoldPlaceholder};
1054 use multi_buffer::MultiBufferRow;
1055 use rope::Point;
1056
1057 self.editor.update(cx, |editor, cx| {
1058 let point = editor
1059 .selections
1060 .newest::<Point>(&editor.display_snapshot(cx))
1061 .head();
1062 let start_row = MultiBufferRow(point.row);
1063
1064 editor.insert(&text, window, cx);
1065
1066 let snapshot = editor.buffer().read(cx).snapshot(cx);
1067 let anchor_before = snapshot.anchor_after(point);
1068 let anchor_after = editor
1069 .selections
1070 .newest_anchor()
1071 .head()
1072 .bias_left(&snapshot);
1073
1074 if add_trailing_newline {
1075 editor.insert("\n", window, cx);
1076 }
1077
1078 let fold_placeholder = FoldPlaceholder {
1079 render: Arc::new({
1080 let title = title.clone();
1081 move |_fold_id, _fold_range, _cx| {
1082 ButtonLike::new("crease")
1083 .style(ButtonStyle::Filled)
1084 .layer(ElevationIndex::ElevatedSurface)
1085 .child(Icon::new(icon))
1086 .child(Label::new(title.clone()).single_line())
1087 .into_any_element()
1088 }
1089 }),
1090 merge_adjacent: false,
1091 ..Default::default()
1092 };
1093
1094 let crease = Crease::inline(
1095 anchor_before..anchor_after,
1096 fold_placeholder,
1097 |row, is_folded, fold, _window, _cx| {
1098 Disclosure::new(("crease-toggle", row.0 as u64), !is_folded)
1099 .toggle_state(is_folded)
1100 .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
1101 .into_any_element()
1102 },
1103 |_, _, _, _| gpui::Empty.into_any(),
1104 );
1105 editor.insert_creases(vec![crease], cx);
1106 editor.fold_at(start_row, window, cx);
1107 });
1108 }
1109
1110 pub fn insert_selections(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1111 let editor = self.editor.read(cx);
1112 let editor_buffer = editor.buffer().read(cx);
1113 let Some(buffer) = editor_buffer.as_singleton() else {
1114 return;
1115 };
1116 let cursor_anchor = editor.selections.newest_anchor().head();
1117 let cursor_offset = cursor_anchor.to_offset(&editor_buffer.snapshot(cx));
1118 let anchor = buffer.update(cx, |buffer, _cx| {
1119 buffer.anchor_before(cursor_offset.0.min(buffer.len()))
1120 });
1121 let Some(workspace) = self.workspace.upgrade() else {
1122 return;
1123 };
1124 let Some(completion) =
1125 PromptCompletionProvider::<Entity<MessageEditor>>::completion_for_action(
1126 PromptContextAction::AddSelections,
1127 anchor..anchor,
1128 self.editor.downgrade(),
1129 self.mention_set.downgrade(),
1130 &workspace,
1131 cx,
1132 )
1133 else {
1134 return;
1135 };
1136
1137 self.editor.update(cx, |message_editor, cx| {
1138 message_editor.edit([(cursor_anchor..cursor_anchor, completion.new_text)], cx);
1139 message_editor.request_autoscroll(Autoscroll::fit(), cx);
1140 });
1141 if let Some(confirm) = completion.confirm {
1142 confirm(CompletionIntent::Complete, window, cx);
1143 }
1144 }
1145
1146 pub fn add_images_from_picker(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1147 if !self.prompt_capabilities.borrow().image {
1148 return;
1149 }
1150
1151 let editor = self.editor.clone();
1152 let mention_set = self.mention_set.clone();
1153 let workspace = self.workspace.clone();
1154
1155 let paths_receiver = cx.prompt_for_paths(gpui::PathPromptOptions {
1156 files: true,
1157 directories: false,
1158 multiple: true,
1159 prompt: Some("Select Images".into()),
1160 });
1161
1162 window
1163 .spawn(cx, async move |cx| {
1164 let paths = match paths_receiver.await {
1165 Ok(Ok(Some(paths))) => paths,
1166 _ => return Ok::<(), anyhow::Error>(()),
1167 };
1168
1169 let supported_formats = [
1170 ("png", gpui::ImageFormat::Png),
1171 ("jpg", gpui::ImageFormat::Jpeg),
1172 ("jpeg", gpui::ImageFormat::Jpeg),
1173 ("webp", gpui::ImageFormat::Webp),
1174 ("gif", gpui::ImageFormat::Gif),
1175 ("bmp", gpui::ImageFormat::Bmp),
1176 ("tiff", gpui::ImageFormat::Tiff),
1177 ("tif", gpui::ImageFormat::Tiff),
1178 ("ico", gpui::ImageFormat::Ico),
1179 ];
1180
1181 let mut images = Vec::new();
1182 for path in paths {
1183 let extension = path
1184 .extension()
1185 .and_then(|ext| ext.to_str())
1186 .map(|s| s.to_lowercase());
1187
1188 let Some(format) = extension.and_then(|ext| {
1189 supported_formats
1190 .iter()
1191 .find(|(e, _)| *e == ext)
1192 .map(|(_, f)| *f)
1193 }) else {
1194 continue;
1195 };
1196
1197 let Ok(content) = async_fs::read(&path).await else {
1198 continue;
1199 };
1200
1201 images.push(gpui::Image::from_bytes(format, content));
1202 }
1203
1204 crate::mention_set::insert_images_as_context(
1205 images,
1206 editor,
1207 mention_set,
1208 workspace,
1209 cx,
1210 )
1211 .await;
1212 Ok(())
1213 })
1214 .detach_and_log_err(cx);
1215 }
1216
1217 pub fn set_read_only(&mut self, read_only: bool, cx: &mut Context<Self>) {
1218 self.editor.update(cx, |message_editor, cx| {
1219 message_editor.set_read_only(read_only);
1220 cx.notify()
1221 })
1222 }
1223
1224 pub fn set_mode(&mut self, mode: EditorMode, cx: &mut Context<Self>) {
1225 self.editor.update(cx, |editor, cx| {
1226 if *editor.mode() != mode {
1227 editor.set_mode(mode);
1228 cx.notify()
1229 }
1230 });
1231 }
1232
1233 pub fn set_message(
1234 &mut self,
1235 message: Vec<acp::ContentBlock>,
1236 window: &mut Window,
1237 cx: &mut Context<Self>,
1238 ) {
1239 self.clear(window, cx);
1240 self.insert_message_blocks(message, false, window, cx);
1241 }
1242
1243 pub fn append_message(
1244 &mut self,
1245 message: Vec<acp::ContentBlock>,
1246 separator: Option<&str>,
1247 window: &mut Window,
1248 cx: &mut Context<Self>,
1249 ) {
1250 if message.is_empty() {
1251 return;
1252 }
1253
1254 if let Some(separator) = separator
1255 && !separator.is_empty()
1256 && !self.is_empty(cx)
1257 {
1258 self.editor.update(cx, |editor, cx| {
1259 editor.insert(separator, window, cx);
1260 });
1261 }
1262
1263 self.insert_message_blocks(message, true, window, cx);
1264 }
1265
1266 fn insert_message_blocks(
1267 &mut self,
1268 message: Vec<acp::ContentBlock>,
1269 append_to_existing: bool,
1270 window: &mut Window,
1271 cx: &mut Context<Self>,
1272 ) {
1273 let Some(workspace) = self.workspace.upgrade() else {
1274 return;
1275 };
1276
1277 let path_style = workspace.read(cx).project().read(cx).path_style(cx);
1278 let mut text = String::new();
1279 let mut mentions = Vec::new();
1280
1281 for chunk in message {
1282 match chunk {
1283 acp::ContentBlock::Text(text_content) => {
1284 text.push_str(&text_content.text);
1285 }
1286 acp::ContentBlock::Resource(acp::EmbeddedResource {
1287 resource: acp::EmbeddedResourceResource::TextResourceContents(resource),
1288 ..
1289 }) => {
1290 let Some(mention_uri) = MentionUri::parse(&resource.uri, path_style).log_err()
1291 else {
1292 continue;
1293 };
1294 let start = text.len();
1295 write!(&mut text, "{}", mention_uri.as_link()).ok();
1296 let end = text.len();
1297 mentions.push((
1298 start..end,
1299 mention_uri,
1300 Mention::Text {
1301 content: resource.text,
1302 tracked_buffers: Vec::new(),
1303 },
1304 ));
1305 }
1306 acp::ContentBlock::ResourceLink(resource) => {
1307 if let Some(mention_uri) =
1308 MentionUri::parse(&resource.uri, path_style).log_err()
1309 {
1310 let start = text.len();
1311 write!(&mut text, "{}", mention_uri.as_link()).ok();
1312 let end = text.len();
1313 mentions.push((start..end, mention_uri, Mention::Link));
1314 }
1315 }
1316 acp::ContentBlock::Image(acp::ImageContent {
1317 uri,
1318 data,
1319 mime_type,
1320 ..
1321 }) => {
1322 let mention_uri = if let Some(uri) = uri {
1323 MentionUri::parse(&uri, path_style)
1324 } else {
1325 Ok(MentionUri::PastedImage)
1326 };
1327 let Some(mention_uri) = mention_uri.log_err() else {
1328 continue;
1329 };
1330 let Some(format) = ImageFormat::from_mime_type(&mime_type) else {
1331 log::error!("failed to parse MIME type for image: {mime_type:?}");
1332 continue;
1333 };
1334 let start = text.len();
1335 write!(&mut text, "{}", mention_uri.as_link()).ok();
1336 let end = text.len();
1337 mentions.push((
1338 start..end,
1339 mention_uri,
1340 Mention::Image(MentionImage {
1341 data: data.into(),
1342 format,
1343 }),
1344 ));
1345 }
1346 _ => {}
1347 }
1348 }
1349
1350 if text.is_empty() && mentions.is_empty() {
1351 return;
1352 }
1353
1354 let insertion_start = if append_to_existing {
1355 self.editor.read(cx).text(cx).len()
1356 } else {
1357 0
1358 };
1359
1360 let snapshot = if append_to_existing {
1361 self.editor.update(cx, |editor, cx| {
1362 editor.insert(&text, window, cx);
1363 editor.buffer().read(cx).snapshot(cx)
1364 })
1365 } else {
1366 self.editor.update(cx, |editor, cx| {
1367 editor.set_text(text, window, cx);
1368 editor.buffer().read(cx).snapshot(cx)
1369 })
1370 };
1371
1372 for (range, mention_uri, mention) in mentions {
1373 let adjusted_start = insertion_start + range.start;
1374 let anchor = snapshot.anchor_before(MultiBufferOffset(adjusted_start));
1375 let Some((crease_id, tx)) = insert_crease_for_mention(
1376 anchor.excerpt_id,
1377 anchor.text_anchor,
1378 range.end - range.start,
1379 mention_uri.name().into(),
1380 mention_uri.icon_path(cx),
1381 mention_uri.tooltip_text(),
1382 Some(mention_uri.clone()),
1383 Some(self.workspace.clone()),
1384 None,
1385 self.editor.clone(),
1386 window,
1387 cx,
1388 ) else {
1389 continue;
1390 };
1391 drop(tx);
1392
1393 self.mention_set.update(cx, |mention_set, _cx| {
1394 mention_set.insert_mention(
1395 crease_id,
1396 mention_uri.clone(),
1397 Task::ready(Ok(mention)).shared(),
1398 )
1399 });
1400 }
1401
1402 cx.notify();
1403 }
1404
1405 pub fn text(&self, cx: &App) -> String {
1406 self.editor.read(cx).text(cx)
1407 }
1408
1409 pub fn insert_text(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
1410 if text.is_empty() {
1411 return;
1412 }
1413
1414 self.editor.update(cx, |editor, cx| {
1415 editor.insert(text, window, cx);
1416 });
1417 }
1418
1419 pub fn set_placeholder_text(
1420 &mut self,
1421 placeholder: &str,
1422 window: &mut Window,
1423 cx: &mut Context<Self>,
1424 ) {
1425 self.editor.update(cx, |editor, cx| {
1426 editor.set_placeholder_text(placeholder, window, cx);
1427 });
1428 }
1429
1430 #[cfg(any(test, feature = "test-support"))]
1431 pub fn set_text(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
1432 self.editor.update(cx, |editor, cx| {
1433 editor.set_text(text, window, cx);
1434 });
1435 }
1436}
1437
1438impl Focusable for MessageEditor {
1439 fn focus_handle(&self, cx: &App) -> FocusHandle {
1440 self.editor.focus_handle(cx)
1441 }
1442}
1443
1444impl Render for MessageEditor {
1445 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1446 div()
1447 .key_context("MessageEditor")
1448 .on_action(cx.listener(Self::chat))
1449 .on_action(cx.listener(Self::send_immediately))
1450 .on_action(cx.listener(Self::chat_with_follow))
1451 .on_action(cx.listener(Self::cancel))
1452 .on_action(cx.listener(Self::paste_raw))
1453 .capture_action(cx.listener(Self::paste))
1454 .flex_1()
1455 .child({
1456 let settings = ThemeSettings::get_global(cx);
1457
1458 let text_style = TextStyle {
1459 color: cx.theme().colors().text,
1460 font_family: settings.buffer_font.family.clone(),
1461 font_fallbacks: settings.buffer_font.fallbacks.clone(),
1462 font_features: settings.buffer_font.features.clone(),
1463 font_size: settings.agent_buffer_font_size(cx).into(),
1464 font_weight: settings.buffer_font.weight,
1465 line_height: relative(settings.buffer_line_height.value()),
1466 ..Default::default()
1467 };
1468
1469 EditorElement::new(
1470 &self.editor,
1471 EditorStyle {
1472 background: cx.theme().colors().editor_background,
1473 local_player: cx.theme().players().local(),
1474 text: text_style,
1475 syntax: cx.theme().syntax().clone(),
1476 inlay_hints_style: editor::make_inlay_hints_style(cx),
1477 ..Default::default()
1478 },
1479 )
1480 })
1481 }
1482}
1483
1484pub struct MessageEditorAddon {}
1485
1486impl MessageEditorAddon {
1487 pub fn new() -> Self {
1488 Self {}
1489 }
1490}
1491
1492impl Addon for MessageEditorAddon {
1493 fn to_any(&self) -> &dyn std::any::Any {
1494 self
1495 }
1496
1497 fn to_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
1498 Some(self)
1499 }
1500
1501 fn extend_key_context(&self, key_context: &mut KeyContext, cx: &App) {
1502 let settings = agent_settings::AgentSettings::get_global(cx);
1503 if settings.use_modifier_to_send {
1504 key_context.add("use_modifier_to_send");
1505 }
1506 }
1507}
1508
1509/// Parses markdown mention links in the format `[@name](uri)` from text.
1510/// Returns a vector of (range, MentionUri) pairs where range is the byte range in the text.
1511fn parse_mention_links(text: &str, path_style: PathStyle) -> Vec<(Range<usize>, MentionUri)> {
1512 let mut mentions = Vec::new();
1513 let mut search_start = 0;
1514
1515 while let Some(link_start) = text[search_start..].find("[@") {
1516 let absolute_start = search_start + link_start;
1517
1518 // Find the matching closing bracket for the name, handling nested brackets.
1519 // Start at the '[' character so find_matching_bracket can track depth correctly.
1520 let Some(name_end) = find_matching_bracket(&text[absolute_start..], '[', ']') else {
1521 search_start = absolute_start + 2;
1522 continue;
1523 };
1524 let name_end = absolute_start + name_end;
1525
1526 // Check for opening parenthesis immediately after
1527 if text.get(name_end + 1..name_end + 2) != Some("(") {
1528 search_start = name_end + 1;
1529 continue;
1530 }
1531
1532 // Find the matching closing parenthesis for the URI, handling nested parens
1533 let uri_start = name_end + 2;
1534 let Some(uri_end_relative) = find_matching_bracket(&text[name_end + 1..], '(', ')') else {
1535 search_start = uri_start;
1536 continue;
1537 };
1538 let uri_end = name_end + 1 + uri_end_relative;
1539 let link_end = uri_end + 1;
1540
1541 let uri_str = &text[uri_start..uri_end];
1542
1543 // Try to parse the URI as a MentionUri
1544 if let Ok(mention_uri) = MentionUri::parse(uri_str, path_style) {
1545 mentions.push((absolute_start..link_end, mention_uri));
1546 }
1547
1548 search_start = link_end;
1549 }
1550
1551 mentions
1552}
1553
1554/// Finds the position of the matching closing bracket, handling nested brackets.
1555/// The input `text` should start with the opening bracket.
1556/// Returns the index of the matching closing bracket relative to `text`.
1557fn find_matching_bracket(text: &str, open: char, close: char) -> Option<usize> {
1558 let mut depth = 0;
1559 for (index, character) in text.char_indices() {
1560 if character == open {
1561 depth += 1;
1562 } else if character == close {
1563 depth -= 1;
1564 if depth == 0 {
1565 return Some(index);
1566 }
1567 }
1568 }
1569 None
1570}
1571
1572#[cfg(test)]
1573mod tests {
1574 use std::{cell::RefCell, ops::Range, path::Path, rc::Rc, sync::Arc};
1575
1576 use acp_thread::MentionUri;
1577 use agent::{ThreadStore, outline};
1578 use agent_client_protocol as acp;
1579 use editor::{
1580 AnchorRangeExt as _, Editor, EditorMode, MultiBufferOffset, SelectionEffects,
1581 actions::Paste,
1582 };
1583
1584 use fs::FakeFs;
1585 use futures::StreamExt as _;
1586 use gpui::{
1587 AppContext, ClipboardItem, Entity, EventEmitter, FocusHandle, Focusable, TestAppContext,
1588 VisualTestContext,
1589 };
1590 use language_model::LanguageModelRegistry;
1591 use lsp::{CompletionContext, CompletionTriggerKind};
1592 use project::{CompletionIntent, Project, ProjectPath};
1593 use serde_json::json;
1594
1595 use text::Point;
1596 use ui::{App, Context, IntoElement, Render, SharedString, Window};
1597 use util::{path, paths::PathStyle, rel_path::rel_path};
1598 use workspace::{AppState, Item, MultiWorkspace};
1599
1600 use crate::completion_provider::{PromptCompletionProviderDelegate, PromptContextType};
1601 use crate::{
1602 connection_view::tests::init_test,
1603 message_editor::{Mention, MessageEditor, parse_mention_links},
1604 };
1605
1606 #[test]
1607 fn test_parse_mention_links() {
1608 // Single file mention
1609 let text = "[@bundle-mac](file:///Users/test/zed/script/bundle-mac)";
1610 let mentions = parse_mention_links(text, PathStyle::local());
1611 assert_eq!(mentions.len(), 1);
1612 assert_eq!(mentions[0].0, 0..text.len());
1613 assert!(matches!(mentions[0].1, MentionUri::File { .. }));
1614
1615 // Multiple mentions
1616 let text = "Check [@file1](file:///path/to/file1) and [@file2](file:///path/to/file2)!";
1617 let mentions = parse_mention_links(text, PathStyle::local());
1618 assert_eq!(mentions.len(), 2);
1619
1620 // Text without mentions
1621 let text = "Just some regular text without mentions";
1622 let mentions = parse_mention_links(text, PathStyle::local());
1623 assert_eq!(mentions.len(), 0);
1624
1625 // Malformed mentions (should be skipped)
1626 let text = "[@incomplete](invalid://uri) and [@missing](";
1627 let mentions = parse_mention_links(text, PathStyle::local());
1628 assert_eq!(mentions.len(), 0);
1629
1630 // Mixed content with valid mention
1631 let text = "Before [@valid](file:///path/to/file) after";
1632 let mentions = parse_mention_links(text, PathStyle::local());
1633 assert_eq!(mentions.len(), 1);
1634 assert_eq!(mentions[0].0.start, 7);
1635
1636 // HTTP URL mention (Fetch)
1637 let text = "Check out [@docs](https://example.com/docs) for more info";
1638 let mentions = parse_mention_links(text, PathStyle::local());
1639 assert_eq!(mentions.len(), 1);
1640 assert!(matches!(mentions[0].1, MentionUri::Fetch { .. }));
1641
1642 // Directory mention (trailing slash)
1643 let text = "[@src](file:///path/to/src/)";
1644 let mentions = parse_mention_links(text, PathStyle::local());
1645 assert_eq!(mentions.len(), 1);
1646 assert!(matches!(mentions[0].1, MentionUri::Directory { .. }));
1647
1648 // Multiple different mention types
1649 let text = "File [@f](file:///a) and URL [@u](https://b.com) and dir [@d](file:///c/)";
1650 let mentions = parse_mention_links(text, PathStyle::local());
1651 assert_eq!(mentions.len(), 3);
1652 assert!(matches!(mentions[0].1, MentionUri::File { .. }));
1653 assert!(matches!(mentions[1].1, MentionUri::Fetch { .. }));
1654 assert!(matches!(mentions[2].1, MentionUri::Directory { .. }));
1655
1656 // Adjacent mentions without separator
1657 let text = "[@a](file:///a)[@b](file:///b)";
1658 let mentions = parse_mention_links(text, PathStyle::local());
1659 assert_eq!(mentions.len(), 2);
1660
1661 // Regular markdown link (not a mention) should be ignored
1662 let text = "[regular link](https://example.com)";
1663 let mentions = parse_mention_links(text, PathStyle::local());
1664 assert_eq!(mentions.len(), 0);
1665
1666 // Incomplete mention link patterns
1667 let text = "[@name] without url and [@name( malformed";
1668 let mentions = parse_mention_links(text, PathStyle::local());
1669 assert_eq!(mentions.len(), 0);
1670
1671 // Nested brackets in name portion
1672 let text = "[@name [with brackets]](file:///path/to/file)";
1673 let mentions = parse_mention_links(text, PathStyle::local());
1674 assert_eq!(mentions.len(), 1);
1675 assert_eq!(mentions[0].0, 0..text.len());
1676
1677 // Deeply nested brackets
1678 let text = "[@outer [inner [deep]]](file:///path)";
1679 let mentions = parse_mention_links(text, PathStyle::local());
1680 assert_eq!(mentions.len(), 1);
1681
1682 // Unbalanced brackets should fail gracefully
1683 let text = "[@unbalanced [bracket](file:///path)";
1684 let mentions = parse_mention_links(text, PathStyle::local());
1685 assert_eq!(mentions.len(), 0);
1686
1687 // Nested parentheses in URI (common in URLs with query params)
1688 let text = "[@wiki](https://en.wikipedia.org/wiki/Rust_(programming_language))";
1689 let mentions = parse_mention_links(text, PathStyle::local());
1690 assert_eq!(mentions.len(), 1);
1691 if let MentionUri::Fetch { url } = &mentions[0].1 {
1692 assert!(url.as_str().contains("Rust_(programming_language)"));
1693 } else {
1694 panic!("Expected Fetch URI");
1695 }
1696 }
1697
1698 #[gpui::test]
1699 async fn test_at_mention_removal(cx: &mut TestAppContext) {
1700 init_test(cx);
1701
1702 let fs = FakeFs::new(cx.executor());
1703 fs.insert_tree("/project", json!({"file": ""})).await;
1704 let project = Project::test(fs, [Path::new(path!("/project"))], cx).await;
1705
1706 let (multi_workspace, cx) =
1707 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
1708 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
1709
1710 let thread_store = None;
1711 let history = cx.update(|_window, cx| cx.new(|cx| crate::ThreadHistory::new(None, cx)));
1712
1713 let message_editor = cx.update(|window, cx| {
1714 cx.new(|cx| {
1715 MessageEditor::new(
1716 workspace.downgrade(),
1717 project.downgrade(),
1718 thread_store.clone(),
1719 history.downgrade(),
1720 None,
1721 Default::default(),
1722 Default::default(),
1723 "Test Agent".into(),
1724 "Test",
1725 EditorMode::AutoHeight {
1726 min_lines: 1,
1727 max_lines: None,
1728 },
1729 window,
1730 cx,
1731 )
1732 })
1733 });
1734 let editor = message_editor.update(cx, |message_editor, _| message_editor.editor.clone());
1735
1736 cx.run_until_parked();
1737
1738 let excerpt_id = editor.update(cx, |editor, cx| {
1739 editor
1740 .buffer()
1741 .read(cx)
1742 .excerpt_ids()
1743 .into_iter()
1744 .next()
1745 .unwrap()
1746 });
1747 let completions = editor.update_in(cx, |editor, window, cx| {
1748 editor.set_text("Hello @file ", window, cx);
1749 let buffer = editor.buffer().read(cx).as_singleton().unwrap();
1750 let completion_provider = editor.completion_provider().unwrap();
1751 completion_provider.completions(
1752 excerpt_id,
1753 &buffer,
1754 text::Anchor::MAX,
1755 CompletionContext {
1756 trigger_kind: CompletionTriggerKind::TRIGGER_CHARACTER,
1757 trigger_character: Some("@".into()),
1758 },
1759 window,
1760 cx,
1761 )
1762 });
1763 let [_, completion]: [_; 2] = completions
1764 .await
1765 .unwrap()
1766 .into_iter()
1767 .flat_map(|response| response.completions)
1768 .collect::<Vec<_>>()
1769 .try_into()
1770 .unwrap();
1771
1772 editor.update_in(cx, |editor, window, cx| {
1773 let snapshot = editor.buffer().read(cx).snapshot(cx);
1774 let range = snapshot
1775 .anchor_range_in_excerpt(excerpt_id, completion.replace_range)
1776 .unwrap();
1777 editor.edit([(range, completion.new_text)], cx);
1778 (completion.confirm.unwrap())(CompletionIntent::Complete, window, cx);
1779 });
1780
1781 cx.run_until_parked();
1782
1783 // Backspace over the inserted crease (and the following space).
1784 editor.update_in(cx, |editor, window, cx| {
1785 editor.backspace(&Default::default(), window, cx);
1786 editor.backspace(&Default::default(), window, cx);
1787 });
1788
1789 let (content, _) = message_editor
1790 .update(cx, |message_editor, cx| message_editor.contents(false, cx))
1791 .await
1792 .unwrap();
1793
1794 // We don't send a resource link for the deleted crease.
1795 pretty_assertions::assert_matches!(content.as_slice(), [acp::ContentBlock::Text { .. }]);
1796 }
1797
1798 #[gpui::test]
1799 async fn test_slash_command_validation(cx: &mut gpui::TestAppContext) {
1800 init_test(cx);
1801 let fs = FakeFs::new(cx.executor());
1802 fs.insert_tree(
1803 "/test",
1804 json!({
1805 ".zed": {
1806 "tasks.json": r#"[{"label": "test", "command": "echo"}]"#
1807 },
1808 "src": {
1809 "main.rs": "fn main() {}",
1810 },
1811 }),
1812 )
1813 .await;
1814
1815 let project = Project::test(fs.clone(), ["/test".as_ref()], cx).await;
1816 let thread_store = None;
1817 let prompt_capabilities = Rc::new(RefCell::new(acp::PromptCapabilities::default()));
1818 // Start with no available commands - simulating Claude which doesn't support slash commands
1819 let available_commands = Rc::new(RefCell::new(vec![]));
1820
1821 let (multi_workspace, cx) =
1822 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
1823 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
1824 let history = cx.update(|_window, cx| cx.new(|cx| crate::ThreadHistory::new(None, cx)));
1825 let workspace_handle = workspace.downgrade();
1826 let message_editor = workspace.update_in(cx, |_, window, cx| {
1827 cx.new(|cx| {
1828 MessageEditor::new(
1829 workspace_handle.clone(),
1830 project.downgrade(),
1831 thread_store.clone(),
1832 history.downgrade(),
1833 None,
1834 prompt_capabilities.clone(),
1835 available_commands.clone(),
1836 "Claude Agent".into(),
1837 "Test",
1838 EditorMode::AutoHeight {
1839 min_lines: 1,
1840 max_lines: None,
1841 },
1842 window,
1843 cx,
1844 )
1845 })
1846 });
1847 let editor = message_editor.update(cx, |message_editor, _| message_editor.editor.clone());
1848
1849 // Test that slash commands fail when no available_commands are set (empty list means no commands supported)
1850 editor.update_in(cx, |editor, window, cx| {
1851 editor.set_text("/file test.txt", window, cx);
1852 });
1853
1854 let contents_result = message_editor
1855 .update(cx, |message_editor, cx| message_editor.contents(false, cx))
1856 .await;
1857
1858 // Should fail because available_commands is empty (no commands supported)
1859 assert!(contents_result.is_err());
1860 let error_message = contents_result.unwrap_err().to_string();
1861 assert!(error_message.contains("not supported by Claude Agent"));
1862 assert!(error_message.contains("Available commands: none"));
1863
1864 // Now simulate Claude providing its list of available commands (which doesn't include file)
1865 available_commands.replace(vec![acp::AvailableCommand::new("help", "Get help")]);
1866
1867 // Test that unsupported slash commands trigger an error when we have a list of available commands
1868 editor.update_in(cx, |editor, window, cx| {
1869 editor.set_text("/file test.txt", window, cx);
1870 });
1871
1872 let contents_result = message_editor
1873 .update(cx, |message_editor, cx| message_editor.contents(false, cx))
1874 .await;
1875
1876 assert!(contents_result.is_err());
1877 let error_message = contents_result.unwrap_err().to_string();
1878 assert!(error_message.contains("not supported by Claude Agent"));
1879 assert!(error_message.contains("/file"));
1880 assert!(error_message.contains("Available commands: /help"));
1881
1882 // Test that supported commands work fine
1883 editor.update_in(cx, |editor, window, cx| {
1884 editor.set_text("/help", window, cx);
1885 });
1886
1887 let contents_result = message_editor
1888 .update(cx, |message_editor, cx| message_editor.contents(false, cx))
1889 .await;
1890
1891 // Should succeed because /help is in available_commands
1892 assert!(contents_result.is_ok());
1893
1894 // Test that regular text works fine
1895 editor.update_in(cx, |editor, window, cx| {
1896 editor.set_text("Hello Claude!", window, cx);
1897 });
1898
1899 let (content, _) = message_editor
1900 .update(cx, |message_editor, cx| message_editor.contents(false, cx))
1901 .await
1902 .unwrap();
1903
1904 assert_eq!(content.len(), 1);
1905 if let acp::ContentBlock::Text(text) = &content[0] {
1906 assert_eq!(text.text, "Hello Claude!");
1907 } else {
1908 panic!("Expected ContentBlock::Text");
1909 }
1910
1911 // Test that @ mentions still work
1912 editor.update_in(cx, |editor, window, cx| {
1913 editor.set_text("Check this @", window, cx);
1914 });
1915
1916 // The @ mention functionality should not be affected
1917 let (content, _) = message_editor
1918 .update(cx, |message_editor, cx| message_editor.contents(false, cx))
1919 .await
1920 .unwrap();
1921
1922 assert_eq!(content.len(), 1);
1923 if let acp::ContentBlock::Text(text) = &content[0] {
1924 assert_eq!(text.text, "Check this @");
1925 } else {
1926 panic!("Expected ContentBlock::Text");
1927 }
1928 }
1929
1930 struct MessageEditorItem(Entity<MessageEditor>);
1931
1932 impl Item for MessageEditorItem {
1933 type Event = ();
1934
1935 fn include_in_nav_history() -> bool {
1936 false
1937 }
1938
1939 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
1940 "Test".into()
1941 }
1942 }
1943
1944 impl EventEmitter<()> for MessageEditorItem {}
1945
1946 impl Focusable for MessageEditorItem {
1947 fn focus_handle(&self, cx: &App) -> FocusHandle {
1948 self.0.read(cx).focus_handle(cx)
1949 }
1950 }
1951
1952 impl Render for MessageEditorItem {
1953 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
1954 self.0.clone().into_any_element()
1955 }
1956 }
1957
1958 #[gpui::test]
1959 async fn test_completion_provider_commands(cx: &mut TestAppContext) {
1960 init_test(cx);
1961
1962 let app_state = cx.update(AppState::test);
1963
1964 cx.update(|cx| {
1965 editor::init(cx);
1966 workspace::init(app_state.clone(), cx);
1967 });
1968
1969 let project = Project::test(app_state.fs.clone(), [path!("/dir").as_ref()], cx).await;
1970 let window =
1971 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
1972 let workspace = window
1973 .read_with(cx, |mw, _| mw.workspace().clone())
1974 .unwrap();
1975
1976 let mut cx = VisualTestContext::from_window(window.into(), cx);
1977
1978 let thread_store = None;
1979 let history = cx.update(|_window, cx| cx.new(|cx| crate::ThreadHistory::new(None, cx)));
1980 let prompt_capabilities = Rc::new(RefCell::new(acp::PromptCapabilities::default()));
1981 let available_commands = Rc::new(RefCell::new(vec![
1982 acp::AvailableCommand::new("quick-math", "2 + 2 = 4 - 1 = 3"),
1983 acp::AvailableCommand::new("say-hello", "Say hello to whoever you want").input(
1984 acp::AvailableCommandInput::Unstructured(acp::UnstructuredCommandInput::new(
1985 "<name>",
1986 )),
1987 ),
1988 ]));
1989
1990 let editor = workspace.update_in(&mut cx, |workspace, window, cx| {
1991 let workspace_handle = cx.weak_entity();
1992 let message_editor = cx.new(|cx| {
1993 MessageEditor::new(
1994 workspace_handle,
1995 project.downgrade(),
1996 thread_store.clone(),
1997 history.downgrade(),
1998 None,
1999 prompt_capabilities.clone(),
2000 available_commands.clone(),
2001 "Test Agent".into(),
2002 "Test",
2003 EditorMode::AutoHeight {
2004 max_lines: None,
2005 min_lines: 1,
2006 },
2007 window,
2008 cx,
2009 )
2010 });
2011 workspace.active_pane().update(cx, |pane, cx| {
2012 pane.add_item(
2013 Box::new(cx.new(|_| MessageEditorItem(message_editor.clone()))),
2014 true,
2015 true,
2016 None,
2017 window,
2018 cx,
2019 );
2020 });
2021 message_editor.read(cx).focus_handle(cx).focus(window, cx);
2022 message_editor.read(cx).editor().clone()
2023 });
2024
2025 cx.simulate_input("/");
2026
2027 editor.update_in(&mut cx, |editor, window, cx| {
2028 assert_eq!(editor.text(cx), "/");
2029 assert!(editor.has_visible_completions_menu());
2030
2031 assert_eq!(
2032 current_completion_labels_with_documentation(editor),
2033 &[
2034 ("quick-math".into(), "2 + 2 = 4 - 1 = 3".into()),
2035 ("say-hello".into(), "Say hello to whoever you want".into())
2036 ]
2037 );
2038 editor.set_text("", window, cx);
2039 });
2040
2041 cx.simulate_input("/qui");
2042
2043 editor.update_in(&mut cx, |editor, window, cx| {
2044 assert_eq!(editor.text(cx), "/qui");
2045 assert!(editor.has_visible_completions_menu());
2046
2047 assert_eq!(
2048 current_completion_labels_with_documentation(editor),
2049 &[("quick-math".into(), "2 + 2 = 4 - 1 = 3".into())]
2050 );
2051 editor.set_text("", window, cx);
2052 });
2053
2054 editor.update_in(&mut cx, |editor, window, cx| {
2055 assert!(editor.has_visible_completions_menu());
2056 editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
2057 });
2058
2059 cx.run_until_parked();
2060
2061 editor.update_in(&mut cx, |editor, window, cx| {
2062 assert_eq!(editor.display_text(cx), "/quick-math ");
2063 assert!(!editor.has_visible_completions_menu());
2064 editor.set_text("", window, cx);
2065 });
2066
2067 cx.simulate_input("/say");
2068
2069 editor.update_in(&mut cx, |editor, _window, cx| {
2070 assert_eq!(editor.display_text(cx), "/say");
2071 assert!(editor.has_visible_completions_menu());
2072
2073 assert_eq!(
2074 current_completion_labels_with_documentation(editor),
2075 &[("say-hello".into(), "Say hello to whoever you want".into())]
2076 );
2077 });
2078
2079 editor.update_in(&mut cx, |editor, window, cx| {
2080 assert!(editor.has_visible_completions_menu());
2081 editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
2082 });
2083
2084 cx.run_until_parked();
2085
2086 editor.update_in(&mut cx, |editor, _window, cx| {
2087 assert_eq!(editor.text(cx), "/say-hello ");
2088 assert_eq!(editor.display_text(cx), "/say-hello <name>");
2089 assert!(!editor.has_visible_completions_menu());
2090 });
2091
2092 cx.simulate_input("GPT5");
2093
2094 cx.run_until_parked();
2095
2096 editor.update_in(&mut cx, |editor, window, cx| {
2097 assert_eq!(editor.text(cx), "/say-hello GPT5");
2098 assert_eq!(editor.display_text(cx), "/say-hello GPT5");
2099 assert!(!editor.has_visible_completions_menu());
2100
2101 // Delete argument
2102 for _ in 0..5 {
2103 editor.backspace(&editor::actions::Backspace, window, cx);
2104 }
2105 });
2106
2107 cx.run_until_parked();
2108
2109 editor.update_in(&mut cx, |editor, window, cx| {
2110 assert_eq!(editor.text(cx), "/say-hello");
2111 // Hint is visible because argument was deleted
2112 assert_eq!(editor.display_text(cx), "/say-hello <name>");
2113
2114 // Delete last command letter
2115 editor.backspace(&editor::actions::Backspace, window, cx);
2116 });
2117
2118 cx.run_until_parked();
2119
2120 editor.update_in(&mut cx, |editor, _window, cx| {
2121 // Hint goes away once command no longer matches an available one
2122 assert_eq!(editor.text(cx), "/say-hell");
2123 assert_eq!(editor.display_text(cx), "/say-hell");
2124 assert!(!editor.has_visible_completions_menu());
2125 });
2126 }
2127
2128 #[gpui::test]
2129 async fn test_context_completion_provider_mentions(cx: &mut TestAppContext) {
2130 init_test(cx);
2131
2132 let app_state = cx.update(AppState::test);
2133
2134 cx.update(|cx| {
2135 editor::init(cx);
2136 workspace::init(app_state.clone(), cx);
2137 });
2138
2139 app_state
2140 .fs
2141 .as_fake()
2142 .insert_tree(
2143 path!("/dir"),
2144 json!({
2145 "editor": "",
2146 "a": {
2147 "one.txt": "1",
2148 "two.txt": "2",
2149 "three.txt": "3",
2150 "four.txt": "4"
2151 },
2152 "b": {
2153 "five.txt": "5",
2154 "six.txt": "6",
2155 "seven.txt": "7",
2156 "eight.txt": "8",
2157 },
2158 "x.png": "",
2159 }),
2160 )
2161 .await;
2162
2163 let project = Project::test(app_state.fs.clone(), [path!("/dir").as_ref()], cx).await;
2164 let window =
2165 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
2166 let workspace = window
2167 .read_with(cx, |mw, _| mw.workspace().clone())
2168 .unwrap();
2169
2170 let worktree = project.update(cx, |project, cx| {
2171 let mut worktrees = project.worktrees(cx).collect::<Vec<_>>();
2172 assert_eq!(worktrees.len(), 1);
2173 worktrees.pop().unwrap()
2174 });
2175 let worktree_id = worktree.read_with(cx, |worktree, _| worktree.id());
2176
2177 let mut cx = VisualTestContext::from_window(window.into(), cx);
2178
2179 let paths = vec![
2180 rel_path("a/one.txt"),
2181 rel_path("a/two.txt"),
2182 rel_path("a/three.txt"),
2183 rel_path("a/four.txt"),
2184 rel_path("b/five.txt"),
2185 rel_path("b/six.txt"),
2186 rel_path("b/seven.txt"),
2187 rel_path("b/eight.txt"),
2188 ];
2189
2190 let slash = PathStyle::local().primary_separator();
2191
2192 let mut opened_editors = Vec::new();
2193 for path in paths {
2194 let buffer = workspace
2195 .update_in(&mut cx, |workspace, window, cx| {
2196 workspace.open_path(
2197 ProjectPath {
2198 worktree_id,
2199 path: path.into(),
2200 },
2201 None,
2202 false,
2203 window,
2204 cx,
2205 )
2206 })
2207 .await
2208 .unwrap();
2209 opened_editors.push(buffer);
2210 }
2211
2212 let thread_store = cx.new(|cx| ThreadStore::new(cx));
2213 let history = cx.update(|_window, cx| cx.new(|cx| crate::ThreadHistory::new(None, cx)));
2214 let prompt_capabilities = Rc::new(RefCell::new(acp::PromptCapabilities::default()));
2215
2216 let (message_editor, editor) = workspace.update_in(&mut cx, |workspace, window, cx| {
2217 let workspace_handle = cx.weak_entity();
2218 let message_editor = cx.new(|cx| {
2219 MessageEditor::new(
2220 workspace_handle,
2221 project.downgrade(),
2222 Some(thread_store),
2223 history.downgrade(),
2224 None,
2225 prompt_capabilities.clone(),
2226 Default::default(),
2227 "Test Agent".into(),
2228 "Test",
2229 EditorMode::AutoHeight {
2230 max_lines: None,
2231 min_lines: 1,
2232 },
2233 window,
2234 cx,
2235 )
2236 });
2237 workspace.active_pane().update(cx, |pane, cx| {
2238 pane.add_item(
2239 Box::new(cx.new(|_| MessageEditorItem(message_editor.clone()))),
2240 true,
2241 true,
2242 None,
2243 window,
2244 cx,
2245 );
2246 });
2247 message_editor.read(cx).focus_handle(cx).focus(window, cx);
2248 let editor = message_editor.read(cx).editor().clone();
2249 (message_editor, editor)
2250 });
2251
2252 cx.simulate_input("Lorem @");
2253
2254 editor.update_in(&mut cx, |editor, window, cx| {
2255 assert_eq!(editor.text(cx), "Lorem @");
2256 assert!(editor.has_visible_completions_menu());
2257
2258 assert_eq!(
2259 current_completion_labels(editor),
2260 &[
2261 format!("eight.txt b{slash}"),
2262 format!("seven.txt b{slash}"),
2263 format!("six.txt b{slash}"),
2264 format!("five.txt b{slash}"),
2265 "Files & Directories".into(),
2266 "Symbols".into()
2267 ]
2268 );
2269 editor.set_text("", window, cx);
2270 });
2271
2272 prompt_capabilities.replace(
2273 acp::PromptCapabilities::new()
2274 .image(true)
2275 .audio(true)
2276 .embedded_context(true),
2277 );
2278
2279 cx.simulate_input("Lorem ");
2280
2281 editor.update(&mut cx, |editor, cx| {
2282 assert_eq!(editor.text(cx), "Lorem ");
2283 assert!(!editor.has_visible_completions_menu());
2284 });
2285
2286 cx.simulate_input("@");
2287
2288 editor.update(&mut cx, |editor, cx| {
2289 assert_eq!(editor.text(cx), "Lorem @");
2290 assert!(editor.has_visible_completions_menu());
2291 assert_eq!(
2292 current_completion_labels(editor),
2293 &[
2294 format!("eight.txt b{slash}"),
2295 format!("seven.txt b{slash}"),
2296 format!("six.txt b{slash}"),
2297 format!("five.txt b{slash}"),
2298 "Files & Directories".into(),
2299 "Symbols".into(),
2300 "Threads".into(),
2301 "Fetch".into()
2302 ]
2303 );
2304 });
2305
2306 // Select and confirm "File"
2307 editor.update_in(&mut cx, |editor, window, cx| {
2308 assert!(editor.has_visible_completions_menu());
2309 editor.context_menu_next(&editor::actions::ContextMenuNext, window, cx);
2310 editor.context_menu_next(&editor::actions::ContextMenuNext, window, cx);
2311 editor.context_menu_next(&editor::actions::ContextMenuNext, window, cx);
2312 editor.context_menu_next(&editor::actions::ContextMenuNext, window, cx);
2313 editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
2314 });
2315
2316 cx.run_until_parked();
2317
2318 editor.update(&mut cx, |editor, cx| {
2319 assert_eq!(editor.text(cx), "Lorem @file ");
2320 assert!(editor.has_visible_completions_menu());
2321 });
2322
2323 cx.simulate_input("one");
2324
2325 editor.update(&mut cx, |editor, cx| {
2326 assert_eq!(editor.text(cx), "Lorem @file one");
2327 assert!(editor.has_visible_completions_menu());
2328 assert_eq!(
2329 current_completion_labels(editor),
2330 vec![format!("one.txt a{slash}")]
2331 );
2332 });
2333
2334 editor.update_in(&mut cx, |editor, window, cx| {
2335 assert!(editor.has_visible_completions_menu());
2336 editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
2337 });
2338
2339 let url_one = MentionUri::File {
2340 abs_path: path!("/dir/a/one.txt").into(),
2341 }
2342 .to_uri()
2343 .to_string();
2344 editor.update(&mut cx, |editor, cx| {
2345 let text = editor.text(cx);
2346 assert_eq!(text, format!("Lorem [@one.txt]({url_one}) "));
2347 assert!(!editor.has_visible_completions_menu());
2348 assert_eq!(fold_ranges(editor, cx).len(), 1);
2349 });
2350
2351 let contents = message_editor
2352 .update(&mut cx, |message_editor, cx| {
2353 message_editor
2354 .mention_set()
2355 .update(cx, |mention_set, cx| mention_set.contents(false, cx))
2356 })
2357 .await
2358 .unwrap()
2359 .into_values()
2360 .collect::<Vec<_>>();
2361
2362 {
2363 let [(uri, Mention::Text { content, .. })] = contents.as_slice() else {
2364 panic!("Unexpected mentions");
2365 };
2366 pretty_assertions::assert_eq!(content, "1");
2367 pretty_assertions::assert_eq!(
2368 uri,
2369 &MentionUri::parse(&url_one, PathStyle::local()).unwrap()
2370 );
2371 }
2372
2373 cx.simulate_input(" ");
2374
2375 editor.update(&mut cx, |editor, cx| {
2376 let text = editor.text(cx);
2377 assert_eq!(text, format!("Lorem [@one.txt]({url_one}) "));
2378 assert!(!editor.has_visible_completions_menu());
2379 assert_eq!(fold_ranges(editor, cx).len(), 1);
2380 });
2381
2382 cx.simulate_input("Ipsum ");
2383
2384 editor.update(&mut cx, |editor, cx| {
2385 let text = editor.text(cx);
2386 assert_eq!(text, format!("Lorem [@one.txt]({url_one}) Ipsum "),);
2387 assert!(!editor.has_visible_completions_menu());
2388 assert_eq!(fold_ranges(editor, cx).len(), 1);
2389 });
2390
2391 cx.simulate_input("@file ");
2392
2393 editor.update(&mut cx, |editor, cx| {
2394 let text = editor.text(cx);
2395 assert_eq!(text, format!("Lorem [@one.txt]({url_one}) Ipsum @file "),);
2396 assert!(editor.has_visible_completions_menu());
2397 assert_eq!(fold_ranges(editor, cx).len(), 1);
2398 });
2399
2400 editor.update_in(&mut cx, |editor, window, cx| {
2401 editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
2402 });
2403
2404 cx.run_until_parked();
2405
2406 let contents = message_editor
2407 .update(&mut cx, |message_editor, cx| {
2408 message_editor
2409 .mention_set()
2410 .update(cx, |mention_set, cx| mention_set.contents(false, cx))
2411 })
2412 .await
2413 .unwrap()
2414 .into_values()
2415 .collect::<Vec<_>>();
2416
2417 let url_eight = MentionUri::File {
2418 abs_path: path!("/dir/b/eight.txt").into(),
2419 }
2420 .to_uri()
2421 .to_string();
2422
2423 {
2424 let [_, (uri, Mention::Text { content, .. })] = contents.as_slice() else {
2425 panic!("Unexpected mentions");
2426 };
2427 pretty_assertions::assert_eq!(content, "8");
2428 pretty_assertions::assert_eq!(
2429 uri,
2430 &MentionUri::parse(&url_eight, PathStyle::local()).unwrap()
2431 );
2432 }
2433
2434 editor.update(&mut cx, |editor, cx| {
2435 assert_eq!(
2436 editor.text(cx),
2437 format!("Lorem [@one.txt]({url_one}) Ipsum [@eight.txt]({url_eight}) ")
2438 );
2439 assert!(!editor.has_visible_completions_menu());
2440 assert_eq!(fold_ranges(editor, cx).len(), 2);
2441 });
2442
2443 let plain_text_language = Arc::new(language::Language::new(
2444 language::LanguageConfig {
2445 name: "Plain Text".into(),
2446 matcher: language::LanguageMatcher {
2447 path_suffixes: vec!["txt".to_string()],
2448 ..Default::default()
2449 },
2450 ..Default::default()
2451 },
2452 None,
2453 ));
2454
2455 // Register the language and fake LSP
2456 let language_registry = project.read_with(&cx, |project, _| project.languages().clone());
2457 language_registry.add(plain_text_language);
2458
2459 let mut fake_language_servers = language_registry.register_fake_lsp(
2460 "Plain Text",
2461 language::FakeLspAdapter {
2462 capabilities: lsp::ServerCapabilities {
2463 workspace_symbol_provider: Some(lsp::OneOf::Left(true)),
2464 ..Default::default()
2465 },
2466 ..Default::default()
2467 },
2468 );
2469
2470 // Open the buffer to trigger LSP initialization
2471 let buffer = project
2472 .update(&mut cx, |project, cx| {
2473 project.open_local_buffer(path!("/dir/a/one.txt"), cx)
2474 })
2475 .await
2476 .unwrap();
2477
2478 // Register the buffer with language servers
2479 let _handle = project.update(&mut cx, |project, cx| {
2480 project.register_buffer_with_language_servers(&buffer, cx)
2481 });
2482
2483 cx.run_until_parked();
2484
2485 let fake_language_server = fake_language_servers.next().await.unwrap();
2486 fake_language_server.set_request_handler::<lsp::WorkspaceSymbolRequest, _, _>(
2487 move |_, _| async move {
2488 Ok(Some(lsp::WorkspaceSymbolResponse::Flat(vec![
2489 #[allow(deprecated)]
2490 lsp::SymbolInformation {
2491 name: "MySymbol".into(),
2492 location: lsp::Location {
2493 uri: lsp::Uri::from_file_path(path!("/dir/a/one.txt")).unwrap(),
2494 range: lsp::Range::new(
2495 lsp::Position::new(0, 0),
2496 lsp::Position::new(0, 1),
2497 ),
2498 },
2499 kind: lsp::SymbolKind::CONSTANT,
2500 tags: None,
2501 container_name: None,
2502 deprecated: None,
2503 },
2504 ])))
2505 },
2506 );
2507
2508 cx.simulate_input("@symbol ");
2509
2510 editor.update(&mut cx, |editor, cx| {
2511 assert_eq!(
2512 editor.text(cx),
2513 format!("Lorem [@one.txt]({url_one}) Ipsum [@eight.txt]({url_eight}) @symbol ")
2514 );
2515 assert!(editor.has_visible_completions_menu());
2516 assert_eq!(current_completion_labels(editor), &["MySymbol one.txt L1"]);
2517 });
2518
2519 editor.update_in(&mut cx, |editor, window, cx| {
2520 editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
2521 });
2522
2523 let symbol = MentionUri::Symbol {
2524 abs_path: path!("/dir/a/one.txt").into(),
2525 name: "MySymbol".into(),
2526 line_range: 0..=0,
2527 };
2528
2529 let contents = message_editor
2530 .update(&mut cx, |message_editor, cx| {
2531 message_editor
2532 .mention_set()
2533 .update(cx, |mention_set, cx| mention_set.contents(false, cx))
2534 })
2535 .await
2536 .unwrap()
2537 .into_values()
2538 .collect::<Vec<_>>();
2539
2540 {
2541 let [_, _, (uri, Mention::Text { content, .. })] = contents.as_slice() else {
2542 panic!("Unexpected mentions");
2543 };
2544 pretty_assertions::assert_eq!(content, "1");
2545 pretty_assertions::assert_eq!(uri, &symbol);
2546 }
2547
2548 cx.run_until_parked();
2549
2550 editor.read_with(&cx, |editor, cx| {
2551 assert_eq!(
2552 editor.text(cx),
2553 format!(
2554 "Lorem [@one.txt]({url_one}) Ipsum [@eight.txt]({url_eight}) [@MySymbol]({}) ",
2555 symbol.to_uri(),
2556 )
2557 );
2558 });
2559
2560 // Try to mention an "image" file that will fail to load
2561 cx.simulate_input("@file x.png");
2562
2563 editor.update(&mut cx, |editor, cx| {
2564 assert_eq!(
2565 editor.text(cx),
2566 format!("Lorem [@one.txt]({url_one}) Ipsum [@eight.txt]({url_eight}) [@MySymbol]({}) @file x.png", symbol.to_uri())
2567 );
2568 assert!(editor.has_visible_completions_menu());
2569 assert_eq!(current_completion_labels(editor), &["x.png "]);
2570 });
2571
2572 editor.update_in(&mut cx, |editor, window, cx| {
2573 editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
2574 });
2575
2576 // Getting the message contents fails
2577 message_editor
2578 .update(&mut cx, |message_editor, cx| {
2579 message_editor
2580 .mention_set()
2581 .update(cx, |mention_set, cx| mention_set.contents(false, cx))
2582 })
2583 .await
2584 .expect_err("Should fail to load x.png");
2585
2586 cx.run_until_parked();
2587
2588 // Mention was removed
2589 editor.read_with(&cx, |editor, cx| {
2590 assert_eq!(
2591 editor.text(cx),
2592 format!(
2593 "Lorem [@one.txt]({url_one}) Ipsum [@eight.txt]({url_eight}) [@MySymbol]({}) ",
2594 symbol.to_uri()
2595 )
2596 );
2597 });
2598
2599 // Once more
2600 cx.simulate_input("@file x.png");
2601
2602 editor.update(&mut cx, |editor, cx| {
2603 assert_eq!(
2604 editor.text(cx),
2605 format!("Lorem [@one.txt]({url_one}) Ipsum [@eight.txt]({url_eight}) [@MySymbol]({}) @file x.png", symbol.to_uri())
2606 );
2607 assert!(editor.has_visible_completions_menu());
2608 assert_eq!(current_completion_labels(editor), &["x.png "]);
2609 });
2610
2611 editor.update_in(&mut cx, |editor, window, cx| {
2612 editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
2613 });
2614
2615 // This time don't immediately get the contents, just let the confirmed completion settle
2616 cx.run_until_parked();
2617
2618 // Mention was removed
2619 editor.read_with(&cx, |editor, cx| {
2620 assert_eq!(
2621 editor.text(cx),
2622 format!(
2623 "Lorem [@one.txt]({url_one}) Ipsum [@eight.txt]({url_eight}) [@MySymbol]({}) ",
2624 symbol.to_uri()
2625 )
2626 );
2627 });
2628
2629 // Now getting the contents succeeds, because the invalid mention was removed
2630 let contents = message_editor
2631 .update(&mut cx, |message_editor, cx| {
2632 message_editor
2633 .mention_set()
2634 .update(cx, |mention_set, cx| mention_set.contents(false, cx))
2635 })
2636 .await
2637 .unwrap();
2638 assert_eq!(contents.len(), 3);
2639 }
2640
2641 fn fold_ranges(editor: &Editor, cx: &mut App) -> Vec<Range<Point>> {
2642 let snapshot = editor.buffer().read(cx).snapshot(cx);
2643 editor.display_map.update(cx, |display_map, cx| {
2644 display_map
2645 .snapshot(cx)
2646 .folds_in_range(MultiBufferOffset(0)..snapshot.len())
2647 .map(|fold| fold.range.to_point(&snapshot))
2648 .collect()
2649 })
2650 }
2651
2652 fn current_completion_labels(editor: &Editor) -> Vec<String> {
2653 let completions = editor.current_completions().expect("Missing completions");
2654 completions
2655 .into_iter()
2656 .map(|completion| completion.label.text)
2657 .collect::<Vec<_>>()
2658 }
2659
2660 fn current_completion_labels_with_documentation(editor: &Editor) -> Vec<(String, String)> {
2661 let completions = editor.current_completions().expect("Missing completions");
2662 completions
2663 .into_iter()
2664 .map(|completion| {
2665 (
2666 completion.label.text,
2667 completion
2668 .documentation
2669 .map(|d| d.text().to_string())
2670 .unwrap_or_default(),
2671 )
2672 })
2673 .collect::<Vec<_>>()
2674 }
2675
2676 #[gpui::test]
2677 async fn test_large_file_mention_fallback(cx: &mut TestAppContext) {
2678 init_test(cx);
2679
2680 let fs = FakeFs::new(cx.executor());
2681
2682 // Create a large file that exceeds AUTO_OUTLINE_SIZE
2683 // Using plain text without a configured language, so no outline is available
2684 const LINE: &str = "This is a line of text in the file\n";
2685 let large_content = LINE.repeat(2 * (outline::AUTO_OUTLINE_SIZE / LINE.len()));
2686 assert!(large_content.len() > outline::AUTO_OUTLINE_SIZE);
2687
2688 // Create a small file that doesn't exceed AUTO_OUTLINE_SIZE
2689 let small_content = "fn small_function() { /* small */ }\n";
2690 assert!(small_content.len() < outline::AUTO_OUTLINE_SIZE);
2691
2692 fs.insert_tree(
2693 "/project",
2694 json!({
2695 "large_file.txt": large_content.clone(),
2696 "small_file.txt": small_content,
2697 }),
2698 )
2699 .await;
2700
2701 let project = Project::test(fs, [Path::new(path!("/project"))], cx).await;
2702
2703 let (multi_workspace, cx) =
2704 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
2705 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2706
2707 let thread_store = Some(cx.new(|cx| ThreadStore::new(cx)));
2708 let history = cx.update(|_window, cx| cx.new(|cx| crate::ThreadHistory::new(None, cx)));
2709
2710 let message_editor = cx.update(|window, cx| {
2711 cx.new(|cx| {
2712 let editor = MessageEditor::new(
2713 workspace.downgrade(),
2714 project.downgrade(),
2715 thread_store.clone(),
2716 history.downgrade(),
2717 None,
2718 Default::default(),
2719 Default::default(),
2720 "Test Agent".into(),
2721 "Test",
2722 EditorMode::AutoHeight {
2723 min_lines: 1,
2724 max_lines: None,
2725 },
2726 window,
2727 cx,
2728 );
2729 // Enable embedded context so files are actually included
2730 editor
2731 .prompt_capabilities
2732 .replace(acp::PromptCapabilities::new().embedded_context(true));
2733 editor
2734 })
2735 });
2736
2737 // Test large file mention
2738 // Get the absolute path using the project's worktree
2739 let large_file_abs_path = project.read_with(cx, |project, cx| {
2740 let worktree = project.worktrees(cx).next().unwrap();
2741 let worktree_root = worktree.read(cx).abs_path();
2742 worktree_root.join("large_file.txt")
2743 });
2744 let large_file_task = message_editor.update(cx, |editor, cx| {
2745 editor.mention_set().update(cx, |set, cx| {
2746 set.confirm_mention_for_file(large_file_abs_path, true, cx)
2747 })
2748 });
2749
2750 let large_file_mention = large_file_task.await.unwrap();
2751 match large_file_mention {
2752 Mention::Text { content, .. } => {
2753 // Should contain some of the content but not all of it
2754 assert!(
2755 content.contains(LINE),
2756 "Should contain some of the file content"
2757 );
2758 assert!(
2759 !content.contains(&LINE.repeat(100)),
2760 "Should not contain the full file"
2761 );
2762 // Should be much smaller than original
2763 assert!(
2764 content.len() < large_content.len() / 10,
2765 "Should be significantly truncated"
2766 );
2767 }
2768 _ => panic!("Expected Text mention for large file"),
2769 }
2770
2771 // Test small file mention
2772 // Get the absolute path using the project's worktree
2773 let small_file_abs_path = project.read_with(cx, |project, cx| {
2774 let worktree = project.worktrees(cx).next().unwrap();
2775 let worktree_root = worktree.read(cx).abs_path();
2776 worktree_root.join("small_file.txt")
2777 });
2778 let small_file_task = message_editor.update(cx, |editor, cx| {
2779 editor.mention_set().update(cx, |set, cx| {
2780 set.confirm_mention_for_file(small_file_abs_path, true, cx)
2781 })
2782 });
2783
2784 let small_file_mention = small_file_task.await.unwrap();
2785 match small_file_mention {
2786 Mention::Text { content, .. } => {
2787 // Should contain the full actual content
2788 assert_eq!(content, small_content);
2789 }
2790 _ => panic!("Expected Text mention for small file"),
2791 }
2792 }
2793
2794 #[gpui::test]
2795 async fn test_insert_thread_summary(cx: &mut TestAppContext) {
2796 init_test(cx);
2797 cx.update(LanguageModelRegistry::test);
2798
2799 let fs = FakeFs::new(cx.executor());
2800 fs.insert_tree("/project", json!({"file": ""})).await;
2801 let project = Project::test(fs, [Path::new(path!("/project"))], cx).await;
2802
2803 let (multi_workspace, cx) =
2804 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
2805 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2806
2807 let thread_store = Some(cx.new(|cx| ThreadStore::new(cx)));
2808 let history = cx.update(|_window, cx| cx.new(|cx| crate::ThreadHistory::new(None, cx)));
2809
2810 let session_id = acp::SessionId::new("thread-123");
2811 let title = Some("Previous Conversation".into());
2812
2813 let message_editor = cx.update(|window, cx| {
2814 cx.new(|cx| {
2815 let mut editor = MessageEditor::new(
2816 workspace.downgrade(),
2817 project.downgrade(),
2818 thread_store.clone(),
2819 history.downgrade(),
2820 None,
2821 Default::default(),
2822 Default::default(),
2823 "Test Agent".into(),
2824 "Test",
2825 EditorMode::AutoHeight {
2826 min_lines: 1,
2827 max_lines: None,
2828 },
2829 window,
2830 cx,
2831 );
2832 editor.insert_thread_summary(session_id.clone(), title.clone(), window, cx);
2833 editor
2834 })
2835 });
2836
2837 // Construct expected values for verification
2838 let expected_uri = MentionUri::Thread {
2839 id: session_id.clone(),
2840 name: title.as_ref().unwrap().to_string(),
2841 };
2842 let expected_title = title.as_ref().unwrap();
2843 let expected_link = format!("[@{}]({})", expected_title, expected_uri.to_uri());
2844
2845 message_editor.read_with(cx, |editor, cx| {
2846 let text = editor.text(cx);
2847
2848 assert!(
2849 text.contains(&expected_link),
2850 "Expected editor text to contain thread mention link.\nExpected substring: {}\nActual text: {}",
2851 expected_link,
2852 text
2853 );
2854
2855 let mentions = editor.mention_set().read(cx).mentions();
2856 assert_eq!(
2857 mentions.len(),
2858 1,
2859 "Expected exactly one mention after inserting thread summary"
2860 );
2861
2862 assert!(
2863 mentions.contains(&expected_uri),
2864 "Expected mentions to contain the thread URI"
2865 );
2866 });
2867 }
2868
2869 #[gpui::test]
2870 async fn test_insert_thread_summary_skipped_for_external_agents(cx: &mut TestAppContext) {
2871 init_test(cx);
2872 cx.update(LanguageModelRegistry::test);
2873
2874 let fs = FakeFs::new(cx.executor());
2875 fs.insert_tree("/project", json!({"file": ""})).await;
2876 let project = Project::test(fs, [Path::new(path!("/project"))], cx).await;
2877
2878 let (multi_workspace, cx) =
2879 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
2880 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2881
2882 let thread_store = None;
2883 let history = cx.update(|_window, cx| cx.new(|cx| crate::ThreadHistory::new(None, cx)));
2884
2885 let message_editor = cx.update(|window, cx| {
2886 cx.new(|cx| {
2887 let mut editor = MessageEditor::new(
2888 workspace.downgrade(),
2889 project.downgrade(),
2890 thread_store.clone(),
2891 history.downgrade(),
2892 None,
2893 Default::default(),
2894 Default::default(),
2895 "Test Agent".into(),
2896 "Test",
2897 EditorMode::AutoHeight {
2898 min_lines: 1,
2899 max_lines: None,
2900 },
2901 window,
2902 cx,
2903 );
2904 editor.insert_thread_summary(
2905 acp::SessionId::new("thread-123"),
2906 Some("Previous Conversation".into()),
2907 window,
2908 cx,
2909 );
2910 editor
2911 })
2912 });
2913
2914 message_editor.read_with(cx, |editor, cx| {
2915 assert!(
2916 editor.text(cx).is_empty(),
2917 "Expected thread summary to be skipped for external agents"
2918 );
2919 assert!(
2920 editor.mention_set().read(cx).mentions().is_empty(),
2921 "Expected no mentions when thread summary is skipped"
2922 );
2923 });
2924 }
2925
2926 #[gpui::test]
2927 async fn test_thread_mode_hidden_when_disabled(cx: &mut TestAppContext) {
2928 init_test(cx);
2929
2930 let fs = FakeFs::new(cx.executor());
2931 fs.insert_tree("/project", json!({"file": ""})).await;
2932 let project = Project::test(fs, [Path::new(path!("/project"))], cx).await;
2933
2934 let (multi_workspace, cx) =
2935 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
2936 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2937
2938 let thread_store = None;
2939 let history = cx.update(|_window, cx| cx.new(|cx| crate::ThreadHistory::new(None, cx)));
2940
2941 let message_editor = cx.update(|window, cx| {
2942 cx.new(|cx| {
2943 MessageEditor::new(
2944 workspace.downgrade(),
2945 project.downgrade(),
2946 thread_store.clone(),
2947 history.downgrade(),
2948 None,
2949 Default::default(),
2950 Default::default(),
2951 "Test Agent".into(),
2952 "Test",
2953 EditorMode::AutoHeight {
2954 min_lines: 1,
2955 max_lines: None,
2956 },
2957 window,
2958 cx,
2959 )
2960 })
2961 });
2962
2963 message_editor.update(cx, |editor, _cx| {
2964 editor
2965 .prompt_capabilities
2966 .replace(acp::PromptCapabilities::new().embedded_context(true));
2967 });
2968
2969 let supported_modes = {
2970 let app = cx.app.borrow();
2971 message_editor.supported_modes(&app)
2972 };
2973
2974 assert!(
2975 !supported_modes.contains(&PromptContextType::Thread),
2976 "Expected thread mode to be hidden when thread mentions are disabled"
2977 );
2978 }
2979
2980 #[gpui::test]
2981 async fn test_thread_mode_visible_when_enabled(cx: &mut TestAppContext) {
2982 init_test(cx);
2983
2984 let fs = FakeFs::new(cx.executor());
2985 fs.insert_tree("/project", json!({"file": ""})).await;
2986 let project = Project::test(fs, [Path::new(path!("/project"))], cx).await;
2987
2988 let (multi_workspace, cx) =
2989 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
2990 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2991
2992 let thread_store = Some(cx.new(|cx| ThreadStore::new(cx)));
2993 let history = cx.update(|_window, cx| cx.new(|cx| crate::ThreadHistory::new(None, cx)));
2994
2995 let message_editor = cx.update(|window, cx| {
2996 cx.new(|cx| {
2997 MessageEditor::new(
2998 workspace.downgrade(),
2999 project.downgrade(),
3000 thread_store.clone(),
3001 history.downgrade(),
3002 None,
3003 Default::default(),
3004 Default::default(),
3005 "Test Agent".into(),
3006 "Test",
3007 EditorMode::AutoHeight {
3008 min_lines: 1,
3009 max_lines: None,
3010 },
3011 window,
3012 cx,
3013 )
3014 })
3015 });
3016
3017 message_editor.update(cx, |editor, _cx| {
3018 editor
3019 .prompt_capabilities
3020 .replace(acp::PromptCapabilities::new().embedded_context(true));
3021 });
3022
3023 let supported_modes = {
3024 let app = cx.app.borrow();
3025 message_editor.supported_modes(&app)
3026 };
3027
3028 assert!(
3029 supported_modes.contains(&PromptContextType::Thread),
3030 "Expected thread mode to be visible when enabled"
3031 );
3032 }
3033
3034 #[gpui::test]
3035 async fn test_whitespace_trimming(cx: &mut TestAppContext) {
3036 init_test(cx);
3037
3038 let fs = FakeFs::new(cx.executor());
3039 fs.insert_tree("/project", json!({"file.rs": "fn main() {}"}))
3040 .await;
3041 let project = Project::test(fs, [Path::new(path!("/project"))], cx).await;
3042
3043 let (multi_workspace, cx) =
3044 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
3045 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
3046
3047 let thread_store = Some(cx.new(|cx| ThreadStore::new(cx)));
3048 let history = cx.update(|_window, cx| cx.new(|cx| crate::ThreadHistory::new(None, cx)));
3049
3050 let message_editor = cx.update(|window, cx| {
3051 cx.new(|cx| {
3052 MessageEditor::new(
3053 workspace.downgrade(),
3054 project.downgrade(),
3055 thread_store.clone(),
3056 history.downgrade(),
3057 None,
3058 Default::default(),
3059 Default::default(),
3060 "Test Agent".into(),
3061 "Test",
3062 EditorMode::AutoHeight {
3063 min_lines: 1,
3064 max_lines: None,
3065 },
3066 window,
3067 cx,
3068 )
3069 })
3070 });
3071 let editor = message_editor.update(cx, |message_editor, _| message_editor.editor.clone());
3072
3073 cx.run_until_parked();
3074
3075 editor.update_in(cx, |editor, window, cx| {
3076 editor.set_text(" \u{A0}してhello world ", window, cx);
3077 });
3078
3079 let (content, _) = message_editor
3080 .update(cx, |message_editor, cx| message_editor.contents(false, cx))
3081 .await
3082 .unwrap();
3083
3084 assert_eq!(content, vec!["してhello world".into()]);
3085 }
3086
3087 #[gpui::test]
3088 async fn test_editor_respects_embedded_context_capability(cx: &mut TestAppContext) {
3089 init_test(cx);
3090
3091 let fs = FakeFs::new(cx.executor());
3092
3093 let file_content = "fn main() { println!(\"Hello, world!\"); }\n";
3094
3095 fs.insert_tree(
3096 "/project",
3097 json!({
3098 "src": {
3099 "main.rs": file_content,
3100 }
3101 }),
3102 )
3103 .await;
3104
3105 let project = Project::test(fs, [Path::new(path!("/project"))], cx).await;
3106
3107 let (multi_workspace, cx) =
3108 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
3109 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
3110
3111 let thread_store = Some(cx.new(|cx| ThreadStore::new(cx)));
3112 let history = cx.update(|_window, cx| cx.new(|cx| crate::ThreadHistory::new(None, cx)));
3113
3114 let (message_editor, editor) = workspace.update_in(cx, |workspace, window, cx| {
3115 let workspace_handle = cx.weak_entity();
3116 let message_editor = cx.new(|cx| {
3117 MessageEditor::new(
3118 workspace_handle,
3119 project.downgrade(),
3120 thread_store.clone(),
3121 history.downgrade(),
3122 None,
3123 Default::default(),
3124 Default::default(),
3125 "Test Agent".into(),
3126 "Test",
3127 EditorMode::AutoHeight {
3128 max_lines: None,
3129 min_lines: 1,
3130 },
3131 window,
3132 cx,
3133 )
3134 });
3135 workspace.active_pane().update(cx, |pane, cx| {
3136 pane.add_item(
3137 Box::new(cx.new(|_| MessageEditorItem(message_editor.clone()))),
3138 true,
3139 true,
3140 None,
3141 window,
3142 cx,
3143 );
3144 });
3145 message_editor.read(cx).focus_handle(cx).focus(window, cx);
3146 let editor = message_editor.read(cx).editor().clone();
3147 (message_editor, editor)
3148 });
3149
3150 cx.simulate_input("What is in @file main");
3151
3152 editor.update_in(cx, |editor, window, cx| {
3153 assert!(editor.has_visible_completions_menu());
3154 assert_eq!(editor.text(cx), "What is in @file main");
3155 editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
3156 });
3157
3158 let content = message_editor
3159 .update(cx, |editor, cx| editor.contents(false, cx))
3160 .await
3161 .unwrap()
3162 .0;
3163
3164 let main_rs_uri = if cfg!(windows) {
3165 "file:///C:/project/src/main.rs"
3166 } else {
3167 "file:///project/src/main.rs"
3168 };
3169
3170 // When embedded context is `false` we should get a resource link
3171 pretty_assertions::assert_eq!(
3172 content,
3173 vec![
3174 "What is in ".into(),
3175 acp::ContentBlock::ResourceLink(acp::ResourceLink::new("main.rs", main_rs_uri))
3176 ]
3177 );
3178
3179 message_editor.update(cx, |editor, _cx| {
3180 editor
3181 .prompt_capabilities
3182 .replace(acp::PromptCapabilities::new().embedded_context(true))
3183 });
3184
3185 let content = message_editor
3186 .update(cx, |editor, cx| editor.contents(false, cx))
3187 .await
3188 .unwrap()
3189 .0;
3190
3191 // When embedded context is `true` we should get a resource
3192 pretty_assertions::assert_eq!(
3193 content,
3194 vec![
3195 "What is in ".into(),
3196 acp::ContentBlock::Resource(acp::EmbeddedResource::new(
3197 acp::EmbeddedResourceResource::TextResourceContents(
3198 acp::TextResourceContents::new(file_content, main_rs_uri)
3199 )
3200 ))
3201 ]
3202 );
3203 }
3204
3205 #[gpui::test]
3206 async fn test_autoscroll_after_insert_selections(cx: &mut TestAppContext) {
3207 init_test(cx);
3208
3209 let app_state = cx.update(AppState::test);
3210
3211 cx.update(|cx| {
3212 editor::init(cx);
3213 workspace::init(app_state.clone(), cx);
3214 });
3215
3216 app_state
3217 .fs
3218 .as_fake()
3219 .insert_tree(
3220 path!("/dir"),
3221 json!({
3222 "test.txt": "line1\nline2\nline3\nline4\nline5\n",
3223 }),
3224 )
3225 .await;
3226
3227 let project = Project::test(app_state.fs.clone(), [path!("/dir").as_ref()], cx).await;
3228 let window =
3229 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
3230 let workspace = window
3231 .read_with(cx, |mw, _| mw.workspace().clone())
3232 .unwrap();
3233
3234 let worktree = project.update(cx, |project, cx| {
3235 let mut worktrees = project.worktrees(cx).collect::<Vec<_>>();
3236 assert_eq!(worktrees.len(), 1);
3237 worktrees.pop().unwrap()
3238 });
3239 let worktree_id = worktree.read_with(cx, |worktree, _| worktree.id());
3240
3241 let mut cx = VisualTestContext::from_window(window.into(), cx);
3242
3243 // Open a regular editor with the created file, and select a portion of
3244 // the text that will be used for the selections that are meant to be
3245 // inserted in the agent panel.
3246 let editor = workspace
3247 .update_in(&mut cx, |workspace, window, cx| {
3248 workspace.open_path(
3249 ProjectPath {
3250 worktree_id,
3251 path: rel_path("test.txt").into(),
3252 },
3253 None,
3254 false,
3255 window,
3256 cx,
3257 )
3258 })
3259 .await
3260 .unwrap()
3261 .downcast::<Editor>()
3262 .unwrap();
3263
3264 editor.update_in(&mut cx, |editor, window, cx| {
3265 editor.change_selections(Default::default(), window, cx, |selections| {
3266 selections.select_ranges([Point::new(0, 0)..Point::new(0, 5)]);
3267 });
3268 });
3269
3270 let thread_store = Some(cx.new(|cx| ThreadStore::new(cx)));
3271 let history = cx.update(|_window, cx| cx.new(|cx| crate::ThreadHistory::new(None, cx)));
3272
3273 // Create a new `MessageEditor`. The `EditorMode::full()` has to be used
3274 // to ensure we have a fixed viewport, so we can eventually actually
3275 // place the cursor outside of the visible area.
3276 let message_editor = workspace.update_in(&mut cx, |workspace, window, cx| {
3277 let workspace_handle = cx.weak_entity();
3278 let message_editor = cx.new(|cx| {
3279 MessageEditor::new(
3280 workspace_handle,
3281 project.downgrade(),
3282 thread_store.clone(),
3283 history.downgrade(),
3284 None,
3285 Default::default(),
3286 Default::default(),
3287 "Test Agent".into(),
3288 "Test",
3289 EditorMode::full(),
3290 window,
3291 cx,
3292 )
3293 });
3294 workspace.active_pane().update(cx, |pane, cx| {
3295 pane.add_item(
3296 Box::new(cx.new(|_| MessageEditorItem(message_editor.clone()))),
3297 true,
3298 true,
3299 None,
3300 window,
3301 cx,
3302 );
3303 });
3304
3305 message_editor
3306 });
3307
3308 message_editor.update_in(&mut cx, |message_editor, window, cx| {
3309 message_editor.editor.update(cx, |editor, cx| {
3310 // Update the Agent Panel's Message Editor text to have 100
3311 // lines, ensuring that the cursor is set at line 90 and that we
3312 // then scroll all the way to the top, so the cursor's position
3313 // remains off screen.
3314 let mut lines = String::new();
3315 for _ in 1..=100 {
3316 lines.push_str(&"Another line in the agent panel's message editor\n");
3317 }
3318 editor.set_text(lines.as_str(), window, cx);
3319 editor.change_selections(Default::default(), window, cx, |selections| {
3320 selections.select_ranges([Point::new(90, 0)..Point::new(90, 0)]);
3321 });
3322 editor.set_scroll_position(gpui::Point::new(0., 0.), window, cx);
3323 });
3324 });
3325
3326 cx.run_until_parked();
3327
3328 // Before proceeding, let's assert that the cursor is indeed off screen,
3329 // otherwise the rest of the test doesn't make sense.
3330 message_editor.update_in(&mut cx, |message_editor, window, cx| {
3331 message_editor.editor.update(cx, |editor, cx| {
3332 let snapshot = editor.snapshot(window, cx);
3333 let cursor_row = editor.selections.newest::<Point>(&snapshot).head().row;
3334 let scroll_top = snapshot.scroll_position().y as u32;
3335 let visible_lines = editor.visible_line_count().unwrap() as u32;
3336 let visible_range = scroll_top..(scroll_top + visible_lines);
3337
3338 assert!(!visible_range.contains(&cursor_row));
3339 })
3340 });
3341
3342 // Now let's insert the selection in the Agent Panel's editor and
3343 // confirm that, after the insertion, the cursor is now in the visible
3344 // range.
3345 message_editor.update_in(&mut cx, |message_editor, window, cx| {
3346 message_editor.insert_selections(window, cx);
3347 });
3348
3349 cx.run_until_parked();
3350
3351 message_editor.update_in(&mut cx, |message_editor, window, cx| {
3352 message_editor.editor.update(cx, |editor, cx| {
3353 let snapshot = editor.snapshot(window, cx);
3354 let cursor_row = editor.selections.newest::<Point>(&snapshot).head().row;
3355 let scroll_top = snapshot.scroll_position().y as u32;
3356 let visible_lines = editor.visible_line_count().unwrap() as u32;
3357 let visible_range = scroll_top..(scroll_top + visible_lines);
3358
3359 assert!(visible_range.contains(&cursor_row));
3360 })
3361 });
3362 }
3363
3364 #[gpui::test]
3365 async fn test_insert_context_with_multibyte_characters(cx: &mut TestAppContext) {
3366 init_test(cx);
3367
3368 let app_state = cx.update(AppState::test);
3369
3370 cx.update(|cx| {
3371 editor::init(cx);
3372 workspace::init(app_state.clone(), cx);
3373 });
3374
3375 app_state
3376 .fs
3377 .as_fake()
3378 .insert_tree(path!("/dir"), json!({}))
3379 .await;
3380
3381 let project = Project::test(app_state.fs.clone(), [path!("/dir").as_ref()], cx).await;
3382 let window =
3383 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
3384 let workspace = window
3385 .read_with(cx, |mw, _| mw.workspace().clone())
3386 .unwrap();
3387
3388 let mut cx = VisualTestContext::from_window(window.into(), cx);
3389
3390 let thread_store = cx.new(|cx| ThreadStore::new(cx));
3391 let history = cx.update(|_window, cx| cx.new(|cx| crate::ThreadHistory::new(None, cx)));
3392
3393 let (message_editor, editor) = workspace.update_in(&mut cx, |workspace, window, cx| {
3394 let workspace_handle = cx.weak_entity();
3395 let message_editor = cx.new(|cx| {
3396 MessageEditor::new(
3397 workspace_handle,
3398 project.downgrade(),
3399 Some(thread_store),
3400 history.downgrade(),
3401 None,
3402 Default::default(),
3403 Default::default(),
3404 "Test Agent".into(),
3405 "Test",
3406 EditorMode::AutoHeight {
3407 max_lines: None,
3408 min_lines: 1,
3409 },
3410 window,
3411 cx,
3412 )
3413 });
3414 workspace.active_pane().update(cx, |pane, cx| {
3415 pane.add_item(
3416 Box::new(cx.new(|_| MessageEditorItem(message_editor.clone()))),
3417 true,
3418 true,
3419 None,
3420 window,
3421 cx,
3422 );
3423 });
3424 message_editor.read(cx).focus_handle(cx).focus(window, cx);
3425 let editor = message_editor.read(cx).editor().clone();
3426 (message_editor, editor)
3427 });
3428
3429 editor.update_in(&mut cx, |editor, window, cx| {
3430 editor.set_text("😄😄", window, cx);
3431 });
3432
3433 cx.run_until_parked();
3434
3435 message_editor.update_in(&mut cx, |message_editor, window, cx| {
3436 message_editor.insert_context_type("file", window, cx);
3437 });
3438
3439 cx.run_until_parked();
3440
3441 editor.update(&mut cx, |editor, cx| {
3442 assert_eq!(editor.text(cx), "😄😄@file");
3443 });
3444 }
3445
3446 #[gpui::test]
3447 async fn test_paste_mention_link_with_multiple_selections(cx: &mut TestAppContext) {
3448 init_test(cx);
3449
3450 let app_state = cx.update(AppState::test);
3451
3452 cx.update(|cx| {
3453 editor::init(cx);
3454 workspace::init(app_state.clone(), cx);
3455 });
3456
3457 app_state
3458 .fs
3459 .as_fake()
3460 .insert_tree(path!("/project"), json!({"file.txt": "content"}))
3461 .await;
3462
3463 let project = Project::test(app_state.fs.clone(), [path!("/project").as_ref()], cx).await;
3464 let window =
3465 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
3466 let workspace = window
3467 .read_with(cx, |mw, _| mw.workspace().clone())
3468 .unwrap();
3469
3470 let mut cx = VisualTestContext::from_window(window.into(), cx);
3471
3472 let thread_store = cx.new(|cx| ThreadStore::new(cx));
3473 let history = cx.update(|_window, cx| cx.new(|cx| crate::ThreadHistory::new(None, cx)));
3474
3475 let (message_editor, editor) = workspace.update_in(&mut cx, |workspace, window, cx| {
3476 let workspace_handle = cx.weak_entity();
3477 let message_editor = cx.new(|cx| {
3478 MessageEditor::new(
3479 workspace_handle,
3480 project.downgrade(),
3481 Some(thread_store),
3482 history.downgrade(),
3483 None,
3484 Default::default(),
3485 Default::default(),
3486 "Test Agent".into(),
3487 "Test",
3488 EditorMode::AutoHeight {
3489 max_lines: None,
3490 min_lines: 1,
3491 },
3492 window,
3493 cx,
3494 )
3495 });
3496 workspace.active_pane().update(cx, |pane, cx| {
3497 pane.add_item(
3498 Box::new(cx.new(|_| MessageEditorItem(message_editor.clone()))),
3499 true,
3500 true,
3501 None,
3502 window,
3503 cx,
3504 );
3505 });
3506 message_editor.read(cx).focus_handle(cx).focus(window, cx);
3507 let editor = message_editor.read(cx).editor().clone();
3508 (message_editor, editor)
3509 });
3510
3511 editor.update_in(&mut cx, |editor, window, cx| {
3512 editor.set_text(
3513 "AAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAA",
3514 window,
3515 cx,
3516 );
3517 });
3518
3519 cx.run_until_parked();
3520
3521 editor.update_in(&mut cx, |editor, window, cx| {
3522 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
3523 s.select_ranges([
3524 MultiBufferOffset(0)..MultiBufferOffset(25), // First selection (large)
3525 MultiBufferOffset(30)..MultiBufferOffset(55), // Second selection (newest)
3526 ]);
3527 });
3528 });
3529
3530 let mention_link = "[@f](file:///test.txt)";
3531 cx.write_to_clipboard(ClipboardItem::new_string(mention_link.into()));
3532
3533 message_editor.update_in(&mut cx, |message_editor, window, cx| {
3534 message_editor.paste(&Paste, window, cx);
3535 });
3536
3537 let text = editor.update(&mut cx, |editor, cx| editor.text(cx));
3538 assert!(
3539 text.contains("[@f](file:///test.txt)"),
3540 "Expected mention link to be pasted, got: {}",
3541 text
3542 );
3543 }
3544
3545 // Helper that creates a minimal MessageEditor inside a window, returning both
3546 // the entity and the underlying VisualTestContext so callers can drive updates.
3547 async fn setup_message_editor(
3548 cx: &mut TestAppContext,
3549 ) -> (Entity<MessageEditor>, &mut VisualTestContext) {
3550 let fs = FakeFs::new(cx.executor());
3551 fs.insert_tree("/project", json!({"file.txt": ""})).await;
3552 let project = Project::test(fs, [Path::new(path!("/project"))], cx).await;
3553
3554 let (multi_workspace, cx) =
3555 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
3556 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
3557 let history = cx.update(|_window, cx| cx.new(|cx| crate::ThreadHistory::new(None, cx)));
3558
3559 let message_editor = cx.update(|window, cx| {
3560 cx.new(|cx| {
3561 MessageEditor::new(
3562 workspace.downgrade(),
3563 project.downgrade(),
3564 None,
3565 history.downgrade(),
3566 None,
3567 Default::default(),
3568 Default::default(),
3569 "Test Agent".into(),
3570 "Test",
3571 EditorMode::AutoHeight {
3572 min_lines: 1,
3573 max_lines: None,
3574 },
3575 window,
3576 cx,
3577 )
3578 })
3579 });
3580
3581 cx.run_until_parked();
3582 (message_editor, cx)
3583 }
3584
3585 #[gpui::test]
3586 async fn test_set_message_plain_text(cx: &mut TestAppContext) {
3587 init_test(cx);
3588 let (message_editor, cx) = setup_message_editor(cx).await;
3589
3590 message_editor.update_in(cx, |editor, window, cx| {
3591 editor.set_message(
3592 vec![acp::ContentBlock::Text(acp::TextContent::new(
3593 "hello world".to_string(),
3594 ))],
3595 window,
3596 cx,
3597 );
3598 });
3599
3600 let text = message_editor.update(cx, |editor, cx| editor.text(cx));
3601 assert_eq!(text, "hello world");
3602 assert!(!message_editor.update(cx, |editor, cx| editor.is_empty(cx)));
3603 }
3604
3605 #[gpui::test]
3606 async fn test_set_message_replaces_existing_content(cx: &mut TestAppContext) {
3607 init_test(cx);
3608 let (message_editor, cx) = setup_message_editor(cx).await;
3609
3610 // Set initial content.
3611 message_editor.update_in(cx, |editor, window, cx| {
3612 editor.set_message(
3613 vec![acp::ContentBlock::Text(acp::TextContent::new(
3614 "old content".to_string(),
3615 ))],
3616 window,
3617 cx,
3618 );
3619 });
3620
3621 // Replace with new content.
3622 message_editor.update_in(cx, |editor, window, cx| {
3623 editor.set_message(
3624 vec![acp::ContentBlock::Text(acp::TextContent::new(
3625 "new content".to_string(),
3626 ))],
3627 window,
3628 cx,
3629 );
3630 });
3631
3632 let text = message_editor.update(cx, |editor, cx| editor.text(cx));
3633 assert_eq!(
3634 text, "new content",
3635 "set_message should replace old content"
3636 );
3637 }
3638
3639 #[gpui::test]
3640 async fn test_append_message_to_empty_editor(cx: &mut TestAppContext) {
3641 init_test(cx);
3642 let (message_editor, cx) = setup_message_editor(cx).await;
3643
3644 message_editor.update_in(cx, |editor, window, cx| {
3645 editor.append_message(
3646 vec![acp::ContentBlock::Text(acp::TextContent::new(
3647 "appended".to_string(),
3648 ))],
3649 Some("\n\n"),
3650 window,
3651 cx,
3652 );
3653 });
3654
3655 let text = message_editor.update(cx, |editor, cx| editor.text(cx));
3656 assert_eq!(
3657 text, "appended",
3658 "No separator should be inserted when the editor is empty"
3659 );
3660 }
3661
3662 #[gpui::test]
3663 async fn test_append_message_to_non_empty_editor(cx: &mut TestAppContext) {
3664 init_test(cx);
3665 let (message_editor, cx) = setup_message_editor(cx).await;
3666
3667 // Seed initial content.
3668 message_editor.update_in(cx, |editor, window, cx| {
3669 editor.set_message(
3670 vec![acp::ContentBlock::Text(acp::TextContent::new(
3671 "initial".to_string(),
3672 ))],
3673 window,
3674 cx,
3675 );
3676 });
3677
3678 // Append with separator.
3679 message_editor.update_in(cx, |editor, window, cx| {
3680 editor.append_message(
3681 vec![acp::ContentBlock::Text(acp::TextContent::new(
3682 "appended".to_string(),
3683 ))],
3684 Some("\n\n"),
3685 window,
3686 cx,
3687 );
3688 });
3689
3690 let text = message_editor.update(cx, |editor, cx| editor.text(cx));
3691 assert_eq!(
3692 text, "initial\n\nappended",
3693 "Separator should appear between existing and appended content"
3694 );
3695 }
3696
3697 #[gpui::test]
3698 async fn test_append_message_preserves_mention_offset(cx: &mut TestAppContext) {
3699 init_test(cx);
3700
3701 let fs = FakeFs::new(cx.executor());
3702 fs.insert_tree("/project", json!({"file.txt": "content"}))
3703 .await;
3704 let project = Project::test(fs, [Path::new(path!("/project"))], cx).await;
3705
3706 let (multi_workspace, cx) =
3707 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
3708 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
3709 let history = cx.update(|_window, cx| cx.new(|cx| crate::ThreadHistory::new(None, cx)));
3710
3711 let message_editor = cx.update(|window, cx| {
3712 cx.new(|cx| {
3713 MessageEditor::new(
3714 workspace.downgrade(),
3715 project.downgrade(),
3716 None,
3717 history.downgrade(),
3718 None,
3719 Default::default(),
3720 Default::default(),
3721 "Test Agent".into(),
3722 "Test",
3723 EditorMode::AutoHeight {
3724 min_lines: 1,
3725 max_lines: None,
3726 },
3727 window,
3728 cx,
3729 )
3730 })
3731 });
3732
3733 cx.run_until_parked();
3734
3735 // Seed plain-text prefix so the editor is non-empty before appending.
3736 message_editor.update_in(cx, |editor, window, cx| {
3737 editor.set_message(
3738 vec![acp::ContentBlock::Text(acp::TextContent::new(
3739 "prefix text".to_string(),
3740 ))],
3741 window,
3742 cx,
3743 );
3744 });
3745
3746 // Append a message that contains a ResourceLink mention.
3747 message_editor.update_in(cx, |editor, window, cx| {
3748 editor.append_message(
3749 vec![acp::ContentBlock::ResourceLink(acp::ResourceLink::new(
3750 "file.txt",
3751 "file:///project/file.txt",
3752 ))],
3753 Some("\n\n"),
3754 window,
3755 cx,
3756 );
3757 });
3758
3759 cx.run_until_parked();
3760
3761 // The mention should be registered in the mention_set so that contents()
3762 // will emit it as a structured block rather than plain text.
3763 let mention_uris =
3764 message_editor.update(cx, |editor, cx| editor.mention_set.read(cx).mentions());
3765 assert_eq!(
3766 mention_uris.len(),
3767 1,
3768 "Expected exactly one mention in the mention_set after append, got: {mention_uris:?}"
3769 );
3770
3771 // The editor text should start with the prefix, then the separator, then
3772 // the mention placeholder — confirming the offset was computed correctly.
3773 let text = message_editor.update(cx, |editor, cx| editor.text(cx));
3774 assert!(
3775 text.starts_with("prefix text\n\n"),
3776 "Expected text to start with 'prefix text\\n\\n', got: {text:?}"
3777 );
3778 }
3779}