1use super::*;
2use crate::udiff::apply_diff_to_string;
3use client::{UserStore, test::FakeServer};
4use clock::FakeSystemClock;
5use clock::ReplicaId;
6use cloud_api_types::{CreateLlmTokenResponse, LlmToken};
7use cloud_llm_client::{
8 EditPredictionRejectReason, EditPredictionRejection, RejectEditPredictionsBody,
9 predict_edits_v3::{PredictEditsV3Request, PredictEditsV3Response},
10};
11
12use futures::{
13 AsyncReadExt, FutureExt, StreamExt,
14 channel::{mpsc, oneshot},
15};
16use gpui::App;
17use gpui::{
18 Entity, TestAppContext,
19 http_client::{FakeHttpClient, Response},
20};
21use indoc::indoc;
22use language::{
23 Anchor, Buffer, Capability, CursorShape, Diagnostic, DiagnosticEntry, DiagnosticSet,
24 DiagnosticSeverity, Operation, Point, Selection, SelectionGoal,
25};
26use language_model::RefreshLlmTokenListener;
27use lsp::LanguageServerId;
28use parking_lot::Mutex;
29use pretty_assertions::{assert_eq, assert_matches};
30use project::{FakeFs, Project};
31use serde_json::json;
32use settings::SettingsStore;
33use std::{ops::Range, path::Path, sync::Arc, time::Duration};
34use util::{
35 path,
36 test::{TextRangeMarker, marked_text_ranges_by},
37};
38use uuid::Uuid;
39use workspace::{AppState, CollaboratorId, MultiWorkspace};
40use zeta_prompt::ZetaPromptInput;
41
42use crate::{
43 BufferEditPrediction, EDIT_PREDICTION_SETTLED_QUIESCENCE, EditPredictionId,
44 EditPredictionJumpsFeatureFlag, EditPredictionStore, REJECT_REQUEST_DEBOUNCE,
45};
46
47#[gpui::test]
48async fn test_current_state(cx: &mut TestAppContext) {
49 let (ep_store, mut requests) = init_test_with_fake_client(cx);
50 let fs = FakeFs::new(cx.executor());
51 fs.insert_tree(
52 "/root",
53 json!({
54 "1.txt": "Hello!\nHow\nBye\n",
55 "2.txt": "Hola!\nComo\nAdios\n"
56 }),
57 )
58 .await;
59 let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
60
61 let buffer1 = project
62 .update(cx, |project, cx| {
63 let path = project.find_project_path(path!("/root/1.txt"), cx).unwrap();
64 project.set_active_path(Some(path.clone()), cx);
65 project.open_buffer(path, cx)
66 })
67 .await
68 .unwrap();
69 let snapshot1 = buffer1.read_with(cx, |buffer, _cx| buffer.snapshot());
70 let position = snapshot1.anchor_before(language::Point::new(1, 3));
71
72 ep_store.update(cx, |ep_store, cx| {
73 ep_store.register_project(&project, cx);
74 ep_store.register_buffer(&buffer1, &project, cx);
75 });
76
77 // Prediction for current file
78
79 ep_store.update(cx, |ep_store, cx| {
80 ep_store.refresh_prediction_from_buffer(project.clone(), buffer1.clone(), position, cx)
81 });
82 let (request, respond_tx) = requests.predict.next().await.unwrap();
83
84 respond_tx
85 .send(model_response(
86 &request,
87 indoc! {r"
88 --- a/root/1.txt
89 +++ b/root/1.txt
90 @@ ... @@
91 Hello!
92 -How
93 +How are you?
94 Bye
95 "},
96 ))
97 .unwrap();
98
99 cx.run_until_parked();
100
101 ep_store.update(cx, |ep_store, cx| {
102 let prediction = ep_store
103 .prediction_at(&buffer1, None, &project, cx)
104 .unwrap();
105 assert_matches!(prediction, BufferEditPrediction::Local { .. });
106 });
107
108 ep_store.update(cx, |ep_store, cx| {
109 ep_store.reject_current_prediction(EditPredictionRejectReason::Discarded, &project, cx);
110 });
111
112 // Prediction for diagnostic in another file
113
114 let diagnostic = lsp::Diagnostic {
115 range: lsp::Range::new(lsp::Position::new(1, 1), lsp::Position::new(1, 5)),
116 severity: Some(lsp::DiagnosticSeverity::ERROR),
117 message: "Sentence is incomplete".to_string(),
118 ..Default::default()
119 };
120
121 project.update(cx, |project, cx| {
122 project.lsp_store().update(cx, |lsp_store, cx| {
123 lsp_store
124 .update_diagnostics(
125 LanguageServerId(0),
126 lsp::PublishDiagnosticsParams {
127 uri: lsp::Uri::from_file_path(path!("/root/2.txt")).unwrap(),
128 diagnostics: vec![diagnostic],
129 version: None,
130 },
131 None,
132 language::DiagnosticSourceKind::Pushed,
133 &[],
134 cx,
135 )
136 .unwrap();
137 });
138 });
139
140 let (request, respond_tx) = requests.predict.next().await.unwrap();
141 respond_tx
142 .send(model_response(
143 &request,
144 indoc! {r#"
145 --- a/root/2.txt
146 +++ b/root/2.txt
147 @@ ... @@
148 Hola!
149 -Como
150 +Como estas?
151 Adios
152 "#},
153 ))
154 .unwrap();
155 cx.run_until_parked();
156
157 ep_store.update(cx, |ep_store, cx| {
158 let prediction = ep_store
159 .prediction_at(&buffer1, None, &project, cx)
160 .unwrap();
161 assert_matches!(
162 prediction,
163 BufferEditPrediction::Jump { prediction } if prediction.snapshot.file().unwrap().full_path(cx) == Path::new(path!("root/2.txt"))
164 );
165 });
166
167 let buffer2 = project
168 .update(cx, |project, cx| {
169 let path = project.find_project_path(path!("root/2.txt"), cx).unwrap();
170 project.open_buffer(path, cx)
171 })
172 .await
173 .unwrap();
174
175 ep_store.update(cx, |ep_store, cx| {
176 let prediction = ep_store
177 .prediction_at(&buffer2, None, &project, cx)
178 .unwrap();
179 assert_matches!(prediction, BufferEditPrediction::Local { .. });
180 });
181}
182
183#[gpui::test]
184async fn test_diagnostics_refresh_suppressed_while_following(cx: &mut TestAppContext) {
185 let (ep_store, mut requests) = init_test_with_fake_client(cx);
186
187 cx.update(|cx| {
188 cx.update_flags(
189 false,
190 vec![EditPredictionJumpsFeatureFlag::NAME.to_string()],
191 );
192 });
193
194 let fs = FakeFs::new(cx.executor());
195 fs.insert_tree(
196 "/root",
197 json!({
198 "1.txt": "Hello!\nHow\nBye\n",
199 "2.txt": "Hola!\nComo\nAdios\n"
200 }),
201 )
202 .await;
203 let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
204
205 let app_state = cx.update(|cx| {
206 let app_state = AppState::test(cx);
207 AppState::set_global(Arc::downgrade(&app_state), cx);
208 app_state
209 });
210
211 let multi_workspace =
212 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
213 let workspace = multi_workspace
214 .read_with(cx, |multi_workspace, _| multi_workspace.workspace().clone())
215 .unwrap();
216 cx.update(|cx| {
217 AppState::set_global(Arc::downgrade(workspace.read(cx).app_state()), cx);
218 });
219 let _ = app_state;
220
221 let buffer1 = project
222 .update(cx, |project, cx| {
223 let path = project.find_project_path(path!("root/1.txt"), cx).unwrap();
224 project.set_active_path(Some(path.clone()), cx);
225 project.open_buffer(path, cx)
226 })
227 .await
228 .unwrap();
229 let snapshot1 = buffer1.read_with(cx, |buffer, _cx| buffer.snapshot());
230 let position = snapshot1.anchor_before(language::Point::new(1, 3));
231
232 ep_store.update(cx, |ep_store, cx| {
233 ep_store.register_project(&project, cx);
234 ep_store.register_buffer(&buffer1, &project, cx);
235 ep_store.refresh_prediction_from_buffer(project.clone(), buffer1.clone(), position, cx);
236 });
237
238 let (request, respond_tx) = requests.predict.next().await.unwrap();
239 respond_tx
240 .send(model_response(
241 &request,
242 indoc! {r"
243 --- a/root/1.txt
244 +++ b/root/1.txt
245 @@ ... @@
246 Hello!
247 -How
248 +How are you?
249 Bye
250 "},
251 ))
252 .unwrap();
253 cx.run_until_parked();
254
255 ep_store.update(cx, |ep_store, cx| {
256 ep_store.reject_current_prediction(EditPredictionRejectReason::Discarded, &project, cx);
257 });
258
259 let _ = multi_workspace.update(cx, |multi_workspace, window, cx| {
260 multi_workspace.workspace().update(cx, |workspace, cx| {
261 workspace.start_following(CollaboratorId::Agent, window, cx);
262 });
263 });
264 cx.run_until_parked();
265
266 let diagnostic = lsp::Diagnostic {
267 range: lsp::Range::new(lsp::Position::new(1, 1), lsp::Position::new(1, 5)),
268 severity: Some(lsp::DiagnosticSeverity::ERROR),
269 message: "Sentence is incomplete".to_string(),
270 ..Default::default()
271 };
272
273 project.update(cx, |project, cx| {
274 project.lsp_store().update(cx, |lsp_store, cx| {
275 lsp_store
276 .update_diagnostics(
277 LanguageServerId(0),
278 lsp::PublishDiagnosticsParams {
279 uri: lsp::Uri::from_file_path(path!("/root/2.txt")).unwrap(),
280 diagnostics: vec![diagnostic.clone()],
281 version: None,
282 },
283 None,
284 language::DiagnosticSourceKind::Pushed,
285 &[],
286 cx,
287 )
288 .unwrap();
289 });
290 });
291
292 cx.run_until_parked();
293 assert_no_predict_request_ready(&mut requests.predict);
294
295 let _ = multi_workspace.update(cx, |multi_workspace, window, cx| {
296 multi_workspace.workspace().update(cx, |workspace, cx| {
297 workspace.unfollow(CollaboratorId::Agent, window, cx);
298 });
299 });
300 cx.run_until_parked();
301
302 project.update(cx, |project, cx| {
303 project.lsp_store().update(cx, |lsp_store, cx| {
304 lsp_store
305 .update_diagnostics(
306 LanguageServerId(0),
307 lsp::PublishDiagnosticsParams {
308 uri: lsp::Uri::from_file_path(path!("/root/2.txt")).unwrap(),
309 diagnostics: vec![diagnostic],
310 version: None,
311 },
312 None,
313 language::DiagnosticSourceKind::Pushed,
314 &[],
315 cx,
316 )
317 .unwrap();
318 });
319 });
320
321 let (request, respond_tx) = requests.predict.next().await.unwrap();
322 respond_tx
323 .send(model_response(
324 &request,
325 indoc! {r#"
326 --- a/root/2.txt
327 +++ b/root/2.txt
328 @@ ... @@
329 Hola!
330 -Como
331 +Como estas?
332 Adios
333 "#},
334 ))
335 .unwrap();
336 cx.run_until_parked();
337
338 ep_store.update(cx, |ep_store, cx| {
339 let prediction = ep_store
340 .prediction_at(&buffer1, None, &project, cx)
341 .unwrap();
342 assert_matches!(
343 prediction,
344 BufferEditPrediction::Jump { prediction } if prediction.snapshot.file().unwrap().full_path(cx) == Path::new(path!("root/2.txt"))
345 );
346 });
347}
348
349#[gpui::test]
350async fn test_simple_request(cx: &mut TestAppContext) {
351 let (ep_store, mut requests) = init_test_with_fake_client(cx);
352 let fs = FakeFs::new(cx.executor());
353 fs.insert_tree(
354 "/root",
355 json!({
356 "foo.md": "Hello!\nHow\nBye\n"
357 }),
358 )
359 .await;
360 let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
361
362 let buffer = project
363 .update(cx, |project, cx| {
364 let path = project.find_project_path(path!("root/foo.md"), cx).unwrap();
365 project.open_buffer(path, cx)
366 })
367 .await
368 .unwrap();
369 let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
370 let position = snapshot.anchor_before(language::Point::new(1, 3));
371
372 let prediction_task = ep_store.update(cx, |ep_store, cx| {
373 ep_store.request_prediction(&project, &buffer, position, Default::default(), cx)
374 });
375
376 let (request, respond_tx) = requests.predict.next().await.unwrap();
377
378 // TODO Put back when we have a structured request again
379 // assert_eq!(
380 // request.excerpt_path.as_ref(),
381 // Path::new(path!("root/foo.md"))
382 // );
383 // assert_eq!(
384 // request.cursor_point,
385 // Point {
386 // line: Line(1),
387 // column: 3
388 // }
389 // );
390
391 respond_tx
392 .send(model_response(
393 &request,
394 indoc! { r"
395 --- a/root/foo.md
396 +++ b/root/foo.md
397 @@ ... @@
398 Hello!
399 -How
400 +How are you?
401 Bye
402 "},
403 ))
404 .unwrap();
405
406 let prediction = prediction_task.await.unwrap().unwrap().prediction.unwrap();
407
408 assert_eq!(prediction.edits.len(), 1);
409 assert_eq!(
410 prediction.edits[0].0.to_point(&snapshot).start,
411 language::Point::new(1, 3)
412 );
413 assert_eq!(prediction.edits[0].1.as_ref(), " are you?");
414}
415
416#[gpui::test]
417async fn test_request_events(cx: &mut TestAppContext) {
418 let (ep_store, mut requests) = init_test_with_fake_client(cx);
419 let fs = FakeFs::new(cx.executor());
420 fs.insert_tree(
421 "/root",
422 json!({
423 "foo.md": "Hello!\n\nBye\n"
424 }),
425 )
426 .await;
427 let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
428
429 let buffer = project
430 .update(cx, |project, cx| {
431 let path = project.find_project_path(path!("root/foo.md"), cx).unwrap();
432 project.open_buffer(path, cx)
433 })
434 .await
435 .unwrap();
436
437 ep_store.update(cx, |ep_store, cx| {
438 ep_store.register_buffer(&buffer, &project, cx);
439 });
440
441 buffer.update(cx, |buffer, cx| {
442 buffer.edit(vec![(7..7, "How")], None, cx);
443 });
444
445 let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
446 let position = snapshot.anchor_before(language::Point::new(1, 3));
447
448 let prediction_task = ep_store.update(cx, |ep_store, cx| {
449 ep_store.request_prediction(&project, &buffer, position, Default::default(), cx)
450 });
451
452 let (request, respond_tx) = requests.predict.next().await.unwrap();
453
454 let prompt = prompt_from_request(&request);
455 assert!(
456 prompt.contains(indoc! {"
457 --- a/root/foo.md
458 +++ b/root/foo.md
459 @@ -1,3 +1,3 @@
460 Hello!
461 -
462 +How
463 Bye
464 "}),
465 "{prompt}"
466 );
467
468 respond_tx
469 .send(model_response(
470 &request,
471 indoc! {r#"
472 --- a/root/foo.md
473 +++ b/root/foo.md
474 @@ ... @@
475 Hello!
476 -How
477 +How are you?
478 Bye
479 "#},
480 ))
481 .unwrap();
482
483 let prediction = prediction_task.await.unwrap().unwrap().prediction.unwrap();
484
485 assert_eq!(prediction.edits.len(), 1);
486 assert_eq!(prediction.edits[0].1.as_ref(), " are you?");
487}
488
489#[gpui::test]
490async fn test_edit_history_getter_pause_splits_last_event(cx: &mut TestAppContext) {
491 let (ep_store, _requests) = init_test_with_fake_client(cx);
492 let fs = FakeFs::new(cx.executor());
493 fs.insert_tree(
494 "/root",
495 json!({
496 "foo.md": "Hello!\n\nBye\n"
497 }),
498 )
499 .await;
500 let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
501
502 let buffer = project
503 .update(cx, |project, cx| {
504 let path = project.find_project_path(path!("root/foo.md"), cx).unwrap();
505 project.open_buffer(path, cx)
506 })
507 .await
508 .unwrap();
509
510 ep_store.update(cx, |ep_store, cx| {
511 ep_store.register_buffer(&buffer, &project, cx);
512 });
513
514 // First burst: insert "How"
515 buffer.update(cx, |buffer, cx| {
516 buffer.edit(vec![(7..7, "How")], None, cx);
517 });
518
519 // Simulate a pause longer than the grouping threshold (e.g. 500ms).
520 cx.executor().advance_clock(LAST_CHANGE_GROUPING_TIME * 2);
521 cx.run_until_parked();
522
523 // Second burst: append " are you?" immediately after "How" on the same line.
524 //
525 // Keeping both bursts on the same line ensures the existing line-span coalescing logic
526 // groups them into a single `LastEvent`, allowing the pause-split getter to return two diffs.
527 buffer.update(cx, |buffer, cx| {
528 buffer.edit(vec![(10..10, " are you?")], None, cx);
529 });
530
531 // A second edit shortly after the first post-pause edit ensures the last edit timestamp is
532 // advanced after the pause boundary is recorded, making pause-splitting deterministic.
533 buffer.update(cx, |buffer, cx| {
534 buffer.edit(vec![(19..19, "!")], None, cx);
535 });
536
537 // With time-based splitting, there are two distinct events.
538 let events = ep_store.update(cx, |ep_store, cx| {
539 ep_store.edit_history_for_project(&project, cx)
540 });
541 assert_eq!(events.len(), 2);
542
543 let first_total_edit_range = buffer.read_with(cx, |buffer, _| {
544 events[0].total_edit_range.to_point(&buffer.snapshot())
545 });
546 assert_eq!(first_total_edit_range, Point::new(1, 0)..Point::new(1, 3));
547
548 let zeta_prompt::Event::BufferChange { diff, .. } = events[0].event.as_ref();
549 assert_eq!(
550 diff.as_str(),
551 indoc! {"
552 @@ -1,3 +1,3 @@
553 Hello!
554 -
555 +How
556 Bye
557 "}
558 );
559
560 let second_total_edit_range = buffer.read_with(cx, |buffer, _| {
561 events[1].total_edit_range.to_point(&buffer.snapshot())
562 });
563 assert_eq!(second_total_edit_range, Point::new(1, 3)..Point::new(1, 13));
564
565 let zeta_prompt::Event::BufferChange { diff, .. } = events[1].event.as_ref();
566 assert_eq!(
567 diff.as_str(),
568 indoc! {"
569 @@ -1,3 +1,3 @@
570 Hello!
571 -How
572 +How are you?!
573 Bye
574 "}
575 );
576}
577
578#[gpui::test]
579async fn test_predicted_edits_are_separated_in_edit_history(cx: &mut TestAppContext) {
580 let (ep_store, _requests) = init_test_with_fake_client(cx);
581 let fs = FakeFs::new(cx.executor());
582
583 // Create a file with 30 lines to test line-based coalescing
584 let content = (1..=30)
585 .map(|i| format!("Line {}\n", i))
586 .collect::<String>();
587 fs.insert_tree(
588 "/root",
589 json!({
590 "foo.md": content
591 }),
592 )
593 .await;
594 let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
595
596 let buffer = project
597 .update(cx, |project, cx| {
598 let path = project.find_project_path(path!("root/foo.md"), cx).unwrap();
599 project.open_buffer(path, cx)
600 })
601 .await
602 .unwrap();
603
604 ep_store.update(cx, |ep_store, cx| {
605 ep_store.register_buffer(&buffer, &project, cx);
606 });
607
608 // First edit: multi-line edit spanning rows 10-12 (replacing lines 11-13)
609 buffer.update(cx, |buffer, cx| {
610 let start = Point::new(10, 0).to_offset(buffer);
611 let end = Point::new(13, 0).to_offset(buffer);
612 buffer.edit(vec![(start..end, "Middle A\nMiddle B\n")], None, cx);
613 });
614
615 let events = ep_store.update(cx, |ep_store, cx| {
616 ep_store.edit_history_for_project(&project, cx)
617 });
618 assert_eq!(
619 render_events(&events),
620 indoc! {"
621 @@ -8,9 +8,8 @@
622 Line 8
623 Line 9
624 Line 10
625 -Line 11
626 -Line 12
627 -Line 13
628 +Middle A
629 +Middle B
630 Line 14
631 Line 15
632 Line 16
633 "},
634 "After first edit"
635 );
636
637 // Second edit: insert ABOVE the first edit's range (row 5, within 8 lines of row 10)
638 // This tests that coalescing considers the START of the existing range
639 buffer.update(cx, |buffer, cx| {
640 let offset = Point::new(5, 0).to_offset(buffer);
641 buffer.edit(vec![(offset..offset, "Above\n")], None, cx);
642 });
643
644 let events = ep_store.update(cx, |ep_store, cx| {
645 ep_store.edit_history_for_project(&project, cx)
646 });
647 assert_eq!(
648 render_events(&events),
649 indoc! {"
650 @@ -3,14 +3,14 @@
651 Line 3
652 Line 4
653 Line 5
654 +Above
655 Line 6
656 Line 7
657 Line 8
658 Line 9
659 Line 10
660 -Line 11
661 -Line 12
662 -Line 13
663 +Middle A
664 +Middle B
665 Line 14
666 Line 15
667 Line 16
668 "},
669 "After inserting above (should coalesce)"
670 );
671
672 // Third edit: insert BELOW the first edit's range (row 14 in current buffer, within 8 lines of row 12)
673 // This tests that coalescing considers the END of the existing range
674 buffer.update(cx, |buffer, cx| {
675 let offset = Point::new(14, 0).to_offset(buffer);
676 buffer.edit(vec![(offset..offset, "Below\n")], None, cx);
677 });
678
679 let events = ep_store.update(cx, |ep_store, cx| {
680 ep_store.edit_history_for_project(&project, cx)
681 });
682 assert_eq!(
683 render_events(&events),
684 indoc! {"
685 @@ -3,15 +3,16 @@
686 Line 3
687 Line 4
688 Line 5
689 +Above
690 Line 6
691 Line 7
692 Line 8
693 Line 9
694 Line 10
695 -Line 11
696 -Line 12
697 -Line 13
698 +Middle A
699 +Middle B
700 Line 14
701 +Below
702 Line 15
703 Line 16
704 Line 17
705 "},
706 "After inserting below (should coalesce)"
707 );
708
709 // Fourth edit: insert FAR BELOW (row 25, beyond 8 lines from the current range end ~row 15)
710 // This should NOT coalesce - creates a new event
711 buffer.update(cx, |buffer, cx| {
712 let offset = Point::new(25, 0).to_offset(buffer);
713 buffer.edit(vec![(offset..offset, "Far below\n")], None, cx);
714 });
715
716 let events = ep_store.update(cx, |ep_store, cx| {
717 ep_store.edit_history_for_project(&project, cx)
718 });
719 assert_eq!(
720 render_events(&events),
721 indoc! {"
722 @@ -3,15 +3,16 @@
723 Line 3
724 Line 4
725 Line 5
726 +Above
727 Line 6
728 Line 7
729 Line 8
730 Line 9
731 Line 10
732 -Line 11
733 -Line 12
734 -Line 13
735 +Middle A
736 +Middle B
737 Line 14
738 +Below
739 Line 15
740 Line 16
741 Line 17
742
743 ---
744 @@ -23,6 +23,7 @@
745 Line 22
746 Line 23
747 Line 24
748 +Far below
749 Line 25
750 Line 26
751 Line 27
752 "},
753 "After inserting far below (should NOT coalesce)"
754 );
755}
756
757fn render_events(events: &[StoredEvent]) -> String {
758 events
759 .iter()
760 .map(|e| {
761 let zeta_prompt::Event::BufferChange { diff, .. } = e.event.as_ref();
762 diff.as_str()
763 })
764 .collect::<Vec<_>>()
765 .join("\n---\n")
766}
767
768fn render_events_with_predicted(events: &[StoredEvent]) -> Vec<String> {
769 events
770 .iter()
771 .map(|e| {
772 let zeta_prompt::Event::BufferChange {
773 diff, predicted, ..
774 } = e.event.as_ref();
775 let prefix = if *predicted { "predicted" } else { "manual" };
776 format!("{}\n{}", prefix, diff)
777 })
778 .collect()
779}
780
781fn make_collaborator_replica(
782 buffer: &Entity<Buffer>,
783 cx: &mut TestAppContext,
784) -> (Entity<Buffer>, clock::Global) {
785 let (state, version) =
786 buffer.read_with(cx, |buffer, _cx| (buffer.to_proto(_cx), buffer.version()));
787 let collaborator = cx.new(|_cx| {
788 Buffer::from_proto(ReplicaId::new(1), Capability::ReadWrite, state, None).unwrap()
789 });
790 (collaborator, version)
791}
792
793async fn apply_collaborator_edit(
794 collaborator: &Entity<Buffer>,
795 buffer: &Entity<Buffer>,
796 since_version: &mut clock::Global,
797 edit_range: Range<usize>,
798 new_text: &str,
799 cx: &mut TestAppContext,
800) {
801 collaborator.update(cx, |collaborator, cx| {
802 collaborator.edit([(edit_range, new_text)], None, cx);
803 });
804
805 let serialize_task = collaborator.read_with(cx, |collaborator, cx| {
806 collaborator.serialize_ops(Some(since_version.clone()), cx)
807 });
808 let ops = serialize_task.await;
809 *since_version = collaborator.read_with(cx, |collaborator, _cx| collaborator.version());
810
811 buffer.update(cx, |buffer, cx| {
812 buffer.apply_ops(
813 ops.into_iter()
814 .map(|op| language::proto::deserialize_operation(op).unwrap()),
815 cx,
816 );
817 });
818}
819
820#[gpui::test]
821async fn test_nearby_collaborator_edits_are_kept_in_history(cx: &mut TestAppContext) {
822 let (ep_store, _requests) = init_test_with_fake_client(cx);
823 let fs = FakeFs::new(cx.executor());
824 fs.insert_tree(
825 "/root",
826 json!({
827 "foo.rs": "line 0\nline 1\nline 2\nline 3\nline 4\nline 5\nline 6\nline 7\nline 8\nline 9\nline 10\nline 11\nline 12\nline 13\nline 14\n"
828 }),
829 )
830 .await;
831 let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
832
833 let buffer = project
834 .update(cx, |project, cx| {
835 let path = project.find_project_path(path!("root/foo.rs"), cx).unwrap();
836 project.set_active_path(Some(path.clone()), cx);
837 project.open_buffer(path, cx)
838 })
839 .await
840 .unwrap();
841
842 let cursor = buffer.read_with(cx, |buffer, _cx| buffer.anchor_before(Point::new(1, 0)));
843
844 ep_store.update(cx, |ep_store, cx| {
845 ep_store.register_buffer(&buffer, &project, cx);
846 let _ = ep_store.prediction_at(&buffer, Some(cursor), &project, cx);
847 });
848
849 buffer.update(cx, |buffer, cx| {
850 buffer.edit(vec![(0..6, "LOCAL ZERO")], None, cx);
851 });
852
853 let (collaborator, mut collaborator_version) = make_collaborator_replica(&buffer, cx);
854
855 let (line_one_start, line_one_len) = collaborator.read_with(cx, |buffer, _cx| {
856 (Point::new(1, 0).to_offset(buffer), buffer.line_len(1))
857 });
858
859 apply_collaborator_edit(
860 &collaborator,
861 &buffer,
862 &mut collaborator_version,
863 line_one_start..line_one_start + line_one_len as usize,
864 "REMOTE ONE",
865 cx,
866 )
867 .await;
868
869 let events = ep_store.update(cx, |ep_store, cx| {
870 ep_store.edit_history_for_project(&project, cx)
871 });
872
873 assert_eq!(
874 render_events_with_predicted(&events),
875 vec![indoc! {"
876 manual
877 @@ -1,5 +1,5 @@
878 -line 0
879 -line 1
880 +LOCAL ZERO
881 +REMOTE ONE
882 line 2
883 line 3
884 line 4
885 "}]
886 );
887}
888
889#[gpui::test]
890async fn test_distant_collaborator_edits_are_omitted_from_history(cx: &mut TestAppContext) {
891 let (ep_store, _requests) = init_test_with_fake_client(cx);
892 let fs = FakeFs::new(cx.executor());
893 fs.insert_tree(
894 "/root",
895 json!({
896 "foo.rs": (0..1000)
897 .map(|i| format!("line {i}\n"))
898 .collect::<String>()
899 }),
900 )
901 .await;
902 let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
903
904 let buffer = project
905 .update(cx, |project, cx| {
906 let path = project.find_project_path(path!("root/foo.rs"), cx).unwrap();
907 project.set_active_path(Some(path.clone()), cx);
908 project.open_buffer(path, cx)
909 })
910 .await
911 .unwrap();
912
913 let cursor = buffer.read_with(cx, |buffer, _cx| buffer.anchor_before(Point::new(1, 0)));
914
915 ep_store.update(cx, |ep_store, cx| {
916 ep_store.register_buffer(&buffer, &project, cx);
917 let _ = ep_store.prediction_at(&buffer, Some(cursor), &project, cx);
918 });
919
920 buffer.update(cx, |buffer, cx| {
921 buffer.edit(vec![(0..6, "LOCAL ZERO")], None, cx);
922 });
923
924 let (collaborator, mut collaborator_version) = make_collaborator_replica(&buffer, cx);
925
926 let far_line_start = buffer.read_with(cx, |buffer, _cx| Point::new(900, 0).to_offset(buffer));
927
928 apply_collaborator_edit(
929 &collaborator,
930 &buffer,
931 &mut collaborator_version,
932 far_line_start..far_line_start + 7,
933 "REMOTE FAR",
934 cx,
935 )
936 .await;
937
938 let events = ep_store.update(cx, |ep_store, cx| {
939 ep_store.edit_history_for_project(&project, cx)
940 });
941
942 assert_eq!(
943 render_events_with_predicted(&events),
944 vec![indoc! {"
945 manual
946 @@ -1,4 +1,4 @@
947 -line 0
948 +LOCAL ZERO
949 line 1
950 line 2
951 line 3
952 "}]
953 );
954}
955
956#[gpui::test]
957async fn test_irrelevant_collaborator_edits_in_different_files_are_omitted_from_history(
958 cx: &mut TestAppContext,
959) {
960 let (ep_store, _requests) = init_test_with_fake_client(cx);
961 let fs = FakeFs::new(cx.executor());
962 fs.insert_tree(
963 "/root",
964 json!({
965 "foo.rs": "line 0\nline 1\nline 2\nline 3\n",
966 "bar.rs": "line 0\nline 1\nline 2\nline 3\n"
967 }),
968 )
969 .await;
970 let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
971
972 let foo_buffer = project
973 .update(cx, |project, cx| {
974 let path = project.find_project_path(path!("root/foo.rs"), cx).unwrap();
975 project.set_active_path(Some(path.clone()), cx);
976 project.open_buffer(path, cx)
977 })
978 .await
979 .unwrap();
980 let bar_buffer = project
981 .update(cx, |project, cx| {
982 let path = project.find_project_path(path!("root/bar.rs"), cx).unwrap();
983 project.open_buffer(path, cx)
984 })
985 .await
986 .unwrap();
987
988 let foo_cursor = foo_buffer.read_with(cx, |buffer, _cx| buffer.anchor_before(Point::new(1, 0)));
989
990 ep_store.update(cx, |ep_store, cx| {
991 ep_store.register_buffer(&foo_buffer, &project, cx);
992 ep_store.register_buffer(&bar_buffer, &project, cx);
993 let _ = ep_store.prediction_at(&foo_buffer, Some(foo_cursor), &project, cx);
994 });
995
996 let (bar_collaborator, mut bar_version) = make_collaborator_replica(&bar_buffer, cx);
997
998 apply_collaborator_edit(
999 &bar_collaborator,
1000 &bar_buffer,
1001 &mut bar_version,
1002 0..6,
1003 "REMOTE BAR",
1004 cx,
1005 )
1006 .await;
1007
1008 let events = ep_store.update(cx, |ep_store, cx| {
1009 ep_store.edit_history_for_project(&project, cx)
1010 });
1011
1012 assert!(events.is_empty());
1013}
1014
1015#[gpui::test]
1016async fn test_predicted_flag_coalescing(cx: &mut TestAppContext) {
1017 let (ep_store, _requests) = init_test_with_fake_client(cx);
1018 let fs = FakeFs::new(cx.executor());
1019 fs.insert_tree(
1020 "/root",
1021 json!({
1022 "foo.rs": "line 0\nline 1\nline 2\nline 3\nline 4\nline 5\nline 6\nline 7\nline 8\nline 9\nline 10\nline 11\nline 12\nline 13\nline 14\n"
1023 }),
1024 )
1025 .await;
1026 let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
1027
1028 let buffer = project
1029 .update(cx, |project, cx| {
1030 let path = project.find_project_path(path!("root/foo.rs"), cx).unwrap();
1031 project.open_buffer(path, cx)
1032 })
1033 .await
1034 .unwrap();
1035
1036 ep_store.update(cx, |ep_store, cx| {
1037 ep_store.register_buffer(&buffer, &project, cx);
1038 });
1039
1040 // Case 1: Manual edits have `predicted` set to false.
1041 buffer.update(cx, |buffer, cx| {
1042 buffer.edit(vec![(0..6, "LINE ZERO")], None, cx);
1043 });
1044
1045 let events = ep_store.update(cx, |ep_store, cx| {
1046 ep_store.edit_history_for_project(&project, cx)
1047 });
1048
1049 assert_eq!(
1050 render_events_with_predicted(&events),
1051 vec![indoc! {"
1052 manual
1053 @@ -1,4 +1,4 @@
1054 -line 0
1055 +LINE ZERO
1056 line 1
1057 line 2
1058 line 3
1059 "}]
1060 );
1061
1062 // Case 2: Multiple successive manual edits near each other are merged into one
1063 // event with `predicted` set to false.
1064 buffer.update(cx, |buffer, cx| {
1065 let offset = Point::new(1, 0).to_offset(buffer);
1066 let end = Point::new(1, 6).to_offset(buffer);
1067 buffer.edit(vec![(offset..end, "LINE ONE")], None, cx);
1068 });
1069
1070 let events = ep_store.update(cx, |ep_store, cx| {
1071 ep_store.edit_history_for_project(&project, cx)
1072 });
1073 assert_eq!(
1074 render_events_with_predicted(&events),
1075 vec![indoc! {"
1076 manual
1077 @@ -1,5 +1,5 @@
1078 -line 0
1079 -line 1
1080 +LINE ZERO
1081 +LINE ONE
1082 line 2
1083 line 3
1084 line 4
1085 "}]
1086 );
1087
1088 // Case 3: Accepted predictions have `predicted` set to true.
1089 // Case 5: A manual edit that follows a predicted edit is not merged with the
1090 // predicted edit, even if it is nearby.
1091 ep_store.update(cx, |ep_store, cx| {
1092 buffer.update(cx, |buffer, cx| {
1093 let offset = Point::new(2, 0).to_offset(buffer);
1094 let end = Point::new(2, 6).to_offset(buffer);
1095 buffer.edit(vec![(offset..end, "LINE TWO")], None, cx);
1096 });
1097 ep_store.report_changes_for_buffer(&buffer, &project, true, true, cx);
1098 });
1099
1100 let events = ep_store.update(cx, |ep_store, cx| {
1101 ep_store.edit_history_for_project(&project, cx)
1102 });
1103 assert_eq!(
1104 render_events_with_predicted(&events),
1105 vec![
1106 indoc! {"
1107 manual
1108 @@ -1,5 +1,5 @@
1109 -line 0
1110 -line 1
1111 +LINE ZERO
1112 +LINE ONE
1113 line 2
1114 line 3
1115 line 4
1116 "},
1117 indoc! {"
1118 predicted
1119 @@ -1,6 +1,6 @@
1120 LINE ZERO
1121 LINE ONE
1122 -line 2
1123 +LINE TWO
1124 line 3
1125 line 4
1126 line 5
1127 "}
1128 ]
1129 );
1130
1131 // Case 4: Multiple successive accepted predictions near each other are merged
1132 // into one event with `predicted` set to true.
1133 ep_store.update(cx, |ep_store, cx| {
1134 buffer.update(cx, |buffer, cx| {
1135 let offset = Point::new(3, 0).to_offset(buffer);
1136 let end = Point::new(3, 6).to_offset(buffer);
1137 buffer.edit(vec![(offset..end, "LINE THREE")], None, cx);
1138 });
1139 ep_store.report_changes_for_buffer(&buffer, &project, true, true, cx);
1140 });
1141
1142 let events = ep_store.update(cx, |ep_store, cx| {
1143 ep_store.edit_history_for_project(&project, cx)
1144 });
1145 assert_eq!(
1146 render_events_with_predicted(&events),
1147 vec![
1148 indoc! {"
1149 manual
1150 @@ -1,5 +1,5 @@
1151 -line 0
1152 -line 1
1153 +LINE ZERO
1154 +LINE ONE
1155 line 2
1156 line 3
1157 line 4
1158 "},
1159 indoc! {"
1160 predicted
1161 @@ -1,7 +1,7 @@
1162 LINE ZERO
1163 LINE ONE
1164 -line 2
1165 -line 3
1166 +LINE TWO
1167 +LINE THREE
1168 line 4
1169 line 5
1170 line 6
1171 "}
1172 ]
1173 );
1174
1175 // Case 5 (continued): A manual edit that follows a predicted edit is not merged
1176 // with the predicted edit, even if it is nearby.
1177 buffer.update(cx, |buffer, cx| {
1178 let offset = Point::new(4, 0).to_offset(buffer);
1179 let end = Point::new(4, 6).to_offset(buffer);
1180 buffer.edit(vec![(offset..end, "LINE FOUR")], None, cx);
1181 });
1182
1183 let events = ep_store.update(cx, |ep_store, cx| {
1184 ep_store.edit_history_for_project(&project, cx)
1185 });
1186 assert_eq!(
1187 render_events_with_predicted(&events),
1188 vec![
1189 indoc! {"
1190 manual
1191 @@ -1,5 +1,5 @@
1192 -line 0
1193 -line 1
1194 +LINE ZERO
1195 +LINE ONE
1196 line 2
1197 line 3
1198 line 4
1199 "},
1200 indoc! {"
1201 predicted
1202 @@ -1,7 +1,7 @@
1203 LINE ZERO
1204 LINE ONE
1205 -line 2
1206 -line 3
1207 +LINE TWO
1208 +LINE THREE
1209 line 4
1210 line 5
1211 line 6
1212 "},
1213 indoc! {"
1214 manual
1215 @@ -2,7 +2,7 @@
1216 LINE ONE
1217 LINE TWO
1218 LINE THREE
1219 -line 4
1220 +LINE FOUR
1221 line 5
1222 line 6
1223 line 7
1224 "}
1225 ]
1226 );
1227
1228 // Case 6: If we then perform a manual edit at a *different* location (more than
1229 // 8 lines away), then the edits at the prior location can be merged with each
1230 // other, even if some are predicted and some are not. `predicted` means all
1231 // constituent edits were predicted.
1232 buffer.update(cx, |buffer, cx| {
1233 let offset = Point::new(14, 0).to_offset(buffer);
1234 let end = Point::new(14, 7).to_offset(buffer);
1235 buffer.edit(vec![(offset..end, "LINE FOURTEEN")], None, cx);
1236 });
1237
1238 let events = ep_store.update(cx, |ep_store, cx| {
1239 ep_store.edit_history_for_project(&project, cx)
1240 });
1241 assert_eq!(
1242 render_events_with_predicted(&events),
1243 vec![
1244 indoc! {"
1245 manual
1246 @@ -1,8 +1,8 @@
1247 -line 0
1248 -line 1
1249 -line 2
1250 -line 3
1251 -line 4
1252 +LINE ZERO
1253 +LINE ONE
1254 +LINE TWO
1255 +LINE THREE
1256 +LINE FOUR
1257 line 5
1258 line 6
1259 line 7
1260 "},
1261 indoc! {"
1262 manual
1263 @@ -12,4 +12,4 @@
1264 line 11
1265 line 12
1266 line 13
1267 -line 14
1268 +LINE FOURTEEN
1269 "}
1270 ]
1271 );
1272}
1273
1274#[gpui::test]
1275async fn test_empty_prediction(cx: &mut TestAppContext) {
1276 let (ep_store, mut requests) = init_test_with_fake_client(cx);
1277 let fs = FakeFs::new(cx.executor());
1278 fs.insert_tree(
1279 "/root",
1280 json!({
1281 "foo.md": "Hello!\nHow\nBye\n"
1282 }),
1283 )
1284 .await;
1285 let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
1286
1287 let buffer = project
1288 .update(cx, |project, cx| {
1289 let path = project.find_project_path(path!("root/foo.md"), cx).unwrap();
1290 project.open_buffer(path, cx)
1291 })
1292 .await
1293 .unwrap();
1294 let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
1295 let position = snapshot.anchor_before(language::Point::new(1, 3));
1296
1297 ep_store.update(cx, |ep_store, cx| {
1298 ep_store.refresh_prediction_from_buffer(project.clone(), buffer.clone(), position, cx);
1299 });
1300
1301 let (request, respond_tx) = requests.predict.next().await.unwrap();
1302 let response = model_response(&request, "");
1303 let id = response.request_id.clone();
1304 respond_tx.send(response).unwrap();
1305
1306 cx.run_until_parked();
1307
1308 ep_store.update(cx, |ep_store, cx| {
1309 assert!(
1310 ep_store
1311 .prediction_at(&buffer, None, &project, cx)
1312 .is_none()
1313 );
1314 });
1315
1316 // prediction is reported as rejected
1317 let (reject_request, _) = requests.reject.next().await.unwrap();
1318
1319 assert_eq!(
1320 &reject_request.rejections,
1321 &[EditPredictionRejection {
1322 request_id: id,
1323 reason: EditPredictionRejectReason::Empty,
1324 was_shown: false,
1325 model_version: None,
1326 }]
1327 );
1328}
1329
1330#[gpui::test]
1331async fn test_interpolated_empty(cx: &mut TestAppContext) {
1332 let (ep_store, mut requests) = init_test_with_fake_client(cx);
1333 let fs = FakeFs::new(cx.executor());
1334 fs.insert_tree(
1335 "/root",
1336 json!({
1337 "foo.md": "Hello!\nHow\nBye\n"
1338 }),
1339 )
1340 .await;
1341 let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
1342
1343 let buffer = project
1344 .update(cx, |project, cx| {
1345 let path = project.find_project_path(path!("root/foo.md"), cx).unwrap();
1346 project.open_buffer(path, cx)
1347 })
1348 .await
1349 .unwrap();
1350 let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
1351 let position = snapshot.anchor_before(language::Point::new(1, 3));
1352
1353 ep_store.update(cx, |ep_store, cx| {
1354 ep_store.refresh_prediction_from_buffer(project.clone(), buffer.clone(), position, cx);
1355 });
1356
1357 let (request, respond_tx) = requests.predict.next().await.unwrap();
1358
1359 buffer.update(cx, |buffer, cx| {
1360 buffer.set_text("Hello!\nHow are you?\nBye", cx);
1361 });
1362
1363 let response = model_response(&request, SIMPLE_DIFF);
1364 let id = response.request_id.clone();
1365 respond_tx.send(response).unwrap();
1366
1367 cx.run_until_parked();
1368
1369 ep_store.update(cx, |ep_store, cx| {
1370 assert!(
1371 ep_store
1372 .prediction_at(&buffer, None, &project, cx)
1373 .is_none()
1374 );
1375 });
1376
1377 // prediction is reported as rejected
1378 let (reject_request, _) = requests.reject.next().await.unwrap();
1379
1380 assert_eq!(
1381 &reject_request.rejections,
1382 &[EditPredictionRejection {
1383 request_id: id,
1384 reason: EditPredictionRejectReason::InterpolatedEmpty,
1385 was_shown: false,
1386 model_version: None,
1387 }]
1388 );
1389}
1390
1391const SIMPLE_DIFF: &str = indoc! { r"
1392 --- a/root/foo.md
1393 +++ b/root/foo.md
1394 @@ ... @@
1395 Hello!
1396 -How
1397 +How are you?
1398 Bye
1399"};
1400
1401#[gpui::test]
1402async fn test_replace_current(cx: &mut TestAppContext) {
1403 let (ep_store, mut requests) = init_test_with_fake_client(cx);
1404 let fs = FakeFs::new(cx.executor());
1405 fs.insert_tree(
1406 "/root",
1407 json!({
1408 "foo.md": "Hello!\nHow\nBye\n"
1409 }),
1410 )
1411 .await;
1412 let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
1413
1414 let buffer = project
1415 .update(cx, |project, cx| {
1416 let path = project.find_project_path(path!("root/foo.md"), cx).unwrap();
1417 project.open_buffer(path, cx)
1418 })
1419 .await
1420 .unwrap();
1421 let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
1422 let position = snapshot.anchor_before(language::Point::new(1, 3));
1423
1424 ep_store.update(cx, |ep_store, cx| {
1425 ep_store.refresh_prediction_from_buffer(project.clone(), buffer.clone(), position, cx);
1426 });
1427
1428 let (request, respond_tx) = requests.predict.next().await.unwrap();
1429 let first_response = model_response(&request, SIMPLE_DIFF);
1430 let first_id = first_response.request_id.clone();
1431 respond_tx.send(first_response).unwrap();
1432
1433 cx.run_until_parked();
1434
1435 ep_store.update(cx, |ep_store, cx| {
1436 assert_eq!(
1437 ep_store
1438 .prediction_at(&buffer, None, &project, cx)
1439 .unwrap()
1440 .id
1441 .0,
1442 first_id
1443 );
1444 });
1445
1446 // a second request is triggered
1447 ep_store.update(cx, |ep_store, cx| {
1448 ep_store.refresh_prediction_from_buffer(project.clone(), buffer.clone(), position, cx);
1449 });
1450
1451 let (request, respond_tx) = requests.predict.next().await.unwrap();
1452 let second_response = model_response(&request, SIMPLE_DIFF);
1453 let second_id = second_response.request_id.clone();
1454 respond_tx.send(second_response).unwrap();
1455
1456 cx.run_until_parked();
1457
1458 ep_store.update(cx, |ep_store, cx| {
1459 // second replaces first
1460 assert_eq!(
1461 ep_store
1462 .prediction_at(&buffer, None, &project, cx)
1463 .unwrap()
1464 .id
1465 .0,
1466 second_id
1467 );
1468 });
1469
1470 // first is reported as replaced
1471 let (reject_request, _) = requests.reject.next().await.unwrap();
1472
1473 assert_eq!(
1474 &reject_request.rejections,
1475 &[EditPredictionRejection {
1476 request_id: first_id,
1477 reason: EditPredictionRejectReason::Replaced,
1478 was_shown: false,
1479 model_version: None,
1480 }]
1481 );
1482}
1483
1484#[gpui::test]
1485async fn test_current_preferred(cx: &mut TestAppContext) {
1486 let (ep_store, mut requests) = init_test_with_fake_client(cx);
1487 let fs = FakeFs::new(cx.executor());
1488 fs.insert_tree(
1489 "/root",
1490 json!({
1491 "foo.md": "Hello!\nHow\nBye\n"
1492 }),
1493 )
1494 .await;
1495 let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
1496
1497 let buffer = project
1498 .update(cx, |project, cx| {
1499 let path = project.find_project_path(path!("root/foo.md"), cx).unwrap();
1500 project.open_buffer(path, cx)
1501 })
1502 .await
1503 .unwrap();
1504 let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
1505 let position = snapshot.anchor_before(language::Point::new(1, 3));
1506
1507 ep_store.update(cx, |ep_store, cx| {
1508 ep_store.refresh_prediction_from_buffer(project.clone(), buffer.clone(), position, cx);
1509 });
1510
1511 let (request, respond_tx) = requests.predict.next().await.unwrap();
1512 let first_response = model_response(&request, SIMPLE_DIFF);
1513 let first_id = first_response.request_id.clone();
1514 respond_tx.send(first_response).unwrap();
1515
1516 cx.run_until_parked();
1517
1518 ep_store.update(cx, |ep_store, cx| {
1519 assert_eq!(
1520 ep_store
1521 .prediction_at(&buffer, None, &project, cx)
1522 .unwrap()
1523 .id
1524 .0,
1525 first_id
1526 );
1527 });
1528
1529 // a second request is triggered
1530 ep_store.update(cx, |ep_store, cx| {
1531 ep_store.refresh_prediction_from_buffer(project.clone(), buffer.clone(), position, cx);
1532 });
1533
1534 let (request, respond_tx) = requests.predict.next().await.unwrap();
1535 // worse than current prediction
1536 let second_response = model_response(
1537 &request,
1538 indoc! { r"
1539 --- a/root/foo.md
1540 +++ b/root/foo.md
1541 @@ ... @@
1542 Hello!
1543 -How
1544 +How are
1545 Bye
1546 "},
1547 );
1548 let second_id = second_response.request_id.clone();
1549 respond_tx.send(second_response).unwrap();
1550
1551 cx.run_until_parked();
1552
1553 ep_store.update(cx, |ep_store, cx| {
1554 // first is preferred over second
1555 assert_eq!(
1556 ep_store
1557 .prediction_at(&buffer, None, &project, cx)
1558 .unwrap()
1559 .id
1560 .0,
1561 first_id
1562 );
1563 });
1564
1565 // second is reported as rejected
1566 let (reject_request, _) = requests.reject.next().await.unwrap();
1567
1568 assert_eq!(
1569 &reject_request.rejections,
1570 &[EditPredictionRejection {
1571 request_id: second_id,
1572 reason: EditPredictionRejectReason::CurrentPreferred,
1573 was_shown: false,
1574 model_version: None,
1575 }]
1576 );
1577}
1578
1579#[gpui::test]
1580async fn test_cancel_earlier_pending_requests(cx: &mut TestAppContext) {
1581 let (ep_store, mut requests) = init_test_with_fake_client(cx);
1582 let fs = FakeFs::new(cx.executor());
1583 fs.insert_tree(
1584 "/root",
1585 json!({
1586 "foo.md": "Hello!\nHow\nBye\n"
1587 }),
1588 )
1589 .await;
1590 let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
1591
1592 let buffer = project
1593 .update(cx, |project, cx| {
1594 let path = project.find_project_path(path!("root/foo.md"), cx).unwrap();
1595 project.open_buffer(path, cx)
1596 })
1597 .await
1598 .unwrap();
1599 let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
1600 let position = snapshot.anchor_before(language::Point::new(1, 3));
1601
1602 // start two refresh tasks
1603 ep_store.update(cx, |ep_store, cx| {
1604 ep_store.refresh_prediction_from_buffer(project.clone(), buffer.clone(), position, cx);
1605 });
1606
1607 let (request1, respond_first) = requests.predict.next().await.unwrap();
1608
1609 ep_store.update(cx, |ep_store, cx| {
1610 ep_store.refresh_prediction_from_buffer(project.clone(), buffer.clone(), position, cx);
1611 });
1612
1613 let (request, respond_second) = requests.predict.next().await.unwrap();
1614
1615 // wait for throttle
1616 cx.run_until_parked();
1617
1618 // second responds first
1619 let second_response = model_response(&request, SIMPLE_DIFF);
1620 let second_id = second_response.request_id.clone();
1621 respond_second.send(second_response).unwrap();
1622
1623 cx.run_until_parked();
1624
1625 ep_store.update(cx, |ep_store, cx| {
1626 // current prediction is second
1627 assert_eq!(
1628 ep_store
1629 .prediction_at(&buffer, None, &project, cx)
1630 .unwrap()
1631 .id
1632 .0,
1633 second_id
1634 );
1635 });
1636
1637 let first_response = model_response(&request1, SIMPLE_DIFF);
1638 let first_id = first_response.request_id.clone();
1639 respond_first.send(first_response).unwrap();
1640
1641 cx.run_until_parked();
1642
1643 ep_store.update(cx, |ep_store, cx| {
1644 // current prediction is still second, since first was cancelled
1645 assert_eq!(
1646 ep_store
1647 .prediction_at(&buffer, None, &project, cx)
1648 .unwrap()
1649 .id
1650 .0,
1651 second_id
1652 );
1653 });
1654
1655 // first is reported as rejected
1656 let (reject_request, _) = requests.reject.next().await.unwrap();
1657
1658 cx.run_until_parked();
1659
1660 assert_eq!(
1661 &reject_request.rejections,
1662 &[EditPredictionRejection {
1663 request_id: first_id,
1664 reason: EditPredictionRejectReason::Canceled,
1665 was_shown: false,
1666 model_version: None,
1667 }]
1668 );
1669}
1670
1671#[gpui::test]
1672async fn test_cancel_second_on_third_request(cx: &mut TestAppContext) {
1673 let (ep_store, mut requests) = init_test_with_fake_client(cx);
1674 let fs = FakeFs::new(cx.executor());
1675 fs.insert_tree(
1676 "/root",
1677 json!({
1678 "foo.md": "Hello!\nHow\nBye\n"
1679 }),
1680 )
1681 .await;
1682 let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
1683
1684 let buffer = project
1685 .update(cx, |project, cx| {
1686 let path = project.find_project_path(path!("root/foo.md"), cx).unwrap();
1687 project.open_buffer(path, cx)
1688 })
1689 .await
1690 .unwrap();
1691 let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
1692 let position = snapshot.anchor_before(language::Point::new(1, 3));
1693
1694 // start two refresh tasks
1695 ep_store.update(cx, |ep_store, cx| {
1696 ep_store.refresh_prediction_from_buffer(project.clone(), buffer.clone(), position, cx);
1697 });
1698
1699 let (request1, respond_first) = requests.predict.next().await.unwrap();
1700
1701 ep_store.update(cx, |ep_store, cx| {
1702 ep_store.refresh_prediction_from_buffer(project.clone(), buffer.clone(), position, cx);
1703 });
1704
1705 let (request2, respond_second) = requests.predict.next().await.unwrap();
1706
1707 // wait for throttle, so requests are sent
1708 cx.run_until_parked();
1709
1710 ep_store.update(cx, |ep_store, cx| {
1711 // start a third request
1712 ep_store.refresh_prediction_from_buffer(project.clone(), buffer.clone(), position, cx);
1713
1714 // 2 are pending, so 2nd is cancelled
1715 assert_eq!(
1716 ep_store
1717 .get_or_init_project(&project, cx)
1718 .cancelled_predictions
1719 .iter()
1720 .copied()
1721 .collect::<Vec<_>>(),
1722 [1]
1723 );
1724 });
1725
1726 // wait for throttle
1727 cx.run_until_parked();
1728
1729 let (request3, respond_third) = requests.predict.next().await.unwrap();
1730
1731 let first_response = model_response(&request1, SIMPLE_DIFF);
1732 let first_id = first_response.request_id.clone();
1733 respond_first.send(first_response).unwrap();
1734
1735 cx.run_until_parked();
1736
1737 ep_store.update(cx, |ep_store, cx| {
1738 // current prediction is first
1739 assert_eq!(
1740 ep_store
1741 .prediction_at(&buffer, None, &project, cx)
1742 .unwrap()
1743 .id
1744 .0,
1745 first_id
1746 );
1747 });
1748
1749 let cancelled_response = model_response(&request2, SIMPLE_DIFF);
1750 let cancelled_id = cancelled_response.request_id.clone();
1751 respond_second.send(cancelled_response).unwrap();
1752
1753 cx.run_until_parked();
1754
1755 ep_store.update(cx, |ep_store, cx| {
1756 // current prediction is still first, since second was cancelled
1757 assert_eq!(
1758 ep_store
1759 .prediction_at(&buffer, None, &project, cx)
1760 .unwrap()
1761 .id
1762 .0,
1763 first_id
1764 );
1765 });
1766
1767 let third_response = model_response(&request3, SIMPLE_DIFF);
1768 let third_response_id = third_response.request_id.clone();
1769 respond_third.send(third_response).unwrap();
1770
1771 cx.run_until_parked();
1772
1773 ep_store.update(cx, |ep_store, cx| {
1774 // third completes and replaces first
1775 assert_eq!(
1776 ep_store
1777 .prediction_at(&buffer, None, &project, cx)
1778 .unwrap()
1779 .id
1780 .0,
1781 third_response_id
1782 );
1783 });
1784
1785 // second is reported as rejected
1786 let (reject_request, _) = requests.reject.next().await.unwrap();
1787
1788 cx.run_until_parked();
1789
1790 assert_eq!(
1791 &reject_request.rejections,
1792 &[
1793 EditPredictionRejection {
1794 request_id: cancelled_id,
1795 reason: EditPredictionRejectReason::Canceled,
1796 was_shown: false,
1797 model_version: None,
1798 },
1799 EditPredictionRejection {
1800 request_id: first_id,
1801 reason: EditPredictionRejectReason::Replaced,
1802 was_shown: false,
1803 model_version: None,
1804 }
1805 ]
1806 );
1807}
1808
1809#[gpui::test]
1810async fn test_jump_and_edit_throttles_are_independent(cx: &mut TestAppContext) {
1811 let (ep_store, mut requests) = init_test_with_fake_client(cx);
1812
1813 let fs = FakeFs::new(cx.executor());
1814 fs.insert_tree(
1815 "/root",
1816 json!({
1817 "foo.md": "Hello!\nHow\nBye\n",
1818 "bar.md": "Hola!\nComo\nAdios\n"
1819 }),
1820 )
1821 .await;
1822 let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
1823
1824 let buffer = project
1825 .update(cx, |project, cx| {
1826 let path = project.find_project_path(path!("root/foo.md"), cx).unwrap();
1827 project.set_active_path(Some(path.clone()), cx);
1828 project.open_buffer(path, cx)
1829 })
1830 .await
1831 .unwrap();
1832 let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
1833 let position = snapshot.anchor_before(language::Point::new(1, 3));
1834
1835 ep_store.update(cx, |ep_store, cx| {
1836 ep_store.register_project(&project, cx);
1837 ep_store.register_buffer(&buffer, &project, cx);
1838 });
1839
1840 // First edit request - no prior edit, so not throttled.
1841 ep_store.update(cx, |ep_store, cx| {
1842 ep_store.refresh_prediction_from_buffer(project.clone(), buffer.clone(), position, cx);
1843 });
1844 let (_edit_request, edit_response_tx) = requests.predict.next().await.unwrap();
1845 edit_response_tx.send(empty_response()).unwrap();
1846 cx.run_until_parked();
1847
1848 let diagnostic = lsp::Diagnostic {
1849 range: lsp::Range::new(lsp::Position::new(1, 1), lsp::Position::new(1, 5)),
1850 severity: Some(lsp::DiagnosticSeverity::ERROR),
1851 message: "Sentence is incomplete".to_string(),
1852 ..Default::default()
1853 };
1854
1855 // First jump request triggered by diagnostic event on buffer - no prior jump, so not throttled (independent from edit).
1856 project.update(cx, |project, cx| {
1857 project.lsp_store().update(cx, |lsp_store, cx| {
1858 lsp_store
1859 .update_diagnostics(
1860 LanguageServerId(0),
1861 lsp::PublishDiagnosticsParams {
1862 uri: lsp::Uri::from_file_path(path!("/root/bar.md")).unwrap(),
1863 diagnostics: vec![diagnostic],
1864 version: None,
1865 },
1866 None,
1867 language::DiagnosticSourceKind::Pushed,
1868 &[],
1869 cx,
1870 )
1871 .unwrap();
1872 });
1873 });
1874 let (_jump_request, jump_response_tx) = requests.predict.next().await.unwrap();
1875 jump_response_tx.send(empty_response()).unwrap();
1876 cx.run_until_parked();
1877
1878 // Second edit request - should be throttled by the first edit.
1879 ep_store.update(cx, |ep_store, cx| {
1880 ep_store.refresh_prediction_from_buffer(project.clone(), buffer.clone(), position, cx);
1881 });
1882 assert_no_predict_request_ready(&mut requests.predict);
1883
1884 // Second jump request - should be throttled by the first jump.
1885 ep_store.update(cx, |ep_store, cx| {
1886 ep_store.refresh_prediction_from_diagnostics(
1887 project.clone(),
1888 DiagnosticSearchScope::Global,
1889 cx,
1890 );
1891 });
1892 assert_no_predict_request_ready(&mut requests.predict);
1893
1894 // Wait for both throttles to expire.
1895 cx.background_executor
1896 .advance_clock(EditPredictionStore::THROTTLE_TIMEOUT);
1897 cx.background_executor.run_until_parked();
1898 cx.run_until_parked();
1899
1900 // Both requests should now go through.
1901 let (_request_1, response_tx_1) = requests.predict.next().await.unwrap();
1902 response_tx_1.send(empty_response()).unwrap();
1903 cx.run_until_parked();
1904
1905 let (_request_2, response_tx_2) = requests.predict.next().await.unwrap();
1906 response_tx_2.send(empty_response()).unwrap();
1907 cx.run_until_parked();
1908}
1909
1910#[gpui::test]
1911async fn test_same_frame_duplicate_requests_deduplicated(cx: &mut TestAppContext) {
1912 let (ep_store, mut requests) = init_test_with_fake_client(cx);
1913 let fs = FakeFs::new(cx.executor());
1914 fs.insert_tree(
1915 "/root",
1916 json!({
1917 "foo.md": "Hello!\nHow\nBye\n"
1918 }),
1919 )
1920 .await;
1921 let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
1922
1923 let buffer = project
1924 .update(cx, |project, cx| {
1925 let path = project.find_project_path(path!("root/foo.md"), cx).unwrap();
1926 project.open_buffer(path, cx)
1927 })
1928 .await
1929 .unwrap();
1930 let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
1931 let position = snapshot.anchor_before(language::Point::new(1, 3));
1932
1933 // Enqueue two refresh calls in the same synchronous frame (no yielding).
1934 // Both `cx.spawn` tasks are created before either executes, so they both
1935 // capture the same `proceed_count_at_enqueue`. Only the first task should
1936 // pass the deduplication gate; the second should be skipped.
1937 ep_store.update(cx, |ep_store, cx| {
1938 ep_store.refresh_prediction_from_buffer(project.clone(), buffer.clone(), position, cx);
1939 ep_store.refresh_prediction_from_buffer(project.clone(), buffer.clone(), position, cx);
1940 });
1941
1942 // Let both spawned tasks run to completion (including any throttle waits).
1943 cx.run_until_parked();
1944
1945 // Exactly one prediction request should have been sent.
1946 let (request, respond_tx) = requests.predict.next().await.unwrap();
1947 respond_tx
1948 .send(model_response(&request, SIMPLE_DIFF))
1949 .unwrap();
1950 cx.run_until_parked();
1951
1952 // No second request should be pending.
1953 assert_no_predict_request_ready(&mut requests.predict);
1954}
1955
1956#[gpui::test]
1957async fn test_rejections_flushing(cx: &mut TestAppContext) {
1958 let (ep_store, mut requests) = init_test_with_fake_client(cx);
1959
1960 ep_store.update(cx, |ep_store, cx| {
1961 ep_store.reject_prediction(
1962 EditPredictionId("test-1".into()),
1963 EditPredictionRejectReason::Discarded,
1964 false,
1965 None,
1966 cx,
1967 );
1968 ep_store.reject_prediction(
1969 EditPredictionId("test-2".into()),
1970 EditPredictionRejectReason::Canceled,
1971 true,
1972 None,
1973 cx,
1974 );
1975 });
1976
1977 cx.executor().advance_clock(REJECT_REQUEST_DEBOUNCE);
1978 cx.run_until_parked();
1979
1980 let (reject_request, respond_tx) = requests.reject.next().await.unwrap();
1981 respond_tx.send(()).unwrap();
1982
1983 // batched
1984 assert_eq!(reject_request.rejections.len(), 2);
1985 assert_eq!(
1986 reject_request.rejections[0],
1987 EditPredictionRejection {
1988 request_id: "test-1".to_string(),
1989 reason: EditPredictionRejectReason::Discarded,
1990 was_shown: false,
1991 model_version: None,
1992 }
1993 );
1994 assert_eq!(
1995 reject_request.rejections[1],
1996 EditPredictionRejection {
1997 request_id: "test-2".to_string(),
1998 reason: EditPredictionRejectReason::Canceled,
1999 was_shown: true,
2000 model_version: None,
2001 }
2002 );
2003
2004 // Reaching batch size limit sends without debounce
2005 ep_store.update(cx, |ep_store, cx| {
2006 for i in 0..70 {
2007 ep_store.reject_prediction(
2008 EditPredictionId(format!("batch-{}", i).into()),
2009 EditPredictionRejectReason::Discarded,
2010 false,
2011 None,
2012 cx,
2013 );
2014 }
2015 });
2016
2017 // First MAX/2 items are sent immediately
2018 cx.run_until_parked();
2019 let (reject_request, respond_tx) = requests.reject.next().await.unwrap();
2020 respond_tx.send(()).unwrap();
2021
2022 assert_eq!(reject_request.rejections.len(), 50);
2023 assert_eq!(reject_request.rejections[0].request_id, "batch-0");
2024 assert_eq!(reject_request.rejections[49].request_id, "batch-49");
2025
2026 // Remaining items are debounced with the next batch
2027 cx.executor().advance_clock(Duration::from_secs(15));
2028 cx.run_until_parked();
2029
2030 let (reject_request, respond_tx) = requests.reject.next().await.unwrap();
2031 respond_tx.send(()).unwrap();
2032
2033 assert_eq!(reject_request.rejections.len(), 20);
2034 assert_eq!(reject_request.rejections[0].request_id, "batch-50");
2035 assert_eq!(reject_request.rejections[19].request_id, "batch-69");
2036
2037 // Request failure
2038 ep_store.update(cx, |ep_store, cx| {
2039 ep_store.reject_prediction(
2040 EditPredictionId("retry-1".into()),
2041 EditPredictionRejectReason::Discarded,
2042 false,
2043 None,
2044 cx,
2045 );
2046 });
2047
2048 cx.executor().advance_clock(REJECT_REQUEST_DEBOUNCE);
2049 cx.run_until_parked();
2050
2051 let (reject_request, _respond_tx) = requests.reject.next().await.unwrap();
2052 assert_eq!(reject_request.rejections.len(), 1);
2053 assert_eq!(reject_request.rejections[0].request_id, "retry-1");
2054 // Simulate failure
2055 drop(_respond_tx);
2056
2057 // Add another rejection
2058 ep_store.update(cx, |ep_store, cx| {
2059 ep_store.reject_prediction(
2060 EditPredictionId("retry-2".into()),
2061 EditPredictionRejectReason::Discarded,
2062 false,
2063 None,
2064 cx,
2065 );
2066 });
2067
2068 cx.executor().advance_clock(REJECT_REQUEST_DEBOUNCE);
2069 cx.run_until_parked();
2070
2071 // Retry should include both the failed item and the new one
2072 let (reject_request, respond_tx) = requests.reject.next().await.unwrap();
2073 respond_tx.send(()).unwrap();
2074
2075 assert_eq!(reject_request.rejections.len(), 2);
2076 assert_eq!(reject_request.rejections[0].request_id, "retry-1");
2077 assert_eq!(reject_request.rejections[1].request_id, "retry-2");
2078}
2079
2080#[gpui::test]
2081fn test_active_buffer_diagnostics_fetching(cx: &mut TestAppContext) {
2082 let diagnostic_marker: TextRangeMarker = ('«', '»').into();
2083 let search_range_marker: TextRangeMarker = ('[', ']').into();
2084
2085 let (text, mut ranges) = marked_text_ranges_by(
2086 indoc! {r#"
2087 fn alpha() {
2088 let «first_value» = 1;
2089 }
2090
2091 [fn beta() {
2092 let «second_value» = 2;
2093 let third_value = second_value + missing_symbol;
2094 }ˇ]
2095
2096 fn gamma() {
2097 let «fourth_value» = missing_other_symbol;
2098 }
2099 "#},
2100 vec![diagnostic_marker.clone(), search_range_marker.clone()],
2101 );
2102
2103 let diagnostic_ranges = ranges.remove(&diagnostic_marker).unwrap_or_default();
2104 let search_ranges = ranges.remove(&search_range_marker).unwrap_or_default();
2105
2106 let buffer = cx.new(|cx| Buffer::local(&text, cx));
2107
2108 buffer.update(cx, |buffer, cx| {
2109 let snapshot = buffer.snapshot();
2110 let diagnostics = DiagnosticSet::new(
2111 diagnostic_ranges
2112 .iter()
2113 .enumerate()
2114 .map(|(index, range)| DiagnosticEntry {
2115 range: snapshot.offset_to_point_utf16(range.start)
2116 ..snapshot.offset_to_point_utf16(range.end),
2117 diagnostic: Diagnostic {
2118 severity: match index {
2119 0 => DiagnosticSeverity::WARNING,
2120 1 => DiagnosticSeverity::ERROR,
2121 _ => DiagnosticSeverity::HINT,
2122 },
2123 message: match index {
2124 0 => "first warning".to_string(),
2125 1 => "second error".to_string(),
2126 _ => "third hint".to_string(),
2127 },
2128 group_id: index + 1,
2129 is_primary: true,
2130 source_kind: language::DiagnosticSourceKind::Pushed,
2131 ..Diagnostic::default()
2132 },
2133 }),
2134 &snapshot,
2135 );
2136 buffer.update_diagnostics(LanguageServerId(0), diagnostics, cx);
2137 });
2138
2139 let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
2140 let search_range = snapshot.offset_to_point(search_ranges[0].start)
2141 ..snapshot.offset_to_point(search_ranges[0].end);
2142
2143 let active_buffer_diagnostics = zeta::active_buffer_diagnostics(&snapshot, search_range, 100);
2144
2145 assert_eq!(
2146 active_buffer_diagnostics,
2147 vec![zeta_prompt::ActiveBufferDiagnostic {
2148 severity: Some(1),
2149 message: "second error".to_string(),
2150 snippet: text,
2151 snippet_buffer_row_range: 5..5,
2152 diagnostic_range_in_snippet: 61..73,
2153 }]
2154 );
2155
2156 let buffer = cx.new(|cx| {
2157 Buffer::local(
2158 indoc! {"
2159 one
2160 two
2161 three
2162 four
2163 five
2164 "},
2165 cx,
2166 )
2167 });
2168
2169 buffer.update(cx, |buffer, cx| {
2170 let snapshot = buffer.snapshot();
2171 let diagnostics = DiagnosticSet::new(
2172 vec![
2173 DiagnosticEntry {
2174 range: text::PointUtf16::new(0, 0)..text::PointUtf16::new(0, 3),
2175 diagnostic: Diagnostic {
2176 severity: DiagnosticSeverity::ERROR,
2177 message: "row zero".to_string(),
2178 group_id: 1,
2179 is_primary: true,
2180 source_kind: language::DiagnosticSourceKind::Pushed,
2181 ..Diagnostic::default()
2182 },
2183 },
2184 DiagnosticEntry {
2185 range: text::PointUtf16::new(2, 0)..text::PointUtf16::new(2, 5),
2186 diagnostic: Diagnostic {
2187 severity: DiagnosticSeverity::WARNING,
2188 message: "row two".to_string(),
2189 group_id: 2,
2190 is_primary: true,
2191 source_kind: language::DiagnosticSourceKind::Pushed,
2192 ..Diagnostic::default()
2193 },
2194 },
2195 DiagnosticEntry {
2196 range: text::PointUtf16::new(4, 0)..text::PointUtf16::new(4, 4),
2197 diagnostic: Diagnostic {
2198 severity: DiagnosticSeverity::INFORMATION,
2199 message: "row four".to_string(),
2200 group_id: 3,
2201 is_primary: true,
2202 source_kind: language::DiagnosticSourceKind::Pushed,
2203 ..Diagnostic::default()
2204 },
2205 },
2206 ],
2207 &snapshot,
2208 );
2209 buffer.update_diagnostics(LanguageServerId(0), diagnostics, cx);
2210 });
2211
2212 let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
2213
2214 let active_buffer_diagnostics =
2215 zeta::active_buffer_diagnostics(&snapshot, Point::new(2, 0)..Point::new(4, 0), 100);
2216
2217 assert_eq!(
2218 active_buffer_diagnostics
2219 .iter()
2220 .map(|diagnostic| (
2221 diagnostic.severity,
2222 diagnostic.message.clone(),
2223 diagnostic.snippet.clone(),
2224 diagnostic.snippet_buffer_row_range.clone(),
2225 diagnostic.diagnostic_range_in_snippet.clone(),
2226 ))
2227 .collect::<Vec<_>>(),
2228 vec![
2229 (
2230 Some(2),
2231 "row two".to_string(),
2232 "one\ntwo\nthree\nfour\nfive\n".to_string(),
2233 2..2,
2234 8..13,
2235 ),
2236 (
2237 Some(3),
2238 "row four".to_string(),
2239 "one\ntwo\nthree\nfour\nfive\n".to_string(),
2240 4..4,
2241 19..23,
2242 ),
2243 ]
2244 );
2245}
2246
2247// Generate a model response that would apply the given diff to the active file.
2248fn model_response(request: &PredictEditsV3Request, diff_to_apply: &str) -> PredictEditsV3Response {
2249 let editable_range =
2250 zeta_prompt::excerpt_range_for_format(Default::default(), &request.input.excerpt_ranges).1;
2251 let excerpt = request.input.cursor_excerpt[editable_range.clone()].to_string();
2252 let new_excerpt = apply_diff_to_string(diff_to_apply, &excerpt).unwrap();
2253
2254 PredictEditsV3Response {
2255 request_id: Uuid::new_v4().to_string(),
2256 editable_range,
2257 output: new_excerpt,
2258 model_version: None,
2259 }
2260}
2261
2262fn empty_response() -> PredictEditsV3Response {
2263 PredictEditsV3Response {
2264 request_id: Uuid::new_v4().to_string(),
2265 editable_range: 0..0,
2266 output: String::new(),
2267 model_version: None,
2268 }
2269}
2270
2271fn prompt_from_request(request: &PredictEditsV3Request) -> String {
2272 zeta_prompt::format_zeta_prompt(&request.input, zeta_prompt::ZetaFormat::default())
2273}
2274
2275fn assert_no_predict_request_ready(
2276 requests: &mut mpsc::UnboundedReceiver<(
2277 PredictEditsV3Request,
2278 oneshot::Sender<PredictEditsV3Response>,
2279 )>,
2280) {
2281 if requests.next().now_or_never().flatten().is_some() {
2282 panic!("Unexpected prediction request while throttled.");
2283 }
2284}
2285
2286struct RequestChannels {
2287 predict: mpsc::UnboundedReceiver<(
2288 PredictEditsV3Request,
2289 oneshot::Sender<PredictEditsV3Response>,
2290 )>,
2291 reject: mpsc::UnboundedReceiver<(RejectEditPredictionsBody, oneshot::Sender<()>)>,
2292}
2293
2294fn init_test_with_fake_client(
2295 cx: &mut TestAppContext,
2296) -> (Entity<EditPredictionStore>, RequestChannels) {
2297 cx.update(move |cx| {
2298 let settings_store = SettingsStore::test(cx);
2299 cx.set_global(settings_store);
2300 zlog::init_test();
2301
2302 let (predict_req_tx, predict_req_rx) = mpsc::unbounded();
2303 let (reject_req_tx, reject_req_rx) = mpsc::unbounded();
2304
2305 let http_client = FakeHttpClient::create({
2306 move |req| {
2307 let uri = req.uri().path().to_string();
2308 let mut body = req.into_body();
2309 let predict_req_tx = predict_req_tx.clone();
2310 let reject_req_tx = reject_req_tx.clone();
2311 async move {
2312 let resp = match uri.as_str() {
2313 "/client/llm_tokens" => serde_json::to_string(&json!({
2314 "token": "test"
2315 }))
2316 .unwrap(),
2317 "/predict_edits/v3" => {
2318 let mut buf = Vec::new();
2319 body.read_to_end(&mut buf).await.ok();
2320 let decompressed = zstd::decode_all(&buf[..]).unwrap();
2321 let req = serde_json::from_slice(&decompressed).unwrap();
2322
2323 let (res_tx, res_rx) = oneshot::channel();
2324 predict_req_tx.unbounded_send((req, res_tx)).unwrap();
2325 serde_json::to_string(&res_rx.await?).unwrap()
2326 }
2327 "/predict_edits/reject" => {
2328 let mut buf = Vec::new();
2329 body.read_to_end(&mut buf).await.ok();
2330 let req = serde_json::from_slice(&buf).unwrap();
2331
2332 let (res_tx, res_rx) = oneshot::channel();
2333 reject_req_tx.unbounded_send((req, res_tx)).unwrap();
2334 serde_json::to_string(&res_rx.await?).unwrap()
2335 }
2336 _ => {
2337 panic!("Unexpected path: {}", uri)
2338 }
2339 };
2340
2341 Ok(Response::builder().body(resp.into()).unwrap())
2342 }
2343 }
2344 });
2345
2346 let client = client::Client::new(Arc::new(FakeSystemClock::new()), http_client, cx);
2347 client.cloud_client().set_credentials(1, "test".into());
2348
2349 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
2350 language_model::init(user_store.clone(), client.clone(), cx);
2351 let ep_store = EditPredictionStore::global(&client, &user_store, cx);
2352
2353 (
2354 ep_store,
2355 RequestChannels {
2356 predict: predict_req_rx,
2357 reject: reject_req_rx,
2358 },
2359 )
2360 })
2361}
2362
2363#[gpui::test]
2364async fn test_edit_prediction_basic_interpolation(cx: &mut TestAppContext) {
2365 let buffer = cx.new(|cx| Buffer::local("Lorem ipsum dolor", cx));
2366 let edits: Arc<[(Range<Anchor>, Arc<str>)]> = cx.update(|cx| {
2367 to_completion_edits([(2..5, "REM".into()), (9..11, "".into())], &buffer, cx).into()
2368 });
2369
2370 let edit_preview = cx
2371 .read(|cx| buffer.read(cx).preview_edits(edits.clone(), cx))
2372 .await;
2373
2374 let prediction = EditPrediction {
2375 edits,
2376 cursor_position: None,
2377 edit_preview,
2378 buffer: buffer.clone(),
2379 snapshot: cx.read(|cx| buffer.read(cx).snapshot()),
2380 id: EditPredictionId("the-id".into()),
2381 inputs: ZetaPromptInput {
2382 events: Default::default(),
2383 related_files: Default::default(),
2384 active_buffer_diagnostics: vec![],
2385 cursor_path: Path::new("").into(),
2386 cursor_excerpt: "".into(),
2387 cursor_offset_in_excerpt: 0,
2388 excerpt_start_row: None,
2389 excerpt_ranges: Default::default(),
2390 syntax_ranges: None,
2391 experiment: None,
2392 in_open_source_repo: false,
2393 can_collect_data: false,
2394 repo_url: None,
2395 },
2396 buffer_snapshotted_at: Instant::now(),
2397 response_received_at: Instant::now(),
2398 model_version: None,
2399 };
2400
2401 cx.update(|cx| {
2402 assert_eq!(
2403 from_completion_edits(
2404 &prediction.interpolate(&buffer.read(cx).snapshot()).unwrap(),
2405 &buffer,
2406 cx
2407 ),
2408 vec![(2..5, "REM".into()), (9..11, "".into())]
2409 );
2410
2411 buffer.update(cx, |buffer, cx| buffer.edit([(2..5, "")], None, cx));
2412 assert_eq!(
2413 from_completion_edits(
2414 &prediction.interpolate(&buffer.read(cx).snapshot()).unwrap(),
2415 &buffer,
2416 cx
2417 ),
2418 vec![(2..2, "REM".into()), (6..8, "".into())]
2419 );
2420
2421 buffer.update(cx, |buffer, cx| buffer.undo(cx));
2422 assert_eq!(
2423 from_completion_edits(
2424 &prediction.interpolate(&buffer.read(cx).snapshot()).unwrap(),
2425 &buffer,
2426 cx
2427 ),
2428 vec![(2..5, "REM".into()), (9..11, "".into())]
2429 );
2430
2431 buffer.update(cx, |buffer, cx| buffer.edit([(2..5, "R")], None, cx));
2432 assert_eq!(
2433 from_completion_edits(
2434 &prediction.interpolate(&buffer.read(cx).snapshot()).unwrap(),
2435 &buffer,
2436 cx
2437 ),
2438 vec![(3..3, "EM".into()), (7..9, "".into())]
2439 );
2440
2441 buffer.update(cx, |buffer, cx| buffer.edit([(3..3, "E")], None, cx));
2442 assert_eq!(
2443 from_completion_edits(
2444 &prediction.interpolate(&buffer.read(cx).snapshot()).unwrap(),
2445 &buffer,
2446 cx
2447 ),
2448 vec![(4..4, "M".into()), (8..10, "".into())]
2449 );
2450
2451 buffer.update(cx, |buffer, cx| buffer.edit([(4..4, "M")], None, cx));
2452 assert_eq!(
2453 from_completion_edits(
2454 &prediction.interpolate(&buffer.read(cx).snapshot()).unwrap(),
2455 &buffer,
2456 cx
2457 ),
2458 vec![(9..11, "".into())]
2459 );
2460
2461 buffer.update(cx, |buffer, cx| buffer.edit([(4..5, "")], None, cx));
2462 assert_eq!(
2463 from_completion_edits(
2464 &prediction.interpolate(&buffer.read(cx).snapshot()).unwrap(),
2465 &buffer,
2466 cx
2467 ),
2468 vec![(4..4, "M".into()), (8..10, "".into())]
2469 );
2470
2471 buffer.update(cx, |buffer, cx| buffer.edit([(8..10, "")], None, cx));
2472 assert_eq!(
2473 from_completion_edits(
2474 &prediction.interpolate(&buffer.read(cx).snapshot()).unwrap(),
2475 &buffer,
2476 cx
2477 ),
2478 vec![(4..4, "M".into())]
2479 );
2480
2481 buffer.update(cx, |buffer, cx| buffer.edit([(4..6, "")], None, cx));
2482 assert_eq!(prediction.interpolate(&buffer.read(cx).snapshot()), None);
2483 })
2484}
2485
2486#[gpui::test]
2487async fn test_clean_up_diff(cx: &mut TestAppContext) {
2488 init_test(cx);
2489
2490 assert_eq!(
2491 apply_edit_prediction(
2492 indoc! {"
2493 fn main() {
2494 let word_1 = \"lorem\";
2495 let range = word.len()..word.len();
2496 }
2497 "},
2498 indoc! {"
2499 fn main() {
2500 let word_1 = \"lorem\";
2501 let range = word_1.len()..word_1.len();
2502 }
2503 "},
2504 cx,
2505 )
2506 .await,
2507 indoc! {"
2508 fn main() {
2509 let word_1 = \"lorem\";
2510 let range = word_1.len()..word_1.len();
2511 }
2512 "},
2513 );
2514
2515 assert_eq!(
2516 apply_edit_prediction(
2517 indoc! {"
2518 fn main() {
2519 let story = \"the quick\"
2520 }
2521 "},
2522 indoc! {"
2523 fn main() {
2524 let story = \"the quick brown fox jumps over the lazy dog\";
2525 }
2526 "},
2527 cx,
2528 )
2529 .await,
2530 indoc! {"
2531 fn main() {
2532 let story = \"the quick brown fox jumps over the lazy dog\";
2533 }
2534 "},
2535 );
2536}
2537
2538#[gpui::test]
2539async fn test_edit_prediction_end_of_buffer(cx: &mut TestAppContext) {
2540 init_test(cx);
2541
2542 let buffer_content = "lorem\n";
2543 let completion_response = "lorem\nipsum\n";
2544
2545 assert_eq!(
2546 apply_edit_prediction(buffer_content, completion_response, cx).await,
2547 "lorem\nipsum\n"
2548 );
2549}
2550
2551#[gpui::test]
2552async fn test_edit_prediction_no_spurious_trailing_newline(cx: &mut TestAppContext) {
2553 // Test that zeta2's newline normalization logic doesn't insert spurious newlines.
2554 // When the buffer ends without a trailing newline, but the model returns output
2555 // with a trailing newline, zeta2 should normalize both sides before diffing
2556 // so no spurious newline is inserted.
2557 let (ep_store, mut requests) = init_test_with_fake_client(cx);
2558 let fs = FakeFs::new(cx.executor());
2559
2560 // Single line buffer with no trailing newline
2561 fs.insert_tree(
2562 "/root",
2563 json!({
2564 "foo.txt": "hello"
2565 }),
2566 )
2567 .await;
2568 let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
2569
2570 let buffer = project
2571 .update(cx, |project, cx| {
2572 let path = project
2573 .find_project_path(path!("root/foo.txt"), cx)
2574 .unwrap();
2575 project.open_buffer(path, cx)
2576 })
2577 .await
2578 .unwrap();
2579
2580 let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
2581 let position = snapshot.anchor_before(language::Point::new(0, 5));
2582
2583 ep_store.update(cx, |ep_store, cx| {
2584 ep_store.refresh_prediction_from_buffer(project.clone(), buffer.clone(), position, cx);
2585 });
2586
2587 let (request, respond_tx) = requests.predict.next().await.unwrap();
2588
2589 // Model returns output WITH a trailing newline, even though the buffer doesn't have one.
2590 // Zeta2 should normalize both sides before diffing, so no spurious newline is inserted.
2591 let excerpt_length = request.input.cursor_excerpt.len();
2592 let response = PredictEditsV3Response {
2593 request_id: Uuid::new_v4().to_string(),
2594 output: "hello world\n".to_string(),
2595 editable_range: 0..excerpt_length,
2596 model_version: None,
2597 };
2598 respond_tx.send(response).unwrap();
2599
2600 cx.run_until_parked();
2601
2602 // The prediction should insert " world" without adding a newline
2603 ep_store.update(cx, |ep_store, cx| {
2604 let prediction = ep_store
2605 .prediction_at(&buffer, None, &project, cx)
2606 .expect("should have prediction");
2607 let edits: Vec<_> = prediction
2608 .edits
2609 .iter()
2610 .map(|(range, text)| {
2611 let snapshot = buffer.read(cx).snapshot();
2612 (range.to_offset(&snapshot), text.clone())
2613 })
2614 .collect();
2615 assert_eq!(edits, vec![(5..5, " world".into())]);
2616 });
2617}
2618
2619fn init_test(cx: &mut TestAppContext) {
2620 cx.update(|cx| {
2621 let settings_store = SettingsStore::test(cx);
2622 cx.set_global(settings_store);
2623 });
2624}
2625
2626async fn apply_edit_prediction(
2627 buffer_content: &str,
2628 completion_response: &str,
2629 cx: &mut TestAppContext,
2630) -> String {
2631 let fs = project::FakeFs::new(cx.executor());
2632 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
2633 let buffer = cx.new(|cx| Buffer::local(buffer_content, cx));
2634 let (ep_store, response) = make_test_ep_store(&project, cx).await;
2635 *response.lock() = completion_response.to_string();
2636 let edit_prediction = run_edit_prediction(&buffer, &project, &ep_store, cx).await;
2637 buffer.update(cx, |buffer, cx| {
2638 buffer.edit(edit_prediction.edits.iter().cloned(), None, cx)
2639 });
2640 buffer.read_with(cx, |buffer, _| buffer.text())
2641}
2642
2643async fn run_edit_prediction(
2644 buffer: &Entity<Buffer>,
2645 project: &Entity<Project>,
2646 ep_store: &Entity<EditPredictionStore>,
2647 cx: &mut TestAppContext,
2648) -> EditPrediction {
2649 let cursor = buffer.read_with(cx, |buffer, _| buffer.anchor_before(Point::new(1, 0)));
2650 ep_store.update(cx, |ep_store, cx| {
2651 ep_store.register_buffer(buffer, &project, cx)
2652 });
2653 cx.background_executor.run_until_parked();
2654 let prediction_task = ep_store.update(cx, |ep_store, cx| {
2655 ep_store.request_prediction(&project, buffer, cursor, Default::default(), cx)
2656 });
2657 prediction_task.await.unwrap().unwrap().prediction.unwrap()
2658}
2659
2660async fn make_test_ep_store(
2661 project: &Entity<Project>,
2662 cx: &mut TestAppContext,
2663) -> (Entity<EditPredictionStore>, Arc<Mutex<String>>) {
2664 let default_response = "hello world\n".to_string();
2665 let completion_response: Arc<Mutex<String>> = Arc::new(Mutex::new(default_response));
2666 let http_client = FakeHttpClient::create({
2667 let completion_response = completion_response.clone();
2668 let mut next_request_id = 0;
2669 move |req| {
2670 let completion_response = completion_response.clone();
2671 let method = req.method().clone();
2672 let uri = req.uri().path().to_string();
2673 let mut body = req.into_body();
2674 async move {
2675 match (method, uri.as_str()) {
2676 (Method::POST, "/client/llm_tokens") => Ok(http_client::Response::builder()
2677 .status(200)
2678 .body(
2679 serde_json::to_string(&CreateLlmTokenResponse {
2680 token: LlmToken("the-llm-token".to_string()),
2681 })
2682 .unwrap()
2683 .into(),
2684 )
2685 .unwrap()),
2686 (Method::POST, "/predict_edits/v3") => {
2687 let mut buf = Vec::new();
2688 body.read_to_end(&mut buf).await.ok();
2689 let decompressed = zstd::decode_all(&buf[..]).unwrap();
2690 let req: PredictEditsV3Request =
2691 serde_json::from_slice(&decompressed).unwrap();
2692
2693 next_request_id += 1;
2694 Ok(http_client::Response::builder()
2695 .status(200)
2696 .body(
2697 serde_json::to_string(&PredictEditsV3Response {
2698 request_id: format!("request-{next_request_id}"),
2699 editable_range: 0..req.input.cursor_excerpt.len(),
2700 output: completion_response.lock().clone(),
2701 model_version: None,
2702 })
2703 .unwrap()
2704 .into(),
2705 )
2706 .unwrap())
2707 }
2708 _ => Ok(http_client::Response::builder()
2709 .status(404)
2710 .body("Not Found".to_string().into())
2711 .unwrap()),
2712 }
2713 }
2714 }
2715 });
2716
2717 let client = cx.update(|cx| Client::new(Arc::new(FakeSystemClock::new()), http_client, cx));
2718 let user_store = cx.update(|cx| cx.new(|cx| client::UserStore::new(client.clone(), cx)));
2719 cx.update(|cx| {
2720 RefreshLlmTokenListener::register(client.clone(), user_store.clone(), cx);
2721 });
2722 let _server = FakeServer::for_client(42, &client, cx).await;
2723
2724 let ep_store = cx.new(|cx| {
2725 let mut ep_store = EditPredictionStore::new(client, project.read(cx).user_store(), cx);
2726 ep_store.set_edit_prediction_model(EditPredictionModel::Zeta);
2727
2728 let worktrees = project.read(cx).worktrees(cx).collect::<Vec<_>>();
2729 for worktree in worktrees {
2730 let worktree_id = worktree.read(cx).id();
2731 ep_store
2732 .get_or_init_project(project, cx)
2733 .license_detection_watchers
2734 .entry(worktree_id)
2735 .or_insert_with(|| Rc::new(LicenseDetectionWatcher::new(&worktree, cx)));
2736 }
2737
2738 ep_store
2739 });
2740
2741 (ep_store, completion_response)
2742}
2743
2744fn to_completion_edits(
2745 iterator: impl IntoIterator<Item = (Range<usize>, Arc<str>)>,
2746 buffer: &Entity<Buffer>,
2747 cx: &App,
2748) -> Vec<(Range<Anchor>, Arc<str>)> {
2749 let buffer = buffer.read(cx);
2750 iterator
2751 .into_iter()
2752 .map(|(range, text)| {
2753 (
2754 buffer.anchor_after(range.start)..buffer.anchor_before(range.end),
2755 text,
2756 )
2757 })
2758 .collect()
2759}
2760
2761fn from_completion_edits(
2762 editor_edits: &[(Range<Anchor>, Arc<str>)],
2763 buffer: &Entity<Buffer>,
2764 cx: &App,
2765) -> Vec<(Range<usize>, Arc<str>)> {
2766 let buffer = buffer.read(cx);
2767 editor_edits
2768 .iter()
2769 .map(|(range, text)| {
2770 (
2771 range.start.to_offset(buffer)..range.end.to_offset(buffer),
2772 text.clone(),
2773 )
2774 })
2775 .collect()
2776}
2777
2778#[gpui::test]
2779async fn test_unauthenticated_without_custom_url_blocks_prediction_impl(cx: &mut TestAppContext) {
2780 init_test(cx);
2781
2782 let fs = FakeFs::new(cx.executor());
2783 fs.insert_tree(
2784 "/project",
2785 serde_json::json!({
2786 "main.rs": "fn main() {\n \n}\n"
2787 }),
2788 )
2789 .await;
2790
2791 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
2792
2793 let http_client = FakeHttpClient::create(|_req| async move {
2794 Ok(gpui::http_client::Response::builder()
2795 .status(401)
2796 .body("Unauthorized".into())
2797 .unwrap())
2798 });
2799
2800 let client =
2801 cx.update(|cx| client::Client::new(Arc::new(FakeSystemClock::new()), http_client, cx));
2802 let user_store = cx.update(|cx| cx.new(|cx| client::UserStore::new(client.clone(), cx)));
2803 cx.update(|cx| {
2804 language_model::RefreshLlmTokenListener::register(client.clone(), user_store.clone(), cx);
2805 });
2806
2807 let ep_store = cx.new(|cx| EditPredictionStore::new(client, project.read(cx).user_store(), cx));
2808
2809 let buffer = project
2810 .update(cx, |project, cx| {
2811 let path = project
2812 .find_project_path(path!("/project/main.rs"), cx)
2813 .unwrap();
2814 project.open_buffer(path, cx)
2815 })
2816 .await
2817 .unwrap();
2818
2819 let cursor = buffer.read_with(cx, |buffer, _| buffer.anchor_before(Point::new(1, 4)));
2820 ep_store.update(cx, |ep_store, cx| {
2821 ep_store.register_buffer(&buffer, &project, cx)
2822 });
2823 cx.background_executor.run_until_parked();
2824
2825 let completion_task = ep_store.update(cx, |ep_store, cx| {
2826 ep_store.set_edit_prediction_model(EditPredictionModel::Zeta);
2827 ep_store.request_prediction(&project, &buffer, cursor, Default::default(), cx)
2828 });
2829
2830 let result = completion_task.await;
2831 assert!(
2832 result.is_err(),
2833 "Without authentication and without custom URL, prediction should fail"
2834 );
2835}
2836
2837#[gpui::test]
2838async fn test_diagnostic_jump_excludes_collaborator_regions(cx: &mut TestAppContext) {
2839 fn set_collaborator_cursor(buffer: &Entity<Buffer>, row: u32, cx: &mut TestAppContext) {
2840 let collab_replica = clock::ReplicaId::new(10);
2841 let anchor = buffer.read_with(cx, |buffer, _| {
2842 buffer.snapshot().anchor_before(Point::new(row, 0))
2843 });
2844 let selections: Arc<[Selection<Anchor>]> = Arc::new([Selection {
2845 id: 1,
2846 start: anchor,
2847 end: anchor,
2848 reversed: false,
2849 goal: SelectionGoal::None,
2850 }]);
2851 buffer.update(cx, |buffer, cx| {
2852 buffer.apply_ops(
2853 [Operation::UpdateSelections {
2854 selections,
2855 lamport_timestamp: clock::Lamport {
2856 replica_id: collab_replica,
2857 value: 1,
2858 },
2859 line_mode: false,
2860 cursor_shape: CursorShape::Bar,
2861 }],
2862 cx,
2863 );
2864 });
2865 }
2866
2867 fn publish_diagnostics(
2868 uri_path: &'static str,
2869 rows: &[u32],
2870 project: &Entity<Project>,
2871 cx: &mut TestAppContext,
2872 ) {
2873 let diagnostics: Vec<_> = rows
2874 .iter()
2875 .map(|&row| lsp::Diagnostic {
2876 range: lsp::Range::new(lsp::Position::new(row, 0), lsp::Position::new(row, 5)),
2877 severity: Some(lsp::DiagnosticSeverity::ERROR),
2878 message: format!("error at row {row}"),
2879 ..Default::default()
2880 })
2881 .collect();
2882 project.update(cx, |project, cx| {
2883 project.lsp_store().update(cx, |lsp_store, cx| {
2884 lsp_store
2885 .update_diagnostics(
2886 LanguageServerId(0),
2887 lsp::PublishDiagnosticsParams {
2888 uri: lsp::Uri::from_file_path(uri_path).expect("invalid uri"),
2889 diagnostics,
2890 version: None,
2891 },
2892 None,
2893 language::DiagnosticSourceKind::Pushed,
2894 &[],
2895 cx,
2896 )
2897 .expect("failed to update diagnostics");
2898 });
2899 });
2900 }
2901
2902 init_test(cx);
2903
2904 let mut lines = String::new();
2905 for i in 0..60 {
2906 lines.push_str(&format!("line {i}\n"));
2907 }
2908
2909 let fs = FakeFs::new(cx.executor());
2910 fs.insert_tree(
2911 "/root",
2912 json!({
2913 "active.txt": lines,
2914 "collab_file.txt": "error here\nsecond line\n",
2915 "free_file.txt": "another error\nsecond line\n",
2916 }),
2917 )
2918 .await;
2919 let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
2920
2921 let active_buffer = project
2922 .update(cx, |project, cx| {
2923 let path = project
2924 .find_project_path(path!("/root/active.txt"), cx)
2925 .expect("active.txt not found");
2926 project.set_active_path(Some(path.clone()), cx);
2927 project.open_buffer(path, cx)
2928 })
2929 .await
2930 .expect("failed to open active buffer");
2931
2932 set_collaborator_cursor(&active_buffer, 5, cx);
2933
2934 publish_diagnostics(path!("/root/active.txt"), &[3, 25, 50], &project, cx);
2935
2936 cx.run_until_parked();
2937
2938 let cursor_point = Point::new(25, 0);
2939 let empty_search_range: Range<Point> = Default::default();
2940
2941 let snapshot = active_buffer.read_with(cx, |buffer, _| buffer.snapshot());
2942 let result = EditPredictionStore::next_diagnostic_location(
2943 active_buffer.clone(),
2944 &snapshot,
2945 empty_search_range.clone(),
2946 cursor_point,
2947 &project,
2948 &mut cx.to_async(),
2949 )
2950 .await
2951 .expect("next_diagnostic_location failed");
2952
2953 let (result_buffer, result_anchor) = result.expect("expected a diagnostic location");
2954 assert_eq!(result_buffer.entity_id(), active_buffer.entity_id());
2955 let result_row = result_buffer.read_with(cx, |buffer, _| {
2956 result_anchor.to_point(&buffer.snapshot()).row
2957 });
2958 assert_ne!(
2959 result_row, 3,
2960 "row 3 is near collaborator (row 5) but far from local cursor (row 25), should be excluded"
2961 );
2962 assert!(
2963 result_row == 25 || result_row == 50,
2964 "expected row 25 or 50, got {result_row}"
2965 );
2966
2967 let snapshot_near = active_buffer.read_with(cx, |buffer, _| buffer.snapshot());
2968 let near_cursor_point = Point::new(4, 0);
2969 let result_near = EditPredictionStore::next_diagnostic_location(
2970 active_buffer.clone(),
2971 &snapshot_near,
2972 empty_search_range.clone(),
2973 near_cursor_point,
2974 &project,
2975 &mut cx.to_async(),
2976 )
2977 .await
2978 .expect("next_diagnostic_location failed");
2979
2980 let (_, near_anchor) = result_near.expect("expected a diagnostic location when both are near");
2981 let near_row =
2982 active_buffer.read_with(cx, |buffer, _| near_anchor.to_point(&buffer.snapshot()).row);
2983 assert_eq!(
2984 near_row, 3,
2985 "row 3 should be included when local cursor (row 4) is also near the collaborator"
2986 );
2987
2988 let snapshot_far = active_buffer.read_with(cx, |buffer, _| buffer.snapshot());
2989 let far_cursor_point = Point::new(50, 0);
2990 let result_far = EditPredictionStore::next_diagnostic_location(
2991 active_buffer.clone(),
2992 &snapshot_far,
2993 empty_search_range.clone(),
2994 far_cursor_point,
2995 &project,
2996 &mut cx.to_async(),
2997 )
2998 .await
2999 .expect("next_diagnostic_location failed");
3000
3001 let (_, far_anchor) = result_far.expect("expected a diagnostic location");
3002 let far_row =
3003 active_buffer.read_with(cx, |buffer, _| far_anchor.to_point(&buffer.snapshot()).row);
3004 assert_eq!(
3005 far_row, 50,
3006 "row 50 is near local cursor (row 50) and far from collaborator, should be picked"
3007 );
3008
3009 publish_diagnostics(path!("/root/collab_file.txt"), &[0], &project, cx);
3010 publish_diagnostics(path!("/root/free_file.txt"), &[0], &project, cx);
3011 cx.run_until_parked();
3012
3013 let collab_buffer = project
3014 .update(cx, |project, cx| {
3015 let path = project
3016 .find_project_path(path!("/root/collab_file.txt"), cx)
3017 .expect("collab_file.txt not found");
3018 project.open_buffer(path, cx)
3019 })
3020 .await
3021 .expect("failed to open collab buffer");
3022
3023 set_collaborator_cursor(&collab_buffer, 0, cx);
3024 cx.run_until_parked();
3025
3026 let no_same_file_search_range = Point::new(0, 0)..Point::new(59, 0);
3027 let snapshot_cross = active_buffer.read_with(cx, |buffer, _| buffer.snapshot());
3028 let result_cross = EditPredictionStore::next_diagnostic_location(
3029 active_buffer.clone(),
3030 &snapshot_cross,
3031 no_same_file_search_range,
3032 Point::new(0, 0),
3033 &project,
3034 &mut cx.to_async(),
3035 )
3036 .await
3037 .expect("cross-file next_diagnostic_location failed");
3038
3039 let (cross_buffer, _) = result_cross.expect("expected a cross-file diagnostic location");
3040 let cross_path = cross_buffer.read_with(cx, |buffer, cx| {
3041 buffer
3042 .file()
3043 .expect("buffer should have a file")
3044 .full_path(cx)
3045 });
3046 assert_eq!(
3047 cross_path,
3048 Path::new(path!("root/free_file.txt")),
3049 "should skip collab_file.txt (has collaborator) and pick free_file.txt"
3050 );
3051}
3052
3053#[gpui::test]
3054async fn test_edit_prediction_settled(cx: &mut TestAppContext) {
3055 let (ep_store, _requests) = init_test_with_fake_client(cx);
3056 let fs = FakeFs::new(cx.executor());
3057
3058 // Buffer with two clearly separated regions:
3059 // Region A = lines 0-9 (offsets 0..50)
3060 // Region B = lines 20-29 (offsets 105..155)
3061 // A big gap in between so edits in one region never overlap the other.
3062 let mut content = String::new();
3063 for i in 0..30 {
3064 content.push_str(&format!("line {i:02}\n"));
3065 }
3066
3067 fs.insert_tree(
3068 "/root",
3069 json!({
3070 "foo.md": content.clone()
3071 }),
3072 )
3073 .await;
3074 let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
3075
3076 let buffer = project
3077 .update(cx, |project, cx| {
3078 let path = project.find_project_path(path!("root/foo.md"), cx).unwrap();
3079 project.open_buffer(path, cx)
3080 })
3081 .await
3082 .unwrap();
3083
3084 type SettledEventRecord = (EditPredictionId, String);
3085 let settled_events: Arc<Mutex<Vec<SettledEventRecord>>> = Arc::new(Mutex::new(Vec::new()));
3086
3087 ep_store.update(cx, |ep_store, cx| {
3088 ep_store.register_buffer(&buffer, &project, cx);
3089
3090 let settled_events = settled_events.clone();
3091 ep_store.settled_event_callback = Some(Box::new(move |id, text| {
3092 settled_events.lock().push((id, text));
3093 }));
3094 });
3095
3096 // --- Phase 1: edit in region A and enqueue prediction A ---
3097
3098 buffer.update(cx, |buffer, cx| {
3099 // Edit at the start of line 0.
3100 buffer.edit(vec![(0..0, "ADDED ")], None, cx);
3101 });
3102 cx.run_until_parked();
3103
3104 let snapshot_a = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
3105
3106 // Region A: first 10 lines of the buffer.
3107 let editable_region_a = 0..snapshot_a.point_to_offset(Point::new(10, 0));
3108
3109 ep_store.update(cx, |ep_store, cx| {
3110 ep_store.enqueue_settled_prediction(
3111 EditPredictionId("prediction-a".into()),
3112 &project,
3113 &buffer,
3114 &snapshot_a,
3115 editable_region_a.clone(),
3116 None,
3117 cx,
3118 );
3119 });
3120
3121 // --- Phase 2: repeatedly edit in region A to keep it unsettled ---
3122
3123 // Let the worker process the channel message before we start advancing.
3124 cx.run_until_parked();
3125
3126 let mut region_a_edit_offset = 5;
3127 for _ in 0..3 {
3128 // Edit inside region A (not at the boundary) so `last_edit_at` is
3129 // updated before the worker's next wake.
3130 buffer.update(cx, |buffer, cx| {
3131 buffer.edit(
3132 vec![(region_a_edit_offset..region_a_edit_offset, "x")],
3133 None,
3134 cx,
3135 );
3136 });
3137 region_a_edit_offset += 1;
3138 cx.run_until_parked();
3139
3140 cx.executor()
3141 .advance_clock(EDIT_PREDICTION_SETTLED_QUIESCENCE / 2);
3142 cx.run_until_parked();
3143 assert!(
3144 settled_events.lock().is_empty(),
3145 "no settled events should fire while region A is still being edited"
3146 );
3147 }
3148
3149 // Still nothing settled.
3150 assert!(settled_events.lock().is_empty());
3151
3152 // --- Phase 3: edit in distinct region B, enqueue prediction B ---
3153 // Advance a small amount so B's quiescence window starts later than A's,
3154 // but not so much that A settles (A's last edit was at the start of
3155 // iteration 3, and it needs a full Q to settle).
3156 cx.executor()
3157 .advance_clock(EDIT_PREDICTION_SETTLED_QUIESCENCE / 4);
3158 cx.run_until_parked();
3159 assert!(settled_events.lock().is_empty());
3160
3161 let snapshot_b = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
3162 let line_20_offset = snapshot_b.point_to_offset(Point::new(20, 0));
3163
3164 buffer.update(cx, |buffer, cx| {
3165 buffer.edit(vec![(line_20_offset..line_20_offset, "NEW ")], None, cx);
3166 });
3167 cx.run_until_parked();
3168
3169 let snapshot_b2 = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
3170 let editable_region_b = line_20_offset..snapshot_b2.point_to_offset(Point::new(25, 0));
3171
3172 ep_store.update(cx, |ep_store, cx| {
3173 ep_store.enqueue_settled_prediction(
3174 EditPredictionId("prediction-b".into()),
3175 &project,
3176 &buffer,
3177 &snapshot_b2,
3178 editable_region_b.clone(),
3179 None,
3180 cx,
3181 );
3182 });
3183
3184 cx.run_until_parked();
3185 assert!(
3186 settled_events.lock().is_empty(),
3187 "neither prediction should have settled yet"
3188 );
3189
3190 // --- Phase 4: let enough time pass for region A to settle ---
3191 // A's last edit was at T_a (during the last loop iteration). The worker is
3192 // sleeping until T_a + Q. We advance just enough to reach that wake time
3193 // (Q/4 since we already advanced Q/4 in phase 3 on top of the loop's
3194 // 3*Q/2). At that point A has been quiet for Q and settles, but B was
3195 // enqueued only Q/4 ago and stays pending.
3196 cx.executor()
3197 .advance_clock(EDIT_PREDICTION_SETTLED_QUIESCENCE / 4);
3198 cx.run_until_parked();
3199
3200 {
3201 let events = settled_events.lock().clone();
3202 assert_eq!(
3203 events.len(),
3204 1,
3205 "prediction and capture_sample for A should have settled, got: {events:?}"
3206 );
3207 assert_eq!(events[0].0, EditPredictionId("prediction-a".into()));
3208 }
3209
3210 // --- Phase 5: let more time pass for region B to settle ---
3211 // B's last edit was Q/4 before A settled. The worker rescheduled to
3212 // B's last_edit_at + Q, which is 3Q/4 from now.
3213 cx.executor()
3214 .advance_clock(EDIT_PREDICTION_SETTLED_QUIESCENCE * 3 / 4);
3215 cx.run_until_parked();
3216
3217 {
3218 let events = settled_events.lock().clone();
3219 assert_eq!(
3220 events.len(),
3221 2,
3222 "both prediction and capture_sample settled events should be emitted for each request, got: {events:?}"
3223 );
3224 assert_eq!(events[1].0, EditPredictionId("prediction-b".into()));
3225 }
3226}
3227
3228#[ctor::ctor]
3229fn init_logger() {
3230 zlog::init_test();
3231}