rate_completion_modal.rs

  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(match self.current_view {
414                            RateCompletionView::SuggestedEdits => self.render_suggested_edits(cx),
415                            RateCompletionView::RawInput => self.render_raw_input(cx),
416                        }, |this, element| this.child(element))
417                )
418                .when(!rated, |this| {
419                    this.child(
420                        h_flex()
421                            .p_2()
422                            .gap_2()
423                            .border_y_1()
424                            .border_color(border_color)
425                            .child(
426                                Icon::new(IconName::Info)
427                                    .size(IconSize::XSmall)
428                                    .color(Color::Muted)
429                            )
430                            .child(
431                                div()
432                                    .w_full()
433                                    .pr_2()
434                                    .flex_wrap()
435                                    .child(
436                                        Label::new("Explain why this completion is good or bad. If it's negative, describe what you expected instead.")
437                                            .size(LabelSize::Small)
438                                            .color(Color::Muted)
439                                    )
440                            )
441                    )
442                })
443                .when(!rated, |this| {
444                    this.child(
445                        div()
446                            .h_40()
447                            .pt_1()
448                            .bg(bg_color)
449                            .child(active_completion.feedback_editor.clone())
450                    )
451                })
452                .child(
453                    h_flex()
454                        .p_1()
455                        .h_8()
456                        .max_h_8()
457                        .border_t_1()
458                        .border_color(border_color)
459                        .max_w_full()
460                        .justify_between()
461                        .children(if rated {
462                            Some(
463                                label_container
464                                    .child(
465                                        Icon::new(IconName::Check)
466                                            .size(IconSize::Small)
467                                            .color(Color::Success),
468                                    )
469                                    .child(Label::new("Rated completion.").color(Color::Muted)),
470                            )
471                        } else if active_completion.completion.edits.is_empty() {
472                            Some(
473                                label_container
474                                    .child(
475                                        Icon::new(IconName::Warning)
476                                            .size(IconSize::Small)
477                                            .color(Color::Warning),
478                                    )
479                                    .child(Label::new("No edits produced.").color(Color::Muted)),
480                            )
481                        } else {
482                            Some(label_container)
483                        })
484                        .child(
485                            h_flex()
486                                .gap_1()
487                                .child(
488                                    Button::new("bad", "Bad Completion")
489                                        .icon(IconName::ThumbsDown)
490                                        .icon_size(IconSize::Small)
491                                        .icon_position(IconPosition::Start)
492                                        .disabled(rated || feedback_empty)
493                                        .when(feedback_empty, |this| {
494                                            this.tooltip(Tooltip::text("Explain what's bad about it before reporting it"))
495                                        })
496                                        .key_binding(KeyBinding::for_action_in(
497                                            &ThumbsDownActiveCompletion,
498                                            focus_handle,
499                                            cx
500                                        ))
501                                        .on_click(cx.listener(move |this, _, window, cx| {
502                                            if this.active_completion.is_some() {
503                                                this.thumbs_down_active(
504                                                    &ThumbsDownActiveCompletion,
505                                                    window, cx,
506                                                );
507                                            }
508                                        })),
509                                )
510                                .child(
511                                    Button::new("good", "Good Completion")
512                                        .icon(IconName::ThumbsUp)
513                                        .icon_size(IconSize::Small)
514                                        .icon_position(IconPosition::Start)
515                                        .disabled(rated)
516                                        .key_binding(KeyBinding::for_action_in(
517                                            &ThumbsUpActiveCompletion,
518                                            focus_handle,
519                                            cx
520                                        ))
521                                        .on_click(cx.listener(move |this, _, window, cx| {
522                                            if this.active_completion.is_some() {
523                                                this.thumbs_up_active(&ThumbsUpActiveCompletion, window, cx);
524                                            }
525                                        })),
526                                ),
527                        ),
528                ),
529        )
530    }
531}
532
533impl Render for RateCompletionModal {
534    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
535        let border_color = cx.theme().colors().border;
536
537        h_flex()
538            .key_context("RateCompletionModal")
539            .track_focus(&self.focus_handle)
540            .on_action(cx.listener(Self::dismiss))
541            .on_action(cx.listener(Self::confirm))
542            .on_action(cx.listener(Self::select_previous))
543            .on_action(cx.listener(Self::select_prev_edit))
544            .on_action(cx.listener(Self::select_next))
545            .on_action(cx.listener(Self::select_next_edit))
546            .on_action(cx.listener(Self::select_first))
547            .on_action(cx.listener(Self::select_last))
548            .on_action(cx.listener(Self::thumbs_up_active))
549            .on_action(cx.listener(Self::thumbs_down_active))
550            .on_action(cx.listener(Self::focus_completions))
551            .on_action(cx.listener(Self::preview_completion))
552            .bg(cx.theme().colors().elevated_surface_background)
553            .border_1()
554            .border_color(border_color)
555            .w(window.viewport_size().width - px(320.))
556            .h(window.viewport_size().height - px(300.))
557            .rounded_lg()
558            .shadow_lg()
559            .child(
560                v_flex()
561                    .w_72()
562                    .h_full()
563                    .border_r_1()
564                    .border_color(border_color)
565                    .flex_shrink_0()
566                    .overflow_hidden()
567                    .child(
568                        h_flex()
569                            .h_8()
570                            .px_2()
571                            .justify_between()
572                            .border_b_1()
573                            .border_color(border_color)
574                            .child(
575                                Icon::new(IconName::ZedPredict)
576                                    .size(IconSize::Small)
577                            )
578                            .child(
579                                Label::new("From most recent to oldest")
580                                    .color(Color::Muted)
581                                    .size(LabelSize::Small),
582                            )
583                    )
584                    .child(
585                        div()
586                            .id("completion_list")
587                            .p_0p5()
588                            .h_full()
589                            .overflow_y_scroll()
590                            .child(
591                                List::new()
592                                    .empty_message(
593                                        div()
594                                            .p_2()
595                                            .child(
596                                                Label::new("No completions yet. Use the editor to generate some, and make sure to rate them!")
597                                                    .color(Color::Muted),
598                                            )
599                                            .into_any_element(),
600                                    )
601                                    .children(self.zeta.read(cx).shown_completions().cloned().enumerate().map(
602                                        |(index, completion)| {
603                                            let selected =
604                                                self.active_completion.as_ref().is_some_and(|selected| {
605                                                    selected.completion.id == completion.id
606                                                });
607                                            let rated =
608                                                self.zeta.read(cx).is_completion_rated(completion.id);
609
610                                            let (icon_name, icon_color, tooltip_text) = match (rated, completion.edits.is_empty()) {
611                                                (true, _) => (IconName::Check, Color::Success, "Rated Completion"),
612                                                (false, true) => (IconName::File, Color::Muted, "No Edits Produced"),
613                                                (false, false) => (IconName::FileDiff, Color::Accent, "Edits Available"),
614                                            };
615
616                                            let file_name = completion.path.file_name().map(|f| f.to_string_lossy().into_owned()).unwrap_or("untitled".to_string());
617                                            let file_path = completion.path.parent().map(|p| p.to_string_lossy().into_owned());
618
619                                            ListItem::new(completion.id)
620                                                .inset(true)
621                                                .spacing(ListItemSpacing::Sparse)
622                                                .focused(index == self.selected_index)
623                                                .toggle_state(selected)
624                                                .child(
625                                                    h_flex()
626                                                        .id("completion-content")
627                                                        .gap_3()
628                                                        .child(
629                                                            Icon::new(icon_name)
630                                                                .color(icon_color)
631                                                                .size(IconSize::Small)
632                                                        )
633                                                        .child(
634                                                            v_flex()
635                                                                .child(
636                                                                    h_flex().gap_1()
637                                                                        .child(Label::new(file_name).size(LabelSize::Small))
638                                                                        .when_some(file_path, |this, p| this.child(Label::new(p).size(LabelSize::Small).color(Color::Muted)))
639                                                                )
640                                                                .child(Label::new(format!("{} ago, {:.2?}", format_time_ago(completion.response_received_at.elapsed()), completion.latency()))
641                                                                    .color(Color::Muted)
642                                                                    .size(LabelSize::XSmall)
643                                                                )
644                                                        )
645                                                )
646                                                .tooltip(Tooltip::text(tooltip_text))
647                                                .on_click(cx.listener(move |this, _, window, cx| {
648                                                    this.select_completion(Some(completion.clone()), true, window, cx);
649                                                }))
650                                        },
651                                    )),
652                            )
653                    ),
654            )
655            .children(self.render_active_completion( cx))
656            .on_mouse_down_out(cx.listener(|_, _, _, cx| cx.emit(DismissEvent)))
657    }
658}
659
660impl EventEmitter<DismissEvent> for RateCompletionModal {}
661
662impl Focusable for RateCompletionModal {
663    fn focus_handle(&self, _cx: &App) -> FocusHandle {
664        self.focus_handle.clone()
665    }
666}
667
668impl ModalView for RateCompletionModal {}
669
670fn format_time_ago(elapsed: Duration) -> String {
671    let seconds = elapsed.as_secs();
672    if seconds < 120 {
673        "1 minute".to_string()
674    } else if seconds < 3600 {
675        format!("{} minutes", seconds / 60)
676    } else if seconds < 7200 {
677        "1 hour".to_string()
678    } else if seconds < 86400 {
679        format!("{} hours", seconds / 3600)
680    } else if seconds < 172800 {
681        "1 day".to_string()
682    } else {
683        format!("{} days", seconds / 86400)
684    }
685}