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