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::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::ContextStore;
 23use crate::context_strip::ContextStrip;
 24use crate::thread::{RequestKind, Thread};
 25use crate::thread_store::ThreadStore;
 26use crate::{Chat, 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());
 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        let inline_context_picker = cx.new_view(|cx| {
 63            ContextPicker::new(
 64                workspace.clone(),
 65                Some(thread_store.clone()),
 66                context_store.downgrade(),
 67                ConfirmBehavior::Close,
 68                cx,
 69            )
 70        });
 71        let subscriptions = vec![
 72            cx.subscribe(&editor, Self::handle_editor_event),
 73            cx.subscribe(
 74                &inline_context_picker,
 75                Self::handle_inline_context_picker_event,
 76            ),
 77        ];
 78
 79        Self {
 80            thread,
 81            editor: editor.clone(),
 82            context_store: context_store.clone(),
 83            context_strip: cx.new_view(|cx| {
 84                ContextStrip::new(
 85                    context_store,
 86                    workspace.clone(),
 87                    Some(thread_store.clone()),
 88                    editor.focus_handle(cx),
 89                    context_picker_menu_handle.clone(),
 90                    cx,
 91                )
 92            }),
 93            context_picker_menu_handle,
 94            inline_context_picker,
 95            inline_context_picker_menu_handle,
 96            model_selector: cx.new_view(|cx| {
 97                AssistantModelSelector::new(fs, model_selector_menu_handle.clone(), cx)
 98            }),
 99            model_selector_menu_handle,
100            use_tools: false,
101            _subscriptions: subscriptions,
102        }
103    }
104
105    fn toggle_model_selector(&mut self, _: &ToggleModelSelector, cx: &mut ViewContext<Self>) {
106        self.model_selector_menu_handle.toggle(cx)
107    }
108
109    fn toggle_context_picker(&mut self, _: &ToggleContextPicker, cx: &mut ViewContext<Self>) {
110        self.context_picker_menu_handle.toggle(cx);
111    }
112
113    fn chat(&mut self, _: &Chat, cx: &mut ViewContext<Self>) {
114        self.send_to_model(RequestKind::Chat, cx);
115    }
116
117    fn send_to_model(
118        &mut self,
119        request_kind: RequestKind,
120        cx: &mut ViewContext<Self>,
121    ) -> Option<()> {
122        let provider = LanguageModelRegistry::read_global(cx).active_provider();
123        if provider
124            .as_ref()
125            .map_or(false, |provider| provider.must_accept_terms(cx))
126        {
127            cx.notify();
128            return None;
129        }
130
131        let model_registry = LanguageModelRegistry::read_global(cx);
132        let model = model_registry.active_model()?;
133
134        let user_message = self.editor.update(cx, |editor, cx| {
135            let text = editor.text(cx);
136            editor.clear(cx);
137            text
138        });
139        let context = self.context_store.update(cx, |this, _cx| this.drain());
140
141        self.thread.update(cx, |thread, cx| {
142            thread.insert_user_message(user_message, context, cx);
143            let mut request = thread.to_completion_request(request_kind, cx);
144
145            if self.use_tools {
146                request.tools = thread
147                    .tools()
148                    .tools(cx)
149                    .into_iter()
150                    .map(|tool| LanguageModelRequestTool {
151                        name: tool.name(),
152                        description: tool.description(),
153                        input_schema: tool.input_schema(),
154                    })
155                    .collect();
156            }
157
158            thread.stream_completion(request, model, cx)
159        });
160
161        None
162    }
163
164    fn handle_editor_event(
165        &mut self,
166        editor: View<Editor>,
167        event: &EditorEvent,
168        cx: &mut ViewContext<Self>,
169    ) {
170        match event {
171            EditorEvent::SelectionsChanged { .. } => {
172                editor.update(cx, |editor, cx| {
173                    let snapshot = editor.buffer().read(cx).snapshot(cx);
174                    let newest_cursor = editor.selections.newest::<Point>(cx).head();
175                    if newest_cursor.column > 0 {
176                        let behind_cursor = Point::new(newest_cursor.row, newest_cursor.column - 1);
177                        let char_behind_cursor = snapshot.chars_at(behind_cursor).next();
178                        if char_behind_cursor == Some('@') {
179                            self.inline_context_picker_menu_handle.show(cx);
180                        }
181                    }
182                });
183            }
184            _ => {}
185        }
186    }
187
188    fn handle_inline_context_picker_event(
189        &mut self,
190        _inline_context_picker: View<ContextPicker>,
191        _event: &DismissEvent,
192        cx: &mut ViewContext<Self>,
193    ) {
194        let editor_focus_handle = self.editor.focus_handle(cx);
195        cx.focus(&editor_focus_handle);
196    }
197}
198
199impl FocusableView for MessageEditor {
200    fn focus_handle(&self, cx: &AppContext) -> gpui::FocusHandle {
201        self.editor.focus_handle(cx)
202    }
203}
204
205impl Render for MessageEditor {
206    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
207        let font_size = TextSize::Default.rems(cx);
208        let line_height = font_size.to_pixels(cx.rem_size()) * 1.5;
209        let focus_handle = self.editor.focus_handle(cx);
210        let inline_context_picker = self.inline_context_picker.clone();
211        let bg_color = cx.theme().colors().editor_background;
212
213        v_flex()
214            .key_context("MessageEditor")
215            .on_action(cx.listener(Self::chat))
216            .on_action(cx.listener(Self::toggle_model_selector))
217            .on_action(cx.listener(Self::toggle_context_picker))
218            .size_full()
219            .gap_2()
220            .p_2()
221            .bg(bg_color)
222            .child(self.context_strip.clone())
223            .child(
224                v_flex()
225                    .gap_4()
226                    .child({
227                        let settings = ThemeSettings::get_global(cx);
228                        let text_style = TextStyle {
229                            color: cx.theme().colors().text,
230                            font_family: settings.ui_font.family.clone(),
231                            font_features: settings.ui_font.features.clone(),
232                            font_size: font_size.into(),
233                            font_weight: settings.ui_font.weight,
234                            line_height: line_height.into(),
235                            ..Default::default()
236                        };
237
238                        EditorElement::new(
239                            &self.editor,
240                            EditorStyle {
241                                background: bg_color,
242                                local_player: cx.theme().players().local(),
243                                text: text_style,
244                                ..Default::default()
245                            },
246                        )
247                    })
248                    .child(
249                        PopoverMenu::new("inline-context-picker")
250                            .menu(move |_cx| Some(inline_context_picker.clone()))
251                            .attach(gpui::Corner::TopLeft)
252                            .anchor(gpui::Corner::BottomLeft)
253                            .offset(gpui::Point {
254                                x: px(0.0),
255                                y: px(-16.0),
256                            })
257                            .with_handle(self.inline_context_picker_menu_handle.clone()),
258                    )
259                    .child(
260                        h_flex()
261                            .justify_between()
262                            .child(SwitchWithLabel::new(
263                                "use-tools",
264                                Label::new("Tools"),
265                                self.use_tools.into(),
266                                cx.listener(|this, selection, _cx| {
267                                    this.use_tools = match selection {
268                                        ToggleState::Selected => true,
269                                        ToggleState::Unselected | ToggleState::Indeterminate => {
270                                            false
271                                        }
272                                    };
273                                }),
274                            ))
275                            .child(
276                                h_flex().gap_1().child(self.model_selector.clone()).child(
277                                    ButtonLike::new("chat")
278                                        .style(ButtonStyle::Filled)
279                                        .layer(ElevationIndex::ModalSurface)
280                                        .child(Label::new("Submit"))
281                                        .children(
282                                            KeyBinding::for_action_in(&Chat, &focus_handle, cx)
283                                                .map(|binding| binding.into_any_element()),
284                                        )
285                                        .on_click(move |_event, cx| {
286                                            focus_handle.dispatch_action(&Chat, cx);
287                                        }),
288                                ),
289                            ),
290                    ),
291            )
292    }
293}