Reorganize edit prediction code and remove old experiments (#44187)
Release Notes: - N/A --------- Co-authored-by: Agus Zubiaga <agus@zed.dev> Co-authored-by: Ben Kunkle <ben@zed.dev>
This commit is contained in:
co-authored by
Agus Zubiaga
Ben Kunkle
parent
76167109db
commit
42583c1141
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,389 @@
|
||||
use std::{
|
||||
any::TypeId,
|
||||
collections::VecDeque,
|
||||
ops::Add,
|
||||
sync::Arc,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use anyhow::Result;
|
||||
use client::{Client, UserStore};
|
||||
use editor::{Editor, PathKey};
|
||||
use futures::StreamExt as _;
|
||||
use gpui::{
|
||||
Animation, AnimationExt, App, AppContext as _, Context, Entity, EventEmitter, FocusHandle,
|
||||
Focusable, InteractiveElement as _, IntoElement as _, ParentElement as _, SharedString,
|
||||
Styled as _, Task, TextAlign, Window, actions, div, pulsating_between,
|
||||
};
|
||||
use multi_buffer::MultiBuffer;
|
||||
use project::Project;
|
||||
use text::OffsetRangeExt;
|
||||
use ui::{
|
||||
ButtonCommon, Clickable, Disableable, FluentBuilder as _, IconButton, IconName,
|
||||
StyledTypography as _, h_flex, v_flex,
|
||||
};
|
||||
|
||||
use edit_prediction::{
|
||||
ContextRetrievalFinishedDebugEvent, ContextRetrievalStartedDebugEvent, DebugEvent,
|
||||
EditPredictionStore,
|
||||
};
|
||||
use workspace::Item;
|
||||
|
||||
pub struct EditPredictionContextView {
|
||||
empty_focus_handle: FocusHandle,
|
||||
project: Entity<Project>,
|
||||
store: Entity<EditPredictionStore>,
|
||||
runs: VecDeque<RetrievalRun>,
|
||||
current_ix: usize,
|
||||
_update_task: Task<Result<()>>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct RetrievalRun {
|
||||
editor: Entity<Editor>,
|
||||
started_at: Instant,
|
||||
metadata: Vec<(&'static str, SharedString)>,
|
||||
finished_at: Option<Instant>,
|
||||
}
|
||||
|
||||
actions!(
|
||||
dev,
|
||||
[
|
||||
/// Go to the previous context retrieval run
|
||||
EditPredictionContextGoBack,
|
||||
/// Go to the next context retrieval run
|
||||
EditPredictionContextGoForward
|
||||
]
|
||||
);
|
||||
|
||||
impl EditPredictionContextView {
|
||||
pub fn new(
|
||||
project: Entity<Project>,
|
||||
client: &Arc<Client>,
|
||||
user_store: &Entity<UserStore>,
|
||||
window: &mut gpui::Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Self {
|
||||
let store = EditPredictionStore::global(client, user_store, cx);
|
||||
|
||||
let mut debug_rx = store.update(cx, |store, _| store.debug_info());
|
||||
let _update_task = cx.spawn_in(window, async move |this, cx| {
|
||||
while let Some(event) = debug_rx.next().await {
|
||||
this.update_in(cx, |this, window, cx| {
|
||||
this.handle_store_event(event, window, cx)
|
||||
})?;
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
|
||||
Self {
|
||||
empty_focus_handle: cx.focus_handle(),
|
||||
project,
|
||||
runs: VecDeque::new(),
|
||||
current_ix: 0,
|
||||
store,
|
||||
_update_task,
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_store_event(
|
||||
&mut self,
|
||||
event: DebugEvent,
|
||||
window: &mut gpui::Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
match event {
|
||||
DebugEvent::ContextRetrievalStarted(info) => {
|
||||
if info.project_entity_id == self.project.entity_id() {
|
||||
self.handle_context_retrieval_started(info, window, cx);
|
||||
}
|
||||
}
|
||||
DebugEvent::ContextRetrievalFinished(info) => {
|
||||
if info.project_entity_id == self.project.entity_id() {
|
||||
self.handle_context_retrieval_finished(info, window, cx);
|
||||
}
|
||||
}
|
||||
DebugEvent::EditPredictionRequested(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_context_retrieval_started(
|
||||
&mut self,
|
||||
info: ContextRetrievalStartedDebugEvent,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
if self
|
||||
.runs
|
||||
.back()
|
||||
.is_some_and(|run| run.finished_at.is_none())
|
||||
{
|
||||
self.runs.pop_back();
|
||||
}
|
||||
|
||||
let multibuffer = cx.new(|_| MultiBuffer::new(language::Capability::ReadOnly));
|
||||
let editor = cx
|
||||
.new(|cx| Editor::for_multibuffer(multibuffer, Some(self.project.clone()), window, cx));
|
||||
|
||||
if self.runs.len() == 32 {
|
||||
self.runs.pop_front();
|
||||
}
|
||||
|
||||
self.runs.push_back(RetrievalRun {
|
||||
editor,
|
||||
started_at: info.timestamp,
|
||||
finished_at: None,
|
||||
metadata: Vec::new(),
|
||||
});
|
||||
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
fn handle_context_retrieval_finished(
|
||||
&mut self,
|
||||
info: ContextRetrievalFinishedDebugEvent,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
let Some(run) = self.runs.back_mut() else {
|
||||
return;
|
||||
};
|
||||
|
||||
run.finished_at = Some(info.timestamp);
|
||||
run.metadata = info.metadata;
|
||||
|
||||
let project = self.project.clone();
|
||||
let related_files = self
|
||||
.store
|
||||
.read(cx)
|
||||
.context_for_project(&self.project, cx)
|
||||
.to_vec();
|
||||
|
||||
let editor = run.editor.clone();
|
||||
let multibuffer = run.editor.read(cx).buffer().clone();
|
||||
|
||||
if self.current_ix + 2 == self.runs.len() {
|
||||
self.current_ix += 1;
|
||||
}
|
||||
|
||||
cx.spawn_in(window, async move |this, cx| {
|
||||
let mut paths = Vec::new();
|
||||
for related_file in related_files {
|
||||
let (buffer, point_ranges): (_, Vec<_>) =
|
||||
if let Some(buffer) = related_file.buffer.upgrade() {
|
||||
let snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot())?;
|
||||
|
||||
(
|
||||
buffer,
|
||||
related_file
|
||||
.excerpts
|
||||
.iter()
|
||||
.map(|excerpt| excerpt.anchor_range.to_point(&snapshot))
|
||||
.collect(),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
project
|
||||
.update(cx, |project, cx| {
|
||||
project.open_buffer(related_file.path.clone(), cx)
|
||||
})?
|
||||
.await?,
|
||||
related_file
|
||||
.excerpts
|
||||
.iter()
|
||||
.map(|excerpt| excerpt.point_range.clone())
|
||||
.collect(),
|
||||
)
|
||||
};
|
||||
cx.update(|_, cx| {
|
||||
let path = PathKey::for_buffer(&buffer, cx);
|
||||
paths.push((path, buffer, point_ranges));
|
||||
})?;
|
||||
}
|
||||
|
||||
multibuffer.update(cx, |multibuffer, cx| {
|
||||
multibuffer.clear(cx);
|
||||
|
||||
for (path, buffer, ranges) in paths {
|
||||
multibuffer.set_excerpts_for_path(path, buffer, ranges, 0, cx);
|
||||
}
|
||||
})?;
|
||||
|
||||
editor.update_in(cx, |editor, window, cx| {
|
||||
editor.move_to_beginning(&Default::default(), window, cx);
|
||||
})?;
|
||||
|
||||
this.update(cx, |_, cx| cx.notify())
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
fn handle_go_back(
|
||||
&mut self,
|
||||
_: &EditPredictionContextGoBack,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
self.current_ix = self.current_ix.saturating_sub(1);
|
||||
cx.focus_self(window);
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
fn handle_go_forward(
|
||||
&mut self,
|
||||
_: &EditPredictionContextGoForward,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
self.current_ix = self
|
||||
.current_ix
|
||||
.add(1)
|
||||
.min(self.runs.len().saturating_sub(1));
|
||||
cx.focus_self(window);
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
fn render_informational_footer(
|
||||
&self,
|
||||
cx: &mut Context<'_, EditPredictionContextView>,
|
||||
) -> ui::Div {
|
||||
let run = &self.runs[self.current_ix];
|
||||
let new_run_started = self
|
||||
.runs
|
||||
.back()
|
||||
.map_or(false, |latest_run| latest_run.finished_at.is_none());
|
||||
|
||||
h_flex()
|
||||
.p_2()
|
||||
.w_full()
|
||||
.font_buffer(cx)
|
||||
.text_xs()
|
||||
.border_t_1()
|
||||
.gap_2()
|
||||
.child(v_flex().h_full().flex_1().child({
|
||||
let t0 = run.started_at;
|
||||
let mut table = ui::Table::<2>::new().width(ui::px(300.)).no_ui_font();
|
||||
for (key, value) in &run.metadata {
|
||||
table = table.row([key.into_any_element(), value.clone().into_any_element()])
|
||||
}
|
||||
table = table.row([
|
||||
"Total Time".into_any_element(),
|
||||
format!("{} ms", (run.finished_at.unwrap_or(t0) - t0).as_millis())
|
||||
.into_any_element(),
|
||||
]);
|
||||
table
|
||||
}))
|
||||
.child(
|
||||
v_flex().h_full().text_align(TextAlign::Right).child(
|
||||
h_flex()
|
||||
.justify_end()
|
||||
.child(
|
||||
IconButton::new("go-back", IconName::ChevronLeft)
|
||||
.disabled(self.current_ix == 0 || self.runs.len() < 2)
|
||||
.tooltip(ui::Tooltip::for_action_title(
|
||||
"Go to previous run",
|
||||
&EditPredictionContextGoBack,
|
||||
))
|
||||
.on_click(cx.listener(|this, _, window, cx| {
|
||||
this.handle_go_back(&EditPredictionContextGoBack, window, cx);
|
||||
})),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.child(format!("{}/{}", self.current_ix + 1, self.runs.len()))
|
||||
.map(|this| {
|
||||
if new_run_started {
|
||||
this.with_animation(
|
||||
"pulsating-count",
|
||||
Animation::new(Duration::from_secs(2))
|
||||
.repeat()
|
||||
.with_easing(pulsating_between(0.4, 0.8)),
|
||||
|label, delta| label.opacity(delta),
|
||||
)
|
||||
.into_any_element()
|
||||
} else {
|
||||
this.into_any_element()
|
||||
}
|
||||
}),
|
||||
)
|
||||
.child(
|
||||
IconButton::new("go-forward", IconName::ChevronRight)
|
||||
.disabled(self.current_ix + 1 == self.runs.len())
|
||||
.tooltip(ui::Tooltip::for_action_title(
|
||||
"Go to next run",
|
||||
&EditPredictionContextGoBack,
|
||||
))
|
||||
.on_click(cx.listener(|this, _, window, cx| {
|
||||
this.handle_go_forward(
|
||||
&EditPredictionContextGoForward,
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
})),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl Focusable for EditPredictionContextView {
|
||||
fn focus_handle(&self, cx: &App) -> FocusHandle {
|
||||
self.runs
|
||||
.get(self.current_ix)
|
||||
.map(|run| run.editor.read(cx).focus_handle(cx))
|
||||
.unwrap_or_else(|| self.empty_focus_handle.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl EventEmitter<()> for EditPredictionContextView {}
|
||||
|
||||
impl Item for EditPredictionContextView {
|
||||
type Event = ();
|
||||
|
||||
fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
|
||||
"Edit Prediction Context".into()
|
||||
}
|
||||
|
||||
fn buffer_kind(&self, _cx: &App) -> workspace::item::ItemBufferKind {
|
||||
workspace::item::ItemBufferKind::Multibuffer
|
||||
}
|
||||
|
||||
fn act_as_type<'a>(
|
||||
&'a self,
|
||||
type_id: TypeId,
|
||||
self_handle: &'a Entity<Self>,
|
||||
_: &'a App,
|
||||
) -> Option<gpui::AnyEntity> {
|
||||
if type_id == TypeId::of::<Self>() {
|
||||
Some(self_handle.clone().into())
|
||||
} else if type_id == TypeId::of::<Editor>() {
|
||||
Some(self.runs.get(self.current_ix)?.editor.clone().into())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl gpui::Render for EditPredictionContextView {
|
||||
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl ui::IntoElement {
|
||||
v_flex()
|
||||
.key_context("EditPredictionContext")
|
||||
.on_action(cx.listener(Self::handle_go_back))
|
||||
.on_action(cx.listener(Self::handle_go_forward))
|
||||
.size_full()
|
||||
.map(|this| {
|
||||
if self.runs.is_empty() {
|
||||
this.child(
|
||||
v_flex()
|
||||
.size_full()
|
||||
.justify_center()
|
||||
.items_center()
|
||||
.child("No retrieval runs yet"),
|
||||
)
|
||||
} else {
|
||||
this.child(self.runs[self.current_ix].editor.clone())
|
||||
.child(self.render_informational_footer(cx))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
mod edit_prediction_button;
|
||||
mod edit_prediction_context_view;
|
||||
mod rate_prediction_modal;
|
||||
mod sweep_api_token_modal;
|
||||
|
||||
use std::any::{Any as _, TypeId};
|
||||
|
||||
use command_palette_hooks::CommandPaletteFilter;
|
||||
use edit_prediction::{ResetOnboarding, Zeta2FeatureFlag};
|
||||
use edit_prediction_context_view::EditPredictionContextView;
|
||||
use feature_flags::FeatureFlagAppExt as _;
|
||||
use gpui::actions;
|
||||
use project::DisableAiSettings;
|
||||
use rate_prediction_modal::RatePredictionsModal;
|
||||
use settings::{Settings as _, SettingsStore};
|
||||
use ui::{App, prelude::*};
|
||||
use workspace::{SplitDirection, Workspace};
|
||||
|
||||
pub use edit_prediction_button::{EditPredictionButton, ToggleMenu};
|
||||
pub use sweep_api_token_modal::SweepApiKeyModal;
|
||||
|
||||
use crate::rate_prediction_modal::PredictEditsRatePredictionsFeatureFlag;
|
||||
|
||||
actions!(
|
||||
dev,
|
||||
[
|
||||
/// Opens the edit prediction context view.
|
||||
OpenEditPredictionContextView,
|
||||
]
|
||||
);
|
||||
|
||||
actions!(
|
||||
edit_prediction,
|
||||
[
|
||||
/// Opens the rate completions modal.
|
||||
RatePredictions,
|
||||
]
|
||||
);
|
||||
|
||||
pub fn init(cx: &mut App) {
|
||||
feature_gate_predict_edits_actions(cx);
|
||||
|
||||
cx.observe_new(move |workspace: &mut Workspace, _, _cx| {
|
||||
workspace.register_action(|workspace, _: &RatePredictions, window, cx| {
|
||||
if cx.has_flag::<PredictEditsRatePredictionsFeatureFlag>() {
|
||||
RatePredictionsModal::toggle(workspace, window, cx);
|
||||
}
|
||||
});
|
||||
|
||||
workspace.register_action_renderer(|div, _, _, cx| {
|
||||
let has_flag = cx.has_flag::<Zeta2FeatureFlag>();
|
||||
div.when(has_flag, |div| {
|
||||
div.on_action(cx.listener(
|
||||
move |workspace, _: &OpenEditPredictionContextView, window, cx| {
|
||||
let project = workspace.project();
|
||||
workspace.split_item(
|
||||
SplitDirection::Right,
|
||||
Box::new(cx.new(|cx| {
|
||||
EditPredictionContextView::new(
|
||||
project.clone(),
|
||||
workspace.client(),
|
||||
workspace.user_store(),
|
||||
window,
|
||||
cx,
|
||||
)
|
||||
})),
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
},
|
||||
))
|
||||
})
|
||||
});
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
fn feature_gate_predict_edits_actions(cx: &mut App) {
|
||||
let rate_completion_action_types = [TypeId::of::<RatePredictions>()];
|
||||
let reset_onboarding_action_types = [TypeId::of::<ResetOnboarding>()];
|
||||
let all_action_types = [
|
||||
TypeId::of::<RatePredictions>(),
|
||||
TypeId::of::<edit_prediction::ResetOnboarding>(),
|
||||
zed_actions::OpenZedPredictOnboarding.type_id(),
|
||||
TypeId::of::<edit_prediction::ClearHistory>(),
|
||||
TypeId::of::<rate_prediction_modal::ThumbsUpActivePrediction>(),
|
||||
TypeId::of::<rate_prediction_modal::ThumbsDownActivePrediction>(),
|
||||
TypeId::of::<rate_prediction_modal::NextEdit>(),
|
||||
TypeId::of::<rate_prediction_modal::PreviousEdit>(),
|
||||
];
|
||||
|
||||
CommandPaletteFilter::update_global(cx, |filter, _cx| {
|
||||
filter.hide_action_types(&rate_completion_action_types);
|
||||
filter.hide_action_types(&reset_onboarding_action_types);
|
||||
filter.hide_action_types(&[zed_actions::OpenZedPredictOnboarding.type_id()]);
|
||||
});
|
||||
|
||||
cx.observe_global::<SettingsStore>(move |cx| {
|
||||
let is_ai_disabled = DisableAiSettings::get_global(cx).disable_ai;
|
||||
let has_feature_flag = cx.has_flag::<PredictEditsRatePredictionsFeatureFlag>();
|
||||
|
||||
CommandPaletteFilter::update_global(cx, |filter, _cx| {
|
||||
if is_ai_disabled {
|
||||
filter.hide_action_types(&all_action_types);
|
||||
} else if has_feature_flag {
|
||||
filter.show_action_types(&rate_completion_action_types);
|
||||
} else {
|
||||
filter.hide_action_types(&rate_completion_action_types);
|
||||
}
|
||||
});
|
||||
})
|
||||
.detach();
|
||||
|
||||
cx.observe_flag::<PredictEditsRatePredictionsFeatureFlag, _>(move |is_enabled, cx| {
|
||||
if !DisableAiSettings::get_global(cx).disable_ai {
|
||||
if is_enabled {
|
||||
CommandPaletteFilter::update_global(cx, |filter, _cx| {
|
||||
filter.show_action_types(&rate_completion_action_types);
|
||||
});
|
||||
} else {
|
||||
CommandPaletteFilter::update_global(cx, |filter, _cx| {
|
||||
filter.hide_action_types(&rate_completion_action_types);
|
||||
});
|
||||
}
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
@@ -0,0 +1,898 @@
|
||||
use buffer_diff::{BufferDiff, BufferDiffSnapshot};
|
||||
use cloud_zeta2_prompt::write_codeblock;
|
||||
use edit_prediction::{EditPrediction, EditPredictionRating, EditPredictionStore};
|
||||
use editor::{Editor, ExcerptRange, MultiBuffer};
|
||||
use feature_flags::FeatureFlag;
|
||||
use gpui::{
|
||||
App, BorderStyle, DismissEvent, EdgesRefinement, Entity, EventEmitter, FocusHandle, Focusable,
|
||||
Length, StyleRefinement, TextStyleRefinement, Window, actions, prelude::*,
|
||||
};
|
||||
use language::{LanguageRegistry, Point, language_settings};
|
||||
use markdown::{Markdown, MarkdownStyle};
|
||||
use settings::Settings as _;
|
||||
use std::{fmt::Write, sync::Arc, time::Duration};
|
||||
use theme::ThemeSettings;
|
||||
use ui::{KeyBinding, List, ListItem, ListItemSpacing, Tooltip, prelude::*};
|
||||
use workspace::{ModalView, Workspace};
|
||||
|
||||
actions!(
|
||||
zeta,
|
||||
[
|
||||
/// Rates the active completion with a thumbs up.
|
||||
ThumbsUpActivePrediction,
|
||||
/// Rates the active completion with a thumbs down.
|
||||
ThumbsDownActivePrediction,
|
||||
/// Navigates to the next edit in the completion history.
|
||||
NextEdit,
|
||||
/// Navigates to the previous edit in the completion history.
|
||||
PreviousEdit,
|
||||
/// Focuses on the completions list.
|
||||
FocusPredictions,
|
||||
/// Previews the selected completion.
|
||||
PreviewPrediction,
|
||||
]
|
||||
);
|
||||
|
||||
pub struct PredictEditsRatePredictionsFeatureFlag;
|
||||
|
||||
impl FeatureFlag for PredictEditsRatePredictionsFeatureFlag {
|
||||
const NAME: &'static str = "predict-edits-rate-completions";
|
||||
}
|
||||
|
||||
pub struct RatePredictionsModal {
|
||||
ep_store: Entity<EditPredictionStore>,
|
||||
language_registry: Arc<LanguageRegistry>,
|
||||
active_prediction: Option<ActivePrediction>,
|
||||
selected_index: usize,
|
||||
diff_editor: Entity<Editor>,
|
||||
focus_handle: FocusHandle,
|
||||
_subscription: gpui::Subscription,
|
||||
current_view: RatePredictionView,
|
||||
}
|
||||
|
||||
struct ActivePrediction {
|
||||
prediction: EditPrediction,
|
||||
feedback_editor: Entity<Editor>,
|
||||
formatted_inputs: Entity<Markdown>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
|
||||
enum RatePredictionView {
|
||||
SuggestedEdits,
|
||||
RawInput,
|
||||
}
|
||||
|
||||
impl RatePredictionView {
|
||||
pub fn name(&self) -> &'static str {
|
||||
match self {
|
||||
Self::SuggestedEdits => "Suggested Edits",
|
||||
Self::RawInput => "Recorded Events & Input",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RatePredictionsModal {
|
||||
pub fn toggle(workspace: &mut Workspace, window: &mut Window, cx: &mut Context<Workspace>) {
|
||||
if let Some(ep_store) = EditPredictionStore::try_global(cx) {
|
||||
let language_registry = workspace.app_state().languages.clone();
|
||||
workspace.toggle_modal(window, cx, |window, cx| {
|
||||
RatePredictionsModal::new(ep_store, language_registry, window, cx)
|
||||
});
|
||||
|
||||
telemetry::event!("Rate Prediction Modal Open", source = "Edit Prediction");
|
||||
}
|
||||
}
|
||||
|
||||
pub fn new(
|
||||
ep_store: Entity<EditPredictionStore>,
|
||||
language_registry: Arc<LanguageRegistry>,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Self {
|
||||
let subscription = cx.observe(&ep_store, |_, _, cx| cx.notify());
|
||||
|
||||
Self {
|
||||
ep_store,
|
||||
language_registry,
|
||||
selected_index: 0,
|
||||
focus_handle: cx.focus_handle(),
|
||||
active_prediction: None,
|
||||
_subscription: subscription,
|
||||
diff_editor: cx.new(|cx| {
|
||||
let multibuffer = cx.new(|_| MultiBuffer::new(language::Capability::ReadOnly));
|
||||
let mut editor = Editor::for_multibuffer(multibuffer, None, window, cx);
|
||||
editor.disable_inline_diagnostics();
|
||||
editor.set_expand_all_diff_hunks(cx);
|
||||
editor.set_show_git_diff_gutter(false, cx);
|
||||
editor
|
||||
}),
|
||||
current_view: RatePredictionView::SuggestedEdits,
|
||||
}
|
||||
}
|
||||
|
||||
fn dismiss(&mut self, _: &menu::Cancel, _: &mut Window, cx: &mut Context<Self>) {
|
||||
cx.emit(DismissEvent);
|
||||
}
|
||||
|
||||
fn select_next(&mut self, _: &menu::SelectNext, _: &mut Window, cx: &mut Context<Self>) {
|
||||
self.selected_index += 1;
|
||||
self.selected_index = usize::min(
|
||||
self.selected_index,
|
||||
self.ep_store.read(cx).shown_predictions().count(),
|
||||
);
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
fn select_previous(
|
||||
&mut self,
|
||||
_: &menu::SelectPrevious,
|
||||
_: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
self.selected_index = self.selected_index.saturating_sub(1);
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
fn select_next_edit(&mut self, _: &NextEdit, _: &mut Window, cx: &mut Context<Self>) {
|
||||
let next_index = self
|
||||
.ep_store
|
||||
.read(cx)
|
||||
.shown_predictions()
|
||||
.skip(self.selected_index)
|
||||
.enumerate()
|
||||
.skip(1) // Skip straight to the next item
|
||||
.find(|(_, completion)| !completion.edits.is_empty())
|
||||
.map(|(ix, _)| ix + self.selected_index);
|
||||
|
||||
if let Some(next_index) = next_index {
|
||||
self.selected_index = next_index;
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
|
||||
fn select_prev_edit(&mut self, _: &PreviousEdit, _: &mut Window, cx: &mut Context<Self>) {
|
||||
let ep_store = self.ep_store.read(cx);
|
||||
let completions_len = ep_store.shown_completions_len();
|
||||
|
||||
let prev_index = self
|
||||
.ep_store
|
||||
.read(cx)
|
||||
.shown_predictions()
|
||||
.rev()
|
||||
.skip((completions_len - 1) - self.selected_index)
|
||||
.enumerate()
|
||||
.skip(1) // Skip straight to the previous item
|
||||
.find(|(_, completion)| !completion.edits.is_empty())
|
||||
.map(|(ix, _)| self.selected_index - ix);
|
||||
|
||||
if let Some(prev_index) = prev_index {
|
||||
self.selected_index = prev_index;
|
||||
cx.notify();
|
||||
}
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
fn select_first(&mut self, _: &menu::SelectFirst, _: &mut Window, cx: &mut Context<Self>) {
|
||||
self.selected_index = 0;
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
fn select_last(&mut self, _: &menu::SelectLast, _window: &mut Window, cx: &mut Context<Self>) {
|
||||
self.selected_index = self.ep_store.read(cx).shown_completions_len() - 1;
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
pub fn thumbs_up_active(
|
||||
&mut self,
|
||||
_: &ThumbsUpActivePrediction,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
self.ep_store.update(cx, |ep_store, cx| {
|
||||
if let Some(active) = &self.active_prediction {
|
||||
ep_store.rate_prediction(
|
||||
&active.prediction,
|
||||
EditPredictionRating::Positive,
|
||||
active.feedback_editor.read(cx).text(cx),
|
||||
cx,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
let current_completion = self
|
||||
.active_prediction
|
||||
.as_ref()
|
||||
.map(|completion| completion.prediction.clone());
|
||||
self.select_completion(current_completion, false, window, cx);
|
||||
self.select_next_edit(&Default::default(), window, cx);
|
||||
self.confirm(&Default::default(), window, cx);
|
||||
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
pub fn thumbs_down_active(
|
||||
&mut self,
|
||||
_: &ThumbsDownActivePrediction,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
if let Some(active) = &self.active_prediction {
|
||||
if active.feedback_editor.read(cx).text(cx).is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
self.ep_store.update(cx, |ep_store, cx| {
|
||||
ep_store.rate_prediction(
|
||||
&active.prediction,
|
||||
EditPredictionRating::Negative,
|
||||
active.feedback_editor.read(cx).text(cx),
|
||||
cx,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
let current_completion = self
|
||||
.active_prediction
|
||||
.as_ref()
|
||||
.map(|completion| completion.prediction.clone());
|
||||
self.select_completion(current_completion, false, window, cx);
|
||||
self.select_next_edit(&Default::default(), window, cx);
|
||||
self.confirm(&Default::default(), window, cx);
|
||||
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
fn focus_completions(
|
||||
&mut self,
|
||||
_: &FocusPredictions,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
cx.focus_self(window);
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
fn preview_completion(
|
||||
&mut self,
|
||||
_: &PreviewPrediction,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
let completion = self
|
||||
.ep_store
|
||||
.read(cx)
|
||||
.shown_predictions()
|
||||
.skip(self.selected_index)
|
||||
.take(1)
|
||||
.next()
|
||||
.cloned();
|
||||
|
||||
self.select_completion(completion, false, window, cx);
|
||||
}
|
||||
|
||||
fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let completion = self
|
||||
.ep_store
|
||||
.read(cx)
|
||||
.shown_predictions()
|
||||
.skip(self.selected_index)
|
||||
.take(1)
|
||||
.next()
|
||||
.cloned();
|
||||
|
||||
self.select_completion(completion, true, window, cx);
|
||||
}
|
||||
|
||||
pub fn select_completion(
|
||||
&mut self,
|
||||
prediction: Option<EditPrediction>,
|
||||
focus: bool,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
// Avoid resetting completion rating if it's already selected.
|
||||
if let Some(prediction) = prediction {
|
||||
self.selected_index = self
|
||||
.ep_store
|
||||
.read(cx)
|
||||
.shown_predictions()
|
||||
.enumerate()
|
||||
.find(|(_, completion_b)| prediction.id == completion_b.id)
|
||||
.map(|(ix, _)| ix)
|
||||
.unwrap_or(self.selected_index);
|
||||
cx.notify();
|
||||
|
||||
if let Some(prev_prediction) = self.active_prediction.as_ref()
|
||||
&& prediction.id == prev_prediction.prediction.id
|
||||
{
|
||||
if focus {
|
||||
window.focus(&prev_prediction.feedback_editor.focus_handle(cx));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
self.diff_editor.update(cx, |editor, cx| {
|
||||
let new_buffer = prediction.edit_preview.build_result_buffer(cx);
|
||||
let new_buffer_snapshot = new_buffer.read(cx).snapshot();
|
||||
let old_buffer_snapshot = prediction.snapshot.clone();
|
||||
let new_buffer_id = new_buffer_snapshot.remote_id();
|
||||
|
||||
let range = prediction
|
||||
.edit_preview
|
||||
.compute_visible_range(&prediction.edits)
|
||||
.unwrap_or(Point::zero()..Point::zero());
|
||||
let start = Point::new(range.start.row.saturating_sub(5), 0);
|
||||
let end = Point::new(range.end.row + 5, 0).min(new_buffer_snapshot.max_point());
|
||||
|
||||
let diff = cx.new::<BufferDiff>(|cx| {
|
||||
let diff_snapshot = BufferDiffSnapshot::new_with_base_buffer(
|
||||
new_buffer_snapshot.text.clone(),
|
||||
Some(old_buffer_snapshot.text().into()),
|
||||
old_buffer_snapshot.clone(),
|
||||
cx,
|
||||
);
|
||||
let diff = BufferDiff::new(&new_buffer_snapshot, cx);
|
||||
cx.spawn(async move |diff, cx| {
|
||||
let diff_snapshot = diff_snapshot.await;
|
||||
diff.update(cx, |diff, cx| {
|
||||
diff.set_snapshot(diff_snapshot, &new_buffer_snapshot.text, cx);
|
||||
})
|
||||
})
|
||||
.detach();
|
||||
diff
|
||||
});
|
||||
|
||||
editor.disable_header_for_buffer(new_buffer_id, cx);
|
||||
editor.buffer().update(cx, |multibuffer, cx| {
|
||||
multibuffer.clear(cx);
|
||||
multibuffer.push_excerpts(
|
||||
new_buffer,
|
||||
vec![ExcerptRange {
|
||||
context: start..end,
|
||||
primary: start..end,
|
||||
}],
|
||||
cx,
|
||||
);
|
||||
multibuffer.add_diff(diff, cx);
|
||||
});
|
||||
});
|
||||
|
||||
let mut formatted_inputs = String::new();
|
||||
|
||||
write!(&mut formatted_inputs, "## Events\n\n").unwrap();
|
||||
|
||||
for event in &prediction.inputs.events {
|
||||
write!(&mut formatted_inputs, "```diff\n{event}```\n\n").unwrap();
|
||||
}
|
||||
|
||||
write!(&mut formatted_inputs, "## Included files\n\n").unwrap();
|
||||
|
||||
for included_file in &prediction.inputs.included_files {
|
||||
let cursor_insertions = &[(prediction.inputs.cursor_point, "<|CURSOR|>")];
|
||||
|
||||
write!(
|
||||
&mut formatted_inputs,
|
||||
"### {}\n\n",
|
||||
included_file.path.display()
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
write_codeblock(
|
||||
&included_file.path,
|
||||
&included_file.excerpts,
|
||||
if included_file.path == prediction.inputs.cursor_path {
|
||||
cursor_insertions.as_slice()
|
||||
} else {
|
||||
&[]
|
||||
},
|
||||
included_file.max_row,
|
||||
false,
|
||||
&mut formatted_inputs,
|
||||
);
|
||||
}
|
||||
|
||||
self.active_prediction = Some(ActivePrediction {
|
||||
prediction,
|
||||
feedback_editor: cx.new(|cx| {
|
||||
let mut editor = Editor::multi_line(window, cx);
|
||||
editor.disable_scrollbars_and_minimap(window, cx);
|
||||
editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
|
||||
editor.set_show_line_numbers(false, cx);
|
||||
editor.set_show_git_diff_gutter(false, cx);
|
||||
editor.set_show_code_actions(false, cx);
|
||||
editor.set_show_runnables(false, cx);
|
||||
editor.set_show_breakpoints(false, cx);
|
||||
editor.set_show_wrap_guides(false, cx);
|
||||
editor.set_show_indent_guides(false, cx);
|
||||
editor.set_show_edit_predictions(Some(false), window, cx);
|
||||
editor.set_placeholder_text("Add your feedback…", window, cx);
|
||||
if focus {
|
||||
cx.focus_self(window);
|
||||
}
|
||||
editor
|
||||
}),
|
||||
formatted_inputs: cx.new(|cx| {
|
||||
Markdown::new(
|
||||
formatted_inputs.into(),
|
||||
Some(self.language_registry.clone()),
|
||||
None,
|
||||
cx,
|
||||
)
|
||||
}),
|
||||
});
|
||||
} else {
|
||||
self.active_prediction = None;
|
||||
}
|
||||
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
fn render_view_nav(&self, cx: &Context<Self>) -> impl IntoElement {
|
||||
h_flex()
|
||||
.h_8()
|
||||
.px_1()
|
||||
.border_b_1()
|
||||
.border_color(cx.theme().colors().border)
|
||||
.bg(cx.theme().colors().elevated_surface_background)
|
||||
.gap_1()
|
||||
.child(
|
||||
Button::new(
|
||||
ElementId::Name("suggested-edits".into()),
|
||||
RatePredictionView::SuggestedEdits.name(),
|
||||
)
|
||||
.label_size(LabelSize::Small)
|
||||
.on_click(cx.listener(move |this, _, _window, cx| {
|
||||
this.current_view = RatePredictionView::SuggestedEdits;
|
||||
cx.notify();
|
||||
}))
|
||||
.toggle_state(self.current_view == RatePredictionView::SuggestedEdits),
|
||||
)
|
||||
.child(
|
||||
Button::new(
|
||||
ElementId::Name("raw-input".into()),
|
||||
RatePredictionView::RawInput.name(),
|
||||
)
|
||||
.label_size(LabelSize::Small)
|
||||
.on_click(cx.listener(move |this, _, _window, cx| {
|
||||
this.current_view = RatePredictionView::RawInput;
|
||||
cx.notify();
|
||||
}))
|
||||
.toggle_state(self.current_view == RatePredictionView::RawInput),
|
||||
)
|
||||
}
|
||||
|
||||
fn render_suggested_edits(&self, cx: &mut Context<Self>) -> Option<gpui::Stateful<Div>> {
|
||||
let bg_color = cx.theme().colors().editor_background;
|
||||
Some(
|
||||
div()
|
||||
.id("diff")
|
||||
.p_4()
|
||||
.size_full()
|
||||
.bg(bg_color)
|
||||
.overflow_scroll()
|
||||
.whitespace_nowrap()
|
||||
.child(self.diff_editor.clone()),
|
||||
)
|
||||
}
|
||||
|
||||
fn render_raw_input(
|
||||
&self,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Option<gpui::Stateful<Div>> {
|
||||
let theme_settings = ThemeSettings::get_global(cx);
|
||||
let buffer_font_size = theme_settings.buffer_font_size(cx);
|
||||
|
||||
Some(
|
||||
v_flex()
|
||||
.size_full()
|
||||
.overflow_hidden()
|
||||
.relative()
|
||||
.child(
|
||||
div()
|
||||
.id("raw-input")
|
||||
.py_4()
|
||||
.px_6()
|
||||
.size_full()
|
||||
.bg(cx.theme().colors().editor_background)
|
||||
.overflow_scroll()
|
||||
.child(if let Some(active_prediction) = &self.active_prediction {
|
||||
markdown::MarkdownElement::new(
|
||||
active_prediction.formatted_inputs.clone(),
|
||||
MarkdownStyle {
|
||||
base_text_style: window.text_style(),
|
||||
syntax: cx.theme().syntax().clone(),
|
||||
code_block: StyleRefinement {
|
||||
text: Some(TextStyleRefinement {
|
||||
font_family: Some(
|
||||
theme_settings.buffer_font.family.clone(),
|
||||
),
|
||||
font_size: Some(buffer_font_size.into()),
|
||||
..Default::default()
|
||||
}),
|
||||
padding: EdgesRefinement {
|
||||
top: Some(DefiniteLength::Absolute(
|
||||
AbsoluteLength::Pixels(px(8.)),
|
||||
)),
|
||||
left: Some(DefiniteLength::Absolute(
|
||||
AbsoluteLength::Pixels(px(8.)),
|
||||
)),
|
||||
right: Some(DefiniteLength::Absolute(
|
||||
AbsoluteLength::Pixels(px(8.)),
|
||||
)),
|
||||
bottom: Some(DefiniteLength::Absolute(
|
||||
AbsoluteLength::Pixels(px(8.)),
|
||||
)),
|
||||
},
|
||||
margin: EdgesRefinement {
|
||||
top: Some(Length::Definite(px(8.).into())),
|
||||
left: Some(Length::Definite(px(0.).into())),
|
||||
right: Some(Length::Definite(px(0.).into())),
|
||||
bottom: Some(Length::Definite(px(12.).into())),
|
||||
},
|
||||
border_style: Some(BorderStyle::Solid),
|
||||
border_widths: EdgesRefinement {
|
||||
top: Some(AbsoluteLength::Pixels(px(1.))),
|
||||
left: Some(AbsoluteLength::Pixels(px(1.))),
|
||||
right: Some(AbsoluteLength::Pixels(px(1.))),
|
||||
bottom: Some(AbsoluteLength::Pixels(px(1.))),
|
||||
},
|
||||
border_color: Some(cx.theme().colors().border_variant),
|
||||
background: Some(
|
||||
cx.theme().colors().editor_background.into(),
|
||||
),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.into_any_element()
|
||||
} else {
|
||||
div()
|
||||
.child("No active completion".to_string())
|
||||
.into_any_element()
|
||||
}),
|
||||
)
|
||||
.id("raw-input-view"),
|
||||
)
|
||||
}
|
||||
|
||||
fn render_active_completion(
|
||||
&mut self,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Option<impl IntoElement> {
|
||||
let active_prediction = self.active_prediction.as_ref()?;
|
||||
let completion_id = active_prediction.prediction.id.clone();
|
||||
let focus_handle = &self.focus_handle(cx);
|
||||
|
||||
let border_color = cx.theme().colors().border;
|
||||
let bg_color = cx.theme().colors().editor_background;
|
||||
|
||||
let rated = self.ep_store.read(cx).is_prediction_rated(&completion_id);
|
||||
let feedback_empty = active_prediction
|
||||
.feedback_editor
|
||||
.read(cx)
|
||||
.text(cx)
|
||||
.is_empty();
|
||||
|
||||
let label_container = h_flex().pl_1().gap_1p5();
|
||||
|
||||
Some(
|
||||
v_flex()
|
||||
.size_full()
|
||||
.overflow_hidden()
|
||||
.relative()
|
||||
.child(
|
||||
v_flex()
|
||||
.size_full()
|
||||
.overflow_hidden()
|
||||
.relative()
|
||||
.child(self.render_view_nav(cx))
|
||||
.when_some(
|
||||
match self.current_view {
|
||||
RatePredictionView::SuggestedEdits => {
|
||||
self.render_suggested_edits(cx)
|
||||
}
|
||||
RatePredictionView::RawInput => self.render_raw_input(window, cx),
|
||||
},
|
||||
|this, element| this.child(element),
|
||||
),
|
||||
)
|
||||
.when(!rated, |this| {
|
||||
this.child(
|
||||
h_flex()
|
||||
.p_2()
|
||||
.gap_2()
|
||||
.border_y_1()
|
||||
.border_color(border_color)
|
||||
.child(
|
||||
Icon::new(IconName::Info)
|
||||
.size(IconSize::XSmall)
|
||||
.color(Color::Muted),
|
||||
)
|
||||
.child(
|
||||
div().w_full().pr_2().flex_wrap().child(
|
||||
Label::new(concat!(
|
||||
"Explain why this completion is good or bad. ",
|
||||
"If it's negative, describe what you expected instead."
|
||||
))
|
||||
.size(LabelSize::Small)
|
||||
.color(Color::Muted),
|
||||
),
|
||||
),
|
||||
)
|
||||
})
|
||||
.when(!rated, |this| {
|
||||
this.child(
|
||||
div()
|
||||
.h_40()
|
||||
.pt_1()
|
||||
.bg(bg_color)
|
||||
.child(active_prediction.feedback_editor.clone()),
|
||||
)
|
||||
})
|
||||
.child(
|
||||
h_flex()
|
||||
.p_1()
|
||||
.h_8()
|
||||
.max_h_8()
|
||||
.border_t_1()
|
||||
.border_color(border_color)
|
||||
.max_w_full()
|
||||
.justify_between()
|
||||
.children(if rated {
|
||||
Some(
|
||||
label_container
|
||||
.child(
|
||||
Icon::new(IconName::Check)
|
||||
.size(IconSize::Small)
|
||||
.color(Color::Success),
|
||||
)
|
||||
.child(Label::new("Rated completion.").color(Color::Muted)),
|
||||
)
|
||||
} else if active_prediction.prediction.edits.is_empty() {
|
||||
Some(
|
||||
label_container
|
||||
.child(
|
||||
Icon::new(IconName::Warning)
|
||||
.size(IconSize::Small)
|
||||
.color(Color::Warning),
|
||||
)
|
||||
.child(Label::new("No edits produced.").color(Color::Muted)),
|
||||
)
|
||||
} else {
|
||||
Some(label_container)
|
||||
})
|
||||
.child(
|
||||
h_flex()
|
||||
.gap_1()
|
||||
.child(
|
||||
Button::new("bad", "Bad Prediction")
|
||||
.icon(IconName::ThumbsDown)
|
||||
.icon_size(IconSize::Small)
|
||||
.icon_position(IconPosition::Start)
|
||||
.disabled(rated || feedback_empty)
|
||||
.when(feedback_empty, |this| {
|
||||
this.tooltip(Tooltip::text(
|
||||
"Explain what's bad about it before reporting it",
|
||||
))
|
||||
})
|
||||
.key_binding(KeyBinding::for_action_in(
|
||||
&ThumbsDownActivePrediction,
|
||||
focus_handle,
|
||||
cx,
|
||||
))
|
||||
.on_click(cx.listener(move |this, _, window, cx| {
|
||||
if this.active_prediction.is_some() {
|
||||
this.thumbs_down_active(
|
||||
&ThumbsDownActivePrediction,
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
}
|
||||
})),
|
||||
)
|
||||
.child(
|
||||
Button::new("good", "Good Prediction")
|
||||
.icon(IconName::ThumbsUp)
|
||||
.icon_size(IconSize::Small)
|
||||
.icon_position(IconPosition::Start)
|
||||
.disabled(rated)
|
||||
.key_binding(KeyBinding::for_action_in(
|
||||
&ThumbsUpActivePrediction,
|
||||
focus_handle,
|
||||
cx,
|
||||
))
|
||||
.on_click(cx.listener(move |this, _, window, cx| {
|
||||
if this.active_prediction.is_some() {
|
||||
this.thumbs_up_active(
|
||||
&ThumbsUpActivePrediction,
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
}
|
||||
})),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
fn render_shown_completions(&self, cx: &Context<Self>) -> impl Iterator<Item = ListItem> {
|
||||
self.ep_store
|
||||
.read(cx)
|
||||
.shown_predictions()
|
||||
.cloned()
|
||||
.enumerate()
|
||||
.map(|(index, completion)| {
|
||||
let selected = self
|
||||
.active_prediction
|
||||
.as_ref()
|
||||
.is_some_and(|selected| selected.prediction.id == completion.id);
|
||||
let rated = self.ep_store.read(cx).is_prediction_rated(&completion.id);
|
||||
|
||||
let (icon_name, icon_color, tooltip_text) =
|
||||
match (rated, completion.edits.is_empty()) {
|
||||
(true, _) => (IconName::Check, Color::Success, "Rated Prediction"),
|
||||
(false, true) => (IconName::File, Color::Muted, "No Edits Produced"),
|
||||
(false, false) => (IconName::FileDiff, Color::Accent, "Edits Available"),
|
||||
};
|
||||
|
||||
let file = completion.buffer.read(cx).file();
|
||||
let file_name = file
|
||||
.as_ref()
|
||||
.map_or(SharedString::new_static("untitled"), |file| {
|
||||
file.file_name(cx).to_string().into()
|
||||
});
|
||||
let file_path = file.map(|file| file.path().as_unix_str().to_string());
|
||||
|
||||
ListItem::new(completion.id.clone())
|
||||
.inset(true)
|
||||
.spacing(ListItemSpacing::Sparse)
|
||||
.focused(index == self.selected_index)
|
||||
.toggle_state(selected)
|
||||
.child(
|
||||
h_flex()
|
||||
.id("completion-content")
|
||||
.gap_3()
|
||||
.child(Icon::new(icon_name).color(icon_color).size(IconSize::Small))
|
||||
.child(
|
||||
v_flex()
|
||||
.child(
|
||||
h_flex()
|
||||
.gap_1()
|
||||
.child(Label::new(file_name).size(LabelSize::Small))
|
||||
.when_some(file_path, |this, p| {
|
||||
this.child(
|
||||
Label::new(p)
|
||||
.size(LabelSize::Small)
|
||||
.color(Color::Muted),
|
||||
)
|
||||
}),
|
||||
)
|
||||
.child(
|
||||
Label::new(format!(
|
||||
"{} ago, {:.2?}",
|
||||
format_time_ago(
|
||||
completion.response_received_at.elapsed()
|
||||
),
|
||||
completion.latency()
|
||||
))
|
||||
.color(Color::Muted)
|
||||
.size(LabelSize::XSmall),
|
||||
),
|
||||
),
|
||||
)
|
||||
.tooltip(Tooltip::text(tooltip_text))
|
||||
.on_click(cx.listener(move |this, _, window, cx| {
|
||||
this.select_completion(Some(completion.clone()), true, window, cx);
|
||||
}))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Render for RatePredictionsModal {
|
||||
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
let border_color = cx.theme().colors().border;
|
||||
|
||||
h_flex()
|
||||
.key_context("RatePredictionModal")
|
||||
.track_focus(&self.focus_handle)
|
||||
.on_action(cx.listener(Self::dismiss))
|
||||
.on_action(cx.listener(Self::confirm))
|
||||
.on_action(cx.listener(Self::select_previous))
|
||||
.on_action(cx.listener(Self::select_prev_edit))
|
||||
.on_action(cx.listener(Self::select_next))
|
||||
.on_action(cx.listener(Self::select_next_edit))
|
||||
.on_action(cx.listener(Self::select_first))
|
||||
.on_action(cx.listener(Self::select_last))
|
||||
.on_action(cx.listener(Self::thumbs_up_active))
|
||||
.on_action(cx.listener(Self::thumbs_down_active))
|
||||
.on_action(cx.listener(Self::focus_completions))
|
||||
.on_action(cx.listener(Self::preview_completion))
|
||||
.bg(cx.theme().colors().elevated_surface_background)
|
||||
.border_1()
|
||||
.border_color(border_color)
|
||||
.w(window.viewport_size().width - px(320.))
|
||||
.h(window.viewport_size().height - px(300.))
|
||||
.rounded_lg()
|
||||
.shadow_lg()
|
||||
.child(
|
||||
v_flex()
|
||||
.w_72()
|
||||
.h_full()
|
||||
.border_r_1()
|
||||
.border_color(border_color)
|
||||
.flex_shrink_0()
|
||||
.overflow_hidden()
|
||||
.child(
|
||||
h_flex()
|
||||
.h_8()
|
||||
.px_2()
|
||||
.justify_between()
|
||||
.border_b_1()
|
||||
.border_color(border_color)
|
||||
.child(Icon::new(IconName::ZedPredict).size(IconSize::Small))
|
||||
.child(
|
||||
Label::new("From most recent to oldest")
|
||||
.color(Color::Muted)
|
||||
.size(LabelSize::Small),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.id("completion_list")
|
||||
.p_0p5()
|
||||
.h_full()
|
||||
.overflow_y_scroll()
|
||||
.child(
|
||||
List::new()
|
||||
.empty_message(
|
||||
div()
|
||||
.p_2()
|
||||
.child(
|
||||
Label::new(concat!(
|
||||
"No completions yet. ",
|
||||
"Use the editor to generate some, ",
|
||||
"and make sure to rate them!"
|
||||
))
|
||||
.color(Color::Muted),
|
||||
)
|
||||
.into_any_element(),
|
||||
)
|
||||
.children(self.render_shown_completions(cx)),
|
||||
),
|
||||
),
|
||||
)
|
||||
.children(self.render_active_completion(window, cx))
|
||||
.on_mouse_down_out(cx.listener(|_, _, _, cx| cx.emit(DismissEvent)))
|
||||
}
|
||||
}
|
||||
|
||||
impl EventEmitter<DismissEvent> for RatePredictionsModal {}
|
||||
|
||||
impl Focusable for RatePredictionsModal {
|
||||
fn focus_handle(&self, _cx: &App) -> FocusHandle {
|
||||
self.focus_handle.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl ModalView for RatePredictionsModal {}
|
||||
|
||||
fn format_time_ago(elapsed: Duration) -> String {
|
||||
let seconds = elapsed.as_secs();
|
||||
if seconds < 120 {
|
||||
"1 minute".to_string()
|
||||
} else if seconds < 3600 {
|
||||
format!("{} minutes", seconds / 60)
|
||||
} else if seconds < 7200 {
|
||||
"1 hour".to_string()
|
||||
} else if seconds < 86400 {
|
||||
format!("{} hours", seconds / 3600)
|
||||
} else if seconds < 172800 {
|
||||
"1 day".to_string()
|
||||
} else {
|
||||
format!("{} days", seconds / 86400)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
use edit_prediction::EditPredictionStore;
|
||||
use gpui::{
|
||||
DismissEvent, Entity, EventEmitter, FocusHandle, Focusable, IntoElement, ParentElement, Render,
|
||||
};
|
||||
use ui::{Button, ButtonStyle, Clickable, Headline, HeadlineSize, prelude::*};
|
||||
use ui_input::InputField;
|
||||
use workspace::ModalView;
|
||||
|
||||
pub struct SweepApiKeyModal {
|
||||
api_key_input: Entity<InputField>,
|
||||
focus_handle: FocusHandle,
|
||||
}
|
||||
|
||||
impl SweepApiKeyModal {
|
||||
pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||
let api_key_input = cx.new(|cx| InputField::new(window, cx, "Enter your Sweep API token"));
|
||||
|
||||
Self {
|
||||
api_key_input,
|
||||
focus_handle: cx.focus_handle(),
|
||||
}
|
||||
}
|
||||
|
||||
fn cancel(&mut self, _: &menu::Cancel, _window: &mut Window, cx: &mut Context<Self>) {
|
||||
cx.emit(DismissEvent);
|
||||
}
|
||||
|
||||
fn confirm(&mut self, _: &menu::Confirm, _window: &mut Window, cx: &mut Context<Self>) {
|
||||
let api_key = self.api_key_input.read(cx).text(cx);
|
||||
let api_key = (!api_key.trim().is_empty()).then_some(api_key);
|
||||
|
||||
if let Some(ep_store) = EditPredictionStore::try_global(cx) {
|
||||
ep_store.update(cx, |ep_store, cx| {
|
||||
ep_store
|
||||
.sweep_ai
|
||||
.set_api_token(api_key, cx)
|
||||
.detach_and_log_err(cx);
|
||||
});
|
||||
}
|
||||
|
||||
cx.emit(DismissEvent);
|
||||
}
|
||||
}
|
||||
|
||||
impl EventEmitter<DismissEvent> for SweepApiKeyModal {}
|
||||
|
||||
impl ModalView for SweepApiKeyModal {}
|
||||
|
||||
impl Focusable for SweepApiKeyModal {
|
||||
fn focus_handle(&self, _cx: &App) -> FocusHandle {
|
||||
self.focus_handle.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl Render for SweepApiKeyModal {
|
||||
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
v_flex()
|
||||
.key_context("SweepApiKeyModal")
|
||||
.on_action(cx.listener(Self::cancel))
|
||||
.on_action(cx.listener(Self::confirm))
|
||||
.elevation_2(cx)
|
||||
.w(px(400.))
|
||||
.p_4()
|
||||
.gap_3()
|
||||
.child(Headline::new("Sweep API Token").size(HeadlineSize::Small))
|
||||
.child(self.api_key_input.clone())
|
||||
.child(
|
||||
h_flex()
|
||||
.justify_end()
|
||||
.gap_2()
|
||||
.child(Button::new("cancel", "Cancel").on_click(cx.listener(
|
||||
|_, _, _window, cx| {
|
||||
cx.emit(DismissEvent);
|
||||
},
|
||||
)))
|
||||
.child(
|
||||
Button::new("save", "Save")
|
||||
.style(ButtonStyle::Filled)
|
||||
.on_click(cx.listener(|this, _, window, cx| {
|
||||
this.confirm(&menu::Confirm, window, cx);
|
||||
})),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user