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::{
8 AnimatedLabel, MaxModeTooltip,
9 preview::{AgentPreview, UsageCallout},
10};
11use buffer_diff::BufferDiff;
12use client::UserStore;
13use collections::{HashMap, HashSet};
14use editor::actions::{MoveUp, Paste};
15use editor::{
16 AnchorRangeExt, ContextMenuOptions, ContextMenuPlacement, Editor, EditorElement, EditorEvent,
17 EditorMode, EditorStyle, MultiBuffer,
18};
19use feature_flags::{FeatureFlagAppExt, NewBillingFeatureFlag};
20use file_icons::FileIcons;
21use fs::Fs;
22use futures::future::Shared;
23use futures::{FutureExt as _, future};
24use gpui::{
25 Animation, AnimationExt, App, ClipboardEntry, Entity, EventEmitter, Focusable, Subscription,
26 Task, TextStyle, WeakEntity, linear_color_stop, linear_gradient, point, pulsating_between,
27};
28use language::{Buffer, Language};
29use language_model::{ConfiguredModel, LanguageModelRequestMessage, MessageContent, RequestUsage};
30use language_model_selector::ToggleModelSelector;
31use multi_buffer;
32use project::Project;
33use prompt_store::PromptStore;
34use proto::Plan;
35use settings::Settings;
36use std::time::Duration;
37use theme::ThemeSettings;
38use ui::{Disclosure, DocumentationSide, KeyBinding, PopoverMenuHandle, Tooltip, prelude::*};
39use util::{ResultExt as _, maybe};
40use workspace::dock::DockPosition;
41use workspace::{CollaboratorId, Workspace};
42use zed_llm_client::CompletionMode;
43
44use crate::context_picker::{ContextPicker, ContextPickerCompletionProvider, crease_for_mention};
45use crate::context_store::ContextStore;
46use crate::context_strip::{ContextStrip, ContextStripEvent, SuggestContextKind};
47use crate::profile_selector::ProfileSelector;
48use crate::thread::{MessageCrease, Thread, TokenUsageRatio};
49use crate::thread_store::{TextThreadStore, ThreadStore};
50use crate::{
51 ActiveThread, AgentDiffPane, Chat, ExpandMessageEditor, Follow, NewThread, OpenAgentDiff,
52 RemoveAllContext, ToggleContextPicker, ToggleProfileSelector, register_agent_preview,
53};
54
55#[derive(RegisterComponent)]
56pub struct MessageEditor {
57 thread: Entity<Thread>,
58 incompatible_tools_state: Entity<IncompatibleToolsState>,
59 editor: Entity<Editor>,
60 workspace: WeakEntity<Workspace>,
61 project: Entity<Project>,
62 user_store: Entity<UserStore>,
63 context_store: Entity<ContextStore>,
64 prompt_store: Option<Entity<PromptStore>>,
65 context_strip: Entity<ContextStrip>,
66 context_picker_menu_handle: PopoverMenuHandle<ContextPicker>,
67 model_selector: Entity<AssistantModelSelector>,
68 last_loaded_context: Option<ContextLoadResult>,
69 load_context_task: Option<Shared<Task<()>>>,
70 profile_selector: Entity<ProfileSelector>,
71 edits_expanded: bool,
72 editor_is_expanded: bool,
73 last_estimated_token_count: Option<usize>,
74 update_token_count_task: Option<Task<()>>,
75 _subscriptions: Vec<Subscription>,
76}
77
78const MAX_EDITOR_LINES: usize = 8;
79
80pub(crate) fn create_editor(
81 workspace: WeakEntity<Workspace>,
82 context_store: WeakEntity<ContextStore>,
83 thread_store: WeakEntity<ThreadStore>,
84 text_thread_store: WeakEntity<TextThreadStore>,
85 window: &mut Window,
86 cx: &mut App,
87) -> Entity<Editor> {
88 let language = Language::new(
89 language::LanguageConfig {
90 completion_query_characters: HashSet::from_iter(['.', '-', '_', '@']),
91 ..Default::default()
92 },
93 None,
94 );
95
96 let editor = cx.new(|cx| {
97 let buffer = cx.new(|cx| Buffer::local("", cx).with_language(Arc::new(language), cx));
98 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
99 let mut editor = Editor::new(
100 editor::EditorMode::AutoHeight {
101 max_lines: MAX_EDITOR_LINES,
102 },
103 buffer,
104 None,
105 window,
106 cx,
107 );
108 editor.set_placeholder_text("Message the agent – @ to include context", cx);
109 editor.set_show_indent_guides(false, cx);
110 editor.set_soft_wrap();
111 editor.set_context_menu_options(ContextMenuOptions {
112 min_entries_visible: 12,
113 max_entries_visible: 12,
114 placement: Some(ContextMenuPlacement::Above),
115 });
116 editor.register_addon(ContextCreasesAddon::new());
117 editor
118 });
119
120 let editor_entity = editor.downgrade();
121 editor.update(cx, |editor, _| {
122 editor.set_completion_provider(Some(Box::new(ContextPickerCompletionProvider::new(
123 workspace,
124 context_store,
125 Some(thread_store),
126 Some(text_thread_store),
127 editor_entity,
128 None,
129 ))));
130 });
131 editor
132}
133
134fn documentation_side(position: DockPosition) -> DocumentationSide {
135 match position {
136 DockPosition::Left => DocumentationSide::Right,
137 DockPosition::Bottom => DocumentationSide::Left,
138 DockPosition::Right => DocumentationSide::Left,
139 }
140}
141
142impl MessageEditor {
143 pub fn new(
144 fs: Arc<dyn Fs>,
145 workspace: WeakEntity<Workspace>,
146 user_store: Entity<UserStore>,
147 context_store: Entity<ContextStore>,
148 prompt_store: Option<Entity<PromptStore>>,
149 thread_store: WeakEntity<ThreadStore>,
150 text_thread_store: WeakEntity<TextThreadStore>,
151 thread: Entity<Thread>,
152 dock_position: DockPosition,
153 window: &mut Window,
154 cx: &mut Context<Self>,
155 ) -> Self {
156 let context_picker_menu_handle = PopoverMenuHandle::default();
157 let model_selector_menu_handle = PopoverMenuHandle::default();
158
159 let editor = create_editor(
160 workspace.clone(),
161 context_store.downgrade(),
162 thread_store.clone(),
163 text_thread_store.clone(),
164 window,
165 cx,
166 );
167
168 let context_strip = cx.new(|cx| {
169 ContextStrip::new(
170 context_store.clone(),
171 workspace.clone(),
172 Some(thread_store.clone()),
173 Some(text_thread_store.clone()),
174 context_picker_menu_handle.clone(),
175 SuggestContextKind::File,
176 window,
177 cx,
178 )
179 });
180
181 let incompatible_tools =
182 cx.new(|cx| IncompatibleToolsState::new(thread.read(cx).tools().clone(), cx));
183
184 let subscriptions = vec![
185 cx.subscribe_in(&context_strip, window, Self::handle_context_strip_event),
186 cx.subscribe(&editor, |this, _, event, cx| match event {
187 EditorEvent::BufferEdited => this.handle_message_changed(cx),
188 _ => {}
189 }),
190 cx.observe(&context_store, |this, _, cx| {
191 // When context changes, reload it for token counting.
192 let _ = this.reload_context(cx);
193 }),
194 cx.observe(&thread.read(cx).action_log().clone(), |_, _, cx| {
195 cx.notify()
196 }),
197 ];
198
199 let model_selector = cx.new(|cx| {
200 AssistantModelSelector::new(
201 fs.clone(),
202 model_selector_menu_handle,
203 editor.focus_handle(cx),
204 ModelType::Default(thread.clone()),
205 window,
206 cx,
207 )
208 });
209
210 Self {
211 editor: editor.clone(),
212 project: thread.read(cx).project().clone(),
213 user_store,
214 thread,
215 incompatible_tools_state: incompatible_tools.clone(),
216 workspace,
217 context_store,
218 prompt_store,
219 context_strip,
220 context_picker_menu_handle,
221 load_context_task: None,
222 last_loaded_context: None,
223 model_selector,
224 edits_expanded: false,
225 editor_is_expanded: false,
226 profile_selector: cx.new(|cx| {
227 ProfileSelector::new(
228 fs,
229 thread_store,
230 editor.focus_handle(cx),
231 documentation_side(dock_position),
232 cx,
233 )
234 }),
235 last_estimated_token_count: None,
236 update_token_count_task: None,
237 _subscriptions: subscriptions,
238 }
239 }
240
241 pub fn context_store(&self) -> &Entity<ContextStore> {
242 &self.context_store
243 }
244
245 pub fn expand_message_editor(
246 &mut self,
247 _: &ExpandMessageEditor,
248 _window: &mut Window,
249 cx: &mut Context<Self>,
250 ) {
251 self.set_editor_is_expanded(!self.editor_is_expanded, cx);
252 }
253
254 fn set_editor_is_expanded(&mut self, is_expanded: bool, cx: &mut Context<Self>) {
255 self.editor_is_expanded = is_expanded;
256 self.editor.update(cx, |editor, _| {
257 if self.editor_is_expanded {
258 editor.set_mode(EditorMode::Full {
259 scale_ui_elements_with_buffer_font_size: false,
260 show_active_line_background: false,
261 sized_by_content: false,
262 })
263 } else {
264 editor.set_mode(EditorMode::AutoHeight {
265 max_lines: MAX_EDITOR_LINES,
266 })
267 }
268 });
269 cx.notify();
270 }
271
272 fn toggle_context_picker(
273 &mut self,
274 _: &ToggleContextPicker,
275 window: &mut Window,
276 cx: &mut Context<Self>,
277 ) {
278 self.context_picker_menu_handle.toggle(window, cx);
279 }
280
281 pub fn remove_all_context(
282 &mut self,
283 _: &RemoveAllContext,
284 _window: &mut Window,
285 cx: &mut Context<Self>,
286 ) {
287 self.context_store.update(cx, |store, _cx| store.clear());
288 cx.notify();
289 }
290
291 fn chat(&mut self, _: &Chat, window: &mut Window, cx: &mut Context<Self>) {
292 if self.is_editor_empty(cx) {
293 return;
294 }
295
296 self.thread.update(cx, |thread, cx| {
297 thread.cancel_editing(cx);
298 });
299
300 if self.thread.read(cx).is_generating() {
301 self.stop_current_and_send_new_message(window, cx);
302 return;
303 }
304
305 self.set_editor_is_expanded(false, cx);
306 self.send_to_model(window, cx);
307
308 cx.notify();
309 }
310
311 fn is_editor_empty(&self, cx: &App) -> bool {
312 self.editor.read(cx).text(cx).trim().is_empty()
313 }
314
315 fn send_to_model(&mut self, window: &mut Window, cx: &mut Context<Self>) {
316 let Some(ConfiguredModel { model, provider }) = self
317 .thread
318 .update(cx, |thread, cx| thread.get_or_init_configured_model(cx))
319 else {
320 return;
321 };
322
323 if provider.must_accept_terms(cx) {
324 cx.notify();
325 return;
326 }
327
328 let (user_message, user_message_creases) = self.editor.update(cx, |editor, cx| {
329 let creases = extract_message_creases(editor, cx);
330 let text = editor.text(cx);
331 editor.clear(window, cx);
332 (text, creases)
333 });
334
335 self.last_estimated_token_count.take();
336 cx.emit(MessageEditorEvent::EstimatedTokenCount);
337
338 let thread = self.thread.clone();
339 let git_store = self.project.read(cx).git_store().clone();
340 let checkpoint = git_store.update(cx, |git_store, cx| git_store.checkpoint(cx));
341 let context_task = self.reload_context(cx);
342 let window_handle = window.window_handle();
343
344 cx.spawn(async move |_this, cx| {
345 let (checkpoint, loaded_context) = future::join(checkpoint, context_task).await;
346 let loaded_context = loaded_context.unwrap_or_default();
347
348 thread
349 .update(cx, |thread, cx| {
350 thread.insert_user_message(
351 user_message,
352 loaded_context,
353 checkpoint.ok(),
354 user_message_creases,
355 cx,
356 );
357 })
358 .log_err();
359
360 thread
361 .update(cx, |thread, cx| {
362 thread.advance_prompt_id();
363 thread.send_to_model(model, Some(window_handle), cx);
364 })
365 .log_err();
366 })
367 .detach();
368 }
369
370 fn stop_current_and_send_new_message(&mut self, window: &mut Window, cx: &mut Context<Self>) {
371 self.thread.update(cx, |thread, cx| {
372 thread.cancel_editing(cx);
373 });
374
375 let cancelled = self.thread.update(cx, |thread, cx| {
376 thread.cancel_last_completion(Some(window.window_handle()), cx)
377 });
378
379 if cancelled {
380 self.set_editor_is_expanded(false, cx);
381 self.send_to_model(window, cx);
382 }
383 }
384
385 fn handle_context_strip_event(
386 &mut self,
387 _context_strip: &Entity<ContextStrip>,
388 event: &ContextStripEvent,
389 window: &mut Window,
390 cx: &mut Context<Self>,
391 ) {
392 match event {
393 ContextStripEvent::PickerDismissed
394 | ContextStripEvent::BlurredEmpty
395 | ContextStripEvent::BlurredDown => {
396 let editor_focus_handle = self.editor.focus_handle(cx);
397 window.focus(&editor_focus_handle);
398 }
399 ContextStripEvent::BlurredUp => {}
400 }
401 }
402
403 fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
404 if self.context_picker_menu_handle.is_deployed() {
405 cx.propagate();
406 } else {
407 self.context_strip.focus_handle(cx).focus(window);
408 }
409 }
410
411 fn paste(&mut self, _: &Paste, _: &mut Window, cx: &mut Context<Self>) {
412 let images = cx
413 .read_from_clipboard()
414 .map(|item| {
415 item.into_entries()
416 .filter_map(|entry| {
417 if let ClipboardEntry::Image(image) = entry {
418 Some(image)
419 } else {
420 None
421 }
422 })
423 .collect::<Vec<_>>()
424 })
425 .unwrap_or_default();
426
427 if images.is_empty() {
428 return;
429 }
430 cx.stop_propagation();
431
432 self.context_store.update(cx, |store, cx| {
433 for image in images {
434 store.add_image_instance(Arc::new(image), cx);
435 }
436 });
437 }
438
439 fn handle_review_click(&mut self, window: &mut Window, cx: &mut Context<Self>) {
440 self.edits_expanded = true;
441 AgentDiffPane::deploy(self.thread.clone(), self.workspace.clone(), window, cx).log_err();
442 cx.notify();
443 }
444
445 fn handle_file_click(
446 &self,
447 buffer: Entity<Buffer>,
448 window: &mut Window,
449 cx: &mut Context<Self>,
450 ) {
451 if let Ok(diff) =
452 AgentDiffPane::deploy(self.thread.clone(), self.workspace.clone(), window, cx)
453 {
454 let path_key = multi_buffer::PathKey::for_buffer(&buffer, cx);
455 diff.update(cx, |diff, cx| diff.move_to_path(path_key, window, cx));
456 }
457 }
458
459 fn render_max_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
460 if !cx.has_flag::<NewBillingFeatureFlag>() {
461 return None;
462 }
463
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 div()
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 if !cx.has_flag::<NewBillingFeatureFlag>() {
1071 return None;
1072 }
1073
1074 let user_store = self.user_store.read(cx);
1075
1076 let ubb_enable = user_store
1077 .usage_based_billing_enabled()
1078 .map_or(false, |enabled| enabled);
1079
1080 if ubb_enable {
1081 return None;
1082 }
1083
1084 let plan = user_store
1085 .current_plan()
1086 .map(|plan| match plan {
1087 Plan::Free => zed_llm_client::Plan::Free,
1088 Plan::ZedPro => zed_llm_client::Plan::ZedPro,
1089 Plan::ZedProTrial => zed_llm_client::Plan::ZedProTrial,
1090 })
1091 .unwrap_or(zed_llm_client::Plan::Free);
1092 let usage = self.thread.read(cx).last_usage().or_else(|| {
1093 maybe!({
1094 let amount = user_store.model_request_usage_amount()?;
1095 let limit = user_store.model_request_usage_limit()?.variant?;
1096
1097 Some(RequestUsage {
1098 amount: amount as i32,
1099 limit: match limit {
1100 proto::usage_limit::Variant::Limited(limited) => {
1101 zed_llm_client::UsageLimit::Limited(limited.limit as i32)
1102 }
1103 proto::usage_limit::Variant::Unlimited(_) => {
1104 zed_llm_client::UsageLimit::Unlimited
1105 }
1106 },
1107 })
1108 })
1109 })?;
1110
1111 Some(
1112 div()
1113 .child(UsageCallout::new(plan, usage))
1114 .line_height(line_height),
1115 )
1116 }
1117
1118 fn render_token_limit_callout(
1119 &self,
1120 line_height: Pixels,
1121 token_usage_ratio: TokenUsageRatio,
1122 cx: &mut Context<Self>,
1123 ) -> Option<Div> {
1124 if !cx.has_flag::<NewBillingFeatureFlag>() {
1125 return None;
1126 }
1127
1128 let title = if token_usage_ratio == TokenUsageRatio::Exceeded {
1129 "Thread reached the token limit"
1130 } else {
1131 "Thread reaching the token limit soon"
1132 };
1133
1134 let message = "Start a new thread from a summary to continue the conversation.";
1135
1136 let icon = if token_usage_ratio == TokenUsageRatio::Exceeded {
1137 Icon::new(IconName::X)
1138 .color(Color::Error)
1139 .size(IconSize::XSmall)
1140 } else {
1141 Icon::new(IconName::Warning)
1142 .color(Color::Warning)
1143 .size(IconSize::XSmall)
1144 };
1145
1146 Some(
1147 div()
1148 .child(ui::Callout::multi_line(
1149 title,
1150 message,
1151 icon,
1152 "Start New Thread",
1153 Box::new(cx.listener(|this, _, window, cx| {
1154 let from_thread_id = Some(this.thread.read(cx).id().clone());
1155 window.dispatch_action(Box::new(NewThread { from_thread_id }), cx);
1156 })),
1157 ))
1158 .line_height(line_height),
1159 )
1160 }
1161
1162 pub fn last_estimated_token_count(&self) -> Option<usize> {
1163 self.last_estimated_token_count
1164 }
1165
1166 pub fn is_waiting_to_update_token_count(&self) -> bool {
1167 self.update_token_count_task.is_some()
1168 }
1169
1170 fn reload_context(&mut self, cx: &mut Context<Self>) -> Task<Option<ContextLoadResult>> {
1171 let load_task = cx.spawn(async move |this, cx| {
1172 let Ok(load_task) = this.update(cx, |this, cx| {
1173 let new_context = this.context_store.read_with(cx, |context_store, cx| {
1174 context_store.new_context_for_thread(this.thread.read(cx), None)
1175 });
1176 load_context(new_context, &this.project, &this.prompt_store, cx)
1177 }) else {
1178 return;
1179 };
1180 let result = load_task.await;
1181 this.update(cx, |this, cx| {
1182 this.last_loaded_context = Some(result);
1183 this.load_context_task = None;
1184 this.message_or_context_changed(false, cx);
1185 })
1186 .ok();
1187 });
1188 // Replace existing load task, if any, causing it to be cancelled.
1189 let load_task = load_task.shared();
1190 self.load_context_task = Some(load_task.clone());
1191 cx.spawn(async move |this, cx| {
1192 load_task.await;
1193 this.read_with(cx, |this, _cx| this.last_loaded_context.clone())
1194 .ok()
1195 .flatten()
1196 })
1197 }
1198
1199 fn handle_message_changed(&mut self, cx: &mut Context<Self>) {
1200 self.message_or_context_changed(true, cx);
1201 }
1202
1203 fn message_or_context_changed(&mut self, debounce: bool, cx: &mut Context<Self>) {
1204 cx.emit(MessageEditorEvent::Changed);
1205 self.update_token_count_task.take();
1206
1207 let Some(model) = self.thread.read(cx).configured_model() else {
1208 self.last_estimated_token_count.take();
1209 return;
1210 };
1211
1212 let editor = self.editor.clone();
1213
1214 self.update_token_count_task = Some(cx.spawn(async move |this, cx| {
1215 if debounce {
1216 cx.background_executor()
1217 .timer(Duration::from_millis(200))
1218 .await;
1219 }
1220
1221 let token_count = if let Some(task) = this
1222 .update(cx, |this, cx| {
1223 let loaded_context = this
1224 .last_loaded_context
1225 .as_ref()
1226 .map(|context_load_result| &context_load_result.loaded_context);
1227 let message_text = editor.read(cx).text(cx);
1228
1229 if message_text.is_empty()
1230 && loaded_context.map_or(true, |loaded_context| loaded_context.is_empty())
1231 {
1232 return None;
1233 }
1234
1235 let mut request_message = LanguageModelRequestMessage {
1236 role: language_model::Role::User,
1237 content: Vec::new(),
1238 cache: false,
1239 };
1240
1241 if let Some(loaded_context) = loaded_context {
1242 loaded_context.add_to_request_message(&mut request_message);
1243 }
1244
1245 if !message_text.is_empty() {
1246 request_message
1247 .content
1248 .push(MessageContent::Text(message_text));
1249 }
1250
1251 let request = language_model::LanguageModelRequest {
1252 thread_id: None,
1253 prompt_id: None,
1254 mode: None,
1255 messages: vec![request_message],
1256 tools: vec![],
1257 stop: vec![],
1258 temperature: None,
1259 };
1260
1261 Some(model.model.count_tokens(request, cx))
1262 })
1263 .ok()
1264 .flatten()
1265 {
1266 task.await.log_err()
1267 } else {
1268 Some(0)
1269 };
1270
1271 this.update(cx, |this, cx| {
1272 if let Some(token_count) = token_count {
1273 this.last_estimated_token_count = Some(token_count);
1274 cx.emit(MessageEditorEvent::EstimatedTokenCount);
1275 }
1276 this.update_token_count_task.take();
1277 })
1278 .ok();
1279 }));
1280 }
1281
1282 pub fn set_dock_position(&mut self, position: DockPosition, cx: &mut Context<Self>) {
1283 self.profile_selector.update(cx, |profile_selector, cx| {
1284 profile_selector.set_documentation_side(documentation_side(position), cx)
1285 });
1286 }
1287}
1288
1289pub fn extract_message_creases(
1290 editor: &mut Editor,
1291 cx: &mut Context<'_, Editor>,
1292) -> Vec<MessageCrease> {
1293 let buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
1294 let mut contexts_by_crease_id = editor
1295 .addon_mut::<ContextCreasesAddon>()
1296 .map(std::mem::take)
1297 .unwrap_or_default()
1298 .into_inner()
1299 .into_iter()
1300 .flat_map(|(key, creases)| {
1301 let context = key.0;
1302 creases
1303 .into_iter()
1304 .map(move |(id, _)| (id, context.clone()))
1305 })
1306 .collect::<HashMap<_, _>>();
1307 // Filter the addon's list of creases based on what the editor reports,
1308 // since the addon might have removed creases in it.
1309 let creases = editor.display_map.update(cx, |display_map, cx| {
1310 display_map
1311 .snapshot(cx)
1312 .crease_snapshot
1313 .creases()
1314 .filter_map(|(id, crease)| {
1315 Some((
1316 id,
1317 (
1318 crease.range().to_offset(&buffer_snapshot),
1319 crease.metadata()?.clone(),
1320 ),
1321 ))
1322 })
1323 .map(|(id, (range, metadata))| {
1324 let context = contexts_by_crease_id.remove(&id);
1325 MessageCrease {
1326 range,
1327 metadata,
1328 context,
1329 }
1330 })
1331 .collect()
1332 });
1333 creases
1334}
1335
1336impl EventEmitter<MessageEditorEvent> for MessageEditor {}
1337
1338pub enum MessageEditorEvent {
1339 EstimatedTokenCount,
1340 Changed,
1341}
1342
1343impl Focusable for MessageEditor {
1344 fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
1345 self.editor.focus_handle(cx)
1346 }
1347}
1348
1349impl Render for MessageEditor {
1350 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1351 let thread = self.thread.read(cx);
1352 let token_usage_ratio = thread
1353 .total_token_usage()
1354 .map_or(TokenUsageRatio::Normal, |total_token_usage| {
1355 total_token_usage.ratio()
1356 });
1357
1358 let action_log = self.thread.read(cx).action_log();
1359 let changed_buffers = action_log.read(cx).changed_buffers(cx);
1360
1361 let line_height = TextSize::Small.rems(cx).to_pixels(window.rem_size()) * 1.5;
1362
1363 v_flex()
1364 .size_full()
1365 .when(changed_buffers.len() > 0, |parent| {
1366 parent.child(self.render_changed_buffers(&changed_buffers, window, cx))
1367 })
1368 .child(self.render_editor(window, cx))
1369 .children({
1370 let usage_callout = self.render_usage_callout(line_height, cx);
1371
1372 if usage_callout.is_some() {
1373 usage_callout
1374 } else if token_usage_ratio != TokenUsageRatio::Normal {
1375 self.render_token_limit_callout(line_height, token_usage_ratio, cx)
1376 } else {
1377 None
1378 }
1379 })
1380 }
1381}
1382
1383pub fn insert_message_creases(
1384 editor: &mut Editor,
1385 message_creases: &[MessageCrease],
1386 context_store: &Entity<ContextStore>,
1387 window: &mut Window,
1388 cx: &mut Context<'_, Editor>,
1389) {
1390 let buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
1391 let creases = message_creases
1392 .iter()
1393 .map(|crease| {
1394 let start = buffer_snapshot.anchor_after(crease.range.start);
1395 let end = buffer_snapshot.anchor_before(crease.range.end);
1396 crease_for_mention(
1397 crease.metadata.label.clone(),
1398 crease.metadata.icon_path.clone(),
1399 start..end,
1400 cx.weak_entity(),
1401 )
1402 })
1403 .collect::<Vec<_>>();
1404 let ids = editor.insert_creases(creases.clone(), cx);
1405 editor.fold_creases(creases, false, window, cx);
1406 if let Some(addon) = editor.addon_mut::<ContextCreasesAddon>() {
1407 for (crease, id) in message_creases.iter().zip(ids) {
1408 if let Some(context) = crease.context.as_ref() {
1409 let key = AgentContextKey(context.clone());
1410 addon.add_creases(
1411 context_store,
1412 key,
1413 vec![(id, crease.metadata.label.clone())],
1414 cx,
1415 );
1416 }
1417 }
1418 }
1419}
1420impl Component for MessageEditor {
1421 fn scope() -> ComponentScope {
1422 ComponentScope::Agent
1423 }
1424
1425 fn description() -> Option<&'static str> {
1426 Some(
1427 "The composer experience of the Agent Panel. This interface handles context, composing messages, switching profiles, models and more.",
1428 )
1429 }
1430}
1431
1432impl AgentPreview for MessageEditor {
1433 fn agent_preview(
1434 workspace: WeakEntity<Workspace>,
1435 active_thread: Entity<ActiveThread>,
1436 window: &mut Window,
1437 cx: &mut App,
1438 ) -> Option<AnyElement> {
1439 if let Some(workspace) = workspace.upgrade() {
1440 let fs = workspace.read(cx).app_state().fs.clone();
1441 let user_store = workspace.read(cx).app_state().user_store.clone();
1442 let project = workspace.read(cx).project().clone();
1443 let weak_project = project.downgrade();
1444 let context_store = cx.new(|_cx| ContextStore::new(weak_project, None));
1445 let active_thread = active_thread.read(cx);
1446 let thread = active_thread.thread().clone();
1447 let thread_store = active_thread.thread_store().clone();
1448 let text_thread_store = active_thread.text_thread_store().clone();
1449
1450 let default_message_editor = cx.new(|cx| {
1451 MessageEditor::new(
1452 fs,
1453 workspace.downgrade(),
1454 user_store,
1455 context_store,
1456 None,
1457 thread_store.downgrade(),
1458 text_thread_store.downgrade(),
1459 thread,
1460 DockPosition::Left,
1461 window,
1462 cx,
1463 )
1464 });
1465
1466 Some(
1467 v_flex()
1468 .gap_4()
1469 .children(vec![single_example(
1470 "Default Message Editor",
1471 div()
1472 .w(px(540.))
1473 .pt_12()
1474 .bg(cx.theme().colors().panel_background)
1475 .border_1()
1476 .border_color(cx.theme().colors().border)
1477 .child(default_message_editor.clone())
1478 .into_any_element(),
1479 )])
1480 .into_any_element(),
1481 )
1482 } else {
1483 None
1484 }
1485 }
1486}
1487
1488register_agent_preview!(MessageEditor);