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