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 git_store = self.project.read(cx).git_store().clone();
226 let checkpoint = git_store.update(cx, |git_store, cx| git_store.checkpoint(cx));
227
228 cx.spawn(async move |this, cx| {
229 let checkpoint = checkpoint.await.ok();
230 refresh_task.await;
231 let (system_prompt_context, load_error) = system_prompt_context_task.await;
232
233 thread
234 .update(cx, |thread, cx| {
235 thread.set_system_prompt_context(system_prompt_context);
236 if let Some(load_error) = load_error {
237 cx.emit(ThreadEvent::ShowError(load_error));
238 }
239 })
240 .log_err();
241
242 thread
243 .update(cx, |thread, cx| {
244 let context = context_store.read(cx).context().clone();
245 thread.insert_user_message(user_message, context, checkpoint, cx);
246 })
247 .log_err();
248
249 if let Some(wait_for_summaries) = context_store
250 .update(cx, |context_store, cx| context_store.wait_for_summaries(cx))
251 .log_err()
252 {
253 this.update(cx, |this, cx| {
254 this.waiting_for_summaries_to_send = true;
255 cx.notify();
256 })
257 .log_err();
258
259 wait_for_summaries.await;
260
261 this.update(cx, |this, cx| {
262 this.waiting_for_summaries_to_send = false;
263 cx.notify();
264 })
265 .log_err();
266 }
267
268 // Send to model after summaries are done
269 thread
270 .update(cx, |thread, cx| {
271 thread.send_to_model(model, request_kind, cx);
272 })
273 .log_err();
274 })
275 .detach();
276 }
277
278 fn handle_inline_context_picker_event(
279 &mut self,
280 _inline_context_picker: &Entity<ContextPicker>,
281 _event: &DismissEvent,
282 window: &mut Window,
283 cx: &mut Context<Self>,
284 ) {
285 let editor_focus_handle = self.editor.focus_handle(cx);
286 window.focus(&editor_focus_handle);
287 }
288
289 fn handle_context_strip_event(
290 &mut self,
291 _context_strip: &Entity<ContextStrip>,
292 event: &ContextStripEvent,
293 window: &mut Window,
294 cx: &mut Context<Self>,
295 ) {
296 match event {
297 ContextStripEvent::PickerDismissed
298 | ContextStripEvent::BlurredEmpty
299 | ContextStripEvent::BlurredDown => {
300 let editor_focus_handle = self.editor.focus_handle(cx);
301 window.focus(&editor_focus_handle);
302 }
303 ContextStripEvent::BlurredUp => {}
304 }
305 }
306
307 fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
308 if self.context_picker_menu_handle.is_deployed()
309 || self.inline_context_picker_menu_handle.is_deployed()
310 {
311 cx.propagate();
312 } else {
313 self.context_strip.focus_handle(cx).focus(window);
314 }
315 }
316
317 fn handle_review_click(&self, window: &mut Window, cx: &mut Context<Self>) {
318 AgentDiff::deploy(self.thread.clone(), self.workspace.clone(), window, cx).log_err();
319 }
320
321 fn handle_file_click(
322 &self,
323 buffer: Entity<Buffer>,
324 window: &mut Window,
325 cx: &mut Context<Self>,
326 ) {
327 if let Ok(diff) = AgentDiff::deploy(self.thread.clone(), self.workspace.clone(), window, cx)
328 {
329 let path_key = multi_buffer::PathKey::for_buffer(&buffer, cx);
330 diff.update(cx, |diff, cx| diff.move_to_path(path_key, window, cx));
331 }
332 }
333}
334
335impl Focusable for MessageEditor {
336 fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
337 self.editor.focus_handle(cx)
338 }
339}
340
341impl Render for MessageEditor {
342 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
343 let font_size = TextSize::Default.rems(cx);
344 let line_height = font_size.to_pixels(window.rem_size()) * 1.5;
345
346 let focus_handle = self.editor.focus_handle(cx);
347 let inline_context_picker = self.inline_context_picker.clone();
348
349 let thread = self.thread.read(cx);
350 let is_generating = thread.is_generating();
351 let total_token_usage = thread.total_token_usage(cx);
352 let is_model_selected = self.is_model_selected(cx);
353 let is_editor_empty = self.is_editor_empty(cx);
354
355 let action_log = self.thread.read(cx).action_log();
356 let changed_buffers = action_log.read(cx).changed_buffers(cx);
357 let changed_buffers_count = changed_buffers.len();
358
359 let editor_bg_color = cx.theme().colors().editor_background;
360 let border_color = cx.theme().colors().border;
361 let active_color = cx.theme().colors().element_selected;
362 let bg_edit_files_disclosure = editor_bg_color.blend(active_color.opacity(0.3));
363
364 v_flex()
365 .size_full()
366 .when(self.waiting_for_summaries_to_send, |parent| {
367 parent.child(
368 h_flex().py_3().w_full().justify_center().child(
369 h_flex()
370 .flex_none()
371 .px_2()
372 .py_2()
373 .bg(editor_bg_color)
374 .border_1()
375 .border_color(cx.theme().colors().border_variant)
376 .rounded_lg()
377 .shadow_md()
378 .gap_1()
379 .child(
380 Icon::new(IconName::ArrowCircle)
381 .size(IconSize::XSmall)
382 .color(Color::Muted)
383 .with_animation(
384 "arrow-circle",
385 Animation::new(Duration::from_secs(2)).repeat(),
386 |icon, delta| {
387 icon.transform(gpui::Transformation::rotate(
388 gpui::percentage(delta),
389 ))
390 },
391 ),
392 )
393 .child(
394 Label::new("Summarizing context…")
395 .size(LabelSize::XSmall)
396 .color(Color::Muted),
397 ),
398 ),
399 )
400 })
401 .when(changed_buffers_count > 0, |parent| {
402 parent.child(
403 v_flex()
404 .mx_2()
405 .bg(bg_edit_files_disclosure)
406 .border_1()
407 .border_b_0()
408 .border_color(border_color)
409 .rounded_t_md()
410 .shadow(smallvec::smallvec![gpui::BoxShadow {
411 color: gpui::black().opacity(0.15),
412 offset: point(px(1.), px(-1.)),
413 blur_radius: px(3.),
414 spread_radius: px(0.),
415 }])
416 .child(
417 h_flex()
418 .id("edits-container")
419 .p_1p5()
420 .justify_between()
421 .when(self.edits_expanded, |this| {
422 this.border_b_1().border_color(border_color)
423 })
424 .cursor_pointer()
425 .on_click(cx.listener(|this, _, window, cx| {
426 this.handle_review_click(window, cx)
427 }))
428 .child(
429 h_flex()
430 .gap_1()
431 .child(
432 Disclosure::new(
433 "edits-disclosure",
434 self.edits_expanded,
435 )
436 .on_click(
437 cx.listener(|this, _ev, _window, cx| {
438 this.edits_expanded = !this.edits_expanded;
439 cx.notify();
440 }),
441 ),
442 )
443 .child(
444 Label::new("Edits")
445 .size(LabelSize::Small)
446 .color(Color::Muted),
447 )
448 .child(
449 Label::new("•")
450 .size(LabelSize::XSmall)
451 .color(Color::Muted),
452 )
453 .child(
454 Label::new(format!(
455 "{} {}",
456 changed_buffers_count,
457 if changed_buffers_count == 1 {
458 "file"
459 } else {
460 "files"
461 }
462 ))
463 .size(LabelSize::Small)
464 .color(Color::Muted),
465 ),
466 )
467 .child(
468 Button::new("review", "Review Changes")
469 .label_size(LabelSize::Small)
470 .key_binding(
471 KeyBinding::for_action_in(
472 &OpenAgentDiff,
473 &focus_handle,
474 window,
475 cx,
476 )
477 .map(|kb| kb.size(rems_from_px(12.))),
478 )
479 .on_click(cx.listener(|this, _, window, cx| {
480 this.handle_review_click(window, cx)
481 })),
482 ),
483 )
484 .when(self.edits_expanded, |parent| {
485 parent.child(
486 v_flex().bg(cx.theme().colors().editor_background).children(
487 changed_buffers.into_iter().enumerate().flat_map(
488 |(index, (buffer, _diff))| {
489 let file = buffer.read(cx).file()?;
490 let path = file.path();
491
492 let parent_label = path.parent().and_then(|parent| {
493 let parent_str = parent.to_string_lossy();
494
495 if parent_str.is_empty() {
496 None
497 } else {
498 Some(
499 Label::new(format!(
500 "{}{}",
501 parent_str,
502 std::path::MAIN_SEPARATOR_STR
503 ))
504 .color(Color::Muted)
505 .size(LabelSize::XSmall)
506 .buffer_font(cx),
507 )
508 }
509 });
510
511 let name_label = path.file_name().map(|name| {
512 Label::new(name.to_string_lossy().to_string())
513 .size(LabelSize::XSmall)
514 .buffer_font(cx)
515 });
516
517 let file_icon = FileIcons::get_icon(&path, cx)
518 .map(Icon::from_path)
519 .map(|icon| {
520 icon.color(Color::Muted).size(IconSize::Small)
521 })
522 .unwrap_or_else(|| {
523 Icon::new(IconName::File)
524 .color(Color::Muted)
525 .size(IconSize::Small)
526 });
527
528 let element = div()
529 .relative()
530 .py_1()
531 .px_2()
532 .when(index + 1 < changed_buffers_count, |parent| {
533 parent.border_color(border_color).border_b_1()
534 })
535 .child(
536 h_flex()
537 .gap_2()
538 .justify_between()
539 .child(
540 h_flex()
541 .id(("file-container", index))
542 .pr_8()
543 .gap_1p5()
544 .max_w_full()
545 .overflow_x_scroll()
546 .cursor_pointer()
547 .on_click({
548 let buffer = buffer.clone();
549 cx.listener(move |this, _, window, cx| {
550 this.handle_file_click(buffer.clone(), window, cx);
551 })
552 })
553 .tooltip(
554 Tooltip::text(format!("Review {}", path.display()))
555 )
556 .child(file_icon)
557 .child(
558 h_flex()
559 .children(parent_label)
560 .children(name_label),
561 ) // TODO: show lines changed
562 .child(
563 Label::new("+")
564 .color(Color::Created),
565 )
566 .child(
567 Label::new("-")
568 .color(Color::Deleted),
569 ),
570 )
571 .child(
572 div()
573 .h_full()
574 .absolute()
575 .w_8()
576 .bottom_0()
577 .right_0()
578 .bg(linear_gradient(
579 90.,
580 linear_color_stop(
581 editor_bg_color,
582 1.,
583 ),
584 linear_color_stop(
585 editor_bg_color
586 .opacity(0.2),
587 0.,
588 ),
589 )),
590 ),
591 );
592
593 Some(element)
594 },
595 ),
596 ),
597 )
598 }),
599 )
600 })
601 .child(
602 v_flex()
603 .key_context("MessageEditor")
604 .on_action(cx.listener(Self::chat))
605 .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
606 this.profile_selector
607 .read(cx)
608 .menu_handle()
609 .toggle(window, cx);
610 }))
611 .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
612 this.model_selector
613 .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
614 }))
615 .on_action(cx.listener(Self::toggle_context_picker))
616 .on_action(cx.listener(Self::remove_all_context))
617 .on_action(cx.listener(Self::move_up))
618 .on_action(cx.listener(Self::toggle_chat_mode))
619 .gap_2()
620 .p_2()
621 .bg(editor_bg_color)
622 .border_t_1()
623 .border_color(cx.theme().colors().border)
624 .child(h_flex().justify_between().child(self.context_strip.clone()))
625 .child(
626 v_flex()
627 .gap_5()
628 .child({
629 let settings = ThemeSettings::get_global(cx);
630 let text_style = TextStyle {
631 color: cx.theme().colors().text,
632 font_family: settings.ui_font.family.clone(),
633 font_fallbacks: settings.ui_font.fallbacks.clone(),
634 font_features: settings.ui_font.features.clone(),
635 font_size: font_size.into(),
636 font_weight: settings.ui_font.weight,
637 line_height: line_height.into(),
638 ..Default::default()
639 };
640
641 EditorElement::new(
642 &self.editor,
643 EditorStyle {
644 background: editor_bg_color,
645 local_player: cx.theme().players().local(),
646 text: text_style,
647 syntax: cx.theme().syntax().clone(),
648 ..Default::default()
649 },
650 ).into_any()
651 })
652 .child(
653 PopoverMenu::new("inline-context-picker")
654 .menu(move |window, cx| {
655 inline_context_picker.update(cx, |this, cx| {
656 this.init(window, cx);
657 });
658 Some(inline_context_picker.clone())
659 })
660 .attach(gpui::Corner::TopLeft)
661 .anchor(gpui::Corner::BottomLeft)
662 .offset(gpui::Point {
663 x: px(0.0),
664 y: (-ThemeSettings::get_global(cx).ui_font_size(cx) * 2)
665 - px(4.0),
666 })
667 .with_handle(self.inline_context_picker_menu_handle.clone()),
668 )
669 .child(
670 h_flex()
671 .justify_between()
672 .child(h_flex().gap_2().child(self.profile_selector.clone()))
673 .child(
674 h_flex().gap_1().child(self.model_selector.clone())
675 .map(|parent| {
676 if is_generating {
677 parent.child(
678 IconButton::new("stop-generation", IconName::StopFilled)
679 .icon_color(Color::Error)
680 .style(ButtonStyle::Tinted(ui::TintColor::Error))
681 .tooltip(move |window, cx| {
682 Tooltip::for_action(
683 "Stop Generation",
684 &editor::actions::Cancel,
685 window,
686 cx,
687 )
688 })
689 .on_click(move |_event, window, cx| {
690 focus_handle.dispatch_action(
691 &editor::actions::Cancel,
692 window,
693 cx,
694 );
695 })
696 .with_animation(
697 "pulsating-label",
698 Animation::new(Duration::from_secs(2))
699 .repeat()
700 .with_easing(pulsating_between(0.4, 1.0)),
701 |icon_button, delta| icon_button.alpha(delta),
702 ),
703 )
704 } else {
705 parent.child(
706 IconButton::new("send-message", IconName::Send)
707 .icon_color(Color::Accent)
708 .style(ButtonStyle::Filled)
709 .disabled(
710 is_editor_empty
711 || !is_model_selected
712 || self.waiting_for_summaries_to_send
713 )
714 .on_click(move |_event, window, cx| {
715 focus_handle.dispatch_action(&Chat, window, cx);
716 })
717 .when(!is_editor_empty && is_model_selected, |button| {
718 button.tooltip(move |window, cx| {
719 Tooltip::for_action(
720 "Send",
721 &Chat,
722 window,
723 cx,
724 )
725 })
726 })
727 .when(is_editor_empty, |button| {
728 button.tooltip(Tooltip::text(
729 "Type a message to submit",
730 ))
731 })
732 .when(!is_model_selected, |button| {
733 button.tooltip(Tooltip::text(
734 "Select a model to continue",
735 ))
736 })
737 )
738 }
739 })
740 ),
741 ),
742 )
743 )
744 .when(total_token_usage.ratio != TokenUsageRatio::Normal, |parent| {
745 parent.child(
746 h_flex()
747 .p_2()
748 .gap_2()
749 .flex_wrap()
750 .justify_between()
751 .bg(cx.theme().status().warning_background.opacity(0.1))
752 .border_t_1()
753 .border_color(cx.theme().colors().border)
754 .child(
755 h_flex()
756 .gap_2()
757 .items_start()
758 .child(
759 h_flex()
760 .h(line_height)
761 .justify_center()
762 .child(
763 Icon::new(IconName::Warning)
764 .color(Color::Warning)
765 .size(IconSize::XSmall),
766 ),
767 )
768 .child(
769 v_flex()
770 .mr_auto()
771 .child(Label::new("Thread reaching the token limit soon").size(LabelSize::Small))
772 .child(
773 Label::new(
774 "Start a new thread from a summary to continue the conversation.",
775 )
776 .size(LabelSize::Small)
777 .color(Color::Muted),
778 ),
779 ),
780 )
781 .child(
782 Button::new("new-thread", "Start New Thread")
783 .on_click(cx.listener(|this, _, window, cx| {
784 let from_thread_id = Some(this.thread.read(cx).id().clone());
785
786 window.dispatch_action(Box::new(NewThread {
787 from_thread_id
788 }), cx);
789 }))
790 .icon(IconName::Plus)
791 .icon_position(IconPosition::Start)
792 .icon_size(IconSize::Small)
793 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
794 .label_size(LabelSize::Small),
795 ),
796 )
797 })
798 }
799}