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