message_editor.rs

  1use std::sync::Arc;
  2
  3use editor::actions::MoveUp;
  4use editor::{Editor, EditorElement, EditorEvent, EditorStyle};
  5use fs::Fs;
  6use gpui::{
  7    pulsating_between, Animation, AnimationExt, App, DismissEvent, Entity, Focusable, Subscription,
  8    TextStyle, WeakEntity,
  9};
 10use language_model::LanguageModelRegistry;
 11use language_model_selector::LanguageModelSelector;
 12use rope::Point;
 13use settings::Settings;
 14use std::time::Duration;
 15use text::Bias;
 16use theme::ThemeSettings;
 17use ui::{
 18    prelude::*, ButtonLike, KeyBinding, PopoverMenu, PopoverMenuHandle, Switch, TintColor, Tooltip,
 19};
 20use workspace::Workspace;
 21
 22use crate::assistant_model_selector::AssistantModelSelector;
 23use crate::context_picker::{ConfirmBehavior, ContextPicker};
 24use crate::context_store::{refresh_context_store_text, ContextStore};
 25use crate::context_strip::{ContextStrip, ContextStripEvent, SuggestContextKind};
 26use crate::thread::{RequestKind, Thread};
 27use crate::thread_store::ThreadStore;
 28use crate::{Chat, ChatMode, RemoveAllContext, ToggleContextPicker, ToggleModelSelector};
 29
 30pub struct MessageEditor {
 31    thread: Entity<Thread>,
 32    editor: Entity<Editor>,
 33    context_store: Entity<ContextStore>,
 34    context_strip: Entity<ContextStrip>,
 35    context_picker_menu_handle: PopoverMenuHandle<ContextPicker>,
 36    inline_context_picker: Entity<ContextPicker>,
 37    inline_context_picker_menu_handle: PopoverMenuHandle<ContextPicker>,
 38    model_selector: Entity<AssistantModelSelector>,
 39    model_selector_menu_handle: PopoverMenuHandle<LanguageModelSelector>,
 40    use_tools: bool,
 41    _subscriptions: Vec<Subscription>,
 42}
 43
 44impl MessageEditor {
 45    pub fn new(
 46        fs: Arc<dyn Fs>,
 47        workspace: WeakEntity<Workspace>,
 48        thread_store: WeakEntity<ThreadStore>,
 49        thread: Entity<Thread>,
 50        window: &mut Window,
 51        cx: &mut Context<Self>,
 52    ) -> Self {
 53        let context_store = cx.new(|_cx| ContextStore::new(workspace.clone()));
 54        let context_picker_menu_handle = PopoverMenuHandle::default();
 55        let inline_context_picker_menu_handle = PopoverMenuHandle::default();
 56        let model_selector_menu_handle = PopoverMenuHandle::default();
 57
 58        let editor = cx.new(|cx| {
 59            let mut editor = Editor::auto_height(10, window, cx);
 60            editor.set_placeholder_text("Ask anything, @ to mention, ↑ to select", cx);
 61            editor.set_show_indent_guides(false, cx);
 62
 63            editor
 64        });
 65
 66        let inline_context_picker = cx.new(|cx| {
 67            ContextPicker::new(
 68                workspace.clone(),
 69                Some(thread_store.clone()),
 70                context_store.downgrade(),
 71                editor.downgrade(),
 72                ConfirmBehavior::Close,
 73                window,
 74                cx,
 75            )
 76        });
 77
 78        let context_strip = cx.new(|cx| {
 79            ContextStrip::new(
 80                context_store.clone(),
 81                workspace.clone(),
 82                editor.downgrade(),
 83                Some(thread_store.clone()),
 84                context_picker_menu_handle.clone(),
 85                SuggestContextKind::File,
 86                window,
 87                cx,
 88            )
 89        });
 90
 91        let subscriptions = vec![
 92            cx.subscribe_in(&editor, window, Self::handle_editor_event),
 93            cx.subscribe_in(
 94                &inline_context_picker,
 95                window,
 96                Self::handle_inline_context_picker_event,
 97            ),
 98            cx.subscribe_in(&context_strip, window, Self::handle_context_strip_event),
 99        ];
100
101        Self {
102            thread,
103            editor: editor.clone(),
104            context_store,
105            context_strip,
106            context_picker_menu_handle,
107            inline_context_picker,
108            inline_context_picker_menu_handle,
109            model_selector: cx.new(|cx| {
110                AssistantModelSelector::new(
111                    fs,
112                    model_selector_menu_handle.clone(),
113                    editor.focus_handle(cx),
114                    window,
115                    cx,
116                )
117            }),
118            model_selector_menu_handle,
119            use_tools: false,
120            _subscriptions: subscriptions,
121        }
122    }
123
124    fn toggle_model_selector(
125        &mut self,
126        _: &ToggleModelSelector,
127        window: &mut Window,
128        cx: &mut Context<Self>,
129    ) {
130        self.model_selector_menu_handle.toggle(window, cx)
131    }
132
133    fn toggle_chat_mode(&mut self, _: &ChatMode, _window: &mut Window, cx: &mut Context<Self>) {
134        self.use_tools = !self.use_tools;
135        cx.notify();
136    }
137
138    fn toggle_context_picker(
139        &mut self,
140        _: &ToggleContextPicker,
141        window: &mut Window,
142        cx: &mut Context<Self>,
143    ) {
144        self.context_picker_menu_handle.toggle(window, cx);
145    }
146
147    pub fn remove_all_context(
148        &mut self,
149        _: &RemoveAllContext,
150        _window: &mut Window,
151        cx: &mut Context<Self>,
152    ) {
153        self.context_store.update(cx, |store, _cx| store.clear());
154        cx.notify();
155    }
156
157    fn chat(&mut self, _: &Chat, window: &mut Window, cx: &mut Context<Self>) {
158        self.send_to_model(RequestKind::Chat, window, cx);
159    }
160
161    fn is_editor_empty(&self, cx: &App) -> bool {
162        self.editor.read(cx).text(cx).is_empty()
163    }
164
165    fn is_model_selected(&self, cx: &App) -> bool {
166        LanguageModelRegistry::read_global(cx)
167            .active_model()
168            .is_some()
169    }
170
171    fn send_to_model(
172        &mut self,
173        request_kind: RequestKind,
174        window: &mut Window,
175        cx: &mut Context<Self>,
176    ) {
177        let provider = LanguageModelRegistry::read_global(cx).active_provider();
178        if provider
179            .as_ref()
180            .map_or(false, |provider| provider.must_accept_terms(cx))
181        {
182            cx.notify();
183            return;
184        }
185
186        let model_registry = LanguageModelRegistry::read_global(cx);
187        let Some(model) = model_registry.active_model() else {
188            return;
189        };
190
191        let user_message = self.editor.update(cx, |editor, cx| {
192            let text = editor.text(cx);
193            editor.clear(window, cx);
194            text
195        });
196
197        let refresh_task = refresh_context_store_text(self.context_store.clone(), cx);
198
199        let thread = self.thread.clone();
200        let context_store = self.context_store.clone();
201        let use_tools = self.use_tools;
202        cx.spawn(move |_, mut cx| async move {
203            refresh_task.await;
204            thread
205                .update(&mut cx, |thread, cx| {
206                    let context = context_store.read(cx).snapshot(cx).collect::<Vec<_>>();
207                    thread.insert_user_message(user_message, context, cx);
208                    thread.send_to_model(model, request_kind, use_tools, cx);
209                })
210                .ok();
211        })
212        .detach();
213    }
214
215    fn handle_editor_event(
216        &mut self,
217        editor: &Entity<Editor>,
218        event: &EditorEvent,
219        window: &mut Window,
220        cx: &mut Context<Self>,
221    ) {
222        match event {
223            EditorEvent::SelectionsChanged { .. } => {
224                editor.update(cx, |editor, cx| {
225                    let snapshot = editor.buffer().read(cx).snapshot(cx);
226                    let newest_cursor = editor.selections.newest::<Point>(cx).head();
227                    if newest_cursor.column > 0 {
228                        let behind_cursor = snapshot.clip_point(
229                            Point::new(newest_cursor.row, newest_cursor.column - 1),
230                            Bias::Left,
231                        );
232                        let char_behind_cursor = snapshot.chars_at(behind_cursor).next();
233                        if char_behind_cursor == Some('@') {
234                            self.inline_context_picker_menu_handle.show(window, cx);
235                        }
236                    }
237                });
238            }
239            _ => {}
240        }
241    }
242
243    fn handle_inline_context_picker_event(
244        &mut self,
245        _inline_context_picker: &Entity<ContextPicker>,
246        _event: &DismissEvent,
247        window: &mut Window,
248        cx: &mut Context<Self>,
249    ) {
250        let editor_focus_handle = self.editor.focus_handle(cx);
251        window.focus(&editor_focus_handle);
252    }
253
254    fn handle_context_strip_event(
255        &mut self,
256        _context_strip: &Entity<ContextStrip>,
257        event: &ContextStripEvent,
258        window: &mut Window,
259        cx: &mut Context<Self>,
260    ) {
261        match event {
262            ContextStripEvent::PickerDismissed
263            | ContextStripEvent::BlurredEmpty
264            | ContextStripEvent::BlurredDown => {
265                let editor_focus_handle = self.editor.focus_handle(cx);
266                window.focus(&editor_focus_handle);
267            }
268            ContextStripEvent::BlurredUp => {}
269        }
270    }
271
272    fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
273        if self.context_picker_menu_handle.is_deployed()
274            || self.inline_context_picker_menu_handle.is_deployed()
275        {
276            cx.propagate();
277        } else {
278            self.context_strip.focus_handle(cx).focus(window);
279        }
280    }
281}
282
283impl Focusable for MessageEditor {
284    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
285        self.editor.focus_handle(cx)
286    }
287}
288
289impl Render for MessageEditor {
290    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
291        let font_size = TextSize::Default.rems(cx);
292        let line_height = font_size.to_pixels(window.rem_size()) * 1.5;
293        let focus_handle = self.editor.focus_handle(cx);
294        let inline_context_picker = self.inline_context_picker.clone();
295        let bg_color = cx.theme().colors().editor_background;
296        let is_streaming_completion = self.thread.read(cx).is_streaming();
297        let button_width = px(64.);
298        let is_model_selected = self.is_model_selected(cx);
299        let is_editor_empty = self.is_editor_empty(cx);
300        let submit_label_color = if is_editor_empty {
301            Color::Muted
302        } else {
303            Color::Default
304        };
305
306        v_flex()
307            .key_context("MessageEditor")
308            .on_action(cx.listener(Self::chat))
309            .on_action(cx.listener(Self::toggle_model_selector))
310            .on_action(cx.listener(Self::toggle_context_picker))
311            .on_action(cx.listener(Self::remove_all_context))
312            .on_action(cx.listener(Self::move_up))
313            .on_action(cx.listener(Self::toggle_chat_mode))
314            .size_full()
315            .gap_2()
316            .p_2()
317            .bg(bg_color)
318            .child(self.context_strip.clone())
319            .child(
320                v_flex()
321                    .gap_4()
322                    .child({
323                        let settings = ThemeSettings::get_global(cx);
324                        let text_style = TextStyle {
325                            color: cx.theme().colors().text,
326                            font_family: settings.ui_font.family.clone(),
327                            font_features: settings.ui_font.features.clone(),
328                            font_size: font_size.into(),
329                            font_weight: settings.ui_font.weight,
330                            line_height: line_height.into(),
331                            ..Default::default()
332                        };
333
334                        EditorElement::new(
335                            &self.editor,
336                            EditorStyle {
337                                background: bg_color,
338                                local_player: cx.theme().players().local(),
339                                text: text_style,
340                                ..Default::default()
341                            },
342                        )
343                    })
344                    .child(
345                        PopoverMenu::new("inline-context-picker")
346                            .menu(move |window, cx| {
347                                inline_context_picker.update(cx, |this, cx| {
348                                    this.init(window, cx);
349                                });
350
351                                Some(inline_context_picker.clone())
352                            })
353                            .attach(gpui::Corner::TopLeft)
354                            .anchor(gpui::Corner::BottomLeft)
355                            .offset(gpui::Point {
356                                x: px(0.0),
357                                y: (-ThemeSettings::get_global(cx).ui_font_size(cx) * 2) - px(4.0),
358                            })
359                            .with_handle(self.inline_context_picker_menu_handle.clone()),
360                    )
361                    .child(
362                        h_flex()
363                            .justify_between()
364                            .child(
365                                Switch::new("use-tools", self.use_tools.into())
366                                    .label("Tools")
367                                    .on_click(cx.listener(|this, selection, _window, _cx| {
368                                        this.use_tools = match selection {
369                                            ToggleState::Selected => true,
370                                            ToggleState::Unselected
371                                            | ToggleState::Indeterminate => false,
372                                        };
373                                    }))
374                                    .key_binding(KeyBinding::for_action_in(
375                                        &ChatMode,
376                                        &focus_handle,
377                                        window,
378                                        cx,
379                                    )),
380                            )
381                            .child(h_flex().gap_1().child(self.model_selector.clone()).child(
382                                if is_streaming_completion {
383                                    ButtonLike::new("cancel-generation")
384                                        .width(button_width.into())
385                                        .style(ButtonStyle::Tinted(TintColor::Accent))
386                                        .child(
387                                            h_flex()
388                                                .w_full()
389                                                .justify_between()
390                                                .child(
391                                                    Label::new("Cancel")
392                                                        .size(LabelSize::Small)
393                                                        .with_animation(
394                                                            "pulsating-label",
395                                                            Animation::new(Duration::from_secs(2))
396                                                                .repeat()
397                                                                .with_easing(pulsating_between(
398                                                                    0.4, 0.8,
399                                                                )),
400                                                            |label, delta| label.alpha(delta),
401                                                        ),
402                                                )
403                                                .children(
404                                                    KeyBinding::for_action_in(
405                                                        &editor::actions::Cancel,
406                                                        &focus_handle,
407                                                        window,
408                                                        cx,
409                                                    )
410                                                    .map(|binding| binding.into_any_element()),
411                                                ),
412                                        )
413                                        .on_click(move |_event, window, cx| {
414                                            focus_handle.dispatch_action(
415                                                &editor::actions::Cancel,
416                                                window,
417                                                cx,
418                                            );
419                                        })
420                                } else {
421                                    ButtonLike::new("submit-message")
422                                        .width(button_width.into())
423                                        .style(ButtonStyle::Filled)
424                                        .disabled(is_editor_empty || !is_model_selected)
425                                        .child(
426                                            h_flex()
427                                                .w_full()
428                                                .justify_between()
429                                                .child(
430                                                    Label::new("Submit")
431                                                        .size(LabelSize::Small)
432                                                        .color(submit_label_color),
433                                                )
434                                                .children(
435                                                    KeyBinding::for_action_in(
436                                                        &Chat,
437                                                        &focus_handle,
438                                                        window,
439                                                        cx,
440                                                    )
441                                                    .map(|binding| binding.into_any_element()),
442                                                ),
443                                        )
444                                        .on_click(move |_event, window, cx| {
445                                            focus_handle.dispatch_action(&Chat, window, cx);
446                                        })
447                                        .when(is_editor_empty, |button| {
448                                            button
449                                                .tooltip(Tooltip::text("Type a message to submit"))
450                                        })
451                                        .when(!is_model_selected, |button| {
452                                            button.tooltip(Tooltip::text(
453                                                "Select a model to continue",
454                                            ))
455                                        })
456                                },
457                            )),
458                    ),
459            )
460    }
461}