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