1use std::collections::BTreeMap;
2use std::sync::Arc;
3
4use crate::assistant_model_selector::{AssistantModelSelector, ModelType};
5use crate::context::{AgentContextKey, ContextCreasesAddon, ContextLoadResult, load_context};
6use crate::tool_compatibility::{IncompatibleToolsState, IncompatibleToolsTooltip};
7use crate::ui::{AgentPreview, AnimatedLabel, MaxModeTooltip};
8use buffer_diff::BufferDiff;
9use collections::{HashMap, HashSet};
10use editor::actions::{MoveUp, Paste};
11use editor::{
12 AnchorRangeExt, ContextMenuOptions, ContextMenuPlacement, Editor, EditorElement, EditorEvent,
13 EditorMode, EditorStyle, MultiBuffer,
14};
15use feature_flags::{FeatureFlagAppExt, NewBillingFeatureFlag};
16use file_icons::FileIcons;
17use fs::Fs;
18use futures::future::Shared;
19use futures::{FutureExt as _, future};
20use gpui::{
21 Animation, AnimationExt, App, ClipboardEntry, Entity, EventEmitter, Focusable, Subscription,
22 Task, TextStyle, WeakEntity, linear_color_stop, linear_gradient, point, pulsating_between,
23};
24use language::{Buffer, Language};
25use language_model::{ConfiguredModel, LanguageModelRequestMessage, MessageContent};
26use language_model_selector::ToggleModelSelector;
27use multi_buffer;
28use project::Project;
29use prompt_store::PromptStore;
30use settings::Settings;
31use std::time::Duration;
32use theme::ThemeSettings;
33use ui::{Disclosure, KeyBinding, PopoverMenuHandle, Tooltip, prelude::*};
34use util::ResultExt as _;
35use workspace::Workspace;
36use zed_llm_client::CompletionMode;
37
38use crate::context_picker::{ContextPicker, ContextPickerCompletionProvider, crease_for_mention};
39use crate::context_store::ContextStore;
40use crate::context_strip::{ContextStrip, ContextStripEvent, SuggestContextKind};
41use crate::profile_selector::ProfileSelector;
42use crate::thread::{MessageCrease, Thread, TokenUsageRatio};
43use crate::thread_store::ThreadStore;
44use crate::{
45 ActiveThread, AgentDiffPane, Chat, ExpandMessageEditor, NewThread, OpenAgentDiff,
46 RemoveAllContext, ToggleContextPicker, ToggleProfileSelector, register_agent_preview,
47};
48
49#[derive(RegisterComponent)]
50pub struct MessageEditor {
51 thread: Entity<Thread>,
52 incompatible_tools_state: Entity<IncompatibleToolsState>,
53 editor: Entity<Editor>,
54 workspace: WeakEntity<Workspace>,
55 project: Entity<Project>,
56 context_store: Entity<ContextStore>,
57 prompt_store: Option<Entity<PromptStore>>,
58 context_strip: Entity<ContextStrip>,
59 context_picker_menu_handle: PopoverMenuHandle<ContextPicker>,
60 model_selector: Entity<AssistantModelSelector>,
61 last_loaded_context: Option<ContextLoadResult>,
62 load_context_task: Option<Shared<Task<()>>>,
63 profile_selector: Entity<ProfileSelector>,
64 edits_expanded: bool,
65 editor_is_expanded: bool,
66 last_estimated_token_count: Option<usize>,
67 update_token_count_task: Option<Task<()>>,
68 _subscriptions: Vec<Subscription>,
69}
70
71const MAX_EDITOR_LINES: usize = 8;
72
73pub(crate) fn create_editor(
74 workspace: WeakEntity<Workspace>,
75 context_store: WeakEntity<ContextStore>,
76 thread_store: WeakEntity<ThreadStore>,
77 window: &mut Window,
78 cx: &mut App,
79) -> Entity<Editor> {
80 let language = Language::new(
81 language::LanguageConfig {
82 completion_query_characters: HashSet::from_iter(['.', '-', '_', '@']),
83 ..Default::default()
84 },
85 None,
86 );
87
88 let editor = cx.new(|cx| {
89 let buffer = cx.new(|cx| Buffer::local("", cx).with_language(Arc::new(language), cx));
90 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
91 let mut editor = Editor::new(
92 editor::EditorMode::AutoHeight {
93 max_lines: MAX_EDITOR_LINES,
94 },
95 buffer,
96 None,
97 window,
98 cx,
99 );
100 editor.set_placeholder_text("Ask anything, @ to mention, ↑ to select", cx);
101 editor.set_show_indent_guides(false, cx);
102 editor.set_soft_wrap();
103 editor.set_context_menu_options(ContextMenuOptions {
104 min_entries_visible: 12,
105 max_entries_visible: 12,
106 placement: Some(ContextMenuPlacement::Above),
107 });
108 editor.register_addon(ContextCreasesAddon::new());
109 editor
110 });
111
112 let editor_entity = editor.downgrade();
113 editor.update(cx, |editor, _| {
114 editor.set_completion_provider(Some(Box::new(ContextPickerCompletionProvider::new(
115 workspace,
116 context_store,
117 Some(thread_store),
118 editor_entity,
119 None,
120 ))));
121 });
122 editor
123}
124
125impl MessageEditor {
126 pub fn new(
127 fs: Arc<dyn Fs>,
128 workspace: WeakEntity<Workspace>,
129 context_store: Entity<ContextStore>,
130 prompt_store: Option<Entity<PromptStore>>,
131 thread_store: WeakEntity<ThreadStore>,
132 thread: Entity<Thread>,
133 window: &mut Window,
134 cx: &mut Context<Self>,
135 ) -> Self {
136 let context_picker_menu_handle = PopoverMenuHandle::default();
137 let model_selector_menu_handle = PopoverMenuHandle::default();
138
139 let editor = create_editor(
140 workspace.clone(),
141 context_store.downgrade(),
142 thread_store.clone(),
143 window,
144 cx,
145 );
146
147 let context_strip = cx.new(|cx| {
148 ContextStrip::new(
149 context_store.clone(),
150 workspace.clone(),
151 Some(thread_store.clone()),
152 context_picker_menu_handle.clone(),
153 SuggestContextKind::File,
154 window,
155 cx,
156 )
157 });
158
159 let incompatible_tools =
160 cx.new(|cx| IncompatibleToolsState::new(thread.read(cx).tools().clone(), cx));
161
162 let subscriptions = vec![
163 cx.subscribe_in(&context_strip, window, Self::handle_context_strip_event),
164 cx.subscribe(&editor, |this, _, event, cx| match event {
165 EditorEvent::BufferEdited => this.handle_message_changed(cx),
166 _ => {}
167 }),
168 cx.observe(&context_store, |this, _, cx| {
169 // When context changes, reload it for token counting.
170 let _ = this.reload_context(cx);
171 }),
172 cx.observe(&thread.read(cx).action_log().clone(), |_, _, cx| {
173 cx.notify()
174 }),
175 ];
176
177 let model_selector = cx.new(|cx| {
178 AssistantModelSelector::new(
179 fs.clone(),
180 model_selector_menu_handle,
181 editor.focus_handle(cx),
182 ModelType::Default(thread.clone()),
183 window,
184 cx,
185 )
186 });
187
188 Self {
189 editor: editor.clone(),
190 project: thread.read(cx).project().clone(),
191 thread,
192 incompatible_tools_state: incompatible_tools.clone(),
193 workspace,
194 context_store,
195 prompt_store,
196 context_strip,
197 context_picker_menu_handle,
198 load_context_task: None,
199 last_loaded_context: None,
200 model_selector,
201 edits_expanded: false,
202 editor_is_expanded: false,
203 profile_selector: cx
204 .new(|cx| ProfileSelector::new(fs, thread_store, editor.focus_handle(cx), cx)),
205 last_estimated_token_count: None,
206 update_token_count_task: None,
207 _subscriptions: subscriptions,
208 }
209 }
210
211 pub fn context_store(&self) -> &Entity<ContextStore> {
212 &self.context_store
213 }
214
215 pub fn expand_message_editor(
216 &mut self,
217 _: &ExpandMessageEditor,
218 _window: &mut Window,
219 cx: &mut Context<Self>,
220 ) {
221 self.set_editor_is_expanded(!self.editor_is_expanded, cx);
222 }
223
224 fn set_editor_is_expanded(&mut self, is_expanded: bool, cx: &mut Context<Self>) {
225 self.editor_is_expanded = is_expanded;
226 self.editor.update(cx, |editor, _| {
227 if self.editor_is_expanded {
228 editor.set_mode(EditorMode::Full {
229 scale_ui_elements_with_buffer_font_size: false,
230 show_active_line_background: false,
231 sized_by_content: false,
232 })
233 } else {
234 editor.set_mode(EditorMode::AutoHeight {
235 max_lines: MAX_EDITOR_LINES,
236 })
237 }
238 });
239 cx.notify();
240 }
241
242 fn toggle_context_picker(
243 &mut self,
244 _: &ToggleContextPicker,
245 window: &mut Window,
246 cx: &mut Context<Self>,
247 ) {
248 self.context_picker_menu_handle.toggle(window, cx);
249 }
250
251 pub fn remove_all_context(
252 &mut self,
253 _: &RemoveAllContext,
254 _window: &mut Window,
255 cx: &mut Context<Self>,
256 ) {
257 self.context_store.update(cx, |store, _cx| store.clear());
258 cx.notify();
259 }
260
261 fn chat(&mut self, _: &Chat, window: &mut Window, cx: &mut Context<Self>) {
262 if self.is_editor_empty(cx) {
263 return;
264 }
265
266 self.thread.update(cx, |thread, cx| {
267 thread.cancel_editing(cx);
268 });
269
270 if self.thread.read(cx).is_generating() {
271 self.stop_current_and_send_new_message(window, cx);
272 return;
273 }
274
275 self.set_editor_is_expanded(false, cx);
276 self.send_to_model(window, cx);
277
278 cx.notify();
279 }
280
281 fn is_editor_empty(&self, cx: &App) -> bool {
282 self.editor.read(cx).text(cx).trim().is_empty()
283 }
284
285 fn send_to_model(&mut self, window: &mut Window, cx: &mut Context<Self>) {
286 let Some(ConfiguredModel { model, provider }) = self
287 .thread
288 .update(cx, |thread, cx| thread.get_or_init_configured_model(cx))
289 else {
290 return;
291 };
292
293 if provider.must_accept_terms(cx) {
294 cx.notify();
295 return;
296 }
297
298 let (user_message, user_message_creases) = self.editor.update(cx, |editor, cx| {
299 let creases = extract_message_creases(editor, cx);
300 let text = editor.text(cx);
301 editor.clear(window, cx);
302 (text, creases)
303 });
304
305 self.last_estimated_token_count.take();
306 cx.emit(MessageEditorEvent::EstimatedTokenCount);
307
308 let thread = self.thread.clone();
309 let git_store = self.project.read(cx).git_store().clone();
310 let checkpoint = git_store.update(cx, |git_store, cx| git_store.checkpoint(cx));
311 let context_task = self.reload_context(cx);
312 let window_handle = window.window_handle();
313
314 cx.spawn(async move |_this, cx| {
315 let (checkpoint, loaded_context) = future::join(checkpoint, context_task).await;
316 let loaded_context = loaded_context.unwrap_or_default();
317
318 thread
319 .update(cx, |thread, cx| {
320 thread.insert_user_message(
321 user_message,
322 loaded_context,
323 checkpoint.ok(),
324 user_message_creases,
325 cx,
326 );
327 })
328 .log_err();
329
330 thread
331 .update(cx, |thread, cx| {
332 thread.advance_prompt_id();
333 thread.send_to_model(model, Some(window_handle), cx);
334 })
335 .log_err();
336 })
337 .detach();
338 }
339
340 fn stop_current_and_send_new_message(&mut self, window: &mut Window, cx: &mut Context<Self>) {
341 self.thread.update(cx, |thread, cx| {
342 thread.cancel_editing(cx);
343 });
344
345 let cancelled = self.thread.update(cx, |thread, cx| {
346 thread.cancel_last_completion(Some(window.window_handle()), cx)
347 });
348
349 if cancelled {
350 self.set_editor_is_expanded(false, cx);
351 self.send_to_model(window, cx);
352 }
353 }
354
355 fn handle_context_strip_event(
356 &mut self,
357 _context_strip: &Entity<ContextStrip>,
358 event: &ContextStripEvent,
359 window: &mut Window,
360 cx: &mut Context<Self>,
361 ) {
362 match event {
363 ContextStripEvent::PickerDismissed
364 | ContextStripEvent::BlurredEmpty
365 | ContextStripEvent::BlurredDown => {
366 let editor_focus_handle = self.editor.focus_handle(cx);
367 window.focus(&editor_focus_handle);
368 }
369 ContextStripEvent::BlurredUp => {}
370 }
371 }
372
373 fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
374 if self.context_picker_menu_handle.is_deployed() {
375 cx.propagate();
376 } else {
377 self.context_strip.focus_handle(cx).focus(window);
378 }
379 }
380
381 fn paste(&mut self, _: &Paste, _: &mut Window, cx: &mut Context<Self>) {
382 let images = cx
383 .read_from_clipboard()
384 .map(|item| {
385 item.into_entries()
386 .filter_map(|entry| {
387 if let ClipboardEntry::Image(image) = entry {
388 Some(image)
389 } else {
390 None
391 }
392 })
393 .collect::<Vec<_>>()
394 })
395 .unwrap_or_default();
396
397 if images.is_empty() {
398 return;
399 }
400 cx.stop_propagation();
401
402 self.context_store.update(cx, |store, cx| {
403 for image in images {
404 store.add_image_instance(Arc::new(image), cx);
405 }
406 });
407 }
408
409 fn handle_review_click(&mut self, window: &mut Window, cx: &mut Context<Self>) {
410 self.edits_expanded = true;
411 AgentDiffPane::deploy(self.thread.clone(), self.workspace.clone(), window, cx).log_err();
412 cx.notify();
413 }
414
415 fn handle_file_click(
416 &self,
417 buffer: Entity<Buffer>,
418 window: &mut Window,
419 cx: &mut Context<Self>,
420 ) {
421 if let Ok(diff) =
422 AgentDiffPane::deploy(self.thread.clone(), self.workspace.clone(), window, cx)
423 {
424 let path_key = multi_buffer::PathKey::for_buffer(&buffer, cx);
425 diff.update(cx, |diff, cx| diff.move_to_path(path_key, window, cx));
426 }
427 }
428
429 fn render_max_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
430 if !cx.has_flag::<NewBillingFeatureFlag>() {
431 return None;
432 }
433
434 let thread = self.thread.read(cx);
435 let model = thread.configured_model();
436 if !model?.model.supports_max_mode() {
437 return None;
438 }
439
440 let active_completion_mode = thread.completion_mode();
441
442 Some(
443 IconButton::new("max-mode", IconName::ZedMaxMode)
444 .icon_size(IconSize::Small)
445 .icon_color(Color::Muted)
446 .toggle_state(active_completion_mode == CompletionMode::Max)
447 .on_click(cx.listener(move |this, _event, _window, cx| {
448 this.thread.update(cx, |thread, _cx| {
449 thread.set_completion_mode(match active_completion_mode {
450 CompletionMode::Max => CompletionMode::Normal,
451 CompletionMode::Normal => CompletionMode::Max,
452 });
453 });
454 }))
455 .tooltip(|_, cx| cx.new(MaxModeTooltip::new).into())
456 .into_any_element(),
457 )
458 }
459
460 fn render_editor(
461 &self,
462 font_size: Rems,
463 line_height: Pixels,
464 window: &mut Window,
465 cx: &mut Context<Self>,
466 ) -> Div {
467 let thread = self.thread.read(cx);
468 let model = thread.configured_model();
469
470 let editor_bg_color = cx.theme().colors().editor_background;
471 let is_generating = thread.is_generating();
472 let focus_handle = self.editor.focus_handle(cx);
473
474 let is_model_selected = model.is_some();
475 let is_editor_empty = self.is_editor_empty(cx);
476
477 let incompatible_tools = model
478 .as_ref()
479 .map(|model| {
480 self.incompatible_tools_state.update(cx, |state, cx| {
481 state
482 .incompatible_tools(&model.model, cx)
483 .iter()
484 .cloned()
485 .collect::<Vec<_>>()
486 })
487 })
488 .unwrap_or_default();
489
490 let is_editor_expanded = self.editor_is_expanded;
491 let expand_icon = if is_editor_expanded {
492 IconName::Minimize
493 } else {
494 IconName::Maximize
495 };
496
497 v_flex()
498 .key_context("MessageEditor")
499 .on_action(cx.listener(Self::chat))
500 .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
501 this.profile_selector
502 .read(cx)
503 .menu_handle()
504 .toggle(window, cx);
505 }))
506 .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
507 this.model_selector
508 .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
509 }))
510 .on_action(cx.listener(Self::toggle_context_picker))
511 .on_action(cx.listener(Self::remove_all_context))
512 .on_action(cx.listener(Self::move_up))
513 .on_action(cx.listener(Self::expand_message_editor))
514 .capture_action(cx.listener(Self::paste))
515 .gap_2()
516 .p_2()
517 .bg(editor_bg_color)
518 .border_t_1()
519 .border_color(cx.theme().colors().border)
520 .child(
521 h_flex()
522 .items_start()
523 .justify_between()
524 .child(self.context_strip.clone())
525 .when(focus_handle.is_focused(window), |this| {
526 this.child(
527 IconButton::new("toggle-height", expand_icon)
528 .icon_size(IconSize::XSmall)
529 .icon_color(Color::Muted)
530 .tooltip({
531 let focus_handle = focus_handle.clone();
532 move |window, cx| {
533 let expand_label = if is_editor_expanded {
534 "Minimize Message Editor".to_string()
535 } else {
536 "Expand Message Editor".to_string()
537 };
538
539 Tooltip::for_action_in(
540 expand_label,
541 &ExpandMessageEditor,
542 &focus_handle,
543 window,
544 cx,
545 )
546 }
547 })
548 .on_click(cx.listener(|_, _, window, cx| {
549 window.dispatch_action(Box::new(ExpandMessageEditor), cx);
550 })),
551 )
552 }),
553 )
554 .child(
555 v_flex()
556 .size_full()
557 .gap_4()
558 .when(is_editor_expanded, |this| {
559 this.h(vh(0.8, window)).justify_between()
560 })
561 .child(
562 div()
563 .min_h_16()
564 .when(is_editor_expanded, |this| this.h_full())
565 .child({
566 let settings = ThemeSettings::get_global(cx);
567
568 let text_style = TextStyle {
569 color: cx.theme().colors().text,
570 font_family: settings.buffer_font.family.clone(),
571 font_fallbacks: settings.buffer_font.fallbacks.clone(),
572 font_features: settings.buffer_font.features.clone(),
573 font_size: font_size.into(),
574 line_height: line_height.into(),
575 ..Default::default()
576 };
577
578 EditorElement::new(
579 &self.editor,
580 EditorStyle {
581 background: editor_bg_color,
582 local_player: cx.theme().players().local(),
583 text: text_style,
584 syntax: cx.theme().syntax().clone(),
585 ..Default::default()
586 },
587 )
588 .into_any()
589 }),
590 )
591 .child(
592 h_flex()
593 .flex_none()
594 .justify_between()
595 .child(h_flex().gap_2().child(self.profile_selector.clone()))
596 .child(
597 h_flex()
598 .gap_1()
599 .when(!incompatible_tools.is_empty(), |this| {
600 this.child(
601 IconButton::new(
602 "tools-incompatible-warning",
603 IconName::Warning,
604 )
605 .icon_color(Color::Warning)
606 .icon_size(IconSize::Small)
607 .tooltip({
608 move |_, cx| {
609 cx.new(|_| IncompatibleToolsTooltip {
610 incompatible_tools: incompatible_tools
611 .clone(),
612 })
613 .into()
614 }
615 }),
616 )
617 })
618 .children(self.render_max_mode_toggle(cx))
619 .child(self.model_selector.clone())
620 .map({
621 let focus_handle = focus_handle.clone();
622 move |parent| {
623 if is_generating {
624 parent
625 .when(is_editor_empty, |parent| {
626 parent.child(
627 IconButton::new(
628 "stop-generation",
629 IconName::StopFilled,
630 )
631 .icon_color(Color::Error)
632 .style(ButtonStyle::Tinted(
633 ui::TintColor::Error,
634 ))
635 .tooltip(move |window, cx| {
636 Tooltip::for_action(
637 "Stop Generation",
638 &editor::actions::Cancel,
639 window,
640 cx,
641 )
642 })
643 .on_click({
644 let focus_handle =
645 focus_handle.clone();
646 move |_event, window, cx| {
647 focus_handle.dispatch_action(
648 &editor::actions::Cancel,
649 window,
650 cx,
651 );
652 }
653 })
654 .with_animation(
655 "pulsating-label",
656 Animation::new(
657 Duration::from_secs(2),
658 )
659 .repeat()
660 .with_easing(pulsating_between(
661 0.4, 1.0,
662 )),
663 |icon_button, delta| {
664 icon_button.alpha(delta)
665 },
666 ),
667 )
668 })
669 .when(!is_editor_empty, |parent| {
670 parent.child(
671 IconButton::new(
672 "send-message",
673 IconName::Send,
674 )
675 .icon_color(Color::Accent)
676 .style(ButtonStyle::Filled)
677 .disabled(!is_model_selected)
678 .on_click({
679 let focus_handle =
680 focus_handle.clone();
681 move |_event, window, cx| {
682 focus_handle.dispatch_action(
683 &Chat, window, cx,
684 );
685 }
686 })
687 .tooltip(move |window, cx| {
688 Tooltip::for_action(
689 "Stop and Send New Message",
690 &Chat,
691 window,
692 cx,
693 )
694 }),
695 )
696 })
697 } else {
698 parent.child(
699 IconButton::new("send-message", IconName::Send)
700 .icon_color(Color::Accent)
701 .style(ButtonStyle::Filled)
702 .disabled(
703 is_editor_empty || !is_model_selected,
704 )
705 .on_click({
706 let focus_handle = focus_handle.clone();
707 move |_event, window, cx| {
708 focus_handle.dispatch_action(
709 &Chat, window, cx,
710 );
711 }
712 })
713 .when(
714 !is_editor_empty && is_model_selected,
715 |button| {
716 button.tooltip(move |window, cx| {
717 Tooltip::for_action(
718 "Send", &Chat, window, cx,
719 )
720 })
721 },
722 )
723 .when(is_editor_empty, |button| {
724 button.tooltip(Tooltip::text(
725 "Type a message to submit",
726 ))
727 })
728 .when(!is_model_selected, |button| {
729 button.tooltip(Tooltip::text(
730 "Select a model to continue",
731 ))
732 }),
733 )
734 }
735 }
736 }),
737 ),
738 ),
739 )
740 }
741
742 fn render_changed_buffers(
743 &self,
744 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
745 window: &mut Window,
746 cx: &mut Context<Self>,
747 ) -> Div {
748 let focus_handle = self.editor.focus_handle(cx);
749
750 let editor_bg_color = cx.theme().colors().editor_background;
751 let border_color = cx.theme().colors().border;
752 let active_color = cx.theme().colors().element_selected;
753 let bg_edit_files_disclosure = editor_bg_color.blend(active_color.opacity(0.3));
754
755 let is_edit_changes_expanded = self.edits_expanded;
756 let is_generating = self.thread.read(cx).is_generating();
757
758 v_flex()
759 .mt_1()
760 .mx_2()
761 .bg(bg_edit_files_disclosure)
762 .border_1()
763 .border_b_0()
764 .border_color(border_color)
765 .rounded_t_md()
766 .shadow(smallvec::smallvec![gpui::BoxShadow {
767 color: gpui::black().opacity(0.15),
768 offset: point(px(1.), px(-1.)),
769 blur_radius: px(3.),
770 spread_radius: px(0.),
771 }])
772 .child(
773 h_flex()
774 .id("edits-container")
775 .cursor_pointer()
776 .p_1p5()
777 .justify_between()
778 .when(is_edit_changes_expanded, |this| {
779 this.border_b_1().border_color(border_color)
780 })
781 .on_click(
782 cx.listener(|this, _, window, cx| this.handle_review_click(window, cx)),
783 )
784 .child(
785 h_flex()
786 .gap_1()
787 .child(
788 Disclosure::new("edits-disclosure", is_edit_changes_expanded)
789 .on_click(cx.listener(|this, _ev, _window, cx| {
790 this.edits_expanded = !this.edits_expanded;
791 cx.notify();
792 })),
793 )
794 .map(|this| {
795 if is_generating {
796 this.child(
797 AnimatedLabel::new(format!(
798 "Editing {} {}",
799 changed_buffers.len(),
800 if changed_buffers.len() == 1 {
801 "file"
802 } else {
803 "files"
804 }
805 ))
806 .size(LabelSize::Small),
807 )
808 } else {
809 this.child(
810 Label::new("Edits")
811 .size(LabelSize::Small)
812 .color(Color::Muted),
813 )
814 .child(
815 Label::new("•").size(LabelSize::XSmall).color(Color::Muted),
816 )
817 .child(
818 Label::new(format!(
819 "{} {}",
820 changed_buffers.len(),
821 if changed_buffers.len() == 1 {
822 "file"
823 } else {
824 "files"
825 }
826 ))
827 .size(LabelSize::Small)
828 .color(Color::Muted),
829 )
830 }
831 }),
832 )
833 .child(
834 Button::new("review", "Review Changes")
835 .label_size(LabelSize::Small)
836 .key_binding(
837 KeyBinding::for_action_in(
838 &OpenAgentDiff,
839 &focus_handle,
840 window,
841 cx,
842 )
843 .map(|kb| kb.size(rems_from_px(12.))),
844 )
845 .on_click(cx.listener(|this, _, window, cx| {
846 this.handle_review_click(window, cx)
847 })),
848 ),
849 )
850 .when(is_edit_changes_expanded, |parent| {
851 parent.child(
852 v_flex().children(changed_buffers.into_iter().enumerate().flat_map(
853 |(index, (buffer, _diff))| {
854 let file = buffer.read(cx).file()?;
855 let path = file.path();
856
857 let parent_label = path.parent().and_then(|parent| {
858 let parent_str = parent.to_string_lossy();
859
860 if parent_str.is_empty() {
861 None
862 } else {
863 Some(
864 Label::new(format!(
865 "/{}{}",
866 parent_str,
867 std::path::MAIN_SEPARATOR_STR
868 ))
869 .color(Color::Muted)
870 .size(LabelSize::XSmall)
871 .buffer_font(cx),
872 )
873 }
874 });
875
876 let name_label = path.file_name().map(|name| {
877 Label::new(name.to_string_lossy().to_string())
878 .size(LabelSize::XSmall)
879 .buffer_font(cx)
880 });
881
882 let file_icon = FileIcons::get_icon(&path, cx)
883 .map(Icon::from_path)
884 .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
885 .unwrap_or_else(|| {
886 Icon::new(IconName::File)
887 .color(Color::Muted)
888 .size(IconSize::Small)
889 });
890
891 let hover_color = cx
892 .theme()
893 .colors()
894 .element_background
895 .blend(cx.theme().colors().editor_foreground.opacity(0.025));
896
897 let overlay_gradient = linear_gradient(
898 90.,
899 linear_color_stop(editor_bg_color, 1.),
900 linear_color_stop(editor_bg_color.opacity(0.2), 0.),
901 );
902
903 let overlay_gradient_hover = linear_gradient(
904 90.,
905 linear_color_stop(hover_color, 1.),
906 linear_color_stop(hover_color.opacity(0.2), 0.),
907 );
908
909 let element = h_flex()
910 .group("edited-code")
911 .id(("file-container", index))
912 .cursor_pointer()
913 .relative()
914 .py_1()
915 .pl_2()
916 .pr_1()
917 .gap_2()
918 .justify_between()
919 .bg(cx.theme().colors().editor_background)
920 .hover(|style| style.bg(hover_color))
921 .when(index < changed_buffers.len() - 1, |parent| {
922 parent.border_color(border_color).border_b_1()
923 })
924 .child(
925 h_flex()
926 .id("file-name")
927 .pr_8()
928 .gap_1p5()
929 .max_w_full()
930 .overflow_x_scroll()
931 .child(file_icon)
932 .child(
933 h_flex()
934 .gap_0p5()
935 .children(name_label)
936 .children(parent_label),
937 ), // TODO: Implement line diff
938 // .child(Label::new("+").color(Color::Created))
939 // .child(Label::new("-").color(Color::Deleted)),
940 )
941 .child(
942 div().visible_on_hover("edited-code").child(
943 Button::new("review", "Review")
944 .label_size(LabelSize::Small)
945 .on_click({
946 let buffer = buffer.clone();
947 cx.listener(move |this, _, window, cx| {
948 this.handle_file_click(
949 buffer.clone(),
950 window,
951 cx,
952 );
953 })
954 }),
955 ),
956 )
957 .child(
958 div()
959 .id("gradient-overlay")
960 .absolute()
961 .h_5_6()
962 .w_12()
963 .bottom_0()
964 .right(px(52.))
965 .bg(overlay_gradient)
966 .group_hover("edited-code", |style| {
967 style.bg(overlay_gradient_hover)
968 }),
969 )
970 .on_click({
971 let buffer = buffer.clone();
972 cx.listener(move |this, _, window, cx| {
973 this.handle_file_click(buffer.clone(), window, cx);
974 })
975 });
976
977 Some(element)
978 },
979 )),
980 )
981 })
982 }
983
984 fn render_token_limit_callout(
985 &self,
986 line_height: Pixels,
987 token_usage_ratio: TokenUsageRatio,
988 cx: &mut Context<Self>,
989 ) -> Div {
990 let heading = if token_usage_ratio == TokenUsageRatio::Exceeded {
991 "Thread reached the token limit"
992 } else {
993 "Thread reaching the token limit soon"
994 };
995
996 h_flex()
997 .p_2()
998 .gap_2()
999 .flex_wrap()
1000 .justify_between()
1001 .bg(
1002 if token_usage_ratio == TokenUsageRatio::Exceeded {
1003 cx.theme().status().error_background.opacity(0.1)
1004 } else {
1005 cx.theme().status().warning_background.opacity(0.1)
1006 })
1007 .border_t_1()
1008 .border_color(cx.theme().colors().border)
1009 .child(
1010 h_flex()
1011 .gap_2()
1012 .items_start()
1013 .child(
1014 h_flex()
1015 .h(line_height)
1016 .justify_center()
1017 .child(
1018 if token_usage_ratio == TokenUsageRatio::Exceeded {
1019 Icon::new(IconName::X)
1020 .color(Color::Error)
1021 .size(IconSize::XSmall)
1022 } else {
1023 Icon::new(IconName::Warning)
1024 .color(Color::Warning)
1025 .size(IconSize::XSmall)
1026 }
1027 ),
1028 )
1029 .child(
1030 v_flex()
1031 .mr_auto()
1032 .child(Label::new(heading).size(LabelSize::Small))
1033 .child(
1034 Label::new(
1035 "Start a new thread from a summary to continue the conversation.",
1036 )
1037 .size(LabelSize::Small)
1038 .color(Color::Muted),
1039 ),
1040 ),
1041 )
1042 .child(
1043 Button::new("new-thread", "Start New Thread")
1044 .on_click(cx.listener(|this, _, window, cx| {
1045 let from_thread_id = Some(this.thread.read(cx).id().clone());
1046
1047 window.dispatch_action(Box::new(NewThread {
1048 from_thread_id
1049 }), cx);
1050 }))
1051 .icon(IconName::Plus)
1052 .icon_position(IconPosition::Start)
1053 .icon_size(IconSize::Small)
1054 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
1055 .label_size(LabelSize::Small),
1056 )
1057 }
1058
1059 pub fn last_estimated_token_count(&self) -> Option<usize> {
1060 self.last_estimated_token_count
1061 }
1062
1063 pub fn is_waiting_to_update_token_count(&self) -> bool {
1064 self.update_token_count_task.is_some()
1065 }
1066
1067 fn reload_context(&mut self, cx: &mut Context<Self>) -> Task<Option<ContextLoadResult>> {
1068 let load_task = cx.spawn(async move |this, cx| {
1069 let Ok(load_task) = this.update(cx, |this, cx| {
1070 let new_context = this.context_store.read_with(cx, |context_store, cx| {
1071 context_store.new_context_for_thread(this.thread.read(cx), None)
1072 });
1073 load_context(new_context, &this.project, &this.prompt_store, cx)
1074 }) else {
1075 return;
1076 };
1077 let result = load_task.await;
1078 this.update(cx, |this, cx| {
1079 this.last_loaded_context = Some(result);
1080 this.load_context_task = None;
1081 this.message_or_context_changed(false, cx);
1082 })
1083 .ok();
1084 });
1085 // Replace existing load task, if any, causing it to be cancelled.
1086 let load_task = load_task.shared();
1087 self.load_context_task = Some(load_task.clone());
1088 cx.spawn(async move |this, cx| {
1089 load_task.await;
1090 this.read_with(cx, |this, _cx| this.last_loaded_context.clone())
1091 .ok()
1092 .flatten()
1093 })
1094 }
1095
1096 fn handle_message_changed(&mut self, cx: &mut Context<Self>) {
1097 self.message_or_context_changed(true, cx);
1098 }
1099
1100 fn message_or_context_changed(&mut self, debounce: bool, cx: &mut Context<Self>) {
1101 cx.emit(MessageEditorEvent::Changed);
1102 self.update_token_count_task.take();
1103
1104 let Some(model) = self.thread.read(cx).configured_model() else {
1105 self.last_estimated_token_count.take();
1106 return;
1107 };
1108
1109 let editor = self.editor.clone();
1110
1111 self.update_token_count_task = Some(cx.spawn(async move |this, cx| {
1112 if debounce {
1113 cx.background_executor()
1114 .timer(Duration::from_millis(200))
1115 .await;
1116 }
1117
1118 let token_count = if let Some(task) = this
1119 .update(cx, |this, cx| {
1120 let loaded_context = this
1121 .last_loaded_context
1122 .as_ref()
1123 .map(|context_load_result| &context_load_result.loaded_context);
1124 let message_text = editor.read(cx).text(cx);
1125
1126 if message_text.is_empty()
1127 && loaded_context.map_or(true, |loaded_context| loaded_context.is_empty())
1128 {
1129 return None;
1130 }
1131
1132 let mut request_message = LanguageModelRequestMessage {
1133 role: language_model::Role::User,
1134 content: Vec::new(),
1135 cache: false,
1136 };
1137
1138 if let Some(loaded_context) = loaded_context {
1139 loaded_context.add_to_request_message(&mut request_message);
1140 }
1141
1142 if !message_text.is_empty() {
1143 request_message
1144 .content
1145 .push(MessageContent::Text(message_text));
1146 }
1147
1148 let request = language_model::LanguageModelRequest {
1149 thread_id: None,
1150 prompt_id: None,
1151 mode: None,
1152 messages: vec![request_message],
1153 tools: vec![],
1154 stop: vec![],
1155 temperature: None,
1156 };
1157
1158 Some(model.model.count_tokens(request, cx))
1159 })
1160 .ok()
1161 .flatten()
1162 {
1163 task.await.log_err()
1164 } else {
1165 Some(0)
1166 };
1167
1168 this.update(cx, |this, cx| {
1169 if let Some(token_count) = token_count {
1170 this.last_estimated_token_count = Some(token_count);
1171 cx.emit(MessageEditorEvent::EstimatedTokenCount);
1172 }
1173 this.update_token_count_task.take();
1174 })
1175 .ok();
1176 }));
1177 }
1178}
1179
1180pub fn extract_message_creases(
1181 editor: &mut Editor,
1182 cx: &mut Context<'_, Editor>,
1183) -> Vec<MessageCrease> {
1184 let buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
1185 let mut contexts_by_crease_id = editor
1186 .addon_mut::<ContextCreasesAddon>()
1187 .map(std::mem::take)
1188 .unwrap_or_default()
1189 .into_inner()
1190 .into_iter()
1191 .flat_map(|(key, creases)| {
1192 let context = key.0;
1193 creases
1194 .into_iter()
1195 .map(move |(id, _)| (id, context.clone()))
1196 })
1197 .collect::<HashMap<_, _>>();
1198 // Filter the addon's list of creases based on what the editor reports,
1199 // since the addon might have removed creases in it.
1200 let creases = editor.display_map.update(cx, |display_map, cx| {
1201 display_map
1202 .snapshot(cx)
1203 .crease_snapshot
1204 .creases()
1205 .filter_map(|(id, crease)| {
1206 Some((
1207 id,
1208 (
1209 crease.range().to_offset(&buffer_snapshot),
1210 crease.metadata()?.clone(),
1211 ),
1212 ))
1213 })
1214 .map(|(id, (range, metadata))| {
1215 let context = contexts_by_crease_id.remove(&id);
1216 MessageCrease {
1217 range,
1218 metadata,
1219 context,
1220 }
1221 })
1222 .collect()
1223 });
1224 creases
1225}
1226
1227impl EventEmitter<MessageEditorEvent> for MessageEditor {}
1228
1229pub enum MessageEditorEvent {
1230 EstimatedTokenCount,
1231 Changed,
1232}
1233
1234impl Focusable for MessageEditor {
1235 fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
1236 self.editor.focus_handle(cx)
1237 }
1238}
1239
1240impl Render for MessageEditor {
1241 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1242 let thread = self.thread.read(cx);
1243 let token_usage_ratio = thread
1244 .total_token_usage()
1245 .map_or(TokenUsageRatio::Normal, |total_token_usage| {
1246 total_token_usage.ratio()
1247 });
1248
1249 let action_log = self.thread.read(cx).action_log();
1250 let changed_buffers = action_log.read(cx).changed_buffers(cx);
1251
1252 let font_size = TextSize::Small.rems(cx);
1253 let line_height = font_size.to_pixels(window.rem_size()) * 1.5;
1254
1255 v_flex()
1256 .size_full()
1257 .when(changed_buffers.len() > 0, |parent| {
1258 parent.child(self.render_changed_buffers(&changed_buffers, window, cx))
1259 })
1260 .child(self.render_editor(font_size, line_height, window, cx))
1261 .when(token_usage_ratio != TokenUsageRatio::Normal, |parent| {
1262 parent.child(self.render_token_limit_callout(line_height, token_usage_ratio, cx))
1263 })
1264 }
1265}
1266
1267pub fn insert_message_creases(
1268 editor: &mut Editor,
1269 message_creases: &[MessageCrease],
1270 context_store: &Entity<ContextStore>,
1271 window: &mut Window,
1272 cx: &mut Context<'_, Editor>,
1273) {
1274 let buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
1275 let creases = message_creases
1276 .iter()
1277 .map(|crease| {
1278 let start = buffer_snapshot.anchor_after(crease.range.start);
1279 let end = buffer_snapshot.anchor_before(crease.range.end);
1280 crease_for_mention(
1281 crease.metadata.label.clone(),
1282 crease.metadata.icon_path.clone(),
1283 start..end,
1284 cx.weak_entity(),
1285 )
1286 })
1287 .collect::<Vec<_>>();
1288 let ids = editor.insert_creases(creases.clone(), cx);
1289 editor.fold_creases(creases, false, window, cx);
1290 if let Some(addon) = editor.addon_mut::<ContextCreasesAddon>() {
1291 for (crease, id) in message_creases.iter().zip(ids) {
1292 if let Some(context) = crease.context.as_ref() {
1293 let key = AgentContextKey(context.clone());
1294 addon.add_creases(
1295 context_store,
1296 key,
1297 vec![(id, crease.metadata.label.clone())],
1298 cx,
1299 );
1300 }
1301 }
1302 }
1303}
1304impl Component for MessageEditor {
1305 fn scope() -> ComponentScope {
1306 ComponentScope::Agent
1307 }
1308}
1309
1310impl AgentPreview for MessageEditor {
1311 fn agent_preview(
1312 workspace: WeakEntity<Workspace>,
1313 active_thread: Entity<ActiveThread>,
1314 thread_store: WeakEntity<ThreadStore>,
1315 window: &mut Window,
1316 cx: &mut App,
1317 ) -> Option<AnyElement> {
1318 if let Some(workspace_entity) = workspace.upgrade() {
1319 let fs = workspace_entity.read(cx).app_state().fs.clone();
1320 let weak_project = workspace_entity.read(cx).project().clone().downgrade();
1321 let context_store = cx.new(|_cx| ContextStore::new(weak_project, None));
1322 let thread = active_thread.read(cx).thread().clone();
1323
1324 let example_message_editor = cx.new(|cx| {
1325 MessageEditor::new(
1326 fs,
1327 workspace,
1328 context_store,
1329 None,
1330 thread_store,
1331 thread,
1332 window,
1333 cx,
1334 )
1335 });
1336
1337 Some(
1338 v_flex()
1339 .gap_4()
1340 .children(vec![single_example(
1341 "Default",
1342 example_message_editor.clone().into_any_element(),
1343 )])
1344 .into_any_element(),
1345 )
1346 } else {
1347 None
1348 }
1349 }
1350}
1351
1352register_agent_preview!(MessageEditor);