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