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