rate_prediction_modal.rs

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