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