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