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