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