1use std::sync::Arc;
2
3use editor::actions::MoveUp;
4use editor::{Editor, EditorElement, EditorEvent, EditorStyle};
5use fs::Fs;
6use gpui::{
7 AppContext, DismissEvent, FocusableView, Model, Subscription, TextStyle, View, WeakModel,
8 WeakView,
9};
10use language_model::{LanguageModelRegistry, LanguageModelRequestTool};
11use language_model_selector::LanguageModelSelector;
12use rope::Point;
13use settings::Settings;
14use theme::{get_ui_font_size, ThemeSettings};
15use ui::{
16 prelude::*, ButtonLike, ElevationIndex, KeyBinding, PopoverMenu, PopoverMenuHandle,
17 SwitchWithLabel,
18};
19use workspace::Workspace;
20
21use crate::assistant_model_selector::AssistantModelSelector;
22use crate::context_picker::{ConfirmBehavior, ContextPicker};
23use crate::context_store::{refresh_context_store_text, ContextStore};
24use crate::context_strip::{ContextStrip, ContextStripEvent, SuggestContextKind};
25use crate::thread::{RequestKind, Thread};
26use crate::thread_store::ThreadStore;
27use crate::{Chat, RemoveAllContext, ToggleContextPicker, ToggleModelSelector};
28
29pub struct MessageEditor {
30 thread: Model<Thread>,
31 editor: View<Editor>,
32 context_store: Model<ContextStore>,
33 context_strip: View<ContextStrip>,
34 context_picker_menu_handle: PopoverMenuHandle<ContextPicker>,
35 inline_context_picker: View<ContextPicker>,
36 inline_context_picker_menu_handle: PopoverMenuHandle<ContextPicker>,
37 model_selector: View<AssistantModelSelector>,
38 model_selector_menu_handle: PopoverMenuHandle<LanguageModelSelector>,
39 use_tools: bool,
40 _subscriptions: Vec<Subscription>,
41}
42
43impl MessageEditor {
44 pub fn new(
45 fs: Arc<dyn Fs>,
46 workspace: WeakView<Workspace>,
47 thread_store: WeakModel<ThreadStore>,
48 thread: Model<Thread>,
49 cx: &mut ViewContext<Self>,
50 ) -> Self {
51 let context_store = cx.new_model(|_cx| ContextStore::new(workspace.clone()));
52 let context_picker_menu_handle = PopoverMenuHandle::default();
53 let inline_context_picker_menu_handle = PopoverMenuHandle::default();
54 let model_selector_menu_handle = PopoverMenuHandle::default();
55
56 let editor = cx.new_view(|cx| {
57 let mut editor = Editor::auto_height(10, cx);
58 editor.set_placeholder_text("Ask anything…", cx);
59 editor.set_show_indent_guides(false, cx);
60
61 editor
62 });
63
64 let inline_context_picker = cx.new_view(|cx| {
65 ContextPicker::new(
66 workspace.clone(),
67 Some(thread_store.clone()),
68 context_store.downgrade(),
69 ConfirmBehavior::Close,
70 cx,
71 )
72 });
73
74 let context_strip = cx.new_view(|cx| {
75 ContextStrip::new(
76 context_store.clone(),
77 workspace.clone(),
78 Some(thread_store.clone()),
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 event: &ContextStripEvent,
225 cx: &mut ViewContext<Self>,
226 ) {
227 match event {
228 ContextStripEvent::PickerDismissed
229 | ContextStripEvent::BlurredEmpty
230 | ContextStripEvent::BlurredDown => {
231 let editor_focus_handle = self.editor.focus_handle(cx);
232 cx.focus(&editor_focus_handle);
233 }
234 ContextStripEvent::BlurredUp => {}
235 }
236 }
237
238 fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
239 if self.context_picker_menu_handle.is_deployed() {
240 cx.propagate();
241 } else {
242 cx.focus_view(&self.context_strip);
243 }
244 }
245}
246
247impl FocusableView for MessageEditor {
248 fn focus_handle(&self, cx: &AppContext) -> gpui::FocusHandle {
249 self.editor.focus_handle(cx)
250 }
251}
252
253impl Render for MessageEditor {
254 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
255 let font_size = TextSize::Default.rems(cx);
256 let line_height = font_size.to_pixels(cx.rem_size()) * 1.5;
257 let focus_handle = self.editor.focus_handle(cx);
258 let inline_context_picker = self.inline_context_picker.clone();
259 let bg_color = cx.theme().colors().editor_background;
260
261 v_flex()
262 .key_context("MessageEditor")
263 .on_action(cx.listener(Self::chat))
264 .on_action(cx.listener(Self::toggle_model_selector))
265 .on_action(cx.listener(Self::toggle_context_picker))
266 .on_action(cx.listener(Self::remove_all_context))
267 .on_action(cx.listener(Self::move_up))
268 .size_full()
269 .gap_2()
270 .p_2()
271 .bg(bg_color)
272 .child(self.context_strip.clone())
273 .child(
274 v_flex()
275 .gap_4()
276 .child({
277 let settings = ThemeSettings::get_global(cx);
278 let text_style = TextStyle {
279 color: cx.theme().colors().text,
280 font_family: settings.ui_font.family.clone(),
281 font_features: settings.ui_font.features.clone(),
282 font_size: font_size.into(),
283 font_weight: settings.ui_font.weight,
284 line_height: line_height.into(),
285 ..Default::default()
286 };
287
288 EditorElement::new(
289 &self.editor,
290 EditorStyle {
291 background: bg_color,
292 local_player: cx.theme().players().local(),
293 text: text_style,
294 ..Default::default()
295 },
296 )
297 })
298 .child(
299 PopoverMenu::new("inline-context-picker")
300 .menu(move |cx| {
301 inline_context_picker.update(cx, |this, cx| {
302 this.init(cx);
303 });
304
305 Some(inline_context_picker.clone())
306 })
307 .attach(gpui::Corner::TopLeft)
308 .anchor(gpui::Corner::BottomLeft)
309 .offset(gpui::Point {
310 x: px(0.0),
311 y: (-get_ui_font_size(cx) * 2) - px(4.0),
312 })
313 .with_handle(self.inline_context_picker_menu_handle.clone()),
314 )
315 .child(
316 h_flex()
317 .justify_between()
318 .child(SwitchWithLabel::new(
319 "use-tools",
320 Label::new("Tools").size(LabelSize::Small),
321 self.use_tools.into(),
322 cx.listener(|this, selection, _cx| {
323 this.use_tools = match selection {
324 ToggleState::Selected => true,
325 ToggleState::Unselected | ToggleState::Indeterminate => {
326 false
327 }
328 };
329 }),
330 ))
331 .child(
332 h_flex().gap_1().child(self.model_selector.clone()).child(
333 ButtonLike::new("chat")
334 .style(ButtonStyle::Filled)
335 .layer(ElevationIndex::ModalSurface)
336 .child(Label::new("Submit").size(LabelSize::Small))
337 .children(
338 KeyBinding::for_action_in(&Chat, &focus_handle, cx)
339 .map(|binding| binding.into_any_element()),
340 )
341 .on_click(move |_event, cx| {
342 focus_handle.dispatch_action(&Chat, cx);
343 }),
344 ),
345 ),
346 ),
347 )
348 }
349}