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