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