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