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 .toggle_state(active_completion_mode == Some(CompletionMode::Max))
432 .on_click(cx.listener(move |this, _event, _window, cx| {
433 this.thread.update(cx, |thread, _cx| {
434 thread.set_completion_mode(match active_completion_mode {
435 Some(CompletionMode::Max) => Some(CompletionMode::Normal),
436 Some(CompletionMode::Normal) | None => Some(CompletionMode::Max),
437 });
438 });
439 }))
440 .tooltip(Tooltip::text("Toggle Max Mode"))
441 .into_any_element(),
442 )
443 }
444
445 fn render_editor(
446 &self,
447 font_size: Rems,
448 line_height: Pixels,
449 window: &mut Window,
450 cx: &mut Context<Self>,
451 ) -> Div {
452 let thread = self.thread.read(cx);
453 let model = thread.configured_model();
454
455 let editor_bg_color = cx.theme().colors().editor_background;
456 let is_generating = thread.is_generating();
457 let focus_handle = self.editor.focus_handle(cx);
458
459 let is_model_selected = model.is_some();
460 let is_editor_empty = self.is_editor_empty(cx);
461
462 let incompatible_tools = model
463 .as_ref()
464 .map(|model| {
465 self.incompatible_tools_state.update(cx, |state, cx| {
466 state
467 .incompatible_tools(&model.model, cx)
468 .iter()
469 .cloned()
470 .collect::<Vec<_>>()
471 })
472 })
473 .unwrap_or_default();
474
475 let is_editor_expanded = self.editor_is_expanded;
476 let expand_icon = if is_editor_expanded {
477 IconName::Minimize
478 } else {
479 IconName::Maximize
480 };
481
482 v_flex()
483 .key_context("MessageEditor")
484 .on_action(cx.listener(Self::chat))
485 .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
486 this.profile_selector
487 .read(cx)
488 .menu_handle()
489 .toggle(window, cx);
490 }))
491 .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
492 this.model_selector
493 .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
494 }))
495 .on_action(cx.listener(Self::toggle_context_picker))
496 .on_action(cx.listener(Self::remove_all_context))
497 .on_action(cx.listener(Self::move_up))
498 .on_action(cx.listener(Self::expand_message_editor))
499 .capture_action(cx.listener(Self::paste))
500 .gap_2()
501 .p_2()
502 .bg(editor_bg_color)
503 .border_t_1()
504 .border_color(cx.theme().colors().border)
505 .child(
506 h_flex()
507 .items_start()
508 .justify_between()
509 .child(self.context_strip.clone())
510 .when(focus_handle.is_focused(window), |this| {
511 this.child(
512 IconButton::new("toggle-height", expand_icon)
513 .icon_size(IconSize::XSmall)
514 .icon_color(Color::Muted)
515 .tooltip({
516 let focus_handle = focus_handle.clone();
517 move |window, cx| {
518 let expand_label = if is_editor_expanded {
519 "Minimize Message Editor".to_string()
520 } else {
521 "Expand Message Editor".to_string()
522 };
523
524 Tooltip::for_action_in(
525 expand_label,
526 &ExpandMessageEditor,
527 &focus_handle,
528 window,
529 cx,
530 )
531 }
532 })
533 .on_click(cx.listener(|_, _, window, cx| {
534 window.dispatch_action(Box::new(ExpandMessageEditor), cx);
535 })),
536 )
537 }),
538 )
539 .child(
540 v_flex()
541 .size_full()
542 .gap_4()
543 .when(is_editor_expanded, |this| {
544 this.h(vh(0.8, window)).justify_between()
545 })
546 .child(
547 div()
548 .min_h_16()
549 .when(is_editor_expanded, |this| this.h_full())
550 .child({
551 let settings = ThemeSettings::get_global(cx);
552
553 let text_style = TextStyle {
554 color: cx.theme().colors().text,
555 font_family: settings.buffer_font.family.clone(),
556 font_fallbacks: settings.buffer_font.fallbacks.clone(),
557 font_features: settings.buffer_font.features.clone(),
558 font_size: font_size.into(),
559 line_height: line_height.into(),
560 ..Default::default()
561 };
562
563 EditorElement::new(
564 &self.editor,
565 EditorStyle {
566 background: editor_bg_color,
567 local_player: cx.theme().players().local(),
568 text: text_style,
569 syntax: cx.theme().syntax().clone(),
570 ..Default::default()
571 },
572 )
573 .into_any()
574 }),
575 )
576 .child(
577 h_flex()
578 .flex_none()
579 .justify_between()
580 .child(h_flex().gap_2().child(self.profile_selector.clone()))
581 .child(
582 h_flex()
583 .gap_1()
584 .when(!incompatible_tools.is_empty(), |this| {
585 this.child(
586 IconButton::new(
587 "tools-incompatible-warning",
588 IconName::Warning,
589 )
590 .icon_color(Color::Warning)
591 .icon_size(IconSize::Small)
592 .tooltip({
593 move |_, cx| {
594 cx.new(|_| IncompatibleToolsTooltip {
595 incompatible_tools: incompatible_tools
596 .clone(),
597 })
598 .into()
599 }
600 }),
601 )
602 })
603 .children(self.render_max_mode_toggle(cx))
604 .child(self.model_selector.clone())
605 .map({
606 let focus_handle = focus_handle.clone();
607 move |parent| {
608 if is_generating {
609 parent
610 .when(is_editor_empty, |parent| {
611 parent.child(
612 IconButton::new(
613 "stop-generation",
614 IconName::StopFilled,
615 )
616 .icon_color(Color::Error)
617 .style(ButtonStyle::Tinted(
618 ui::TintColor::Error,
619 ))
620 .tooltip(move |window, cx| {
621 Tooltip::for_action(
622 "Stop Generation",
623 &editor::actions::Cancel,
624 window,
625 cx,
626 )
627 })
628 .on_click({
629 let focus_handle =
630 focus_handle.clone();
631 move |_event, window, cx| {
632 focus_handle.dispatch_action(
633 &editor::actions::Cancel,
634 window,
635 cx,
636 );
637 }
638 })
639 .with_animation(
640 "pulsating-label",
641 Animation::new(
642 Duration::from_secs(2),
643 )
644 .repeat()
645 .with_easing(pulsating_between(
646 0.4, 1.0,
647 )),
648 |icon_button, delta| {
649 icon_button.alpha(delta)
650 },
651 ),
652 )
653 })
654 .when(!is_editor_empty, |parent| {
655 parent.child(
656 IconButton::new(
657 "send-message",
658 IconName::Send,
659 )
660 .icon_color(Color::Accent)
661 .style(ButtonStyle::Filled)
662 .disabled(!is_model_selected)
663 .on_click({
664 let focus_handle =
665 focus_handle.clone();
666 move |_event, window, cx| {
667 focus_handle.dispatch_action(
668 &Chat, window, cx,
669 );
670 }
671 })
672 .tooltip(move |window, cx| {
673 Tooltip::for_action(
674 "Stop and Send New Message",
675 &Chat,
676 window,
677 cx,
678 )
679 }),
680 )
681 })
682 } else {
683 parent.child(
684 IconButton::new("send-message", IconName::Send)
685 .icon_color(Color::Accent)
686 .style(ButtonStyle::Filled)
687 .disabled(
688 is_editor_empty || !is_model_selected,
689 )
690 .on_click({
691 let focus_handle = focus_handle.clone();
692 move |_event, window, cx| {
693 focus_handle.dispatch_action(
694 &Chat, window, cx,
695 );
696 }
697 })
698 .when(
699 !is_editor_empty && is_model_selected,
700 |button| {
701 button.tooltip(move |window, cx| {
702 Tooltip::for_action(
703 "Send", &Chat, window, cx,
704 )
705 })
706 },
707 )
708 .when(is_editor_empty, |button| {
709 button.tooltip(Tooltip::text(
710 "Type a message to submit",
711 ))
712 })
713 .when(!is_model_selected, |button| {
714 button.tooltip(Tooltip::text(
715 "Select a model to continue",
716 ))
717 }),
718 )
719 }
720 }
721 }),
722 ),
723 ),
724 )
725 }
726
727 fn render_changed_buffers(
728 &self,
729 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
730 window: &mut Window,
731 cx: &mut Context<Self>,
732 ) -> Div {
733 let focus_handle = self.editor.focus_handle(cx);
734
735 let editor_bg_color = cx.theme().colors().editor_background;
736 let border_color = cx.theme().colors().border;
737 let active_color = cx.theme().colors().element_selected;
738 let bg_edit_files_disclosure = editor_bg_color.blend(active_color.opacity(0.3));
739
740 let is_edit_changes_expanded = self.edits_expanded;
741 let is_generating = self.thread.read(cx).is_generating();
742
743 v_flex()
744 .mt_1()
745 .mx_2()
746 .bg(bg_edit_files_disclosure)
747 .border_1()
748 .border_b_0()
749 .border_color(border_color)
750 .rounded_t_md()
751 .shadow(smallvec::smallvec![gpui::BoxShadow {
752 color: gpui::black().opacity(0.15),
753 offset: point(px(1.), px(-1.)),
754 blur_radius: px(3.),
755 spread_radius: px(0.),
756 }])
757 .child(
758 h_flex()
759 .id("edits-container")
760 .cursor_pointer()
761 .p_1p5()
762 .justify_between()
763 .when(is_edit_changes_expanded, |this| {
764 this.border_b_1().border_color(border_color)
765 })
766 .on_click(
767 cx.listener(|this, _, window, cx| this.handle_review_click(window, cx)),
768 )
769 .child(
770 h_flex()
771 .gap_1()
772 .child(
773 Disclosure::new("edits-disclosure", is_edit_changes_expanded)
774 .on_click(cx.listener(|this, _ev, _window, cx| {
775 this.edits_expanded = !this.edits_expanded;
776 cx.notify();
777 })),
778 )
779 .map(|this| {
780 if is_generating {
781 this.child(
782 AnimatedLabel::new(format!(
783 "Editing {} {}",
784 changed_buffers.len(),
785 if changed_buffers.len() == 1 {
786 "file"
787 } else {
788 "files"
789 }
790 ))
791 .size(LabelSize::Small),
792 )
793 } else {
794 this.child(
795 Label::new("Edits")
796 .size(LabelSize::Small)
797 .color(Color::Muted),
798 )
799 .child(
800 Label::new("•").size(LabelSize::XSmall).color(Color::Muted),
801 )
802 .child(
803 Label::new(format!(
804 "{} {}",
805 changed_buffers.len(),
806 if changed_buffers.len() == 1 {
807 "file"
808 } else {
809 "files"
810 }
811 ))
812 .size(LabelSize::Small)
813 .color(Color::Muted),
814 )
815 }
816 }),
817 )
818 .child(
819 Button::new("review", "Review Changes")
820 .label_size(LabelSize::Small)
821 .key_binding(
822 KeyBinding::for_action_in(
823 &OpenAgentDiff,
824 &focus_handle,
825 window,
826 cx,
827 )
828 .map(|kb| kb.size(rems_from_px(12.))),
829 )
830 .on_click(cx.listener(|this, _, window, cx| {
831 this.handle_review_click(window, cx)
832 })),
833 ),
834 )
835 .when(is_edit_changes_expanded, |parent| {
836 parent.child(
837 v_flex().children(changed_buffers.into_iter().enumerate().flat_map(
838 |(index, (buffer, _diff))| {
839 let file = buffer.read(cx).file()?;
840 let path = file.path();
841
842 let parent_label = path.parent().and_then(|parent| {
843 let parent_str = parent.to_string_lossy();
844
845 if parent_str.is_empty() {
846 None
847 } else {
848 Some(
849 Label::new(format!(
850 "/{}{}",
851 parent_str,
852 std::path::MAIN_SEPARATOR_STR
853 ))
854 .color(Color::Muted)
855 .size(LabelSize::XSmall)
856 .buffer_font(cx),
857 )
858 }
859 });
860
861 let name_label = path.file_name().map(|name| {
862 Label::new(name.to_string_lossy().to_string())
863 .size(LabelSize::XSmall)
864 .buffer_font(cx)
865 });
866
867 let file_icon = FileIcons::get_icon(&path, cx)
868 .map(Icon::from_path)
869 .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
870 .unwrap_or_else(|| {
871 Icon::new(IconName::File)
872 .color(Color::Muted)
873 .size(IconSize::Small)
874 });
875
876 let hover_color = cx
877 .theme()
878 .colors()
879 .element_background
880 .blend(cx.theme().colors().editor_foreground.opacity(0.025));
881
882 let overlay_gradient = linear_gradient(
883 90.,
884 linear_color_stop(editor_bg_color, 1.),
885 linear_color_stop(editor_bg_color.opacity(0.2), 0.),
886 );
887
888 let overlay_gradient_hover = linear_gradient(
889 90.,
890 linear_color_stop(hover_color, 1.),
891 linear_color_stop(hover_color.opacity(0.2), 0.),
892 );
893
894 let element = h_flex()
895 .group("edited-code")
896 .id(("file-container", index))
897 .cursor_pointer()
898 .relative()
899 .py_1()
900 .pl_2()
901 .pr_1()
902 .gap_2()
903 .justify_between()
904 .bg(cx.theme().colors().editor_background)
905 .hover(|style| style.bg(hover_color))
906 .when(index < changed_buffers.len() - 1, |parent| {
907 parent.border_color(border_color).border_b_1()
908 })
909 .child(
910 h_flex()
911 .id("file-name")
912 .pr_8()
913 .gap_1p5()
914 .max_w_full()
915 .overflow_x_scroll()
916 .child(file_icon)
917 .child(
918 h_flex()
919 .gap_0p5()
920 .children(name_label)
921 .children(parent_label),
922 ), // TODO: Implement line diff
923 // .child(Label::new("+").color(Color::Created))
924 // .child(Label::new("-").color(Color::Deleted)),
925 )
926 .child(
927 div().visible_on_hover("edited-code").child(
928 Button::new("review", "Review")
929 .label_size(LabelSize::Small)
930 .on_click({
931 let buffer = buffer.clone();
932 cx.listener(move |this, _, window, cx| {
933 this.handle_file_click(
934 buffer.clone(),
935 window,
936 cx,
937 );
938 })
939 }),
940 ),
941 )
942 .child(
943 div()
944 .id("gradient-overlay")
945 .absolute()
946 .h_5_6()
947 .w_12()
948 .bottom_0()
949 .right(px(52.))
950 .bg(overlay_gradient)
951 .group_hover("edited-code", |style| {
952 style.bg(overlay_gradient_hover)
953 }),
954 )
955 .on_click({
956 let buffer = buffer.clone();
957 cx.listener(move |this, _, window, cx| {
958 this.handle_file_click(buffer.clone(), window, cx);
959 })
960 });
961
962 Some(element)
963 },
964 )),
965 )
966 })
967 }
968
969 fn render_token_limit_callout(
970 &self,
971 line_height: Pixels,
972 token_usage_ratio: TokenUsageRatio,
973 cx: &mut Context<Self>,
974 ) -> Div {
975 let heading = if token_usage_ratio == TokenUsageRatio::Exceeded {
976 "Thread reached the token limit"
977 } else {
978 "Thread reaching the token limit soon"
979 };
980
981 h_flex()
982 .p_2()
983 .gap_2()
984 .flex_wrap()
985 .justify_between()
986 .bg(
987 if token_usage_ratio == TokenUsageRatio::Exceeded {
988 cx.theme().status().error_background.opacity(0.1)
989 } else {
990 cx.theme().status().warning_background.opacity(0.1)
991 })
992 .border_t_1()
993 .border_color(cx.theme().colors().border)
994 .child(
995 h_flex()
996 .gap_2()
997 .items_start()
998 .child(
999 h_flex()
1000 .h(line_height)
1001 .justify_center()
1002 .child(
1003 if token_usage_ratio == TokenUsageRatio::Exceeded {
1004 Icon::new(IconName::X)
1005 .color(Color::Error)
1006 .size(IconSize::XSmall)
1007 } else {
1008 Icon::new(IconName::Warning)
1009 .color(Color::Warning)
1010 .size(IconSize::XSmall)
1011 }
1012 ),
1013 )
1014 .child(
1015 v_flex()
1016 .mr_auto()
1017 .child(Label::new(heading).size(LabelSize::Small))
1018 .child(
1019 Label::new(
1020 "Start a new thread from a summary to continue the conversation.",
1021 )
1022 .size(LabelSize::Small)
1023 .color(Color::Muted),
1024 ),
1025 ),
1026 )
1027 .child(
1028 Button::new("new-thread", "Start New Thread")
1029 .on_click(cx.listener(|this, _, window, cx| {
1030 let from_thread_id = Some(this.thread.read(cx).id().clone());
1031
1032 window.dispatch_action(Box::new(NewThread {
1033 from_thread_id
1034 }), cx);
1035 }))
1036 .icon(IconName::Plus)
1037 .icon_position(IconPosition::Start)
1038 .icon_size(IconSize::Small)
1039 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
1040 .label_size(LabelSize::Small),
1041 )
1042 }
1043
1044 pub fn last_estimated_token_count(&self) -> Option<usize> {
1045 self.last_estimated_token_count
1046 }
1047
1048 pub fn is_waiting_to_update_token_count(&self) -> bool {
1049 self.update_token_count_task.is_some()
1050 }
1051
1052 fn reload_context(&mut self, cx: &mut Context<Self>) -> Task<Option<ContextLoadResult>> {
1053 let load_task = cx.spawn(async move |this, cx| {
1054 let Ok(load_task) = this.update(cx, |this, cx| {
1055 let new_context = this.context_store.read_with(cx, |context_store, cx| {
1056 context_store.new_context_for_thread(this.thread.read(cx), None)
1057 });
1058 load_context(new_context, &this.project, &this.prompt_store, cx)
1059 }) else {
1060 return;
1061 };
1062 let result = load_task.await;
1063 this.update(cx, |this, cx| {
1064 this.last_loaded_context = Some(result);
1065 this.load_context_task = None;
1066 this.message_or_context_changed(false, cx);
1067 })
1068 .ok();
1069 });
1070 // Replace existing load task, if any, causing it to be cancelled.
1071 let load_task = load_task.shared();
1072 self.load_context_task = Some(load_task.clone());
1073 cx.spawn(async move |this, cx| {
1074 load_task.await;
1075 this.read_with(cx, |this, _cx| this.last_loaded_context.clone())
1076 .ok()
1077 .flatten()
1078 })
1079 }
1080
1081 fn handle_message_changed(&mut self, cx: &mut Context<Self>) {
1082 self.message_or_context_changed(true, cx);
1083 }
1084
1085 fn message_or_context_changed(&mut self, debounce: bool, cx: &mut Context<Self>) {
1086 cx.emit(MessageEditorEvent::Changed);
1087 self.update_token_count_task.take();
1088
1089 let Some(model) = self.thread.read(cx).configured_model() else {
1090 self.last_estimated_token_count.take();
1091 return;
1092 };
1093
1094 let editor = self.editor.clone();
1095
1096 self.update_token_count_task = Some(cx.spawn(async move |this, cx| {
1097 if debounce {
1098 cx.background_executor()
1099 .timer(Duration::from_millis(200))
1100 .await;
1101 }
1102
1103 let token_count = if let Some(task) = this
1104 .update(cx, |this, cx| {
1105 let loaded_context = this
1106 .last_loaded_context
1107 .as_ref()
1108 .map(|context_load_result| &context_load_result.loaded_context);
1109 let message_text = editor.read(cx).text(cx);
1110
1111 if message_text.is_empty()
1112 && loaded_context.map_or(true, |loaded_context| loaded_context.is_empty())
1113 {
1114 return None;
1115 }
1116
1117 let mut request_message = LanguageModelRequestMessage {
1118 role: language_model::Role::User,
1119 content: Vec::new(),
1120 cache: false,
1121 };
1122
1123 if let Some(loaded_context) = loaded_context {
1124 loaded_context.add_to_request_message(&mut request_message);
1125 }
1126
1127 if !message_text.is_empty() {
1128 request_message
1129 .content
1130 .push(MessageContent::Text(message_text));
1131 }
1132
1133 let request = language_model::LanguageModelRequest {
1134 thread_id: None,
1135 prompt_id: None,
1136 mode: None,
1137 messages: vec![request_message],
1138 tools: vec![],
1139 stop: vec![],
1140 temperature: None,
1141 };
1142
1143 Some(model.model.count_tokens(request, cx))
1144 })
1145 .ok()
1146 .flatten()
1147 {
1148 task.await.log_err()
1149 } else {
1150 Some(0)
1151 };
1152
1153 this.update(cx, |this, cx| {
1154 if let Some(token_count) = token_count {
1155 this.last_estimated_token_count = Some(token_count);
1156 cx.emit(MessageEditorEvent::EstimatedTokenCount);
1157 }
1158 this.update_token_count_task.take();
1159 })
1160 .ok();
1161 }));
1162 }
1163}
1164
1165impl EventEmitter<MessageEditorEvent> for MessageEditor {}
1166
1167pub enum MessageEditorEvent {
1168 EstimatedTokenCount,
1169 Changed,
1170}
1171
1172impl Focusable for MessageEditor {
1173 fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
1174 self.editor.focus_handle(cx)
1175 }
1176}
1177
1178impl Render for MessageEditor {
1179 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1180 let thread = self.thread.read(cx);
1181 let token_usage_ratio = thread
1182 .total_token_usage()
1183 .map_or(TokenUsageRatio::Normal, |total_token_usage| {
1184 total_token_usage.ratio()
1185 });
1186
1187 let action_log = self.thread.read(cx).action_log();
1188 let changed_buffers = action_log.read(cx).changed_buffers(cx);
1189
1190 let font_size = TextSize::Small.rems(cx);
1191 let line_height = font_size.to_pixels(window.rem_size()) * 1.5;
1192
1193 v_flex()
1194 .size_full()
1195 .when(changed_buffers.len() > 0, |parent| {
1196 parent.child(self.render_changed_buffers(&changed_buffers, window, cx))
1197 })
1198 .child(self.render_editor(font_size, line_height, window, cx))
1199 .when(token_usage_ratio != TokenUsageRatio::Normal, |parent| {
1200 parent.child(self.render_token_limit_callout(line_height, token_usage_ratio, cx))
1201 })
1202 }
1203}