rate_completion_modal.rs

  1use crate::{InlineCompletion, InlineCompletionRating, Zeta};
  2use editor::Editor;
  3use gpui::{
  4    actions, prelude::*, AppContext, DismissEvent, EventEmitter, FocusHandle, FocusableView,
  5    HighlightStyle, Model, StyledText, TextStyle, View, ViewContext,
  6};
  7use language::{language_settings, OffsetRangeExt};
  8
  9use settings::Settings;
 10use theme::ThemeSettings;
 11use ui::{prelude::*, KeyBinding, List, ListItem, ListItemSpacing, TintColor, Tooltip};
 12use workspace::{ModalView, Workspace};
 13
 14actions!(
 15    zeta,
 16    [
 17        RateCompletions,
 18        ThumbsUp,
 19        ThumbsDown,
 20        ThumbsUpActiveCompletion,
 21        ThumbsDownActiveCompletion,
 22        NextEdit,
 23        PreviousEdit,
 24        FocusCompletions,
 25        PreviewCompletion,
 26    ]
 27);
 28
 29pub fn init(cx: &mut AppContext) {
 30    cx.observe_new_views(move |workspace: &mut Workspace, _cx| {
 31        workspace.register_action(|workspace, _: &RateCompletions, cx| {
 32            RateCompletionModal::toggle(workspace, cx);
 33        });
 34    })
 35    .detach();
 36}
 37
 38pub struct RateCompletionModal {
 39    zeta: Model<Zeta>,
 40    active_completion: Option<ActiveCompletion>,
 41    selected_index: usize,
 42    focus_handle: FocusHandle,
 43    _subscription: gpui::Subscription,
 44}
 45
 46struct ActiveCompletion {
 47    completion: InlineCompletion,
 48    feedback_editor: View<Editor>,
 49}
 50
 51impl RateCompletionModal {
 52    pub fn toggle(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) {
 53        if let Some(zeta) = Zeta::global(cx) {
 54            workspace.toggle_modal(cx, |cx| RateCompletionModal::new(zeta, cx));
 55        }
 56    }
 57
 58    pub fn new(zeta: Model<Zeta>, cx: &mut ViewContext<Self>) -> Self {
 59        let subscription = cx.observe(&zeta, |_, _, cx| cx.notify());
 60        Self {
 61            zeta,
 62            selected_index: 0,
 63            focus_handle: cx.focus_handle(),
 64            active_completion: None,
 65            _subscription: subscription,
 66        }
 67    }
 68
 69    fn dismiss(&mut self, _: &menu::Cancel, cx: &mut ViewContext<Self>) {
 70        cx.emit(DismissEvent);
 71    }
 72
 73    fn select_next(&mut self, _: &menu::SelectNext, cx: &mut ViewContext<Self>) {
 74        self.selected_index += 1;
 75        self.selected_index = usize::min(
 76            self.selected_index,
 77            self.zeta.read(cx).recent_completions().count(),
 78        );
 79        cx.notify();
 80    }
 81
 82    fn select_prev(&mut self, _: &menu::SelectPrev, cx: &mut ViewContext<Self>) {
 83        self.selected_index = self.selected_index.saturating_sub(1);
 84        cx.notify();
 85    }
 86
 87    fn select_next_edit(&mut self, _: &NextEdit, cx: &mut ViewContext<Self>) {
 88        let next_index = self
 89            .zeta
 90            .read(cx)
 91            .recent_completions()
 92            .skip(self.selected_index)
 93            .enumerate()
 94            .skip(1) // Skip straight to the next item
 95            .find(|(_, completion)| !completion.edits.is_empty())
 96            .map(|(ix, _)| ix + self.selected_index);
 97
 98        if let Some(next_index) = next_index {
 99            self.selected_index = next_index;
100            cx.notify();
101        }
102    }
103
104    fn select_prev_edit(&mut self, _: &PreviousEdit, cx: &mut ViewContext<Self>) {
105        let zeta = self.zeta.read(cx);
106        let completions_len = zeta.recent_completions_len();
107
108        let prev_index = self
109            .zeta
110            .read(cx)
111            .recent_completions()
112            .rev()
113            .skip((completions_len - 1) - self.selected_index)
114            .enumerate()
115            .skip(1) // Skip straight to the previous item
116            .find(|(_, completion)| !completion.edits.is_empty())
117            .map(|(ix, _)| self.selected_index - ix);
118
119        if let Some(prev_index) = prev_index {
120            self.selected_index = prev_index;
121            cx.notify();
122        }
123        cx.notify();
124    }
125
126    fn select_first(&mut self, _: &menu::SelectFirst, cx: &mut ViewContext<Self>) {
127        self.selected_index = 0;
128        cx.notify();
129    }
130
131    fn select_last(&mut self, _: &menu::SelectLast, cx: &mut ViewContext<Self>) {
132        self.selected_index = self.zeta.read(cx).recent_completions_len() - 1;
133        cx.notify();
134    }
135
136    fn thumbs_up(&mut self, _: &ThumbsUp, cx: &mut ViewContext<Self>) {
137        self.zeta.update(cx, |zeta, cx| {
138            let completion = zeta
139                .recent_completions()
140                .skip(self.selected_index)
141                .next()
142                .cloned();
143
144            if let Some(completion) = completion {
145                zeta.rate_completion(
146                    &completion,
147                    InlineCompletionRating::Positive,
148                    "".to_string(),
149                    cx,
150                );
151            }
152        });
153        self.select_next_edit(&Default::default(), cx);
154        cx.notify();
155    }
156
157    fn thumbs_up_active(&mut self, _: &ThumbsUpActiveCompletion, cx: &mut ViewContext<Self>) {
158        self.zeta.update(cx, |zeta, cx| {
159            if let Some(active) = &self.active_completion {
160                zeta.rate_completion(
161                    &active.completion,
162                    InlineCompletionRating::Positive,
163                    active.feedback_editor.read(cx).text(cx),
164                    cx,
165                );
166            }
167        });
168
169        let current_completion = self
170            .active_completion
171            .as_ref()
172            .map(|completion| completion.completion.clone());
173        self.select_completion(current_completion, false, cx);
174        self.select_next_edit(&Default::default(), cx);
175        self.confirm(&Default::default(), cx);
176
177        cx.notify();
178    }
179
180    fn thumbs_down_active(&mut self, _: &ThumbsDownActiveCompletion, cx: &mut ViewContext<Self>) {
181        if let Some(active) = &self.active_completion {
182            if active.feedback_editor.read(cx).text(cx).is_empty() {
183                return;
184            }
185
186            self.zeta.update(cx, |zeta, cx| {
187                zeta.rate_completion(
188                    &active.completion,
189                    InlineCompletionRating::Negative,
190                    active.feedback_editor.read(cx).text(cx),
191                    cx,
192                );
193            });
194        }
195
196        let current_completion = self
197            .active_completion
198            .as_ref()
199            .map(|completion| completion.completion.clone());
200        self.select_completion(current_completion, false, cx);
201        self.select_next_edit(&Default::default(), cx);
202        self.confirm(&Default::default(), cx);
203
204        cx.notify();
205    }
206
207    fn focus_completions(&mut self, _: &FocusCompletions, cx: &mut ViewContext<Self>) {
208        cx.focus_self();
209        cx.notify();
210    }
211
212    fn preview_completion(&mut self, _: &PreviewCompletion, cx: &mut ViewContext<Self>) {
213        let completion = self
214            .zeta
215            .read(cx)
216            .recent_completions()
217            .skip(self.selected_index)
218            .take(1)
219            .next()
220            .cloned();
221
222        self.select_completion(completion, false, cx);
223    }
224
225    fn confirm(&mut self, _: &menu::Confirm, cx: &mut ViewContext<Self>) {
226        let completion = self
227            .zeta
228            .read(cx)
229            .recent_completions()
230            .skip(self.selected_index)
231            .take(1)
232            .next()
233            .cloned();
234
235        self.select_completion(completion, true, cx);
236    }
237
238    pub fn select_completion(
239        &mut self,
240        completion: Option<InlineCompletion>,
241        focus: bool,
242        cx: &mut ViewContext<Self>,
243    ) {
244        // Avoid resetting completion rating if it's already selected.
245        if let Some(completion) = completion.as_ref() {
246            self.selected_index = self
247                .zeta
248                .read(cx)
249                .recent_completions()
250                .enumerate()
251                .find(|(_, completion_b)| completion.id == completion_b.id)
252                .map(|(ix, _)| ix)
253                .unwrap_or(self.selected_index);
254            cx.notify();
255
256            if let Some(prev_completion) = self.active_completion.as_ref() {
257                if completion.id == prev_completion.completion.id {
258                    if focus {
259                        cx.focus_view(&prev_completion.feedback_editor);
260                    }
261                    return;
262                }
263            }
264        }
265
266        self.active_completion = completion.map(|completion| ActiveCompletion {
267            completion,
268            feedback_editor: cx.new_view(|cx| {
269                let mut editor = Editor::multi_line(cx);
270                editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
271                editor.set_show_line_numbers(false, cx);
272                editor.set_show_git_diff_gutter(false, cx);
273                editor.set_show_code_actions(false, cx);
274                editor.set_show_runnables(false, cx);
275                editor.set_show_wrap_guides(false, cx);
276                editor.set_show_indent_guides(false, cx);
277                editor.set_show_inline_completions(Some(false), cx);
278                editor.set_placeholder_text("Add your feedback…", cx);
279                if focus {
280                    cx.focus_self();
281                }
282                editor
283            }),
284        });
285        cx.notify();
286    }
287
288    fn render_active_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<impl IntoElement> {
289        let active_completion = self.active_completion.as_ref()?;
290        let completion_id = active_completion.completion.id;
291
292        let mut diff = active_completion
293            .completion
294            .snapshot
295            .text_for_range(active_completion.completion.excerpt_range.clone())
296            .collect::<String>();
297
298        let mut delta = 0;
299        let mut diff_highlights = Vec::new();
300        for (old_range, new_text) in active_completion.completion.edits.iter() {
301            let old_range = old_range.to_offset(&active_completion.completion.snapshot);
302            let old_start_in_text =
303                old_range.start - active_completion.completion.excerpt_range.start + delta;
304            let old_end_in_text =
305                old_range.end - active_completion.completion.excerpt_range.start + delta;
306            if old_start_in_text < old_end_in_text {
307                diff_highlights.push((
308                    old_start_in_text..old_end_in_text,
309                    HighlightStyle {
310                        background_color: Some(cx.theme().status().deleted_background),
311                        strikethrough: Some(gpui::StrikethroughStyle {
312                            thickness: px(1.),
313                            color: Some(cx.theme().colors().text_muted),
314                        }),
315                        ..Default::default()
316                    },
317                ));
318            }
319
320            if !new_text.is_empty() {
321                diff.insert_str(old_end_in_text, new_text);
322                diff_highlights.push((
323                    old_end_in_text..old_end_in_text + new_text.len(),
324                    HighlightStyle {
325                        background_color: Some(cx.theme().status().created_background),
326                        ..Default::default()
327                    },
328                ));
329                delta += new_text.len();
330            }
331        }
332
333        let settings = ThemeSettings::get_global(cx).clone();
334        let text_style = TextStyle {
335            color: cx.theme().colors().editor_foreground,
336            font_size: settings.buffer_font_size(cx).into(),
337            font_family: settings.buffer_font.family,
338            font_features: settings.buffer_font.features,
339            font_fallbacks: settings.buffer_font.fallbacks,
340            line_height: relative(settings.buffer_line_height.value()),
341            font_weight: settings.buffer_font.weight,
342            font_style: settings.buffer_font.style,
343            ..Default::default()
344        };
345
346        let rated = self.zeta.read(cx).is_completion_rated(completion_id);
347        let feedback_empty = active_completion
348            .feedback_editor
349            .read(cx)
350            .text(cx)
351            .is_empty();
352
353        let border_color = cx.theme().colors().border;
354        let bg_color = cx.theme().colors().editor_background;
355
356        let label_container = || h_flex().pl_1().gap_1p5();
357
358        Some(
359            v_flex()
360                .size_full()
361                .overflow_hidden()
362                .child(
363                    div()
364                        .id("diff")
365                        .py_4()
366                        .px_6()
367                        .size_full()
368                        .bg(bg_color)
369                        .overflow_scroll()
370                        .child(StyledText::new(diff).with_highlights(&text_style, diff_highlights)),
371                )
372                .child(
373                    h_flex()
374                        .p_2()
375                        .gap_2()
376                        .border_y_1()
377                        .border_color(border_color)
378                        .child(
379                            Icon::new(IconName::Info)
380                                .size(IconSize::XSmall)
381                                .color(Color::Muted)
382                        )
383                        .child(
384                            Label::new("Ensure you explain why this completion is negative or positive. In case it's negative, report what you expected instead.")
385                                .size(LabelSize::Small)
386                                .color(Color::Muted)
387                        )
388                )
389                .child(
390                    div()
391                        .h_40()
392                        .pt_1()
393                        .bg(bg_color)
394                        .child(active_completion.feedback_editor.clone()),
395                )
396                .child(
397                    h_flex()
398                        .p_1()
399                        .h_8()
400                        .border_t_1()
401                        .border_color(border_color)
402                        .max_w_full()
403                        .justify_between()
404                        .children(if rated {
405                            Some(
406                                label_container()
407                                    .child(
408                                        Icon::new(IconName::Check)
409                                            .size(IconSize::Small)
410                                            .color(Color::Success),
411                                    )
412                                    .child(Label::new("Rated completion").color(Color::Muted)),
413                            )
414                        } else if active_completion.completion.edits.is_empty() {
415                            Some(
416                                label_container()
417                                    .child(
418                                        Icon::new(IconName::Warning)
419                                            .size(IconSize::Small)
420                                            .color(Color::Warning),
421                                    )
422                                    .child(Label::new("No edits produced").color(Color::Muted)),
423                            )
424                        } else {
425                            Some(label_container())
426                        })
427                        .child(
428                            h_flex()
429                                .gap_1()
430                                .child(
431                                    Button::new("bad", "Bad Completion")
432                                        .key_binding(KeyBinding::for_action_in(
433                                            &ThumbsDown,
434                                            &self.focus_handle(cx),
435                                            cx,
436                                        ))
437                                        .style(ButtonStyle::Tinted(TintColor::Negative))
438                                        .icon(IconName::ThumbsDown)
439                                        .icon_size(IconSize::Small)
440                                        .icon_position(IconPosition::Start)
441                                        .icon_color(Color::Error)
442                                        .disabled(rated || feedback_empty)
443                                        .when(feedback_empty, |this| {
444                                            this.tooltip(|cx| {
445                                                Tooltip::text("Explain why this completion is bad before reporting it", cx)
446                                            })
447                                        })
448                                        .on_click(cx.listener(move |this, _, cx| {
449                                            this.thumbs_down_active(
450                                                &ThumbsDownActiveCompletion,
451                                                cx,
452                                            );
453                                        })),
454                                )
455                                .child(
456                                    Button::new("good", "Good Completion")
457                                        .key_binding(KeyBinding::for_action_in(
458                                            &ThumbsUp,
459                                            &self.focus_handle(cx),
460                                            cx,
461                                        ))
462                                        .style(ButtonStyle::Tinted(TintColor::Positive))
463                                        .icon(IconName::ThumbsUp)
464                                        .icon_size(IconSize::Small)
465                                        .icon_position(IconPosition::Start)
466                                        .icon_color(Color::Success)
467                                        .disabled(rated)
468                                        .on_click(cx.listener(move |this, _, cx| {
469                                            this.thumbs_up_active(&ThumbsUpActiveCompletion, cx);
470                                        })),
471                                ),
472                        ),
473                ),
474        )
475    }
476}
477
478impl Render for RateCompletionModal {
479    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
480        let border_color = cx.theme().colors().border;
481
482        h_flex()
483            .key_context("RateCompletionModal")
484            .track_focus(&self.focus_handle)
485            .on_action(cx.listener(Self::dismiss))
486            .on_action(cx.listener(Self::confirm))
487            .on_action(cx.listener(Self::select_prev))
488            .on_action(cx.listener(Self::select_prev_edit))
489            .on_action(cx.listener(Self::select_next))
490            .on_action(cx.listener(Self::select_next_edit))
491            .on_action(cx.listener(Self::select_first))
492            .on_action(cx.listener(Self::select_last))
493            .on_action(cx.listener(Self::thumbs_up))
494            .on_action(cx.listener(Self::thumbs_up_active))
495            .on_action(cx.listener(Self::thumbs_down_active))
496            .on_action(cx.listener(Self::focus_completions))
497            .on_action(cx.listener(Self::preview_completion))
498            .bg(cx.theme().colors().elevated_surface_background)
499            .border_1()
500            .border_color(border_color)
501            .w(cx.viewport_size().width - px(320.))
502            .h(cx.viewport_size().height - px(300.))
503            .rounded_lg()
504            .shadow_lg()
505            .child(
506                div()
507                    .id("completion_list")
508                    .border_r_1()
509                    .border_color(border_color)
510                    .w_96()
511                    .h_full()
512                    .p_0p5()
513                    .overflow_y_scroll()
514                    .child(
515                        List::new()
516                            .empty_message(
517                                div()
518                                    .p_2()
519                                    .child(
520                                            Label::new("No completions yet. Use the editor to generate some and rate them!")
521                                                .color(Color::Muted),
522                                    )
523                                    .into_any_element(),
524                            )
525                            .children(self.zeta.read(cx).recent_completions().cloned().enumerate().map(
526                                |(index, completion)| {
527                                    let selected =
528                                        self.active_completion.as_ref().map_or(false, |selected| {
529                                            selected.completion.id == completion.id
530                                        });
531                                    let rated =
532                                        self.zeta.read(cx).is_completion_rated(completion.id);
533                                    ListItem::new(completion.id)
534                                        .inset(true)
535                                        .spacing(ListItemSpacing::Sparse)
536                                        .focused(index == self.selected_index)
537                                        .selected(selected)
538                                        .start_slot(if rated {
539                                            Icon::new(IconName::Check).color(Color::Success)
540                                        } else if completion.edits.is_empty() {
541                                            Icon::new(IconName::File).color(Color::Muted).size(IconSize::Small)
542                                        } else {
543                                            Icon::new(IconName::FileDiff).color(Color::Accent).size(IconSize::Small)
544                                        })
545                                        .child(Label::new(
546                                            completion.path.to_string_lossy().to_string(),
547                                        ).size(LabelSize::Small))
548                                        .child(
549                                            div()
550                                                .overflow_hidden()
551                                                .text_ellipsis()
552                                                .child(Label::new(format!("({})", completion.id))
553                                                    .color(Color::Muted)
554                                                    .size(LabelSize::XSmall)),
555                                        )
556                                        .on_click(cx.listener(move |this, _, cx| {
557                                            this.select_completion(Some(completion.clone()), true, cx);
558                                        }))
559                                },
560                            )),
561                    ),
562            )
563            .children(self.render_active_completion(cx))
564            .on_mouse_down_out(cx.listener(|_, _, cx| cx.emit(DismissEvent)))
565    }
566}
567
568impl EventEmitter<DismissEvent> for RateCompletionModal {}
569
570impl FocusableView for RateCompletionModal {
571    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
572        self.focus_handle.clone()
573    }
574}
575
576impl ModalView for RateCompletionModal {}