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, ToggleBurnMode, 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 pub fn toggle_burn_mode(
481 &mut self,
482 _: &ToggleBurnMode,
483 _window: &mut Window,
484 cx: &mut Context<Self>,
485 ) {
486 self.thread.update(cx, |thread, _cx| {
487 let active_completion_mode = thread.completion_mode();
488
489 thread.set_completion_mode(match active_completion_mode {
490 CompletionMode::Burn => CompletionMode::Normal,
491 CompletionMode::Normal => CompletionMode::Burn,
492 });
493 });
494 }
495
496 fn render_max_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
497 let thread = self.thread.read(cx);
498 let model = thread.configured_model();
499 if !model?.model.supports_max_mode() {
500 return None;
501 }
502
503 let active_completion_mode = thread.completion_mode();
504 let burn_mode_enabled = active_completion_mode == CompletionMode::Burn;
505 let icon = if burn_mode_enabled {
506 IconName::ZedBurnModeOn
507 } else {
508 IconName::ZedBurnMode
509 };
510
511 Some(
512 IconButton::new("burn-mode", icon)
513 .icon_size(IconSize::Small)
514 .icon_color(Color::Muted)
515 .toggle_state(burn_mode_enabled)
516 .selected_icon_color(Color::Error)
517 .on_click(cx.listener(|this, _event, window, cx| {
518 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
519 }))
520 .tooltip(move |_window, cx| {
521 cx.new(|_| MaxModeTooltip::new().selected(burn_mode_enabled))
522 .into()
523 })
524 .into_any_element(),
525 )
526 }
527
528 fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
529 let following = self
530 .workspace
531 .read_with(cx, |workspace, _| {
532 workspace.is_being_followed(CollaboratorId::Agent)
533 })
534 .unwrap_or(false);
535
536 IconButton::new("follow-agent", IconName::Crosshair)
537 .icon_size(IconSize::Small)
538 .icon_color(Color::Muted)
539 .toggle_state(following)
540 .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
541 .tooltip(move |window, cx| {
542 if following {
543 Tooltip::for_action("Stop Following Agent", &Follow, window, cx)
544 } else {
545 Tooltip::with_meta(
546 "Follow Agent",
547 Some(&Follow),
548 "Track the agent's location as it reads and edits files.",
549 window,
550 cx,
551 )
552 }
553 })
554 .on_click(cx.listener(move |this, _, window, cx| {
555 this.workspace
556 .update(cx, |workspace, cx| {
557 if following {
558 workspace.unfollow(CollaboratorId::Agent, window, cx);
559 } else {
560 workspace.follow(CollaboratorId::Agent, window, cx);
561 }
562 })
563 .ok();
564 }))
565 }
566
567 fn render_editor(&self, window: &mut Window, cx: &mut Context<Self>) -> Div {
568 let thread = self.thread.read(cx);
569 let model = thread.configured_model();
570
571 let editor_bg_color = cx.theme().colors().editor_background;
572 let is_generating = thread.is_generating();
573 let focus_handle = self.editor.focus_handle(cx);
574
575 let is_model_selected = model.is_some();
576 let is_editor_empty = self.is_editor_empty(cx);
577
578 let incompatible_tools = model
579 .as_ref()
580 .map(|model| {
581 self.incompatible_tools_state.update(cx, |state, cx| {
582 state
583 .incompatible_tools(&model.model, cx)
584 .iter()
585 .cloned()
586 .collect::<Vec<_>>()
587 })
588 })
589 .unwrap_or_default();
590
591 let is_editor_expanded = self.editor_is_expanded;
592 let expand_icon = if is_editor_expanded {
593 IconName::Minimize
594 } else {
595 IconName::Maximize
596 };
597
598 v_flex()
599 .key_context("MessageEditor")
600 .on_action(cx.listener(Self::chat))
601 .on_action(cx.listener(Self::chat_with_follow))
602 .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
603 this.profile_selector
604 .read(cx)
605 .menu_handle()
606 .toggle(window, cx);
607 }))
608 .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
609 this.model_selector
610 .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
611 }))
612 .on_action(cx.listener(Self::toggle_context_picker))
613 .on_action(cx.listener(Self::remove_all_context))
614 .on_action(cx.listener(Self::move_up))
615 .on_action(cx.listener(Self::expand_message_editor))
616 .on_action(cx.listener(Self::toggle_burn_mode))
617 .capture_action(cx.listener(Self::paste))
618 .gap_2()
619 .p_2()
620 .bg(editor_bg_color)
621 .border_t_1()
622 .border_color(cx.theme().colors().border)
623 .child(
624 h_flex()
625 .items_start()
626 .justify_between()
627 .child(self.context_strip.clone())
628 .child(
629 h_flex()
630 .gap_1()
631 .when(focus_handle.is_focused(window), |this| {
632 this.child(
633 IconButton::new("toggle-height", expand_icon)
634 .icon_size(IconSize::XSmall)
635 .icon_color(Color::Muted)
636 .tooltip({
637 let focus_handle = focus_handle.clone();
638 move |window, cx| {
639 let expand_label = if is_editor_expanded {
640 "Minimize Message Editor".to_string()
641 } else {
642 "Expand Message Editor".to_string()
643 };
644
645 Tooltip::for_action_in(
646 expand_label,
647 &ExpandMessageEditor,
648 &focus_handle,
649 window,
650 cx,
651 )
652 }
653 })
654 .on_click(cx.listener(|_, _, window, cx| {
655 window
656 .dispatch_action(Box::new(ExpandMessageEditor), cx);
657 })),
658 )
659 }),
660 ),
661 )
662 .child(
663 v_flex()
664 .size_full()
665 .gap_4()
666 .when(is_editor_expanded, |this| {
667 this.h(vh(0.8, window)).justify_between()
668 })
669 .child(
670 v_flex()
671 .min_h_16()
672 .when(is_editor_expanded, |this| this.h_full())
673 .child({
674 let settings = ThemeSettings::get_global(cx);
675 let font_size = TextSize::Small
676 .rems(cx)
677 .to_pixels(settings.agent_font_size(cx));
678 let line_height = settings.buffer_line_height.value() * font_size;
679
680 let text_style = TextStyle {
681 color: cx.theme().colors().text,
682 font_family: settings.buffer_font.family.clone(),
683 font_fallbacks: settings.buffer_font.fallbacks.clone(),
684 font_features: settings.buffer_font.features.clone(),
685 font_size: font_size.into(),
686 line_height: line_height.into(),
687 ..Default::default()
688 };
689
690 EditorElement::new(
691 &self.editor,
692 EditorStyle {
693 background: editor_bg_color,
694 local_player: cx.theme().players().local(),
695 text: text_style,
696 syntax: cx.theme().syntax().clone(),
697 ..Default::default()
698 },
699 )
700 .into_any()
701 }),
702 )
703 .child(
704 h_flex()
705 .flex_none()
706 .justify_between()
707 .child(
708 h_flex()
709 .child(self.render_follow_toggle(cx))
710 .children(self.render_max_mode_toggle(cx)),
711 )
712 .child(
713 h_flex()
714 .gap_1()
715 .when(!incompatible_tools.is_empty(), |this| {
716 this.child(
717 IconButton::new(
718 "tools-incompatible-warning",
719 IconName::Warning,
720 )
721 .icon_color(Color::Warning)
722 .icon_size(IconSize::Small)
723 .tooltip({
724 move |_, cx| {
725 cx.new(|_| IncompatibleToolsTooltip {
726 incompatible_tools: incompatible_tools
727 .clone(),
728 })
729 .into()
730 }
731 }),
732 )
733 })
734 .child(self.profile_selector.clone())
735 .child(self.model_selector.clone())
736 .map({
737 let focus_handle = focus_handle.clone();
738 move |parent| {
739 if is_generating {
740 parent
741 .when(is_editor_empty, |parent| {
742 parent.child(
743 IconButton::new(
744 "stop-generation",
745 IconName::StopFilled,
746 )
747 .icon_color(Color::Error)
748 .style(ButtonStyle::Tinted(
749 ui::TintColor::Error,
750 ))
751 .tooltip(move |window, cx| {
752 Tooltip::for_action(
753 "Stop Generation",
754 &editor::actions::Cancel,
755 window,
756 cx,
757 )
758 })
759 .on_click({
760 let focus_handle =
761 focus_handle.clone();
762 move |_event, window, cx| {
763 focus_handle.dispatch_action(
764 &editor::actions::Cancel,
765 window,
766 cx,
767 );
768 }
769 })
770 .with_animation(
771 "pulsating-label",
772 Animation::new(
773 Duration::from_secs(2),
774 )
775 .repeat()
776 .with_easing(pulsating_between(
777 0.4, 1.0,
778 )),
779 |icon_button, delta| {
780 icon_button.alpha(delta)
781 },
782 ),
783 )
784 })
785 .when(!is_editor_empty, |parent| {
786 parent.child(
787 IconButton::new(
788 "send-message",
789 IconName::Send,
790 )
791 .icon_color(Color::Accent)
792 .style(ButtonStyle::Filled)
793 .disabled(!is_model_selected)
794 .on_click({
795 let focus_handle =
796 focus_handle.clone();
797 move |_event, window, cx| {
798 focus_handle.dispatch_action(
799 &Chat, window, cx,
800 );
801 }
802 })
803 .tooltip(move |window, cx| {
804 Tooltip::for_action(
805 "Stop and Send New Message",
806 &Chat,
807 window,
808 cx,
809 )
810 }),
811 )
812 })
813 } else {
814 parent.child(
815 IconButton::new("send-message", IconName::Send)
816 .icon_color(Color::Accent)
817 .style(ButtonStyle::Filled)
818 .disabled(
819 is_editor_empty || !is_model_selected,
820 )
821 .on_click({
822 let focus_handle = focus_handle.clone();
823 move |_event, window, cx| {
824 focus_handle.dispatch_action(
825 &Chat, window, cx,
826 );
827 }
828 })
829 .when(
830 !is_editor_empty && is_model_selected,
831 |button| {
832 button.tooltip(move |window, cx| {
833 Tooltip::for_action(
834 "Send", &Chat, window, cx,
835 )
836 })
837 },
838 )
839 .when(is_editor_empty, |button| {
840 button.tooltip(Tooltip::text(
841 "Type a message to submit",
842 ))
843 })
844 .when(!is_model_selected, |button| {
845 button.tooltip(Tooltip::text(
846 "Select a model to continue",
847 ))
848 }),
849 )
850 }
851 }
852 }),
853 ),
854 ),
855 )
856 }
857
858 fn render_changed_buffers(
859 &self,
860 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
861 window: &mut Window,
862 cx: &mut Context<Self>,
863 ) -> Div {
864 let focus_handle = self.editor.focus_handle(cx);
865
866 let editor_bg_color = cx.theme().colors().editor_background;
867 let border_color = cx.theme().colors().border;
868 let active_color = cx.theme().colors().element_selected;
869 let bg_edit_files_disclosure = editor_bg_color.blend(active_color.opacity(0.3));
870
871 let is_edit_changes_expanded = self.edits_expanded;
872 let is_generating = self.thread.read(cx).is_generating();
873
874 v_flex()
875 .mt_1()
876 .mx_2()
877 .bg(bg_edit_files_disclosure)
878 .border_1()
879 .border_b_0()
880 .border_color(border_color)
881 .rounded_t_md()
882 .shadow(vec![gpui::BoxShadow {
883 color: gpui::black().opacity(0.15),
884 offset: point(px(1.), px(-1.)),
885 blur_radius: px(3.),
886 spread_radius: px(0.),
887 }])
888 .child(
889 h_flex()
890 .id("edits-container")
891 .cursor_pointer()
892 .p_1p5()
893 .justify_between()
894 .when(is_edit_changes_expanded, |this| {
895 this.border_b_1().border_color(border_color)
896 })
897 .on_click(
898 cx.listener(|this, _, window, cx| this.handle_review_click(window, cx)),
899 )
900 .child(
901 h_flex()
902 .gap_1()
903 .child(
904 Disclosure::new("edits-disclosure", is_edit_changes_expanded)
905 .on_click(cx.listener(|this, _ev, _window, cx| {
906 this.edits_expanded = !this.edits_expanded;
907 cx.notify();
908 })),
909 )
910 .map(|this| {
911 if is_generating {
912 this.child(
913 AnimatedLabel::new(format!(
914 "Editing {} {}",
915 changed_buffers.len(),
916 if changed_buffers.len() == 1 {
917 "file"
918 } else {
919 "files"
920 }
921 ))
922 .size(LabelSize::Small),
923 )
924 } else {
925 this.child(
926 Label::new("Edits")
927 .size(LabelSize::Small)
928 .color(Color::Muted),
929 )
930 .child(
931 Label::new("•").size(LabelSize::XSmall).color(Color::Muted),
932 )
933 .child(
934 Label::new(format!(
935 "{} {}",
936 changed_buffers.len(),
937 if changed_buffers.len() == 1 {
938 "file"
939 } else {
940 "files"
941 }
942 ))
943 .size(LabelSize::Small)
944 .color(Color::Muted),
945 )
946 }
947 }),
948 )
949 .child(
950 Button::new("review", "Review Changes")
951 .label_size(LabelSize::Small)
952 .key_binding(
953 KeyBinding::for_action_in(
954 &OpenAgentDiff,
955 &focus_handle,
956 window,
957 cx,
958 )
959 .map(|kb| kb.size(rems_from_px(12.))),
960 )
961 .on_click(cx.listener(|this, _, window, cx| {
962 this.handle_review_click(window, cx)
963 })),
964 ),
965 )
966 .when(is_edit_changes_expanded, |parent| {
967 parent.child(
968 v_flex().children(changed_buffers.into_iter().enumerate().flat_map(
969 |(index, (buffer, _diff))| {
970 let file = buffer.read(cx).file()?;
971 let path = file.path();
972
973 let parent_label = path.parent().and_then(|parent| {
974 let parent_str = parent.to_string_lossy();
975
976 if parent_str.is_empty() {
977 None
978 } else {
979 Some(
980 Label::new(format!(
981 "/{}{}",
982 parent_str,
983 std::path::MAIN_SEPARATOR_STR
984 ))
985 .color(Color::Muted)
986 .size(LabelSize::XSmall)
987 .buffer_font(cx),
988 )
989 }
990 });
991
992 let name_label = path.file_name().map(|name| {
993 Label::new(name.to_string_lossy().to_string())
994 .size(LabelSize::XSmall)
995 .buffer_font(cx)
996 });
997
998 let file_icon = FileIcons::get_icon(&path, cx)
999 .map(Icon::from_path)
1000 .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
1001 .unwrap_or_else(|| {
1002 Icon::new(IconName::File)
1003 .color(Color::Muted)
1004 .size(IconSize::Small)
1005 });
1006
1007 let hover_color = cx
1008 .theme()
1009 .colors()
1010 .element_background
1011 .blend(cx.theme().colors().editor_foreground.opacity(0.025));
1012
1013 let overlay_gradient = linear_gradient(
1014 90.,
1015 linear_color_stop(editor_bg_color, 1.),
1016 linear_color_stop(editor_bg_color.opacity(0.2), 0.),
1017 );
1018
1019 let overlay_gradient_hover = linear_gradient(
1020 90.,
1021 linear_color_stop(hover_color, 1.),
1022 linear_color_stop(hover_color.opacity(0.2), 0.),
1023 );
1024
1025 let element = h_flex()
1026 .group("edited-code")
1027 .id(("file-container", index))
1028 .cursor_pointer()
1029 .relative()
1030 .py_1()
1031 .pl_2()
1032 .pr_1()
1033 .gap_2()
1034 .justify_between()
1035 .bg(cx.theme().colors().editor_background)
1036 .hover(|style| style.bg(hover_color))
1037 .when(index < changed_buffers.len() - 1, |parent| {
1038 parent.border_color(border_color).border_b_1()
1039 })
1040 .child(
1041 h_flex()
1042 .id("file-name")
1043 .pr_8()
1044 .gap_1p5()
1045 .max_w_full()
1046 .overflow_x_scroll()
1047 .child(file_icon)
1048 .child(
1049 h_flex()
1050 .gap_0p5()
1051 .children(name_label)
1052 .children(parent_label),
1053 ), // TODO: Implement line diff
1054 // .child(Label::new("+").color(Color::Created))
1055 // .child(Label::new("-").color(Color::Deleted)),
1056 )
1057 .child(
1058 div().visible_on_hover("edited-code").child(
1059 Button::new("review", "Review")
1060 .label_size(LabelSize::Small)
1061 .on_click({
1062 let buffer = buffer.clone();
1063 cx.listener(move |this, _, window, cx| {
1064 this.handle_file_click(
1065 buffer.clone(),
1066 window,
1067 cx,
1068 );
1069 })
1070 }),
1071 ),
1072 )
1073 .child(
1074 div()
1075 .id("gradient-overlay")
1076 .absolute()
1077 .h_5_6()
1078 .w_12()
1079 .bottom_0()
1080 .right(px(52.))
1081 .bg(overlay_gradient)
1082 .group_hover("edited-code", |style| {
1083 style.bg(overlay_gradient_hover)
1084 }),
1085 )
1086 .on_click({
1087 let buffer = buffer.clone();
1088 cx.listener(move |this, _, window, cx| {
1089 this.handle_file_click(buffer.clone(), window, cx);
1090 })
1091 });
1092
1093 Some(element)
1094 },
1095 )),
1096 )
1097 })
1098 }
1099
1100 fn render_usage_callout(&self, line_height: Pixels, cx: &mut Context<Self>) -> Option<Div> {
1101 let is_using_zed_provider = self
1102 .thread
1103 .read(cx)
1104 .configured_model()
1105 .map_or(false, |model| {
1106 model.provider.id().0 == ZED_CLOUD_PROVIDER_ID
1107 });
1108 if !is_using_zed_provider {
1109 return None;
1110 }
1111
1112 let user_store = self.user_store.read(cx);
1113
1114 let ubb_enable = user_store
1115 .usage_based_billing_enabled()
1116 .map_or(false, |enabled| enabled);
1117
1118 if ubb_enable {
1119 return None;
1120 }
1121
1122 let plan = user_store
1123 .current_plan()
1124 .map(|plan| match plan {
1125 Plan::Free => zed_llm_client::Plan::ZedFree,
1126 Plan::ZedPro => zed_llm_client::Plan::ZedPro,
1127 Plan::ZedProTrial => zed_llm_client::Plan::ZedProTrial,
1128 })
1129 .unwrap_or(zed_llm_client::Plan::ZedFree);
1130 let usage = self.thread.read(cx).last_usage().or_else(|| {
1131 maybe!({
1132 let amount = user_store.model_request_usage_amount()?;
1133 let limit = user_store.model_request_usage_limit()?.variant?;
1134
1135 Some(RequestUsage {
1136 amount: amount as i32,
1137 limit: match limit {
1138 proto::usage_limit::Variant::Limited(limited) => {
1139 zed_llm_client::UsageLimit::Limited(limited.limit as i32)
1140 }
1141 proto::usage_limit::Variant::Unlimited(_) => {
1142 zed_llm_client::UsageLimit::Unlimited
1143 }
1144 },
1145 })
1146 })
1147 })?;
1148
1149 Some(
1150 div()
1151 .child(UsageCallout::new(plan, usage))
1152 .line_height(line_height),
1153 )
1154 }
1155
1156 fn render_token_limit_callout(
1157 &self,
1158 line_height: Pixels,
1159 token_usage_ratio: TokenUsageRatio,
1160 cx: &mut Context<Self>,
1161 ) -> Option<Div> {
1162 let title = if token_usage_ratio == TokenUsageRatio::Exceeded {
1163 "Thread reached the token limit"
1164 } else {
1165 "Thread reaching the token limit soon"
1166 };
1167
1168 let message = "Start a new thread from a summary to continue the conversation.";
1169
1170 let icon = if token_usage_ratio == TokenUsageRatio::Exceeded {
1171 Icon::new(IconName::X)
1172 .color(Color::Error)
1173 .size(IconSize::XSmall)
1174 } else {
1175 Icon::new(IconName::Warning)
1176 .color(Color::Warning)
1177 .size(IconSize::XSmall)
1178 };
1179
1180 Some(
1181 div()
1182 .child(ui::Callout::multi_line(
1183 title,
1184 message,
1185 icon,
1186 "Start New Thread",
1187 Box::new(cx.listener(|this, _, window, cx| {
1188 let from_thread_id = Some(this.thread.read(cx).id().clone());
1189 window.dispatch_action(Box::new(NewThread { from_thread_id }), cx);
1190 })),
1191 ))
1192 .line_height(line_height),
1193 )
1194 }
1195
1196 pub fn last_estimated_token_count(&self) -> Option<usize> {
1197 self.last_estimated_token_count
1198 }
1199
1200 pub fn is_waiting_to_update_token_count(&self) -> bool {
1201 self.update_token_count_task.is_some()
1202 }
1203
1204 fn reload_context(&mut self, cx: &mut Context<Self>) -> Task<Option<ContextLoadResult>> {
1205 let load_task = cx.spawn(async move |this, cx| {
1206 let Ok(load_task) = this.update(cx, |this, cx| {
1207 let new_context = this
1208 .context_store
1209 .read(cx)
1210 .new_context_for_thread(this.thread.read(cx), None);
1211 load_context(new_context, &this.project, &this.prompt_store, cx)
1212 }) else {
1213 return;
1214 };
1215 let result = load_task.await;
1216 this.update(cx, |this, cx| {
1217 this.last_loaded_context = Some(result);
1218 this.load_context_task = None;
1219 this.message_or_context_changed(false, cx);
1220 })
1221 .ok();
1222 });
1223 // Replace existing load task, if any, causing it to be cancelled.
1224 let load_task = load_task.shared();
1225 self.load_context_task = Some(load_task.clone());
1226 cx.spawn(async move |this, cx| {
1227 load_task.await;
1228 this.read_with(cx, |this, _cx| this.last_loaded_context.clone())
1229 .ok()
1230 .flatten()
1231 })
1232 }
1233
1234 fn handle_message_changed(&mut self, cx: &mut Context<Self>) {
1235 self.message_or_context_changed(true, cx);
1236 }
1237
1238 fn message_or_context_changed(&mut self, debounce: bool, cx: &mut Context<Self>) {
1239 cx.emit(MessageEditorEvent::Changed);
1240 self.update_token_count_task.take();
1241
1242 let Some(model) = self.thread.read(cx).configured_model() else {
1243 self.last_estimated_token_count.take();
1244 return;
1245 };
1246
1247 let editor = self.editor.clone();
1248
1249 self.update_token_count_task = Some(cx.spawn(async move |this, cx| {
1250 if debounce {
1251 cx.background_executor()
1252 .timer(Duration::from_millis(200))
1253 .await;
1254 }
1255
1256 let token_count = if let Some(task) = this
1257 .update(cx, |this, cx| {
1258 let loaded_context = this
1259 .last_loaded_context
1260 .as_ref()
1261 .map(|context_load_result| &context_load_result.loaded_context);
1262 let message_text = editor.read(cx).text(cx);
1263
1264 if message_text.is_empty()
1265 && loaded_context.map_or(true, |loaded_context| loaded_context.is_empty())
1266 {
1267 return None;
1268 }
1269
1270 let mut request_message = LanguageModelRequestMessage {
1271 role: language_model::Role::User,
1272 content: Vec::new(),
1273 cache: false,
1274 };
1275
1276 if let Some(loaded_context) = loaded_context {
1277 loaded_context.add_to_request_message(&mut request_message);
1278 }
1279
1280 if !message_text.is_empty() {
1281 request_message
1282 .content
1283 .push(MessageContent::Text(message_text));
1284 }
1285
1286 let request = language_model::LanguageModelRequest {
1287 thread_id: None,
1288 prompt_id: None,
1289 intent: None,
1290 mode: None,
1291 messages: vec![request_message],
1292 tools: vec![],
1293 tool_choice: None,
1294 stop: vec![],
1295 temperature: AgentSettings::temperature_for_model(&model.model, cx),
1296 };
1297
1298 Some(model.model.count_tokens(request, cx))
1299 })
1300 .ok()
1301 .flatten()
1302 {
1303 task.await.log_err()
1304 } else {
1305 Some(0)
1306 };
1307
1308 this.update(cx, |this, cx| {
1309 if let Some(token_count) = token_count {
1310 this.last_estimated_token_count = Some(token_count);
1311 cx.emit(MessageEditorEvent::EstimatedTokenCount);
1312 }
1313 this.update_token_count_task.take();
1314 })
1315 .ok();
1316 }));
1317 }
1318}
1319
1320pub fn extract_message_creases(
1321 editor: &mut Editor,
1322 cx: &mut Context<'_, Editor>,
1323) -> Vec<MessageCrease> {
1324 let buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
1325 let mut contexts_by_crease_id = editor
1326 .addon_mut::<ContextCreasesAddon>()
1327 .map(std::mem::take)
1328 .unwrap_or_default()
1329 .into_inner()
1330 .into_iter()
1331 .flat_map(|(key, creases)| {
1332 let context = key.0;
1333 creases
1334 .into_iter()
1335 .map(move |(id, _)| (id, context.clone()))
1336 })
1337 .collect::<HashMap<_, _>>();
1338 // Filter the addon's list of creases based on what the editor reports,
1339 // since the addon might have removed creases in it.
1340 let creases = editor.display_map.update(cx, |display_map, cx| {
1341 display_map
1342 .snapshot(cx)
1343 .crease_snapshot
1344 .creases()
1345 .filter_map(|(id, crease)| {
1346 Some((
1347 id,
1348 (
1349 crease.range().to_offset(&buffer_snapshot),
1350 crease.metadata()?.clone(),
1351 ),
1352 ))
1353 })
1354 .map(|(id, (range, metadata))| {
1355 let context = contexts_by_crease_id.remove(&id);
1356 MessageCrease {
1357 range,
1358 metadata,
1359 context,
1360 }
1361 })
1362 .collect()
1363 });
1364 creases
1365}
1366
1367impl EventEmitter<MessageEditorEvent> for MessageEditor {}
1368
1369pub enum MessageEditorEvent {
1370 EstimatedTokenCount,
1371 Changed,
1372}
1373
1374impl Focusable for MessageEditor {
1375 fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
1376 self.editor.focus_handle(cx)
1377 }
1378}
1379
1380impl Render for MessageEditor {
1381 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1382 let thread = self.thread.read(cx);
1383 let token_usage_ratio = thread
1384 .total_token_usage()
1385 .map_or(TokenUsageRatio::Normal, |total_token_usage| {
1386 total_token_usage.ratio()
1387 });
1388
1389 let action_log = self.thread.read(cx).action_log();
1390 let changed_buffers = action_log.read(cx).changed_buffers(cx);
1391
1392 let line_height = TextSize::Small.rems(cx).to_pixels(window.rem_size()) * 1.5;
1393
1394 v_flex()
1395 .size_full()
1396 .when(changed_buffers.len() > 0, |parent| {
1397 parent.child(self.render_changed_buffers(&changed_buffers, window, cx))
1398 })
1399 .child(self.render_editor(window, cx))
1400 .children({
1401 let usage_callout = self.render_usage_callout(line_height, cx);
1402
1403 if usage_callout.is_some() {
1404 usage_callout
1405 } else if token_usage_ratio != TokenUsageRatio::Normal {
1406 self.render_token_limit_callout(line_height, token_usage_ratio, cx)
1407 } else {
1408 None
1409 }
1410 })
1411 }
1412}
1413
1414pub fn insert_message_creases(
1415 editor: &mut Editor,
1416 message_creases: &[MessageCrease],
1417 context_store: &Entity<ContextStore>,
1418 window: &mut Window,
1419 cx: &mut Context<'_, Editor>,
1420) {
1421 let buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
1422 let creases = message_creases
1423 .iter()
1424 .map(|crease| {
1425 let start = buffer_snapshot.anchor_after(crease.range.start);
1426 let end = buffer_snapshot.anchor_before(crease.range.end);
1427 crease_for_mention(
1428 crease.metadata.label.clone(),
1429 crease.metadata.icon_path.clone(),
1430 start..end,
1431 cx.weak_entity(),
1432 )
1433 })
1434 .collect::<Vec<_>>();
1435 let ids = editor.insert_creases(creases.clone(), cx);
1436 editor.fold_creases(creases, false, window, cx);
1437 if let Some(addon) = editor.addon_mut::<ContextCreasesAddon>() {
1438 for (crease, id) in message_creases.iter().zip(ids) {
1439 if let Some(context) = crease.context.as_ref() {
1440 let key = AgentContextKey(context.clone());
1441 addon.add_creases(
1442 context_store,
1443 key,
1444 vec![(id, crease.metadata.label.clone())],
1445 cx,
1446 );
1447 }
1448 }
1449 }
1450}
1451impl Component for MessageEditor {
1452 fn scope() -> ComponentScope {
1453 ComponentScope::Agent
1454 }
1455
1456 fn description() -> Option<&'static str> {
1457 Some(
1458 "The composer experience of the Agent Panel. This interface handles context, composing messages, switching profiles, models and more.",
1459 )
1460 }
1461}
1462
1463impl AgentPreview for MessageEditor {
1464 fn agent_preview(
1465 workspace: WeakEntity<Workspace>,
1466 active_thread: Entity<ActiveThread>,
1467 window: &mut Window,
1468 cx: &mut App,
1469 ) -> Option<AnyElement> {
1470 if let Some(workspace) = workspace.upgrade() {
1471 let fs = workspace.read(cx).app_state().fs.clone();
1472 let user_store = workspace.read(cx).app_state().user_store.clone();
1473 let project = workspace.read(cx).project().clone();
1474 let weak_project = project.downgrade();
1475 let context_store = cx.new(|_cx| ContextStore::new(weak_project, None));
1476 let active_thread = active_thread.read(cx);
1477 let thread = active_thread.thread().clone();
1478 let thread_store = active_thread.thread_store().clone();
1479 let text_thread_store = active_thread.text_thread_store().clone();
1480
1481 let default_message_editor = cx.new(|cx| {
1482 MessageEditor::new(
1483 fs,
1484 workspace.downgrade(),
1485 user_store,
1486 context_store,
1487 None,
1488 thread_store.downgrade(),
1489 text_thread_store.downgrade(),
1490 thread,
1491 window,
1492 cx,
1493 )
1494 });
1495
1496 Some(
1497 v_flex()
1498 .gap_4()
1499 .children(vec![single_example(
1500 "Default Message Editor",
1501 div()
1502 .w(px(540.))
1503 .pt_12()
1504 .bg(cx.theme().colors().panel_background)
1505 .border_1()
1506 .border_color(cx.theme().colors().border)
1507 .child(default_message_editor.clone())
1508 .into_any_element(),
1509 )])
1510 .into_any_element(),
1511 )
1512 } else {
1513 None
1514 }
1515 }
1516}
1517
1518register_agent_preview!(MessageEditor);