rate_completion_modal.rs

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