rate_prediction_modal.rs

  1use crate::{EditPrediction, EditPredictionRating, Zeta};
  2use buffer_diff::{BufferDiff};
  3use cloud_zeta2_prompt::write_codeblock;
  4use editor::{Editor, ExcerptRange, MultiBuffer};
  5use gpui::{
  6    App, BorderStyle, DismissEvent, EdgesRefinement, Entity, EventEmitter, FocusHandle, Focusable,
  7    Length, StyleRefinement, TextStyleRefinement, Window, actions, prelude::*,
  8};
  9use language::{LanguageRegistry, Point, language_settings};
 10use markdown::{Markdown, MarkdownStyle};
 11use settings::Settings as _;
 12use std::fmt::Write;
 13use std::sync::Arc;
 14use std::time::Duration;
 15use theme::ThemeSettings;
 16use ui::{KeyBinding, List, ListItem, ListItemSpacing, Tooltip, prelude::*};
 17use workspace::{ModalView, Workspace};
 18
 19actions!(
 20    zeta,
 21    [
 22        /// Rates the active completion with a thumbs up.
 23        ThumbsUpActivePrediction,
 24        /// Rates the active completion with a thumbs down.
 25        ThumbsDownActivePrediction,
 26        /// Navigates to the next edit in the completion history.
 27        NextEdit,
 28        /// Navigates to the previous edit in the completion history.
 29        PreviousEdit,
 30        /// Focuses on the completions list.
 31        FocusPredictions,
 32        /// Previews the selected completion.
 33        PreviewPrediction,
 34    ]
 35);
 36
 37pub struct RatePredictionsModal {
 38    zeta: Entity<Zeta>,
 39    language_registry: Arc<LanguageRegistry>,
 40    active_prediction: Option<ActivePrediction>,
 41    selected_index: usize,
 42    diff_editor: Entity<Editor>,
 43    focus_handle: FocusHandle,
 44    _subscription: gpui::Subscription,
 45    current_view: RatePredictionView,
 46}
 47
 48struct ActivePrediction {
 49    prediction: EditPrediction,
 50    feedback_editor: Entity<Editor>,
 51    formatted_inputs: Entity<Markdown>,
 52}
 53
 54#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
 55enum RatePredictionView {
 56    SuggestedEdits,
 57    RawInput,
 58}
 59
 60impl RatePredictionView {
 61    pub fn name(&self) -> &'static str {
 62        match self {
 63            Self::SuggestedEdits => "Suggested Edits",
 64            Self::RawInput => "Recorded Events & Input",
 65        }
 66    }
 67}
 68
 69impl RatePredictionsModal {
 70    pub fn toggle(workspace: &mut Workspace, window: &mut Window, cx: &mut Context<Workspace>) {
 71        if let Some(zeta) = Zeta::try_global(cx) {
 72            let language_registry = workspace.app_state().languages.clone();
 73            workspace.toggle_modal(window, cx, |window, cx| {
 74                RatePredictionsModal::new(zeta, language_registry, window, cx)
 75            });
 76
 77            telemetry::event!("Rate Prediction Modal Open", source = "Edit Prediction");
 78        }
 79    }
 80
 81    pub fn new(
 82        zeta: Entity<Zeta>,
 83        language_registry: Arc<LanguageRegistry>,
 84        window: &mut Window,
 85        cx: &mut Context<Self>,
 86    ) -> Self {
 87        let subscription = cx.observe(&zeta, |_, _, cx| cx.notify());
 88
 89        Self {
 90            zeta,
 91            language_registry,
 92            selected_index: 0,
 93            focus_handle: cx.focus_handle(),
 94            active_prediction: None,
 95            _subscription: subscription,
 96            diff_editor: cx.new(|cx| {
 97                let multibuffer = cx.new(|_| MultiBuffer::new(language::Capability::ReadOnly));
 98                let mut editor = Editor::for_multibuffer(multibuffer, None, window, cx);
 99                editor.disable_inline_diagnostics();
100                editor.set_expand_all_diff_hunks(cx);
101                editor.set_show_git_diff_gutter(false, cx);
102                editor
103            }),
104            current_view: RatePredictionView::SuggestedEdits,
105        }
106    }
107
108    fn dismiss(&mut self, _: &menu::Cancel, _: &mut Window, cx: &mut Context<Self>) {
109        cx.emit(DismissEvent);
110    }
111
112    fn select_next(&mut self, _: &menu::SelectNext, _: &mut Window, cx: &mut Context<Self>) {
113        self.selected_index += 1;
114        self.selected_index = usize::min(
115            self.selected_index,
116            self.zeta.read(cx).shown_predictions().count(),
117        );
118        cx.notify();
119    }
120
121    fn select_previous(
122        &mut self,
123        _: &menu::SelectPrevious,
124        _: &mut Window,
125        cx: &mut Context<Self>,
126    ) {
127        self.selected_index = self.selected_index.saturating_sub(1);
128        cx.notify();
129    }
130
131    fn select_next_edit(&mut self, _: &NextEdit, _: &mut Window, cx: &mut Context<Self>) {
132        let next_index = self
133            .zeta
134            .read(cx)
135            .shown_predictions()
136            .skip(self.selected_index)
137            .enumerate()
138            .skip(1) // Skip straight to the next item
139            .find(|(_, completion)| !completion.edits.is_empty())
140            .map(|(ix, _)| ix + self.selected_index);
141
142        if let Some(next_index) = next_index {
143            self.selected_index = next_index;
144            cx.notify();
145        }
146    }
147
148    fn select_prev_edit(&mut self, _: &PreviousEdit, _: &mut Window, cx: &mut Context<Self>) {
149        let zeta = self.zeta.read(cx);
150        let completions_len = zeta.shown_completions_len();
151
152        let prev_index = self
153            .zeta
154            .read(cx)
155            .shown_predictions()
156            .rev()
157            .skip((completions_len - 1) - self.selected_index)
158            .enumerate()
159            .skip(1) // Skip straight to the previous item
160            .find(|(_, completion)| !completion.edits.is_empty())
161            .map(|(ix, _)| self.selected_index - ix);
162
163        if let Some(prev_index) = prev_index {
164            self.selected_index = prev_index;
165            cx.notify();
166        }
167        cx.notify();
168    }
169
170    fn select_first(&mut self, _: &menu::SelectFirst, _: &mut Window, cx: &mut Context<Self>) {
171        self.selected_index = 0;
172        cx.notify();
173    }
174
175    fn select_last(&mut self, _: &menu::SelectLast, _window: &mut Window, cx: &mut Context<Self>) {
176        self.selected_index = self.zeta.read(cx).shown_completions_len() - 1;
177        cx.notify();
178    }
179
180    pub fn thumbs_up_active(
181        &mut self,
182        _: &ThumbsUpActivePrediction,
183        window: &mut Window,
184        cx: &mut Context<Self>,
185    ) {
186        self.zeta.update(cx, |zeta, cx| {
187            if let Some(active) = &self.active_prediction {
188                zeta.rate_prediction(
189                    &active.prediction,
190                    EditPredictionRating::Positive,
191                    active.feedback_editor.read(cx).text(cx),
192                    cx,
193                );
194            }
195        });
196
197        let current_completion = self
198            .active_prediction
199            .as_ref()
200            .map(|completion| completion.prediction.clone());
201        self.select_completion(current_completion, false, window, cx);
202        self.select_next_edit(&Default::default(), window, cx);
203        self.confirm(&Default::default(), window, cx);
204
205        cx.notify();
206    }
207
208    pub fn thumbs_down_active(
209        &mut self,
210        _: &ThumbsDownActivePrediction,
211        window: &mut Window,
212        cx: &mut Context<Self>,
213    ) {
214        if let Some(active) = &self.active_prediction {
215            if active.feedback_editor.read(cx).text(cx).is_empty() {
216                return;
217            }
218
219            self.zeta.update(cx, |zeta, cx| {
220                zeta.rate_prediction(
221                    &active.prediction,
222                    EditPredictionRating::Negative,
223                    active.feedback_editor.read(cx).text(cx),
224                    cx,
225                );
226            });
227        }
228
229        let current_completion = self
230            .active_prediction
231            .as_ref()
232            .map(|completion| completion.prediction.clone());
233        self.select_completion(current_completion, false, window, cx);
234        self.select_next_edit(&Default::default(), window, cx);
235        self.confirm(&Default::default(), window, cx);
236
237        cx.notify();
238    }
239
240    fn focus_completions(
241        &mut self,
242        _: &FocusPredictions,
243        window: &mut Window,
244        cx: &mut Context<Self>,
245    ) {
246        cx.focus_self(window);
247        cx.notify();
248    }
249
250    fn preview_completion(
251        &mut self,
252        _: &PreviewPrediction,
253        window: &mut Window,
254        cx: &mut Context<Self>,
255    ) {
256        let completion = self
257            .zeta
258            .read(cx)
259            .shown_predictions()
260            .skip(self.selected_index)
261            .take(1)
262            .next()
263            .cloned();
264
265        self.select_completion(completion, false, window, cx);
266    }
267
268    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
269        let completion = self
270            .zeta
271            .read(cx)
272            .shown_predictions()
273            .skip(self.selected_index)
274            .take(1)
275            .next()
276            .cloned();
277
278        self.select_completion(completion, true, window, cx);
279    }
280
281    pub fn select_completion(
282        &mut self,
283        prediction: Option<EditPrediction>,
284        focus: bool,
285        window: &mut Window,
286        cx: &mut Context<Self>,
287    ) {
288        // Avoid resetting completion rating if it's already selected.
289        if let Some(prediction) = prediction {
290            self.selected_index = self
291                .zeta
292                .read(cx)
293                .shown_predictions()
294                .enumerate()
295                .find(|(_, completion_b)| prediction.id == completion_b.id)
296                .map(|(ix, _)| ix)
297                .unwrap_or(self.selected_index);
298            cx.notify();
299
300            if let Some(prev_prediction) = self.active_prediction.as_ref()
301                && prediction.id == prev_prediction.prediction.id
302            {
303                if focus {
304                    window.focus(&prev_prediction.feedback_editor.focus_handle(cx));
305                }
306                return;
307            }
308
309            self.diff_editor.update(cx, |editor, cx| {
310                let new_buffer = prediction.edit_preview.build_result_buffer(cx);
311                let new_buffer_snapshot = new_buffer.read(cx).snapshot();
312                let old_buffer_snapshot = prediction.snapshot.clone();
313                let new_buffer_id = new_buffer_snapshot.remote_id();
314
315                let range = prediction
316                    .edit_preview
317                    .compute_visible_range(&prediction.edits)
318                    .unwrap_or(Point::zero()..Point::zero());
319                let start = Point::new(range.start.row.saturating_sub(5), 0);
320                let end = Point::new(range.end.row + 5, 0).min(new_buffer_snapshot.max_point());
321
322                let language = new_buffer_snapshot.language().cloned();
323                let diff = cx.new(|cx| BufferDiff::new(&new_buffer_snapshot.text, cx));
324                diff.update(cx, |diff, cx| {
325                    let update = diff.update_diff(
326                        new_buffer_snapshot.text.clone(),
327                        Some(old_buffer_snapshot.text().into()),
328                        true,
329                        language,
330                        cx,
331                    );
332                    cx.spawn(async move |diff, cx| {
333                        let update = update.await;
334                        diff.update(cx, |diff, cx| {
335                            diff.set_snapshot(update, &new_buffer_snapshot.text, true, cx);
336                        })
337                    })
338                    .detach();
339                });
340
341                editor.disable_header_for_buffer(new_buffer_id, cx);
342                editor.buffer().update(cx, |multibuffer, cx| {
343                    multibuffer.clear(cx);
344                    multibuffer.push_excerpts(
345                        new_buffer,
346                        vec![ExcerptRange {
347                            context: start..end,
348                            primary: start..end,
349                        }],
350                        cx,
351                    );
352                    multibuffer.add_diff(diff, cx);
353                });
354            });
355
356            let mut formatted_inputs = String::new();
357
358            write!(&mut formatted_inputs, "## Events\n\n").unwrap();
359
360            for event in &prediction.inputs.events {
361                write!(&mut formatted_inputs, "```diff\n{event}```\n\n").unwrap();
362            }
363
364            write!(&mut formatted_inputs, "## Included files\n\n").unwrap();
365
366            for included_file in &prediction.inputs.included_files {
367                let cursor_insertions = &[(prediction.inputs.cursor_point, "<|CURSOR|>")];
368
369                write!(
370                    &mut formatted_inputs,
371                    "### {}\n\n",
372                    included_file.path.display()
373                )
374                .unwrap();
375
376                write_codeblock(
377                    &included_file.path,
378                    &included_file.excerpts,
379                    if included_file.path == prediction.inputs.cursor_path {
380                        cursor_insertions
381                    } else {
382                        &[]
383                    },
384                    included_file.max_row,
385                    false,
386                    &mut formatted_inputs,
387                );
388            }
389
390            self.active_prediction = Some(ActivePrediction {
391                prediction,
392                feedback_editor: cx.new(|cx| {
393                    let mut editor = Editor::multi_line(window, cx);
394                    editor.disable_scrollbars_and_minimap(window, cx);
395                    editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
396                    editor.set_show_line_numbers(false, cx);
397                    editor.set_show_git_diff_gutter(false, cx);
398                    editor.set_show_code_actions(false, cx);
399                    editor.set_show_runnables(false, cx);
400                    editor.set_show_breakpoints(false, cx);
401                    editor.set_show_wrap_guides(false, cx);
402                    editor.set_show_indent_guides(false, cx);
403                    editor.set_show_edit_predictions(Some(false), window, cx);
404                    editor.set_placeholder_text("Add your feedback…", window, cx);
405                    if focus {
406                        cx.focus_self(window);
407                    }
408                    editor
409                }),
410                formatted_inputs: cx.new(|cx| {
411                    Markdown::new(
412                        formatted_inputs.into(),
413                        Some(self.language_registry.clone()),
414                        None,
415                        cx,
416                    )
417                }),
418            });
419        } else {
420            self.active_prediction = None;
421        }
422
423        cx.notify();
424    }
425
426    fn render_view_nav(&self, cx: &Context<Self>) -> impl IntoElement {
427        h_flex()
428            .h_8()
429            .px_1()
430            .border_b_1()
431            .border_color(cx.theme().colors().border)
432            .bg(cx.theme().colors().elevated_surface_background)
433            .gap_1()
434            .child(
435                Button::new(
436                    ElementId::Name("suggested-edits".into()),
437                    RatePredictionView::SuggestedEdits.name(),
438                )
439                .label_size(LabelSize::Small)
440                .on_click(cx.listener(move |this, _, _window, cx| {
441                    this.current_view = RatePredictionView::SuggestedEdits;
442                    cx.notify();
443                }))
444                .toggle_state(self.current_view == RatePredictionView::SuggestedEdits),
445            )
446            .child(
447                Button::new(
448                    ElementId::Name("raw-input".into()),
449                    RatePredictionView::RawInput.name(),
450                )
451                .label_size(LabelSize::Small)
452                .on_click(cx.listener(move |this, _, _window, cx| {
453                    this.current_view = RatePredictionView::RawInput;
454                    cx.notify();
455                }))
456                .toggle_state(self.current_view == RatePredictionView::RawInput),
457            )
458    }
459
460    fn render_suggested_edits(&self, cx: &mut Context<Self>) -> Option<gpui::Stateful<Div>> {
461        let bg_color = cx.theme().colors().editor_background;
462        Some(
463            div()
464                .id("diff")
465                .p_4()
466                .size_full()
467                .bg(bg_color)
468                .overflow_scroll()
469                .whitespace_nowrap()
470                .child(self.diff_editor.clone()),
471        )
472    }
473
474    fn render_raw_input(
475        &self,
476        window: &mut Window,
477        cx: &mut Context<Self>,
478    ) -> Option<gpui::Stateful<Div>> {
479        let theme_settings = ThemeSettings::get_global(cx);
480        let buffer_font_size = theme_settings.buffer_font_size(cx);
481
482        Some(
483            v_flex()
484                .size_full()
485                .overflow_hidden()
486                .relative()
487                .child(
488                    div()
489                        .id("raw-input")
490                        .py_4()
491                        .px_6()
492                        .size_full()
493                        .bg(cx.theme().colors().editor_background)
494                        .overflow_scroll()
495                        .child(if let Some(active_prediction) = &self.active_prediction {
496                            markdown::MarkdownElement::new(
497                                active_prediction.formatted_inputs.clone(),
498                                MarkdownStyle {
499                                    base_text_style: window.text_style(),
500                                    syntax: cx.theme().syntax().clone(),
501                                    code_block: StyleRefinement {
502                                        text: Some(TextStyleRefinement {
503                                            font_family: Some(
504                                                theme_settings.buffer_font.family.clone(),
505                                            ),
506                                            font_size: Some(buffer_font_size.into()),
507                                            ..Default::default()
508                                        }),
509                                        padding: EdgesRefinement {
510                                            top: Some(DefiniteLength::Absolute(
511                                                AbsoluteLength::Pixels(px(8.)),
512                                            )),
513                                            left: Some(DefiniteLength::Absolute(
514                                                AbsoluteLength::Pixels(px(8.)),
515                                            )),
516                                            right: Some(DefiniteLength::Absolute(
517                                                AbsoluteLength::Pixels(px(8.)),
518                                            )),
519                                            bottom: Some(DefiniteLength::Absolute(
520                                                AbsoluteLength::Pixels(px(8.)),
521                                            )),
522                                        },
523                                        margin: EdgesRefinement {
524                                            top: Some(Length::Definite(px(8.).into())),
525                                            left: Some(Length::Definite(px(0.).into())),
526                                            right: Some(Length::Definite(px(0.).into())),
527                                            bottom: Some(Length::Definite(px(12.).into())),
528                                        },
529                                        border_style: Some(BorderStyle::Solid),
530                                        border_widths: EdgesRefinement {
531                                            top: Some(AbsoluteLength::Pixels(px(1.))),
532                                            left: Some(AbsoluteLength::Pixels(px(1.))),
533                                            right: Some(AbsoluteLength::Pixels(px(1.))),
534                                            bottom: Some(AbsoluteLength::Pixels(px(1.))),
535                                        },
536                                        border_color: Some(cx.theme().colors().border_variant),
537                                        background: Some(
538                                            cx.theme().colors().editor_background.into(),
539                                        ),
540                                        ..Default::default()
541                                    },
542                                    ..Default::default()
543                                },
544                            )
545                            .into_any_element()
546                        } else {
547                            div()
548                                .child("No active completion".to_string())
549                                .into_any_element()
550                        }),
551                )
552                .id("raw-input-view"),
553        )
554    }
555
556    fn render_active_completion(
557        &mut self,
558        window: &mut Window,
559        cx: &mut Context<Self>,
560    ) -> Option<impl IntoElement> {
561        let active_prediction = self.active_prediction.as_ref()?;
562        let completion_id = active_prediction.prediction.id.clone();
563        let focus_handle = &self.focus_handle(cx);
564
565        let border_color = cx.theme().colors().border;
566        let bg_color = cx.theme().colors().editor_background;
567
568        let rated = self.zeta.read(cx).is_prediction_rated(&completion_id);
569        let feedback_empty = active_prediction
570            .feedback_editor
571            .read(cx)
572            .text(cx)
573            .is_empty();
574
575        let label_container = h_flex().pl_1().gap_1p5();
576
577        Some(
578            v_flex()
579                .size_full()
580                .overflow_hidden()
581                .relative()
582                .child(
583                    v_flex()
584                        .size_full()
585                        .overflow_hidden()
586                        .relative()
587                        .child(self.render_view_nav(cx))
588                        .when_some(
589                            match self.current_view {
590                                RatePredictionView::SuggestedEdits => {
591                                    self.render_suggested_edits(cx)
592                                }
593                                RatePredictionView::RawInput => self.render_raw_input(window, cx),
594                            },
595                            |this, element| this.child(element),
596                        ),
597                )
598                .when(!rated, |this| {
599                    this.child(
600                        h_flex()
601                            .p_2()
602                            .gap_2()
603                            .border_y_1()
604                            .border_color(border_color)
605                            .child(
606                                Icon::new(IconName::Info)
607                                    .size(IconSize::XSmall)
608                                    .color(Color::Muted),
609                            )
610                            .child(
611                                div().w_full().pr_2().flex_wrap().child(
612                                    Label::new(concat!(
613                                        "Explain why this completion is good or bad. ",
614                                        "If it's negative, describe what you expected instead."
615                                    ))
616                                    .size(LabelSize::Small)
617                                    .color(Color::Muted),
618                                ),
619                            ),
620                    )
621                })
622                .when(!rated, |this| {
623                    this.child(
624                        div()
625                            .h_40()
626                            .pt_1()
627                            .bg(bg_color)
628                            .child(active_prediction.feedback_editor.clone()),
629                    )
630                })
631                .child(
632                    h_flex()
633                        .p_1()
634                        .h_8()
635                        .max_h_8()
636                        .border_t_1()
637                        .border_color(border_color)
638                        .max_w_full()
639                        .justify_between()
640                        .children(if rated {
641                            Some(
642                                label_container
643                                    .child(
644                                        Icon::new(IconName::Check)
645                                            .size(IconSize::Small)
646                                            .color(Color::Success),
647                                    )
648                                    .child(Label::new("Rated completion.").color(Color::Muted)),
649                            )
650                        } else if active_prediction.prediction.edits.is_empty() {
651                            Some(
652                                label_container
653                                    .child(
654                                        Icon::new(IconName::Warning)
655                                            .size(IconSize::Small)
656                                            .color(Color::Warning),
657                                    )
658                                    .child(Label::new("No edits produced.").color(Color::Muted)),
659                            )
660                        } else {
661                            Some(label_container)
662                        })
663                        .child(
664                            h_flex()
665                                .gap_1()
666                                .child(
667                                    Button::new("bad", "Bad Prediction")
668                                        .icon(IconName::ThumbsDown)
669                                        .icon_size(IconSize::Small)
670                                        .icon_position(IconPosition::Start)
671                                        .disabled(rated || feedback_empty)
672                                        .when(feedback_empty, |this| {
673                                            this.tooltip(Tooltip::text(
674                                                "Explain what's bad about it before reporting it",
675                                            ))
676                                        })
677                                        .key_binding(KeyBinding::for_action_in(
678                                            &ThumbsDownActivePrediction,
679                                            focus_handle,
680                                            cx,
681                                        ))
682                                        .on_click(cx.listener(move |this, _, window, cx| {
683                                            if this.active_prediction.is_some() {
684                                                this.thumbs_down_active(
685                                                    &ThumbsDownActivePrediction,
686                                                    window,
687                                                    cx,
688                                                );
689                                            }
690                                        })),
691                                )
692                                .child(
693                                    Button::new("good", "Good Prediction")
694                                        .icon(IconName::ThumbsUp)
695                                        .icon_size(IconSize::Small)
696                                        .icon_position(IconPosition::Start)
697                                        .disabled(rated)
698                                        .key_binding(KeyBinding::for_action_in(
699                                            &ThumbsUpActivePrediction,
700                                            focus_handle,
701                                            cx,
702                                        ))
703                                        .on_click(cx.listener(move |this, _, window, cx| {
704                                            if this.active_prediction.is_some() {
705                                                this.thumbs_up_active(
706                                                    &ThumbsUpActivePrediction,
707                                                    window,
708                                                    cx,
709                                                );
710                                            }
711                                        })),
712                                ),
713                        ),
714                ),
715        )
716    }
717
718    fn render_shown_completions(&self, cx: &Context<Self>) -> impl Iterator<Item = ListItem> {
719        self.zeta
720            .read(cx)
721            .shown_predictions()
722            .cloned()
723            .enumerate()
724            .map(|(index, completion)| {
725                let selected = self
726                    .active_prediction
727                    .as_ref()
728                    .is_some_and(|selected| selected.prediction.id == completion.id);
729                let rated = self.zeta.read(cx).is_prediction_rated(&completion.id);
730
731                let (icon_name, icon_color, tooltip_text) =
732                    match (rated, completion.edits.is_empty()) {
733                        (true, _) => (IconName::Check, Color::Success, "Rated Prediction"),
734                        (false, true) => (IconName::File, Color::Muted, "No Edits Produced"),
735                        (false, false) => (IconName::FileDiff, Color::Accent, "Edits Available"),
736                    };
737
738                let file = completion.buffer.read(cx).file();
739                let file_name = file
740                    .as_ref()
741                    .map_or(SharedString::new_static("untitled"), |file| {
742                        file.file_name(cx).to_string().into()
743                    });
744                let file_path = file.map(|file| file.path().as_unix_str().to_string());
745
746                ListItem::new(completion.id.clone())
747                    .inset(true)
748                    .spacing(ListItemSpacing::Sparse)
749                    .focused(index == self.selected_index)
750                    .toggle_state(selected)
751                    .child(
752                        h_flex()
753                            .id("completion-content")
754                            .gap_3()
755                            .child(Icon::new(icon_name).color(icon_color).size(IconSize::Small))
756                            .child(
757                                v_flex()
758                                    .child(
759                                        h_flex()
760                                            .gap_1()
761                                            .child(Label::new(file_name).size(LabelSize::Small))
762                                            .when_some(file_path, |this, p| {
763                                                this.child(
764                                                    Label::new(p)
765                                                        .size(LabelSize::Small)
766                                                        .color(Color::Muted),
767                                                )
768                                            }),
769                                    )
770                                    .child(
771                                        Label::new(format!(
772                                            "{} ago, {:.2?}",
773                                            format_time_ago(
774                                                completion.response_received_at.elapsed()
775                                            ),
776                                            completion.latency()
777                                        ))
778                                        .color(Color::Muted)
779                                        .size(LabelSize::XSmall),
780                                    ),
781                            ),
782                    )
783                    .tooltip(Tooltip::text(tooltip_text))
784                    .on_click(cx.listener(move |this, _, window, cx| {
785                        this.select_completion(Some(completion.clone()), true, window, cx);
786                    }))
787            })
788    }
789}
790
791impl Render for RatePredictionsModal {
792    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
793        let border_color = cx.theme().colors().border;
794
795        h_flex()
796            .key_context("RatePredictionModal")
797            .track_focus(&self.focus_handle)
798            .on_action(cx.listener(Self::dismiss))
799            .on_action(cx.listener(Self::confirm))
800            .on_action(cx.listener(Self::select_previous))
801            .on_action(cx.listener(Self::select_prev_edit))
802            .on_action(cx.listener(Self::select_next))
803            .on_action(cx.listener(Self::select_next_edit))
804            .on_action(cx.listener(Self::select_first))
805            .on_action(cx.listener(Self::select_last))
806            .on_action(cx.listener(Self::thumbs_up_active))
807            .on_action(cx.listener(Self::thumbs_down_active))
808            .on_action(cx.listener(Self::focus_completions))
809            .on_action(cx.listener(Self::preview_completion))
810            .bg(cx.theme().colors().elevated_surface_background)
811            .border_1()
812            .border_color(border_color)
813            .w(window.viewport_size().width - px(320.))
814            .h(window.viewport_size().height - px(300.))
815            .rounded_lg()
816            .shadow_lg()
817            .child(
818                v_flex()
819                    .w_72()
820                    .h_full()
821                    .border_r_1()
822                    .border_color(border_color)
823                    .flex_shrink_0()
824                    .overflow_hidden()
825                    .child(
826                        h_flex()
827                            .h_8()
828                            .px_2()
829                            .justify_between()
830                            .border_b_1()
831                            .border_color(border_color)
832                            .child(Icon::new(IconName::ZedPredict).size(IconSize::Small))
833                            .child(
834                                Label::new("From most recent to oldest")
835                                    .color(Color::Muted)
836                                    .size(LabelSize::Small),
837                            ),
838                    )
839                    .child(
840                        div()
841                            .id("completion_list")
842                            .p_0p5()
843                            .h_full()
844                            .overflow_y_scroll()
845                            .child(
846                                List::new()
847                                    .empty_message(
848                                        div()
849                                            .p_2()
850                                            .child(
851                                                Label::new(concat!(
852                                                    "No completions yet. ",
853                                                    "Use the editor to generate some, ",
854                                                    "and make sure to rate them!"
855                                                ))
856                                                .color(Color::Muted),
857                                            )
858                                            .into_any_element(),
859                                    )
860                                    .children(self.render_shown_completions(cx)),
861                            ),
862                    ),
863            )
864            .children(self.render_active_completion(window, cx))
865            .on_mouse_down_out(cx.listener(|_, _, _, cx| cx.emit(DismissEvent)))
866    }
867}
868
869impl EventEmitter<DismissEvent> for RatePredictionsModal {}
870
871impl Focusable for RatePredictionsModal {
872    fn focus_handle(&self, _cx: &App) -> FocusHandle {
873        self.focus_handle.clone()
874    }
875}
876
877impl ModalView for RatePredictionsModal {}
878
879fn format_time_ago(elapsed: Duration) -> String {
880    let seconds = elapsed.as_secs();
881    if seconds < 120 {
882        "1 minute".to_string()
883    } else if seconds < 3600 {
884        format!("{} minutes", seconds / 60)
885    } else if seconds < 7200 {
886        "1 hour".to_string()
887    } else if seconds < 86400 {
888        format!("{} hours", seconds / 3600)
889    } else if seconds < 172800 {
890        "1 day".to_string()
891    } else {
892        format!("{} days", seconds / 86400)
893    }
894}