1use crate::{InlineCompletion, InlineCompletionRating, Zeta};
2use editor::Editor;
3use gpui::{
4 actions, prelude::*, AppContext, DismissEvent, EventEmitter, FocusHandle, FocusableView,
5 HighlightStyle, Model, StyledText, TextStyle, View, ViewContext,
6};
7use language::{language_settings, OffsetRangeExt};
8use settings::Settings;
9use std::time::Duration;
10use theme::ThemeSettings;
11use ui::{prelude::*, KeyBinding, List, ListItem, ListItemSpacing, Tooltip};
12use workspace::{ModalView, Workspace};
13
14actions!(
15 zeta,
16 [
17 RateCompletions,
18 ThumbsUp,
19 ThumbsDown,
20 ThumbsUpActiveCompletion,
21 ThumbsDownActiveCompletion,
22 NextEdit,
23 PreviousEdit,
24 FocusCompletions,
25 PreviewCompletion,
26 ]
27);
28
29pub fn init(cx: &mut AppContext) {
30 cx.observe_new_views(move |workspace: &mut Workspace, _cx| {
31 workspace.register_action(|workspace, _: &RateCompletions, cx| {
32 RateCompletionModal::toggle(workspace, cx);
33 });
34 })
35 .detach();
36}
37
38pub struct RateCompletionModal {
39 zeta: Model<Zeta>,
40 active_completion: Option<ActiveCompletion>,
41 selected_index: usize,
42 focus_handle: FocusHandle,
43 _subscription: gpui::Subscription,
44}
45
46struct ActiveCompletion {
47 completion: InlineCompletion,
48 feedback_editor: View<Editor>,
49}
50
51impl RateCompletionModal {
52 pub fn toggle(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) {
53 if let Some(zeta) = Zeta::global(cx) {
54 workspace.toggle_modal(cx, |cx| RateCompletionModal::new(zeta, cx));
55 }
56 }
57
58 pub fn new(zeta: Model<Zeta>, cx: &mut ViewContext<Self>) -> Self {
59 let subscription = cx.observe(&zeta, |_, _, cx| cx.notify());
60 Self {
61 zeta,
62 selected_index: 0,
63 focus_handle: cx.focus_handle(),
64 active_completion: None,
65 _subscription: subscription,
66 }
67 }
68
69 fn dismiss(&mut self, _: &menu::Cancel, cx: &mut ViewContext<Self>) {
70 cx.emit(DismissEvent);
71 }
72
73 fn select_next(&mut self, _: &menu::SelectNext, cx: &mut ViewContext<Self>) {
74 self.selected_index += 1;
75 self.selected_index = usize::min(
76 self.selected_index,
77 self.zeta.read(cx).recent_completions().count(),
78 );
79 cx.notify();
80 }
81
82 fn select_prev(&mut self, _: &menu::SelectPrev, cx: &mut ViewContext<Self>) {
83 self.selected_index = self.selected_index.saturating_sub(1);
84 cx.notify();
85 }
86
87 fn select_next_edit(&mut self, _: &NextEdit, cx: &mut ViewContext<Self>) {
88 let next_index = self
89 .zeta
90 .read(cx)
91 .recent_completions()
92 .skip(self.selected_index)
93 .enumerate()
94 .skip(1) // Skip straight to the next item
95 .find(|(_, completion)| !completion.edits.is_empty())
96 .map(|(ix, _)| ix + self.selected_index);
97
98 if let Some(next_index) = next_index {
99 self.selected_index = next_index;
100 cx.notify();
101 }
102 }
103
104 fn select_prev_edit(&mut self, _: &PreviousEdit, cx: &mut ViewContext<Self>) {
105 let zeta = self.zeta.read(cx);
106 let completions_len = zeta.recent_completions_len();
107
108 let prev_index = self
109 .zeta
110 .read(cx)
111 .recent_completions()
112 .rev()
113 .skip((completions_len - 1) - self.selected_index)
114 .enumerate()
115 .skip(1) // Skip straight to the previous item
116 .find(|(_, completion)| !completion.edits.is_empty())
117 .map(|(ix, _)| self.selected_index - ix);
118
119 if let Some(prev_index) = prev_index {
120 self.selected_index = prev_index;
121 cx.notify();
122 }
123 cx.notify();
124 }
125
126 fn select_first(&mut self, _: &menu::SelectFirst, cx: &mut ViewContext<Self>) {
127 self.selected_index = 0;
128 cx.notify();
129 }
130
131 fn select_last(&mut self, _: &menu::SelectLast, cx: &mut ViewContext<Self>) {
132 self.selected_index = self.zeta.read(cx).recent_completions_len() - 1;
133 cx.notify();
134 }
135
136 fn thumbs_up(&mut self, _: &ThumbsUp, cx: &mut ViewContext<Self>) {
137 self.zeta.update(cx, |zeta, cx| {
138 let completion = zeta
139 .recent_completions()
140 .skip(self.selected_index)
141 .next()
142 .cloned();
143
144 if let Some(completion) = completion {
145 zeta.rate_completion(
146 &completion,
147 InlineCompletionRating::Positive,
148 "".to_string(),
149 cx,
150 );
151 }
152 });
153 self.select_next_edit(&Default::default(), cx);
154 cx.notify();
155 }
156
157 fn thumbs_up_active(&mut self, _: &ThumbsUpActiveCompletion, cx: &mut ViewContext<Self>) {
158 self.zeta.update(cx, |zeta, cx| {
159 if let Some(active) = &self.active_completion {
160 zeta.rate_completion(
161 &active.completion,
162 InlineCompletionRating::Positive,
163 active.feedback_editor.read(cx).text(cx),
164 cx,
165 );
166 }
167 });
168
169 let current_completion = self
170 .active_completion
171 .as_ref()
172 .map(|completion| completion.completion.clone());
173 self.select_completion(current_completion, false, cx);
174 self.select_next_edit(&Default::default(), cx);
175 self.confirm(&Default::default(), cx);
176
177 cx.notify();
178 }
179
180 fn thumbs_down_active(&mut self, _: &ThumbsDownActiveCompletion, cx: &mut ViewContext<Self>) {
181 if let Some(active) = &self.active_completion {
182 if active.feedback_editor.read(cx).text(cx).is_empty() {
183 return;
184 }
185
186 self.zeta.update(cx, |zeta, cx| {
187 zeta.rate_completion(
188 &active.completion,
189 InlineCompletionRating::Negative,
190 active.feedback_editor.read(cx).text(cx),
191 cx,
192 );
193 });
194 }
195
196 let current_completion = self
197 .active_completion
198 .as_ref()
199 .map(|completion| completion.completion.clone());
200 self.select_completion(current_completion, false, cx);
201 self.select_next_edit(&Default::default(), cx);
202 self.confirm(&Default::default(), cx);
203
204 cx.notify();
205 }
206
207 fn focus_completions(&mut self, _: &FocusCompletions, cx: &mut ViewContext<Self>) {
208 cx.focus_self();
209 cx.notify();
210 }
211
212 fn preview_completion(&mut self, _: &PreviewCompletion, cx: &mut ViewContext<Self>) {
213 let completion = self
214 .zeta
215 .read(cx)
216 .recent_completions()
217 .skip(self.selected_index)
218 .take(1)
219 .next()
220 .cloned();
221
222 self.select_completion(completion, false, cx);
223 }
224
225 fn confirm(&mut self, _: &menu::Confirm, cx: &mut ViewContext<Self>) {
226 let completion = self
227 .zeta
228 .read(cx)
229 .recent_completions()
230 .skip(self.selected_index)
231 .take(1)
232 .next()
233 .cloned();
234
235 self.select_completion(completion, true, cx);
236 }
237
238 pub fn select_completion(
239 &mut self,
240 completion: Option<InlineCompletion>,
241 focus: bool,
242 cx: &mut ViewContext<Self>,
243 ) {
244 // Avoid resetting completion rating if it's already selected.
245 if let Some(completion) = completion.as_ref() {
246 self.selected_index = self
247 .zeta
248 .read(cx)
249 .recent_completions()
250 .enumerate()
251 .find(|(_, completion_b)| completion.id == completion_b.id)
252 .map(|(ix, _)| ix)
253 .unwrap_or(self.selected_index);
254 cx.notify();
255
256 if let Some(prev_completion) = self.active_completion.as_ref() {
257 if completion.id == prev_completion.completion.id {
258 if focus {
259 cx.focus_view(&prev_completion.feedback_editor);
260 }
261 return;
262 }
263 }
264 }
265
266 self.active_completion = completion.map(|completion| ActiveCompletion {
267 completion,
268 feedback_editor: cx.new_view(|cx| {
269 let mut editor = Editor::multi_line(cx);
270 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
271 editor.set_show_line_numbers(false, cx);
272 editor.set_show_git_diff_gutter(false, cx);
273 editor.set_show_code_actions(false, cx);
274 editor.set_show_runnables(false, cx);
275 editor.set_show_wrap_guides(false, cx);
276 editor.set_show_indent_guides(false, cx);
277 editor.set_show_inline_completions(Some(false), cx);
278 editor.set_placeholder_text("Add your feedback…", cx);
279 if focus {
280 cx.focus_self();
281 }
282 editor
283 }),
284 });
285 cx.notify();
286 }
287
288 fn render_active_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<impl IntoElement> {
289 let active_completion = self.active_completion.as_ref()?;
290 let completion_id = active_completion.completion.id;
291
292 let mut diff = active_completion
293 .completion
294 .snapshot
295 .text_for_range(active_completion.completion.excerpt_range.clone())
296 .collect::<String>();
297
298 let mut delta = 0;
299 let mut diff_highlights = Vec::new();
300 for (old_range, new_text) in active_completion.completion.edits.iter() {
301 let old_range = old_range.to_offset(&active_completion.completion.snapshot);
302 let old_start_in_text =
303 old_range.start - active_completion.completion.excerpt_range.start + delta;
304 let old_end_in_text =
305 old_range.end - active_completion.completion.excerpt_range.start + delta;
306 if old_start_in_text < old_end_in_text {
307 diff_highlights.push((
308 old_start_in_text..old_end_in_text,
309 HighlightStyle {
310 background_color: Some(cx.theme().status().deleted_background),
311 strikethrough: Some(gpui::StrikethroughStyle {
312 thickness: px(1.),
313 color: Some(cx.theme().colors().text_muted),
314 }),
315 ..Default::default()
316 },
317 ));
318 }
319
320 if !new_text.is_empty() {
321 diff.insert_str(old_end_in_text, new_text);
322 diff_highlights.push((
323 old_end_in_text..old_end_in_text + new_text.len(),
324 HighlightStyle {
325 background_color: Some(cx.theme().status().created_background),
326 ..Default::default()
327 },
328 ));
329 delta += new_text.len();
330 }
331 }
332
333 let settings = ThemeSettings::get_global(cx).clone();
334 let text_style = TextStyle {
335 color: cx.theme().colors().editor_foreground,
336 font_size: settings.buffer_font_size(cx).into(),
337 font_family: settings.buffer_font.family,
338 font_features: settings.buffer_font.features,
339 font_fallbacks: settings.buffer_font.fallbacks,
340 line_height: relative(settings.buffer_line_height.value()),
341 font_weight: settings.buffer_font.weight,
342 font_style: settings.buffer_font.style,
343 ..Default::default()
344 };
345
346 let rated = self.zeta.read(cx).is_completion_rated(completion_id);
347 let was_shown = self.zeta.read(cx).was_completion_shown(completion_id);
348 let feedback_empty = active_completion
349 .feedback_editor
350 .read(cx)
351 .text(cx)
352 .is_empty();
353
354 let border_color = cx.theme().colors().border;
355 let bg_color = cx.theme().colors().editor_background;
356
357 let label_container = || h_flex().pl_1().gap_1p5();
358
359 Some(
360 v_flex()
361 .size_full()
362 .overflow_hidden()
363 .child(
364 div()
365 .id("diff")
366 .py_4()
367 .px_6()
368 .size_full()
369 .bg(bg_color)
370 .overflow_scroll()
371 .child(StyledText::new(diff).with_highlights(&text_style, diff_highlights)),
372 )
373 .when_some((!rated).then(|| ()), |this, _| {
374 this.child(
375 h_flex()
376 .p_2()
377 .gap_2()
378 .border_y_1()
379 .border_color(border_color)
380
381 .child(
382 Icon::new(IconName::Info)
383 .size(IconSize::XSmall)
384 .color(Color::Muted)
385 )
386 .child(
387 div()
388 .w_full()
389 .pr_2()
390 .flex_wrap()
391 .child(
392 Label::new("Ensure you explain why this completion is negative or positive. In case it's negative, report what you expected instead.")
393 .size(LabelSize::Small)
394 .color(Color::Muted)
395 )
396 )
397 )
398 })
399 .when_some((!rated).then(|| ()), |this, _| {
400 this.child(
401 div()
402 .h_40()
403 .pt_1()
404 .bg(bg_color)
405 .child(active_completion.feedback_editor.clone())
406 )
407 })
408 .child(
409 h_flex()
410 .p_1()
411 .h_8()
412 .max_h_8()
413 .border_t_1()
414 .border_color(border_color)
415 .max_w_full()
416 .justify_between()
417 .children(if rated {
418 Some(
419 label_container()
420 .child(
421 Icon::new(IconName::Check)
422 .size(IconSize::Small)
423 .color(Color::Success),
424 )
425 .child(Label::new("Rated completion.").color(Color::Muted)),
426 )
427 } else if active_completion.completion.edits.is_empty() {
428 Some(
429 label_container()
430 .child(
431 Icon::new(IconName::Warning)
432 .size(IconSize::Small)
433 .color(Color::Warning),
434 )
435 .child(Label::new("No edits produced.").color(Color::Muted)),
436 )
437 } else if !was_shown {
438 Some(
439 label_container()
440 .child(
441 Icon::new(IconName::Warning)
442 .size(IconSize::Small)
443 .color(Color::Warning),
444 )
445 .child(Label::new("Completion wasn't shown because another valid one was already on screen.")),
446 )
447 } else {
448 Some(label_container())
449 })
450 .child(
451 h_flex()
452 .gap_1()
453 .child(
454 Button::new("bad", "Bad Completion")
455 .key_binding(KeyBinding::for_action_in(
456 &ThumbsDown,
457 &self.focus_handle(cx),
458 cx,
459 ))
460 .style(ButtonStyle::Filled)
461 .icon(IconName::ThumbsDown)
462 .icon_size(IconSize::Small)
463 .icon_position(IconPosition::Start)
464 .disabled(rated || feedback_empty)
465 .when(feedback_empty, |this| {
466 this.tooltip(|cx| {
467 Tooltip::text("Explain what's bad about it before reporting it", cx)
468 })
469 })
470 .on_click(cx.listener(move |this, _, cx| {
471 this.thumbs_down_active(
472 &ThumbsDownActiveCompletion,
473 cx,
474 );
475 })),
476 )
477 .child(
478 Button::new("good", "Good Completion")
479 .key_binding(KeyBinding::for_action_in(
480 &ThumbsUp,
481 &self.focus_handle(cx),
482 cx,
483 ))
484 .style(ButtonStyle::Filled)
485 .icon(IconName::ThumbsUp)
486 .icon_size(IconSize::Small)
487 .icon_position(IconPosition::Start)
488 .disabled(rated)
489 .on_click(cx.listener(move |this, _, cx| {
490 this.thumbs_up_active(&ThumbsUpActiveCompletion, cx);
491 })),
492 ),
493 ),
494 ),
495 )
496 }
497}
498
499impl Render for RateCompletionModal {
500 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
501 let border_color = cx.theme().colors().border;
502
503 h_flex()
504 .key_context("RateCompletionModal")
505 .track_focus(&self.focus_handle)
506 .on_action(cx.listener(Self::dismiss))
507 .on_action(cx.listener(Self::confirm))
508 .on_action(cx.listener(Self::select_prev))
509 .on_action(cx.listener(Self::select_prev_edit))
510 .on_action(cx.listener(Self::select_next))
511 .on_action(cx.listener(Self::select_next_edit))
512 .on_action(cx.listener(Self::select_first))
513 .on_action(cx.listener(Self::select_last))
514 .on_action(cx.listener(Self::thumbs_up))
515 .on_action(cx.listener(Self::thumbs_up_active))
516 .on_action(cx.listener(Self::thumbs_down_active))
517 .on_action(cx.listener(Self::focus_completions))
518 .on_action(cx.listener(Self::preview_completion))
519 .bg(cx.theme().colors().elevated_surface_background)
520 .border_1()
521 .border_color(border_color)
522 .w(cx.viewport_size().width - px(320.))
523 .h(cx.viewport_size().height - px(300.))
524 .rounded_lg()
525 .shadow_lg()
526 .child(
527 v_flex()
528 .border_r_1()
529 .border_color(border_color)
530 .w_96()
531 .h_full()
532 .flex_shrink_0()
533 .overflow_hidden()
534 .child(
535 h_flex()
536 .px_2()
537 .py_1()
538 .justify_between()
539 .border_b_1()
540 .border_color(border_color)
541 .child(
542 Icon::new(IconName::ZedPredict)
543 .size(IconSize::Small)
544 )
545 .child(
546 Label::new("From most recent to oldest")
547 .color(Color::Muted)
548 .size(LabelSize::Small),
549 )
550 )
551 .child(
552 div()
553 .id("completion_list")
554 .p_0p5()
555 .h_full()
556 .overflow_y_scroll()
557 .child(
558 List::new()
559 .empty_message(
560 div()
561 .p_2()
562 .child(
563 Label::new("No completions yet. Use the editor to generate some and rate them!")
564 .color(Color::Muted),
565 )
566 .into_any_element(),
567 )
568 .children(self.zeta.read(cx).recent_completions().cloned().enumerate().map(
569 |(index, completion)| {
570 let selected =
571 self.active_completion.as_ref().map_or(false, |selected| {
572 selected.completion.id == completion.id
573 });
574 let rated =
575 self.zeta.read(cx).is_completion_rated(completion.id);
576
577 ListItem::new(completion.id)
578 .inset(true)
579 .spacing(ListItemSpacing::Sparse)
580 .focused(index == self.selected_index)
581 .toggle_state(selected)
582 .start_slot(if rated {
583 Icon::new(IconName::Check).color(Color::Success).size(IconSize::Small)
584 } else if completion.edits.is_empty() {
585 Icon::new(IconName::File).color(Color::Muted).size(IconSize::Small)
586 } else {
587 Icon::new(IconName::FileDiff).color(Color::Accent).size(IconSize::Small)
588 })
589 .child(
590 v_flex()
591 .pl_1p5()
592 .child(Label::new(completion.path.to_string_lossy().to_string()).size(LabelSize::Small))
593 .child(Label::new(format!("{} ago, {:.2?}", format_time_ago(completion.response_received_at.elapsed()), completion.latency()))
594 .color(Color::Muted)
595 .size(LabelSize::XSmall)
596 )
597 )
598 .on_click(cx.listener(move |this, _, cx| {
599 this.select_completion(Some(completion.clone()), true, cx);
600 }))
601 },
602 )),
603 )
604 ),
605 )
606 .children(self.render_active_completion(cx))
607 .on_mouse_down_out(cx.listener(|_, _, cx| cx.emit(DismissEvent)))
608 }
609}
610
611impl EventEmitter<DismissEvent> for RateCompletionModal {}
612
613impl FocusableView for RateCompletionModal {
614 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
615 self.focus_handle.clone()
616 }
617}
618
619impl ModalView for RateCompletionModal {}
620
621fn format_time_ago(elapsed: Duration) -> String {
622 let seconds = elapsed.as_secs();
623 if seconds < 120 {
624 "1 minute".to_string()
625 } else if seconds < 3600 {
626 format!("{} minutes", seconds / 60)
627 } else if seconds < 7200 {
628 "1 hour".to_string()
629 } else if seconds < 86400 {
630 format!("{} hours", seconds / 3600)
631 } else if seconds < 172800 {
632 "1 day".to_string()
633 } else {
634 format!("{} days", seconds / 86400)
635 }
636}