1use crate::{CompletionDiffElement, EditPrediction, EditPredictionRating, Zeta};
2use editor::Editor;
3use gpui::{App, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable, actions, prelude::*};
4use language::language_settings;
5use std::time::Duration;
6use ui::{KeyBinding, List, ListItem, ListItemSpacing, Tooltip, prelude::*};
7use workspace::{ModalView, Workspace};
8
9actions!(
10 zeta,
11 [
12 /// Rates the active completion with a thumbs up.
13 ThumbsUpActiveCompletion,
14 /// Rates the active completion with a thumbs down.
15 ThumbsDownActiveCompletion,
16 /// Navigates to the next edit in the completion history.
17 NextEdit,
18 /// Navigates to the previous edit in the completion history.
19 PreviousEdit,
20 /// Focuses on the completions list.
21 FocusCompletions,
22 /// Previews the selected completion.
23 PreviewCompletion,
24 ]
25);
26
27pub struct RateCompletionModal {
28 zeta: Entity<Zeta>,
29 active_completion: Option<ActiveCompletion>,
30 selected_index: usize,
31 focus_handle: FocusHandle,
32 _subscription: gpui::Subscription,
33 current_view: RateCompletionView,
34}
35
36struct ActiveCompletion {
37 completion: EditPrediction,
38 feedback_editor: Entity<Editor>,
39}
40
41#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
42enum RateCompletionView {
43 SuggestedEdits,
44 RawInput,
45}
46
47impl RateCompletionView {
48 pub fn name(&self) -> &'static str {
49 match self {
50 Self::SuggestedEdits => "Suggested Edits",
51 Self::RawInput => "Recorded Events & Input",
52 }
53 }
54}
55
56impl RateCompletionModal {
57 pub fn toggle(workspace: &mut Workspace, window: &mut Window, cx: &mut Context<Workspace>) {
58 if let Some(zeta) = Zeta::global(cx) {
59 workspace.toggle_modal(window, cx, |_window, cx| RateCompletionModal::new(zeta, cx));
60
61 telemetry::event!("Rate Completion Modal Open", source = "Edit Prediction");
62 }
63 }
64
65 pub fn new(zeta: Entity<Zeta>, cx: &mut Context<Self>) -> Self {
66 let subscription = cx.observe(&zeta, |_, _, cx| cx.notify());
67
68 Self {
69 zeta,
70 selected_index: 0,
71 focus_handle: cx.focus_handle(),
72 active_completion: None,
73 _subscription: subscription,
74 current_view: RateCompletionView::SuggestedEdits,
75 }
76 }
77
78 fn dismiss(&mut self, _: &menu::Cancel, _: &mut Window, cx: &mut Context<Self>) {
79 cx.emit(DismissEvent);
80 }
81
82 fn select_next(&mut self, _: &menu::SelectNext, _: &mut Window, cx: &mut Context<Self>) {
83 self.selected_index += 1;
84 self.selected_index = usize::min(
85 self.selected_index,
86 self.zeta.read(cx).shown_completions().count(),
87 );
88 cx.notify();
89 }
90
91 fn select_previous(
92 &mut self,
93 _: &menu::SelectPrevious,
94 _: &mut Window,
95 cx: &mut Context<Self>,
96 ) {
97 self.selected_index = self.selected_index.saturating_sub(1);
98 cx.notify();
99 }
100
101 fn select_next_edit(&mut self, _: &NextEdit, _: &mut Window, cx: &mut Context<Self>) {
102 let next_index = self
103 .zeta
104 .read(cx)
105 .shown_completions()
106 .skip(self.selected_index)
107 .enumerate()
108 .skip(1) // Skip straight to the next item
109 .find(|(_, completion)| !completion.edits.is_empty())
110 .map(|(ix, _)| ix + self.selected_index);
111
112 if let Some(next_index) = next_index {
113 self.selected_index = next_index;
114 cx.notify();
115 }
116 }
117
118 fn select_prev_edit(&mut self, _: &PreviousEdit, _: &mut Window, cx: &mut Context<Self>) {
119 let zeta = self.zeta.read(cx);
120 let completions_len = zeta.shown_completions_len();
121
122 let prev_index = self
123 .zeta
124 .read(cx)
125 .shown_completions()
126 .rev()
127 .skip((completions_len - 1) - self.selected_index)
128 .enumerate()
129 .skip(1) // Skip straight to the previous item
130 .find(|(_, completion)| !completion.edits.is_empty())
131 .map(|(ix, _)| self.selected_index - ix);
132
133 if let Some(prev_index) = prev_index {
134 self.selected_index = prev_index;
135 cx.notify();
136 }
137 cx.notify();
138 }
139
140 fn select_first(&mut self, _: &menu::SelectFirst, _: &mut Window, cx: &mut Context<Self>) {
141 self.selected_index = 0;
142 cx.notify();
143 }
144
145 fn select_last(&mut self, _: &menu::SelectLast, _window: &mut Window, cx: &mut Context<Self>) {
146 self.selected_index = self.zeta.read(cx).shown_completions_len() - 1;
147 cx.notify();
148 }
149
150 pub fn thumbs_up_active(
151 &mut self,
152 _: &ThumbsUpActiveCompletion,
153 window: &mut Window,
154 cx: &mut Context<Self>,
155 ) {
156 self.zeta.update(cx, |zeta, cx| {
157 if let Some(active) = &self.active_completion {
158 zeta.rate_completion(
159 &active.completion,
160 EditPredictionRating::Positive,
161 active.feedback_editor.read(cx).text(cx),
162 cx,
163 );
164 }
165 });
166
167 let current_completion = self
168 .active_completion
169 .as_ref()
170 .map(|completion| completion.completion.clone());
171 self.select_completion(current_completion, false, window, cx);
172 self.select_next_edit(&Default::default(), window, cx);
173 self.confirm(&Default::default(), window, cx);
174
175 cx.notify();
176 }
177
178 pub fn thumbs_down_active(
179 &mut self,
180 _: &ThumbsDownActiveCompletion,
181 window: &mut Window,
182 cx: &mut Context<Self>,
183 ) {
184 if let Some(active) = &self.active_completion {
185 if active.feedback_editor.read(cx).text(cx).is_empty() {
186 return;
187 }
188
189 self.zeta.update(cx, |zeta, cx| {
190 zeta.rate_completion(
191 &active.completion,
192 EditPredictionRating::Negative,
193 active.feedback_editor.read(cx).text(cx),
194 cx,
195 );
196 });
197 }
198
199 let current_completion = self
200 .active_completion
201 .as_ref()
202 .map(|completion| completion.completion.clone());
203 self.select_completion(current_completion, false, window, cx);
204 self.select_next_edit(&Default::default(), window, cx);
205 self.confirm(&Default::default(), window, cx);
206
207 cx.notify();
208 }
209
210 fn focus_completions(
211 &mut self,
212 _: &FocusCompletions,
213 window: &mut Window,
214 cx: &mut Context<Self>,
215 ) {
216 cx.focus_self(window);
217 cx.notify();
218 }
219
220 fn preview_completion(
221 &mut self,
222 _: &PreviewCompletion,
223 window: &mut Window,
224 cx: &mut Context<Self>,
225 ) {
226 let completion = self
227 .zeta
228 .read(cx)
229 .shown_completions()
230 .skip(self.selected_index)
231 .take(1)
232 .next()
233 .cloned();
234
235 self.select_completion(completion, false, window, cx);
236 }
237
238 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
239 let completion = self
240 .zeta
241 .read(cx)
242 .shown_completions()
243 .skip(self.selected_index)
244 .take(1)
245 .next()
246 .cloned();
247
248 self.select_completion(completion, true, window, cx);
249 }
250
251 pub fn select_completion(
252 &mut self,
253 completion: Option<EditPrediction>,
254 focus: bool,
255 window: &mut Window,
256 cx: &mut Context<Self>,
257 ) {
258 // Avoid resetting completion rating if it's already selected.
259 if let Some(completion) = completion.as_ref() {
260 self.selected_index = self
261 .zeta
262 .read(cx)
263 .shown_completions()
264 .enumerate()
265 .find(|(_, completion_b)| completion.id == completion_b.id)
266 .map(|(ix, _)| ix)
267 .unwrap_or(self.selected_index);
268 cx.notify();
269
270 if let Some(prev_completion) = self.active_completion.as_ref()
271 && completion.id == prev_completion.completion.id
272 {
273 if focus {
274 window.focus(&prev_completion.feedback_editor.focus_handle(cx));
275 }
276 return;
277 }
278 }
279
280 self.active_completion = completion.map(|completion| ActiveCompletion {
281 completion,
282 feedback_editor: cx.new(|cx| {
283 let mut editor = Editor::multi_line(window, cx);
284 editor.disable_scrollbars_and_minimap(window, cx);
285 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
286 editor.set_show_line_numbers(false, cx);
287 editor.set_show_git_diff_gutter(false, cx);
288 editor.set_show_code_actions(false, cx);
289 editor.set_show_runnables(false, cx);
290 editor.set_show_breakpoints(false, cx);
291 editor.set_show_wrap_guides(false, cx);
292 editor.set_show_indent_guides(false, cx);
293 editor.set_show_edit_predictions(Some(false), window, cx);
294 editor.set_placeholder_text("Add your feedback…", window, cx);
295 if focus {
296 cx.focus_self(window);
297 }
298 editor
299 }),
300 });
301 cx.notify();
302 }
303
304 fn render_view_nav(&self, cx: &Context<Self>) -> impl IntoElement {
305 h_flex()
306 .h_8()
307 .px_1()
308 .border_b_1()
309 .border_color(cx.theme().colors().border)
310 .bg(cx.theme().colors().elevated_surface_background)
311 .gap_1()
312 .child(
313 Button::new(
314 ElementId::Name("suggested-edits".into()),
315 RateCompletionView::SuggestedEdits.name(),
316 )
317 .label_size(LabelSize::Small)
318 .on_click(cx.listener(move |this, _, _window, cx| {
319 this.current_view = RateCompletionView::SuggestedEdits;
320 cx.notify();
321 }))
322 .toggle_state(self.current_view == RateCompletionView::SuggestedEdits),
323 )
324 .child(
325 Button::new(
326 ElementId::Name("raw-input".into()),
327 RateCompletionView::RawInput.name(),
328 )
329 .label_size(LabelSize::Small)
330 .on_click(cx.listener(move |this, _, _window, cx| {
331 this.current_view = RateCompletionView::RawInput;
332 cx.notify();
333 }))
334 .toggle_state(self.current_view == RateCompletionView::RawInput),
335 )
336 }
337
338 fn render_suggested_edits(&self, cx: &mut Context<Self>) -> Option<gpui::Stateful<Div>> {
339 let active_completion = self.active_completion.as_ref()?;
340 let bg_color = cx.theme().colors().editor_background;
341
342 Some(
343 div()
344 .id("diff")
345 .p_4()
346 .size_full()
347 .bg(bg_color)
348 .overflow_scroll()
349 .whitespace_nowrap()
350 .child(CompletionDiffElement::new(
351 &active_completion.completion,
352 cx,
353 )),
354 )
355 }
356
357 fn render_raw_input(&self, cx: &mut Context<Self>) -> Option<gpui::Stateful<Div>> {
358 Some(
359 v_flex()
360 .size_full()
361 .overflow_hidden()
362 .relative()
363 .child(
364 div()
365 .id("raw-input")
366 .py_4()
367 .px_6()
368 .size_full()
369 .bg(cx.theme().colors().editor_background)
370 .overflow_scroll()
371 .child(if let Some(active_completion) = &self.active_completion {
372 format!(
373 "{}\n{}",
374 active_completion.completion.input_events,
375 active_completion.completion.input_excerpt
376 )
377 } else {
378 "No active completion".to_string()
379 }),
380 )
381 .id("raw-input-view"),
382 )
383 }
384
385 fn render_active_completion(
386 &mut self,
387 window: &mut Window,
388 cx: &mut Context<Self>,
389 ) -> Option<impl IntoElement> {
390 let active_completion = self.active_completion.as_ref()?;
391 let completion_id = active_completion.completion.id;
392 let focus_handle = &self.focus_handle(cx);
393
394 let border_color = cx.theme().colors().border;
395 let bg_color = cx.theme().colors().editor_background;
396
397 let rated = self.zeta.read(cx).is_completion_rated(completion_id);
398 let feedback_empty = active_completion
399 .feedback_editor
400 .read(cx)
401 .text(cx)
402 .is_empty();
403
404 let label_container = h_flex().pl_1().gap_1p5();
405
406 Some(
407 v_flex()
408 .size_full()
409 .overflow_hidden()
410 .relative()
411 .child(
412 v_flex()
413 .size_full()
414 .overflow_hidden()
415 .relative()
416 .child(self.render_view_nav(cx))
417 .when_some(match self.current_view {
418 RateCompletionView::SuggestedEdits => self.render_suggested_edits(cx),
419 RateCompletionView::RawInput => self.render_raw_input(cx),
420 }, |this, element| this.child(element))
421 )
422 .when(!rated, |this| {
423 this.child(
424 h_flex()
425 .p_2()
426 .gap_2()
427 .border_y_1()
428 .border_color(border_color)
429 .child(
430 Icon::new(IconName::Info)
431 .size(IconSize::XSmall)
432 .color(Color::Muted)
433 )
434 .child(
435 div()
436 .w_full()
437 .pr_2()
438 .flex_wrap()
439 .child(
440 Label::new("Explain why this completion is good or bad. If it's negative, describe what you expected instead.")
441 .size(LabelSize::Small)
442 .color(Color::Muted)
443 )
444 )
445 )
446 })
447 .when(!rated, |this| {
448 this.child(
449 div()
450 .h_40()
451 .pt_1()
452 .bg(bg_color)
453 .child(active_completion.feedback_editor.clone())
454 )
455 })
456 .child(
457 h_flex()
458 .p_1()
459 .h_8()
460 .max_h_8()
461 .border_t_1()
462 .border_color(border_color)
463 .max_w_full()
464 .justify_between()
465 .children(if rated {
466 Some(
467 label_container
468 .child(
469 Icon::new(IconName::Check)
470 .size(IconSize::Small)
471 .color(Color::Success),
472 )
473 .child(Label::new("Rated completion.").color(Color::Muted)),
474 )
475 } else if active_completion.completion.edits.is_empty() {
476 Some(
477 label_container
478 .child(
479 Icon::new(IconName::Warning)
480 .size(IconSize::Small)
481 .color(Color::Warning),
482 )
483 .child(Label::new("No edits produced.").color(Color::Muted)),
484 )
485 } else {
486 Some(label_container)
487 })
488 .child(
489 h_flex()
490 .gap_1()
491 .child(
492 Button::new("bad", "Bad Completion")
493 .icon(IconName::ThumbsDown)
494 .icon_size(IconSize::Small)
495 .icon_position(IconPosition::Start)
496 .disabled(rated || feedback_empty)
497 .when(feedback_empty, |this| {
498 this.tooltip(Tooltip::text("Explain what's bad about it before reporting it"))
499 })
500 .key_binding(KeyBinding::for_action_in(
501 &ThumbsDownActiveCompletion,
502 focus_handle,
503 window,
504 cx
505 ))
506 .on_click(cx.listener(move |this, _, window, cx| {
507 if this.active_completion.is_some() {
508 this.thumbs_down_active(
509 &ThumbsDownActiveCompletion,
510 window, cx,
511 );
512 }
513 })),
514 )
515 .child(
516 Button::new("good", "Good Completion")
517 .icon(IconName::ThumbsUp)
518 .icon_size(IconSize::Small)
519 .icon_position(IconPosition::Start)
520 .disabled(rated)
521 .key_binding(KeyBinding::for_action_in(
522 &ThumbsUpActiveCompletion,
523 focus_handle,
524 window,
525 cx
526 ))
527 .on_click(cx.listener(move |this, _, window, cx| {
528 if this.active_completion.is_some() {
529 this.thumbs_up_active(&ThumbsUpActiveCompletion, window, cx);
530 }
531 })),
532 ),
533 ),
534 ),
535 )
536 }
537}
538
539impl Render for RateCompletionModal {
540 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
541 let border_color = cx.theme().colors().border;
542
543 h_flex()
544 .key_context("RateCompletionModal")
545 .track_focus(&self.focus_handle)
546 .on_action(cx.listener(Self::dismiss))
547 .on_action(cx.listener(Self::confirm))
548 .on_action(cx.listener(Self::select_previous))
549 .on_action(cx.listener(Self::select_prev_edit))
550 .on_action(cx.listener(Self::select_next))
551 .on_action(cx.listener(Self::select_next_edit))
552 .on_action(cx.listener(Self::select_first))
553 .on_action(cx.listener(Self::select_last))
554 .on_action(cx.listener(Self::thumbs_up_active))
555 .on_action(cx.listener(Self::thumbs_down_active))
556 .on_action(cx.listener(Self::focus_completions))
557 .on_action(cx.listener(Self::preview_completion))
558 .bg(cx.theme().colors().elevated_surface_background)
559 .border_1()
560 .border_color(border_color)
561 .w(window.viewport_size().width - px(320.))
562 .h(window.viewport_size().height - px(300.))
563 .rounded_lg()
564 .shadow_lg()
565 .child(
566 v_flex()
567 .w_72()
568 .h_full()
569 .border_r_1()
570 .border_color(border_color)
571 .flex_shrink_0()
572 .overflow_hidden()
573 .child(
574 h_flex()
575 .h_8()
576 .px_2()
577 .justify_between()
578 .border_b_1()
579 .border_color(border_color)
580 .child(
581 Icon::new(IconName::ZedPredict)
582 .size(IconSize::Small)
583 )
584 .child(
585 Label::new("From most recent to oldest")
586 .color(Color::Muted)
587 .size(LabelSize::Small),
588 )
589 )
590 .child(
591 div()
592 .id("completion_list")
593 .p_0p5()
594 .h_full()
595 .overflow_y_scroll()
596 .child(
597 List::new()
598 .empty_message(
599 div()
600 .p_2()
601 .child(
602 Label::new("No completions yet. Use the editor to generate some, and make sure to rate them!")
603 .color(Color::Muted),
604 )
605 .into_any_element(),
606 )
607 .children(self.zeta.read(cx).shown_completions().cloned().enumerate().map(
608 |(index, completion)| {
609 let selected =
610 self.active_completion.as_ref().is_some_and(|selected| {
611 selected.completion.id == completion.id
612 });
613 let rated =
614 self.zeta.read(cx).is_completion_rated(completion.id);
615
616 let (icon_name, icon_color, tooltip_text) = match (rated, completion.edits.is_empty()) {
617 (true, _) => (IconName::Check, Color::Success, "Rated Completion"),
618 (false, true) => (IconName::File, Color::Muted, "No Edits Produced"),
619 (false, false) => (IconName::FileDiff, Color::Accent, "Edits Available"),
620 };
621
622 let file_name = completion.path.file_name().map(|f| f.to_string_lossy().into_owned()).unwrap_or("untitled".to_string());
623 let file_path = completion.path.parent().map(|p| p.to_string_lossy().into_owned());
624
625 ListItem::new(completion.id)
626 .inset(true)
627 .spacing(ListItemSpacing::Sparse)
628 .focused(index == self.selected_index)
629 .toggle_state(selected)
630 .child(
631 h_flex()
632 .id("completion-content")
633 .gap_3()
634 .child(
635 Icon::new(icon_name)
636 .color(icon_color)
637 .size(IconSize::Small)
638 )
639 .child(
640 v_flex()
641 .child(
642 h_flex().gap_1()
643 .child(Label::new(file_name).size(LabelSize::Small))
644 .when_some(file_path, |this, p| this.child(Label::new(p).size(LabelSize::Small).color(Color::Muted)))
645 )
646 .child(Label::new(format!("{} ago, {:.2?}", format_time_ago(completion.response_received_at.elapsed()), completion.latency()))
647 .color(Color::Muted)
648 .size(LabelSize::XSmall)
649 )
650 )
651 )
652 .tooltip(Tooltip::text(tooltip_text))
653 .on_click(cx.listener(move |this, _, window, cx| {
654 this.select_completion(Some(completion.clone()), true, window, cx);
655 }))
656 },
657 )),
658 )
659 ),
660 )
661 .children(self.render_active_completion(window, cx))
662 .on_mouse_down_out(cx.listener(|_, _, _, cx| cx.emit(DismissEvent)))
663 }
664}
665
666impl EventEmitter<DismissEvent> for RateCompletionModal {}
667
668impl Focusable for RateCompletionModal {
669 fn focus_handle(&self, _cx: &App) -> FocusHandle {
670 self.focus_handle.clone()
671 }
672}
673
674impl ModalView for RateCompletionModal {}
675
676fn format_time_ago(elapsed: Duration) -> String {
677 let seconds = elapsed.as_secs();
678 if seconds < 120 {
679 "1 minute".to_string()
680 } else if seconds < 3600 {
681 format!("{} minutes", seconds / 60)
682 } else if seconds < 7200 {
683 "1 hour".to_string()
684 } else if seconds < 86400 {
685 format!("{} hours", seconds / 3600)
686 } else if seconds < 172800 {
687 "1 day".to_string()
688 } else {
689 format!("{} days", seconds / 86400)
690 }
691}