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