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