message_editor.rs
1use std::sync::Arc;
2
3use crate::assistant_model_selector::ModelType;
4use collections::HashSet;
5use editor::actions::MoveUp;
6use editor::{ContextMenuOptions, ContextMenuPlacement, Editor, EditorElement, EditorStyle};
7use file_icons::FileIcons;
8use fs::Fs;
9use gpui::{
10 Animation, AnimationExt, App, DismissEvent, Entity, Focusable, Subscription, TextStyle,
11 WeakEntity, linear_color_stop, linear_gradient, point, pulsating_between,
12};
13use language::Buffer;
14use language_model::{ConfiguredModel, LanguageModelRegistry};
15use language_model_selector::ToggleModelSelector;
16use multi_buffer;
17use project::Project;
18use settings::Settings;
19use std::time::Duration;
20use theme::ThemeSettings;
21use ui::{Disclosure, KeyBinding, PopoverMenu, PopoverMenuHandle, Tooltip, prelude::*};
22use util::ResultExt as _;
23use workspace::Workspace;
24
25use crate::assistant_model_selector::AssistantModelSelector;
26use crate::context_picker::{ConfirmBehavior, ContextPicker, ContextPickerCompletionProvider};
27use crate::context_store::{ContextStore, refresh_context_store_text};
28use crate::context_strip::{ContextStrip, ContextStripEvent, SuggestContextKind};
29use crate::profile_selector::ProfileSelector;
30use crate::thread::{RequestKind, Thread, TokenUsageRatio};
31use crate::thread_store::ThreadStore;
32use crate::{
33 AgentDiff, Chat, ChatMode, NewThread, OpenAgentDiff, RemoveAllContext, ThreadEvent,
34 ToggleContextPicker, ToggleProfileSelector,
35};
36
37pub struct MessageEditor {
38 thread: Entity<Thread>,
39 editor: Entity<Editor>,
40 #[allow(dead_code)]
41 workspace: WeakEntity<Workspace>,
42 project: Entity<Project>,
43 context_store: Entity<ContextStore>,
44 context_strip: Entity<ContextStrip>,
45 context_picker_menu_handle: PopoverMenuHandle<ContextPicker>,
46 inline_context_picker: Entity<ContextPicker>,
47 inline_context_picker_menu_handle: PopoverMenuHandle<ContextPicker>,
48 model_selector: Entity<AssistantModelSelector>,
49 profile_selector: Entity<ProfileSelector>,
50 edits_expanded: bool,
51 waiting_for_summaries_to_send: bool,
52 _subscriptions: Vec<Subscription>,
53}
54
55impl MessageEditor {
56 pub fn new(
57 fs: Arc<dyn Fs>,
58 workspace: WeakEntity<Workspace>,
59 context_store: Entity<ContextStore>,
60 thread_store: WeakEntity<ThreadStore>,
61 thread: Entity<Thread>,
62 window: &mut Window,
63 cx: &mut Context<Self>,
64 ) -> Self {
65 let context_picker_menu_handle = PopoverMenuHandle::default();
66 let inline_context_picker_menu_handle = PopoverMenuHandle::default();
67 let model_selector_menu_handle = PopoverMenuHandle::default();
68
69 let editor = cx.new(|cx| {
70 let mut editor = Editor::auto_height(10, window, cx);
71 editor.set_placeholder_text("Ask anything, @ to mention, ↑ to select", cx);
72 editor.set_show_indent_guides(false, cx);
73 editor.set_context_menu_options(ContextMenuOptions {
74 min_entries_visible: 12,
75 max_entries_visible: 12,
76 placement: Some(ContextMenuPlacement::Above),
77 });
78
79 editor
80 });
81
82 let editor_entity = editor.downgrade();
83 editor.update(cx, |editor, _| {
84 editor.set_completion_provider(Some(Box::new(ContextPickerCompletionProvider::new(
85 workspace.clone(),
86 context_store.downgrade(),
87 Some(thread_store.clone()),
88 editor_entity,
89 ))));
90 });
91
92 let inline_context_picker = cx.new(|cx| {
93 ContextPicker::new(
94 workspace.clone(),
95 Some(thread_store.clone()),
96 context_store.downgrade(),
97 ConfirmBehavior::Close,
98 window,
99 cx,
100 )
101 });
102
103 let context_strip = cx.new(|cx| {
104 ContextStrip::new(
105 context_store.clone(),
106 workspace.clone(),
107 Some(thread_store.clone()),
108 context_picker_menu_handle.clone(),
109 SuggestContextKind::File,
110 window,
111 cx,
112 )
113 });
114
115 let subscriptions = vec![
116 cx.subscribe_in(
117 &inline_context_picker,
118 window,
119 Self::handle_inline_context_picker_event,
120 ),
121 cx.subscribe_in(&context_strip, window, Self::handle_context_strip_event),
122 ];
123
124 Self {
125 editor: editor.clone(),
126 project: thread.read(cx).project().clone(),
127 thread,
128 workspace,
129 context_store,
130 context_strip,
131 context_picker_menu_handle,
132 inline_context_picker,
133 inline_context_picker_menu_handle,
134 model_selector: cx.new(|cx| {
135 AssistantModelSelector::new(
136 fs.clone(),
137 model_selector_menu_handle,
138 editor.focus_handle(cx),
139 ModelType::Default,
140 window,
141 cx,
142 )
143 }),
144 edits_expanded: false,
145 waiting_for_summaries_to_send: false,
146 profile_selector: cx
147 .new(|cx| ProfileSelector::new(fs, thread_store, editor.focus_handle(cx), cx)),
148 _subscriptions: subscriptions,
149 }
150 }
151
152 fn toggle_chat_mode(&mut self, _: &ChatMode, _window: &mut Window, cx: &mut Context<Self>) {
153 cx.notify();
154 }
155
156 fn toggle_context_picker(
157 &mut self,
158 _: &ToggleContextPicker,
159 window: &mut Window,
160 cx: &mut Context<Self>,
161 ) {
162 self.context_picker_menu_handle.toggle(window, cx);
163 }
164 pub fn remove_all_context(
165 &mut self,
166 _: &RemoveAllContext,
167 _window: &mut Window,
168 cx: &mut Context<Self>,
169 ) {
170 self.context_store.update(cx, |store, _cx| store.clear());
171 cx.notify();
172 }
173
174 fn chat(&mut self, _: &Chat, window: &mut Window, cx: &mut Context<Self>) {
175 if self.is_editor_empty(cx) {
176 return;
177 }
178
179 if self.thread.read(cx).is_generating() {
180 return;
181 }
182
183 self.send_to_model(RequestKind::Chat, window, cx);
184 }
185
186 fn is_editor_empty(&self, cx: &App) -> bool {
187 self.editor.read(cx).text(cx).is_empty()
188 }
189
190 fn is_model_selected(&self, cx: &App) -> bool {
191 LanguageModelRegistry::read_global(cx)
192 .default_model()
193 .is_some()
194 }
195
196 fn send_to_model(
197 &mut self,
198 request_kind: RequestKind,
199 window: &mut Window,
200 cx: &mut Context<Self>,
201 ) {
202 let model_registry = LanguageModelRegistry::read_global(cx);
203 let Some(ConfiguredModel { model, provider }) = model_registry.default_model() else {
204 return;
205 };
206
207 if provider.must_accept_terms(cx) {
208 cx.notify();
209 return;
210 }
211
212 let user_message = self.editor.update(cx, |editor, cx| {
213 let text = editor.text(cx);
214 editor.clear(window, cx);
215 text
216 });
217
218 let refresh_task =
219 refresh_context_store_text(self.context_store.clone(), &HashSet::default(), cx);
220
221 let system_prompt_context_task = self.thread.read(cx).load_system_prompt_context(cx);
222
223 let thread = self.thread.clone();
224 let context_store = self.context_store.clone();
225 let checkpoint = self.project.read(cx).git_store().read(cx).checkpoint(cx);
226
227 cx.spawn(async move |this, cx| {
228 let checkpoint = checkpoint.await.ok();
229 refresh_task.await;
230 let (system_prompt_context, load_error) = system_prompt_context_task.await;
231
232 thread
233 .update(cx, |thread, cx| {
234 thread.set_system_prompt_context(system_prompt_context);
235 if let Some(load_error) = load_error {
236 cx.emit(ThreadEvent::ShowError(load_error));
237 }
238 })
239 .log_err();
240
241 thread
242 .update(cx, |thread, cx| {
243 let context = context_store.read(cx).context().clone();
244 thread.insert_user_message(user_message, context, checkpoint, cx);
245 })
246 .log_err();
247
248 if let Some(wait_for_summaries) = context_store
249 .update(cx, |context_store, cx| context_store.wait_for_summaries(cx))
250 .log_err()
251 {
252 this.update(cx, |this, cx| {
253 this.waiting_for_summaries_to_send = true;
254 cx.notify();
255 })
256 .log_err();
257
258 wait_for_summaries.await;
259
260 this.update(cx, |this, cx| {
261 this.waiting_for_summaries_to_send = false;
262 cx.notify();
263 })
264 .log_err();
265 }
266
267 // Send to model after summaries are done
268 thread
269 .update(cx, |thread, cx| {
270 thread.send_to_model(model, request_kind, cx);
271 })
272 .log_err();
273 })
274 .detach();
275 }
276
277 fn handle_inline_context_picker_event(
278 &mut self,
279 _inline_context_picker: &Entity<ContextPicker>,
280 _event: &DismissEvent,
281 window: &mut Window,
282 cx: &mut Context<Self>,
283 ) {
284 let editor_focus_handle = self.editor.focus_handle(cx);
285 window.focus(&editor_focus_handle);
286 }
287
288 fn handle_context_strip_event(
289 &mut self,
290 _context_strip: &Entity<ContextStrip>,
291 event: &ContextStripEvent,
292 window: &mut Window,
293 cx: &mut Context<Self>,
294 ) {
295 match event {
296 ContextStripEvent::PickerDismissed
297 | ContextStripEvent::BlurredEmpty
298 | ContextStripEvent::BlurredDown => {
299 let editor_focus_handle = self.editor.focus_handle(cx);
300 window.focus(&editor_focus_handle);
301 }
302 ContextStripEvent::BlurredUp => {}
303 }
304 }
305
306 fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
307 if self.context_picker_menu_handle.is_deployed()
308 || self.inline_context_picker_menu_handle.is_deployed()
309 {
310 cx.propagate();
311 } else {
312 self.context_strip.focus_handle(cx).focus(window);
313 }
314 }
315
316 fn handle_review_click(&self, window: &mut Window, cx: &mut Context<Self>) {
317 AgentDiff::deploy(self.thread.clone(), self.workspace.clone(), window, cx).log_err();
318 }
319
320 fn handle_file_click(
321 &self,
322 buffer: Entity<Buffer>,
323 window: &mut Window,
324 cx: &mut Context<Self>,
325 ) {
326 if let Ok(diff) = AgentDiff::deploy(self.thread.clone(), self.workspace.clone(), window, cx)
327 {
328 let path_key = multi_buffer::PathKey::for_buffer(&buffer, cx);
329 diff.update(cx, |diff, cx| diff.move_to_path(path_key, window, cx));
330 }
331 }
332}
333
334impl Focusable for MessageEditor {
335 fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
336 self.editor.focus_handle(cx)
337 }
338}
339
340impl Render for MessageEditor {
341 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
342 let font_size = TextSize::Default.rems(cx);
343 let line_height = font_size.to_pixels(window.rem_size()) * 1.5;
344
345 let focus_handle = self.editor.focus_handle(cx);
346 let inline_context_picker = self.inline_context_picker.clone();
347
348 let thread = self.thread.read(cx);
349 let is_generating = thread.is_generating();
350 let total_token_usage = thread.total_token_usage(cx);
351 let is_model_selected = self.is_model_selected(cx);
352 let is_editor_empty = self.is_editor_empty(cx);
353
354 let action_log = self.thread.read(cx).action_log();
355 let changed_buffers = action_log.read(cx).changed_buffers(cx);
356 let changed_buffers_count = changed_buffers.len();
357
358 let editor_bg_color = cx.theme().colors().editor_background;
359 let border_color = cx.theme().colors().border;
360 let active_color = cx.theme().colors().element_selected;
361 let bg_edit_files_disclosure = editor_bg_color.blend(active_color.opacity(0.3));
362
363 v_flex()
364 .size_full()
365 .when(self.waiting_for_summaries_to_send, |parent| {
366 parent.child(
367 h_flex().py_3().w_full().justify_center().child(
368 h_flex()
369 .flex_none()
370 .px_2()
371 .py_2()
372 .bg(editor_bg_color)
373 .border_1()
374 .border_color(cx.theme().colors().border_variant)
375 .rounded_lg()
376 .shadow_md()
377 .gap_1()
378 .child(
379 Icon::new(IconName::ArrowCircle)
380 .size(IconSize::XSmall)
381 .color(Color::Muted)
382 .with_animation(
383 "arrow-circle",
384 Animation::new(Duration::from_secs(2)).repeat(),
385 |icon, delta| {
386 icon.transform(gpui::Transformation::rotate(
387 gpui::percentage(delta),
388 ))
389 },
390 ),
391 )
392 .child(
393 Label::new("Summarizing context…")
394 .size(LabelSize::XSmall)
395 .color(Color::Muted),
396 ),
397 ),
398 )
399 })
400 .when(changed_buffers_count > 0, |parent| {
401 parent.child(
402 v_flex()
403 .mx_2()
404 .bg(bg_edit_files_disclosure)
405 .border_1()
406 .border_b_0()
407 .border_color(border_color)
408 .rounded_t_md()
409 .shadow(smallvec::smallvec![gpui::BoxShadow {
410 color: gpui::black().opacity(0.15),
411 offset: point(px(1.), px(-1.)),
412 blur_radius: px(3.),
413 spread_radius: px(0.),
414 }])
415 .child(
416 h_flex()
417 .id("edits-container")
418 .p_1p5()
419 .justify_between()
420 .when(self.edits_expanded, |this| {
421 this.border_b_1().border_color(border_color)
422 })
423 .cursor_pointer()
424 .on_click(cx.listener(|this, _, window, cx| {
425 this.handle_review_click(window, cx)
426 }))
427 .child(
428 h_flex()
429 .gap_1()
430 .child(
431 Disclosure::new(
432 "edits-disclosure",
433 self.edits_expanded,
434 )
435 .on_click(
436 cx.listener(|this, _ev, _window, cx| {
437 this.edits_expanded = !this.edits_expanded;
438 cx.notify();
439 }),
440 ),
441 )
442 .child(
443 Label::new("Edits")
444 .size(LabelSize::Small)
445 .color(Color::Muted),
446 )
447 .child(
448 Label::new("•")
449 .size(LabelSize::XSmall)
450 .color(Color::Muted),
451 )
452 .child(
453 Label::new(format!(
454 "{} {}",
455 changed_buffers_count,
456 if changed_buffers_count == 1 {
457 "file"
458 } else {
459 "files"
460 }
461 ))
462 .size(LabelSize::Small)
463 .color(Color::Muted),
464 ),
465 )
466 .child(
467 Button::new("review", "Review Changes")
468 .label_size(LabelSize::Small)
469 .key_binding(
470 KeyBinding::for_action_in(
471 &OpenAgentDiff,
472 &focus_handle,
473 window,
474 cx,
475 )
476 .map(|kb| kb.size(rems_from_px(12.))),
477 )
478 .on_click(cx.listener(|this, _, window, cx| {
479 this.handle_review_click(window, cx)
480 })),
481 ),
482 )
483 .when(self.edits_expanded, |parent| {
484 parent.child(
485 v_flex().bg(cx.theme().colors().editor_background).children(
486 changed_buffers.into_iter().enumerate().flat_map(
487 |(index, (buffer, _diff))| {
488 let file = buffer.read(cx).file()?;
489 let path = file.path();
490
491 let parent_label = path.parent().and_then(|parent| {
492 let parent_str = parent.to_string_lossy();
493
494 if parent_str.is_empty() {
495 None
496 } else {
497 Some(
498 Label::new(format!(
499 "{}{}",
500 parent_str,
501 std::path::MAIN_SEPARATOR_STR
502 ))
503 .color(Color::Muted)
504 .size(LabelSize::XSmall)
505 .buffer_font(cx),
506 )
507 }
508 });
509
510 let name_label = path.file_name().map(|name| {
511 Label::new(name.to_string_lossy().to_string())
512 .size(LabelSize::XSmall)
513 .buffer_font(cx)
514 });
515
516 let file_icon = FileIcons::get_icon(&path, cx)
517 .map(Icon::from_path)
518 .map(|icon| {
519 icon.color(Color::Muted).size(IconSize::Small)
520 })
521 .unwrap_or_else(|| {
522 Icon::new(IconName::File)
523 .color(Color::Muted)
524 .size(IconSize::Small)
525 });
526
527 let element = div()
528 .relative()
529 .py_1()
530 .px_2()
531 .when(index + 1 < changed_buffers_count, |parent| {
532 parent.border_color(border_color).border_b_1()
533 })
534 .child(
535 h_flex()
536 .gap_2()
537 .justify_between()
538 .child(
539 h_flex()
540 .id(("file-container", index))
541 .pr_8()
542 .gap_1p5()
543 .max_w_full()
544 .overflow_x_scroll()
545 .cursor_pointer()
546 .on_click({
547 let buffer = buffer.clone();
548 cx.listener(move |this, _, window, cx| {
549 this.handle_file_click(buffer.clone(), window, cx);
550 })
551 })
552 .tooltip(
553 Tooltip::text(format!("Review {}", path.display()))
554 )
555 .child(file_icon)
556 .child(
557 h_flex()
558 .children(parent_label)
559 .children(name_label),
560 ) // TODO: show lines changed
561 .child(
562 Label::new("+")
563 .color(Color::Created),
564 )
565 .child(
566 Label::new("-")
567 .color(Color::Deleted),
568 ),
569 )
570 .child(
571 div()
572 .h_full()
573 .absolute()
574 .w_8()
575 .bottom_0()
576 .right_0()
577 .bg(linear_gradient(
578 90.,
579 linear_color_stop(
580 editor_bg_color,
581 1.,
582 ),
583 linear_color_stop(
584 editor_bg_color
585 .opacity(0.2),
586 0.,
587 ),
588 )),
589 ),
590 );
591
592 Some(element)
593 },
594 ),
595 ),
596 )
597 }),
598 )
599 })
600 .child(
601 v_flex()
602 .key_context("MessageEditor")
603 .on_action(cx.listener(Self::chat))
604 .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
605 this.profile_selector
606 .read(cx)
607 .menu_handle()
608 .toggle(window, cx);
609 }))
610 .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
611 this.model_selector
612 .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
613 }))
614 .on_action(cx.listener(Self::toggle_context_picker))
615 .on_action(cx.listener(Self::remove_all_context))
616 .on_action(cx.listener(Self::move_up))
617 .on_action(cx.listener(Self::toggle_chat_mode))
618 .gap_2()
619 .p_2()
620 .bg(editor_bg_color)
621 .border_t_1()
622 .border_color(cx.theme().colors().border)
623 .child(h_flex().justify_between().child(self.context_strip.clone()))
624 .child(
625 v_flex()
626 .gap_5()
627 .child({
628 let settings = ThemeSettings::get_global(cx);
629 let text_style = TextStyle {
630 color: cx.theme().colors().text,
631 font_family: settings.ui_font.family.clone(),
632 font_fallbacks: settings.ui_font.fallbacks.clone(),
633 font_features: settings.ui_font.features.clone(),
634 font_size: font_size.into(),
635 font_weight: settings.ui_font.weight,
636 line_height: line_height.into(),
637 ..Default::default()
638 };
639
640 EditorElement::new(
641 &self.editor,
642 EditorStyle {
643 background: editor_bg_color,
644 local_player: cx.theme().players().local(),
645 text: text_style,
646 syntax: cx.theme().syntax().clone(),
647 ..Default::default()
648 },
649 ).into_any()
650 })
651 .child(
652 PopoverMenu::new("inline-context-picker")
653 .menu(move |window, cx| {
654 inline_context_picker.update(cx, |this, cx| {
655 this.init(window, cx);
656 });
657 Some(inline_context_picker.clone())
658 })
659 .attach(gpui::Corner::TopLeft)
660 .anchor(gpui::Corner::BottomLeft)
661 .offset(gpui::Point {
662 x: px(0.0),
663 y: (-ThemeSettings::get_global(cx).ui_font_size(cx) * 2)
664 - px(4.0),
665 })
666 .with_handle(self.inline_context_picker_menu_handle.clone()),
667 )
668 .child(
669 h_flex()
670 .justify_between()
671 .child(h_flex().gap_2().child(self.profile_selector.clone()))
672 .child(
673 h_flex().gap_1().child(self.model_selector.clone())
674 .map(|parent| {
675 if is_generating {
676 parent.child(
677 IconButton::new("stop-generation", IconName::StopFilled)
678 .icon_color(Color::Error)
679 .style(ButtonStyle::Tinted(ui::TintColor::Error))
680 .tooltip(move |window, cx| {
681 Tooltip::for_action(
682 "Stop Generation",
683 &editor::actions::Cancel,
684 window,
685 cx,
686 )
687 })
688 .on_click(move |_event, window, cx| {
689 focus_handle.dispatch_action(
690 &editor::actions::Cancel,
691 window,
692 cx,
693 );
694 })
695 .with_animation(
696 "pulsating-label",
697 Animation::new(Duration::from_secs(2))
698 .repeat()
699 .with_easing(pulsating_between(0.4, 1.0)),
700 |icon_button, delta| icon_button.alpha(delta),
701 ),
702 )
703 } else {
704 parent.child(
705 IconButton::new("send-message", IconName::Send)
706 .icon_color(Color::Accent)
707 .style(ButtonStyle::Filled)
708 .disabled(
709 is_editor_empty
710 || !is_model_selected
711 || self.waiting_for_summaries_to_send
712 )
713 .on_click(move |_event, window, cx| {
714 focus_handle.dispatch_action(&Chat, window, cx);
715 })
716 .when(!is_editor_empty && is_model_selected, |button| {
717 button.tooltip(move |window, cx| {
718 Tooltip::for_action(
719 "Send",
720 &Chat,
721 window,
722 cx,
723 )
724 })
725 })
726 .when(is_editor_empty, |button| {
727 button.tooltip(Tooltip::text(
728 "Type a message to submit",
729 ))
730 })
731 .when(!is_model_selected, |button| {
732 button.tooltip(Tooltip::text(
733 "Select a model to continue",
734 ))
735 })
736 )
737 }
738 })
739 ),
740 ),
741 )
742 )
743 .when(total_token_usage.ratio != TokenUsageRatio::Normal, |parent| {
744 parent.child(
745 h_flex()
746 .p_2()
747 .gap_2()
748 .flex_wrap()
749 .justify_between()
750 .bg(cx.theme().status().warning_background.opacity(0.1))
751 .border_t_1()
752 .border_color(cx.theme().colors().border)
753 .child(
754 h_flex()
755 .gap_2()
756 .items_start()
757 .child(
758 h_flex()
759 .h(line_height)
760 .justify_center()
761 .child(
762 Icon::new(IconName::Warning)
763 .color(Color::Warning)
764 .size(IconSize::XSmall),
765 ),
766 )
767 .child(
768 v_flex()
769 .mr_auto()
770 .child(Label::new("Thread reaching the token limit soon").size(LabelSize::Small))
771 .child(
772 Label::new(
773 "Start a new thread from a summary to continue the conversation.",
774 )
775 .size(LabelSize::Small)
776 .color(Color::Muted),
777 ),
778 ),
779 )
780 .child(
781 Button::new("new-thread", "Start New Thread")
782 .on_click(cx.listener(|this, _, window, cx| {
783 let from_thread_id = Some(this.thread.read(cx).id().clone());
784
785 window.dispatch_action(Box::new(NewThread {
786 from_thread_id
787 }), cx);
788 }))
789 .icon(IconName::Plus)
790 .icon_position(IconPosition::Start)
791 .icon_size(IconSize::Small)
792 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
793 .label_size(LabelSize::Small),
794 ),
795 )
796 })
797 }
798}