rate_prediction_modal.rs

   1use buffer_diff::BufferDiff;
   2use edit_prediction::{EditPrediction, EditPredictionRating, EditPredictionStore};
   3use editor::{Editor, Inlay, MultiBuffer};
   4use feature_flags::FeatureFlag;
   5use gpui::{
   6    App, BorderStyle, DismissEvent, EdgesRefinement, Entity, EventEmitter, FocusHandle, Focusable,
   7    Length, StyleRefinement, TextStyleRefinement, Window, actions, prelude::*,
   8};
   9use language::{Buffer, CodeLabel, LanguageRegistry, Point, ToOffset, language_settings};
  10use markdown::{Markdown, MarkdownStyle};
  11use project::{
  12    Completion, CompletionDisplayOptions, CompletionResponse, CompletionSource, InlayId,
  13};
  14use settings::Settings as _;
  15use std::rc::Rc;
  16use std::{fmt::Write, sync::Arc, time::Duration};
  17use theme::ThemeSettings;
  18use ui::{
  19    ContextMenu, DropdownMenu, KeyBinding, List, ListItem, ListItemSpacing, PopoverMenuHandle,
  20    Tooltip, prelude::*,
  21};
  22use workspace::{ModalView, Workspace};
  23
  24actions!(
  25    zeta,
  26    [
  27        /// Rates the active completion with a thumbs up.
  28        ThumbsUpActivePrediction,
  29        /// Rates the active completion with a thumbs down.
  30        ThumbsDownActivePrediction,
  31        /// Navigates to the next edit in the completion history.
  32        NextEdit,
  33        /// Navigates to the previous edit in the completion history.
  34        PreviousEdit,
  35        /// Focuses on the completions list.
  36        FocusPredictions,
  37        /// Previews the selected completion.
  38        PreviewPrediction,
  39    ]
  40);
  41
  42pub struct PredictEditsRatePredictionsFeatureFlag;
  43
  44impl FeatureFlag for PredictEditsRatePredictionsFeatureFlag {
  45    const NAME: &'static str = "predict-edits-rate-completions";
  46}
  47
  48pub struct RatePredictionsModal {
  49    ep_store: Entity<EditPredictionStore>,
  50    language_registry: Arc<LanguageRegistry>,
  51    active_prediction: Option<ActivePrediction>,
  52    selected_index: usize,
  53    diff_editor: Entity<Editor>,
  54    focus_handle: FocusHandle,
  55    _subscription: gpui::Subscription,
  56    current_view: RatePredictionView,
  57    failure_mode_menu_handle: PopoverMenuHandle<ContextMenu>,
  58}
  59
  60struct ActivePrediction {
  61    prediction: EditPrediction,
  62    feedback_editor: Entity<Editor>,
  63    formatted_inputs: Entity<Markdown>,
  64}
  65
  66#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
  67enum RatePredictionView {
  68    SuggestedEdits,
  69    RawInput,
  70}
  71
  72impl RatePredictionView {
  73    pub fn name(&self) -> &'static str {
  74        match self {
  75            Self::SuggestedEdits => "Suggested Edits",
  76            Self::RawInput => "Recorded Events & Input",
  77        }
  78    }
  79}
  80
  81impl RatePredictionsModal {
  82    pub fn toggle(workspace: &mut Workspace, window: &mut Window, cx: &mut Context<Workspace>) {
  83        if let Some(ep_store) = EditPredictionStore::try_global(cx) {
  84            let language_registry = workspace.app_state().languages.clone();
  85            workspace.toggle_modal(window, cx, |window, cx| {
  86                RatePredictionsModal::new(ep_store, language_registry, window, cx)
  87            });
  88
  89            telemetry::event!("Rate Prediction Modal Open", source = "Edit Prediction");
  90        }
  91    }
  92
  93    pub fn new(
  94        ep_store: Entity<EditPredictionStore>,
  95        language_registry: Arc<LanguageRegistry>,
  96        window: &mut Window,
  97        cx: &mut Context<Self>,
  98    ) -> Self {
  99        let subscription = cx.observe(&ep_store, |_, _, cx| cx.notify());
 100
 101        Self {
 102            ep_store,
 103            language_registry,
 104            selected_index: 0,
 105            focus_handle: cx.focus_handle(),
 106            active_prediction: None,
 107            _subscription: subscription,
 108            diff_editor: cx.new(|cx| {
 109                let multibuffer = cx.new(|_| MultiBuffer::new(language::Capability::ReadOnly));
 110                let mut editor = Editor::for_multibuffer(multibuffer, None, window, cx);
 111                editor.disable_inline_diagnostics();
 112                editor.set_expand_all_diff_hunks(cx);
 113                editor.set_show_git_diff_gutter(false, cx);
 114                editor
 115            }),
 116            current_view: RatePredictionView::SuggestedEdits,
 117            failure_mode_menu_handle: PopoverMenuHandle::default(),
 118        }
 119    }
 120
 121    fn dismiss(&mut self, _: &menu::Cancel, _: &mut Window, cx: &mut Context<Self>) {
 122        cx.emit(DismissEvent);
 123    }
 124
 125    fn select_next(&mut self, _: &menu::SelectNext, _: &mut Window, cx: &mut Context<Self>) {
 126        self.selected_index += 1;
 127        self.selected_index = usize::min(
 128            self.selected_index,
 129            self.ep_store.read(cx).shown_predictions().count(),
 130        );
 131        cx.notify();
 132    }
 133
 134    fn select_previous(
 135        &mut self,
 136        _: &menu::SelectPrevious,
 137        _: &mut Window,
 138        cx: &mut Context<Self>,
 139    ) {
 140        self.selected_index = self.selected_index.saturating_sub(1);
 141        cx.notify();
 142    }
 143
 144    fn select_next_edit(&mut self, _: &NextEdit, _: &mut Window, cx: &mut Context<Self>) {
 145        let next_index = self
 146            .ep_store
 147            .read(cx)
 148            .shown_predictions()
 149            .skip(self.selected_index)
 150            .enumerate()
 151            .skip(1) // Skip straight to the next item
 152            .find(|(_, completion)| !completion.edits.is_empty())
 153            .map(|(ix, _)| ix + self.selected_index);
 154
 155        if let Some(next_index) = next_index {
 156            self.selected_index = next_index;
 157            cx.notify();
 158        }
 159    }
 160
 161    fn select_prev_edit(&mut self, _: &PreviousEdit, _: &mut Window, cx: &mut Context<Self>) {
 162        let ep_store = self.ep_store.read(cx);
 163        let completions_len = ep_store.shown_completions_len();
 164
 165        let prev_index = self
 166            .ep_store
 167            .read(cx)
 168            .shown_predictions()
 169            .rev()
 170            .skip((completions_len - 1) - self.selected_index)
 171            .enumerate()
 172            .skip(1) // Skip straight to the previous item
 173            .find(|(_, completion)| !completion.edits.is_empty())
 174            .map(|(ix, _)| self.selected_index - ix);
 175
 176        if let Some(prev_index) = prev_index {
 177            self.selected_index = prev_index;
 178            cx.notify();
 179        }
 180        cx.notify();
 181    }
 182
 183    fn select_first(&mut self, _: &menu::SelectFirst, _: &mut Window, cx: &mut Context<Self>) {
 184        self.selected_index = 0;
 185        cx.notify();
 186    }
 187
 188    fn select_last(&mut self, _: &menu::SelectLast, _window: &mut Window, cx: &mut Context<Self>) {
 189        self.selected_index = self.ep_store.read(cx).shown_completions_len() - 1;
 190        cx.notify();
 191    }
 192
 193    pub fn thumbs_up_active(
 194        &mut self,
 195        _: &ThumbsUpActivePrediction,
 196        window: &mut Window,
 197        cx: &mut Context<Self>,
 198    ) {
 199        self.ep_store.update(cx, |ep_store, cx| {
 200            if let Some(active) = &self.active_prediction {
 201                ep_store.rate_prediction(
 202                    &active.prediction,
 203                    EditPredictionRating::Positive,
 204                    active.feedback_editor.read(cx).text(cx),
 205                    cx,
 206                );
 207            }
 208        });
 209
 210        let current_completion = self
 211            .active_prediction
 212            .as_ref()
 213            .map(|completion| completion.prediction.clone());
 214        self.select_completion(current_completion, false, window, cx);
 215        self.select_next_edit(&Default::default(), window, cx);
 216        self.confirm(&Default::default(), window, cx);
 217
 218        cx.notify();
 219    }
 220
 221    pub fn thumbs_down_active(
 222        &mut self,
 223        _: &ThumbsDownActivePrediction,
 224        window: &mut Window,
 225        cx: &mut Context<Self>,
 226    ) {
 227        if let Some(active) = &self.active_prediction {
 228            if active.feedback_editor.read(cx).text(cx).is_empty() {
 229                return;
 230            }
 231
 232            self.ep_store.update(cx, |ep_store, cx| {
 233                ep_store.rate_prediction(
 234                    &active.prediction,
 235                    EditPredictionRating::Negative,
 236                    active.feedback_editor.read(cx).text(cx),
 237                    cx,
 238                );
 239            });
 240        }
 241
 242        let current_completion = self
 243            .active_prediction
 244            .as_ref()
 245            .map(|completion| completion.prediction.clone());
 246        self.select_completion(current_completion, false, window, cx);
 247        self.select_next_edit(&Default::default(), window, cx);
 248        self.confirm(&Default::default(), window, cx);
 249
 250        cx.notify();
 251    }
 252
 253    fn focus_completions(
 254        &mut self,
 255        _: &FocusPredictions,
 256        window: &mut Window,
 257        cx: &mut Context<Self>,
 258    ) {
 259        cx.focus_self(window);
 260        cx.notify();
 261    }
 262
 263    fn preview_completion(
 264        &mut self,
 265        _: &PreviewPrediction,
 266        window: &mut Window,
 267        cx: &mut Context<Self>,
 268    ) {
 269        let completion = self
 270            .ep_store
 271            .read(cx)
 272            .shown_predictions()
 273            .skip(self.selected_index)
 274            .take(1)
 275            .next()
 276            .cloned();
 277
 278        self.select_completion(completion, false, window, cx);
 279    }
 280
 281    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
 282        let completion = self
 283            .ep_store
 284            .read(cx)
 285            .shown_predictions()
 286            .skip(self.selected_index)
 287            .take(1)
 288            .next()
 289            .cloned();
 290
 291        self.select_completion(completion, true, window, cx);
 292    }
 293
 294    pub fn select_completion(
 295        &mut self,
 296        prediction: Option<EditPrediction>,
 297        focus: bool,
 298        window: &mut Window,
 299        cx: &mut Context<Self>,
 300    ) {
 301        // Avoid resetting completion rating if it's already selected.
 302        if let Some(prediction) = prediction {
 303            self.selected_index = self
 304                .ep_store
 305                .read(cx)
 306                .shown_predictions()
 307                .enumerate()
 308                .find(|(_, completion_b)| prediction.id == completion_b.id)
 309                .map(|(ix, _)| ix)
 310                .unwrap_or(self.selected_index);
 311            cx.notify();
 312
 313            if let Some(prev_prediction) = self.active_prediction.as_ref()
 314                && prediction.id == prev_prediction.prediction.id
 315            {
 316                if focus {
 317                    window.focus(&prev_prediction.feedback_editor.focus_handle(cx), cx);
 318                }
 319                return;
 320            }
 321
 322            self.diff_editor.update(cx, |editor, cx| {
 323                let new_buffer = prediction.edit_preview.build_result_buffer(cx);
 324                let new_buffer_snapshot = new_buffer.read(cx).snapshot();
 325                let old_buffer_snapshot = prediction.snapshot.clone();
 326                let new_buffer_id = new_buffer_snapshot.remote_id();
 327
 328                let range = prediction
 329                    .edit_preview
 330                    .compute_visible_range(&prediction.edits)
 331                    .unwrap_or(Point::zero()..Point::zero());
 332                let start = Point::new(range.start.row.saturating_sub(5), 0);
 333                let end = Point::new(range.end.row + 5, 0).min(new_buffer_snapshot.max_point());
 334
 335                let language = new_buffer_snapshot.language().cloned();
 336                let diff = cx.new(|cx| BufferDiff::new(&new_buffer_snapshot.text, cx));
 337                diff.update(cx, |diff, cx| {
 338                    let update = diff.update_diff(
 339                        new_buffer_snapshot.text.clone(),
 340                        Some(old_buffer_snapshot.text().into()),
 341                        Some(true),
 342                        language,
 343                        cx,
 344                    );
 345                    cx.spawn(async move |diff, cx| {
 346                        let update = update.await;
 347                        if let Some(task) = diff
 348                            .update(cx, |diff, cx| {
 349                                diff.set_snapshot(update, &new_buffer_snapshot.text, cx)
 350                            })
 351                            .ok()
 352                        {
 353                            task.await;
 354                        }
 355                    })
 356                    .detach();
 357                });
 358
 359                editor.disable_header_for_buffer(new_buffer_id, cx);
 360                let excerpt_id = editor.buffer().update(cx, |multibuffer, cx| {
 361                    multibuffer.clear(cx);
 362                    multibuffer.set_excerpts_for_buffer(new_buffer, [start..end], 0, cx);
 363                    multibuffer.add_diff(diff, cx);
 364                    multibuffer.excerpt_ids().into_iter().next()
 365                });
 366
 367                if let Some((excerpt_id, cursor_position)) =
 368                    excerpt_id.zip(prediction.cursor_position.as_ref())
 369                {
 370                    let multibuffer_snapshot = editor.buffer().read(cx).snapshot(cx);
 371                    if let Some(buffer_snapshot) =
 372                        multibuffer_snapshot.buffer_for_excerpt(excerpt_id)
 373                    {
 374                        let cursor_offset = prediction
 375                            .edit_preview
 376                            .anchor_to_offset_in_result(cursor_position.anchor)
 377                            + cursor_position.offset;
 378                        let cursor_anchor = buffer_snapshot.anchor_after(cursor_offset);
 379
 380                        if let Some(anchor) =
 381                            multibuffer_snapshot.anchor_in_excerpt(excerpt_id, cursor_anchor)
 382                        {
 383                            editor.splice_inlays(
 384                                &[InlayId::EditPrediction(0)],
 385                                vec![Inlay::edit_prediction(0, anchor, "")],
 386                                cx,
 387                            );
 388                        }
 389                    }
 390                }
 391            });
 392
 393            let mut formatted_inputs = String::new();
 394
 395            write!(&mut formatted_inputs, "## Events\n\n").unwrap();
 396
 397            for event in &prediction.inputs.events {
 398                formatted_inputs.push_str("```diff\n");
 399                zeta_prompt::write_event(&mut formatted_inputs, event.as_ref());
 400                formatted_inputs.push_str("```\n\n");
 401            }
 402
 403            write!(&mut formatted_inputs, "## Related files\n\n").unwrap();
 404
 405            for included_file in prediction.inputs.related_files.iter() {
 406                write!(
 407                    &mut formatted_inputs,
 408                    "### {}\n\n",
 409                    included_file.path.display()
 410                )
 411                .unwrap();
 412
 413                for excerpt in included_file.excerpts.iter() {
 414                    write!(
 415                        &mut formatted_inputs,
 416                        "```{}\n{}\n```\n",
 417                        included_file.path.display(),
 418                        excerpt.text
 419                    )
 420                    .unwrap();
 421                }
 422            }
 423
 424            write!(&mut formatted_inputs, "## Cursor Excerpt\n\n").unwrap();
 425
 426            writeln!(
 427                &mut formatted_inputs,
 428                "```{}\n{}<CURSOR>{}\n```\n",
 429                prediction.inputs.cursor_path.display(),
 430                &prediction.inputs.cursor_excerpt[..prediction.inputs.cursor_offset_in_excerpt],
 431                &prediction.inputs.cursor_excerpt[prediction.inputs.cursor_offset_in_excerpt..],
 432            )
 433            .unwrap();
 434
 435            self.active_prediction = Some(ActivePrediction {
 436                prediction,
 437                feedback_editor: cx.new(|cx| {
 438                    let mut editor = Editor::multi_line(window, cx);
 439                    editor.disable_scrollbars_and_minimap(window, cx);
 440                    editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
 441                    editor.set_show_line_numbers(false, cx);
 442                    editor.set_show_git_diff_gutter(false, cx);
 443                    editor.set_show_code_actions(false, cx);
 444                    editor.set_show_runnables(false, cx);
 445                    editor.set_show_breakpoints(false, cx);
 446                    editor.set_show_wrap_guides(false, cx);
 447                    editor.set_show_indent_guides(false, cx);
 448                    editor.set_show_edit_predictions(Some(false), window, cx);
 449                    editor.set_placeholder_text("Add your feedback…", window, cx);
 450                    editor.set_completion_provider(Some(Rc::new(FeedbackCompletionProvider)));
 451                    if focus {
 452                        cx.focus_self(window);
 453                    }
 454                    editor
 455                }),
 456                formatted_inputs: cx.new(|cx| {
 457                    Markdown::new(
 458                        formatted_inputs.into(),
 459                        Some(self.language_registry.clone()),
 460                        None,
 461                        cx,
 462                    )
 463                }),
 464            });
 465        } else {
 466            self.active_prediction = None;
 467        }
 468
 469        cx.notify();
 470    }
 471
 472    fn render_view_nav(&self, cx: &Context<Self>) -> impl IntoElement {
 473        h_flex()
 474            .h_8()
 475            .px_1()
 476            .border_b_1()
 477            .border_color(cx.theme().colors().border)
 478            .bg(cx.theme().colors().elevated_surface_background)
 479            .gap_1()
 480            .child(
 481                Button::new(
 482                    ElementId::Name("suggested-edits".into()),
 483                    RatePredictionView::SuggestedEdits.name(),
 484                )
 485                .label_size(LabelSize::Small)
 486                .on_click(cx.listener(move |this, _, _window, cx| {
 487                    this.current_view = RatePredictionView::SuggestedEdits;
 488                    cx.notify();
 489                }))
 490                .toggle_state(self.current_view == RatePredictionView::SuggestedEdits),
 491            )
 492            .child(
 493                Button::new(
 494                    ElementId::Name("raw-input".into()),
 495                    RatePredictionView::RawInput.name(),
 496                )
 497                .label_size(LabelSize::Small)
 498                .on_click(cx.listener(move |this, _, _window, cx| {
 499                    this.current_view = RatePredictionView::RawInput;
 500                    cx.notify();
 501                }))
 502                .toggle_state(self.current_view == RatePredictionView::RawInput),
 503            )
 504    }
 505
 506    fn render_suggested_edits(&self, cx: &mut Context<Self>) -> Option<gpui::Stateful<Div>> {
 507        let bg_color = cx.theme().colors().editor_background;
 508        Some(
 509            div()
 510                .id("diff")
 511                .p_4()
 512                .size_full()
 513                .bg(bg_color)
 514                .overflow_scroll()
 515                .whitespace_nowrap()
 516                .child(self.diff_editor.clone()),
 517        )
 518    }
 519
 520    fn render_raw_input(
 521        &self,
 522        window: &mut Window,
 523        cx: &mut Context<Self>,
 524    ) -> Option<gpui::Stateful<Div>> {
 525        let theme_settings = ThemeSettings::get_global(cx);
 526        let buffer_font_size = theme_settings.buffer_font_size(cx);
 527
 528        Some(
 529            v_flex()
 530                .size_full()
 531                .overflow_hidden()
 532                .relative()
 533                .child(
 534                    div()
 535                        .id("raw-input")
 536                        .py_4()
 537                        .px_6()
 538                        .size_full()
 539                        .bg(cx.theme().colors().editor_background)
 540                        .overflow_scroll()
 541                        .child(if let Some(active_prediction) = &self.active_prediction {
 542                            markdown::MarkdownElement::new(
 543                                active_prediction.formatted_inputs.clone(),
 544                                MarkdownStyle {
 545                                    base_text_style: window.text_style(),
 546                                    syntax: cx.theme().syntax().clone(),
 547                                    code_block: StyleRefinement {
 548                                        text: TextStyleRefinement {
 549                                            font_family: Some(
 550                                                theme_settings.buffer_font.family.clone(),
 551                                            ),
 552                                            font_size: Some(buffer_font_size.into()),
 553                                            ..Default::default()
 554                                        },
 555                                        padding: EdgesRefinement {
 556                                            top: Some(DefiniteLength::Absolute(
 557                                                AbsoluteLength::Pixels(px(8.)),
 558                                            )),
 559                                            left: Some(DefiniteLength::Absolute(
 560                                                AbsoluteLength::Pixels(px(8.)),
 561                                            )),
 562                                            right: Some(DefiniteLength::Absolute(
 563                                                AbsoluteLength::Pixels(px(8.)),
 564                                            )),
 565                                            bottom: Some(DefiniteLength::Absolute(
 566                                                AbsoluteLength::Pixels(px(8.)),
 567                                            )),
 568                                        },
 569                                        margin: EdgesRefinement {
 570                                            top: Some(Length::Definite(px(8.).into())),
 571                                            left: Some(Length::Definite(px(0.).into())),
 572                                            right: Some(Length::Definite(px(0.).into())),
 573                                            bottom: Some(Length::Definite(px(12.).into())),
 574                                        },
 575                                        border_style: Some(BorderStyle::Solid),
 576                                        border_widths: EdgesRefinement {
 577                                            top: Some(AbsoluteLength::Pixels(px(1.))),
 578                                            left: Some(AbsoluteLength::Pixels(px(1.))),
 579                                            right: Some(AbsoluteLength::Pixels(px(1.))),
 580                                            bottom: Some(AbsoluteLength::Pixels(px(1.))),
 581                                        },
 582                                        border_color: Some(cx.theme().colors().border_variant),
 583                                        background: Some(
 584                                            cx.theme().colors().editor_background.into(),
 585                                        ),
 586                                        ..Default::default()
 587                                    },
 588                                    ..Default::default()
 589                                },
 590                            )
 591                            .into_any_element()
 592                        } else {
 593                            div()
 594                                .child("No active completion".to_string())
 595                                .into_any_element()
 596                        }),
 597                )
 598                .id("raw-input-view"),
 599        )
 600    }
 601
 602    fn render_active_completion(
 603        &mut self,
 604        window: &mut Window,
 605        cx: &mut Context<Self>,
 606    ) -> Option<impl IntoElement> {
 607        let active_prediction = self.active_prediction.as_ref()?;
 608        let completion_id = active_prediction.prediction.id.clone();
 609        let focus_handle = &self.focus_handle(cx);
 610
 611        let border_color = cx.theme().colors().border;
 612        let bg_color = cx.theme().colors().editor_background;
 613
 614        let rated = self.ep_store.read(cx).is_prediction_rated(&completion_id);
 615        let feedback_empty = active_prediction
 616            .feedback_editor
 617            .read(cx)
 618            .text(cx)
 619            .is_empty();
 620
 621        let label_container = h_flex().pl_1().gap_1p5();
 622
 623        Some(
 624            v_flex()
 625                .size_full()
 626                .overflow_hidden()
 627                .relative()
 628                .child(
 629                    v_flex()
 630                        .size_full()
 631                        .overflow_hidden()
 632                        .relative()
 633                        .child(self.render_view_nav(cx))
 634                        .when_some(
 635                            match self.current_view {
 636                                RatePredictionView::SuggestedEdits => {
 637                                    self.render_suggested_edits(cx)
 638                                }
 639                                RatePredictionView::RawInput => self.render_raw_input(window, cx),
 640                            },
 641                            |this, element| this.child(element),
 642                        ),
 643                )
 644                .when(!rated, |this| {
 645                    let modal = cx.entity().downgrade();
 646                    let failure_mode_menu =
 647                        ContextMenu::build(window, cx, move |menu, _window, _cx| {
 648                            FeedbackCompletionProvider::FAILURE_MODES
 649                                .iter()
 650                                .fold(menu, |menu, (key, description)| {
 651                                    let key: SharedString = (*key).into();
 652                                    let description: SharedString = (*description).into();
 653                                    let modal = modal.clone();
 654                                    menu.entry(
 655                                        format!("{} {}", key, description),
 656                                        None,
 657                                        move |window, cx| {
 658                                            if let Some(modal) = modal.upgrade() {
 659                                                modal.update(cx, |this, cx| {
 660                                                    if let Some(active) = &this.active_prediction {
 661                                                        active.feedback_editor.update(
 662                                                            cx,
 663                                                            |editor, cx| {
 664                                                                editor.set_text(
 665                                                                    format!("{} {}", key, description),
 666                                                                    window,
 667                                                                    cx,
 668                                                                );
 669                                                            },
 670                                                        );
 671                                                    }
 672                                                });
 673                                            }
 674                                        },
 675                                    )
 676                                })
 677                        });
 678
 679                    this.child(
 680                        h_flex()
 681                            .p_2()
 682                            .gap_2()
 683                            .border_y_1()
 684                            .border_color(border_color)
 685                            .child(
 686                                DropdownMenu::new(
 687                                        "failure-mode-dropdown",
 688                                        "Issue",
 689                                        failure_mode_menu,
 690                                    )
 691                                    .handle(self.failure_mode_menu_handle.clone())
 692                                    .style(ui::DropdownStyle::Outlined)
 693                                    .trigger_size(ButtonSize::Compact),
 694                            )
 695                            .child(
 696                                h_flex()
 697                                    .gap_2()
 698                                    .child(
 699                                        Icon::new(IconName::Info)
 700                                            .size(IconSize::XSmall)
 701                                            .color(Color::Muted),
 702                                    )
 703                                    .child(
 704                                        div().flex_wrap().child(
 705                                            Label::new(concat!(
 706                                                "Explain why this completion is good or bad. ",
 707                                                "If it's negative, describe what you expected instead."
 708                                            ))
 709                                            .size(LabelSize::Small)
 710                                            .color(Color::Muted),
 711                                        ),
 712                                    ),
 713                            ),
 714                    )
 715                })
 716                .when(!rated, |this| {
 717                    this.child(
 718                        div()
 719                            .h_40()
 720                            .pt_1()
 721                            .bg(bg_color)
 722                            .child(active_prediction.feedback_editor.clone()),
 723                    )
 724                })
 725                .child(
 726                    h_flex()
 727                        .p_1()
 728                        .h_8()
 729                        .max_h_8()
 730                        .border_t_1()
 731                        .border_color(border_color)
 732                        .max_w_full()
 733                        .justify_between()
 734                        .children(if rated {
 735                            Some(
 736                                label_container
 737                                    .child(
 738                                        Icon::new(IconName::Check)
 739                                            .size(IconSize::Small)
 740                                            .color(Color::Success),
 741                                    )
 742                                    .child(Label::new("Rated completion.").color(Color::Muted)),
 743                            )
 744                        } else if active_prediction.prediction.edits.is_empty() {
 745                            Some(
 746                                label_container
 747                                    .child(
 748                                        Icon::new(IconName::Warning)
 749                                            .size(IconSize::Small)
 750                                            .color(Color::Warning),
 751                                    )
 752                                    .child(Label::new("No edits produced.").color(Color::Muted)),
 753                            )
 754                        } else {
 755                            Some(label_container)
 756                        })
 757                        .child(
 758                            h_flex()
 759                                .gap_1()
 760                                .child(
 761                                    Button::new("bad", "Bad Prediction")
 762                                        .icon(IconName::ThumbsDown)
 763                                        .icon_size(IconSize::Small)
 764                                        .icon_position(IconPosition::Start)
 765                                        .disabled(rated || feedback_empty)
 766                                        .when(feedback_empty, |this| {
 767                                            this.tooltip(Tooltip::text(
 768                                                "Explain what's bad about it before reporting it",
 769                                            ))
 770                                        })
 771                                        .key_binding(KeyBinding::for_action_in(
 772                                            &ThumbsDownActivePrediction,
 773                                            focus_handle,
 774                                            cx,
 775                                        ))
 776                                        .on_click(cx.listener(move |this, _, window, cx| {
 777                                            if this.active_prediction.is_some() {
 778                                                this.thumbs_down_active(
 779                                                    &ThumbsDownActivePrediction,
 780                                                    window,
 781                                                    cx,
 782                                                );
 783                                            }
 784                                        })),
 785                                )
 786                                .child(
 787                                    Button::new("good", "Good Prediction")
 788                                        .icon(IconName::ThumbsUp)
 789                                        .icon_size(IconSize::Small)
 790                                        .icon_position(IconPosition::Start)
 791                                        .disabled(rated)
 792                                        .key_binding(KeyBinding::for_action_in(
 793                                            &ThumbsUpActivePrediction,
 794                                            focus_handle,
 795                                            cx,
 796                                        ))
 797                                        .on_click(cx.listener(move |this, _, window, cx| {
 798                                            if this.active_prediction.is_some() {
 799                                                this.thumbs_up_active(
 800                                                    &ThumbsUpActivePrediction,
 801                                                    window,
 802                                                    cx,
 803                                                );
 804                                            }
 805                                        })),
 806                                ),
 807                        ),
 808                ),
 809        )
 810    }
 811
 812    fn render_shown_completions(&self, cx: &Context<Self>) -> impl Iterator<Item = ListItem> {
 813        self.ep_store
 814            .read(cx)
 815            .shown_predictions()
 816            .cloned()
 817            .enumerate()
 818            .map(|(index, completion)| {
 819                let selected = self
 820                    .active_prediction
 821                    .as_ref()
 822                    .is_some_and(|selected| selected.prediction.id == completion.id);
 823                let rated = self.ep_store.read(cx).is_prediction_rated(&completion.id);
 824
 825                let (icon_name, icon_color, tooltip_text) =
 826                    match (rated, completion.edits.is_empty()) {
 827                        (true, _) => (IconName::Check, Color::Success, "Rated Prediction"),
 828                        (false, true) => (IconName::File, Color::Muted, "No Edits Produced"),
 829                        (false, false) => (IconName::FileDiff, Color::Accent, "Edits Available"),
 830                    };
 831
 832                let file = completion.buffer.read(cx).file();
 833                let file_name = file
 834                    .as_ref()
 835                    .map_or(SharedString::new_static("untitled"), |file| {
 836                        file.file_name(cx).to_string().into()
 837                    });
 838                let file_path = file.map(|file| file.path().as_unix_str().to_string());
 839
 840                ListItem::new(completion.id.clone())
 841                    .inset(true)
 842                    .spacing(ListItemSpacing::Sparse)
 843                    .focused(index == self.selected_index)
 844                    .toggle_state(selected)
 845                    .child(
 846                        h_flex()
 847                            .id("completion-content")
 848                            .gap_3()
 849                            .child(Icon::new(icon_name).color(icon_color).size(IconSize::Small))
 850                            .child(
 851                                v_flex()
 852                                    .child(
 853                                        h_flex()
 854                                            .gap_1()
 855                                            .child(Label::new(file_name).size(LabelSize::Small))
 856                                            .when_some(file_path, |this, p| {
 857                                                this.child(
 858                                                    Label::new(p)
 859                                                        .size(LabelSize::Small)
 860                                                        .color(Color::Muted),
 861                                                )
 862                                            }),
 863                                    )
 864                                    .child(
 865                                        Label::new(format!(
 866                                            "{} ago, {:.2?}",
 867                                            format_time_ago(
 868                                                completion.response_received_at.elapsed()
 869                                            ),
 870                                            completion.latency()
 871                                        ))
 872                                        .color(Color::Muted)
 873                                        .size(LabelSize::XSmall),
 874                                    ),
 875                            ),
 876                    )
 877                    .tooltip(Tooltip::text(tooltip_text))
 878                    .on_click(cx.listener(move |this, _, window, cx| {
 879                        this.select_completion(Some(completion.clone()), true, window, cx);
 880                    }))
 881            })
 882    }
 883}
 884
 885impl Render for RatePredictionsModal {
 886    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 887        let border_color = cx.theme().colors().border;
 888
 889        h_flex()
 890            .key_context("RatePredictionModal")
 891            .track_focus(&self.focus_handle)
 892            .on_action(cx.listener(Self::dismiss))
 893            .on_action(cx.listener(Self::confirm))
 894            .on_action(cx.listener(Self::select_previous))
 895            .on_action(cx.listener(Self::select_prev_edit))
 896            .on_action(cx.listener(Self::select_next))
 897            .on_action(cx.listener(Self::select_next_edit))
 898            .on_action(cx.listener(Self::select_first))
 899            .on_action(cx.listener(Self::select_last))
 900            .on_action(cx.listener(Self::thumbs_up_active))
 901            .on_action(cx.listener(Self::thumbs_down_active))
 902            .on_action(cx.listener(Self::focus_completions))
 903            .on_action(cx.listener(Self::preview_completion))
 904            .bg(cx.theme().colors().elevated_surface_background)
 905            .border_1()
 906            .border_color(border_color)
 907            .w(window.viewport_size().width - px(320.))
 908            .h(window.viewport_size().height - px(300.))
 909            .rounded_lg()
 910            .shadow_lg()
 911            .child(
 912                v_flex()
 913                    .w_72()
 914                    .h_full()
 915                    .border_r_1()
 916                    .border_color(border_color)
 917                    .flex_shrink_0()
 918                    .overflow_hidden()
 919                    .child({
 920                        let icons = self.ep_store.read(cx).icons(cx);
 921                        h_flex()
 922                            .h_8()
 923                            .px_2()
 924                            .justify_between()
 925                            .border_b_1()
 926                            .border_color(border_color)
 927                            .child(Icon::new(icons.base).size(IconSize::Small))
 928                            .child(
 929                                Label::new("From most recent to oldest")
 930                                    .color(Color::Muted)
 931                                    .size(LabelSize::Small),
 932                            )
 933                    })
 934                    .child(
 935                        div()
 936                            .id("completion_list")
 937                            .p_0p5()
 938                            .h_full()
 939                            .overflow_y_scroll()
 940                            .child(
 941                                List::new()
 942                                    .empty_message(
 943                                        div()
 944                                            .p_2()
 945                                            .child(
 946                                                Label::new(concat!(
 947                                                    "No completions yet. ",
 948                                                    "Use the editor to generate some, ",
 949                                                    "and make sure to rate them!"
 950                                                ))
 951                                                .color(Color::Muted),
 952                                            )
 953                                            .into_any_element(),
 954                                    )
 955                                    .children(self.render_shown_completions(cx)),
 956                            ),
 957                    ),
 958            )
 959            .children(self.render_active_completion(window, cx))
 960            .on_mouse_down_out(cx.listener(|this, _, _, cx| {
 961                if !this.failure_mode_menu_handle.is_deployed() {
 962                    cx.emit(DismissEvent);
 963                }
 964            }))
 965    }
 966}
 967
 968impl EventEmitter<DismissEvent> for RatePredictionsModal {}
 969
 970impl Focusable for RatePredictionsModal {
 971    fn focus_handle(&self, _cx: &App) -> FocusHandle {
 972        self.focus_handle.clone()
 973    }
 974}
 975
 976impl ModalView for RatePredictionsModal {}
 977
 978fn format_time_ago(elapsed: Duration) -> String {
 979    let seconds = elapsed.as_secs();
 980    if seconds < 120 {
 981        "1 minute".to_string()
 982    } else if seconds < 3600 {
 983        format!("{} minutes", seconds / 60)
 984    } else if seconds < 7200 {
 985        "1 hour".to_string()
 986    } else if seconds < 86400 {
 987        format!("{} hours", seconds / 3600)
 988    } else if seconds < 172800 {
 989        "1 day".to_string()
 990    } else {
 991        format!("{} days", seconds / 86400)
 992    }
 993}
 994
 995struct FeedbackCompletionProvider;
 996
 997impl FeedbackCompletionProvider {
 998    const FAILURE_MODES: &'static [(&'static str, &'static str)] = &[
 999        ("@location", "Unexpected location"),
1000        ("@malformed", "Incomplete, cut off, or syntax error"),
1001        (
1002            "@deleted",
1003            "Deleted code that should be kept (use `@reverted` if it undid a recent edit)",
1004        ),
1005        ("@style", "Wrong coding style or conventions"),
1006        ("@repetitive", "Repeated existing code"),
1007        ("@hallucinated", "Referenced non-existent symbols"),
1008        ("@formatting", "Wrong indentation or structure"),
1009        ("@aggressive", "Changed more than expected"),
1010        ("@conservative", "Too cautious, changed too little"),
1011        ("@context", "Ignored or misunderstood context"),
1012        ("@reverted", "Undid recent edits"),
1013        ("@cursor_position", "Cursor placed in unhelpful position"),
1014        ("@whitespace", "Unwanted whitespace or newline changes"),
1015    ];
1016}
1017
1018impl editor::CompletionProvider for FeedbackCompletionProvider {
1019    fn completions(
1020        &self,
1021        _excerpt_id: editor::ExcerptId,
1022        buffer: &Entity<Buffer>,
1023        buffer_position: language::Anchor,
1024        _trigger: editor::CompletionContext,
1025        _window: &mut Window,
1026        cx: &mut Context<Editor>,
1027    ) -> gpui::Task<anyhow::Result<Vec<CompletionResponse>>> {
1028        let buffer = buffer.read(cx);
1029        let mut count_back = 0;
1030
1031        for char in buffer.reversed_chars_at(buffer_position) {
1032            if char.is_ascii_alphanumeric() || char == '_' || char == '@' {
1033                count_back += 1;
1034            } else {
1035                break;
1036            }
1037        }
1038
1039        let start_anchor = buffer.anchor_before(
1040            buffer_position
1041                .to_offset(&buffer)
1042                .saturating_sub(count_back),
1043        );
1044
1045        let replace_range = start_anchor..buffer_position;
1046        let snapshot = buffer.text_snapshot();
1047        let query: String = snapshot.text_for_range(replace_range.clone()).collect();
1048
1049        if !query.starts_with('@') {
1050            return gpui::Task::ready(Ok(vec![CompletionResponse {
1051                completions: vec![],
1052                display_options: CompletionDisplayOptions {
1053                    dynamic_width: true,
1054                },
1055                is_incomplete: false,
1056            }]));
1057        }
1058
1059        let query_lower = query.to_lowercase();
1060
1061        let completions: Vec<Completion> = Self::FAILURE_MODES
1062            .iter()
1063            .filter(|(key, _description)| key.starts_with(&query_lower))
1064            .map(|(key, description)| Completion {
1065                replace_range: replace_range.clone(),
1066                new_text: format!("{} {}", key, description),
1067                label: CodeLabel::plain(format!("{}: {}", key, description), None),
1068                documentation: None,
1069                source: CompletionSource::Custom,
1070                icon_path: None,
1071                match_start: None,
1072                snippet_deduplication_key: None,
1073                insert_text_mode: None,
1074                confirm: None,
1075            })
1076            .collect();
1077
1078        gpui::Task::ready(Ok(vec![CompletionResponse {
1079            completions,
1080            display_options: CompletionDisplayOptions {
1081                dynamic_width: true,
1082            },
1083            is_incomplete: false,
1084        }]))
1085    }
1086
1087    fn is_completion_trigger(
1088        &self,
1089        _buffer: &Entity<Buffer>,
1090        _position: language::Anchor,
1091        text: &str,
1092        _trigger_in_words: bool,
1093        _cx: &mut Context<Editor>,
1094    ) -> bool {
1095        text.chars()
1096            .last()
1097            .is_some_and(|c| c.is_ascii_alphanumeric() || c == '_' || c == '@')
1098    }
1099}