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, Switch,
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 context_picker_menu_handle.clone(),
79 SuggestContextKind::File,
80 cx,
81 )
82 });
83
84 let subscriptions = vec![
85 cx.subscribe(&editor, Self::handle_editor_event),
86 cx.subscribe(
87 &inline_context_picker,
88 Self::handle_inline_context_picker_event,
89 ),
90 cx.subscribe(&context_strip, Self::handle_context_strip_event),
91 ];
92
93 Self {
94 thread,
95 editor: editor.clone(),
96 context_store,
97 context_strip,
98 context_picker_menu_handle,
99 inline_context_picker,
100 inline_context_picker_menu_handle,
101 model_selector: cx.new_view(|cx| {
102 AssistantModelSelector::new(
103 fs,
104 model_selector_menu_handle.clone(),
105 editor.focus_handle(cx),
106 cx,
107 )
108 }),
109 model_selector_menu_handle,
110 use_tools: false,
111 _subscriptions: subscriptions,
112 }
113 }
114
115 fn toggle_model_selector(&mut self, _: &ToggleModelSelector, cx: &mut ViewContext<Self>) {
116 self.model_selector_menu_handle.toggle(cx)
117 }
118
119 fn toggle_context_picker(&mut self, _: &ToggleContextPicker, cx: &mut ViewContext<Self>) {
120 self.context_picker_menu_handle.toggle(cx);
121 }
122
123 pub fn remove_all_context(&mut self, _: &RemoveAllContext, cx: &mut ViewContext<Self>) {
124 self.context_store.update(cx, |store, _cx| store.clear());
125 cx.notify();
126 }
127
128 fn chat(&mut self, _: &Chat, cx: &mut ViewContext<Self>) {
129 self.send_to_model(RequestKind::Chat, cx);
130 }
131
132 fn send_to_model(&mut self, request_kind: RequestKind, cx: &mut ViewContext<Self>) {
133 let provider = LanguageModelRegistry::read_global(cx).active_provider();
134 if provider
135 .as_ref()
136 .map_or(false, |provider| provider.must_accept_terms(cx))
137 {
138 cx.notify();
139 return;
140 }
141
142 let model_registry = LanguageModelRegistry::read_global(cx);
143 let Some(model) = model_registry.active_model() else {
144 return;
145 };
146
147 let user_message = self.editor.update(cx, |editor, cx| {
148 let text = editor.text(cx);
149 editor.clear(cx);
150 text
151 });
152
153 let refresh_task = refresh_context_store_text(self.context_store.clone(), cx);
154
155 let thread = self.thread.clone();
156 let context_store = self.context_store.clone();
157 let use_tools = self.use_tools;
158 cx.spawn(move |_, mut cx| async move {
159 refresh_task.await;
160 thread
161 .update(&mut cx, |thread, cx| {
162 let context = context_store.read(cx).snapshot(cx).collect::<Vec<_>>();
163 thread.insert_user_message(user_message, context, cx);
164 let mut request = thread.to_completion_request(request_kind, cx);
165
166 if use_tools {
167 request.tools = thread
168 .tools()
169 .tools(cx)
170 .into_iter()
171 .map(|tool| LanguageModelRequestTool {
172 name: tool.name(),
173 description: tool.description(),
174 input_schema: tool.input_schema(),
175 })
176 .collect();
177 }
178
179 thread.stream_completion(request, model, cx)
180 })
181 .ok();
182 })
183 .detach();
184 }
185
186 fn handle_editor_event(
187 &mut self,
188 editor: View<Editor>,
189 event: &EditorEvent,
190 cx: &mut ViewContext<Self>,
191 ) {
192 match event {
193 EditorEvent::SelectionsChanged { .. } => {
194 editor.update(cx, |editor, cx| {
195 let snapshot = editor.buffer().read(cx).snapshot(cx);
196 let newest_cursor = editor.selections.newest::<Point>(cx).head();
197 if newest_cursor.column > 0 {
198 let behind_cursor = Point::new(newest_cursor.row, newest_cursor.column - 1);
199 let char_behind_cursor = snapshot.chars_at(behind_cursor).next();
200 if char_behind_cursor == Some('@') {
201 self.inline_context_picker_menu_handle.show(cx);
202 }
203 }
204 });
205 }
206 _ => {}
207 }
208 }
209
210 fn handle_inline_context_picker_event(
211 &mut self,
212 _inline_context_picker: View<ContextPicker>,
213 _event: &DismissEvent,
214 cx: &mut ViewContext<Self>,
215 ) {
216 let editor_focus_handle = self.editor.focus_handle(cx);
217 cx.focus(&editor_focus_handle);
218 }
219
220 fn handle_context_strip_event(
221 &mut self,
222 _context_strip: View<ContextStrip>,
223 event: &ContextStripEvent,
224 cx: &mut ViewContext<Self>,
225 ) {
226 match event {
227 ContextStripEvent::PickerDismissed
228 | ContextStripEvent::BlurredEmpty
229 | ContextStripEvent::BlurredDown => {
230 let editor_focus_handle = self.editor.focus_handle(cx);
231 cx.focus(&editor_focus_handle);
232 }
233 ContextStripEvent::BlurredUp => {}
234 }
235 }
236
237 fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
238 if self.context_picker_menu_handle.is_deployed() {
239 cx.propagate();
240 } else {
241 cx.focus_view(&self.context_strip);
242 }
243 }
244}
245
246impl FocusableView for MessageEditor {
247 fn focus_handle(&self, cx: &AppContext) -> gpui::FocusHandle {
248 self.editor.focus_handle(cx)
249 }
250}
251
252impl Render for MessageEditor {
253 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
254 let font_size = TextSize::Default.rems(cx);
255 let line_height = font_size.to_pixels(cx.rem_size()) * 1.5;
256 let focus_handle = self.editor.focus_handle(cx);
257 let inline_context_picker = self.inline_context_picker.clone();
258 let bg_color = cx.theme().colors().editor_background;
259
260 v_flex()
261 .key_context("MessageEditor")
262 .on_action(cx.listener(Self::chat))
263 .on_action(cx.listener(Self::toggle_model_selector))
264 .on_action(cx.listener(Self::toggle_context_picker))
265 .on_action(cx.listener(Self::remove_all_context))
266 .on_action(cx.listener(Self::move_up))
267 .size_full()
268 .gap_2()
269 .p_2()
270 .bg(bg_color)
271 .child(self.context_strip.clone())
272 .child(
273 v_flex()
274 .gap_4()
275 .child({
276 let settings = ThemeSettings::get_global(cx);
277 let text_style = TextStyle {
278 color: cx.theme().colors().text,
279 font_family: settings.ui_font.family.clone(),
280 font_features: settings.ui_font.features.clone(),
281 font_size: font_size.into(),
282 font_weight: settings.ui_font.weight,
283 line_height: line_height.into(),
284 ..Default::default()
285 };
286
287 EditorElement::new(
288 &self.editor,
289 EditorStyle {
290 background: bg_color,
291 local_player: cx.theme().players().local(),
292 text: text_style,
293 ..Default::default()
294 },
295 )
296 })
297 .child(
298 PopoverMenu::new("inline-context-picker")
299 .menu(move |cx| {
300 inline_context_picker.update(cx, |this, cx| {
301 this.init(cx);
302 });
303
304 Some(inline_context_picker.clone())
305 })
306 .attach(gpui::Corner::TopLeft)
307 .anchor(gpui::Corner::BottomLeft)
308 .offset(gpui::Point {
309 x: px(0.0),
310 y: (-get_ui_font_size(cx) * 2) - px(4.0),
311 })
312 .with_handle(self.inline_context_picker_menu_handle.clone()),
313 )
314 .child(
315 h_flex()
316 .justify_between()
317 .child(
318 Switch::new("use-tools", self.use_tools.into())
319 .label("Tools")
320 .on_click(cx.listener(|this, selection, _cx| {
321 this.use_tools = match selection {
322 ToggleState::Selected => true,
323 ToggleState::Unselected
324 | ToggleState::Indeterminate => false,
325 };
326 })),
327 )
328 .child(
329 h_flex().gap_1().child(self.model_selector.clone()).child(
330 ButtonLike::new("chat")
331 .style(ButtonStyle::Filled)
332 .layer(ElevationIndex::ModalSurface)
333 .child(Label::new("Submit").size(LabelSize::Small))
334 .children(
335 KeyBinding::for_action_in(&Chat, &focus_handle, cx)
336 .map(|binding| binding.into_any_element()),
337 )
338 .on_click(move |_event, cx| {
339 focus_handle.dispatch_action(&Chat, cx);
340 }),
341 ),
342 ),
343 ),
344 )
345 }
346}