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