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