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_bookmarks(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                                        .start_icon(Icon::new(IconName::ThumbsDown).size(IconSize::Small))
 763                                        .disabled(rated || feedback_empty)
 764                                        .when(feedback_empty, |this| {
 765                                            this.tooltip(Tooltip::text(
 766                                                "Explain what's bad about it before reporting it",
 767                                            ))
 768                                        })
 769                                        .key_binding(KeyBinding::for_action_in(
 770                                            &ThumbsDownActivePrediction,
 771                                            focus_handle,
 772                                            cx,
 773                                        ))
 774                                        .on_click(cx.listener(move |this, _, window, cx| {
 775                                            if this.active_prediction.is_some() {
 776                                                this.thumbs_down_active(
 777                                                    &ThumbsDownActivePrediction,
 778                                                    window,
 779                                                    cx,
 780                                                );
 781                                            }
 782                                        })),
 783                                )
 784                                .child(
 785                                    Button::new("good", "Good Prediction")
 786                                        .start_icon(Icon::new(IconName::ThumbsUp).size(IconSize::Small))
 787                                        .disabled(rated)
 788                                        .key_binding(KeyBinding::for_action_in(
 789                                            &ThumbsUpActivePrediction,
 790                                            focus_handle,
 791                                            cx,
 792                                        ))
 793                                        .on_click(cx.listener(move |this, _, window, cx| {
 794                                            if this.active_prediction.is_some() {
 795                                                this.thumbs_up_active(
 796                                                    &ThumbsUpActivePrediction,
 797                                                    window,
 798                                                    cx,
 799                                                );
 800                                            }
 801                                        })),
 802                                ),
 803                        ),
 804                ),
 805        )
 806    }
 807
 808    fn render_shown_completions(&self, cx: &Context<Self>) -> impl Iterator<Item = ListItem> {
 809        self.ep_store
 810            .read(cx)
 811            .shown_predictions()
 812            .cloned()
 813            .enumerate()
 814            .map(|(index, completion)| {
 815                let selected = self
 816                    .active_prediction
 817                    .as_ref()
 818                    .is_some_and(|selected| selected.prediction.id == completion.id);
 819                let rated = self.ep_store.read(cx).is_prediction_rated(&completion.id);
 820
 821                let (icon_name, icon_color, tooltip_text) =
 822                    match (rated, completion.edits.is_empty()) {
 823                        (true, _) => (IconName::Check, Color::Success, "Rated Prediction"),
 824                        (false, true) => (IconName::File, Color::Muted, "No Edits Produced"),
 825                        (false, false) => (IconName::FileDiff, Color::Accent, "Edits Available"),
 826                    };
 827
 828                let file = completion.buffer.read(cx).file();
 829                let file_name = file
 830                    .as_ref()
 831                    .map_or(SharedString::new_static("untitled"), |file| {
 832                        file.file_name(cx).to_string().into()
 833                    });
 834                let file_path = file.map(|file| file.path().as_unix_str().to_string());
 835
 836                ListItem::new(completion.id.clone())
 837                    .inset(true)
 838                    .spacing(ListItemSpacing::Sparse)
 839                    .focused(index == self.selected_index)
 840                    .toggle_state(selected)
 841                    .child(
 842                        h_flex()
 843                            .id("completion-content")
 844                            .gap_3()
 845                            .child(Icon::new(icon_name).color(icon_color).size(IconSize::Small))
 846                            .child(
 847                                v_flex().child(
 848                                    h_flex()
 849                                        .gap_1()
 850                                        .child(Label::new(file_name).size(LabelSize::Small))
 851                                        .when_some(file_path, |this, p| {
 852                                            this.child(
 853                                                Label::new(p)
 854                                                    .size(LabelSize::Small)
 855                                                    .color(Color::Muted),
 856                                            )
 857                                        }),
 858                                ),
 859                            ),
 860                    )
 861                    .tooltip(Tooltip::text(tooltip_text))
 862                    .on_click(cx.listener(move |this, _, window, cx| {
 863                        this.select_completion(Some(completion.clone()), true, window, cx);
 864                    }))
 865            })
 866    }
 867}
 868
 869impl Render for RatePredictionsModal {
 870    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 871        let border_color = cx.theme().colors().border;
 872
 873        h_flex()
 874            .key_context("RatePredictionModal")
 875            .track_focus(&self.focus_handle)
 876            .on_action(cx.listener(Self::dismiss))
 877            .on_action(cx.listener(Self::confirm))
 878            .on_action(cx.listener(Self::select_previous))
 879            .on_action(cx.listener(Self::select_prev_edit))
 880            .on_action(cx.listener(Self::select_next))
 881            .on_action(cx.listener(Self::select_next_edit))
 882            .on_action(cx.listener(Self::select_first))
 883            .on_action(cx.listener(Self::select_last))
 884            .on_action(cx.listener(Self::thumbs_up_active))
 885            .on_action(cx.listener(Self::thumbs_down_active))
 886            .on_action(cx.listener(Self::focus_completions))
 887            .on_action(cx.listener(Self::preview_completion))
 888            .bg(cx.theme().colors().elevated_surface_background)
 889            .border_1()
 890            .border_color(border_color)
 891            .w(window.viewport_size().width - px(320.))
 892            .h(window.viewport_size().height - px(300.))
 893            .rounded_lg()
 894            .shadow_lg()
 895            .child(
 896                v_flex()
 897                    .w_72()
 898                    .h_full()
 899                    .border_r_1()
 900                    .border_color(border_color)
 901                    .flex_shrink_0()
 902                    .overflow_hidden()
 903                    .child({
 904                        let icons = self.ep_store.read(cx).icons(cx);
 905                        h_flex()
 906                            .h_8()
 907                            .px_2()
 908                            .justify_between()
 909                            .border_b_1()
 910                            .border_color(border_color)
 911                            .child(Icon::new(icons.base).size(IconSize::Small))
 912                            .child(
 913                                Label::new("From most recent to oldest")
 914                                    .color(Color::Muted)
 915                                    .size(LabelSize::Small),
 916                            )
 917                    })
 918                    .child(
 919                        div()
 920                            .id("completion_list")
 921                            .p_0p5()
 922                            .h_full()
 923                            .overflow_y_scroll()
 924                            .child(
 925                                List::new()
 926                                    .empty_message(
 927                                        div()
 928                                            .p_2()
 929                                            .child(
 930                                                Label::new(concat!(
 931                                                    "No completions yet. ",
 932                                                    "Use the editor to generate some, ",
 933                                                    "and make sure to rate them!"
 934                                                ))
 935                                                .color(Color::Muted),
 936                                            )
 937                                            .into_any_element(),
 938                                    )
 939                                    .children(self.render_shown_completions(cx)),
 940                            ),
 941                    ),
 942            )
 943            .children(self.render_active_completion(window, cx))
 944            .on_mouse_down_out(cx.listener(|this, _, _, cx| {
 945                if !this.failure_mode_menu_handle.is_deployed() {
 946                    cx.emit(DismissEvent);
 947                }
 948            }))
 949    }
 950}
 951
 952impl EventEmitter<DismissEvent> for RatePredictionsModal {}
 953
 954impl Focusable for RatePredictionsModal {
 955    fn focus_handle(&self, _cx: &App) -> FocusHandle {
 956        self.focus_handle.clone()
 957    }
 958}
 959
 960impl ModalView for RatePredictionsModal {}
 961
 962struct FeedbackCompletionProvider;
 963
 964impl FeedbackCompletionProvider {
 965    const FAILURE_MODES: &'static [(&'static str, &'static str)] = &[
 966        ("@location", "Unexpected location"),
 967        ("@malformed", "Incomplete, cut off, or syntax error"),
 968        (
 969            "@deleted",
 970            "Deleted code that should be kept (use `@reverted` if it undid a recent edit)",
 971        ),
 972        ("@style", "Wrong coding style or conventions"),
 973        ("@repetitive", "Repeated existing code"),
 974        ("@hallucinated", "Referenced non-existent symbols"),
 975        ("@formatting", "Wrong indentation or structure"),
 976        ("@aggressive", "Changed more than expected"),
 977        ("@conservative", "Too cautious, changed too little"),
 978        ("@context", "Ignored or misunderstood context"),
 979        ("@reverted", "Undid recent edits"),
 980        ("@cursor_position", "Cursor placed in unhelpful position"),
 981        ("@whitespace", "Unwanted whitespace or newline changes"),
 982    ];
 983}
 984
 985impl editor::CompletionProvider for FeedbackCompletionProvider {
 986    fn completions(
 987        &self,
 988        buffer: &Entity<Buffer>,
 989        buffer_position: language::Anchor,
 990        _trigger: editor::CompletionContext,
 991        _window: &mut Window,
 992        cx: &mut Context<Editor>,
 993    ) -> gpui::Task<anyhow::Result<Vec<CompletionResponse>>> {
 994        let buffer = buffer.read(cx);
 995        let mut count_back = 0;
 996
 997        for char in buffer.reversed_chars_at(buffer_position) {
 998            if char.is_ascii_alphanumeric() || char == '_' || char == '@' {
 999                count_back += 1;
1000            } else {
1001                break;
1002            }
1003        }
1004
1005        let start_anchor = buffer.anchor_before(
1006            buffer_position
1007                .to_offset(&buffer)
1008                .saturating_sub(count_back),
1009        );
1010
1011        let replace_range = start_anchor..buffer_position;
1012        let snapshot = buffer.text_snapshot();
1013        let query: String = snapshot.text_for_range(replace_range.clone()).collect();
1014
1015        if !query.starts_with('@') {
1016            return gpui::Task::ready(Ok(vec![CompletionResponse {
1017                completions: vec![],
1018                display_options: CompletionDisplayOptions {
1019                    dynamic_width: true,
1020                },
1021                is_incomplete: false,
1022            }]));
1023        }
1024
1025        let query_lower = query.to_lowercase();
1026
1027        let completions: Vec<Completion> = Self::FAILURE_MODES
1028            .iter()
1029            .filter(|(key, _description)| key.starts_with(&query_lower))
1030            .map(|(key, description)| Completion {
1031                replace_range: replace_range.clone(),
1032                new_text: format!("{} {}", key, description),
1033                label: CodeLabel::plain(format!("{}: {}", key, description), None),
1034                documentation: None,
1035                source: CompletionSource::Custom,
1036                icon_path: None,
1037                match_start: None,
1038                snippet_deduplication_key: None,
1039                insert_text_mode: None,
1040                confirm: None,
1041            })
1042            .collect();
1043
1044        gpui::Task::ready(Ok(vec![CompletionResponse {
1045            completions,
1046            display_options: CompletionDisplayOptions {
1047                dynamic_width: true,
1048            },
1049            is_incomplete: false,
1050        }]))
1051    }
1052
1053    fn is_completion_trigger(
1054        &self,
1055        _buffer: &Entity<Buffer>,
1056        _position: language::Anchor,
1057        text: &str,
1058        _trigger_in_words: bool,
1059        _cx: &mut Context<Editor>,
1060    ) -> bool {
1061        text.chars()
1062            .last()
1063            .is_some_and(|c| c.is_ascii_alphanumeric() || c == '_' || c == '@')
1064    }
1065}