1use crate::{CompletionDiffElement, EditPrediction, EditPredictionRating, Zeta};
2use editor::Editor;
3use gpui::{App, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable, actions, prelude::*};
4use language::language_settings;
5use std::time::Duration;
6use ui::{KeyBinding, List, ListItem, ListItemSpacing, Tooltip, prelude::*};
7use workspace::{ModalView, Workspace};
8
9actions!(
10 zeta,
11 [
12 /// Rates the active completion with a thumbs up.
13 ThumbsUpActiveCompletion,
14 /// Rates the active completion with a thumbs down.
15 ThumbsDownActiveCompletion,
16 /// Navigates to the next edit in the completion history.
17 NextEdit,
18 /// Navigates to the previous edit in the completion history.
19 PreviousEdit,
20 /// Focuses on the completions list.
21 FocusCompletions,
22 /// Previews the selected completion.
23 PreviewCompletion,
24 ]
25);
26
27pub struct RateCompletionModal {
28 zeta: Entity<Zeta>,
29 active_completion: Option<ActiveCompletion>,
30 selected_index: usize,
31 focus_handle: FocusHandle,
32 _subscription: gpui::Subscription,
33 current_view: RateCompletionView,
34}
35
36struct ActiveCompletion {
37 completion: EditPrediction,
38 feedback_editor: Entity<Editor>,
39}
40
41#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
42enum RateCompletionView {
43 SuggestedEdits,
44 RawInput,
45}
46
47impl RateCompletionView {
48 pub fn name(&self) -> &'static str {
49 match self {
50 Self::SuggestedEdits => "Suggested Edits",
51 Self::RawInput => "Recorded Events & Input",
52 }
53 }
54}
55
56impl RateCompletionModal {
57 pub fn toggle(workspace: &mut Workspace, window: &mut Window, cx: &mut Context<Workspace>) {
58 if let Some(zeta) = Zeta::global(cx) {
59 workspace.toggle_modal(window, cx, |_window, cx| RateCompletionModal::new(zeta, cx));
60
61 telemetry::event!("Rate Completion Modal Open", source = "Edit Prediction");
62 }
63 }
64
65 pub fn new(zeta: Entity<Zeta>, cx: &mut Context<Self>) -> Self {
66 let subscription = cx.observe(&zeta, |_, _, cx| cx.notify());
67
68 Self {
69 zeta,
70 selected_index: 0,
71 focus_handle: cx.focus_handle(),
72 active_completion: None,
73 _subscription: subscription,
74 current_view: RateCompletionView::SuggestedEdits,
75 }
76 }
77
78 fn dismiss(&mut self, _: &menu::Cancel, _: &mut Window, cx: &mut Context<Self>) {
79 cx.emit(DismissEvent);
80 }
81
82 fn select_next(&mut self, _: &menu::SelectNext, _: &mut Window, cx: &mut Context<Self>) {
83 self.selected_index += 1;
84 self.selected_index = usize::min(
85 self.selected_index,
86 self.zeta.read(cx).shown_completions().count(),
87 );
88 cx.notify();
89 }
90
91 fn select_previous(
92 &mut self,
93 _: &menu::SelectPrevious,
94 _: &mut Window,
95 cx: &mut Context<Self>,
96 ) {
97 self.selected_index = self.selected_index.saturating_sub(1);
98 cx.notify();
99 }
100
101 fn select_next_edit(&mut self, _: &NextEdit, _: &mut Window, cx: &mut Context<Self>) {
102 let next_index = self
103 .zeta
104 .read(cx)
105 .shown_completions()
106 .skip(self.selected_index)
107 .enumerate()
108 .skip(1) // Skip straight to the next item
109 .find(|(_, completion)| !completion.edits.is_empty())
110 .map(|(ix, _)| ix + self.selected_index);
111
112 if let Some(next_index) = next_index {
113 self.selected_index = next_index;
114 cx.notify();
115 }
116 }
117
118 fn select_prev_edit(&mut self, _: &PreviousEdit, _: &mut Window, cx: &mut Context<Self>) {
119 let zeta = self.zeta.read(cx);
120 let completions_len = zeta.shown_completions_len();
121
122 let prev_index = self
123 .zeta
124 .read(cx)
125 .shown_completions()
126 .rev()
127 .skip((completions_len - 1) - self.selected_index)
128 .enumerate()
129 .skip(1) // Skip straight to the previous item
130 .find(|(_, completion)| !completion.edits.is_empty())
131 .map(|(ix, _)| self.selected_index - ix);
132
133 if let Some(prev_index) = prev_index {
134 self.selected_index = prev_index;
135 cx.notify();
136 }
137 cx.notify();
138 }
139
140 fn select_first(&mut self, _: &menu::SelectFirst, _: &mut Window, cx: &mut Context<Self>) {
141 self.selected_index = 0;
142 cx.notify();
143 }
144
145 fn select_last(&mut self, _: &menu::SelectLast, _window: &mut Window, cx: &mut Context<Self>) {
146 self.selected_index = self.zeta.read(cx).shown_completions_len() - 1;
147 cx.notify();
148 }
149
150 pub fn thumbs_up_active(
151 &mut self,
152 _: &ThumbsUpActiveCompletion,
153 window: &mut Window,
154 cx: &mut Context<Self>,
155 ) {
156 self.zeta.update(cx, |zeta, cx| {
157 if let Some(active) = &self.active_completion {
158 zeta.rate_completion(
159 &active.completion,
160 EditPredictionRating::Positive,
161 active.feedback_editor.read(cx).text(cx),
162 cx,
163 );
164 }
165 });
166
167 let current_completion = self
168 .active_completion
169 .as_ref()
170 .map(|completion| completion.completion.clone());
171 self.select_completion(current_completion, false, window, cx);
172 self.select_next_edit(&Default::default(), window, cx);
173 self.confirm(&Default::default(), window, cx);
174
175 cx.notify();
176 }
177
178 pub fn thumbs_down_active(
179 &mut self,
180 _: &ThumbsDownActiveCompletion,
181 window: &mut Window,
182 cx: &mut Context<Self>,
183 ) {
184 if let Some(active) = &self.active_completion {
185 if active.feedback_editor.read(cx).text(cx).is_empty() {
186 return;
187 }
188
189 self.zeta.update(cx, |zeta, cx| {
190 zeta.rate_completion(
191 &active.completion,
192 EditPredictionRating::Negative,
193 active.feedback_editor.read(cx).text(cx),
194 cx,
195 );
196 });
197 }
198
199 let current_completion = self
200 .active_completion
201 .as_ref()
202 .map(|completion| completion.completion.clone());
203 self.select_completion(current_completion, false, window, cx);
204 self.select_next_edit(&Default::default(), window, cx);
205 self.confirm(&Default::default(), window, cx);
206
207 cx.notify();
208 }
209
210 fn focus_completions(
211 &mut self,
212 _: &FocusCompletions,
213 window: &mut Window,
214 cx: &mut Context<Self>,
215 ) {
216 cx.focus_self(window);
217 cx.notify();
218 }
219
220 fn preview_completion(
221 &mut self,
222 _: &PreviewCompletion,
223 window: &mut Window,
224 cx: &mut Context<Self>,
225 ) {
226 let completion = self
227 .zeta
228 .read(cx)
229 .shown_completions()
230 .skip(self.selected_index)
231 .take(1)
232 .next()
233 .cloned();
234
235 self.select_completion(completion, false, window, cx);
236 }
237
238 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
239 let completion = self
240 .zeta
241 .read(cx)
242 .shown_completions()
243 .skip(self.selected_index)
244 .take(1)
245 .next()
246 .cloned();
247
248 self.select_completion(completion, true, window, cx);
249 }
250
251 pub fn select_completion(
252 &mut self,
253 completion: Option<EditPrediction>,
254 focus: bool,
255 window: &mut Window,
256 cx: &mut Context<Self>,
257 ) {
258 // Avoid resetting completion rating if it's already selected.
259 if let Some(completion) = completion.as_ref() {
260 self.selected_index = self
261 .zeta
262 .read(cx)
263 .shown_completions()
264 .enumerate()
265 .find(|(_, completion_b)| completion.id == completion_b.id)
266 .map(|(ix, _)| ix)
267 .unwrap_or(self.selected_index);
268 cx.notify();
269
270 if let Some(prev_completion) = self.active_completion.as_ref()
271 && completion.id == prev_completion.completion.id
272 {
273 if focus {
274 window.focus(&prev_completion.feedback_editor.focus_handle(cx));
275 }
276 return;
277 }
278 }
279
280 self.active_completion = completion.map(|completion| ActiveCompletion {
281 completion,
282 feedback_editor: cx.new(|cx| {
283 let mut editor = Editor::multi_line(window, cx);
284 editor.disable_scrollbars_and_minimap(window, cx);
285 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
286 editor.set_show_line_numbers(false, cx);
287 editor.set_show_git_diff_gutter(false, cx);
288 editor.set_show_code_actions(false, cx);
289 editor.set_show_runnables(false, cx);
290 editor.set_show_breakpoints(false, cx);
291 editor.set_show_wrap_guides(false, cx);
292 editor.set_show_indent_guides(false, cx);
293 editor.set_show_edit_predictions(Some(false), window, cx);
294 editor.set_placeholder_text("Add your feedback…", window, cx);
295 if focus {
296 cx.focus_self(window);
297 }
298 editor
299 }),
300 });
301 cx.notify();
302 }
303
304 fn render_view_nav(&self, cx: &Context<Self>) -> impl IntoElement {
305 h_flex()
306 .h_8()
307 .px_1()
308 .border_b_1()
309 .border_color(cx.theme().colors().border)
310 .bg(cx.theme().colors().elevated_surface_background)
311 .gap_1()
312 .child(
313 Button::new(
314 ElementId::Name("suggested-edits".into()),
315 RateCompletionView::SuggestedEdits.name(),
316 )
317 .label_size(LabelSize::Small)
318 .on_click(cx.listener(move |this, _, _window, cx| {
319 this.current_view = RateCompletionView::SuggestedEdits;
320 cx.notify();
321 }))
322 .toggle_state(self.current_view == RateCompletionView::SuggestedEdits),
323 )
324 .child(
325 Button::new(
326 ElementId::Name("raw-input".into()),
327 RateCompletionView::RawInput.name(),
328 )
329 .label_size(LabelSize::Small)
330 .on_click(cx.listener(move |this, _, _window, cx| {
331 this.current_view = RateCompletionView::RawInput;
332 cx.notify();
333 }))
334 .toggle_state(self.current_view == RateCompletionView::RawInput),
335 )
336 }
337
338 fn render_suggested_edits(&self, cx: &mut Context<Self>) -> Option<gpui::Stateful<Div>> {
339 let active_completion = self.active_completion.as_ref()?;
340 let bg_color = cx.theme().colors().editor_background;
341
342 Some(
343 div()
344 .id("diff")
345 .p_4()
346 .size_full()
347 .bg(bg_color)
348 .overflow_scroll()
349 .whitespace_nowrap()
350 .child(CompletionDiffElement::new(
351 &active_completion.completion,
352 cx,
353 )),
354 )
355 }
356
357 fn render_raw_input(&self, cx: &mut Context<Self>) -> Option<gpui::Stateful<Div>> {
358 Some(
359 v_flex()
360 .size_full()
361 .overflow_hidden()
362 .relative()
363 .child(
364 div()
365 .id("raw-input")
366 .py_4()
367 .px_6()
368 .size_full()
369 .bg(cx.theme().colors().editor_background)
370 .overflow_scroll()
371 .child(if let Some(active_completion) = &self.active_completion {
372 format!(
373 "{}\n{}",
374 active_completion.completion.input_events,
375 active_completion.completion.input_excerpt
376 )
377 } else {
378 "No active completion".to_string()
379 }),
380 )
381 .id("raw-input-view"),
382 )
383 }
384
385 fn render_active_completion(&mut self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
386 let active_completion = self.active_completion.as_ref()?;
387 let completion_id = active_completion.completion.id;
388 let focus_handle = &self.focus_handle(cx);
389
390 let border_color = cx.theme().colors().border;
391 let bg_color = cx.theme().colors().editor_background;
392
393 let rated = self.zeta.read(cx).is_completion_rated(completion_id);
394 let feedback_empty = active_completion
395 .feedback_editor
396 .read(cx)
397 .text(cx)
398 .is_empty();
399
400 let label_container = h_flex().pl_1().gap_1p5();
401
402 Some(
403 v_flex()
404 .size_full()
405 .overflow_hidden()
406 .relative()
407 .child(
408 v_flex()
409 .size_full()
410 .overflow_hidden()
411 .relative()
412 .child(self.render_view_nav(cx))
413 .when_some(
414 match self.current_view {
415 RateCompletionView::SuggestedEdits => {
416 self.render_suggested_edits(cx)
417 }
418 RateCompletionView::RawInput => self.render_raw_input(cx),
419 },
420 |this, element| this.child(element),
421 ),
422 )
423 .when(!rated, |this| {
424 this.child(
425 h_flex()
426 .p_2()
427 .gap_2()
428 .border_y_1()
429 .border_color(border_color)
430 .child(
431 Icon::new(IconName::Info)
432 .size(IconSize::XSmall)
433 .color(Color::Muted),
434 )
435 .child(
436 div().w_full().pr_2().flex_wrap().child(
437 Label::new(concat!(
438 "Explain why this completion is good or bad. ",
439 "If it's negative, describe what you expected instead."
440 ))
441 .size(LabelSize::Small)
442 .color(Color::Muted),
443 ),
444 ),
445 )
446 })
447 .when(!rated, |this| {
448 this.child(
449 div()
450 .h_40()
451 .pt_1()
452 .bg(bg_color)
453 .child(active_completion.feedback_editor.clone()),
454 )
455 })
456 .child(
457 h_flex()
458 .p_1()
459 .h_8()
460 .max_h_8()
461 .border_t_1()
462 .border_color(border_color)
463 .max_w_full()
464 .justify_between()
465 .children(if rated {
466 Some(
467 label_container
468 .child(
469 Icon::new(IconName::Check)
470 .size(IconSize::Small)
471 .color(Color::Success),
472 )
473 .child(Label::new("Rated completion.").color(Color::Muted)),
474 )
475 } else if active_completion.completion.edits.is_empty() {
476 Some(
477 label_container
478 .child(
479 Icon::new(IconName::Warning)
480 .size(IconSize::Small)
481 .color(Color::Warning),
482 )
483 .child(Label::new("No edits produced.").color(Color::Muted)),
484 )
485 } else {
486 Some(label_container)
487 })
488 .child(
489 h_flex()
490 .gap_1()
491 .child(
492 Button::new("bad", "Bad Completion")
493 .icon(IconName::ThumbsDown)
494 .icon_size(IconSize::Small)
495 .icon_position(IconPosition::Start)
496 .disabled(rated || feedback_empty)
497 .when(feedback_empty, |this| {
498 this.tooltip(Tooltip::text(
499 "Explain what's bad about it before reporting it",
500 ))
501 })
502 .key_binding(KeyBinding::for_action_in(
503 &ThumbsDownActiveCompletion,
504 focus_handle,
505 cx,
506 ))
507 .on_click(cx.listener(move |this, _, window, cx| {
508 if this.active_completion.is_some() {
509 this.thumbs_down_active(
510 &ThumbsDownActiveCompletion,
511 window,
512 cx,
513 );
514 }
515 })),
516 )
517 .child(
518 Button::new("good", "Good Completion")
519 .icon(IconName::ThumbsUp)
520 .icon_size(IconSize::Small)
521 .icon_position(IconPosition::Start)
522 .disabled(rated)
523 .key_binding(KeyBinding::for_action_in(
524 &ThumbsUpActiveCompletion,
525 focus_handle,
526 cx,
527 ))
528 .on_click(cx.listener(move |this, _, window, cx| {
529 if this.active_completion.is_some() {
530 this.thumbs_up_active(
531 &ThumbsUpActiveCompletion,
532 window,
533 cx,
534 );
535 }
536 })),
537 ),
538 ),
539 ),
540 )
541 }
542
543 fn render_shown_completions(&self, cx: &Context<Self>) -> impl Iterator<Item = ListItem> {
544 self.zeta
545 .read(cx)
546 .shown_completions()
547 .cloned()
548 .enumerate()
549 .map(|(index, completion)| {
550 let selected = self
551 .active_completion
552 .as_ref()
553 .is_some_and(|selected| selected.completion.id == completion.id);
554 let rated = self.zeta.read(cx).is_completion_rated(completion.id);
555
556 let (icon_name, icon_color, tooltip_text) =
557 match (rated, completion.edits.is_empty()) {
558 (true, _) => (IconName::Check, Color::Success, "Rated Completion"),
559 (false, true) => (IconName::File, Color::Muted, "No Edits Produced"),
560 (false, false) => (IconName::FileDiff, Color::Accent, "Edits Available"),
561 };
562
563 let file_name = completion
564 .path
565 .file_name()
566 .map(|f| f.to_string_lossy().into_owned())
567 .unwrap_or("untitled".to_string());
568 let file_path = completion
569 .path
570 .parent()
571 .map(|p| p.to_string_lossy().into_owned());
572
573 ListItem::new(completion.id)
574 .inset(true)
575 .spacing(ListItemSpacing::Sparse)
576 .focused(index == self.selected_index)
577 .toggle_state(selected)
578 .child(
579 h_flex()
580 .id("completion-content")
581 .gap_3()
582 .child(Icon::new(icon_name).color(icon_color).size(IconSize::Small))
583 .child(
584 v_flex()
585 .child(
586 h_flex()
587 .gap_1()
588 .child(Label::new(file_name).size(LabelSize::Small))
589 .when_some(file_path, |this, p| {
590 this.child(
591 Label::new(p)
592 .size(LabelSize::Small)
593 .color(Color::Muted),
594 )
595 }),
596 )
597 .child(
598 Label::new(format!(
599 "{} ago, {:.2?}",
600 format_time_ago(
601 completion.response_received_at.elapsed()
602 ),
603 completion.latency()
604 ))
605 .color(Color::Muted)
606 .size(LabelSize::XSmall),
607 ),
608 ),
609 )
610 .tooltip(Tooltip::text(tooltip_text))
611 .on_click(cx.listener(move |this, _, window, cx| {
612 this.select_completion(Some(completion.clone()), true, window, cx);
613 }))
614 })
615 }
616}
617
618impl Render for RateCompletionModal {
619 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
620 let border_color = cx.theme().colors().border;
621
622 h_flex()
623 .key_context("RateCompletionModal")
624 .track_focus(&self.focus_handle)
625 .on_action(cx.listener(Self::dismiss))
626 .on_action(cx.listener(Self::confirm))
627 .on_action(cx.listener(Self::select_previous))
628 .on_action(cx.listener(Self::select_prev_edit))
629 .on_action(cx.listener(Self::select_next))
630 .on_action(cx.listener(Self::select_next_edit))
631 .on_action(cx.listener(Self::select_first))
632 .on_action(cx.listener(Self::select_last))
633 .on_action(cx.listener(Self::thumbs_up_active))
634 .on_action(cx.listener(Self::thumbs_down_active))
635 .on_action(cx.listener(Self::focus_completions))
636 .on_action(cx.listener(Self::preview_completion))
637 .bg(cx.theme().colors().elevated_surface_background)
638 .border_1()
639 .border_color(border_color)
640 .w(window.viewport_size().width - px(320.))
641 .h(window.viewport_size().height - px(300.))
642 .rounded_lg()
643 .shadow_lg()
644 .child(
645 v_flex()
646 .w_72()
647 .h_full()
648 .border_r_1()
649 .border_color(border_color)
650 .flex_shrink_0()
651 .overflow_hidden()
652 .child(
653 h_flex()
654 .h_8()
655 .px_2()
656 .justify_between()
657 .border_b_1()
658 .border_color(border_color)
659 .child(Icon::new(IconName::ZedPredict).size(IconSize::Small))
660 .child(
661 Label::new("From most recent to oldest")
662 .color(Color::Muted)
663 .size(LabelSize::Small),
664 ),
665 )
666 .child(
667 div()
668 .id("completion_list")
669 .p_0p5()
670 .h_full()
671 .overflow_y_scroll()
672 .child(
673 List::new()
674 .empty_message(
675 div()
676 .p_2()
677 .child(
678 Label::new(concat!(
679 "No completions yet. ",
680 "Use the editor to generate some, ",
681 "and make sure to rate them!"
682 ))
683 .color(Color::Muted),
684 )
685 .into_any_element(),
686 )
687 .children(self.render_shown_completions(cx)),
688 ),
689 ),
690 )
691 .children(self.render_active_completion(cx))
692 .on_mouse_down_out(cx.listener(|_, _, _, cx| cx.emit(DismissEvent)))
693 }
694}
695
696impl EventEmitter<DismissEvent> for RateCompletionModal {}
697
698impl Focusable for RateCompletionModal {
699 fn focus_handle(&self, _cx: &App) -> FocusHandle {
700 self.focus_handle.clone()
701 }
702}
703
704impl ModalView for RateCompletionModal {}
705
706fn format_time_ago(elapsed: Duration) -> String {
707 let seconds = elapsed.as_secs();
708 if seconds < 120 {
709 "1 minute".to_string()
710 } else if seconds < 3600 {
711 format!("{} minutes", seconds / 60)
712 } else if seconds < 7200 {
713 "1 hour".to_string()
714 } else if seconds < 86400 {
715 format!("{} hours", seconds / 3600)
716 } else if seconds < 172800 {
717 "1 day".to_string()
718 } else {
719 format!("{} days", seconds / 86400)
720 }
721}