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