1use crate::{
2 agent_panel::AgentType,
3 language_model_selector::{LanguageModelSelector, language_model_selector},
4 ui::ModelSelectorTooltip,
5};
6use anyhow::Result;
7use assistant_slash_command::{SlashCommand, SlashCommandOutputSection, SlashCommandWorkingSet};
8use assistant_slash_commands::{DefaultSlashCommand, FileSlashCommand, selections_creases};
9use client::{proto, zed_urls};
10use collections::{BTreeSet, HashMap, HashSet, hash_map};
11use editor::{
12 Anchor, Editor, EditorEvent, MenuEditPredictionsPolicy, MultiBuffer, MultiBufferOffset,
13 MultiBufferSnapshot, RowExt, ToOffset as _, ToPoint as _,
14 actions::{MoveToEndOfLine, Newline, SendReviewToAgent, ShowCompletions},
15 display_map::{
16 BlockPlacement, BlockProperties, BlockStyle, Crease, CreaseMetadata, CustomBlockId, FoldId,
17 RenderBlock, ToDisplayPoint,
18 },
19 scroll::ScrollOffset,
20};
21use editor::{FoldPlaceholder, display_map::CreaseId};
22use fs::Fs;
23use futures::FutureExt;
24use gpui::{
25 Action, Animation, AnimationExt, AnyElement, App, ClipboardEntry, ClipboardItem, Empty, Entity,
26 EventEmitter, FocusHandle, Focusable, FontWeight, Global, InteractiveElement, IntoElement,
27 ParentElement, Pixels, Render, RenderImage, SharedString, Size, StatefulInteractiveElement,
28 Styled, Subscription, Task, WeakEntity, actions, div, img, point, prelude::*,
29 pulsating_between, size,
30};
31use language::{
32 BufferSnapshot, LspAdapterDelegate, ToOffset,
33 language_settings::{SoftWrap, all_language_settings},
34};
35use language_model::{
36 ConfigurationError, IconOrSvg, LanguageModelImage, LanguageModelRegistry, Role,
37};
38use multi_buffer::MultiBufferRow;
39use picker::{Picker, popover_menu::PickerPopoverMenu};
40use project::{Project, Worktree};
41use project::{ProjectPath, lsp_store::LocalLspAdapterDelegate};
42use rope::Point;
43use serde::{Deserialize, Serialize};
44use settings::{
45 LanguageModelProviderSetting, LanguageModelSelection, Settings, SettingsStore,
46 update_settings_file,
47};
48use std::{
49 any::{Any, TypeId},
50 cmp,
51 ops::Range,
52 path::{Path, PathBuf},
53 rc::Rc,
54 sync::Arc,
55 time::Duration,
56};
57use text::SelectionGoal;
58use ui::{
59 ButtonLike, CommonAnimationExt, Disclosure, ElevationIndex, KeyBinding, PopoverMenuHandle,
60 TintColor, Tooltip, prelude::*,
61};
62use util::{ResultExt, maybe};
63use workspace::{
64 CollaboratorId,
65 searchable::{Direction, SearchableItemHandle},
66};
67
68use workspace::{
69 Save, Toast, Workspace,
70 item::{self, FollowableItem, Item},
71 notifications::NotificationId,
72 pane,
73 searchable::{SearchEvent, SearchableItem},
74};
75use zed_actions::agent::{AddSelectionToThread, PasteRaw, ToggleModelSelector};
76
77use crate::CycleFavoriteModels;
78
79use crate::{slash_command::SlashCommandCompletionProvider, slash_command_picker};
80use assistant_text_thread::{
81 CacheStatus, Content, InvokedSlashCommandId, InvokedSlashCommandStatus, Message, MessageId,
82 MessageMetadata, MessageStatus, PendingSlashCommandStatus, TextThread, TextThreadEvent,
83 TextThreadId, ThoughtProcessOutputSection,
84};
85
86actions!(
87 assistant,
88 [
89 /// Sends the current message to the assistant.
90 Assist,
91 /// Confirms and executes the entered slash command.
92 ConfirmCommand,
93 /// Copies code from the assistant's response to the clipboard.
94 CopyCode,
95 /// Cycles between user and assistant message roles.
96 CycleMessageRole,
97 /// Inserts the selected text into the active editor.
98 InsertIntoEditor,
99 /// Splits the conversation at the current cursor position.
100 Split,
101 ]
102);
103
104/// Inserts files that were dragged and dropped into the assistant conversation.
105#[derive(PartialEq, Clone, Action)]
106#[action(namespace = assistant, no_json, no_register)]
107pub enum InsertDraggedFiles {
108 ProjectPaths(Vec<ProjectPath>),
109 ExternalFiles(Vec<PathBuf>),
110}
111
112#[derive(Copy, Clone, Debug, PartialEq)]
113struct ScrollPosition {
114 offset_before_cursor: gpui::Point<ScrollOffset>,
115 cursor: Anchor,
116}
117
118type MessageHeader = MessageMetadata;
119
120#[derive(Clone)]
121enum AssistError {
122 PaymentRequired,
123 Message(SharedString),
124}
125
126pub enum ThoughtProcessStatus {
127 Pending,
128 Completed,
129}
130
131pub trait AgentPanelDelegate {
132 fn active_text_thread_editor(
133 &self,
134 workspace: &mut Workspace,
135 window: &mut Window,
136 cx: &mut Context<Workspace>,
137 ) -> Option<Entity<TextThreadEditor>>;
138
139 fn open_local_text_thread(
140 &self,
141 workspace: &mut Workspace,
142 path: Arc<Path>,
143 window: &mut Window,
144 cx: &mut Context<Workspace>,
145 ) -> Task<Result<()>>;
146
147 fn open_remote_text_thread(
148 &self,
149 workspace: &mut Workspace,
150 text_thread_id: TextThreadId,
151 window: &mut Window,
152 cx: &mut Context<Workspace>,
153 ) -> Task<Result<Entity<TextThreadEditor>>>;
154
155 fn quote_selection(
156 &self,
157 workspace: &mut Workspace,
158 selection_ranges: Vec<Range<Anchor>>,
159 buffer: Entity<MultiBuffer>,
160 window: &mut Window,
161 cx: &mut Context<Workspace>,
162 );
163
164 fn quote_terminal_text(
165 &self,
166 workspace: &mut Workspace,
167 text: String,
168 window: &mut Window,
169 cx: &mut Context<Workspace>,
170 );
171}
172
173impl dyn AgentPanelDelegate {
174 /// Returns the global [`AssistantPanelDelegate`], if it exists.
175 pub fn try_global(cx: &App) -> Option<Arc<Self>> {
176 cx.try_global::<GlobalAssistantPanelDelegate>()
177 .map(|global| global.0.clone())
178 }
179
180 /// Sets the global [`AssistantPanelDelegate`].
181 pub fn set_global(delegate: Arc<Self>, cx: &mut App) {
182 cx.set_global(GlobalAssistantPanelDelegate(delegate));
183 }
184}
185
186struct GlobalAssistantPanelDelegate(Arc<dyn AgentPanelDelegate>);
187
188impl Global for GlobalAssistantPanelDelegate {}
189
190pub struct TextThreadEditor {
191 text_thread: Entity<TextThread>,
192 fs: Arc<dyn Fs>,
193 slash_commands: Arc<SlashCommandWorkingSet>,
194 workspace: WeakEntity<Workspace>,
195 project: Entity<Project>,
196 lsp_adapter_delegate: Option<Arc<dyn LspAdapterDelegate>>,
197 editor: Entity<Editor>,
198 pending_thought_process: Option<(CreaseId, language::Anchor)>,
199 blocks: HashMap<MessageId, (MessageHeader, CustomBlockId)>,
200 image_blocks: HashSet<CustomBlockId>,
201 scroll_position: Option<ScrollPosition>,
202 remote_id: Option<workspace::ViewId>,
203 pending_slash_command_creases: HashMap<Range<language::Anchor>, CreaseId>,
204 invoked_slash_command_creases: HashMap<InvokedSlashCommandId, CreaseId>,
205 _subscriptions: Vec<Subscription>,
206 last_error: Option<AssistError>,
207 pub(crate) slash_menu_handle:
208 PopoverMenuHandle<Picker<slash_command_picker::SlashCommandDelegate>>,
209 // dragged_file_worktrees is used to keep references to worktrees that were added
210 // when the user drag/dropped an external file onto the context editor. Since
211 // the worktree is not part of the project panel, it would be dropped as soon as
212 // the file is opened. In order to keep the worktree alive for the duration of the
213 // context editor, we keep a reference here.
214 dragged_file_worktrees: Vec<Entity<Worktree>>,
215 language_model_selector: Entity<LanguageModelSelector>,
216 language_model_selector_menu_handle: PopoverMenuHandle<LanguageModelSelector>,
217}
218
219const MAX_TAB_TITLE_LEN: usize = 16;
220
221impl TextThreadEditor {
222 pub fn init(cx: &mut App) {
223 workspace::FollowableViewRegistry::register::<TextThreadEditor>(cx);
224
225 cx.observe_new(
226 |workspace: &mut Workspace, _window, _cx: &mut Context<Workspace>| {
227 workspace
228 .register_action(TextThreadEditor::quote_selection)
229 .register_action(TextThreadEditor::insert_selection)
230 .register_action(TextThreadEditor::copy_code)
231 .register_action(TextThreadEditor::handle_insert_dragged_files)
232 .register_action(TextThreadEditor::handle_send_review_to_agent);
233 },
234 )
235 .detach();
236 }
237
238 pub fn for_text_thread(
239 text_thread: Entity<TextThread>,
240 fs: Arc<dyn Fs>,
241 workspace: WeakEntity<Workspace>,
242 project: Entity<Project>,
243 lsp_adapter_delegate: Option<Arc<dyn LspAdapterDelegate>>,
244 window: &mut Window,
245 cx: &mut Context<Self>,
246 ) -> Self {
247 let completion_provider = SlashCommandCompletionProvider::new(
248 text_thread.read(cx).slash_commands().clone(),
249 Some(cx.entity().downgrade()),
250 Some(workspace.clone()),
251 );
252
253 let editor = cx.new(|cx| {
254 let mut editor =
255 Editor::for_buffer(text_thread.read(cx).buffer().clone(), None, window, cx);
256 editor.disable_scrollbars_and_minimap(window, cx);
257 editor.set_soft_wrap_mode(SoftWrap::EditorWidth, cx);
258 editor.set_show_line_numbers(false, cx);
259 editor.set_show_git_diff_gutter(false, cx);
260 editor.set_show_code_actions(false, cx);
261 editor.set_show_runnables(false, cx);
262 editor.set_show_breakpoints(false, cx);
263 editor.set_show_wrap_guides(false, cx);
264 editor.set_show_indent_guides(false, cx);
265 editor.set_completion_provider(Some(Rc::new(completion_provider)));
266 editor.set_menu_edit_predictions_policy(MenuEditPredictionsPolicy::Never);
267 editor.set_collaboration_hub(Box::new(project.clone()));
268
269 let show_edit_predictions = all_language_settings(None, cx)
270 .edit_predictions
271 .enabled_in_text_threads;
272
273 editor.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
274
275 editor
276 });
277
278 let _subscriptions = vec![
279 cx.observe(&text_thread, |_, _, cx| cx.notify()),
280 cx.subscribe_in(&text_thread, window, Self::handle_text_thread_event),
281 cx.subscribe_in(&editor, window, Self::handle_editor_event),
282 cx.subscribe_in(&editor, window, Self::handle_editor_search_event),
283 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
284 ];
285
286 let slash_command_sections = text_thread
287 .read(cx)
288 .slash_command_output_sections()
289 .to_vec();
290 let thought_process_sections = text_thread
291 .read(cx)
292 .thought_process_output_sections()
293 .to_vec();
294 let slash_commands = text_thread.read(cx).slash_commands().clone();
295 let focus_handle = editor.read(cx).focus_handle(cx);
296
297 let mut this = Self {
298 text_thread,
299 slash_commands,
300 editor,
301 lsp_adapter_delegate,
302 blocks: Default::default(),
303 image_blocks: Default::default(),
304 scroll_position: None,
305 remote_id: None,
306 pending_thought_process: None,
307 fs: fs.clone(),
308 workspace,
309 project,
310 pending_slash_command_creases: HashMap::default(),
311 invoked_slash_command_creases: HashMap::default(),
312 _subscriptions,
313 last_error: None,
314 slash_menu_handle: Default::default(),
315 dragged_file_worktrees: Vec::new(),
316 language_model_selector: cx.new(|cx| {
317 language_model_selector(
318 |cx| LanguageModelRegistry::read_global(cx).default_model(),
319 {
320 let fs = fs.clone();
321 move |model, cx| {
322 update_settings_file(fs.clone(), cx, move |settings, _| {
323 let provider = model.provider_id().0.to_string();
324 let model = model.id().0.to_string();
325 settings.agent.get_or_insert_default().set_model(
326 LanguageModelSelection {
327 provider: LanguageModelProviderSetting(provider),
328 model,
329 },
330 )
331 });
332 }
333 },
334 {
335 let fs = fs.clone();
336 move |model, should_be_favorite, cx| {
337 crate::favorite_models::toggle_in_settings(
338 model,
339 should_be_favorite,
340 fs.clone(),
341 cx,
342 );
343 }
344 },
345 true, // Use popover styles for picker
346 focus_handle,
347 window,
348 cx,
349 )
350 }),
351 language_model_selector_menu_handle: PopoverMenuHandle::default(),
352 };
353 this.update_message_headers(cx);
354 this.update_image_blocks(cx);
355 this.insert_slash_command_output_sections(slash_command_sections, false, window, cx);
356 this.insert_thought_process_output_sections(
357 thought_process_sections
358 .into_iter()
359 .map(|section| (section, ThoughtProcessStatus::Completed)),
360 window,
361 cx,
362 );
363 this
364 }
365
366 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
367 self.editor.update(cx, |editor, cx| {
368 let show_edit_predictions = all_language_settings(None, cx)
369 .edit_predictions
370 .enabled_in_text_threads;
371
372 editor.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
373 });
374 }
375
376 pub fn text_thread(&self) -> &Entity<TextThread> {
377 &self.text_thread
378 }
379
380 pub fn editor(&self) -> &Entity<Editor> {
381 &self.editor
382 }
383
384 pub fn insert_default_prompt(&mut self, window: &mut Window, cx: &mut Context<Self>) {
385 let command_name = DefaultSlashCommand.name();
386 self.editor.update(cx, |editor, cx| {
387 editor.insert(&format!("/{command_name}\n\n"), window, cx)
388 });
389 let command = self.text_thread.update(cx, |text_thread, cx| {
390 text_thread.reparse(cx);
391 text_thread.parsed_slash_commands()[0].clone()
392 });
393 self.run_command(
394 command.source_range,
395 &command.name,
396 &command.arguments,
397 false,
398 self.workspace.clone(),
399 window,
400 cx,
401 );
402 }
403
404 fn assist(&mut self, _: &Assist, window: &mut Window, cx: &mut Context<Self>) {
405 if self.sending_disabled(cx) {
406 return;
407 }
408 telemetry::event!("Agent Message Sent", agent = "zed-text");
409 self.send_to_model(window, cx);
410 }
411
412 fn send_to_model(&mut self, window: &mut Window, cx: &mut Context<Self>) {
413 self.last_error = None;
414 if let Some(user_message) = self
415 .text_thread
416 .update(cx, |text_thread, cx| text_thread.assist(cx))
417 {
418 let new_selection = {
419 let cursor = user_message
420 .start
421 .to_offset(self.text_thread.read(cx).buffer().read(cx));
422 MultiBufferOffset(cursor)..MultiBufferOffset(cursor)
423 };
424 self.editor.update(cx, |editor, cx| {
425 editor.change_selections(Default::default(), window, cx, |selections| {
426 selections.select_ranges([new_selection])
427 });
428 });
429 // Avoid scrolling to the new cursor position so the assistant's output is stable.
430 cx.defer_in(window, |this, _, _| this.scroll_position = None);
431 }
432
433 cx.notify();
434 }
435
436 fn cancel(
437 &mut self,
438 _: &editor::actions::Cancel,
439 _window: &mut Window,
440 cx: &mut Context<Self>,
441 ) {
442 self.last_error = None;
443
444 if self
445 .text_thread
446 .update(cx, |text_thread, cx| text_thread.cancel_last_assist(cx))
447 {
448 return;
449 }
450
451 cx.propagate();
452 }
453
454 fn cycle_message_role(
455 &mut self,
456 _: &CycleMessageRole,
457 _window: &mut Window,
458 cx: &mut Context<Self>,
459 ) {
460 let cursors = self.cursors(cx);
461 self.text_thread.update(cx, |text_thread, cx| {
462 let messages = text_thread
463 .messages_for_offsets(cursors.into_iter().map(|cursor| cursor.0), cx)
464 .into_iter()
465 .map(|message| message.id)
466 .collect();
467 text_thread.cycle_message_roles(messages, cx)
468 });
469 }
470
471 fn cursors(&self, cx: &mut App) -> Vec<MultiBufferOffset> {
472 let selections = self.editor.update(cx, |editor, cx| {
473 editor
474 .selections
475 .all::<MultiBufferOffset>(&editor.display_snapshot(cx))
476 });
477 selections
478 .into_iter()
479 .map(|selection| selection.head())
480 .collect()
481 }
482
483 pub fn insert_command(&mut self, name: &str, window: &mut Window, cx: &mut Context<Self>) {
484 if let Some(command) = self.slash_commands.command(name, cx) {
485 self.editor.update(cx, |editor, cx| {
486 editor.transact(window, cx, |editor, window, cx| {
487 editor.change_selections(Default::default(), window, cx, |s| s.try_cancel());
488 let snapshot = editor.buffer().read(cx).snapshot(cx);
489 let newest_cursor = editor
490 .selections
491 .newest::<Point>(&editor.display_snapshot(cx))
492 .head();
493 if newest_cursor.column > 0
494 || snapshot
495 .chars_at(newest_cursor)
496 .next()
497 .is_some_and(|ch| ch != '\n')
498 {
499 editor.move_to_end_of_line(
500 &MoveToEndOfLine {
501 stop_at_soft_wraps: false,
502 },
503 window,
504 cx,
505 );
506 editor.newline(&Newline, window, cx);
507 }
508
509 editor.insert(&format!("/{name}"), window, cx);
510 if command.accepts_arguments() {
511 editor.insert(" ", window, cx);
512 editor.show_completions(&ShowCompletions, window, cx);
513 }
514 });
515 });
516 if !command.requires_argument() {
517 self.confirm_command(&ConfirmCommand, window, cx);
518 }
519 }
520 }
521
522 pub fn confirm_command(
523 &mut self,
524 _: &ConfirmCommand,
525 window: &mut Window,
526 cx: &mut Context<Self>,
527 ) {
528 if self.editor.read(cx).has_visible_completions_menu() {
529 return;
530 }
531
532 let selections = self.editor.read(cx).selections.disjoint_anchors_arc();
533 let mut commands_by_range = HashMap::default();
534 let workspace = self.workspace.clone();
535 self.text_thread.update(cx, |text_thread, cx| {
536 text_thread.reparse(cx);
537 for selection in selections.iter() {
538 if let Some(command) =
539 text_thread.pending_command_for_position(selection.head().text_anchor, cx)
540 {
541 commands_by_range
542 .entry(command.source_range.clone())
543 .or_insert_with(|| command.clone());
544 }
545 }
546 });
547
548 if commands_by_range.is_empty() {
549 cx.propagate();
550 } else {
551 for command in commands_by_range.into_values() {
552 self.run_command(
553 command.source_range,
554 &command.name,
555 &command.arguments,
556 true,
557 workspace.clone(),
558 window,
559 cx,
560 );
561 }
562 cx.stop_propagation();
563 }
564 }
565
566 pub fn run_command(
567 &mut self,
568 command_range: Range<language::Anchor>,
569 name: &str,
570 arguments: &[String],
571 ensure_trailing_newline: bool,
572 workspace: WeakEntity<Workspace>,
573 window: &mut Window,
574 cx: &mut Context<Self>,
575 ) {
576 if let Some(command) = self.slash_commands.command(name, cx) {
577 let text_thread = self.text_thread.read(cx);
578 let sections = text_thread
579 .slash_command_output_sections()
580 .iter()
581 .filter(|section| section.is_valid(text_thread.buffer().read(cx)))
582 .cloned()
583 .collect::<Vec<_>>();
584 let snapshot = text_thread.buffer().read(cx).snapshot();
585 let output = command.run(
586 arguments,
587 §ions,
588 snapshot,
589 workspace,
590 self.lsp_adapter_delegate.clone(),
591 window,
592 cx,
593 );
594 self.text_thread.update(cx, |text_thread, cx| {
595 text_thread.insert_command_output(
596 command_range,
597 name,
598 output,
599 ensure_trailing_newline,
600 cx,
601 )
602 });
603 }
604 }
605
606 fn handle_text_thread_event(
607 &mut self,
608 _: &Entity<TextThread>,
609 event: &TextThreadEvent,
610 window: &mut Window,
611 cx: &mut Context<Self>,
612 ) {
613 let text_thread_editor = cx.entity().downgrade();
614
615 match event {
616 TextThreadEvent::MessagesEdited => {
617 self.update_message_headers(cx);
618 self.update_image_blocks(cx);
619 self.text_thread.update(cx, |text_thread, cx| {
620 text_thread.save(Some(Duration::from_millis(500)), self.fs.clone(), cx);
621 });
622 }
623 TextThreadEvent::SummaryChanged => {
624 cx.emit(EditorEvent::TitleChanged);
625 self.text_thread.update(cx, |text_thread, cx| {
626 text_thread.save(Some(Duration::from_millis(500)), self.fs.clone(), cx);
627 });
628 }
629 TextThreadEvent::SummaryGenerated => {}
630 TextThreadEvent::PathChanged { .. } => {}
631 TextThreadEvent::StartedThoughtProcess(range) => {
632 let creases = self.insert_thought_process_output_sections(
633 [(
634 ThoughtProcessOutputSection {
635 range: range.clone(),
636 },
637 ThoughtProcessStatus::Pending,
638 )],
639 window,
640 cx,
641 );
642 self.pending_thought_process = Some((creases[0], range.start));
643 }
644 TextThreadEvent::EndedThoughtProcess(end) => {
645 if let Some((crease_id, start)) = self.pending_thought_process.take() {
646 self.editor.update(cx, |editor, cx| {
647 let multi_buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
648 let start_anchor =
649 multi_buffer_snapshot.as_singleton_anchor(start).unwrap();
650
651 editor.display_map.update(cx, |display_map, cx| {
652 display_map.unfold_intersecting(
653 vec![start_anchor..start_anchor],
654 true,
655 cx,
656 );
657 });
658 editor.remove_creases(vec![crease_id], cx);
659 });
660 self.insert_thought_process_output_sections(
661 [(
662 ThoughtProcessOutputSection { range: start..*end },
663 ThoughtProcessStatus::Completed,
664 )],
665 window,
666 cx,
667 );
668 }
669 }
670 TextThreadEvent::StreamedCompletion => {
671 self.editor.update(cx, |editor, cx| {
672 if let Some(scroll_position) = self.scroll_position {
673 let snapshot = editor.snapshot(window, cx);
674 let cursor_point = scroll_position.cursor.to_display_point(&snapshot);
675 let scroll_top =
676 cursor_point.row().as_f64() - scroll_position.offset_before_cursor.y;
677 editor.set_scroll_position(
678 point(scroll_position.offset_before_cursor.x, scroll_top),
679 window,
680 cx,
681 );
682 }
683 });
684 }
685 TextThreadEvent::ParsedSlashCommandsUpdated { removed, updated } => {
686 self.editor.update(cx, |editor, cx| {
687 let buffer = editor.buffer().read(cx).snapshot(cx);
688 let (&excerpt_id, _, _) = buffer.as_singleton().unwrap();
689
690 editor.remove_creases(
691 removed
692 .iter()
693 .filter_map(|range| self.pending_slash_command_creases.remove(range)),
694 cx,
695 );
696
697 let crease_ids = editor.insert_creases(
698 updated.iter().map(|command| {
699 let workspace = self.workspace.clone();
700 let confirm_command = Arc::new({
701 let text_thread_editor = text_thread_editor.clone();
702 let command = command.clone();
703 move |window: &mut Window, cx: &mut App| {
704 text_thread_editor
705 .update(cx, |text_thread_editor, cx| {
706 text_thread_editor.run_command(
707 command.source_range.clone(),
708 &command.name,
709 &command.arguments,
710 false,
711 workspace.clone(),
712 window,
713 cx,
714 );
715 })
716 .ok();
717 }
718 });
719 let placeholder = FoldPlaceholder {
720 render: Arc::new(move |_, _, _| Empty.into_any()),
721 ..Default::default()
722 };
723 let render_toggle = {
724 let confirm_command = confirm_command.clone();
725 let command = command.clone();
726 move |row, _, _, _window: &mut Window, _cx: &mut App| {
727 render_pending_slash_command_gutter_decoration(
728 row,
729 &command.status,
730 confirm_command.clone(),
731 )
732 }
733 };
734 let render_trailer = {
735 move |_row, _unfold, _window: &mut Window, _cx: &mut App| {
736 Empty.into_any()
737 }
738 };
739
740 let range = buffer
741 .anchor_range_in_excerpt(excerpt_id, command.source_range.clone())
742 .unwrap();
743 Crease::inline(range, placeholder, render_toggle, render_trailer)
744 }),
745 cx,
746 );
747
748 self.pending_slash_command_creases.extend(
749 updated
750 .iter()
751 .map(|command| command.source_range.clone())
752 .zip(crease_ids),
753 );
754 })
755 }
756 TextThreadEvent::InvokedSlashCommandChanged { command_id } => {
757 self.update_invoked_slash_command(*command_id, window, cx);
758 }
759 TextThreadEvent::SlashCommandOutputSectionAdded { section } => {
760 self.insert_slash_command_output_sections([section.clone()], false, window, cx);
761 }
762 TextThreadEvent::Operation(_) => {}
763 TextThreadEvent::ShowAssistError(error_message) => {
764 self.last_error = Some(AssistError::Message(error_message.clone()));
765 }
766 TextThreadEvent::ShowPaymentRequiredError => {
767 self.last_error = Some(AssistError::PaymentRequired);
768 }
769 }
770 }
771
772 fn update_invoked_slash_command(
773 &mut self,
774 command_id: InvokedSlashCommandId,
775 window: &mut Window,
776 cx: &mut Context<Self>,
777 ) {
778 if let Some(invoked_slash_command) =
779 self.text_thread.read(cx).invoked_slash_command(&command_id)
780 && let InvokedSlashCommandStatus::Finished = invoked_slash_command.status
781 {
782 let run_commands_in_ranges = invoked_slash_command.run_commands_in_ranges.clone();
783 for range in run_commands_in_ranges {
784 let commands = self.text_thread.update(cx, |text_thread, cx| {
785 text_thread.reparse(cx);
786 text_thread
787 .pending_commands_for_range(range.clone(), cx)
788 .to_vec()
789 });
790
791 for command in commands {
792 self.run_command(
793 command.source_range,
794 &command.name,
795 &command.arguments,
796 false,
797 self.workspace.clone(),
798 window,
799 cx,
800 );
801 }
802 }
803 }
804
805 self.editor.update(cx, |editor, cx| {
806 if let Some(invoked_slash_command) =
807 self.text_thread.read(cx).invoked_slash_command(&command_id)
808 {
809 if let InvokedSlashCommandStatus::Finished = invoked_slash_command.status {
810 let buffer = editor.buffer().read(cx).snapshot(cx);
811 let (&excerpt_id, _buffer_id, _buffer_snapshot) =
812 buffer.as_singleton().unwrap();
813
814 let range = buffer
815 .anchor_range_in_excerpt(excerpt_id, invoked_slash_command.range.clone())
816 .unwrap();
817 editor.remove_folds_with_type(
818 &[range],
819 TypeId::of::<PendingSlashCommand>(),
820 false,
821 cx,
822 );
823
824 editor.remove_creases(
825 HashSet::from_iter(self.invoked_slash_command_creases.remove(&command_id)),
826 cx,
827 );
828 } else if let hash_map::Entry::Vacant(entry) =
829 self.invoked_slash_command_creases.entry(command_id)
830 {
831 let buffer = editor.buffer().read(cx).snapshot(cx);
832 let (&excerpt_id, _buffer_id, _buffer_snapshot) =
833 buffer.as_singleton().unwrap();
834 let context = self.text_thread.downgrade();
835 let range = buffer
836 .anchor_range_in_excerpt(excerpt_id, invoked_slash_command.range.clone())
837 .unwrap();
838 let crease = Crease::inline(
839 range,
840 invoked_slash_command_fold_placeholder(command_id, context),
841 fold_toggle("invoked-slash-command"),
842 |_row, _folded, _window, _cx| Empty.into_any(),
843 );
844 let crease_ids = editor.insert_creases([crease.clone()], cx);
845 editor.fold_creases(vec![crease], false, window, cx);
846 entry.insert(crease_ids[0]);
847 } else {
848 cx.notify()
849 }
850 } else {
851 editor.remove_creases(
852 HashSet::from_iter(self.invoked_slash_command_creases.remove(&command_id)),
853 cx,
854 );
855 cx.notify();
856 };
857 });
858 }
859
860 fn insert_thought_process_output_sections(
861 &mut self,
862 sections: impl IntoIterator<
863 Item = (
864 ThoughtProcessOutputSection<language::Anchor>,
865 ThoughtProcessStatus,
866 ),
867 >,
868 window: &mut Window,
869 cx: &mut Context<Self>,
870 ) -> Vec<CreaseId> {
871 self.editor.update(cx, |editor, cx| {
872 let buffer = editor.buffer().read(cx).snapshot(cx);
873 let excerpt_id = *buffer.as_singleton().unwrap().0;
874 let mut buffer_rows_to_fold = BTreeSet::new();
875 let mut creases = Vec::new();
876 for (section, status) in sections {
877 let range = buffer
878 .anchor_range_in_excerpt(excerpt_id, section.range)
879 .unwrap();
880 let buffer_row = MultiBufferRow(range.start.to_point(&buffer).row);
881 buffer_rows_to_fold.insert(buffer_row);
882 creases.push(
883 Crease::inline(
884 range,
885 FoldPlaceholder {
886 render: render_thought_process_fold_icon_button(
887 cx.entity().downgrade(),
888 status,
889 ),
890 merge_adjacent: false,
891 ..Default::default()
892 },
893 render_slash_command_output_toggle,
894 |_, _, _, _| Empty.into_any_element(),
895 )
896 .with_metadata(CreaseMetadata {
897 icon_path: SharedString::from(IconName::Ai.path()),
898 label: "Thinking Process".into(),
899 }),
900 );
901 }
902
903 let creases = editor.insert_creases(creases, cx);
904
905 for buffer_row in buffer_rows_to_fold.into_iter().rev() {
906 editor.fold_at(buffer_row, window, cx);
907 }
908
909 creases
910 })
911 }
912
913 fn insert_slash_command_output_sections(
914 &mut self,
915 sections: impl IntoIterator<Item = SlashCommandOutputSection<language::Anchor>>,
916 expand_result: bool,
917 window: &mut Window,
918 cx: &mut Context<Self>,
919 ) {
920 self.editor.update(cx, |editor, cx| {
921 let buffer = editor.buffer().read(cx).snapshot(cx);
922 let excerpt_id = *buffer.as_singleton().unwrap().0;
923 let mut buffer_rows_to_fold = BTreeSet::new();
924 let mut creases = Vec::new();
925 for section in sections {
926 let range = buffer
927 .anchor_range_in_excerpt(excerpt_id, section.range)
928 .unwrap();
929 let buffer_row = MultiBufferRow(range.start.to_point(&buffer).row);
930 buffer_rows_to_fold.insert(buffer_row);
931 creases.push(
932 Crease::inline(
933 range,
934 FoldPlaceholder {
935 render: render_fold_icon_button(
936 cx.entity().downgrade(),
937 section.icon.path().into(),
938 section.label.clone(),
939 ),
940 merge_adjacent: false,
941 ..Default::default()
942 },
943 render_slash_command_output_toggle,
944 |_, _, _, _| Empty.into_any_element(),
945 )
946 .with_metadata(CreaseMetadata {
947 icon_path: section.icon.path().into(),
948 label: section.label,
949 }),
950 );
951 }
952
953 editor.insert_creases(creases, cx);
954
955 if expand_result {
956 buffer_rows_to_fold.clear();
957 }
958 for buffer_row in buffer_rows_to_fold.into_iter().rev() {
959 editor.fold_at(buffer_row, window, cx);
960 }
961 });
962 }
963
964 fn handle_editor_event(
965 &mut self,
966 _: &Entity<Editor>,
967 event: &EditorEvent,
968 window: &mut Window,
969 cx: &mut Context<Self>,
970 ) {
971 match event {
972 EditorEvent::ScrollPositionChanged { autoscroll, .. } => {
973 let cursor_scroll_position = self.cursor_scroll_position(window, cx);
974 if *autoscroll {
975 self.scroll_position = cursor_scroll_position;
976 } else if self.scroll_position != cursor_scroll_position {
977 self.scroll_position = None;
978 }
979 }
980 EditorEvent::SelectionsChanged { .. } => {
981 self.scroll_position = self.cursor_scroll_position(window, cx);
982 }
983 _ => {}
984 }
985 cx.emit(event.clone());
986 }
987
988 fn handle_editor_search_event(
989 &mut self,
990 _: &Entity<Editor>,
991 event: &SearchEvent,
992 _window: &mut Window,
993 cx: &mut Context<Self>,
994 ) {
995 cx.emit(event.clone());
996 }
997
998 fn cursor_scroll_position(
999 &self,
1000 window: &mut Window,
1001 cx: &mut Context<Self>,
1002 ) -> Option<ScrollPosition> {
1003 self.editor.update(cx, |editor, cx| {
1004 let snapshot = editor.snapshot(window, cx);
1005 let cursor = editor.selections.newest_anchor().head();
1006 let cursor_row = cursor
1007 .to_display_point(&snapshot.display_snapshot)
1008 .row()
1009 .as_f64();
1010 let scroll_position = editor
1011 .scroll_manager
1012 .scroll_position(&snapshot.display_snapshot, cx);
1013
1014 let scroll_bottom = scroll_position.y + editor.visible_line_count().unwrap_or(0.);
1015 if (scroll_position.y..scroll_bottom).contains(&cursor_row) {
1016 Some(ScrollPosition {
1017 cursor,
1018 offset_before_cursor: point(scroll_position.x, cursor_row - scroll_position.y),
1019 })
1020 } else {
1021 None
1022 }
1023 })
1024 }
1025
1026 fn esc_kbd(cx: &App) -> Div {
1027 let colors = cx.theme().colors().clone();
1028
1029 h_flex()
1030 .items_center()
1031 .gap_1()
1032 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
1033 .text_size(TextSize::XSmall.rems(cx))
1034 .text_color(colors.text_muted)
1035 .child("Press")
1036 .child(
1037 h_flex()
1038 .rounded_sm()
1039 .px_1()
1040 .mr_0p5()
1041 .border_1()
1042 .border_color(colors.border_variant.alpha(0.6))
1043 .bg(colors.element_background.alpha(0.6))
1044 .child("esc"),
1045 )
1046 .child("to cancel")
1047 }
1048
1049 fn update_message_headers(&mut self, cx: &mut Context<Self>) {
1050 self.editor.update(cx, |editor, cx| {
1051 let buffer = editor.buffer().read(cx).snapshot(cx);
1052
1053 let excerpt_id = *buffer.as_singleton().unwrap().0;
1054 let mut old_blocks = std::mem::take(&mut self.blocks);
1055 let mut blocks_to_remove: HashMap<_, _> = old_blocks
1056 .iter()
1057 .map(|(message_id, (_, block_id))| (*message_id, *block_id))
1058 .collect();
1059 let mut blocks_to_replace: HashMap<_, RenderBlock> = Default::default();
1060
1061 let render_block = |message: MessageMetadata| -> RenderBlock {
1062 Arc::new({
1063 let text_thread = self.text_thread.clone();
1064
1065 move |cx| {
1066 let message_id = MessageId(message.timestamp);
1067 let llm_loading = message.role == Role::Assistant
1068 && message.status == MessageStatus::Pending;
1069
1070 let (label, spinner, note) = match message.role {
1071 Role::User => (
1072 Label::new("You").color(Color::Default).into_any_element(),
1073 None,
1074 None,
1075 ),
1076 Role::Assistant => {
1077 let base_label = Label::new("Agent").color(Color::Info);
1078 let mut spinner = None;
1079 let mut note = None;
1080 let animated_label = if llm_loading {
1081 base_label
1082 .with_animation(
1083 "pulsating-label",
1084 Animation::new(Duration::from_secs(2))
1085 .repeat()
1086 .with_easing(pulsating_between(0.4, 0.8)),
1087 |label, delta| label.alpha(delta),
1088 )
1089 .into_any_element()
1090 } else {
1091 base_label.into_any_element()
1092 };
1093 if llm_loading {
1094 spinner = Some(
1095 Icon::new(IconName::ArrowCircle)
1096 .size(IconSize::XSmall)
1097 .color(Color::Info)
1098 .with_rotate_animation(2)
1099 .into_any_element(),
1100 );
1101 note = Some(Self::esc_kbd(cx).into_any_element());
1102 }
1103 (animated_label, spinner, note)
1104 }
1105 Role::System => (
1106 Label::new("System")
1107 .color(Color::Warning)
1108 .into_any_element(),
1109 None,
1110 None,
1111 ),
1112 };
1113
1114 let sender = h_flex()
1115 .items_center()
1116 .gap_2p5()
1117 .child(
1118 ButtonLike::new("role")
1119 .style(ButtonStyle::Filled)
1120 .child(
1121 h_flex()
1122 .items_center()
1123 .gap_1p5()
1124 .child(label)
1125 .children(spinner),
1126 )
1127 .tooltip(|_window, cx| {
1128 Tooltip::with_meta(
1129 "Toggle message role",
1130 None,
1131 "Available roles: You (User), Agent, System",
1132 cx,
1133 )
1134 })
1135 .on_click({
1136 let text_thread = text_thread.clone();
1137 move |_, _window, cx| {
1138 text_thread.update(cx, |text_thread, cx| {
1139 text_thread.cycle_message_roles(
1140 HashSet::from_iter(Some(message_id)),
1141 cx,
1142 )
1143 })
1144 }
1145 }),
1146 )
1147 .children(note);
1148
1149 h_flex()
1150 .id(("message_header", message_id.as_u64()))
1151 .pl(cx.margins.gutter.full_width())
1152 .h_11()
1153 .w_full()
1154 .relative()
1155 .gap_1p5()
1156 .child(sender)
1157 .children(match &message.cache {
1158 Some(cache) if cache.is_final_anchor => match cache.status {
1159 CacheStatus::Cached => Some(
1160 div()
1161 .id("cached")
1162 .child(
1163 Icon::new(IconName::DatabaseZap)
1164 .size(IconSize::XSmall)
1165 .color(Color::Hint),
1166 )
1167 .tooltip(|_window, cx| {
1168 Tooltip::with_meta(
1169 "Context Cached",
1170 None,
1171 "Large messages cached to optimize performance",
1172 cx,
1173 )
1174 })
1175 .into_any_element(),
1176 ),
1177 CacheStatus::Pending => Some(
1178 div()
1179 .child(
1180 Icon::new(IconName::Ellipsis)
1181 .size(IconSize::XSmall)
1182 .color(Color::Hint),
1183 )
1184 .into_any_element(),
1185 ),
1186 },
1187 _ => None,
1188 })
1189 .children(match &message.status {
1190 MessageStatus::Error(error) => Some(
1191 Button::new("show-error", "Error")
1192 .color(Color::Error)
1193 .selected_label_color(Color::Error)
1194 .selected_icon_color(Color::Error)
1195 .icon(IconName::XCircle)
1196 .icon_color(Color::Error)
1197 .icon_size(IconSize::XSmall)
1198 .icon_position(IconPosition::Start)
1199 .tooltip(Tooltip::text("View Details"))
1200 .on_click({
1201 let text_thread = text_thread.clone();
1202 let error = error.clone();
1203 move |_, _window, cx| {
1204 text_thread.update(cx, |_, cx| {
1205 cx.emit(TextThreadEvent::ShowAssistError(
1206 error.clone(),
1207 ));
1208 });
1209 }
1210 })
1211 .into_any_element(),
1212 ),
1213 MessageStatus::Canceled => Some(
1214 h_flex()
1215 .gap_1()
1216 .items_center()
1217 .child(
1218 Icon::new(IconName::XCircle)
1219 .color(Color::Disabled)
1220 .size(IconSize::XSmall),
1221 )
1222 .child(
1223 Label::new("Canceled")
1224 .size(LabelSize::Small)
1225 .color(Color::Disabled),
1226 )
1227 .into_any_element(),
1228 ),
1229 _ => None,
1230 })
1231 .into_any_element()
1232 }
1233 })
1234 };
1235 let create_block_properties = |message: &Message| BlockProperties {
1236 height: Some(2),
1237 style: BlockStyle::Sticky,
1238 placement: BlockPlacement::Above(
1239 buffer
1240 .anchor_in_excerpt(excerpt_id, message.anchor_range.start)
1241 .unwrap(),
1242 ),
1243 priority: usize::MAX,
1244 render: render_block(MessageMetadata::from(message)),
1245 };
1246 let mut new_blocks = vec![];
1247 let mut block_index_to_message = vec![];
1248 for message in self.text_thread.read(cx).messages(cx) {
1249 if blocks_to_remove.remove(&message.id).is_some() {
1250 // This is an old message that we might modify.
1251 let Some((meta, block_id)) = old_blocks.get_mut(&message.id) else {
1252 debug_assert!(
1253 false,
1254 "old_blocks should contain a message_id we've just removed."
1255 );
1256 continue;
1257 };
1258 // Should we modify it?
1259 let message_meta = MessageMetadata::from(&message);
1260 if meta != &message_meta {
1261 blocks_to_replace.insert(*block_id, render_block(message_meta.clone()));
1262 *meta = message_meta;
1263 }
1264 } else {
1265 // This is a new message.
1266 new_blocks.push(create_block_properties(&message));
1267 block_index_to_message.push((message.id, MessageMetadata::from(&message)));
1268 }
1269 }
1270 editor.replace_blocks(blocks_to_replace, None, cx);
1271 editor.remove_blocks(blocks_to_remove.into_values().collect(), None, cx);
1272
1273 let ids = editor.insert_blocks(new_blocks, None, cx);
1274 old_blocks.extend(ids.into_iter().zip(block_index_to_message).map(
1275 |(block_id, (message_id, message_meta))| (message_id, (message_meta, block_id)),
1276 ));
1277 self.blocks = old_blocks;
1278 });
1279 }
1280
1281 /// Returns either the selected text, or the content of the Markdown code
1282 /// block surrounding the cursor.
1283 fn get_selection_or_code_block(
1284 context_editor_view: &Entity<TextThreadEditor>,
1285 cx: &mut Context<Workspace>,
1286 ) -> Option<(String, bool)> {
1287 const CODE_FENCE_DELIMITER: &str = "```";
1288
1289 let text_thread_editor = context_editor_view.read(cx).editor.clone();
1290 text_thread_editor.update(cx, |text_thread_editor, cx| {
1291 let display_map = text_thread_editor.display_snapshot(cx);
1292 if text_thread_editor
1293 .selections
1294 .newest::<Point>(&display_map)
1295 .is_empty()
1296 {
1297 let snapshot = text_thread_editor.buffer().read(cx).snapshot(cx);
1298 let (_, _, snapshot) = snapshot.as_singleton()?;
1299
1300 let head = text_thread_editor
1301 .selections
1302 .newest::<Point>(&display_map)
1303 .head();
1304 let offset = snapshot.point_to_offset(head);
1305
1306 let surrounding_code_block_range = find_surrounding_code_block(snapshot, offset)?;
1307 let mut text = snapshot
1308 .text_for_range(surrounding_code_block_range)
1309 .collect::<String>();
1310
1311 // If there is no newline trailing the closing three-backticks, then
1312 // tree-sitter-md extends the range of the content node to include
1313 // the backticks.
1314 if text.ends_with(CODE_FENCE_DELIMITER) {
1315 text.drain((text.len() - CODE_FENCE_DELIMITER.len())..);
1316 }
1317
1318 (!text.is_empty()).then_some((text, true))
1319 } else {
1320 let selection = text_thread_editor.selections.newest_adjusted(&display_map);
1321 let buffer = text_thread_editor.buffer().read(cx).snapshot(cx);
1322 let selected_text = buffer.text_for_range(selection.range()).collect::<String>();
1323
1324 (!selected_text.is_empty()).then_some((selected_text, false))
1325 }
1326 })
1327 }
1328
1329 pub fn insert_selection(
1330 workspace: &mut Workspace,
1331 _: &InsertIntoEditor,
1332 window: &mut Window,
1333 cx: &mut Context<Workspace>,
1334 ) {
1335 let Some(agent_panel_delegate) = <dyn AgentPanelDelegate>::try_global(cx) else {
1336 return;
1337 };
1338 let Some(context_editor_view) =
1339 agent_panel_delegate.active_text_thread_editor(workspace, window, cx)
1340 else {
1341 return;
1342 };
1343 let Some(active_editor_view) = workspace
1344 .active_item(cx)
1345 .and_then(|item| item.act_as::<Editor>(cx))
1346 else {
1347 return;
1348 };
1349
1350 if let Some((text, _)) = Self::get_selection_or_code_block(&context_editor_view, cx) {
1351 active_editor_view.update(cx, |editor, cx| {
1352 editor.insert(&text, window, cx);
1353 editor.focus_handle(cx).focus(window, cx);
1354 })
1355 }
1356 }
1357
1358 pub fn copy_code(
1359 workspace: &mut Workspace,
1360 _: &CopyCode,
1361 window: &mut Window,
1362 cx: &mut Context<Workspace>,
1363 ) {
1364 let result = maybe!({
1365 let agent_panel_delegate = <dyn AgentPanelDelegate>::try_global(cx)?;
1366 let context_editor_view =
1367 agent_panel_delegate.active_text_thread_editor(workspace, window, cx)?;
1368 Self::get_selection_or_code_block(&context_editor_view, cx)
1369 });
1370 let Some((text, is_code_block)) = result else {
1371 return;
1372 };
1373
1374 cx.write_to_clipboard(ClipboardItem::new_string(text));
1375
1376 struct CopyToClipboardToast;
1377 workspace.show_toast(
1378 Toast::new(
1379 NotificationId::unique::<CopyToClipboardToast>(),
1380 format!(
1381 "{} copied to clipboard.",
1382 if is_code_block {
1383 "Code block"
1384 } else {
1385 "Selection"
1386 }
1387 ),
1388 )
1389 .autohide(),
1390 cx,
1391 );
1392 }
1393
1394 pub fn handle_insert_dragged_files(
1395 workspace: &mut Workspace,
1396 action: &InsertDraggedFiles,
1397 window: &mut Window,
1398 cx: &mut Context<Workspace>,
1399 ) {
1400 let Some(agent_panel_delegate) = <dyn AgentPanelDelegate>::try_global(cx) else {
1401 return;
1402 };
1403 let Some(context_editor_view) =
1404 agent_panel_delegate.active_text_thread_editor(workspace, window, cx)
1405 else {
1406 return;
1407 };
1408
1409 let project = context_editor_view.read(cx).project.clone();
1410
1411 let paths = match action {
1412 InsertDraggedFiles::ProjectPaths(paths) => Task::ready((paths.clone(), vec![])),
1413 InsertDraggedFiles::ExternalFiles(paths) => {
1414 let tasks = paths
1415 .clone()
1416 .into_iter()
1417 .map(|path| Workspace::project_path_for_path(project.clone(), &path, false, cx))
1418 .collect::<Vec<_>>();
1419
1420 cx.background_spawn(async move {
1421 let mut paths = vec![];
1422 let mut worktrees = vec![];
1423
1424 let opened_paths = futures::future::join_all(tasks).await;
1425
1426 for entry in opened_paths {
1427 if let Some((worktree, project_path)) = entry.log_err() {
1428 worktrees.push(worktree);
1429 paths.push(project_path);
1430 }
1431 }
1432
1433 (paths, worktrees)
1434 })
1435 }
1436 };
1437
1438 context_editor_view.update(cx, |_, cx| {
1439 cx.spawn_in(window, async move |this, cx| {
1440 let (paths, dragged_file_worktrees) = paths.await;
1441 this.update_in(cx, |this, window, cx| {
1442 this.insert_dragged_files(paths, dragged_file_worktrees, window, cx);
1443 })
1444 .ok();
1445 })
1446 .detach();
1447 })
1448 }
1449
1450 pub fn insert_dragged_files(
1451 &mut self,
1452 opened_paths: Vec<ProjectPath>,
1453 added_worktrees: Vec<Entity<Worktree>>,
1454 window: &mut Window,
1455 cx: &mut Context<Self>,
1456 ) {
1457 let mut file_slash_command_args = vec![];
1458 for project_path in opened_paths.into_iter() {
1459 let Some(worktree) = self
1460 .project
1461 .read(cx)
1462 .worktree_for_id(project_path.worktree_id, cx)
1463 else {
1464 continue;
1465 };
1466 let path_style = worktree.read(cx).path_style();
1467 let full_path = worktree
1468 .read(cx)
1469 .root_name()
1470 .join(&project_path.path)
1471 .display(path_style)
1472 .into_owned();
1473 file_slash_command_args.push(full_path);
1474 }
1475
1476 let cmd_name = FileSlashCommand.name();
1477
1478 let file_argument = file_slash_command_args.join(" ");
1479
1480 self.editor.update(cx, |editor, cx| {
1481 editor.insert("\n", window, cx);
1482 editor.insert(&format!("/{} {}", cmd_name, file_argument), window, cx);
1483 });
1484 self.confirm_command(&ConfirmCommand, window, cx);
1485 self.dragged_file_worktrees.extend(added_worktrees);
1486 }
1487
1488 pub fn quote_selection(
1489 workspace: &mut Workspace,
1490 _: &AddSelectionToThread,
1491 window: &mut Window,
1492 cx: &mut Context<Workspace>,
1493 ) {
1494 let Some(agent_panel_delegate) = <dyn AgentPanelDelegate>::try_global(cx) else {
1495 return;
1496 };
1497
1498 // Get buffer info for the delegate call (even if empty, AcpThreadView ignores these
1499 // params and calls insert_selections which handles both terminal and buffer)
1500 if let Some((selections, buffer)) = maybe!({
1501 let editor = workspace
1502 .active_item(cx)
1503 .and_then(|item| item.act_as::<Editor>(cx))?;
1504
1505 let buffer = editor.read(cx).buffer().clone();
1506 let snapshot = buffer.read(cx).snapshot(cx);
1507 let selections = editor.update(cx, |editor, cx| {
1508 editor
1509 .selections
1510 .all_adjusted(&editor.display_snapshot(cx))
1511 .into_iter()
1512 .filter_map(|s| {
1513 (!s.is_empty())
1514 .then(|| snapshot.anchor_after(s.start)..snapshot.anchor_before(s.end))
1515 })
1516 .collect::<Vec<_>>()
1517 });
1518 Some((selections, buffer))
1519 }) {
1520 agent_panel_delegate.quote_selection(workspace, selections, buffer, window, cx);
1521 }
1522 }
1523
1524 /// Handles the SendReviewToAgent action from the ProjectDiff toolbar.
1525 /// Collects ALL stored review comments from ALL hunks and sends them
1526 /// to the Agent panel as creases.
1527 pub fn handle_send_review_to_agent(
1528 workspace: &mut Workspace,
1529 _: &SendReviewToAgent,
1530 window: &mut Window,
1531 cx: &mut Context<Workspace>,
1532 ) {
1533 use editor::{DiffHunkKey, StoredReviewComment};
1534 use git_ui::project_diff::ProjectDiff;
1535
1536 // Find the ProjectDiff item
1537 let Some(project_diff) = workspace.items_of_type::<ProjectDiff>(cx).next() else {
1538 workspace.show_toast(
1539 Toast::new(
1540 NotificationId::unique::<SendReviewToAgent>(),
1541 "No Project Diff panel found. Open it first to add review comments.",
1542 ),
1543 cx,
1544 );
1545 return;
1546 };
1547
1548 // Get the buffer reference first (before taking comments)
1549 let buffer = project_diff.update(cx, |project_diff, cx| {
1550 project_diff
1551 .editor()
1552 .read(cx)
1553 .rhs_editor()
1554 .read(cx)
1555 .buffer()
1556 .clone()
1557 });
1558
1559 // Extract all stored comments from all hunks
1560 let all_comments: Vec<(DiffHunkKey, Vec<StoredReviewComment>)> =
1561 project_diff.update(cx, |project_diff, cx| {
1562 let editor = project_diff.editor().read(cx).rhs_editor().clone();
1563 editor.update(cx, |editor, cx| editor.take_all_review_comments(cx))
1564 });
1565
1566 // Flatten: we have Vec<(DiffHunkKey, Vec<StoredReviewComment>)>
1567 // Convert to Vec<StoredReviewComment> for processing
1568 let comments: Vec<StoredReviewComment> = all_comments
1569 .into_iter()
1570 .flat_map(|(_, comments)| comments)
1571 .collect();
1572
1573 if comments.is_empty() {
1574 workspace.show_toast(
1575 Toast::new(
1576 NotificationId::unique::<SendReviewToAgent>(),
1577 "No review comments to send. Add comments using the + button in the diff view.",
1578 ),
1579 cx,
1580 );
1581 return;
1582 }
1583
1584 // Get or create the agent panel
1585 let Some(panel) = workspace.panel::<crate::AgentPanel>(cx) else {
1586 workspace.show_toast(
1587 Toast::new(
1588 NotificationId::unique::<SendReviewToAgent>(),
1589 "Agent panel is not available.",
1590 ),
1591 cx,
1592 );
1593 return;
1594 };
1595
1596 // Create a new thread if there isn't an active one (synchronous call)
1597 let has_active_thread = panel.read(cx).active_thread_view().is_some();
1598 if !has_active_thread {
1599 panel.update(cx, |panel, cx| {
1600 panel.new_agent_thread(AgentType::NativeAgent, window, cx);
1601 });
1602 }
1603
1604 // Focus the agent panel
1605 workspace.focus_panel::<crate::AgentPanel>(window, cx);
1606
1607 // Defer inserting creases until after the current update cycle completes,
1608 // allowing the newly created thread (if any) to fully initialize.
1609 cx.defer_in(window, move |workspace, window, cx| {
1610 let Some(panel) = workspace.panel::<crate::AgentPanel>(cx) else {
1611 workspace.show_toast(
1612 Toast::new(
1613 NotificationId::unique::<SendReviewToAgent>(),
1614 "Agent panel closed unexpectedly.",
1615 ),
1616 cx,
1617 );
1618 return;
1619 };
1620
1621 let thread_view = panel.read(cx).active_thread_view().cloned();
1622 let Some(thread_view) = thread_view else {
1623 workspace.show_toast(
1624 Toast::new(
1625 NotificationId::unique::<SendReviewToAgent>(),
1626 "No active thread view available after creating thread.",
1627 ),
1628 cx,
1629 );
1630 return;
1631 };
1632
1633 // Build creases for all comments, grouping by code snippet
1634 // so each snippet appears once with all its comments
1635 let snapshot = buffer.read(cx).snapshot(cx);
1636
1637 // Group comments by their point range (code snippet)
1638 let mut comments_by_range: std::collections::BTreeMap<
1639 (rope::Point, rope::Point),
1640 Vec<String>,
1641 > = std::collections::BTreeMap::new();
1642
1643 for comment in comments {
1644 let start = comment.range.start.to_point(&snapshot);
1645 let end = comment.range.end.to_point(&snapshot);
1646 comments_by_range
1647 .entry((start, end))
1648 .or_default()
1649 .push(comment.comment);
1650 }
1651
1652 // Build one crease per unique code snippet with all its comments
1653 let mut all_creases = Vec::new();
1654 for ((start, end), comment_texts) in comments_by_range {
1655 let point_range = start..end;
1656
1657 let mut creases =
1658 selections_creases(vec![point_range.clone()], snapshot.clone(), cx);
1659
1660 // Append all comments after the code snippet
1661 for (code_text, crease_title) in &mut creases {
1662 let comments_section = comment_texts.join("\n\n");
1663 *code_text = format!("{}\n\n{}", code_text, comments_section);
1664 *crease_title = format!("Review: {}", crease_title);
1665 }
1666
1667 all_creases.extend(creases);
1668 }
1669
1670 // Insert all creases into the message editor
1671 thread_view.update(cx, |thread_view, cx| {
1672 thread_view.insert_code_crease(all_creases, window, cx);
1673 });
1674 });
1675 }
1676
1677 pub fn quote_ranges(
1678 &mut self,
1679 ranges: Vec<Range<Point>>,
1680 snapshot: MultiBufferSnapshot,
1681 window: &mut Window,
1682 cx: &mut Context<Self>,
1683 ) {
1684 let creases = selections_creases(ranges, snapshot, cx);
1685
1686 self.editor.update(cx, |editor, cx| {
1687 editor.insert("\n", window, cx);
1688 for (text, crease_title) in creases {
1689 let point = editor
1690 .selections
1691 .newest::<Point>(&editor.display_snapshot(cx))
1692 .head();
1693 let start_row = MultiBufferRow(point.row);
1694
1695 editor.insert(&text, window, cx);
1696
1697 let snapshot = editor.buffer().read(cx).snapshot(cx);
1698 let anchor_before = snapshot.anchor_after(point);
1699 let anchor_after = editor
1700 .selections
1701 .newest_anchor()
1702 .head()
1703 .bias_left(&snapshot);
1704
1705 editor.insert("\n", window, cx);
1706
1707 let fold_placeholder =
1708 quote_selection_fold_placeholder(crease_title, cx.entity().downgrade());
1709 let crease = Crease::inline(
1710 anchor_before..anchor_after,
1711 fold_placeholder,
1712 render_quote_selection_output_toggle,
1713 |_, _, _, _| Empty.into_any(),
1714 );
1715 editor.insert_creases(vec![crease], cx);
1716 editor.fold_at(start_row, window, cx);
1717 }
1718 })
1719 }
1720
1721 pub fn quote_terminal_text(
1722 &mut self,
1723 text: String,
1724 window: &mut Window,
1725 cx: &mut Context<Self>,
1726 ) {
1727 let crease_title = "terminal".to_string();
1728 let formatted_text = format!("```console\n{}\n```\n", text);
1729
1730 self.editor.update(cx, |editor, cx| {
1731 // Insert newline first if not at the start of a line
1732 let point = editor
1733 .selections
1734 .newest::<Point>(&editor.display_snapshot(cx))
1735 .head();
1736 if point.column > 0 {
1737 editor.insert("\n", window, cx);
1738 }
1739
1740 let point = editor
1741 .selections
1742 .newest::<Point>(&editor.display_snapshot(cx))
1743 .head();
1744 let start_row = MultiBufferRow(point.row);
1745
1746 editor.insert(&formatted_text, window, cx);
1747
1748 let snapshot = editor.buffer().read(cx).snapshot(cx);
1749 let anchor_before = snapshot.anchor_after(point);
1750 let anchor_after = editor
1751 .selections
1752 .newest_anchor()
1753 .head()
1754 .bias_left(&snapshot);
1755
1756 let fold_placeholder =
1757 quote_selection_fold_placeholder(crease_title, cx.entity().downgrade());
1758 let crease = Crease::inline(
1759 anchor_before..anchor_after,
1760 fold_placeholder,
1761 render_quote_selection_output_toggle,
1762 |_, _, _, _| Empty.into_any(),
1763 );
1764 editor.insert_creases(vec![crease], cx);
1765 editor.fold_at(start_row, window, cx);
1766 })
1767 }
1768
1769 fn copy(&mut self, _: &editor::actions::Copy, _window: &mut Window, cx: &mut Context<Self>) {
1770 if self.editor.read(cx).selections.count() == 1 {
1771 let (copied_text, metadata, _) = self.get_clipboard_contents(cx);
1772 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
1773 copied_text,
1774 metadata,
1775 ));
1776 cx.stop_propagation();
1777 return;
1778 }
1779
1780 cx.propagate();
1781 }
1782
1783 fn cut(&mut self, _: &editor::actions::Cut, window: &mut Window, cx: &mut Context<Self>) {
1784 if self.editor.read(cx).selections.count() == 1 {
1785 let (copied_text, metadata, selections) = self.get_clipboard_contents(cx);
1786
1787 self.editor.update(cx, |editor, cx| {
1788 editor.transact(window, cx, |this, window, cx| {
1789 this.change_selections(Default::default(), window, cx, |s| {
1790 s.select(selections);
1791 });
1792 this.insert("", window, cx);
1793 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
1794 copied_text,
1795 metadata,
1796 ));
1797 });
1798 });
1799
1800 cx.stop_propagation();
1801 return;
1802 }
1803
1804 cx.propagate();
1805 }
1806
1807 fn get_clipboard_contents(
1808 &mut self,
1809 cx: &mut Context<Self>,
1810 ) -> (
1811 String,
1812 CopyMetadata,
1813 Vec<text::Selection<MultiBufferOffset>>,
1814 ) {
1815 let (mut selection, creases) = self.editor.update(cx, |editor, cx| {
1816 let mut selection = editor
1817 .selections
1818 .newest_adjusted(&editor.display_snapshot(cx));
1819 let snapshot = editor.buffer().read(cx).snapshot(cx);
1820
1821 selection.goal = SelectionGoal::None;
1822
1823 let selection_start = snapshot.point_to_offset(selection.start);
1824
1825 (
1826 selection.map(|point| snapshot.point_to_offset(point)),
1827 editor.display_map.update(cx, |display_map, cx| {
1828 display_map
1829 .snapshot(cx)
1830 .crease_snapshot
1831 .creases_in_range(
1832 MultiBufferRow(selection.start.row)
1833 ..MultiBufferRow(selection.end.row + 1),
1834 &snapshot,
1835 )
1836 .filter_map(|crease| {
1837 if let Crease::Inline {
1838 range, metadata, ..
1839 } = &crease
1840 {
1841 let metadata = metadata.as_ref()?;
1842 let start = range
1843 .start
1844 .to_offset(&snapshot)
1845 .saturating_sub(selection_start);
1846 let end = range
1847 .end
1848 .to_offset(&snapshot)
1849 .saturating_sub(selection_start);
1850
1851 let range_relative_to_selection = start..end;
1852 if !range_relative_to_selection.is_empty() {
1853 return Some(SelectedCreaseMetadata {
1854 range_relative_to_selection,
1855 crease: metadata.clone(),
1856 });
1857 }
1858 }
1859 None
1860 })
1861 .collect::<Vec<_>>()
1862 }),
1863 )
1864 });
1865
1866 let text_thread = self.text_thread.read(cx);
1867
1868 let mut text = String::new();
1869
1870 // If selection is empty, we want to copy the entire line
1871 if selection.range().is_empty() {
1872 let snapshot = self.editor.read(cx).buffer().read(cx).snapshot(cx);
1873 let point = snapshot.offset_to_point(selection.range().start);
1874 selection.start = snapshot.point_to_offset(Point::new(point.row, 0));
1875 selection.end = snapshot
1876 .point_to_offset(cmp::min(Point::new(point.row + 1, 0), snapshot.max_point()));
1877 for chunk in snapshot.text_for_range(selection.range()) {
1878 text.push_str(chunk);
1879 }
1880 } else {
1881 for message in text_thread.messages(cx) {
1882 if message.offset_range.start >= selection.range().end.0 {
1883 break;
1884 } else if message.offset_range.end >= selection.range().start.0 {
1885 let range = cmp::max(message.offset_range.start, selection.range().start.0)
1886 ..cmp::min(message.offset_range.end, selection.range().end.0);
1887 if !range.is_empty() {
1888 for chunk in text_thread.buffer().read(cx).text_for_range(range) {
1889 text.push_str(chunk);
1890 }
1891 if message.offset_range.end < selection.range().end.0 {
1892 text.push('\n');
1893 }
1894 }
1895 }
1896 }
1897 }
1898 (text, CopyMetadata { creases }, vec![selection])
1899 }
1900
1901 fn paste(
1902 &mut self,
1903 action: &editor::actions::Paste,
1904 window: &mut Window,
1905 cx: &mut Context<Self>,
1906 ) {
1907 let Some(workspace) = self.workspace.upgrade() else {
1908 return;
1909 };
1910 let editor_clipboard_selections = cx
1911 .read_from_clipboard()
1912 .and_then(|item| item.entries().first().cloned())
1913 .and_then(|entry| match entry {
1914 ClipboardEntry::String(text) => {
1915 text.metadata_json::<Vec<editor::ClipboardSelection>>()
1916 }
1917 _ => None,
1918 });
1919
1920 // Insert creases for pasted clipboard selections that:
1921 // 1. Contain exactly one selection
1922 // 2. Have an associated file path
1923 // 3. Span multiple lines (not single-line selections)
1924 // 4. Belong to a file that exists in the current project
1925 let should_insert_creases = util::maybe!({
1926 let selections = editor_clipboard_selections.as_ref()?;
1927 if selections.len() > 1 {
1928 return Some(false);
1929 }
1930 let selection = selections.first()?;
1931 let file_path = selection.file_path.as_ref()?;
1932 let line_range = selection.line_range.as_ref()?;
1933
1934 if line_range.start() == line_range.end() {
1935 return Some(false);
1936 }
1937
1938 Some(
1939 workspace
1940 .read(cx)
1941 .project()
1942 .read(cx)
1943 .project_path_for_absolute_path(file_path, cx)
1944 .is_some(),
1945 )
1946 })
1947 .unwrap_or(false);
1948
1949 if should_insert_creases && let Some(clipboard_item) = cx.read_from_clipboard() {
1950 if let Some(ClipboardEntry::String(clipboard_text)) = clipboard_item.entries().first() {
1951 if let Some(selections) = editor_clipboard_selections {
1952 cx.stop_propagation();
1953
1954 let text = clipboard_text.text();
1955 self.editor.update(cx, |editor, cx| {
1956 let mut current_offset = 0;
1957 let weak_editor = cx.entity().downgrade();
1958
1959 for selection in selections {
1960 if let (Some(file_path), Some(line_range)) =
1961 (selection.file_path, selection.line_range)
1962 {
1963 let selected_text =
1964 &text[current_offset..current_offset + selection.len];
1965 let fence = assistant_slash_commands::codeblock_fence_for_path(
1966 file_path.to_str(),
1967 Some(line_range.clone()),
1968 );
1969 let formatted_text = format!("{fence}{selected_text}\n```");
1970
1971 let insert_point = editor
1972 .selections
1973 .newest::<Point>(&editor.display_snapshot(cx))
1974 .head();
1975 let start_row = MultiBufferRow(insert_point.row);
1976
1977 editor.insert(&formatted_text, window, cx);
1978
1979 let snapshot = editor.buffer().read(cx).snapshot(cx);
1980 let anchor_before = snapshot.anchor_after(insert_point);
1981 let anchor_after = editor
1982 .selections
1983 .newest_anchor()
1984 .head()
1985 .bias_left(&snapshot);
1986
1987 editor.insert("\n", window, cx);
1988
1989 let crease_text = acp_thread::selection_name(
1990 Some(file_path.as_ref()),
1991 &line_range,
1992 );
1993
1994 let fold_placeholder = quote_selection_fold_placeholder(
1995 crease_text,
1996 weak_editor.clone(),
1997 );
1998 let crease = Crease::inline(
1999 anchor_before..anchor_after,
2000 fold_placeholder,
2001 render_quote_selection_output_toggle,
2002 |_, _, _, _| Empty.into_any(),
2003 );
2004 editor.insert_creases(vec![crease], cx);
2005 editor.fold_at(start_row, window, cx);
2006
2007 current_offset += selection.len;
2008 if !selection.is_entire_line && current_offset < text.len() {
2009 current_offset += 1;
2010 }
2011 }
2012 }
2013 });
2014 return;
2015 }
2016 }
2017 }
2018
2019 cx.stop_propagation();
2020
2021 let mut images = if let Some(item) = cx.read_from_clipboard() {
2022 item.into_entries()
2023 .filter_map(|entry| {
2024 if let ClipboardEntry::Image(image) = entry {
2025 Some(image)
2026 } else {
2027 None
2028 }
2029 })
2030 .collect()
2031 } else {
2032 Vec::new()
2033 };
2034
2035 if let Some(paths) = cx.read_from_clipboard() {
2036 for path in paths
2037 .into_entries()
2038 .filter_map(|entry| {
2039 if let ClipboardEntry::ExternalPaths(paths) = entry {
2040 Some(paths.paths().to_owned())
2041 } else {
2042 None
2043 }
2044 })
2045 .flatten()
2046 {
2047 let Ok(content) = std::fs::read(path) else {
2048 continue;
2049 };
2050 let Ok(format) = image::guess_format(&content) else {
2051 continue;
2052 };
2053 images.push(gpui::Image::from_bytes(
2054 match format {
2055 image::ImageFormat::Png => gpui::ImageFormat::Png,
2056 image::ImageFormat::Jpeg => gpui::ImageFormat::Jpeg,
2057 image::ImageFormat::WebP => gpui::ImageFormat::Webp,
2058 image::ImageFormat::Gif => gpui::ImageFormat::Gif,
2059 image::ImageFormat::Bmp => gpui::ImageFormat::Bmp,
2060 image::ImageFormat::Tiff => gpui::ImageFormat::Tiff,
2061 image::ImageFormat::Ico => gpui::ImageFormat::Ico,
2062 _ => continue,
2063 },
2064 content,
2065 ));
2066 }
2067 }
2068
2069 let metadata = if let Some(item) = cx.read_from_clipboard() {
2070 item.entries().first().and_then(|entry| {
2071 if let ClipboardEntry::String(text) = entry {
2072 text.metadata_json::<CopyMetadata>()
2073 } else {
2074 None
2075 }
2076 })
2077 } else {
2078 None
2079 };
2080
2081 if images.is_empty() {
2082 self.editor.update(cx, |editor, cx| {
2083 let paste_position = editor
2084 .selections
2085 .newest::<MultiBufferOffset>(&editor.display_snapshot(cx))
2086 .head();
2087 editor.paste(action, window, cx);
2088
2089 if let Some(metadata) = metadata {
2090 let buffer = editor.buffer().read(cx).snapshot(cx);
2091
2092 let mut buffer_rows_to_fold = BTreeSet::new();
2093 let weak_editor = cx.entity().downgrade();
2094 editor.insert_creases(
2095 metadata.creases.into_iter().map(|metadata| {
2096 let start = buffer.anchor_after(
2097 paste_position + metadata.range_relative_to_selection.start,
2098 );
2099 let end = buffer.anchor_before(
2100 paste_position + metadata.range_relative_to_selection.end,
2101 );
2102
2103 let buffer_row = MultiBufferRow(start.to_point(&buffer).row);
2104 buffer_rows_to_fold.insert(buffer_row);
2105 Crease::inline(
2106 start..end,
2107 FoldPlaceholder {
2108 render: render_fold_icon_button(
2109 weak_editor.clone(),
2110 metadata.crease.icon_path.clone(),
2111 metadata.crease.label.clone(),
2112 ),
2113 ..Default::default()
2114 },
2115 render_slash_command_output_toggle,
2116 |_, _, _, _| Empty.into_any(),
2117 )
2118 .with_metadata(metadata.crease)
2119 }),
2120 cx,
2121 );
2122 for buffer_row in buffer_rows_to_fold.into_iter().rev() {
2123 editor.fold_at(buffer_row, window, cx);
2124 }
2125 }
2126 });
2127 } else {
2128 let mut image_positions = Vec::new();
2129 self.editor.update(cx, |editor, cx| {
2130 editor.transact(window, cx, |editor, _window, cx| {
2131 let edits = editor
2132 .selections
2133 .all::<MultiBufferOffset>(&editor.display_snapshot(cx))
2134 .into_iter()
2135 .map(|selection| (selection.start..selection.end, "\n"));
2136 editor.edit(edits, cx);
2137
2138 let snapshot = editor.buffer().read(cx).snapshot(cx);
2139 for selection in editor
2140 .selections
2141 .all::<MultiBufferOffset>(&editor.display_snapshot(cx))
2142 {
2143 image_positions.push(snapshot.anchor_before(selection.end));
2144 }
2145 });
2146 });
2147
2148 self.text_thread.update(cx, |text_thread, cx| {
2149 for image in images {
2150 let Some(render_image) = image.to_image_data(cx.svg_renderer()).log_err()
2151 else {
2152 continue;
2153 };
2154 let image_id = image.id();
2155 let image_task = LanguageModelImage::from_image(Arc::new(image), cx).shared();
2156
2157 for image_position in image_positions.iter() {
2158 text_thread.insert_content(
2159 Content::Image {
2160 anchor: image_position.text_anchor,
2161 image_id,
2162 image: image_task.clone(),
2163 render_image: render_image.clone(),
2164 },
2165 cx,
2166 );
2167 }
2168 }
2169 });
2170 }
2171 }
2172
2173 fn paste_raw(&mut self, _: &PasteRaw, window: &mut Window, cx: &mut Context<Self>) {
2174 self.editor.update(cx, |editor, cx| {
2175 editor.paste(&editor::actions::Paste, window, cx);
2176 });
2177 }
2178
2179 fn update_image_blocks(&mut self, cx: &mut Context<Self>) {
2180 self.editor.update(cx, |editor, cx| {
2181 let buffer = editor.buffer().read(cx).snapshot(cx);
2182 let excerpt_id = *buffer.as_singleton().unwrap().0;
2183 let old_blocks = std::mem::take(&mut self.image_blocks);
2184 let new_blocks = self
2185 .text_thread
2186 .read(cx)
2187 .contents(cx)
2188 .map(
2189 |Content::Image {
2190 anchor,
2191 render_image,
2192 ..
2193 }| (anchor, render_image),
2194 )
2195 .filter_map(|(anchor, render_image)| {
2196 const MAX_HEIGHT_IN_LINES: u32 = 8;
2197 let anchor = buffer.anchor_in_excerpt(excerpt_id, anchor).unwrap();
2198 let image = render_image;
2199 anchor.is_valid(&buffer).then(|| BlockProperties {
2200 placement: BlockPlacement::Above(anchor),
2201 height: Some(MAX_HEIGHT_IN_LINES),
2202 style: BlockStyle::Sticky,
2203 render: Arc::new(move |cx| {
2204 let image_size = size_for_image(
2205 &image,
2206 size(
2207 cx.max_width - cx.margins.gutter.full_width(),
2208 MAX_HEIGHT_IN_LINES as f32 * cx.line_height,
2209 ),
2210 );
2211 h_flex()
2212 .pl(cx.margins.gutter.full_width())
2213 .child(
2214 img(image.clone())
2215 .object_fit(gpui::ObjectFit::ScaleDown)
2216 .w(image_size.width)
2217 .h(image_size.height),
2218 )
2219 .into_any_element()
2220 }),
2221 priority: 0,
2222 })
2223 })
2224 .collect::<Vec<_>>();
2225
2226 editor.remove_blocks(old_blocks, None, cx);
2227 let ids = editor.insert_blocks(new_blocks, None, cx);
2228 self.image_blocks = HashSet::from_iter(ids);
2229 });
2230 }
2231
2232 fn split(&mut self, _: &Split, _window: &mut Window, cx: &mut Context<Self>) {
2233 self.text_thread.update(cx, |text_thread, cx| {
2234 let selections = self.editor.read(cx).selections.disjoint_anchors_arc();
2235 for selection in selections.as_ref() {
2236 let buffer = self.editor.read(cx).buffer().read(cx).snapshot(cx);
2237 let range = selection
2238 .map(|endpoint| endpoint.to_offset(&buffer))
2239 .range();
2240 text_thread.split_message(range.start.0..range.end.0, cx);
2241 }
2242 });
2243 }
2244
2245 fn save(&mut self, _: &Save, _window: &mut Window, cx: &mut Context<Self>) {
2246 self.text_thread.update(cx, |text_thread, cx| {
2247 text_thread.save(Some(Duration::from_millis(500)), self.fs.clone(), cx)
2248 });
2249 }
2250
2251 pub fn title(&self, cx: &App) -> SharedString {
2252 self.text_thread.read(cx).summary().or_default()
2253 }
2254
2255 pub fn regenerate_summary(&mut self, cx: &mut Context<Self>) {
2256 self.text_thread
2257 .update(cx, |text_thread, cx| text_thread.summarize(true, cx));
2258 }
2259
2260 fn render_remaining_tokens(&self, cx: &App) -> Option<impl IntoElement + use<>> {
2261 let (token_count_color, token_count, max_token_count, tooltip) =
2262 match token_state(&self.text_thread, cx)? {
2263 TokenState::NoTokensLeft {
2264 max_token_count,
2265 token_count,
2266 } => (
2267 Color::Error,
2268 token_count,
2269 max_token_count,
2270 Some("Token Limit Reached"),
2271 ),
2272 TokenState::HasMoreTokens {
2273 max_token_count,
2274 token_count,
2275 over_warn_threshold,
2276 } => {
2277 let (color, tooltip) = if over_warn_threshold {
2278 (Color::Warning, Some("Token Limit is Close to Exhaustion"))
2279 } else {
2280 (Color::Muted, None)
2281 };
2282 (color, token_count, max_token_count, tooltip)
2283 }
2284 };
2285
2286 Some(
2287 h_flex()
2288 .id("token-count")
2289 .gap_0p5()
2290 .child(
2291 Label::new(humanize_token_count(token_count))
2292 .size(LabelSize::Small)
2293 .color(token_count_color),
2294 )
2295 .child(Label::new("/").size(LabelSize::Small).color(Color::Muted))
2296 .child(
2297 Label::new(humanize_token_count(max_token_count))
2298 .size(LabelSize::Small)
2299 .color(Color::Muted),
2300 )
2301 .when_some(tooltip, |element, tooltip| {
2302 element.tooltip(Tooltip::text(tooltip))
2303 }),
2304 )
2305 }
2306
2307 fn render_send_button(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2308 let focus_handle = self.focus_handle(cx);
2309
2310 let (style, tooltip) = match token_state(&self.text_thread, cx) {
2311 Some(TokenState::NoTokensLeft { .. }) => (
2312 ButtonStyle::Tinted(TintColor::Error),
2313 Some(Tooltip::text("Token limit reached")(window, cx)),
2314 ),
2315 Some(TokenState::HasMoreTokens {
2316 over_warn_threshold,
2317 ..
2318 }) => {
2319 let (style, tooltip) = if over_warn_threshold {
2320 (
2321 ButtonStyle::Tinted(TintColor::Warning),
2322 Some(Tooltip::text("Token limit is close to exhaustion")(
2323 window, cx,
2324 )),
2325 )
2326 } else {
2327 (ButtonStyle::Filled, None)
2328 };
2329 (style, tooltip)
2330 }
2331 None => (ButtonStyle::Filled, None),
2332 };
2333
2334 Button::new("send_button", "Send")
2335 .label_size(LabelSize::Small)
2336 .disabled(self.sending_disabled(cx))
2337 .style(style)
2338 .when_some(tooltip, |button, tooltip| {
2339 button.tooltip(move |_, _| tooltip.clone())
2340 })
2341 .layer(ElevationIndex::ModalSurface)
2342 .key_binding(
2343 KeyBinding::for_action_in(&Assist, &focus_handle, cx)
2344 .map(|kb| kb.size(rems_from_px(12.))),
2345 )
2346 .on_click(move |_event, window, cx| {
2347 focus_handle.dispatch_action(&Assist, window, cx);
2348 })
2349 }
2350
2351 /// Whether or not we should allow messages to be sent.
2352 /// Will return false if the selected provided has a configuration error or
2353 /// if the user has not accepted the terms of service for this provider.
2354 fn sending_disabled(&self, cx: &mut Context<'_, TextThreadEditor>) -> bool {
2355 let model_registry = LanguageModelRegistry::read_global(cx);
2356 let Some(configuration_error) =
2357 model_registry.configuration_error(model_registry.default_model(), cx)
2358 else {
2359 return false;
2360 };
2361
2362 match configuration_error {
2363 ConfigurationError::NoProvider
2364 | ConfigurationError::ModelNotFound
2365 | ConfigurationError::ProviderNotAuthenticated(_) => true,
2366 }
2367 }
2368
2369 fn render_inject_context_menu(&self, cx: &mut Context<Self>) -> impl IntoElement {
2370 slash_command_picker::SlashCommandSelector::new(
2371 self.slash_commands.clone(),
2372 cx.entity().downgrade(),
2373 IconButton::new("trigger", IconName::Plus)
2374 .icon_size(IconSize::Small)
2375 .icon_color(Color::Muted)
2376 .selected_icon_color(Color::Accent)
2377 .selected_style(ButtonStyle::Filled),
2378 move |_window, cx| {
2379 Tooltip::with_meta("Add Context", None, "Type / to insert via keyboard", cx)
2380 },
2381 )
2382 }
2383
2384 fn render_language_model_selector(
2385 &self,
2386 window: &mut Window,
2387 cx: &mut Context<Self>,
2388 ) -> impl IntoElement {
2389 let active_model = LanguageModelRegistry::read_global(cx)
2390 .default_model()
2391 .map(|default| default.model);
2392 let model_name = match active_model {
2393 Some(model) => model.name().0,
2394 None => SharedString::from("Select Model"),
2395 };
2396
2397 let active_provider = LanguageModelRegistry::read_global(cx)
2398 .default_model()
2399 .map(|default| default.provider);
2400
2401 let provider_icon = active_provider
2402 .as_ref()
2403 .map(|p| p.icon())
2404 .unwrap_or(IconOrSvg::Icon(IconName::Ai));
2405
2406 let focus_handle = self.editor().focus_handle(cx);
2407
2408 let (color, icon) = if self.language_model_selector_menu_handle.is_deployed() {
2409 (Color::Accent, IconName::ChevronUp)
2410 } else {
2411 (Color::Muted, IconName::ChevronDown)
2412 };
2413
2414 let provider_icon_element = match provider_icon {
2415 IconOrSvg::Svg(path) => Icon::from_external_svg(path),
2416 IconOrSvg::Icon(name) => Icon::new(name),
2417 }
2418 .color(color)
2419 .size(IconSize::XSmall);
2420
2421 let show_cycle_row = self
2422 .language_model_selector
2423 .read(cx)
2424 .delegate
2425 .favorites_count()
2426 > 1;
2427
2428 let tooltip = Tooltip::element({
2429 move |_, _cx| {
2430 ModelSelectorTooltip::new(focus_handle.clone())
2431 .show_cycle_row(show_cycle_row)
2432 .into_any_element()
2433 }
2434 });
2435
2436 PickerPopoverMenu::new(
2437 self.language_model_selector.clone(),
2438 ButtonLike::new("active-model")
2439 .selected_style(ButtonStyle::Tinted(TintColor::Accent))
2440 .child(
2441 h_flex()
2442 .gap_0p5()
2443 .child(provider_icon_element)
2444 .child(
2445 Label::new(model_name)
2446 .color(color)
2447 .size(LabelSize::Small)
2448 .ml_0p5(),
2449 )
2450 .child(Icon::new(icon).color(color).size(IconSize::XSmall)),
2451 ),
2452 tooltip,
2453 gpui::Corner::BottomRight,
2454 cx,
2455 )
2456 .with_handle(self.language_model_selector_menu_handle.clone())
2457 .render(window, cx)
2458 }
2459
2460 fn render_last_error(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
2461 let last_error = self.last_error.as_ref()?;
2462
2463 Some(
2464 div()
2465 .absolute()
2466 .right_3()
2467 .bottom_12()
2468 .max_w_96()
2469 .py_2()
2470 .px_3()
2471 .elevation_2(cx)
2472 .occlude()
2473 .child(match last_error {
2474 AssistError::PaymentRequired => self.render_payment_required_error(cx),
2475 AssistError::Message(error_message) => {
2476 self.render_assist_error(error_message, cx)
2477 }
2478 })
2479 .into_any(),
2480 )
2481 }
2482
2483 fn render_payment_required_error(&self, cx: &mut Context<Self>) -> AnyElement {
2484 const ERROR_MESSAGE: &str = "Free tier exceeded. Subscribe and add payment to continue using Zed LLMs. You'll be billed at cost for tokens used.";
2485
2486 v_flex()
2487 .gap_0p5()
2488 .child(
2489 h_flex()
2490 .gap_1p5()
2491 .items_center()
2492 .child(Icon::new(IconName::XCircle).color(Color::Error))
2493 .child(Label::new("Free Usage Exceeded").weight(FontWeight::MEDIUM)),
2494 )
2495 .child(
2496 div()
2497 .id("error-message")
2498 .max_h_24()
2499 .overflow_y_scroll()
2500 .child(Label::new(ERROR_MESSAGE)),
2501 )
2502 .child(
2503 h_flex()
2504 .justify_end()
2505 .mt_1()
2506 .child(Button::new("subscribe", "Subscribe").on_click(cx.listener(
2507 |this, _, _window, cx| {
2508 this.last_error = None;
2509 cx.open_url(&zed_urls::account_url(cx));
2510 cx.notify();
2511 },
2512 )))
2513 .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2514 |this, _, _window, cx| {
2515 this.last_error = None;
2516 cx.notify();
2517 },
2518 ))),
2519 )
2520 .into_any()
2521 }
2522
2523 fn render_assist_error(
2524 &self,
2525 error_message: &SharedString,
2526 cx: &mut Context<Self>,
2527 ) -> AnyElement {
2528 v_flex()
2529 .gap_0p5()
2530 .child(
2531 h_flex()
2532 .gap_1p5()
2533 .items_center()
2534 .child(Icon::new(IconName::XCircle).color(Color::Error))
2535 .child(
2536 Label::new("Error interacting with language model")
2537 .weight(FontWeight::MEDIUM),
2538 ),
2539 )
2540 .child(
2541 div()
2542 .id("error-message")
2543 .max_h_32()
2544 .overflow_y_scroll()
2545 .child(Label::new(error_message.clone())),
2546 )
2547 .child(
2548 h_flex()
2549 .justify_end()
2550 .mt_1()
2551 .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2552 |this, _, _window, cx| {
2553 this.last_error = None;
2554 cx.notify();
2555 },
2556 ))),
2557 )
2558 .into_any()
2559 }
2560}
2561
2562/// Returns the contents of the *outermost* fenced code block that contains the given offset.
2563fn find_surrounding_code_block(snapshot: &BufferSnapshot, offset: usize) -> Option<Range<usize>> {
2564 const CODE_BLOCK_NODE: &str = "fenced_code_block";
2565 const CODE_BLOCK_CONTENT: &str = "code_fence_content";
2566
2567 let layer = snapshot.syntax_layers().next()?;
2568
2569 let root_node = layer.node();
2570 let mut cursor = root_node.walk();
2571
2572 // Go to the first child for the given offset
2573 while cursor.goto_first_child_for_byte(offset).is_some() {
2574 // If we're at the end of the node, go to the next one.
2575 // Example: if you have a fenced-code-block, and you're on the start of the line
2576 // right after the closing ```, you want to skip the fenced-code-block and
2577 // go to the next sibling.
2578 if cursor.node().end_byte() == offset {
2579 cursor.goto_next_sibling();
2580 }
2581
2582 if cursor.node().start_byte() > offset {
2583 break;
2584 }
2585
2586 // We found the fenced code block.
2587 if cursor.node().kind() == CODE_BLOCK_NODE {
2588 // Now we need to find the child node that contains the code.
2589 cursor.goto_first_child();
2590 loop {
2591 if cursor.node().kind() == CODE_BLOCK_CONTENT {
2592 return Some(cursor.node().byte_range());
2593 }
2594 if !cursor.goto_next_sibling() {
2595 break;
2596 }
2597 }
2598 }
2599 }
2600
2601 None
2602}
2603
2604fn render_thought_process_fold_icon_button(
2605 editor: WeakEntity<Editor>,
2606 status: ThoughtProcessStatus,
2607) -> Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut App) -> AnyElement> {
2608 Arc::new(move |fold_id, fold_range, _cx| {
2609 let editor = editor.clone();
2610
2611 let button = ButtonLike::new(fold_id).layer(ElevationIndex::ElevatedSurface);
2612 let button = match status {
2613 ThoughtProcessStatus::Pending => button
2614 .child(
2615 Icon::new(IconName::ToolThink)
2616 .size(IconSize::Small)
2617 .color(Color::Muted),
2618 )
2619 .child(
2620 Label::new("Thinking…").color(Color::Muted).with_animation(
2621 "pulsating-label",
2622 Animation::new(Duration::from_secs(2))
2623 .repeat()
2624 .with_easing(pulsating_between(0.4, 0.8)),
2625 |label, delta| label.alpha(delta),
2626 ),
2627 ),
2628 ThoughtProcessStatus::Completed => button
2629 .style(ButtonStyle::Filled)
2630 .child(Icon::new(IconName::ToolThink).size(IconSize::Small))
2631 .child(Label::new("Thought Process").single_line()),
2632 };
2633
2634 button
2635 .on_click(move |_, window, cx| {
2636 editor
2637 .update(cx, |editor, cx| {
2638 let buffer_start = fold_range
2639 .start
2640 .to_point(&editor.buffer().read(cx).read(cx));
2641 let buffer_row = MultiBufferRow(buffer_start.row);
2642 editor.unfold_at(buffer_row, window, cx);
2643 })
2644 .ok();
2645 })
2646 .into_any_element()
2647 })
2648}
2649
2650fn render_fold_icon_button(
2651 editor: WeakEntity<Editor>,
2652 icon_path: SharedString,
2653 label: SharedString,
2654) -> Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut App) -> AnyElement> {
2655 Arc::new(move |fold_id, fold_range, _cx| {
2656 let editor = editor.clone();
2657 ButtonLike::new(fold_id)
2658 .style(ButtonStyle::Filled)
2659 .layer(ElevationIndex::ElevatedSurface)
2660 .child(Icon::from_path(icon_path.clone()))
2661 .child(Label::new(label.clone()).single_line())
2662 .on_click(move |_, window, cx| {
2663 editor
2664 .update(cx, |editor, cx| {
2665 let buffer_start = fold_range
2666 .start
2667 .to_point(&editor.buffer().read(cx).read(cx));
2668 let buffer_row = MultiBufferRow(buffer_start.row);
2669 editor.unfold_at(buffer_row, window, cx);
2670 })
2671 .ok();
2672 })
2673 .into_any_element()
2674 })
2675}
2676
2677type ToggleFold = Arc<dyn Fn(bool, &mut Window, &mut App) + Send + Sync>;
2678
2679fn render_slash_command_output_toggle(
2680 row: MultiBufferRow,
2681 is_folded: bool,
2682 fold: ToggleFold,
2683 _window: &mut Window,
2684 _cx: &mut App,
2685) -> AnyElement {
2686 Disclosure::new(
2687 ("slash-command-output-fold-indicator", row.0 as u64),
2688 !is_folded,
2689 )
2690 .toggle_state(is_folded)
2691 .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
2692 .into_any_element()
2693}
2694
2695pub fn fold_toggle(
2696 name: &'static str,
2697) -> impl Fn(
2698 MultiBufferRow,
2699 bool,
2700 Arc<dyn Fn(bool, &mut Window, &mut App) + Send + Sync>,
2701 &mut Window,
2702 &mut App,
2703) -> AnyElement {
2704 move |row, is_folded, fold, _window, _cx| {
2705 Disclosure::new((name, row.0 as u64), !is_folded)
2706 .toggle_state(is_folded)
2707 .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
2708 .into_any_element()
2709 }
2710}
2711
2712fn quote_selection_fold_placeholder(title: String, editor: WeakEntity<Editor>) -> FoldPlaceholder {
2713 FoldPlaceholder {
2714 render: Arc::new({
2715 move |fold_id, fold_range, _cx| {
2716 let editor = editor.clone();
2717 ButtonLike::new(fold_id)
2718 .style(ButtonStyle::Filled)
2719 .layer(ElevationIndex::ElevatedSurface)
2720 .child(Icon::new(IconName::TextSnippet))
2721 .child(Label::new(title.clone()).single_line())
2722 .on_click(move |_, window, cx| {
2723 editor
2724 .update(cx, |editor, cx| {
2725 let buffer_start = fold_range
2726 .start
2727 .to_point(&editor.buffer().read(cx).read(cx));
2728 let buffer_row = MultiBufferRow(buffer_start.row);
2729 editor.unfold_at(buffer_row, window, cx);
2730 })
2731 .ok();
2732 })
2733 .into_any_element()
2734 }
2735 }),
2736 merge_adjacent: false,
2737 ..Default::default()
2738 }
2739}
2740
2741fn render_quote_selection_output_toggle(
2742 row: MultiBufferRow,
2743 is_folded: bool,
2744 fold: ToggleFold,
2745 _window: &mut Window,
2746 _cx: &mut App,
2747) -> AnyElement {
2748 Disclosure::new(("quote-selection-indicator", row.0 as u64), !is_folded)
2749 .toggle_state(is_folded)
2750 .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
2751 .into_any_element()
2752}
2753
2754fn render_pending_slash_command_gutter_decoration(
2755 row: MultiBufferRow,
2756 status: &PendingSlashCommandStatus,
2757 confirm_command: Arc<dyn Fn(&mut Window, &mut App)>,
2758) -> AnyElement {
2759 let mut icon = IconButton::new(
2760 ("slash-command-gutter-decoration", row.0),
2761 ui::IconName::TriangleRight,
2762 )
2763 .on_click(move |_e, window, cx| confirm_command(window, cx))
2764 .icon_size(ui::IconSize::Small)
2765 .size(ui::ButtonSize::None);
2766
2767 match status {
2768 PendingSlashCommandStatus::Idle => {
2769 icon = icon.icon_color(Color::Muted);
2770 }
2771 PendingSlashCommandStatus::Running { .. } => {
2772 icon = icon.toggle_state(true);
2773 }
2774 PendingSlashCommandStatus::Error(_) => icon = icon.icon_color(Color::Error),
2775 }
2776
2777 icon.into_any_element()
2778}
2779
2780#[derive(Debug, Clone, Serialize, Deserialize)]
2781struct CopyMetadata {
2782 creases: Vec<SelectedCreaseMetadata>,
2783}
2784
2785#[derive(Debug, Clone, Serialize, Deserialize)]
2786struct SelectedCreaseMetadata {
2787 range_relative_to_selection: Range<usize>,
2788 crease: CreaseMetadata,
2789}
2790
2791impl EventEmitter<EditorEvent> for TextThreadEditor {}
2792impl EventEmitter<SearchEvent> for TextThreadEditor {}
2793
2794impl Render for TextThreadEditor {
2795 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2796 let language_model_selector = self.language_model_selector_menu_handle.clone();
2797
2798 v_flex()
2799 .key_context("ContextEditor")
2800 .capture_action(cx.listener(TextThreadEditor::cancel))
2801 .capture_action(cx.listener(TextThreadEditor::save))
2802 .capture_action(cx.listener(TextThreadEditor::copy))
2803 .capture_action(cx.listener(TextThreadEditor::cut))
2804 .capture_action(cx.listener(TextThreadEditor::paste))
2805 .on_action(cx.listener(TextThreadEditor::paste_raw))
2806 .capture_action(cx.listener(TextThreadEditor::cycle_message_role))
2807 .capture_action(cx.listener(TextThreadEditor::confirm_command))
2808 .on_action(cx.listener(TextThreadEditor::assist))
2809 .on_action(cx.listener(TextThreadEditor::split))
2810 .on_action(move |_: &ToggleModelSelector, window, cx| {
2811 language_model_selector.toggle(window, cx);
2812 })
2813 .on_action(cx.listener(|this, _: &CycleFavoriteModels, window, cx| {
2814 this.language_model_selector.update(cx, |selector, cx| {
2815 selector.delegate.cycle_favorite_models(window, cx);
2816 });
2817 }))
2818 .size_full()
2819 .child(
2820 div()
2821 .flex_grow()
2822 .bg(cx.theme().colors().editor_background)
2823 .child(self.editor.clone()),
2824 )
2825 .children(self.render_last_error(cx))
2826 .child(
2827 h_flex()
2828 .relative()
2829 .py_2()
2830 .pl_1p5()
2831 .pr_2()
2832 .w_full()
2833 .justify_between()
2834 .border_t_1()
2835 .border_color(cx.theme().colors().border_variant)
2836 .bg(cx.theme().colors().editor_background)
2837 .child(
2838 h_flex()
2839 .gap_0p5()
2840 .child(self.render_inject_context_menu(cx)),
2841 )
2842 .child(
2843 h_flex()
2844 .gap_2p5()
2845 .children(self.render_remaining_tokens(cx))
2846 .child(
2847 h_flex()
2848 .gap_1()
2849 .child(self.render_language_model_selector(window, cx))
2850 .child(self.render_send_button(window, cx)),
2851 ),
2852 ),
2853 )
2854 }
2855}
2856
2857impl Focusable for TextThreadEditor {
2858 fn focus_handle(&self, cx: &App) -> FocusHandle {
2859 self.editor.focus_handle(cx)
2860 }
2861}
2862
2863impl Item for TextThreadEditor {
2864 type Event = editor::EditorEvent;
2865
2866 fn tab_content_text(&self, _detail: usize, cx: &App) -> SharedString {
2867 util::truncate_and_trailoff(&self.title(cx), MAX_TAB_TITLE_LEN).into()
2868 }
2869
2870 fn to_item_events(event: &Self::Event, mut f: impl FnMut(item::ItemEvent)) {
2871 match event {
2872 EditorEvent::Edited { .. } => {
2873 f(item::ItemEvent::Edit);
2874 }
2875 EditorEvent::TitleChanged => {
2876 f(item::ItemEvent::UpdateTab);
2877 }
2878 _ => {}
2879 }
2880 }
2881
2882 fn tab_tooltip_text(&self, cx: &App) -> Option<SharedString> {
2883 Some(self.title(cx).to_string().into())
2884 }
2885
2886 fn as_searchable(
2887 &self,
2888 handle: &Entity<Self>,
2889 _: &App,
2890 ) -> Option<Box<dyn SearchableItemHandle>> {
2891 Some(Box::new(handle.clone()))
2892 }
2893
2894 fn set_nav_history(
2895 &mut self,
2896 nav_history: pane::ItemNavHistory,
2897 window: &mut Window,
2898 cx: &mut Context<Self>,
2899 ) {
2900 self.editor.update(cx, |editor, cx| {
2901 Item::set_nav_history(editor, nav_history, window, cx)
2902 })
2903 }
2904
2905 fn navigate(
2906 &mut self,
2907 data: Arc<dyn Any + Send>,
2908 window: &mut Window,
2909 cx: &mut Context<Self>,
2910 ) -> bool {
2911 self.editor
2912 .update(cx, |editor, cx| Item::navigate(editor, data, window, cx))
2913 }
2914
2915 fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2916 self.editor
2917 .update(cx, |editor, cx| Item::deactivated(editor, window, cx))
2918 }
2919
2920 fn act_as_type<'a>(
2921 &'a self,
2922 type_id: TypeId,
2923 self_handle: &'a Entity<Self>,
2924 _: &'a App,
2925 ) -> Option<gpui::AnyEntity> {
2926 if type_id == TypeId::of::<Self>() {
2927 Some(self_handle.clone().into())
2928 } else if type_id == TypeId::of::<Editor>() {
2929 Some(self.editor.clone().into())
2930 } else {
2931 None
2932 }
2933 }
2934
2935 fn include_in_nav_history() -> bool {
2936 false
2937 }
2938}
2939
2940impl SearchableItem for TextThreadEditor {
2941 type Match = <Editor as SearchableItem>::Match;
2942
2943 fn clear_matches(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2944 self.editor.update(cx, |editor, cx| {
2945 editor.clear_matches(window, cx);
2946 });
2947 }
2948
2949 fn update_matches(
2950 &mut self,
2951 matches: &[Self::Match],
2952 active_match_index: Option<usize>,
2953 window: &mut Window,
2954 cx: &mut Context<Self>,
2955 ) {
2956 self.editor.update(cx, |editor, cx| {
2957 editor.update_matches(matches, active_match_index, window, cx)
2958 });
2959 }
2960
2961 fn query_suggestion(&mut self, window: &mut Window, cx: &mut Context<Self>) -> String {
2962 self.editor
2963 .update(cx, |editor, cx| editor.query_suggestion(window, cx))
2964 }
2965
2966 fn activate_match(
2967 &mut self,
2968 index: usize,
2969 matches: &[Self::Match],
2970 window: &mut Window,
2971 cx: &mut Context<Self>,
2972 ) {
2973 self.editor.update(cx, |editor, cx| {
2974 editor.activate_match(index, matches, window, cx);
2975 });
2976 }
2977
2978 fn select_matches(
2979 &mut self,
2980 matches: &[Self::Match],
2981 window: &mut Window,
2982 cx: &mut Context<Self>,
2983 ) {
2984 self.editor
2985 .update(cx, |editor, cx| editor.select_matches(matches, window, cx));
2986 }
2987
2988 fn replace(
2989 &mut self,
2990 identifier: &Self::Match,
2991 query: &project::search::SearchQuery,
2992 window: &mut Window,
2993 cx: &mut Context<Self>,
2994 ) {
2995 self.editor.update(cx, |editor, cx| {
2996 editor.replace(identifier, query, window, cx)
2997 });
2998 }
2999
3000 fn find_matches(
3001 &mut self,
3002 query: Arc<project::search::SearchQuery>,
3003 window: &mut Window,
3004 cx: &mut Context<Self>,
3005 ) -> Task<Vec<Self::Match>> {
3006 self.editor
3007 .update(cx, |editor, cx| editor.find_matches(query, window, cx))
3008 }
3009
3010 fn active_match_index(
3011 &mut self,
3012 direction: Direction,
3013 matches: &[Self::Match],
3014 window: &mut Window,
3015 cx: &mut Context<Self>,
3016 ) -> Option<usize> {
3017 self.editor.update(cx, |editor, cx| {
3018 editor.active_match_index(direction, matches, window, cx)
3019 })
3020 }
3021}
3022
3023impl FollowableItem for TextThreadEditor {
3024 fn remote_id(&self) -> Option<workspace::ViewId> {
3025 self.remote_id
3026 }
3027
3028 fn to_state_proto(&self, window: &mut Window, cx: &mut App) -> Option<proto::view::Variant> {
3029 let context_id = self.text_thread.read(cx).id().to_proto();
3030 let editor_proto = self
3031 .editor
3032 .update(cx, |editor, cx| editor.to_state_proto(window, cx));
3033 Some(proto::view::Variant::ContextEditor(
3034 proto::view::ContextEditor {
3035 context_id,
3036 editor: if let Some(proto::view::Variant::Editor(proto)) = editor_proto {
3037 Some(proto)
3038 } else {
3039 None
3040 },
3041 },
3042 ))
3043 }
3044
3045 fn from_state_proto(
3046 workspace: Entity<Workspace>,
3047 id: workspace::ViewId,
3048 state: &mut Option<proto::view::Variant>,
3049 window: &mut Window,
3050 cx: &mut App,
3051 ) -> Option<Task<Result<Entity<Self>>>> {
3052 let proto::view::Variant::ContextEditor(_) = state.as_ref()? else {
3053 return None;
3054 };
3055 let Some(proto::view::Variant::ContextEditor(state)) = state.take() else {
3056 unreachable!()
3057 };
3058
3059 let text_thread_id = TextThreadId::from_proto(state.context_id);
3060 let editor_state = state.editor?;
3061
3062 let project = workspace.read(cx).project().clone();
3063 let agent_panel_delegate = <dyn AgentPanelDelegate>::try_global(cx)?;
3064
3065 let text_thread_editor_task = workspace.update(cx, |workspace, cx| {
3066 agent_panel_delegate.open_remote_text_thread(workspace, text_thread_id, window, cx)
3067 });
3068
3069 Some(window.spawn(cx, async move |cx| {
3070 let text_thread_editor = text_thread_editor_task.await?;
3071 text_thread_editor
3072 .update_in(cx, |text_thread_editor, window, cx| {
3073 text_thread_editor.remote_id = Some(id);
3074 text_thread_editor.editor.update(cx, |editor, cx| {
3075 editor.apply_update_proto(
3076 &project,
3077 proto::update_view::Variant::Editor(proto::update_view::Editor {
3078 selections: editor_state.selections,
3079 pending_selection: editor_state.pending_selection,
3080 scroll_top_anchor: editor_state.scroll_top_anchor,
3081 scroll_x: editor_state.scroll_y,
3082 scroll_y: editor_state.scroll_y,
3083 ..Default::default()
3084 }),
3085 window,
3086 cx,
3087 )
3088 })
3089 })?
3090 .await?;
3091 Ok(text_thread_editor)
3092 }))
3093 }
3094
3095 fn to_follow_event(event: &Self::Event) -> Option<item::FollowEvent> {
3096 Editor::to_follow_event(event)
3097 }
3098
3099 fn add_event_to_update_proto(
3100 &self,
3101 event: &Self::Event,
3102 update: &mut Option<proto::update_view::Variant>,
3103 window: &mut Window,
3104 cx: &mut App,
3105 ) -> bool {
3106 self.editor.update(cx, |editor, cx| {
3107 editor.add_event_to_update_proto(event, update, window, cx)
3108 })
3109 }
3110
3111 fn apply_update_proto(
3112 &mut self,
3113 project: &Entity<Project>,
3114 message: proto::update_view::Variant,
3115 window: &mut Window,
3116 cx: &mut Context<Self>,
3117 ) -> Task<Result<()>> {
3118 self.editor.update(cx, |editor, cx| {
3119 editor.apply_update_proto(project, message, window, cx)
3120 })
3121 }
3122
3123 fn is_project_item(&self, _window: &Window, _cx: &App) -> bool {
3124 true
3125 }
3126
3127 fn set_leader_id(
3128 &mut self,
3129 leader_id: Option<CollaboratorId>,
3130 window: &mut Window,
3131 cx: &mut Context<Self>,
3132 ) {
3133 self.editor
3134 .update(cx, |editor, cx| editor.set_leader_id(leader_id, window, cx))
3135 }
3136
3137 fn dedup(&self, existing: &Self, _window: &Window, cx: &App) -> Option<item::Dedup> {
3138 if existing.text_thread.read(cx).id() == self.text_thread.read(cx).id() {
3139 Some(item::Dedup::KeepExisting)
3140 } else {
3141 None
3142 }
3143 }
3144}
3145
3146enum PendingSlashCommand {}
3147
3148fn invoked_slash_command_fold_placeholder(
3149 command_id: InvokedSlashCommandId,
3150 text_thread: WeakEntity<TextThread>,
3151) -> FoldPlaceholder {
3152 FoldPlaceholder {
3153 constrain_width: false,
3154 merge_adjacent: false,
3155 render: Arc::new(move |fold_id, _, cx| {
3156 let Some(text_thread) = text_thread.upgrade() else {
3157 return Empty.into_any();
3158 };
3159
3160 let Some(command) = text_thread.read(cx).invoked_slash_command(&command_id) else {
3161 return Empty.into_any();
3162 };
3163
3164 h_flex()
3165 .id(fold_id)
3166 .px_1()
3167 .ml_6()
3168 .gap_2()
3169 .bg(cx.theme().colors().surface_background)
3170 .rounded_sm()
3171 .child(Label::new(format!("/{}", command.name)))
3172 .map(|parent| match &command.status {
3173 InvokedSlashCommandStatus::Running(_) => {
3174 parent.child(Icon::new(IconName::ArrowCircle).with_rotate_animation(4))
3175 }
3176 InvokedSlashCommandStatus::Error(message) => parent.child(
3177 Label::new(format!("error: {message}"))
3178 .single_line()
3179 .color(Color::Error),
3180 ),
3181 InvokedSlashCommandStatus::Finished => parent,
3182 })
3183 .into_any_element()
3184 }),
3185 type_tag: Some(TypeId::of::<PendingSlashCommand>()),
3186 }
3187}
3188
3189enum TokenState {
3190 NoTokensLeft {
3191 max_token_count: u64,
3192 token_count: u64,
3193 },
3194 HasMoreTokens {
3195 max_token_count: u64,
3196 token_count: u64,
3197 over_warn_threshold: bool,
3198 },
3199}
3200
3201fn token_state(text_thread: &Entity<TextThread>, cx: &App) -> Option<TokenState> {
3202 const WARNING_TOKEN_THRESHOLD: f32 = 0.8;
3203
3204 let model = LanguageModelRegistry::read_global(cx)
3205 .default_model()?
3206 .model;
3207 let token_count = text_thread.read(cx).token_count()?;
3208 let max_token_count = model.max_token_count();
3209 let token_state = if max_token_count.saturating_sub(token_count) == 0 {
3210 TokenState::NoTokensLeft {
3211 max_token_count,
3212 token_count,
3213 }
3214 } else {
3215 let over_warn_threshold =
3216 token_count as f32 / max_token_count as f32 >= WARNING_TOKEN_THRESHOLD;
3217 TokenState::HasMoreTokens {
3218 max_token_count,
3219 token_count,
3220 over_warn_threshold,
3221 }
3222 };
3223 Some(token_state)
3224}
3225
3226fn size_for_image(data: &RenderImage, max_size: Size<Pixels>) -> Size<Pixels> {
3227 let image_size = data
3228 .size(0)
3229 .map(|dimension| Pixels::from(u32::from(dimension)));
3230 let image_ratio = image_size.width / image_size.height;
3231 let bounds_ratio = max_size.width / max_size.height;
3232
3233 if image_size.width > max_size.width || image_size.height > max_size.height {
3234 if bounds_ratio > image_ratio {
3235 size(
3236 image_size.width * (max_size.height / image_size.height),
3237 max_size.height,
3238 )
3239 } else {
3240 size(
3241 max_size.width,
3242 image_size.height * (max_size.width / image_size.width),
3243 )
3244 }
3245 } else {
3246 size(image_size.width, image_size.height)
3247 }
3248}
3249
3250pub fn humanize_token_count(count: u64) -> String {
3251 match count {
3252 0..=999 => count.to_string(),
3253 1000..=9999 => {
3254 let thousands = count / 1000;
3255 let hundreds = (count % 1000 + 50) / 100;
3256 if hundreds == 0 {
3257 format!("{}k", thousands)
3258 } else if hundreds == 10 {
3259 format!("{}k", thousands + 1)
3260 } else {
3261 format!("{}.{}k", thousands, hundreds)
3262 }
3263 }
3264 1_000_000..=9_999_999 => {
3265 let millions = count / 1_000_000;
3266 let hundred_thousands = (count % 1_000_000 + 50_000) / 100_000;
3267 if hundred_thousands == 0 {
3268 format!("{}M", millions)
3269 } else if hundred_thousands == 10 {
3270 format!("{}M", millions + 1)
3271 } else {
3272 format!("{}.{}M", millions, hundred_thousands)
3273 }
3274 }
3275 10_000_000.. => format!("{}M", (count + 500_000) / 1_000_000),
3276 _ => format!("{}k", (count + 500) / 1000),
3277 }
3278}
3279
3280pub fn make_lsp_adapter_delegate(
3281 project: &Entity<Project>,
3282 cx: &mut App,
3283) -> Result<Option<Arc<dyn LspAdapterDelegate>>> {
3284 project.update(cx, |project, cx| {
3285 // TODO: Find the right worktree.
3286 let Some(worktree) = project.worktrees(cx).next() else {
3287 return Ok(None::<Arc<dyn LspAdapterDelegate>>);
3288 };
3289 let http_client = project.client().http_client();
3290 project.lsp_store().update(cx, |_, cx| {
3291 Ok(Some(LocalLspAdapterDelegate::new(
3292 project.languages().clone(),
3293 project.environment(),
3294 cx.weak_entity(),
3295 &worktree,
3296 http_client,
3297 project.fs().clone(),
3298 cx,
3299 ) as Arc<dyn LspAdapterDelegate>))
3300 })
3301 })
3302}
3303
3304#[cfg(test)]
3305mod tests {
3306 use super::*;
3307 use editor::{MultiBufferOffset, SelectionEffects};
3308 use fs::FakeFs;
3309 use gpui::{App, TestAppContext, VisualTestContext};
3310 use indoc::indoc;
3311 use language::{Buffer, LanguageRegistry};
3312 use pretty_assertions::assert_eq;
3313 use prompt_store::PromptBuilder;
3314 use text::OffsetRangeExt;
3315 use unindent::Unindent;
3316 use util::path;
3317
3318 #[gpui::test]
3319 async fn test_copy_paste_whole_message(cx: &mut TestAppContext) {
3320 let (context, text_thread_editor, mut cx) = setup_text_thread_editor_text(vec![
3321 (Role::User, "What is the Zed editor?"),
3322 (
3323 Role::Assistant,
3324 "Zed is a modern, high-performance code editor designed from the ground up for speed and collaboration.",
3325 ),
3326 (Role::User, ""),
3327 ],cx).await;
3328
3329 // Select & Copy whole user message
3330 assert_copy_paste_text_thread_editor(
3331 &text_thread_editor,
3332 message_range(&context, 0, &mut cx),
3333 indoc! {"
3334 What is the Zed editor?
3335 Zed is a modern, high-performance code editor designed from the ground up for speed and collaboration.
3336 What is the Zed editor?
3337 "},
3338 &mut cx,
3339 );
3340
3341 // Select & Copy whole assistant message
3342 assert_copy_paste_text_thread_editor(
3343 &text_thread_editor,
3344 message_range(&context, 1, &mut cx),
3345 indoc! {"
3346 What is the Zed editor?
3347 Zed is a modern, high-performance code editor designed from the ground up for speed and collaboration.
3348 What is the Zed editor?
3349 Zed is a modern, high-performance code editor designed from the ground up for speed and collaboration.
3350 "},
3351 &mut cx,
3352 );
3353 }
3354
3355 #[gpui::test]
3356 async fn test_copy_paste_no_selection(cx: &mut TestAppContext) {
3357 let (context, text_thread_editor, mut cx) = setup_text_thread_editor_text(
3358 vec![
3359 (Role::User, "user1"),
3360 (Role::Assistant, "assistant1"),
3361 (Role::Assistant, "assistant2"),
3362 (Role::User, ""),
3363 ],
3364 cx,
3365 )
3366 .await;
3367
3368 // Copy and paste first assistant message
3369 let message_2_range = message_range(&context, 1, &mut cx);
3370 assert_copy_paste_text_thread_editor(
3371 &text_thread_editor,
3372 message_2_range.start..message_2_range.start,
3373 indoc! {"
3374 user1
3375 assistant1
3376 assistant2
3377 assistant1
3378 "},
3379 &mut cx,
3380 );
3381
3382 // Copy and cut second assistant message
3383 let message_3_range = message_range(&context, 2, &mut cx);
3384 assert_copy_paste_text_thread_editor(
3385 &text_thread_editor,
3386 message_3_range.start..message_3_range.start,
3387 indoc! {"
3388 user1
3389 assistant1
3390 assistant2
3391 assistant1
3392 assistant2
3393 "},
3394 &mut cx,
3395 );
3396 }
3397
3398 #[gpui::test]
3399 fn test_find_code_blocks(cx: &mut App) {
3400 let markdown = languages::language("markdown", tree_sitter_md::LANGUAGE.into());
3401
3402 let buffer = cx.new(|cx| {
3403 let text = r#"
3404 line 0
3405 line 1
3406 ```rust
3407 fn main() {}
3408 ```
3409 line 5
3410 line 6
3411 line 7
3412 ```go
3413 func main() {}
3414 ```
3415 line 11
3416 ```
3417 this is plain text code block
3418 ```
3419
3420 ```go
3421 func another() {}
3422 ```
3423 line 19
3424 "#
3425 .unindent();
3426 let mut buffer = Buffer::local(text, cx);
3427 buffer.set_language(Some(markdown.clone()), cx);
3428 buffer
3429 });
3430 let snapshot = buffer.read(cx).snapshot();
3431
3432 let code_blocks = vec![
3433 Point::new(3, 0)..Point::new(4, 0),
3434 Point::new(9, 0)..Point::new(10, 0),
3435 Point::new(13, 0)..Point::new(14, 0),
3436 Point::new(17, 0)..Point::new(18, 0),
3437 ]
3438 .into_iter()
3439 .map(|range| snapshot.point_to_offset(range.start)..snapshot.point_to_offset(range.end))
3440 .collect::<Vec<_>>();
3441
3442 let expected_results = vec![
3443 (0, None),
3444 (1, None),
3445 (2, Some(code_blocks[0].clone())),
3446 (3, Some(code_blocks[0].clone())),
3447 (4, Some(code_blocks[0].clone())),
3448 (5, None),
3449 (6, None),
3450 (7, None),
3451 (8, Some(code_blocks[1].clone())),
3452 (9, Some(code_blocks[1].clone())),
3453 (10, Some(code_blocks[1].clone())),
3454 (11, None),
3455 (12, Some(code_blocks[2].clone())),
3456 (13, Some(code_blocks[2].clone())),
3457 (14, Some(code_blocks[2].clone())),
3458 (15, None),
3459 (16, Some(code_blocks[3].clone())),
3460 (17, Some(code_blocks[3].clone())),
3461 (18, Some(code_blocks[3].clone())),
3462 (19, None),
3463 ];
3464
3465 for (row, expected) in expected_results {
3466 let offset = snapshot.point_to_offset(Point::new(row, 0));
3467 let range = find_surrounding_code_block(&snapshot, offset);
3468 assert_eq!(range, expected, "unexpected result on row {:?}", row);
3469 }
3470 }
3471
3472 async fn setup_text_thread_editor_text(
3473 messages: Vec<(Role, &str)>,
3474 cx: &mut TestAppContext,
3475 ) -> (
3476 Entity<TextThread>,
3477 Entity<TextThreadEditor>,
3478 VisualTestContext,
3479 ) {
3480 cx.update(init_test);
3481
3482 let fs = FakeFs::new(cx.executor());
3483 let text_thread = create_text_thread_with_messages(messages, cx);
3484
3485 let project = Project::test(fs.clone(), [path!("/test").as_ref()], cx).await;
3486 let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
3487 let workspace = window.root(cx).unwrap();
3488 let mut cx = VisualTestContext::from_window(*window, cx);
3489
3490 let text_thread_editor = window
3491 .update(&mut cx, |_, window, cx| {
3492 cx.new(|cx| {
3493 TextThreadEditor::for_text_thread(
3494 text_thread.clone(),
3495 fs,
3496 workspace.downgrade(),
3497 project,
3498 None,
3499 window,
3500 cx,
3501 )
3502 })
3503 })
3504 .unwrap();
3505
3506 (text_thread, text_thread_editor, cx)
3507 }
3508
3509 fn message_range(
3510 text_thread: &Entity<TextThread>,
3511 message_ix: usize,
3512 cx: &mut TestAppContext,
3513 ) -> Range<MultiBufferOffset> {
3514 let range = text_thread.update(cx, |text_thread, cx| {
3515 text_thread
3516 .messages(cx)
3517 .nth(message_ix)
3518 .unwrap()
3519 .anchor_range
3520 .to_offset(&text_thread.buffer().read(cx).snapshot())
3521 });
3522 MultiBufferOffset(range.start)..MultiBufferOffset(range.end)
3523 }
3524
3525 fn assert_copy_paste_text_thread_editor<T: editor::ToOffset>(
3526 text_thread_editor: &Entity<TextThreadEditor>,
3527 range: Range<T>,
3528 expected_text: &str,
3529 cx: &mut VisualTestContext,
3530 ) {
3531 text_thread_editor.update_in(cx, |text_thread_editor, window, cx| {
3532 text_thread_editor.editor.update(cx, |editor, cx| {
3533 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
3534 s.select_ranges([range])
3535 });
3536 });
3537
3538 text_thread_editor.copy(&Default::default(), window, cx);
3539
3540 text_thread_editor.editor.update(cx, |editor, cx| {
3541 editor.move_to_end(&Default::default(), window, cx);
3542 });
3543
3544 text_thread_editor.paste(&Default::default(), window, cx);
3545
3546 text_thread_editor.editor.update(cx, |editor, cx| {
3547 assert_eq!(editor.text(cx), expected_text);
3548 });
3549 });
3550 }
3551
3552 fn create_text_thread_with_messages(
3553 mut messages: Vec<(Role, &str)>,
3554 cx: &mut TestAppContext,
3555 ) -> Entity<TextThread> {
3556 let registry = Arc::new(LanguageRegistry::test(cx.executor()));
3557 let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3558 cx.new(|cx| {
3559 let mut text_thread = TextThread::local(
3560 registry,
3561 prompt_builder.clone(),
3562 Arc::new(SlashCommandWorkingSet::default()),
3563 cx,
3564 );
3565 let mut message_1 = text_thread.messages(cx).next().unwrap();
3566 let (role, text) = messages.remove(0);
3567
3568 loop {
3569 if role == message_1.role {
3570 text_thread.buffer().update(cx, |buffer, cx| {
3571 buffer.edit([(message_1.offset_range, text)], None, cx);
3572 });
3573 break;
3574 }
3575 let mut ids = HashSet::default();
3576 ids.insert(message_1.id);
3577 text_thread.cycle_message_roles(ids, cx);
3578 message_1 = text_thread.messages(cx).next().unwrap();
3579 }
3580
3581 let mut last_message_id = message_1.id;
3582 for (role, text) in messages {
3583 text_thread.insert_message_after(last_message_id, role, MessageStatus::Done, cx);
3584 let message = text_thread.messages(cx).last().unwrap();
3585 last_message_id = message.id;
3586 text_thread.buffer().update(cx, |buffer, cx| {
3587 buffer.edit([(message.offset_range, text)], None, cx);
3588 })
3589 }
3590
3591 text_thread
3592 })
3593 }
3594
3595 fn init_test(cx: &mut App) {
3596 let settings_store = SettingsStore::test(cx);
3597 prompt_store::init(cx);
3598 editor::init(cx);
3599 LanguageModelRegistry::test(cx);
3600 cx.set_global(settings_store);
3601
3602 theme::init(theme::LoadThemes::JustBase, cx);
3603 }
3604
3605 #[gpui::test]
3606 async fn test_quote_terminal_text(cx: &mut TestAppContext) {
3607 let (_context, text_thread_editor, mut cx) =
3608 setup_text_thread_editor_text(vec![(Role::User, "")], cx).await;
3609
3610 let terminal_output = "$ ls -la\ntotal 0\ndrwxr-xr-x 2 user user 40 Jan 1 00:00 .";
3611
3612 text_thread_editor.update_in(&mut cx, |text_thread_editor, window, cx| {
3613 text_thread_editor.quote_terminal_text(terminal_output.to_string(), window, cx);
3614
3615 text_thread_editor.editor.update(cx, |editor, cx| {
3616 let text = editor.text(cx);
3617 // The text should contain the terminal output wrapped in a code block
3618 assert!(
3619 text.contains(&format!("```console\n{}\n```", terminal_output)),
3620 "Terminal text should be wrapped in code block. Got: {}",
3621 text
3622 );
3623 });
3624 });
3625 }
3626}