Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

edit_prediction: Remove diagnostic-triggered jumps (#59724)

Ben Kunkle131ff63ce5c1
diff --git a/crates/edit_prediction/src/edit_prediction.rs b/crates/edit_prediction/src/edit_prediction.rs
index 85c4f9279cf..4e576580fc2 100644
--- a/crates/edit_prediction/src/edit_prediction.rs
+++ b/crates/edit_prediction/src/edit_prediction.rs
@@ -68,7 +68,7 @@ use std::sync::Arc;
use std::time::{Duration, Instant};
use thiserror::Error;
-use util::{RangeExt as _, ResultExt as _};
+use util::ResultExt as _;
pub mod cursor_excerpt;
pub mod data_collection;
@@ -140,10 +140,6 @@ pub struct EditPredictionJumpsFeatureFlag;
impl FeatureFlag for EditPredictionJumpsFeatureFlag {
const NAME: &'static str = "edit_prediction_jumps";
type Value = PresenceFlag;
-
- fn enabled_for_staff() -> bool {
- false
- }
}
register_feature_flag!(EditPredictionJumpsFeatureFlag);
@@ -367,7 +363,6 @@ struct ProjectState {
pending_prediction_captures: Vec<PendingPredictionCapture>,
debug_tx: Option<mpsc::UnboundedSender<DebugEvent>>,
last_edit_prediction_refresh: Option<(EntityId, Instant)>,
- last_jump_prediction_refresh: Option<(EntityId, Instant)>,
cancelled_predictions: HashSet<usize>,
context: Entity<RelatedExcerptStore>,
license_detection_watchers: HashMap<WorktreeId, Rc<LicenseDetectionWatcher>>,
@@ -502,7 +497,7 @@ impl ProjectState {
#[derive(Debug, Clone)]
struct CurrentEditPrediction {
- pub requested_by: PredictionRequestedBy,
+ pub requested_by: EntityId,
pub prediction: EditPrediction,
pub was_shown: bool,
pub shown_with: Option<edit_prediction_types::SuggestionDisplayType>,
@@ -529,13 +524,11 @@ impl CurrentEditPrediction {
return true;
};
- let requested_by_buffer_id = self.requested_by.buffer_id();
-
// This reduces the occurrence of UI thrash from replacing edits
//
// TODO: This is fairly arbitrary - should have a more general heuristic that handles multiple edits.
- if requested_by_buffer_id == Some(self.prediction.buffer.entity_id())
- && requested_by_buffer_id == Some(old_prediction.prediction.buffer.entity_id())
+ if self.requested_by == self.prediction.buffer.entity_id()
+ && self.requested_by == old_prediction.prediction.buffer.entity_id()
&& old_edits.len() == 1
&& new_edits.len() == 1
{
@@ -548,29 +541,8 @@ impl CurrentEditPrediction {
}
}
-#[derive(Debug, Clone)]
-enum PredictionRequestedBy {
- DiagnosticsUpdate,
- Buffer(EntityId),
-}
-
-impl PredictionRequestedBy {
- pub fn buffer_id(&self) -> Option<EntityId> {
- match self {
- PredictionRequestedBy::DiagnosticsUpdate => None,
- PredictionRequestedBy::Buffer(buffer_id) => Some(*buffer_id),
- }
- }
-}
-
const DIAGNOSTIC_LINES_RANGE: u32 = 20;
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
-pub enum DiagnosticSearchScope {
- Local,
- Global,
-}
-
#[derive(Debug)]
struct PendingPrediction {
id: usize,
@@ -1441,7 +1413,6 @@ impl EditPredictionStore {
pending_prediction_captures: Vec::new(),
next_pending_prediction_id: 0,
last_edit_prediction_refresh: None,
- last_jump_prediction_refresh: None,
license_detection_watchers: HashMap::default(),
_subscriptions: [
cx.subscribe(&project, Self::handle_project_event),
@@ -1585,24 +1556,6 @@ impl EditPredictionStore {
push_recent_file(&mut project_state.recently_viewed_files, recent_file);
}
}
- project::Event::DiagnosticsUpdated { .. } => {
- if self
- .projects
- .get(&project.entity_id())
- .and_then(|project_state| project_state.last_edit_source)
- == Some(BufferEditSource::Agent)
- {
- return;
- }
-
- if cx.has_flag::<EditPredictionJumpsFeatureFlag>() {
- self.refresh_prediction_from_diagnostics(
- project,
- DiagnosticSearchScope::Global,
- cx,
- );
- }
- }
_ => (),
}
}
@@ -1854,19 +1807,10 @@ impl EditPredictionStore {
if prediction.targets_buffer(buffer.read(cx)) {
Some(BufferEditPrediction::Local { prediction })
+ } else if requested_by == &buffer.entity_id() {
+ Some(BufferEditPrediction::Jump { prediction })
} else {
- let show_jump = match requested_by {
- PredictionRequestedBy::Buffer(requested_by_buffer_id) => {
- requested_by_buffer_id == &buffer.entity_id()
- }
- PredictionRequestedBy::DiagnosticsUpdate => true,
- };
-
- if show_jump {
- Some(BufferEditPrediction::Jump { prediction })
- } else {
- None
- }
+ None
}
}
@@ -2439,192 +2383,35 @@ impl EditPredictionStore {
trigger: EditPredictionRequestTrigger,
cx: &mut Context<Self>,
) {
- let trigger = predict_edits_request_trigger_from_editor_trigger(trigger);
-
- self.queue_prediction_refresh(
- project.clone(),
- trigger,
- buffer.entity_id(),
- cx,
- move |this, cx| {
- let Some(request_task) = this
- .update(cx, |this, cx| {
- this.request_prediction_internal(
- project.clone(),
- buffer.clone(),
- position,
- trigger,
- cx.has_flag::<EditPredictionJumpsFeatureFlag>(),
- cx,
- )
- })
- .log_err()
- else {
- return Task::ready(anyhow::Ok(None));
- };
-
- cx.spawn(async move |_cx| {
- request_task.await.map(|prediction_result| {
- prediction_result.map(|prediction_result| {
- (
- prediction_result,
- PredictionRequestedBy::Buffer(buffer.entity_id()),
- )
- })
- })
- })
- },
- )
- }
-
- pub fn refresh_prediction_from_diagnostics(
- &mut self,
- project: Entity<Project>,
- scope: DiagnosticSearchScope,
- cx: &mut Context<Self>,
- ) {
- if !is_ep_store_provider(all_language_settings(None, cx).edit_predictions.provider) {
- return;
- }
-
if currently_following(&project, cx) {
return;
}
- let Some(project_state) = self.projects.get_mut(&project.entity_id()) else {
- return;
- };
-
- // Prefer predictions from buffer
- if project_state.current_prediction.is_some() {
- log::debug!(
- "edit_prediction: diagnostic refresh skipped, current prediction already exists"
- );
- return;
- }
-
- self.queue_prediction_refresh(
- project.clone(),
- PredictEditsRequestTrigger::Diagnostics,
- project.entity_id(),
- cx,
- move |this, cx| {
- let Some((active_buffer, snapshot, cursor_point)) = this
- .read_with(cx, |this, cx| {
- let project_state = this.projects.get(&project.entity_id())?;
- let (buffer, position) = project_state.active_buffer(&project, cx)?;
- let snapshot = buffer.read(cx).snapshot();
-
- if !Self::predictions_enabled_at(&snapshot, position, cx) {
- return None;
- }
-
- let cursor_point = position
- .map(|pos| pos.to_point(&snapshot))
- .unwrap_or_default();
-
- Some((buffer, snapshot, cursor_point))
- })
- .log_err()
- .flatten()
- else {
- return Task::ready(anyhow::Ok(None));
- };
-
- cx.spawn(async move |cx| {
- let diagnostic_search_range = match scope {
- DiagnosticSearchScope::Local => {
- let diagnostic_search_start =
- cursor_point.row.saturating_sub(DIAGNOSTIC_LINES_RANGE);
- let diagnostic_search_end = cursor_point.row + DIAGNOSTIC_LINES_RANGE;
- Point::new(diagnostic_search_start, 0)
- ..Point::new(diagnostic_search_end, 0)
- }
- DiagnosticSearchScope::Global => Default::default(),
- };
+ let trigger = predict_edits_request_trigger_from_editor_trigger(trigger);
- let Some((jump_buffer, jump_position)) = Self::next_diagnostic_location(
- active_buffer,
- &snapshot,
- diagnostic_search_range,
- cursor_point,
- &project,
+ self.queue_prediction_refresh(project.clone(), buffer.entity_id(), cx, move |this, cx| {
+ let Some(request_task) = this
+ .update(cx, |this, cx| {
+ this.request_prediction_internal(
+ project.clone(),
+ buffer.clone(),
+ position,
+ trigger,
cx,
)
- .await?
- else {
- return anyhow::Ok(None);
- };
-
- let Some(prediction_result) = this
- .update(cx, |this, cx| {
- this.request_prediction_internal(
- project.clone(),
- jump_buffer.clone(),
- jump_position,
- PredictEditsRequestTrigger::Diagnostics,
- cx.has_flag::<EditPredictionJumpsFeatureFlag>(),
- cx,
- )
- })?
- .await?
- else {
- return anyhow::Ok(None);
- };
-
- this.update(cx, |this, cx| {
- Some((
- if this
- .get_or_init_project(&project, cx)
- .current_prediction
- .is_none()
- {
- prediction_result
- } else {
- EditPredictionResult {
- reject_reason: Some(
- EditPredictionRejectReason::CurrentPreferred,
- ),
- ..prediction_result
- }
- },
- PredictionRequestedBy::DiagnosticsUpdate,
- ))
- })
})
- },
- );
- }
-
- fn predictions_enabled_at(
- snapshot: &BufferSnapshot,
- position: Option<language::Anchor>,
- cx: &App,
- ) -> bool {
- let file = snapshot.file();
- let all_settings = all_language_settings(file, cx);
- if !all_settings.show_edit_predictions(snapshot.language(), cx)
- || file.is_some_and(|file| !all_settings.edit_predictions_enabled_for_file(file, cx))
- {
- return false;
- }
-
- if let Some(last_position) = position {
- let settings = snapshot.settings_at(last_position, cx);
-
- if !settings.edit_predictions_disabled_in.is_empty()
- && let Some(scope) = snapshot.language_scope_at(last_position)
- && let Some(scope_name) = scope.override_name()
- && settings
- .edit_predictions_disabled_in
- .iter()
- .any(|s| s == scope_name)
- {
- return false;
- }
- }
+ .log_err()
+ else {
+ return Task::ready(anyhow::Ok(None));
+ };
- true
+ cx.spawn(async move |_cx| {
+ request_task.await.map(|prediction_result| {
+ prediction_result
+ .map(|prediction_result| (prediction_result, buffer.entity_id()))
+ })
+ })
+ })
}
pub const THROTTLE_TIMEOUT: Duration = Duration::from_millis(300);
@@ -2665,29 +2452,14 @@ impl EditPredictionStore {
fn queue_prediction_refresh(
&mut self,
project: Entity<Project>,
- request_trigger: PredictEditsRequestTrigger,
throttle_entity: EntityId,
cx: &mut Context<Self>,
do_refresh: impl FnOnce(
WeakEntity<Self>,
&mut AsyncApp,
- )
- -> Task<Result<Option<(EditPredictionResult, PredictionRequestedBy)>>>
+ ) -> Task<Result<Option<(EditPredictionResult, EntityId)>>>
+ 'static,
) {
- fn select_throttle(
- project_state: &mut ProjectState,
- request_trigger: PredictEditsRequestTrigger,
- ) -> &mut Option<(EntityId, Instant)> {
- match request_trigger {
- PredictEditsRequestTrigger::Diagnostics
- | PredictEditsRequestTrigger::DiagnosticNavigation => {
- &mut project_state.last_jump_prediction_refresh
- }
- _ => &mut project_state.last_edit_prediction_refresh,
- }
- }
-
let (needs_acceptance_tracking, max_pending_predictions) =
match all_language_settings(None, cx).edit_predictions.provider {
EditPredictionProvider::Zed | EditPredictionProvider::Mercury => (true, 2),
@@ -2706,13 +2478,13 @@ impl EditPredictionStore {
let project_state = self.get_or_init_project(&project, cx);
let pending_prediction_id = project_state.next_pending_prediction_id;
project_state.next_pending_prediction_id += 1;
- let throttle_at_enqueue = *select_throttle(project_state, request_trigger);
+ let throttle_at_enqueue = project_state.last_edit_prediction_refresh;
let task = cx.spawn(async move |this, cx| {
let throttle_wait = this
.update(cx, |this, cx| {
let project_state = this.get_or_init_project(&project, cx);
- let throttle = *select_throttle(project_state, request_trigger);
+ let throttle = project_state.last_edit_prediction_refresh;
let now = cx.background_executor().now();
throttle.and_then(|(last_entity, last_timestamp)| {
@@ -2743,12 +2515,12 @@ impl EditPredictionStore {
}
// Another request has been already sent since this was enqueued
- if *select_throttle(project_state, request_trigger) != throttle_at_enqueue {
+ if project_state.last_edit_prediction_refresh != throttle_at_enqueue {
return;
}
let new_refresh = (throttle_entity, cx.background_executor().now());
- *select_throttle(project_state, request_trigger) = Some(new_refresh);
+ project_state.last_edit_prediction_refresh = Some(new_refresh);
is_cancelled = false;
})
.ok();
@@ -2908,7 +2680,6 @@ impl EditPredictionStore {
active_buffer.clone(),
position,
trigger,
- cx.has_flag::<EditPredictionJumpsFeatureFlag>(),
cx,
)
}
@@ -2919,7 +2690,6 @@ impl EditPredictionStore {
active_buffer: Entity<Buffer>,
position: language::Anchor,
trigger: PredictEditsRequestTrigger,
- allow_jump: bool,
cx: &mut Context<Self>,
) -> Task<Result<Option<EditPredictionResult>>> {
let is_cloud_zeta = matches!(self.edit_prediction_model, EditPredictionModel::Zeta)
@@ -2953,7 +2723,6 @@ impl EditPredictionStore {
.as_ref()
.map(|last_event| last_event.new_snapshot.clone()),
});
- let has_events = !stored_events.is_empty();
let events: Vec<Arc<zeta_prompt::Event>> =
stored_events.iter().map(|e| e.event.clone()).collect();
let debug_tx = project_state.debug_tx.clone();
@@ -3053,148 +2822,7 @@ impl EditPredictionStore {
}
};
- cx.spawn(async move |this, cx| {
- let prediction = task.await?;
-
- // Only fall back to diagnostics-based prediction if we got a
- // the model had nothing to suggest for the buffer
- if prediction.is_none()
- && allow_jump
- && has_events
- && !matches!(
- trigger,
- PredictEditsRequestTrigger::Diagnostics
- | PredictEditsRequestTrigger::DiagnosticNavigation
- )
- {
- this.update(cx, |this, cx| {
- this.refresh_prediction_from_diagnostics(
- project,
- DiagnosticSearchScope::Local,
- cx,
- );
- })?;
- return anyhow::Ok(None);
- }
-
- Ok(prediction)
- })
- }
-
- pub(crate) async fn next_diagnostic_location(
- active_buffer: Entity<Buffer>,
- active_buffer_snapshot: &BufferSnapshot,
- active_buffer_diagnostic_search_range: Range<Point>,
- active_buffer_cursor_point: Point,
- project: &Entity<Project>,
- cx: &mut AsyncApp,
- ) -> Result<Option<(Entity<Buffer>, language::Anchor)>> {
- let collaborator_cursor_rows: Vec<u32> = active_buffer_snapshot
- .selections_in_range(
- Anchor::min_max_range_for_buffer(active_buffer_snapshot.remote_id()),
- false,
- )
- .flat_map(|(_, _, _, selections)| {
- selections.map(|s| s.head().to_point(active_buffer_snapshot).row)
- })
- .collect();
-
- let mut jump_location = active_buffer_snapshot
- .diagnostic_groups(None)
- .into_iter()
- .filter_map(|(_, group)| {
- let range = &group.entries[group.primary_ix]
- .range
- .to_point(&active_buffer_snapshot);
- if range.overlaps(&active_buffer_diagnostic_search_range) {
- return None;
- }
- let near_collaborator = collaborator_cursor_rows.iter().any(|&collab_row| {
- range.start.row.abs_diff(collab_row) <= DIAGNOSTIC_LINES_RANGE
- });
- let near_local = active_buffer_cursor_point.row.abs_diff(range.start.row)
- <= DIAGNOSTIC_LINES_RANGE;
- if near_collaborator && !near_local {
- return None;
- }
- Some(range.start)
- })
- .min_by_key(|probe| probe.row.abs_diff(active_buffer_cursor_point.row))
- .map(|position| {
- (
- active_buffer.clone(),
- active_buffer_snapshot.anchor_before(position),
- )
- });
-
- if jump_location.is_none() {
- let active_buffer_path = active_buffer.read_with(cx, |buffer, cx| {
- let file = buffer.file()?;
-
- Some(ProjectPath {
- worktree_id: file.worktree_id(cx),
- path: file.path().clone(),
- })
- });
-
- let mut candidates: Vec<(ProjectPath, usize)> = project.read_with(cx, |project, cx| {
- project
- .diagnostic_summaries(false, cx)
- .filter(|(path, _, _)| Some(path) != active_buffer_path.as_ref())
- .map(|(path, _, _)| {
- let shared_prefix = path
- .path
- .components()
- .zip(
- active_buffer_path
- .as_ref()
- .map(|p| p.path.components())
- .unwrap_or_default(),
- )
- .take_while(|(a, b)| a == b)
- .count();
- (path, shared_prefix)
- })
- .collect()
- });
-
- candidates.sort_by_key(|c| std::cmp::Reverse(c.1));
-
- for (path, _) in candidates {
- let candidate_buffer = project
- .update(cx, |project, cx| project.open_buffer(path, cx))
- .await?;
-
- let (has_collaborators, diagnostic_position) =
- candidate_buffer.read_with(cx, |buffer, _cx| {
- let snapshot = buffer.snapshot();
- let has_collaborators = snapshot
- .selections_in_range(
- Anchor::min_max_range_for_buffer(snapshot.remote_id()),
- false,
- )
- .next()
- .is_some();
- let position = buffer
- .buffer_diagnostics(None)
- .into_iter()
- .min_by_key(|entry| entry.diagnostic.severity)
- .map(|entry| entry.range.start);
- (has_collaborators, position)
- });
-
- if has_collaborators {
- continue;
- }
-
- if let Some(position) = diagnostic_position {
- jump_location = Some((candidate_buffer, position));
- break;
- }
- }
- }
-
- anyhow::Ok(jump_location)
+ task
}
async fn send_raw_llm_request(
diff --git a/crates/edit_prediction/src/edit_prediction_tests.rs b/crates/edit_prediction/src/edit_prediction_tests.rs
index 1ef96d84af5..bf9ed2c2052 100644
--- a/crates/edit_prediction/src/edit_prediction_tests.rs
+++ b/crates/edit_prediction/src/edit_prediction_tests.rs
@@ -24,8 +24,8 @@ use gpui::{
};
use indoc::indoc;
use language::{
- Anchor, Buffer, BufferEditSource, Capability, CursorShape, Diagnostic, DiagnosticEntry,
- DiagnosticSet, DiagnosticSeverity, Operation, Point, Selection, SelectionGoal,
+ Anchor, Buffer, Capability, Diagnostic, DiagnosticEntry, DiagnosticSet, DiagnosticSeverity,
+ Point,
};
use lsp::LanguageServerId;
use parking_lot::Mutex;
@@ -46,15 +46,13 @@ use zeta_prompt::ZetaPromptInput;
use crate::udiff::apply_diff_to_string;
use crate::{
BufferEditPrediction, EDIT_PREDICTION_SETTLED_QUIESCENCE, EditPredictionId,
- EditPredictionJumpsFeatureFlag, EditPredictionStore, REJECT_REQUEST_DEBOUNCE,
- REQUEST_TIMEOUT_BACKOFF,
+ EditPredictionStore, REJECT_REQUEST_DEBOUNCE, REQUEST_TIMEOUT_BACKOFF,
};
use super::*;
#[gpui::test]
async fn test_current_state(cx: &mut TestAppContext) {
- enable_edit_prediction_jumps(cx);
let (ep_store, mut requests) = init_test_with_fake_client(cx);
let fs = FakeFs::new(cx.executor());
fs.insert_tree(
@@ -123,89 +121,16 @@ async fn test_current_state(cx: &mut TestAppContext) {
ep_store.update(cx, |ep_store, cx| {
ep_store.reject_current_prediction(EditPredictionRejectReason::Discarded, &project, cx);
});
-
- // Prediction for diagnostic in another file
-
- let diagnostic = lsp::Diagnostic {
- range: lsp::Range::new(lsp::Position::new(1, 1), lsp::Position::new(1, 5)),
- severity: Some(lsp::DiagnosticSeverity::ERROR),
- message: "Sentence is incomplete".to_string(),
- ..Default::default()
- };
-
- project.update(cx, |project, cx| {
- project.lsp_store().update(cx, |lsp_store, cx| {
- lsp_store
- .update_diagnostics(
- LanguageServerId(0),
- lsp::PublishDiagnosticsParams {
- uri: lsp::Uri::from_file_path(path!("/root/2.txt")).unwrap(),
- diagnostics: vec![diagnostic],
- version: None,
- },
- None,
- language::DiagnosticSourceKind::Pushed,
- &[],
- cx,
- )
- .unwrap();
- });
- });
-
- let (request, respond_tx) = requests.predict.next().await.unwrap();
- respond_tx
- .send(model_response(
- &request,
- indoc! {r#"
- --- a/root/2.txt
- +++ b/root/2.txt
- @@ ... @@
- Hola!
- -Como
- +Como estas?
- Adios
- "#},
- ))
- .unwrap();
- cx.run_until_parked();
-
- ep_store.update(cx, |ep_store, cx| {
- let prediction = ep_store
- .prediction_at(&buffer1, None, &project, cx)
- .unwrap();
- assert_matches!(
- prediction,
- BufferEditPrediction::Jump { prediction } if prediction.snapshot.file().unwrap().full_path(cx) == Path::new(path!("root/2.txt"))
- );
- });
-
- let buffer2 = project
- .update(cx, |project, cx| {
- let path = project.find_project_path(path!("root/2.txt"), cx).unwrap();
- project.open_buffer(path, cx)
- })
- .await
- .unwrap();
-
- ep_store.update(cx, |ep_store, cx| {
- let prediction = ep_store
- .prediction_at(&buffer2, None, &project, cx)
- .unwrap();
- assert_matches!(prediction, BufferEditPrediction::Local { .. });
- });
}
#[gpui::test]
-async fn test_diagnostics_refresh_suppressed_while_following(cx: &mut TestAppContext) {
- enable_edit_prediction_jumps(cx);
+async fn test_refresh_prediction_from_buffer_suppressed_while_following(cx: &mut TestAppContext) {
let (ep_store, mut requests) = init_test_with_fake_client(cx);
-
let fs = FakeFs::new(cx.executor());
fs.insert_tree(
"/root",
json!({
- "1.txt": "Hello!\nHow\nBye\n",
- "2.txt": "Hola!\nComo\nAdios\n"
+ "foo.md": "Hello!\nHow\nBye\n"
}),
)
.await;
@@ -216,7 +141,6 @@ async fn test_diagnostics_refresh_suppressed_while_following(cx: &mut TestAppCon
AppState::set_global(app_state.clone(), cx);
app_state
});
-
let multi_workspace =
cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
let workspace = multi_workspace
@@ -225,198 +149,41 @@ async fn test_diagnostics_refresh_suppressed_while_following(cx: &mut TestAppCon
cx.update(|cx| {
AppState::set_global(workspace.read(cx).app_state().clone(), cx);
});
- let _ = app_state;
+ drop(app_state);
- let buffer1 = project
+ let buffer = project
.update(cx, |project, cx| {
- let path = project.find_project_path(path!("root/1.txt"), cx).unwrap();
- project.set_active_path(Some(path.clone()), cx);
+ let path = project.find_project_path(path!("root/foo.md"), cx).unwrap();
project.open_buffer(path, cx)
})
.await
.unwrap();
- let snapshot1 = buffer1.read_with(cx, |buffer, _cx| buffer.snapshot());
- let position = snapshot1.anchor_before(language::Point::new(1, 3));
+ let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
+ let position = snapshot.anchor_before(language::Point::new(1, 3));
+
+ multi_workspace
+ .update(cx, |multi_workspace, window, cx| {
+ multi_workspace.workspace().update(cx, |workspace, cx| {
+ workspace.start_following(CollaboratorId::Agent, window, cx);
+ });
+ })
+ .unwrap();
+ cx.run_until_parked();
ep_store.update(cx, |ep_store, cx| {
ep_store.register_project(&project, cx);
- ep_store.register_buffer(&buffer1, &project, cx);
+ ep_store.register_buffer(&buffer, &project, cx);
ep_store.refresh_prediction_from_buffer(
project.clone(),
- buffer1.clone(),
+ buffer.clone(),
position,
EditPredictionRequestTrigger::Other,
cx,
);
});
-
- let (request, respond_tx) = requests.predict.next().await.unwrap();
- respond_tx
- .send(model_response(
- &request,
- indoc! {r"
- --- a/root/1.txt
- +++ b/root/1.txt
- @@ ... @@
- Hello!
- -How
- +How are you?
- Bye
- "},
- ))
- .unwrap();
- cx.run_until_parked();
-
- ep_store.update(cx, |ep_store, cx| {
- ep_store.reject_current_prediction(EditPredictionRejectReason::Discarded, &project, cx);
- });
-
- let _ = multi_workspace.update(cx, |multi_workspace, window, cx| {
- multi_workspace.workspace().update(cx, |workspace, cx| {
- workspace.start_following(CollaboratorId::Agent, window, cx);
- });
- });
- cx.run_until_parked();
-
- let diagnostic = lsp::Diagnostic {
- range: lsp::Range::new(lsp::Position::new(1, 1), lsp::Position::new(1, 5)),
- severity: Some(lsp::DiagnosticSeverity::ERROR),
- message: "Sentence is incomplete".to_string(),
- ..Default::default()
- };
-
- project.update(cx, |project, cx| {
- project.lsp_store().update(cx, |lsp_store, cx| {
- lsp_store
- .update_diagnostics(
- LanguageServerId(0),
- lsp::PublishDiagnosticsParams {
- uri: lsp::Uri::from_file_path(path!("/root/2.txt")).unwrap(),
- diagnostics: vec![diagnostic.clone()],
- version: None,
- },
- None,
- language::DiagnosticSourceKind::Pushed,
- &[],
- cx,
- )
- .unwrap();
- });
- });
-
- cx.run_until_parked();
- assert_no_predict_request_ready(&mut requests.predict);
-
- let _ = multi_workspace.update(cx, |multi_workspace, window, cx| {
- multi_workspace.workspace().update(cx, |workspace, cx| {
- workspace.unfollow(CollaboratorId::Agent, window, cx);
- });
- });
- cx.run_until_parked();
-
- project.update(cx, |project, cx| {
- project.lsp_store().update(cx, |lsp_store, cx| {
- lsp_store
- .update_diagnostics(
- LanguageServerId(0),
- lsp::PublishDiagnosticsParams {
- uri: lsp::Uri::from_file_path(path!("/root/2.txt")).unwrap(),
- diagnostics: vec![diagnostic],
- version: None,
- },
- None,
- language::DiagnosticSourceKind::Pushed,
- &[],
- cx,
- )
- .unwrap();
- });
- });
-
- let (request, respond_tx) = requests.predict.next().await.unwrap();
- respond_tx
- .send(model_response(
- &request,
- indoc! {r#"
- --- a/root/2.txt
- +++ b/root/2.txt
- @@ ... @@
- Hola!
- -Como
- +Como estas?
- Adios
- "#},
- ))
- .unwrap();
- cx.run_until_parked();
-
- ep_store.update(cx, |ep_store, cx| {
- let prediction = ep_store
- .prediction_at(&buffer1, None, &project, cx)
- .unwrap();
- assert_matches!(
- prediction,
- BufferEditPrediction::Jump { prediction } if prediction.snapshot.file().unwrap().full_path(cx) == Path::new(path!("root/2.txt"))
- );
- });
-}
-
-#[gpui::test]
-async fn test_diagnostics_refresh_suppressed_after_agent_edit(cx: &mut TestAppContext) {
- enable_edit_prediction_jumps(cx);
- let (ep_store, mut requests) = init_test_with_fake_client(cx);
-
- let fs = FakeFs::new(cx.executor());
- fs.insert_tree(
- "/root",
- json!({
- "1.txt": "Hello!\nHow\nBye\n",
- "2.txt": "Hola!\nComo\nAdios\n"
- }),
- )
- .await;
- let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
-
- let buffer = project
- .update(cx, |project, cx| {
- let path = project.find_project_path(path!("root/1.txt"), cx).unwrap();
- project.set_active_path(Some(path.clone()), cx);
- project.open_buffer(path, cx)
- })
- .await
- .unwrap();
-
- ep_store.update(cx, |ep_store, cx| {
- ep_store.register_project(&project, cx);
- ep_store.register_buffer(&buffer, &project, cx);
- });
-
- buffer.update(cx, |buffer, cx| {
- buffer.start_transaction();
- buffer.edit([(Point::new(1, 3)..Point::new(1, 3), "!")], None, cx);
- buffer.end_transaction_with_source(BufferEditSource::Agent, cx);
- });
cx.run_until_parked();
- update_test_diagnostics(&project, path!("/root/2.txt"), "Sentence is incomplete", cx);
- cx.run_until_parked();
assert_no_predict_request_ready(&mut requests.predict);
-
- buffer.update(cx, |buffer, cx| {
- buffer.edit([(Point::new(1, 4)..Point::new(1, 4), "?")], None, cx);
- });
- cx.run_until_parked();
-
- update_test_diagnostics(
- &project,
- path!("/root/2.txt"),
- "Sentence is still incomplete",
- cx,
- );
-
- let (_request, respond_tx) = requests.predict.next().await.unwrap();
- respond_tx.send(empty_response()).unwrap();
- cx.run_until_parked();
}
#[gpui::test]
@@ -2066,120 +1833,6 @@ async fn test_cancel_second_on_third_request(cx: &mut TestAppContext) {
);
}
-#[gpui::test]
-async fn test_jump_and_edit_throttles_are_independent(cx: &mut TestAppContext) {
- enable_edit_prediction_jumps(cx);
- let (ep_store, mut requests) = init_test_with_fake_client(cx);
-
- let fs = FakeFs::new(cx.executor());
- fs.insert_tree(
- "/root",
- json!({
- "foo.md": "Hello!\nHow\nBye\n",
- "bar.md": "Hola!\nComo\nAdios\n"
- }),
- )
- .await;
- let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
-
- let buffer = project
- .update(cx, |project, cx| {
- let path = project.find_project_path(path!("root/foo.md"), cx).unwrap();
- project.set_active_path(Some(path.clone()), cx);
- project.open_buffer(path, cx)
- })
- .await
- .unwrap();
- let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
- let position = snapshot.anchor_before(language::Point::new(1, 3));
-
- ep_store.update(cx, |ep_store, cx| {
- ep_store.register_project(&project, cx);
- ep_store.register_buffer(&buffer, &project, cx);
- });
-
- // First edit request - no prior edit, so not throttled.
- ep_store.update(cx, |ep_store, cx| {
- ep_store.refresh_prediction_from_buffer(
- project.clone(),
- buffer.clone(),
- position,
- EditPredictionRequestTrigger::Other,
- cx,
- );
- });
- let (_edit_request, edit_response_tx) = requests.predict.next().await.unwrap();
- edit_response_tx.send(empty_response()).unwrap();
- cx.run_until_parked();
-
- let diagnostic = lsp::Diagnostic {
- range: lsp::Range::new(lsp::Position::new(1, 1), lsp::Position::new(1, 5)),
- severity: Some(lsp::DiagnosticSeverity::ERROR),
- message: "Sentence is incomplete".to_string(),
- ..Default::default()
- };
-
- // First jump request triggered by diagnostic event on buffer - no prior jump, so not throttled (independent from edit).
- project.update(cx, |project, cx| {
- project.lsp_store().update(cx, |lsp_store, cx| {
- lsp_store
- .update_diagnostics(
- LanguageServerId(0),
- lsp::PublishDiagnosticsParams {
- uri: lsp::Uri::from_file_path(path!("/root/bar.md")).unwrap(),
- diagnostics: vec![diagnostic],
- version: None,
- },
- None,
- language::DiagnosticSourceKind::Pushed,
- &[],
- cx,
- )
- .unwrap();
- });
- });
- let (_jump_request, jump_response_tx) = requests.predict.next().await.unwrap();
- jump_response_tx.send(empty_response()).unwrap();
- cx.run_until_parked();
-
- // Second edit request - should be throttled by the first edit.
- ep_store.update(cx, |ep_store, cx| {
- ep_store.refresh_prediction_from_buffer(
- project.clone(),
- buffer.clone(),
- position,
- EditPredictionRequestTrigger::Other,
- cx,
- );
- });
- assert_no_predict_request_ready(&mut requests.predict);
-
- // Second jump request - should be throttled by the first jump.
- ep_store.update(cx, |ep_store, cx| {
- ep_store.refresh_prediction_from_diagnostics(
- project.clone(),
- DiagnosticSearchScope::Global,
- cx,
- );
- });
- assert_no_predict_request_ready(&mut requests.predict);
-
- // Wait for both throttles to expire.
- cx.background_executor
- .advance_clock(EditPredictionStore::THROTTLE_TIMEOUT);
- cx.background_executor.run_until_parked();
- cx.run_until_parked();
-
- // Both requests should now go through.
- let (_request_1, response_tx_1) = requests.predict.next().await.unwrap();
- response_tx_1.send(empty_response()).unwrap();
- cx.run_until_parked();
-
- let (_request_2, response_tx_2) = requests.predict.next().await.unwrap();
- response_tx_2.send(empty_response()).unwrap();
- cx.run_until_parked();
-}
-
#[gpui::test]
async fn test_cloud_timeout_backs_off_zeta_requests(cx: &mut TestAppContext) {
let (ep_store, mut requests) = init_test_with_fake_client(cx);
@@ -2784,45 +2437,6 @@ fn assert_no_predict_request_ready(
}
}
-fn enable_edit_prediction_jumps(cx: &mut TestAppContext) {
- cx.update(|cx| {
- cx.update_flags(true, vec![EditPredictionJumpsFeatureFlag::NAME.to_string()]);
- });
-}
-
-fn update_test_diagnostics(
- project: &Entity<Project>,
- path: &str,
- message: &str,
- cx: &mut TestAppContext,
-) {
- let diagnostic = lsp::Diagnostic {
- range: lsp::Range::new(lsp::Position::new(1, 1), lsp::Position::new(1, 5)),
- severity: Some(lsp::DiagnosticSeverity::ERROR),
- message: message.to_string(),
- ..Default::default()
- };
-
- project.update(cx, |project, cx| {
- project.lsp_store().update(cx, |lsp_store, cx| {
- lsp_store
- .update_diagnostics(
- LanguageServerId(0),
- lsp::PublishDiagnosticsParams {
- uri: lsp::Uri::from_file_path(path).unwrap(),
- diagnostics: vec![diagnostic],
- version: None,
- },
- None,
- language::DiagnosticSourceKind::Pushed,
- &[],
- cx,
- )
- .unwrap();
- });
- });
-}
-
struct RequestChannels {
predict: mpsc::UnboundedReceiver<(
PredictEditsV3Request,
@@ -3555,222 +3169,6 @@ async fn test_unauthenticated_without_custom_url_blocks_prediction_impl(cx: &mut
assert_eq!(request_count.load(std::sync::atomic::Ordering::SeqCst), 0);
}
-#[gpui::test]
-async fn test_diagnostic_jump_excludes_collaborator_regions(cx: &mut TestAppContext) {
- fn set_collaborator_cursor(buffer: &Entity<Buffer>, row: u32, cx: &mut TestAppContext) {
- let collab_replica = clock::ReplicaId::new(10);
- let anchor = buffer.read_with(cx, |buffer, _| {
- buffer.snapshot().anchor_before(Point::new(row, 0))
- });
- let selections: Arc<[Selection<Anchor>]> = Arc::new([Selection {
- id: 1,
- start: anchor,
- end: anchor,
- reversed: false,
- goal: SelectionGoal::None,
- }]);
- buffer.update(cx, |buffer, cx| {
- buffer.apply_ops(
- [Operation::UpdateSelections {
- selections,
- lamport_timestamp: clock::Lamport {
- replica_id: collab_replica,
- value: 1,
- },
- line_mode: false,
- cursor_shape: CursorShape::Bar,
- }],
- cx,
- );
- });
- }
-
- fn publish_diagnostics(
- uri_path: &'static str,
- rows: &[u32],
- project: &Entity<Project>,
- cx: &mut TestAppContext,
- ) {
- let diagnostics: Vec<_> = rows
- .iter()
- .map(|&row| lsp::Diagnostic {
- range: lsp::Range::new(lsp::Position::new(row, 0), lsp::Position::new(row, 5)),
- severity: Some(lsp::DiagnosticSeverity::ERROR),
- message: format!("error at row {row}"),
- ..Default::default()
- })
- .collect();
- project.update(cx, |project, cx| {
- project.lsp_store().update(cx, |lsp_store, cx| {
- lsp_store
- .update_diagnostics(
- LanguageServerId(0),
- lsp::PublishDiagnosticsParams {
- uri: lsp::Uri::from_file_path(uri_path).expect("invalid uri"),
- diagnostics,
- version: None,
- },
- None,
- language::DiagnosticSourceKind::Pushed,
- &[],
- cx,
- )
- .expect("failed to update diagnostics");
- });
- });
- }
-
- init_test(cx);
-
- let mut lines = String::new();
- for i in 0..60 {
- lines.push_str(&format!("line {i}\n"));
- }
-
- let fs = FakeFs::new(cx.executor());
- fs.insert_tree(
- "/root",
- json!({
- "active.txt": lines,
- "collab_file.txt": "error here\nsecond line\n",
- "free_file.txt": "another error\nsecond line\n",
- }),
- )
- .await;
- let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
-
- let active_buffer = project
- .update(cx, |project, cx| {
- let path = project
- .find_project_path(path!("/root/active.txt"), cx)
- .expect("active.txt not found");
- project.set_active_path(Some(path.clone()), cx);
- project.open_buffer(path, cx)
- })
- .await
- .expect("failed to open active buffer");
-
- set_collaborator_cursor(&active_buffer, 5, cx);
-
- publish_diagnostics(path!("/root/active.txt"), &[3, 25, 50], &project, cx);
-
- cx.run_until_parked();
-
- let cursor_point = Point::new(25, 0);
- let empty_search_range: Range<Point> = Default::default();
-
- let snapshot = active_buffer.read_with(cx, |buffer, _| buffer.snapshot());
- let result = EditPredictionStore::next_diagnostic_location(
- active_buffer.clone(),
- &snapshot,
- empty_search_range.clone(),
- cursor_point,
- &project,
- &mut cx.to_async(),
- )
- .await
- .expect("next_diagnostic_location failed");
-
- let (result_buffer, result_anchor) = result.expect("expected a diagnostic location");
- assert_eq!(result_buffer.entity_id(), active_buffer.entity_id());
- let result_row = result_buffer.read_with(cx, |buffer, _| {
- result_anchor.to_point(&buffer.snapshot()).row
- });
- assert_ne!(
- result_row, 3,
- "row 3 is near collaborator (row 5) but far from local cursor (row 25), should be excluded"
- );
- assert!(
- result_row == 25 || result_row == 50,
- "expected row 25 or 50, got {result_row}"
- );
-
- let snapshot_near = active_buffer.read_with(cx, |buffer, _| buffer.snapshot());
- let near_cursor_point = Point::new(4, 0);
- let result_near = EditPredictionStore::next_diagnostic_location(
- active_buffer.clone(),
- &snapshot_near,
- empty_search_range.clone(),
- near_cursor_point,
- &project,
- &mut cx.to_async(),
- )
- .await
- .expect("next_diagnostic_location failed");
-
- let (_, near_anchor) = result_near.expect("expected a diagnostic location when both are near");
- let near_row =
- active_buffer.read_with(cx, |buffer, _| near_anchor.to_point(&buffer.snapshot()).row);
- assert_eq!(
- near_row, 3,
- "row 3 should be included when local cursor (row 4) is also near the collaborator"
- );
-
- let snapshot_far = active_buffer.read_with(cx, |buffer, _| buffer.snapshot());
- let far_cursor_point = Point::new(50, 0);
- let result_far = EditPredictionStore::next_diagnostic_location(
- active_buffer.clone(),
- &snapshot_far,
- empty_search_range.clone(),
- far_cursor_point,
- &project,
- &mut cx.to_async(),
- )
- .await
- .expect("next_diagnostic_location failed");
-
- let (_, far_anchor) = result_far.expect("expected a diagnostic location");
- let far_row =
- active_buffer.read_with(cx, |buffer, _| far_anchor.to_point(&buffer.snapshot()).row);
- assert_eq!(
- far_row, 50,
- "row 50 is near local cursor (row 50) and far from collaborator, should be picked"
- );
-
- publish_diagnostics(path!("/root/collab_file.txt"), &[0], &project, cx);
- publish_diagnostics(path!("/root/free_file.txt"), &[0], &project, cx);
- cx.run_until_parked();
-
- let collab_buffer = project
- .update(cx, |project, cx| {
- let path = project
- .find_project_path(path!("/root/collab_file.txt"), cx)
- .expect("collab_file.txt not found");
- project.open_buffer(path, cx)
- })
- .await
- .expect("failed to open collab buffer");
-
- set_collaborator_cursor(&collab_buffer, 0, cx);
- cx.run_until_parked();
-
- let no_same_file_search_range = Point::new(0, 0)..Point::new(59, 0);
- let snapshot_cross = active_buffer.read_with(cx, |buffer, _| buffer.snapshot());
- let result_cross = EditPredictionStore::next_diagnostic_location(
- active_buffer.clone(),
- &snapshot_cross,
- no_same_file_search_range,
- Point::new(0, 0),
- &project,
- &mut cx.to_async(),
- )
- .await
- .expect("cross-file next_diagnostic_location failed");
-
- let (cross_buffer, _) = result_cross.expect("expected a cross-file diagnostic location");
- let cross_path = cross_buffer.read_with(cx, |buffer, cx| {
- buffer
- .file()
- .expect("buffer should have a file")
- .full_path(cx)
- });
- assert_eq!(
- cross_path,
- Path::new(path!("root/free_file.txt")),
- "should skip collab_file.txt (has collaborator) and pick free_file.txt"
- );
-}
-
#[gpui::test]
async fn test_edit_prediction_settled(cx: &mut TestAppContext) {
let (ep_store, _requests) = init_test_with_fake_client(cx);