message_editor.rs

  1use std::sync::Arc;
  2
  3use editor::{Editor, EditorElement, EditorEvent, EditorStyle};
  4use fs::Fs;
  5use gpui::{
  6    AppContext, DismissEvent, FocusableView, Model, Subscription, TextStyle, View, WeakModel,
  7    WeakView,
  8};
  9use language_model::{LanguageModelRegistry, LanguageModelRequestTool};
 10use language_model_selector::LanguageModelSelector;
 11use rope::Point;
 12use settings::Settings;
 13use theme::{get_ui_font_size, ThemeSettings};
 14use ui::{
 15    prelude::*, ButtonLike, ElevationIndex, KeyBinding, PopoverMenu, PopoverMenuHandle,
 16    SwitchWithLabel,
 17};
 18use workspace::Workspace;
 19
 20use crate::assistant_model_selector::AssistantModelSelector;
 21use crate::context_picker::{ConfirmBehavior, ContextPicker};
 22use crate::context_store::{refresh_context_store_text, ContextStore};
 23use crate::context_strip::{ContextStrip, ContextStripEvent, SuggestContextKind};
 24use crate::thread::{RequestKind, Thread};
 25use crate::thread_store::ThreadStore;
 26use crate::{Chat, RemoveAllContext, ToggleContextPicker, ToggleModelSelector};
 27
 28pub struct MessageEditor {
 29    thread: Model<Thread>,
 30    editor: View<Editor>,
 31    context_store: Model<ContextStore>,
 32    context_strip: View<ContextStrip>,
 33    context_picker_menu_handle: PopoverMenuHandle<ContextPicker>,
 34    inline_context_picker: View<ContextPicker>,
 35    inline_context_picker_menu_handle: PopoverMenuHandle<ContextPicker>,
 36    model_selector: View<AssistantModelSelector>,
 37    model_selector_menu_handle: PopoverMenuHandle<LanguageModelSelector>,
 38    use_tools: bool,
 39    _subscriptions: Vec<Subscription>,
 40}
 41
 42impl MessageEditor {
 43    pub fn new(
 44        fs: Arc<dyn Fs>,
 45        workspace: WeakView<Workspace>,
 46        thread_store: WeakModel<ThreadStore>,
 47        thread: Model<Thread>,
 48        cx: &mut ViewContext<Self>,
 49    ) -> Self {
 50        let context_store = cx.new_model(|_cx| ContextStore::new(workspace.clone()));
 51        let context_picker_menu_handle = PopoverMenuHandle::default();
 52        let inline_context_picker_menu_handle = PopoverMenuHandle::default();
 53        let model_selector_menu_handle = PopoverMenuHandle::default();
 54
 55        let editor = cx.new_view(|cx| {
 56            let mut editor = Editor::auto_height(10, cx);
 57            editor.set_placeholder_text("Ask anything…", cx);
 58            editor.set_show_indent_guides(false, cx);
 59
 60            editor
 61        });
 62
 63        let inline_context_picker = cx.new_view(|cx| {
 64            ContextPicker::new(
 65                workspace.clone(),
 66                Some(thread_store.clone()),
 67                context_store.downgrade(),
 68                ConfirmBehavior::Close,
 69                cx,
 70            )
 71        });
 72
 73        let context_strip = cx.new_view(|cx| {
 74            ContextStrip::new(
 75                context_store.clone(),
 76                workspace.clone(),
 77                Some(thread_store.clone()),
 78                editor.focus_handle(cx),
 79                context_picker_menu_handle.clone(),
 80                SuggestContextKind::File,
 81                cx,
 82            )
 83        });
 84
 85        let subscriptions = vec![
 86            cx.subscribe(&editor, Self::handle_editor_event),
 87            cx.subscribe(
 88                &inline_context_picker,
 89                Self::handle_inline_context_picker_event,
 90            ),
 91            cx.subscribe(&context_strip, Self::handle_context_strip_event),
 92        ];
 93
 94        Self {
 95            thread,
 96            editor: editor.clone(),
 97            context_store,
 98            context_strip,
 99            context_picker_menu_handle,
100            inline_context_picker,
101            inline_context_picker_menu_handle,
102            model_selector: cx.new_view(|cx| {
103                AssistantModelSelector::new(
104                    fs,
105                    model_selector_menu_handle.clone(),
106                    editor.focus_handle(cx),
107                    cx,
108                )
109            }),
110            model_selector_menu_handle,
111            use_tools: false,
112            _subscriptions: subscriptions,
113        }
114    }
115
116    fn toggle_model_selector(&mut self, _: &ToggleModelSelector, cx: &mut ViewContext<Self>) {
117        self.model_selector_menu_handle.toggle(cx)
118    }
119
120    fn toggle_context_picker(&mut self, _: &ToggleContextPicker, cx: &mut ViewContext<Self>) {
121        self.context_picker_menu_handle.toggle(cx);
122    }
123
124    pub fn remove_all_context(&mut self, _: &RemoveAllContext, cx: &mut ViewContext<Self>) {
125        self.context_store.update(cx, |store, _cx| store.clear());
126        cx.notify();
127    }
128
129    fn chat(&mut self, _: &Chat, cx: &mut ViewContext<Self>) {
130        self.send_to_model(RequestKind::Chat, cx);
131    }
132
133    fn send_to_model(&mut self, request_kind: RequestKind, cx: &mut ViewContext<Self>) {
134        let provider = LanguageModelRegistry::read_global(cx).active_provider();
135        if provider
136            .as_ref()
137            .map_or(false, |provider| provider.must_accept_terms(cx))
138        {
139            cx.notify();
140            return;
141        }
142
143        let model_registry = LanguageModelRegistry::read_global(cx);
144        let Some(model) = model_registry.active_model() else {
145            return;
146        };
147
148        let user_message = self.editor.update(cx, |editor, cx| {
149            let text = editor.text(cx);
150            editor.clear(cx);
151            text
152        });
153
154        let refresh_task = refresh_context_store_text(self.context_store.clone(), cx);
155
156        let thread = self.thread.clone();
157        let context_store = self.context_store.clone();
158        let use_tools = self.use_tools;
159        cx.spawn(move |_, mut cx| async move {
160            refresh_task.await;
161            thread
162                .update(&mut cx, |thread, cx| {
163                    let context = context_store.read(cx).snapshot(cx).collect::<Vec<_>>();
164                    thread.insert_user_message(user_message, context, cx);
165                    let mut request = thread.to_completion_request(request_kind, cx);
166
167                    if use_tools {
168                        request.tools = thread
169                            .tools()
170                            .tools(cx)
171                            .into_iter()
172                            .map(|tool| LanguageModelRequestTool {
173                                name: tool.name(),
174                                description: tool.description(),
175                                input_schema: tool.input_schema(),
176                            })
177                            .collect();
178                    }
179
180                    thread.stream_completion(request, model, cx)
181                })
182                .ok();
183        })
184        .detach();
185    }
186
187    fn handle_editor_event(
188        &mut self,
189        editor: View<Editor>,
190        event: &EditorEvent,
191        cx: &mut ViewContext<Self>,
192    ) {
193        match event {
194            EditorEvent::SelectionsChanged { .. } => {
195                editor.update(cx, |editor, cx| {
196                    let snapshot = editor.buffer().read(cx).snapshot(cx);
197                    let newest_cursor = editor.selections.newest::<Point>(cx).head();
198                    if newest_cursor.column > 0 {
199                        let behind_cursor = Point::new(newest_cursor.row, newest_cursor.column - 1);
200                        let char_behind_cursor = snapshot.chars_at(behind_cursor).next();
201                        if char_behind_cursor == Some('@') {
202                            self.inline_context_picker_menu_handle.show(cx);
203                        }
204                    }
205                });
206            }
207            _ => {}
208        }
209    }
210
211    fn handle_inline_context_picker_event(
212        &mut self,
213        _inline_context_picker: View<ContextPicker>,
214        _event: &DismissEvent,
215        cx: &mut ViewContext<Self>,
216    ) {
217        let editor_focus_handle = self.editor.focus_handle(cx);
218        cx.focus(&editor_focus_handle);
219    }
220
221    fn handle_context_strip_event(
222        &mut self,
223        _context_strip: View<ContextStrip>,
224        ContextStripEvent::PickerDismissed: &ContextStripEvent,
225        cx: &mut ViewContext<Self>,
226    ) {
227        let editor_focus_handle = self.editor.focus_handle(cx);
228        cx.focus(&editor_focus_handle);
229    }
230}
231
232impl FocusableView for MessageEditor {
233    fn focus_handle(&self, cx: &AppContext) -> gpui::FocusHandle {
234        self.editor.focus_handle(cx)
235    }
236}
237
238impl Render for MessageEditor {
239    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
240        let font_size = TextSize::Default.rems(cx);
241        let line_height = font_size.to_pixels(cx.rem_size()) * 1.5;
242        let focus_handle = self.editor.focus_handle(cx);
243        let inline_context_picker = self.inline_context_picker.clone();
244        let bg_color = cx.theme().colors().editor_background;
245
246        v_flex()
247            .key_context("MessageEditor")
248            .on_action(cx.listener(Self::chat))
249            .on_action(cx.listener(Self::toggle_model_selector))
250            .on_action(cx.listener(Self::toggle_context_picker))
251            .on_action(cx.listener(Self::remove_all_context))
252            .size_full()
253            .gap_2()
254            .p_2()
255            .bg(bg_color)
256            .child(self.context_strip.clone())
257            .child(
258                v_flex()
259                    .gap_4()
260                    .child({
261                        let settings = ThemeSettings::get_global(cx);
262                        let text_style = TextStyle {
263                            color: cx.theme().colors().text,
264                            font_family: settings.ui_font.family.clone(),
265                            font_features: settings.ui_font.features.clone(),
266                            font_size: font_size.into(),
267                            font_weight: settings.ui_font.weight,
268                            line_height: line_height.into(),
269                            ..Default::default()
270                        };
271
272                        EditorElement::new(
273                            &self.editor,
274                            EditorStyle {
275                                background: bg_color,
276                                local_player: cx.theme().players().local(),
277                                text: text_style,
278                                ..Default::default()
279                            },
280                        )
281                    })
282                    .child(
283                        PopoverMenu::new("inline-context-picker")
284                            .menu(move |_cx| Some(inline_context_picker.clone()))
285                            .attach(gpui::Corner::TopLeft)
286                            .anchor(gpui::Corner::BottomLeft)
287                            .offset(gpui::Point {
288                                x: px(0.0),
289                                y: (-get_ui_font_size(cx) * 2) - px(4.0),
290                            })
291                            .with_handle(self.inline_context_picker_menu_handle.clone()),
292                    )
293                    .child(
294                        h_flex()
295                            .justify_between()
296                            .child(SwitchWithLabel::new(
297                                "use-tools",
298                                Label::new("Tools").size(LabelSize::Small),
299                                self.use_tools.into(),
300                                cx.listener(|this, selection, _cx| {
301                                    this.use_tools = match selection {
302                                        ToggleState::Selected => true,
303                                        ToggleState::Unselected | ToggleState::Indeterminate => {
304                                            false
305                                        }
306                                    };
307                                }),
308                            ))
309                            .child(
310                                h_flex().gap_1().child(self.model_selector.clone()).child(
311                                    ButtonLike::new("chat")
312                                        .style(ButtonStyle::Filled)
313                                        .layer(ElevationIndex::ModalSurface)
314                                        .child(Label::new("Submit").size(LabelSize::Small))
315                                        .children(
316                                            KeyBinding::for_action_in(&Chat, &focus_handle, cx)
317                                                .map(|binding| binding.into_any_element()),
318                                        )
319                                        .on_click(move |_event, cx| {
320                                            focus_handle.dispatch_action(&Chat, cx);
321                                        }),
322                                ),
323                            ),
324                    ),
325            )
326    }
327}