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