rate_completion_modal.rs

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