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                    if focus {
273                        window.focus(&prev_completion.feedback_editor.focus_handle(cx));
274                    }
275                    return;
276                }
277        }
278
279        self.active_completion = completion.map(|completion| ActiveCompletion {
280            completion,
281            feedback_editor: cx.new(|cx| {
282                let mut editor = Editor::multi_line(window, cx);
283                editor.disable_scrollbars_and_minimap(window, cx);
284                editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
285                editor.set_show_line_numbers(false, cx);
286                editor.set_show_git_diff_gutter(false, cx);
287                editor.set_show_code_actions(false, cx);
288                editor.set_show_runnables(false, cx);
289                editor.set_show_breakpoints(false, cx);
290                editor.set_show_wrap_guides(false, cx);
291                editor.set_show_indent_guides(false, cx);
292                editor.set_show_edit_predictions(Some(false), window, cx);
293                editor.set_placeholder_text("Add your feedback…", cx);
294                if focus {
295                    cx.focus_self(window);
296                }
297                editor
298            }),
299        });
300        cx.notify();
301    }
302
303    fn render_view_nav(&self, cx: &Context<Self>) -> impl IntoElement {
304        h_flex()
305            .h_8()
306            .px_1()
307            .border_b_1()
308            .border_color(cx.theme().colors().border)
309            .bg(cx.theme().colors().elevated_surface_background)
310            .gap_1()
311            .child(
312                Button::new(
313                    ElementId::Name("suggested-edits".into()),
314                    RateCompletionView::SuggestedEdits.name(),
315                )
316                .label_size(LabelSize::Small)
317                .on_click(cx.listener(move |this, _, _window, cx| {
318                    this.current_view = RateCompletionView::SuggestedEdits;
319                    cx.notify();
320                }))
321                .toggle_state(self.current_view == RateCompletionView::SuggestedEdits),
322            )
323            .child(
324                Button::new(
325                    ElementId::Name("raw-input".into()),
326                    RateCompletionView::RawInput.name(),
327                )
328                .label_size(LabelSize::Small)
329                .on_click(cx.listener(move |this, _, _window, cx| {
330                    this.current_view = RateCompletionView::RawInput;
331                    cx.notify();
332                }))
333                .toggle_state(self.current_view == RateCompletionView::RawInput),
334            )
335    }
336
337    fn render_suggested_edits(&self, cx: &mut Context<Self>) -> Option<gpui::Stateful<Div>> {
338        let active_completion = self.active_completion.as_ref()?;
339        let bg_color = cx.theme().colors().editor_background;
340
341        Some(
342            div()
343                .id("diff")
344                .p_4()
345                .size_full()
346                .bg(bg_color)
347                .overflow_scroll()
348                .whitespace_nowrap()
349                .child(CompletionDiffElement::new(
350                    &active_completion.completion,
351                    cx,
352                )),
353        )
354    }
355
356    fn render_raw_input(&self, cx: &mut Context<Self>) -> Option<gpui::Stateful<Div>> {
357        Some(
358            v_flex()
359                .size_full()
360                .overflow_hidden()
361                .relative()
362                .child(
363                    div()
364                        .id("raw-input")
365                        .py_4()
366                        .px_6()
367                        .size_full()
368                        .bg(cx.theme().colors().editor_background)
369                        .overflow_scroll()
370                        .child(if let Some(active_completion) = &self.active_completion {
371                            format!(
372                                "{}\n{}",
373                                active_completion.completion.input_events,
374                                active_completion.completion.input_excerpt
375                            )
376                        } else {
377                            "No active completion".to_string()
378                        }),
379                )
380                .id("raw-input-view"),
381        )
382    }
383
384    fn render_active_completion(
385        &mut self,
386        window: &mut Window,
387        cx: &mut Context<Self>,
388    ) -> Option<impl IntoElement> {
389        let active_completion = self.active_completion.as_ref()?;
390        let completion_id = active_completion.completion.id;
391        let focus_handle = &self.focus_handle(cx);
392
393        let border_color = cx.theme().colors().border;
394        let bg_color = cx.theme().colors().editor_background;
395
396        let rated = self.zeta.read(cx).is_completion_rated(completion_id);
397        let feedback_empty = active_completion
398            .feedback_editor
399            .read(cx)
400            .text(cx)
401            .is_empty();
402
403        let label_container = h_flex().pl_1().gap_1p5();
404
405        Some(
406            v_flex()
407                .size_full()
408                .overflow_hidden()
409                .relative()
410                .child(
411                    v_flex()
412                        .size_full()
413                        .overflow_hidden()
414                        .relative()
415                        .child(self.render_view_nav(cx))
416                        .when_some(match self.current_view {
417                            RateCompletionView::SuggestedEdits => self.render_suggested_edits(cx),
418                            RateCompletionView::RawInput => self.render_raw_input(cx),
419                        }, |this, element| this.child(element))
420                )
421                .when(!rated, |this| {
422                    this.child(
423                        h_flex()
424                            .p_2()
425                            .gap_2()
426                            .border_y_1()
427                            .border_color(border_color)
428                            .child(
429                                Icon::new(IconName::Info)
430                                    .size(IconSize::XSmall)
431                                    .color(Color::Muted)
432                            )
433                            .child(
434                                div()
435                                    .w_full()
436                                    .pr_2()
437                                    .flex_wrap()
438                                    .child(
439                                        Label::new("Explain why this completion is good or bad. If it's negative, describe what you expected instead.")
440                                            .size(LabelSize::Small)
441                                            .color(Color::Muted)
442                                    )
443                            )
444                    )
445                })
446                .when(!rated, |this| {
447                    this.child(
448                        div()
449                            .h_40()
450                            .pt_1()
451                            .bg(bg_color)
452                            .child(active_completion.feedback_editor.clone())
453                    )
454                })
455                .child(
456                    h_flex()
457                        .p_1()
458                        .h_8()
459                        .max_h_8()
460                        .border_t_1()
461                        .border_color(border_color)
462                        .max_w_full()
463                        .justify_between()
464                        .children(if rated {
465                            Some(
466                                label_container
467                                    .child(
468                                        Icon::new(IconName::Check)
469                                            .size(IconSize::Small)
470                                            .color(Color::Success),
471                                    )
472                                    .child(Label::new("Rated completion.").color(Color::Muted)),
473                            )
474                        } else if active_completion.completion.edits.is_empty() {
475                            Some(
476                                label_container
477                                    .child(
478                                        Icon::new(IconName::Warning)
479                                            .size(IconSize::Small)
480                                            .color(Color::Warning),
481                                    )
482                                    .child(Label::new("No edits produced.").color(Color::Muted)),
483                            )
484                        } else {
485                            Some(label_container)
486                        })
487                        .child(
488                            h_flex()
489                                .gap_1()
490                                .child(
491                                    Button::new("bad", "Bad Completion")
492                                        .icon(IconName::ThumbsDown)
493                                        .icon_size(IconSize::Small)
494                                        .icon_position(IconPosition::Start)
495                                        .disabled(rated || feedback_empty)
496                                        .when(feedback_empty, |this| {
497                                            this.tooltip(Tooltip::text("Explain what's bad about it before reporting it"))
498                                        })
499                                        .key_binding(KeyBinding::for_action_in(
500                                            &ThumbsDownActiveCompletion,
501                                            focus_handle,
502                                            window,
503                                            cx
504                                        ))
505                                        .on_click(cx.listener(move |this, _, window, cx| {
506                                            if this.active_completion.is_some() {
507                                                this.thumbs_down_active(
508                                                    &ThumbsDownActiveCompletion,
509                                                    window, cx,
510                                                );
511                                            }
512                                        })),
513                                )
514                                .child(
515                                    Button::new("good", "Good Completion")
516                                        .icon(IconName::ThumbsUp)
517                                        .icon_size(IconSize::Small)
518                                        .icon_position(IconPosition::Start)
519                                        .disabled(rated)
520                                        .key_binding(KeyBinding::for_action_in(
521                                            &ThumbsUpActiveCompletion,
522                                            focus_handle,
523                                            window,
524                                            cx
525                                        ))
526                                        .on_click(cx.listener(move |this, _, window, cx| {
527                                            if this.active_completion.is_some() {
528                                                this.thumbs_up_active(&ThumbsUpActiveCompletion, window, cx);
529                                            }
530                                        })),
531                                ),
532                        ),
533                ),
534        )
535    }
536}
537
538impl Render for RateCompletionModal {
539    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
540        let border_color = cx.theme().colors().border;
541
542        h_flex()
543            .key_context("RateCompletionModal")
544            .track_focus(&self.focus_handle)
545            .on_action(cx.listener(Self::dismiss))
546            .on_action(cx.listener(Self::confirm))
547            .on_action(cx.listener(Self::select_previous))
548            .on_action(cx.listener(Self::select_prev_edit))
549            .on_action(cx.listener(Self::select_next))
550            .on_action(cx.listener(Self::select_next_edit))
551            .on_action(cx.listener(Self::select_first))
552            .on_action(cx.listener(Self::select_last))
553            .on_action(cx.listener(Self::thumbs_up_active))
554            .on_action(cx.listener(Self::thumbs_down_active))
555            .on_action(cx.listener(Self::focus_completions))
556            .on_action(cx.listener(Self::preview_completion))
557            .bg(cx.theme().colors().elevated_surface_background)
558            .border_1()
559            .border_color(border_color)
560            .w(window.viewport_size().width - px(320.))
561            .h(window.viewport_size().height - px(300.))
562            .rounded_lg()
563            .shadow_lg()
564            .child(
565                v_flex()
566                    .w_72()
567                    .h_full()
568                    .border_r_1()
569                    .border_color(border_color)
570                    .flex_shrink_0()
571                    .overflow_hidden()
572                    .child(
573                        h_flex()
574                            .h_8()
575                            .px_2()
576                            .justify_between()
577                            .border_b_1()
578                            .border_color(border_color)
579                            .child(
580                                Icon::new(IconName::ZedPredict)
581                                    .size(IconSize::Small)
582                            )
583                            .child(
584                                Label::new("From most recent to oldest")
585                                    .color(Color::Muted)
586                                    .size(LabelSize::Small),
587                            )
588                    )
589                    .child(
590                        div()
591                            .id("completion_list")
592                            .p_0p5()
593                            .h_full()
594                            .overflow_y_scroll()
595                            .child(
596                                List::new()
597                                    .empty_message(
598                                        div()
599                                            .p_2()
600                                            .child(
601                                                Label::new("No completions yet. Use the editor to generate some, and make sure to rate them!")
602                                                    .color(Color::Muted),
603                                            )
604                                            .into_any_element(),
605                                    )
606                                    .children(self.zeta.read(cx).shown_completions().cloned().enumerate().map(
607                                        |(index, completion)| {
608                                            let selected =
609                                                self.active_completion.as_ref().map_or(false, |selected| {
610                                                    selected.completion.id == completion.id
611                                                });
612                                            let rated =
613                                                self.zeta.read(cx).is_completion_rated(completion.id);
614
615                                            let (icon_name, icon_color, tooltip_text) = match (rated, completion.edits.is_empty()) {
616                                                (true, _) => (IconName::Check, Color::Success, "Rated Completion"),
617                                                (false, true) => (IconName::File, Color::Muted, "No Edits Produced"),
618                                                (false, false) => (IconName::FileDiff, Color::Accent, "Edits Available"),
619                                            };
620
621                                            let file_name = completion.path.file_name().map(|f| f.to_string_lossy().to_string()).unwrap_or("untitled".to_string());
622                                            let file_path = completion.path.parent().map(|p| p.to_string_lossy().to_string());
623
624                                            ListItem::new(completion.id)
625                                                .inset(true)
626                                                .spacing(ListItemSpacing::Sparse)
627                                                .focused(index == self.selected_index)
628                                                .toggle_state(selected)
629                                                .child(
630                                                    h_flex()
631                                                        .id("completion-content")
632                                                        .gap_3()
633                                                        .child(
634                                                            Icon::new(icon_name)
635                                                                .color(icon_color)
636                                                                .size(IconSize::Small)
637                                                        )
638                                                        .child(
639                                                            v_flex()
640                                                                .child(
641                                                                    h_flex().gap_1()
642                                                                        .child(Label::new(file_name).size(LabelSize::Small))
643                                                                        .when_some(file_path, |this, p| this.child(Label::new(p).size(LabelSize::Small).color(Color::Muted)))
644                                                                )
645                                                                .child(Label::new(format!("{} ago, {:.2?}", format_time_ago(completion.response_received_at.elapsed()), completion.latency()))
646                                                                    .color(Color::Muted)
647                                                                    .size(LabelSize::XSmall)
648                                                                )
649                                                        )
650                                                )
651                                                .tooltip(Tooltip::text(tooltip_text))
652                                                .on_click(cx.listener(move |this, _, window, cx| {
653                                                    this.select_completion(Some(completion.clone()), true, window, cx);
654                                                }))
655                                        },
656                                    )),
657                            )
658                    ),
659            )
660            .children(self.render_active_completion(window, cx))
661            .on_mouse_down_out(cx.listener(|_, _, _, cx| cx.emit(DismissEvent)))
662    }
663}
664
665impl EventEmitter<DismissEvent> for RateCompletionModal {}
666
667impl Focusable for RateCompletionModal {
668    fn focus_handle(&self, _cx: &App) -> FocusHandle {
669        self.focus_handle.clone()
670    }
671}
672
673impl ModalView for RateCompletionModal {}
674
675fn format_time_ago(elapsed: Duration) -> String {
676    let seconds = elapsed.as_secs();
677    if seconds < 120 {
678        "1 minute".to_string()
679    } else if seconds < 3600 {
680        format!("{} minutes", seconds / 60)
681    } else if seconds < 7200 {
682        "1 hour".to_string()
683    } else if seconds < 86400 {
684        format!("{} hours", seconds / 3600)
685    } else if seconds < 172800 {
686        "1 day".to_string()
687    } else {
688        format!("{} days", seconds / 86400)
689    }
690}