1use crate::{InlineCompletion, InlineCompletionRating, Zeta};
2use editor::Editor;
3use gpui::{
4 actions, prelude::*, AppContext, DismissEvent, EventEmitter, FocusHandle, FocusableView,
5 HighlightStyle, Model, StyledText, TextStyle, View, ViewContext,
6};
7use language::{language_settings, OffsetRangeExt};
8use settings::Settings;
9use std::time::Duration;
10use theme::ThemeSettings;
11use ui::{prelude::*, KeyBinding, List, ListItem, ListItemSpacing, Tooltip};
12use workspace::{ModalView, Workspace};
13
14actions!(
15 zeta,
16 [
17 RateCompletions,
18 ThumbsUpActiveCompletion,
19 ThumbsDownActiveCompletion,
20 NextEdit,
21 PreviousEdit,
22 FocusCompletions,
23 PreviewCompletion,
24 ]
25);
26
27pub fn init(cx: &mut AppContext) {
28 cx.observe_new_views(move |workspace: &mut Workspace, _cx| {
29 workspace.register_action(|workspace, _: &RateCompletions, cx| {
30 RateCompletionModal::toggle(workspace, cx);
31 });
32 })
33 .detach();
34}
35
36pub struct RateCompletionModal {
37 zeta: Model<Zeta>,
38 active_completion: Option<ActiveCompletion>,
39 selected_index: usize,
40 focus_handle: FocusHandle,
41 _subscription: gpui::Subscription,
42}
43
44struct ActiveCompletion {
45 completion: InlineCompletion,
46 feedback_editor: View<Editor>,
47}
48
49impl RateCompletionModal {
50 pub fn toggle(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) {
51 if let Some(zeta) = Zeta::global(cx) {
52 workspace.toggle_modal(cx, |cx| RateCompletionModal::new(zeta, cx));
53 }
54 }
55
56 pub fn new(zeta: Model<Zeta>, cx: &mut ViewContext<Self>) -> Self {
57 let subscription = cx.observe(&zeta, |_, _, cx| cx.notify());
58
59 Self {
60 zeta,
61 selected_index: 0,
62 focus_handle: cx.focus_handle(),
63 active_completion: None,
64 _subscription: subscription,
65 }
66 }
67
68 fn dismiss(&mut self, _: &menu::Cancel, cx: &mut ViewContext<Self>) {
69 cx.emit(DismissEvent);
70 }
71
72 fn select_next(&mut self, _: &menu::SelectNext, cx: &mut ViewContext<Self>) {
73 self.selected_index += 1;
74 self.selected_index = usize::min(
75 self.selected_index,
76 self.zeta.read(cx).recent_completions().count(),
77 );
78 cx.notify();
79 }
80
81 fn select_prev(&mut self, _: &menu::SelectPrev, cx: &mut ViewContext<Self>) {
82 self.selected_index = self.selected_index.saturating_sub(1);
83 cx.notify();
84 }
85
86 fn select_next_edit(&mut self, _: &NextEdit, cx: &mut ViewContext<Self>) {
87 let next_index = self
88 .zeta
89 .read(cx)
90 .recent_completions()
91 .skip(self.selected_index)
92 .enumerate()
93 .skip(1) // Skip straight to the next item
94 .find(|(_, completion)| !completion.edits.is_empty())
95 .map(|(ix, _)| ix + self.selected_index);
96
97 if let Some(next_index) = next_index {
98 self.selected_index = next_index;
99 cx.notify();
100 }
101 }
102
103 fn select_prev_edit(&mut self, _: &PreviousEdit, cx: &mut ViewContext<Self>) {
104 let zeta = self.zeta.read(cx);
105 let completions_len = zeta.recent_completions_len();
106
107 let prev_index = self
108 .zeta
109 .read(cx)
110 .recent_completions()
111 .rev()
112 .skip((completions_len - 1) - self.selected_index)
113 .enumerate()
114 .skip(1) // Skip straight to the previous item
115 .find(|(_, completion)| !completion.edits.is_empty())
116 .map(|(ix, _)| self.selected_index - ix);
117
118 if let Some(prev_index) = prev_index {
119 self.selected_index = prev_index;
120 cx.notify();
121 }
122 cx.notify();
123 }
124
125 fn select_first(&mut self, _: &menu::SelectFirst, cx: &mut ViewContext<Self>) {
126 self.selected_index = 0;
127 cx.notify();
128 }
129
130 fn select_last(&mut self, _: &menu::SelectLast, cx: &mut ViewContext<Self>) {
131 self.selected_index = self.zeta.read(cx).recent_completions_len() - 1;
132 cx.notify();
133 }
134
135 fn thumbs_up_active(&mut self, _: &ThumbsUpActiveCompletion, cx: &mut ViewContext<Self>) {
136 self.zeta.update(cx, |zeta, cx| {
137 if let Some(active) = &self.active_completion {
138 zeta.rate_completion(
139 &active.completion,
140 InlineCompletionRating::Positive,
141 active.feedback_editor.read(cx).text(cx),
142 cx,
143 );
144 }
145 });
146
147 let current_completion = self
148 .active_completion
149 .as_ref()
150 .map(|completion| completion.completion.clone());
151 self.select_completion(current_completion, false, cx);
152 self.select_next_edit(&Default::default(), cx);
153 self.confirm(&Default::default(), cx);
154
155 cx.notify();
156 }
157
158 fn thumbs_down_active(&mut self, _: &ThumbsDownActiveCompletion, cx: &mut ViewContext<Self>) {
159 if let Some(active) = &self.active_completion {
160 if active.feedback_editor.read(cx).text(cx).is_empty() {
161 return;
162 }
163
164 self.zeta.update(cx, |zeta, cx| {
165 zeta.rate_completion(
166 &active.completion,
167 InlineCompletionRating::Negative,
168 active.feedback_editor.read(cx).text(cx),
169 cx,
170 );
171 });
172 }
173
174 let current_completion = self
175 .active_completion
176 .as_ref()
177 .map(|completion| completion.completion.clone());
178 self.select_completion(current_completion, false, cx);
179 self.select_next_edit(&Default::default(), cx);
180 self.confirm(&Default::default(), cx);
181
182 cx.notify();
183 }
184
185 fn focus_completions(&mut self, _: &FocusCompletions, cx: &mut ViewContext<Self>) {
186 cx.focus_self();
187 cx.notify();
188 }
189
190 fn preview_completion(&mut self, _: &PreviewCompletion, cx: &mut ViewContext<Self>) {
191 let completion = self
192 .zeta
193 .read(cx)
194 .recent_completions()
195 .skip(self.selected_index)
196 .take(1)
197 .next()
198 .cloned();
199
200 self.select_completion(completion, false, cx);
201 }
202
203 fn confirm(&mut self, _: &menu::Confirm, cx: &mut ViewContext<Self>) {
204 let completion = self
205 .zeta
206 .read(cx)
207 .recent_completions()
208 .skip(self.selected_index)
209 .take(1)
210 .next()
211 .cloned();
212
213 self.select_completion(completion, true, cx);
214 }
215
216 pub fn select_completion(
217 &mut self,
218 completion: Option<InlineCompletion>,
219 focus: bool,
220 cx: &mut ViewContext<Self>,
221 ) {
222 // Avoid resetting completion rating if it's already selected.
223 if let Some(completion) = completion.as_ref() {
224 self.selected_index = self
225 .zeta
226 .read(cx)
227 .recent_completions()
228 .enumerate()
229 .find(|(_, completion_b)| completion.id == completion_b.id)
230 .map(|(ix, _)| ix)
231 .unwrap_or(self.selected_index);
232 cx.notify();
233
234 if let Some(prev_completion) = self.active_completion.as_ref() {
235 if completion.id == prev_completion.completion.id {
236 if focus {
237 cx.focus_view(&prev_completion.feedback_editor);
238 }
239 return;
240 }
241 }
242 }
243
244 self.active_completion = completion.map(|completion| ActiveCompletion {
245 completion,
246 feedback_editor: cx.new_view(|cx| {
247 let mut editor = Editor::multi_line(cx);
248 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
249 editor.set_show_line_numbers(false, cx);
250 editor.set_show_scrollbars(false, cx);
251 editor.set_show_git_diff_gutter(false, cx);
252 editor.set_show_code_actions(false, cx);
253 editor.set_show_runnables(false, cx);
254 editor.set_show_wrap_guides(false, cx);
255 editor.set_show_indent_guides(false, cx);
256 editor.set_show_inline_completions(Some(false), cx);
257 editor.set_placeholder_text("Add your feedback…", cx);
258 if focus {
259 cx.focus_self();
260 }
261 editor
262 }),
263 });
264 cx.notify();
265 }
266
267 fn render_active_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<impl IntoElement> {
268 let active_completion = self.active_completion.as_ref()?;
269 let completion_id = active_completion.completion.id;
270 let focus_handle = &self.focus_handle(cx);
271
272 let mut diff = active_completion
273 .completion
274 .snapshot
275 .text_for_range(active_completion.completion.excerpt_range.clone())
276 .collect::<String>();
277
278 let mut delta = 0;
279 let mut diff_highlights = Vec::new();
280 for (old_range, new_text) in active_completion.completion.edits.iter() {
281 let old_range = old_range.to_offset(&active_completion.completion.snapshot);
282 let old_start_in_text =
283 old_range.start - active_completion.completion.excerpt_range.start + delta;
284 let old_end_in_text =
285 old_range.end - active_completion.completion.excerpt_range.start + delta;
286 if old_start_in_text < old_end_in_text {
287 diff_highlights.push((
288 old_start_in_text..old_end_in_text,
289 HighlightStyle {
290 background_color: Some(cx.theme().status().deleted_background),
291 strikethrough: Some(gpui::StrikethroughStyle {
292 thickness: px(1.),
293 color: Some(cx.theme().colors().text_muted),
294 }),
295 ..Default::default()
296 },
297 ));
298 }
299
300 if !new_text.is_empty() {
301 diff.insert_str(old_end_in_text, new_text);
302 diff_highlights.push((
303 old_end_in_text..old_end_in_text + new_text.len(),
304 HighlightStyle {
305 background_color: Some(cx.theme().status().created_background),
306 ..Default::default()
307 },
308 ));
309 delta += new_text.len();
310 }
311 }
312
313 let settings = ThemeSettings::get_global(cx).clone();
314 let text_style = TextStyle {
315 color: cx.theme().colors().editor_foreground,
316 font_size: settings.buffer_font_size(cx).into(),
317 font_family: settings.buffer_font.family,
318 font_features: settings.buffer_font.features,
319 font_fallbacks: settings.buffer_font.fallbacks,
320 line_height: relative(settings.buffer_line_height.value()),
321 font_weight: settings.buffer_font.weight,
322 font_style: settings.buffer_font.style,
323 ..Default::default()
324 };
325 let border_color = cx.theme().colors().border;
326 let bg_color = cx.theme().colors().editor_background;
327
328 let rated = self.zeta.read(cx).is_completion_rated(completion_id);
329 let was_shown = self.zeta.read(cx).was_completion_shown(completion_id);
330 let feedback_empty = active_completion
331 .feedback_editor
332 .read(cx)
333 .text(cx)
334 .is_empty();
335
336 let label_container = || h_flex().pl_1().gap_1p5();
337
338 Some(
339 v_flex()
340 .size_full()
341 .overflow_hidden()
342 .child(
343 div()
344 .id("diff")
345 .py_4()
346 .px_6()
347 .size_full()
348 .bg(bg_color)
349 .overflow_scroll()
350 .child(StyledText::new(diff).with_highlights(&text_style, diff_highlights)),
351 )
352 .when_some((!rated).then(|| ()), |this, _| {
353 this.child(
354 h_flex()
355 .p_2()
356 .gap_2()
357 .border_y_1()
358 .border_color(border_color)
359
360 .child(
361 Icon::new(IconName::Info)
362 .size(IconSize::XSmall)
363 .color(Color::Muted)
364 )
365 .child(
366 div()
367 .w_full()
368 .pr_2()
369 .flex_wrap()
370 .child(
371 Label::new("Ensure you explain why this completion is negative or positive. In case it's negative, report what you expected instead.")
372 .size(LabelSize::Small)
373 .color(Color::Muted)
374 )
375 )
376 )
377 })
378 .when_some((!rated).then(|| ()), |this, _| {
379 this.child(
380 div()
381 .h_40()
382 .pt_1()
383 .bg(bg_color)
384 .child(active_completion.feedback_editor.clone())
385 )
386 })
387 .child(
388 h_flex()
389 .p_1()
390 .h_8()
391 .max_h_8()
392 .border_t_1()
393 .border_color(border_color)
394 .max_w_full()
395 .justify_between()
396 .children(if rated {
397 Some(
398 label_container()
399 .child(
400 Icon::new(IconName::Check)
401 .size(IconSize::Small)
402 .color(Color::Success),
403 )
404 .child(Label::new("Rated completion.").color(Color::Muted)),
405 )
406 } else if active_completion.completion.edits.is_empty() {
407 Some(
408 label_container()
409 .child(
410 Icon::new(IconName::Warning)
411 .size(IconSize::Small)
412 .color(Color::Warning),
413 )
414 .child(Label::new("No edits produced.").color(Color::Muted)),
415 )
416 } else if !was_shown {
417 Some(
418 label_container()
419 .child(
420 Icon::new(IconName::Warning)
421 .size(IconSize::Small)
422 .color(Color::Warning),
423 )
424 .child(Label::new("Completion wasn't shown because another valid one was already on screen.")),
425 )
426 } else {
427 Some(label_container())
428 })
429 .child(
430 h_flex()
431 .gap_1()
432 .child(
433 Button::new("bad", "Bad Completion")
434 .icon(IconName::ThumbsDown)
435 .icon_size(IconSize::Small)
436 .icon_position(IconPosition::Start)
437 .disabled(rated || feedback_empty)
438 .when(feedback_empty, |this| {
439 this.tooltip(|cx| {
440 Tooltip::text("Explain what's bad about it before reporting it", cx)
441 })
442 })
443 .key_binding(KeyBinding::for_action_in(
444 &ThumbsDownActiveCompletion,
445 focus_handle,
446 cx,
447 ))
448 .on_click(cx.listener(move |this, _, cx| {
449 this.thumbs_down_active(
450 &ThumbsDownActiveCompletion,
451 cx,
452 );
453 })),
454 )
455 .child(
456 Button::new("good", "Good Completion")
457 .icon(IconName::ThumbsUp)
458 .icon_size(IconSize::Small)
459 .icon_position(IconPosition::Start)
460 .disabled(rated)
461 .key_binding(KeyBinding::for_action_in(
462 &ThumbsUpActiveCompletion,
463 focus_handle,
464 cx,
465 ))
466 .on_click(cx.listener(move |this, _, cx| {
467 this.thumbs_up_active(&ThumbsUpActiveCompletion, cx);
468 })),
469 ),
470 ),
471 ),
472 )
473 }
474}
475
476impl Render for RateCompletionModal {
477 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
478 let border_color = cx.theme().colors().border;
479
480 h_flex()
481 .key_context("RateCompletionModal")
482 .track_focus(&self.focus_handle)
483 .on_action(cx.listener(Self::dismiss))
484 .on_action(cx.listener(Self::confirm))
485 .on_action(cx.listener(Self::select_prev))
486 .on_action(cx.listener(Self::select_prev_edit))
487 .on_action(cx.listener(Self::select_next))
488 .on_action(cx.listener(Self::select_next_edit))
489 .on_action(cx.listener(Self::select_first))
490 .on_action(cx.listener(Self::select_last))
491 .on_action(cx.listener(Self::thumbs_up_active))
492 .on_action(cx.listener(Self::thumbs_down_active))
493 .on_action(cx.listener(Self::focus_completions))
494 .on_action(cx.listener(Self::preview_completion))
495 .bg(cx.theme().colors().elevated_surface_background)
496 .border_1()
497 .border_color(border_color)
498 .w(cx.viewport_size().width - px(320.))
499 .h(cx.viewport_size().height - px(300.))
500 .rounded_lg()
501 .shadow_lg()
502 .child(
503 v_flex()
504 .border_r_1()
505 .border_color(border_color)
506 .w_72()
507 .h_full()
508 .flex_shrink_0()
509 .overflow_hidden()
510 .child(
511 h_flex()
512 .px_2()
513 .py_1()
514 .justify_between()
515 .border_b_1()
516 .border_color(border_color)
517 .child(
518 Icon::new(IconName::ZedPredict)
519 .size(IconSize::Small)
520 )
521 .child(
522 Label::new("From most recent to oldest")
523 .color(Color::Muted)
524 .size(LabelSize::Small),
525 )
526 )
527 .child(
528 div()
529 .id("completion_list")
530 .p_0p5()
531 .h_full()
532 .overflow_y_scroll()
533 .child(
534 List::new()
535 .empty_message(
536 div()
537 .p_2()
538 .child(
539 Label::new("No completions yet. Use the editor to generate some and rate them!")
540 .color(Color::Muted),
541 )
542 .into_any_element(),
543 )
544 .children(self.zeta.read(cx).recent_completions().cloned().enumerate().map(
545 |(index, completion)| {
546 let selected =
547 self.active_completion.as_ref().map_or(false, |selected| {
548 selected.completion.id == completion.id
549 });
550 let rated =
551 self.zeta.read(cx).is_completion_rated(completion.id);
552
553 let (icon_name, icon_color, tooltip_text) = match (rated, completion.edits.is_empty()) {
554 (true, _) => (IconName::Check, Color::Success, "Rated Completion"),
555 (false, true) => (IconName::File, Color::Muted, "No Edits Produced"),
556 (false, false) => (IconName::FileDiff, Color::Accent, "Edits Available"),
557 };
558
559 ListItem::new(completion.id)
560 .inset(true)
561 .spacing(ListItemSpacing::Sparse)
562 .focused(index == self.selected_index)
563 .toggle_state(selected)
564 .child(
565 h_flex()
566 .id("completion-content")
567 .gap_2p5()
568 .child(
569 Icon::new(icon_name)
570 .color(icon_color)
571 .size(IconSize::Small)
572 )
573 .child(
574 v_flex()
575 .child(Label::new(completion.path.to_string_lossy().to_string()).size(LabelSize::Small))
576 .child(Label::new(format!("{} ago, {:.2?}", format_time_ago(completion.response_received_at.elapsed()), completion.latency()))
577 .color(Color::Muted)
578 .size(LabelSize::XSmall)
579 )
580 )
581 )
582 .tooltip(move |cx| {
583 Tooltip::text(tooltip_text, cx)
584 })
585 .on_click(cx.listener(move |this, _, cx| {
586 this.select_completion(Some(completion.clone()), true, cx);
587 }))
588 },
589 )),
590 )
591 ),
592 )
593 .children(self.render_active_completion(cx))
594 .on_mouse_down_out(cx.listener(|_, _, cx| cx.emit(DismissEvent)))
595 }
596}
597
598impl EventEmitter<DismissEvent> for RateCompletionModal {}
599
600impl FocusableView for RateCompletionModal {
601 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
602 self.focus_handle.clone()
603 }
604}
605
606impl ModalView for RateCompletionModal {}
607
608fn format_time_ago(elapsed: Duration) -> String {
609 let seconds = elapsed.as_secs();
610 if seconds < 120 {
611 "1 minute".to_string()
612 } else if seconds < 3600 {
613 format!("{} minutes", seconds / 60)
614 } else if seconds < 7200 {
615 "1 hour".to_string()
616 } else if seconds < 86400 {
617 format!("{} hours", seconds / 3600)
618 } else if seconds < 172800 {
619 "1 day".to_string()
620 } else {
621 format!("{} days", seconds / 86400)
622 }
623}