1use std::collections::BTreeMap;
2use std::sync::Arc;
3
4use crate::assistant_model_selector::{AssistantModelSelector, ModelType};
5use crate::context::{ContextLoadResult, load_context};
6use crate::tool_compatibility::{IncompatibleToolsState, IncompatibleToolsTooltip};
7use crate::ui::AnimatedLabel;
8use buffer_diff::BufferDiff;
9use collections::HashSet;
10use editor::actions::{MoveUp, Paste};
11use editor::{
12 ContextMenuOptions, ContextMenuPlacement, Editor, EditorElement, EditorEvent, EditorMode,
13 EditorStyle, MultiBuffer,
14};
15use feature_flags::{FeatureFlagAppExt, NewBillingFeatureFlag};
16use file_icons::FileIcons;
17use fs::Fs;
18use futures::future::Shared;
19use futures::{FutureExt as _, future};
20use gpui::{
21 Animation, AnimationExt, App, ClipboardEntry, Entity, EventEmitter, Focusable, Subscription,
22 Task, TextStyle, WeakEntity, linear_color_stop, linear_gradient, point, pulsating_between,
23};
24use language::{Buffer, Language};
25use language_model::{ConfiguredModel, LanguageModelRequestMessage, MessageContent};
26use language_model_selector::ToggleModelSelector;
27use multi_buffer;
28use project::Project;
29use prompt_store::PromptStore;
30use settings::Settings;
31use std::time::Duration;
32use theme::ThemeSettings;
33use ui::{Disclosure, KeyBinding, PopoverMenuHandle, Tooltip, prelude::*};
34use util::ResultExt as _;
35use workspace::Workspace;
36use zed_llm_client::CompletionMode;
37
38use crate::context_picker::{ContextPicker, ContextPickerCompletionProvider};
39use crate::context_store::ContextStore;
40use crate::context_strip::{ContextStrip, ContextStripEvent, SuggestContextKind};
41use crate::profile_selector::ProfileSelector;
42use crate::thread::{Thread, TokenUsageRatio};
43use crate::thread_store::ThreadStore;
44use crate::{
45 AgentDiff, Chat, ExpandMessageEditor, NewThread, OpenAgentDiff, RemoveAllContext,
46 ToggleContextPicker, ToggleProfileSelector,
47};
48
49pub struct MessageEditor {
50 thread: Entity<Thread>,
51 incompatible_tools_state: Entity<IncompatibleToolsState>,
52 editor: Entity<Editor>,
53 workspace: WeakEntity<Workspace>,
54 project: Entity<Project>,
55 context_store: Entity<ContextStore>,
56 prompt_store: Option<Entity<PromptStore>>,
57 context_strip: Entity<ContextStrip>,
58 context_picker_menu_handle: PopoverMenuHandle<ContextPicker>,
59 model_selector: Entity<AssistantModelSelector>,
60 last_loaded_context: Option<ContextLoadResult>,
61 load_context_task: Option<Shared<Task<()>>>,
62 profile_selector: Entity<ProfileSelector>,
63 edits_expanded: bool,
64 editor_is_expanded: bool,
65 last_estimated_token_count: Option<usize>,
66 update_token_count_task: Option<Task<()>>,
67 _subscriptions: Vec<Subscription>,
68}
69
70const MAX_EDITOR_LINES: usize = 8;
71
72pub(crate) fn create_editor(
73 workspace: WeakEntity<Workspace>,
74 context_store: WeakEntity<ContextStore>,
75 thread_store: WeakEntity<ThreadStore>,
76 window: &mut Window,
77 cx: &mut App,
78) -> Entity<Editor> {
79 let language = Language::new(
80 language::LanguageConfig {
81 completion_query_characters: HashSet::from_iter(['.', '-', '_', '@']),
82 ..Default::default()
83 },
84 None,
85 );
86
87 let editor = cx.new(|cx| {
88 let buffer = cx.new(|cx| Buffer::local("", cx).with_language(Arc::new(language), cx));
89 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
90 let mut editor = Editor::new(
91 editor::EditorMode::AutoHeight {
92 max_lines: MAX_EDITOR_LINES,
93 },
94 buffer,
95 None,
96 window,
97 cx,
98 );
99 editor.set_placeholder_text("Ask anything, @ to mention, ↑ to select", cx);
100 editor.set_show_indent_guides(false, cx);
101 editor.set_soft_wrap();
102 editor.set_context_menu_options(ContextMenuOptions {
103 min_entries_visible: 12,
104 max_entries_visible: 12,
105 placement: Some(ContextMenuPlacement::Above),
106 });
107 editor
108 });
109
110 let editor_entity = editor.downgrade();
111 editor.update(cx, |editor, _| {
112 editor.set_completion_provider(Some(Box::new(ContextPickerCompletionProvider::new(
113 workspace,
114 context_store,
115 Some(thread_store),
116 editor_entity,
117 ))));
118 });
119 editor
120}
121
122impl MessageEditor {
123 pub fn new(
124 fs: Arc<dyn Fs>,
125 workspace: WeakEntity<Workspace>,
126 context_store: Entity<ContextStore>,
127 prompt_store: Option<Entity<PromptStore>>,
128 thread_store: WeakEntity<ThreadStore>,
129 thread: Entity<Thread>,
130 window: &mut Window,
131 cx: &mut Context<Self>,
132 ) -> Self {
133 let context_picker_menu_handle = PopoverMenuHandle::default();
134 let model_selector_menu_handle = PopoverMenuHandle::default();
135
136 let editor = create_editor(
137 workspace.clone(),
138 context_store.downgrade(),
139 thread_store.clone(),
140 window,
141 cx,
142 );
143
144 let context_strip = cx.new(|cx| {
145 ContextStrip::new(
146 context_store.clone(),
147 workspace.clone(),
148 Some(thread_store.clone()),
149 context_picker_menu_handle.clone(),
150 SuggestContextKind::File,
151 window,
152 cx,
153 )
154 });
155
156 let incompatible_tools =
157 cx.new(|cx| IncompatibleToolsState::new(thread.read(cx).tools().clone(), cx));
158
159 let subscriptions = vec![
160 cx.subscribe_in(&context_strip, window, Self::handle_context_strip_event),
161 cx.subscribe(&editor, |this, _, event, cx| match event {
162 EditorEvent::BufferEdited => this.handle_message_changed(cx),
163 _ => {}
164 }),
165 cx.observe(&context_store, |this, _, cx| {
166 // When context changes, reload it for token counting.
167 let _ = this.reload_context(cx);
168 }),
169 ];
170
171 let model_selector = cx.new(|cx| {
172 AssistantModelSelector::new(
173 fs.clone(),
174 model_selector_menu_handle,
175 editor.focus_handle(cx),
176 ModelType::Default(thread.clone()),
177 window,
178 cx,
179 )
180 });
181
182 Self {
183 editor: editor.clone(),
184 project: thread.read(cx).project().clone(),
185 thread,
186 incompatible_tools_state: incompatible_tools.clone(),
187 workspace,
188 context_store,
189 prompt_store,
190 context_strip,
191 context_picker_menu_handle,
192 load_context_task: None,
193 last_loaded_context: None,
194 model_selector,
195 edits_expanded: false,
196 editor_is_expanded: false,
197 profile_selector: cx
198 .new(|cx| ProfileSelector::new(fs, thread_store, editor.focus_handle(cx), cx)),
199 last_estimated_token_count: None,
200 update_token_count_task: None,
201 _subscriptions: subscriptions,
202 }
203 }
204
205 pub fn context_store(&self) -> &Entity<ContextStore> {
206 &self.context_store
207 }
208
209 pub fn expand_message_editor(
210 &mut self,
211 _: &ExpandMessageEditor,
212 _window: &mut Window,
213 cx: &mut Context<Self>,
214 ) {
215 self.set_editor_is_expanded(!self.editor_is_expanded, cx);
216 }
217
218 fn set_editor_is_expanded(&mut self, is_expanded: bool, cx: &mut Context<Self>) {
219 self.editor_is_expanded = is_expanded;
220 self.editor.update(cx, |editor, _| {
221 if self.editor_is_expanded {
222 editor.set_mode(EditorMode::Full {
223 scale_ui_elements_with_buffer_font_size: false,
224 show_active_line_background: false,
225 sized_by_content: false,
226 })
227 } else {
228 editor.set_mode(EditorMode::AutoHeight {
229 max_lines: MAX_EDITOR_LINES,
230 })
231 }
232 });
233 cx.notify();
234 }
235
236 fn toggle_context_picker(
237 &mut self,
238 _: &ToggleContextPicker,
239 window: &mut Window,
240 cx: &mut Context<Self>,
241 ) {
242 self.context_picker_menu_handle.toggle(window, cx);
243 }
244
245 pub fn remove_all_context(
246 &mut self,
247 _: &RemoveAllContext,
248 _window: &mut Window,
249 cx: &mut Context<Self>,
250 ) {
251 self.context_store.update(cx, |store, _cx| store.clear());
252 cx.notify();
253 }
254
255 fn chat(&mut self, _: &Chat, window: &mut Window, cx: &mut Context<Self>) {
256 if self.is_editor_empty(cx) {
257 return;
258 }
259
260 self.thread.update(cx, |thread, cx| {
261 thread.cancel_editing(cx);
262 });
263
264 if self.thread.read(cx).is_generating() {
265 self.stop_current_and_send_new_message(window, cx);
266 return;
267 }
268
269 self.set_editor_is_expanded(false, cx);
270 self.send_to_model(window, cx);
271
272 cx.notify();
273 }
274
275 fn is_editor_empty(&self, cx: &App) -> bool {
276 self.editor.read(cx).text(cx).trim().is_empty()
277 }
278
279 fn send_to_model(&mut self, window: &mut Window, cx: &mut Context<Self>) {
280 let Some(ConfiguredModel { model, provider }) = self
281 .thread
282 .update(cx, |thread, cx| thread.get_or_init_configured_model(cx))
283 else {
284 return;
285 };
286
287 if provider.must_accept_terms(cx) {
288 cx.notify();
289 return;
290 }
291
292 let user_message = self.editor.update(cx, |editor, cx| {
293 let text = editor.text(cx);
294 editor.clear(window, cx);
295 text
296 });
297
298 self.last_estimated_token_count.take();
299 cx.emit(MessageEditorEvent::EstimatedTokenCount);
300
301 let thread = self.thread.clone();
302 let git_store = self.project.read(cx).git_store().clone();
303 let checkpoint = git_store.update(cx, |git_store, cx| git_store.checkpoint(cx));
304 let context_task = self.reload_context(cx);
305 let window_handle = window.window_handle();
306
307 cx.spawn(async move |_this, cx| {
308 let (checkpoint, loaded_context) = future::join(checkpoint, context_task).await;
309 let loaded_context = loaded_context.unwrap_or_default();
310
311 thread
312 .update(cx, |thread, cx| {
313 thread.insert_user_message(user_message, loaded_context, checkpoint.ok(), cx);
314 })
315 .log_err();
316
317 thread
318 .update(cx, |thread, cx| {
319 thread.advance_prompt_id();
320 thread.send_to_model(model, Some(window_handle), cx);
321 })
322 .log_err();
323 })
324 .detach();
325 }
326
327 fn stop_current_and_send_new_message(&mut self, window: &mut Window, cx: &mut Context<Self>) {
328 self.thread.update(cx, |thread, cx| {
329 thread.cancel_editing(cx);
330 });
331
332 let cancelled = self.thread.update(cx, |thread, cx| {
333 thread.cancel_last_completion(Some(window.window_handle()), cx)
334 });
335
336 if cancelled {
337 self.set_editor_is_expanded(false, cx);
338 self.send_to_model(window, cx);
339 }
340 }
341
342 fn handle_context_strip_event(
343 &mut self,
344 _context_strip: &Entity<ContextStrip>,
345 event: &ContextStripEvent,
346 window: &mut Window,
347 cx: &mut Context<Self>,
348 ) {
349 match event {
350 ContextStripEvent::PickerDismissed
351 | ContextStripEvent::BlurredEmpty
352 | ContextStripEvent::BlurredDown => {
353 let editor_focus_handle = self.editor.focus_handle(cx);
354 window.focus(&editor_focus_handle);
355 }
356 ContextStripEvent::BlurredUp => {}
357 }
358 }
359
360 fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
361 if self.context_picker_menu_handle.is_deployed() {
362 cx.propagate();
363 } else {
364 self.context_strip.focus_handle(cx).focus(window);
365 }
366 }
367
368 fn paste(&mut self, _: &Paste, _: &mut Window, cx: &mut Context<Self>) {
369 let images = cx
370 .read_from_clipboard()
371 .map(|item| {
372 item.into_entries()
373 .filter_map(|entry| {
374 if let ClipboardEntry::Image(image) = entry {
375 Some(image)
376 } else {
377 None
378 }
379 })
380 .collect::<Vec<_>>()
381 })
382 .unwrap_or_default();
383
384 if images.is_empty() {
385 return;
386 }
387 cx.stop_propagation();
388
389 self.context_store.update(cx, |store, cx| {
390 for image in images {
391 store.add_image_instance(Arc::new(image), cx);
392 }
393 });
394 }
395
396 fn handle_review_click(&mut self, window: &mut Window, cx: &mut Context<Self>) {
397 self.edits_expanded = true;
398 AgentDiff::deploy(self.thread.clone(), self.workspace.clone(), window, cx).log_err();
399 cx.notify();
400 }
401
402 fn handle_file_click(
403 &self,
404 buffer: Entity<Buffer>,
405 window: &mut Window,
406 cx: &mut Context<Self>,
407 ) {
408 if let Ok(diff) = AgentDiff::deploy(self.thread.clone(), self.workspace.clone(), window, cx)
409 {
410 let path_key = multi_buffer::PathKey::for_buffer(&buffer, cx);
411 diff.update(cx, |diff, cx| diff.move_to_path(path_key, window, cx));
412 }
413 }
414
415 fn render_max_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
416 if !cx.has_flag::<NewBillingFeatureFlag>() {
417 return None;
418 }
419
420 let thread = self.thread.read(cx);
421 let model = thread.configured_model();
422 if !model?.model.supports_max_mode() {
423 return None;
424 }
425
426 let active_completion_mode = thread.completion_mode();
427
428 Some(
429 IconButton::new("max-mode", IconName::ZedMaxMode)
430 .icon_size(IconSize::Small)
431 .icon_color(Color::Muted)
432 .toggle_state(active_completion_mode == CompletionMode::Max)
433 .on_click(cx.listener(move |this, _event, _window, cx| {
434 this.thread.update(cx, |thread, _cx| {
435 thread.set_completion_mode(match active_completion_mode {
436 CompletionMode::Max => CompletionMode::Normal,
437 CompletionMode::Normal => CompletionMode::Max,
438 });
439 });
440 }))
441 .tooltip(Tooltip::text("Toggle Max Mode"))
442 .into_any_element(),
443 )
444 }
445
446 fn render_editor(
447 &self,
448 font_size: Rems,
449 line_height: Pixels,
450 window: &mut Window,
451 cx: &mut Context<Self>,
452 ) -> Div {
453 let thread = self.thread.read(cx);
454 let model = thread.configured_model();
455
456 let editor_bg_color = cx.theme().colors().editor_background;
457 let is_generating = thread.is_generating();
458 let focus_handle = self.editor.focus_handle(cx);
459
460 let is_model_selected = model.is_some();
461 let is_editor_empty = self.is_editor_empty(cx);
462
463 let incompatible_tools = model
464 .as_ref()
465 .map(|model| {
466 self.incompatible_tools_state.update(cx, |state, cx| {
467 state
468 .incompatible_tools(&model.model, cx)
469 .iter()
470 .cloned()
471 .collect::<Vec<_>>()
472 })
473 })
474 .unwrap_or_default();
475
476 let is_editor_expanded = self.editor_is_expanded;
477 let expand_icon = if is_editor_expanded {
478 IconName::Minimize
479 } else {
480 IconName::Maximize
481 };
482
483 v_flex()
484 .key_context("MessageEditor")
485 .on_action(cx.listener(Self::chat))
486 .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
487 this.profile_selector
488 .read(cx)
489 .menu_handle()
490 .toggle(window, cx);
491 }))
492 .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
493 this.model_selector
494 .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
495 }))
496 .on_action(cx.listener(Self::toggle_context_picker))
497 .on_action(cx.listener(Self::remove_all_context))
498 .on_action(cx.listener(Self::move_up))
499 .on_action(cx.listener(Self::expand_message_editor))
500 .capture_action(cx.listener(Self::paste))
501 .gap_2()
502 .p_2()
503 .bg(editor_bg_color)
504 .border_t_1()
505 .border_color(cx.theme().colors().border)
506 .child(
507 h_flex()
508 .items_start()
509 .justify_between()
510 .child(self.context_strip.clone())
511 .when(focus_handle.is_focused(window), |this| {
512 this.child(
513 IconButton::new("toggle-height", expand_icon)
514 .icon_size(IconSize::XSmall)
515 .icon_color(Color::Muted)
516 .tooltip({
517 let focus_handle = focus_handle.clone();
518 move |window, cx| {
519 let expand_label = if is_editor_expanded {
520 "Minimize Message Editor".to_string()
521 } else {
522 "Expand Message Editor".to_string()
523 };
524
525 Tooltip::for_action_in(
526 expand_label,
527 &ExpandMessageEditor,
528 &focus_handle,
529 window,
530 cx,
531 )
532 }
533 })
534 .on_click(cx.listener(|_, _, window, cx| {
535 window.dispatch_action(Box::new(ExpandMessageEditor), cx);
536 })),
537 )
538 }),
539 )
540 .child(
541 v_flex()
542 .size_full()
543 .gap_4()
544 .when(is_editor_expanded, |this| {
545 this.h(vh(0.8, window)).justify_between()
546 })
547 .child(
548 div()
549 .min_h_16()
550 .when(is_editor_expanded, |this| this.h_full())
551 .child({
552 let settings = ThemeSettings::get_global(cx);
553
554 let text_style = TextStyle {
555 color: cx.theme().colors().text,
556 font_family: settings.buffer_font.family.clone(),
557 font_fallbacks: settings.buffer_font.fallbacks.clone(),
558 font_features: settings.buffer_font.features.clone(),
559 font_size: font_size.into(),
560 line_height: line_height.into(),
561 ..Default::default()
562 };
563
564 EditorElement::new(
565 &self.editor,
566 EditorStyle {
567 background: editor_bg_color,
568 local_player: cx.theme().players().local(),
569 text: text_style,
570 syntax: cx.theme().syntax().clone(),
571 ..Default::default()
572 },
573 )
574 .into_any()
575 }),
576 )
577 .child(
578 h_flex()
579 .flex_none()
580 .justify_between()
581 .child(h_flex().gap_2().child(self.profile_selector.clone()))
582 .child(
583 h_flex()
584 .gap_1()
585 .when(!incompatible_tools.is_empty(), |this| {
586 this.child(
587 IconButton::new(
588 "tools-incompatible-warning",
589 IconName::Warning,
590 )
591 .icon_color(Color::Warning)
592 .icon_size(IconSize::Small)
593 .tooltip({
594 move |_, cx| {
595 cx.new(|_| IncompatibleToolsTooltip {
596 incompatible_tools: incompatible_tools
597 .clone(),
598 })
599 .into()
600 }
601 }),
602 )
603 })
604 .children(self.render_max_mode_toggle(cx))
605 .child(self.model_selector.clone())
606 .map({
607 let focus_handle = focus_handle.clone();
608 move |parent| {
609 if is_generating {
610 parent
611 .when(is_editor_empty, |parent| {
612 parent.child(
613 IconButton::new(
614 "stop-generation",
615 IconName::StopFilled,
616 )
617 .icon_color(Color::Error)
618 .style(ButtonStyle::Tinted(
619 ui::TintColor::Error,
620 ))
621 .tooltip(move |window, cx| {
622 Tooltip::for_action(
623 "Stop Generation",
624 &editor::actions::Cancel,
625 window,
626 cx,
627 )
628 })
629 .on_click({
630 let focus_handle =
631 focus_handle.clone();
632 move |_event, window, cx| {
633 focus_handle.dispatch_action(
634 &editor::actions::Cancel,
635 window,
636 cx,
637 );
638 }
639 })
640 .with_animation(
641 "pulsating-label",
642 Animation::new(
643 Duration::from_secs(2),
644 )
645 .repeat()
646 .with_easing(pulsating_between(
647 0.4, 1.0,
648 )),
649 |icon_button, delta| {
650 icon_button.alpha(delta)
651 },
652 ),
653 )
654 })
655 .when(!is_editor_empty, |parent| {
656 parent.child(
657 IconButton::new(
658 "send-message",
659 IconName::Send,
660 )
661 .icon_color(Color::Accent)
662 .style(ButtonStyle::Filled)
663 .disabled(!is_model_selected)
664 .on_click({
665 let focus_handle =
666 focus_handle.clone();
667 move |_event, window, cx| {
668 focus_handle.dispatch_action(
669 &Chat, window, cx,
670 );
671 }
672 })
673 .tooltip(move |window, cx| {
674 Tooltip::for_action(
675 "Stop and Send New Message",
676 &Chat,
677 window,
678 cx,
679 )
680 }),
681 )
682 })
683 } else {
684 parent.child(
685 IconButton::new("send-message", IconName::Send)
686 .icon_color(Color::Accent)
687 .style(ButtonStyle::Filled)
688 .disabled(
689 is_editor_empty || !is_model_selected,
690 )
691 .on_click({
692 let focus_handle = focus_handle.clone();
693 move |_event, window, cx| {
694 focus_handle.dispatch_action(
695 &Chat, window, cx,
696 );
697 }
698 })
699 .when(
700 !is_editor_empty && is_model_selected,
701 |button| {
702 button.tooltip(move |window, cx| {
703 Tooltip::for_action(
704 "Send", &Chat, window, cx,
705 )
706 })
707 },
708 )
709 .when(is_editor_empty, |button| {
710 button.tooltip(Tooltip::text(
711 "Type a message to submit",
712 ))
713 })
714 .when(!is_model_selected, |button| {
715 button.tooltip(Tooltip::text(
716 "Select a model to continue",
717 ))
718 }),
719 )
720 }
721 }
722 }),
723 ),
724 ),
725 )
726 }
727
728 fn render_changed_buffers(
729 &self,
730 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
731 window: &mut Window,
732 cx: &mut Context<Self>,
733 ) -> Div {
734 let focus_handle = self.editor.focus_handle(cx);
735
736 let editor_bg_color = cx.theme().colors().editor_background;
737 let border_color = cx.theme().colors().border;
738 let active_color = cx.theme().colors().element_selected;
739 let bg_edit_files_disclosure = editor_bg_color.blend(active_color.opacity(0.3));
740
741 let is_edit_changes_expanded = self.edits_expanded;
742 let is_generating = self.thread.read(cx).is_generating();
743
744 v_flex()
745 .mt_1()
746 .mx_2()
747 .bg(bg_edit_files_disclosure)
748 .border_1()
749 .border_b_0()
750 .border_color(border_color)
751 .rounded_t_md()
752 .shadow(smallvec::smallvec![gpui::BoxShadow {
753 color: gpui::black().opacity(0.15),
754 offset: point(px(1.), px(-1.)),
755 blur_radius: px(3.),
756 spread_radius: px(0.),
757 }])
758 .child(
759 h_flex()
760 .id("edits-container")
761 .cursor_pointer()
762 .p_1p5()
763 .justify_between()
764 .when(is_edit_changes_expanded, |this| {
765 this.border_b_1().border_color(border_color)
766 })
767 .on_click(
768 cx.listener(|this, _, window, cx| this.handle_review_click(window, cx)),
769 )
770 .child(
771 h_flex()
772 .gap_1()
773 .child(
774 Disclosure::new("edits-disclosure", is_edit_changes_expanded)
775 .on_click(cx.listener(|this, _ev, _window, cx| {
776 this.edits_expanded = !this.edits_expanded;
777 cx.notify();
778 })),
779 )
780 .map(|this| {
781 if is_generating {
782 this.child(
783 AnimatedLabel::new(format!(
784 "Editing {} {}",
785 changed_buffers.len(),
786 if changed_buffers.len() == 1 {
787 "file"
788 } else {
789 "files"
790 }
791 ))
792 .size(LabelSize::Small),
793 )
794 } else {
795 this.child(
796 Label::new("Edits")
797 .size(LabelSize::Small)
798 .color(Color::Muted),
799 )
800 .child(
801 Label::new("•").size(LabelSize::XSmall).color(Color::Muted),
802 )
803 .child(
804 Label::new(format!(
805 "{} {}",
806 changed_buffers.len(),
807 if changed_buffers.len() == 1 {
808 "file"
809 } else {
810 "files"
811 }
812 ))
813 .size(LabelSize::Small)
814 .color(Color::Muted),
815 )
816 }
817 }),
818 )
819 .child(
820 Button::new("review", "Review Changes")
821 .label_size(LabelSize::Small)
822 .key_binding(
823 KeyBinding::for_action_in(
824 &OpenAgentDiff,
825 &focus_handle,
826 window,
827 cx,
828 )
829 .map(|kb| kb.size(rems_from_px(12.))),
830 )
831 .on_click(cx.listener(|this, _, window, cx| {
832 this.handle_review_click(window, cx)
833 })),
834 ),
835 )
836 .when(is_edit_changes_expanded, |parent| {
837 parent.child(
838 v_flex().children(changed_buffers.into_iter().enumerate().flat_map(
839 |(index, (buffer, _diff))| {
840 let file = buffer.read(cx).file()?;
841 let path = file.path();
842
843 let parent_label = path.parent().and_then(|parent| {
844 let parent_str = parent.to_string_lossy();
845
846 if parent_str.is_empty() {
847 None
848 } else {
849 Some(
850 Label::new(format!(
851 "/{}{}",
852 parent_str,
853 std::path::MAIN_SEPARATOR_STR
854 ))
855 .color(Color::Muted)
856 .size(LabelSize::XSmall)
857 .buffer_font(cx),
858 )
859 }
860 });
861
862 let name_label = path.file_name().map(|name| {
863 Label::new(name.to_string_lossy().to_string())
864 .size(LabelSize::XSmall)
865 .buffer_font(cx)
866 });
867
868 let file_icon = FileIcons::get_icon(&path, cx)
869 .map(Icon::from_path)
870 .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
871 .unwrap_or_else(|| {
872 Icon::new(IconName::File)
873 .color(Color::Muted)
874 .size(IconSize::Small)
875 });
876
877 let hover_color = cx
878 .theme()
879 .colors()
880 .element_background
881 .blend(cx.theme().colors().editor_foreground.opacity(0.025));
882
883 let overlay_gradient = linear_gradient(
884 90.,
885 linear_color_stop(editor_bg_color, 1.),
886 linear_color_stop(editor_bg_color.opacity(0.2), 0.),
887 );
888
889 let overlay_gradient_hover = linear_gradient(
890 90.,
891 linear_color_stop(hover_color, 1.),
892 linear_color_stop(hover_color.opacity(0.2), 0.),
893 );
894
895 let element = h_flex()
896 .group("edited-code")
897 .id(("file-container", index))
898 .cursor_pointer()
899 .relative()
900 .py_1()
901 .pl_2()
902 .pr_1()
903 .gap_2()
904 .justify_between()
905 .bg(cx.theme().colors().editor_background)
906 .hover(|style| style.bg(hover_color))
907 .when(index < changed_buffers.len() - 1, |parent| {
908 parent.border_color(border_color).border_b_1()
909 })
910 .child(
911 h_flex()
912 .id("file-name")
913 .pr_8()
914 .gap_1p5()
915 .max_w_full()
916 .overflow_x_scroll()
917 .child(file_icon)
918 .child(
919 h_flex()
920 .gap_0p5()
921 .children(name_label)
922 .children(parent_label),
923 ), // TODO: Implement line diff
924 // .child(Label::new("+").color(Color::Created))
925 // .child(Label::new("-").color(Color::Deleted)),
926 )
927 .child(
928 div().visible_on_hover("edited-code").child(
929 Button::new("review", "Review")
930 .label_size(LabelSize::Small)
931 .on_click({
932 let buffer = buffer.clone();
933 cx.listener(move |this, _, window, cx| {
934 this.handle_file_click(
935 buffer.clone(),
936 window,
937 cx,
938 );
939 })
940 }),
941 ),
942 )
943 .child(
944 div()
945 .id("gradient-overlay")
946 .absolute()
947 .h_5_6()
948 .w_12()
949 .bottom_0()
950 .right(px(52.))
951 .bg(overlay_gradient)
952 .group_hover("edited-code", |style| {
953 style.bg(overlay_gradient_hover)
954 }),
955 )
956 .on_click({
957 let buffer = buffer.clone();
958 cx.listener(move |this, _, window, cx| {
959 this.handle_file_click(buffer.clone(), window, cx);
960 })
961 });
962
963 Some(element)
964 },
965 )),
966 )
967 })
968 }
969
970 fn render_token_limit_callout(
971 &self,
972 line_height: Pixels,
973 token_usage_ratio: TokenUsageRatio,
974 cx: &mut Context<Self>,
975 ) -> Div {
976 let heading = if token_usage_ratio == TokenUsageRatio::Exceeded {
977 "Thread reached the token limit"
978 } else {
979 "Thread reaching the token limit soon"
980 };
981
982 h_flex()
983 .p_2()
984 .gap_2()
985 .flex_wrap()
986 .justify_between()
987 .bg(
988 if token_usage_ratio == TokenUsageRatio::Exceeded {
989 cx.theme().status().error_background.opacity(0.1)
990 } else {
991 cx.theme().status().warning_background.opacity(0.1)
992 })
993 .border_t_1()
994 .border_color(cx.theme().colors().border)
995 .child(
996 h_flex()
997 .gap_2()
998 .items_start()
999 .child(
1000 h_flex()
1001 .h(line_height)
1002 .justify_center()
1003 .child(
1004 if token_usage_ratio == TokenUsageRatio::Exceeded {
1005 Icon::new(IconName::X)
1006 .color(Color::Error)
1007 .size(IconSize::XSmall)
1008 } else {
1009 Icon::new(IconName::Warning)
1010 .color(Color::Warning)
1011 .size(IconSize::XSmall)
1012 }
1013 ),
1014 )
1015 .child(
1016 v_flex()
1017 .mr_auto()
1018 .child(Label::new(heading).size(LabelSize::Small))
1019 .child(
1020 Label::new(
1021 "Start a new thread from a summary to continue the conversation.",
1022 )
1023 .size(LabelSize::Small)
1024 .color(Color::Muted),
1025 ),
1026 ),
1027 )
1028 .child(
1029 Button::new("new-thread", "Start New Thread")
1030 .on_click(cx.listener(|this, _, window, cx| {
1031 let from_thread_id = Some(this.thread.read(cx).id().clone());
1032
1033 window.dispatch_action(Box::new(NewThread {
1034 from_thread_id
1035 }), cx);
1036 }))
1037 .icon(IconName::Plus)
1038 .icon_position(IconPosition::Start)
1039 .icon_size(IconSize::Small)
1040 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
1041 .label_size(LabelSize::Small),
1042 )
1043 }
1044
1045 pub fn last_estimated_token_count(&self) -> Option<usize> {
1046 self.last_estimated_token_count
1047 }
1048
1049 pub fn is_waiting_to_update_token_count(&self) -> bool {
1050 self.update_token_count_task.is_some()
1051 }
1052
1053 fn reload_context(&mut self, cx: &mut Context<Self>) -> Task<Option<ContextLoadResult>> {
1054 let load_task = cx.spawn(async move |this, cx| {
1055 let Ok(load_task) = this.update(cx, |this, cx| {
1056 let new_context = this.context_store.read_with(cx, |context_store, cx| {
1057 context_store.new_context_for_thread(this.thread.read(cx), None)
1058 });
1059 load_context(new_context, &this.project, &this.prompt_store, cx)
1060 }) else {
1061 return;
1062 };
1063 let result = load_task.await;
1064 this.update(cx, |this, cx| {
1065 this.last_loaded_context = Some(result);
1066 this.load_context_task = None;
1067 this.message_or_context_changed(false, cx);
1068 })
1069 .ok();
1070 });
1071 // Replace existing load task, if any, causing it to be cancelled.
1072 let load_task = load_task.shared();
1073 self.load_context_task = Some(load_task.clone());
1074 cx.spawn(async move |this, cx| {
1075 load_task.await;
1076 this.read_with(cx, |this, _cx| this.last_loaded_context.clone())
1077 .ok()
1078 .flatten()
1079 })
1080 }
1081
1082 fn handle_message_changed(&mut self, cx: &mut Context<Self>) {
1083 self.message_or_context_changed(true, cx);
1084 }
1085
1086 fn message_or_context_changed(&mut self, debounce: bool, cx: &mut Context<Self>) {
1087 cx.emit(MessageEditorEvent::Changed);
1088 self.update_token_count_task.take();
1089
1090 let Some(model) = self.thread.read(cx).configured_model() else {
1091 self.last_estimated_token_count.take();
1092 return;
1093 };
1094
1095 let editor = self.editor.clone();
1096
1097 self.update_token_count_task = Some(cx.spawn(async move |this, cx| {
1098 if debounce {
1099 cx.background_executor()
1100 .timer(Duration::from_millis(200))
1101 .await;
1102 }
1103
1104 let token_count = if let Some(task) = this
1105 .update(cx, |this, cx| {
1106 let loaded_context = this
1107 .last_loaded_context
1108 .as_ref()
1109 .map(|context_load_result| &context_load_result.loaded_context);
1110 let message_text = editor.read(cx).text(cx);
1111
1112 if message_text.is_empty()
1113 && loaded_context.map_or(true, |loaded_context| loaded_context.is_empty())
1114 {
1115 return None;
1116 }
1117
1118 let mut request_message = LanguageModelRequestMessage {
1119 role: language_model::Role::User,
1120 content: Vec::new(),
1121 cache: false,
1122 };
1123
1124 if let Some(loaded_context) = loaded_context {
1125 loaded_context.add_to_request_message(&mut request_message);
1126 }
1127
1128 if !message_text.is_empty() {
1129 request_message
1130 .content
1131 .push(MessageContent::Text(message_text));
1132 }
1133
1134 let request = language_model::LanguageModelRequest {
1135 thread_id: None,
1136 prompt_id: None,
1137 mode: None,
1138 messages: vec![request_message],
1139 tools: vec![],
1140 stop: vec![],
1141 temperature: None,
1142 };
1143
1144 Some(model.model.count_tokens(request, cx))
1145 })
1146 .ok()
1147 .flatten()
1148 {
1149 task.await.log_err()
1150 } else {
1151 Some(0)
1152 };
1153
1154 this.update(cx, |this, cx| {
1155 if let Some(token_count) = token_count {
1156 this.last_estimated_token_count = Some(token_count);
1157 cx.emit(MessageEditorEvent::EstimatedTokenCount);
1158 }
1159 this.update_token_count_task.take();
1160 })
1161 .ok();
1162 }));
1163 }
1164}
1165
1166impl EventEmitter<MessageEditorEvent> for MessageEditor {}
1167
1168pub enum MessageEditorEvent {
1169 EstimatedTokenCount,
1170 Changed,
1171}
1172
1173impl Focusable for MessageEditor {
1174 fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
1175 self.editor.focus_handle(cx)
1176 }
1177}
1178
1179impl Render for MessageEditor {
1180 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1181 let thread = self.thread.read(cx);
1182 let token_usage_ratio = thread
1183 .total_token_usage()
1184 .map_or(TokenUsageRatio::Normal, |total_token_usage| {
1185 total_token_usage.ratio()
1186 });
1187
1188 let action_log = self.thread.read(cx).action_log();
1189 let changed_buffers = action_log.read(cx).changed_buffers(cx);
1190
1191 let font_size = TextSize::Small.rems(cx);
1192 let line_height = font_size.to_pixels(window.rem_size()) * 1.5;
1193
1194 v_flex()
1195 .size_full()
1196 .when(changed_buffers.len() > 0, |parent| {
1197 parent.child(self.render_changed_buffers(&changed_buffers, window, cx))
1198 })
1199 .child(self.render_editor(font_size, line_height, window, cx))
1200 .when(token_usage_ratio != TokenUsageRatio::Normal, |parent| {
1201 parent.child(self.render_token_limit_callout(line_height, token_usage_ratio, cx))
1202 })
1203 }
1204}