capture_example.rs

  1use crate::{
  2    StoredEvent,
  3    cursor_excerpt::editable_and_context_ranges_for_cursor_position,
  4    example_spec::{
  5        CapturedEvent, CapturedPromptInput, CapturedRelatedExcerpt, CapturedRelatedFile,
  6        ExampleSpec, MAX_CURSOR_FILE_SIZE,
  7    },
  8};
  9use anyhow::Result;
 10use buffer_diff::BufferDiffSnapshot;
 11use collections::HashMap;
 12use gpui::{App, Entity, Task};
 13use language::{Buffer, ToPoint as _};
 14use project::{Project, WorktreeId};
 15use std::{collections::hash_map, fmt::Write as _, ops::Range, path::Path, sync::Arc};
 16use text::{BufferSnapshot as TextBufferSnapshot, Point, ToOffset as _};
 17
 18pub fn capture_example(
 19    project: Entity<Project>,
 20    buffer: Entity<Buffer>,
 21    cursor_anchor: language::Anchor,
 22    mut events: Vec<StoredEvent>,
 23    related_files: Vec<zeta_prompt::RelatedFile>,
 24    populate_expected_patch: bool,
 25    cx: &mut App,
 26) -> Option<Task<Result<ExampleSpec>>> {
 27    let snapshot = buffer.read(cx).snapshot();
 28    let file = snapshot.file()?;
 29    let worktree_id = file.worktree_id(cx);
 30    let repository = project.read(cx).active_repository(cx)?;
 31    let repository_snapshot = repository.read(cx).snapshot();
 32    let worktree = project.read(cx).worktree_for_id(worktree_id, cx)?;
 33    let root_name = worktree.read(cx).root_name_str().to_owned();
 34    let cursor_path: Arc<Path> = file.path().as_std_path().into();
 35    if worktree.read(cx).abs_path() != repository_snapshot.work_directory_abs_path {
 36        return None;
 37    }
 38
 39    let repository_url = repository_snapshot
 40        .remote_origin_url
 41        .clone()
 42        .or_else(|| repository_snapshot.remote_upstream_url.clone())?;
 43    let revision = repository_snapshot.head_commit.as_ref()?.sha.to_string();
 44
 45    let git_store = project.read(cx).git_store().clone();
 46
 47    Some(cx.spawn(async move |mut cx| {
 48        let snapshots_by_path =
 49            collect_snapshots(&project, &git_store, worktree_id, &events, &mut cx).await?;
 50
 51        events.retain(|stored_event| {
 52            let zeta_prompt::Event::BufferChange { path, .. } = stored_event.event.as_ref();
 53            let relative_path = strip_root_name(path, &root_name);
 54            snapshots_by_path.contains_key(relative_path)
 55        });
 56
 57        let line_comment_prefix = snapshot
 58            .language()
 59            .and_then(|lang| lang.config().line_comments.first())
 60            .map(|s| s.to_string())
 61            .unwrap_or_default();
 62
 63        let full_cursor_offset = cursor_anchor.to_offset(&snapshot);
 64        let cursor_point = cursor_anchor.to_point(&snapshot);
 65        let cursor_file_content = if snapshot.len() <= MAX_CURSOR_FILE_SIZE {
 66            Some(snapshot.text())
 67        } else {
 68            None
 69        };
 70
 71        let (cursor_excerpt, cursor_offset_in_excerpt, cursor_excerpt_range) = cx
 72            .background_executor()
 73            .spawn(async move { compute_cursor_excerpt(&snapshot, cursor_anchor) })
 74            .await;
 75        let uncommitted_diff = cx
 76            .background_executor()
 77            .spawn(async move { compute_uncommitted_diff(snapshots_by_path) })
 78            .await;
 79
 80        let mut edit_history = String::new();
 81        for stored_event in &events {
 82            write_event_with_relative_paths(&mut edit_history, &stored_event.event, &root_name);
 83            if !edit_history.ends_with('\n') {
 84                edit_history.push('\n');
 85            }
 86        }
 87
 88        // Initialize an empty patch with context lines, to make it easy
 89        // to write the expected patch by hand.
 90        let mut expected_patches = Vec::new();
 91        let mut rejected_patch = None;
 92        if populate_expected_patch {
 93            let mut empty_patch = String::new();
 94            let start_row = cursor_excerpt_range.start.row + 1;
 95            let row_count = cursor_excerpt_range.end.row - cursor_excerpt_range.start.row + 1;
 96            writeln!(&mut empty_patch, "--- a/{}", cursor_path.display()).ok();
 97            writeln!(&mut empty_patch, "+++ b/{}", cursor_path.display()).ok();
 98            writeln!(
 99                &mut empty_patch,
100                "@@ -{},{} +{},{} @@",
101                start_row, row_count, start_row, row_count,
102            )
103            .ok();
104            for line in cursor_excerpt.lines() {
105                writeln!(&mut empty_patch, " {}", line).ok();
106            }
107
108            expected_patches.push(empty_patch.clone());
109            rejected_patch = Some(empty_patch);
110        }
111
112        let prompt_input = cursor_file_content.map(|content| {
113            let captured_events: Vec<CapturedEvent> = events
114                .iter()
115                .map(|stored_event| {
116                    let zeta_prompt::Event::BufferChange {
117                        path,
118                        old_path,
119                        diff,
120                        predicted,
121                        in_open_source_repo,
122                    } = stored_event.event.as_ref();
123                    CapturedEvent {
124                        path: strip_root_name(path, &root_name).into(),
125                        old_path: strip_root_name(old_path, &root_name).into(),
126                        diff: diff.clone(),
127                        predicted: *predicted,
128                        in_open_source_repo: *in_open_source_repo,
129                    }
130                })
131                .collect();
132
133            let captured_related_files: Vec<CapturedRelatedFile> = related_files
134                .iter()
135                .map(|rf| CapturedRelatedFile {
136                    path: strip_root_name(&rf.path, &root_name).into(),
137                    max_row: rf.max_row,
138                    excerpts: rf
139                        .excerpts
140                        .iter()
141                        .map(|e| CapturedRelatedExcerpt {
142                            row_range: e.row_range.clone(),
143                            text: e.text.to_string(),
144                        })
145                        .collect(),
146                })
147                .collect();
148
149            CapturedPromptInput {
150                cursor_file_content: content,
151                cursor_offset: full_cursor_offset,
152                cursor_row: cursor_point.row,
153                cursor_column: cursor_point.column,
154                excerpt_start_row: Some(0),
155                events: captured_events,
156                related_files: captured_related_files,
157                in_open_source_repo: false,
158                zed_version: None,
159            }
160        });
161
162        let mut spec = ExampleSpec {
163            name: generate_timestamp_name(),
164            repository_url,
165            revision,
166            tags: Vec::new(),
167            reasoning: None,
168            uncommitted_diff,
169            cursor_path,
170            cursor_position: String::new(),
171            edit_history,
172            expected_patches,
173            rejected_patch,
174            captured_prompt_input: prompt_input,
175            telemetry: None,
176            human_feedback: Vec::new(),
177            rating: None,
178        };
179        spec.set_cursor_excerpt(
180            &cursor_excerpt,
181            cursor_offset_in_excerpt,
182            &line_comment_prefix,
183        );
184        Ok(spec)
185    }))
186}
187
188fn strip_root_name<'a>(path: &'a Path, root_name: &str) -> &'a Path {
189    path.strip_prefix(root_name).unwrap_or(path)
190}
191
192fn write_event_with_relative_paths(
193    output: &mut String,
194    event: &zeta_prompt::Event,
195    root_name: &str,
196) {
197    fn write_relative_path(output: &mut String, path: &Path, root_name: &str) {
198        for component in strip_root_name(path, root_name).components() {
199            output.push('/');
200            write!(output, "{}", component.as_os_str().to_string_lossy()).ok();
201        }
202    }
203
204    let zeta_prompt::Event::BufferChange {
205        path,
206        old_path,
207        diff,
208        ..
209    } = event;
210
211    output.push_str("--- a");
212    write_relative_path(output, old_path.as_ref(), root_name);
213    output.push_str("\n+++ b");
214    write_relative_path(output, path.as_ref(), root_name);
215    output.push('\n');
216    output.push_str(diff);
217}
218
219fn compute_cursor_excerpt(
220    snapshot: &language::BufferSnapshot,
221    cursor_anchor: language::Anchor,
222) -> (String, usize, Range<Point>) {
223    use text::ToOffset as _;
224
225    let cursor_point = cursor_anchor.to_point(snapshot);
226    let (_editable_range, context_range) =
227        editable_and_context_ranges_for_cursor_position(cursor_point, snapshot, 100, 50);
228    let context_start_offset = context_range.start.to_offset(snapshot);
229    let cursor_offset = cursor_anchor.to_offset(snapshot);
230    let cursor_offset_in_excerpt = cursor_offset.saturating_sub(context_start_offset);
231    let excerpt = snapshot
232        .text_for_range(context_range.clone())
233        .collect::<String>();
234    (excerpt, cursor_offset_in_excerpt, context_range)
235}
236
237async fn collect_snapshots(
238    project: &Entity<Project>,
239    git_store: &Entity<project::git_store::GitStore>,
240    worktree_id: WorktreeId,
241    events: &[StoredEvent],
242    cx: &mut gpui::AsyncApp,
243) -> Result<HashMap<Arc<Path>, (TextBufferSnapshot, BufferDiffSnapshot)>> {
244    let mut snapshots_by_path = HashMap::default();
245    for stored_event in events {
246        let zeta_prompt::Event::BufferChange { path, .. } = stored_event.event.as_ref();
247        if let Some((project_path, relative_path)) = project.read_with(cx, |project, cx| {
248            let project_path = project
249                .find_project_path(path, cx)
250                .filter(|path| path.worktree_id == worktree_id)?;
251            let relative_path: Arc<Path> = project_path.path.as_std_path().into();
252            Some((project_path, relative_path))
253        }) {
254            if let hash_map::Entry::Vacant(entry) = snapshots_by_path.entry(relative_path) {
255                let buffer = project
256                    .update(cx, |project, cx| {
257                        project.open_buffer(project_path.clone(), cx)
258                    })
259                    .await?;
260                let diff = git_store
261                    .update(cx, |git_store, cx| {
262                        git_store.open_uncommitted_diff(buffer.clone(), cx)
263                    })
264                    .await?;
265                let diff_snapshot = diff.update(cx, |diff, cx| diff.snapshot(cx));
266                entry.insert((stored_event.old_snapshot.clone(), diff_snapshot));
267            }
268        }
269    }
270    Ok(snapshots_by_path)
271}
272
273fn compute_uncommitted_diff(
274    snapshots_by_path: HashMap<Arc<Path>, (TextBufferSnapshot, BufferDiffSnapshot)>,
275) -> String {
276    let mut uncommitted_diff = String::new();
277    for (relative_path, (before_text, diff_snapshot)) in snapshots_by_path {
278        if let Some(head_text) = &diff_snapshot.base_text_string() {
279            let file_diff = language::unified_diff(head_text, &before_text.text());
280            if !file_diff.is_empty() {
281                let path_str = relative_path.to_string_lossy();
282                writeln!(uncommitted_diff, "--- a/{path_str}").ok();
283                writeln!(uncommitted_diff, "+++ b/{path_str}").ok();
284                uncommitted_diff.push_str(&file_diff);
285                if !uncommitted_diff.ends_with('\n') {
286                    uncommitted_diff.push('\n');
287                }
288            }
289        }
290    }
291    uncommitted_diff
292}
293
294fn generate_timestamp_name() -> String {
295    let format = time::format_description::parse("[year]-[month]-[day] [hour]:[minute]:[second]");
296    match format {
297        Ok(format) => {
298            let now = time::OffsetDateTime::now_local()
299                .unwrap_or_else(|_| time::OffsetDateTime::now_utc());
300            now.format(&format)
301                .unwrap_or_else(|_| "unknown-time".to_string())
302        }
303        Err(_) => "unknown-time".to_string(),
304    }
305}
306
307#[cfg(test)]
308mod tests {
309    use super::*;
310    use crate::EditPredictionStore;
311    use client::{Client, UserStore};
312    use clock::FakeSystemClock;
313    use gpui::{AppContext as _, TestAppContext, http_client::FakeHttpClient};
314    use indoc::indoc;
315    use language::{Anchor, Point};
316    use project::{FakeFs, Project};
317    use serde_json::json;
318    use settings::SettingsStore;
319    use std::path::Path;
320
321    #[gpui::test]
322    async fn test_capture_example(cx: &mut TestAppContext) {
323        init_test(cx);
324        let fs = FakeFs::new(cx.executor());
325
326        let committed_contents = indoc! {"
327            fn main() {
328                one();
329                two();
330                three();
331                four();
332                five();
333                six();
334                seven();
335                eight();
336                nine();
337            }
338        "};
339
340        let disk_contents = indoc! {"
341            fn main() {
342                // comment 1
343                one();
344                two();
345                three();
346                four();
347                five();
348                six();
349                seven();
350                eight();
351                // comment 2
352                nine();
353            }
354        "};
355
356        fs.insert_tree(
357            "/project",
358            json!({
359                ".git": {},
360                "src": {
361                    "main.rs": disk_contents,
362                }
363            }),
364        )
365        .await;
366
367        // Create an external file outside the main project
368        fs.insert_tree(
369            "/external",
370            json!({
371                "external.rs": "fn external() {}\n",
372            }),
373        )
374        .await;
375
376        fs.set_head_for_repo(
377            Path::new("/project/.git"),
378            &[("src/main.rs", committed_contents.to_string())],
379            "abc123def456",
380        );
381        fs.set_remote_for_repo(
382            Path::new("/project/.git"),
383            "origin",
384            "https://github.com/test/repo.git",
385        );
386
387        let project = Project::test(fs.clone(), ["/project".as_ref()], cx).await;
388
389        let buffer = project
390            .update(cx, |project, cx| {
391                project.open_local_buffer("/project/src/main.rs", cx)
392            })
393            .await
394            .unwrap();
395
396        let ep_store = cx.read(|cx| EditPredictionStore::try_global(cx).unwrap());
397        ep_store.update(cx, |ep_store, cx| {
398            ep_store.register_buffer(&buffer, &project, cx)
399        });
400        cx.run_until_parked();
401
402        buffer.update(cx, |buffer, cx| {
403            let point = Point::new(6, 0);
404            buffer.edit([(point..point, "    // comment 3\n")], None, cx);
405            let point = Point::new(4, 0);
406            buffer.edit([(point..point, "    // comment 4\n")], None, cx);
407
408            pretty_assertions::assert_eq!(
409                buffer.text(),
410                indoc! {"
411                    fn main() {
412                        // comment 1
413                        one();
414                        two();
415                        // comment 4
416                        three();
417                        four();
418                        // comment 3
419                        five();
420                        six();
421                        seven();
422                        eight();
423                        // comment 2
424                        nine();
425                    }
426                "}
427            );
428        });
429        cx.run_until_parked();
430
431        // Open and edit an external file (outside the main project's worktree)
432        let external_buffer = project
433            .update(cx, |project, cx| {
434                project.open_local_buffer("/external/external.rs", cx)
435            })
436            .await
437            .unwrap();
438        ep_store.update(cx, |ep_store, cx| {
439            ep_store.register_buffer(&external_buffer, &project, cx)
440        });
441        cx.run_until_parked();
442        external_buffer.update(cx, |buffer, cx| {
443            let point = Point::new(0, 0);
444            buffer.edit([(point..point, "// external edit\n")], None, cx);
445        });
446        cx.run_until_parked();
447
448        // Verify the external edit was recorded in events
449        let events = ep_store.update(cx, |store, cx| store.edit_history_for_project(&project, cx));
450        assert!(
451            matches!(
452                events
453                    .last()
454                    .unwrap()
455                    .event
456                    .as_ref(),
457                zeta_prompt::Event::BufferChange { path, .. } if path.as_ref() == "/external/external.rs"
458            ),
459            "external file edit should be in events"
460        );
461
462        let mut example = cx
463            .update(|cx| {
464                capture_example(
465                    project.clone(),
466                    buffer.clone(),
467                    Anchor::MIN,
468                    events,
469                    Vec::new(),
470                    true,
471                    cx,
472                )
473                .unwrap()
474            })
475            .await
476            .unwrap();
477        example.name = "test".to_string();
478
479        pretty_assertions::assert_eq!(
480            example,
481            ExampleSpec {
482                name: "test".to_string(),
483                repository_url: "https://github.com/test/repo.git".to_string(),
484                revision: "abc123def456".to_string(),
485                tags: Vec::new(),
486                reasoning: None,
487                uncommitted_diff: indoc! {"
488                    --- a/src/main.rs
489                    +++ b/src/main.rs
490                    @@ -1,4 +1,5 @@
491                     fn main() {
492                    +    // comment 1
493                         one();
494                         two();
495                         three();
496                    @@ -7,5 +8,6 @@
497                         six();
498                         seven();
499                         eight();
500                    +    // comment 2
501                         nine();
502                     }
503                "}
504                .to_string(),
505                cursor_path: Path::new("src/main.rs").into(),
506                cursor_position: indoc! {"
507                    fn main() {
508                    ^[CURSOR_POSITION]
509                        // comment 1
510                        one();
511                        two();
512                        // comment 4
513                        three();
514                        four();
515                        // comment 3
516                        five();
517                        six();
518                        seven();
519                        eight();
520                        // comment 2
521                        nine();
522                    }
523                "}
524                .to_string(),
525                edit_history: indoc! {"
526                    --- a/src/main.rs
527                    +++ b/src/main.rs
528                    @@ -2,8 +2,10 @@
529                         // comment 1
530                         one();
531                         two();
532                    +    // comment 4
533                         three();
534                         four();
535                    +    // comment 3
536                         five();
537                         six();
538                         seven();
539                "}
540                .to_string(),
541                expected_patches: vec![
542                    indoc! {"
543                        --- a/src/main.rs
544                        +++ b/src/main.rs
545                        @@ -1,16 +1,16 @@
546                         fn main() {
547                             // comment 1
548                             one();
549                             two();
550                             // comment 4
551                             three();
552                             four();
553                             // comment 3
554                             five();
555                             six();
556                             seven();
557                             eight();
558                             // comment 2
559                             nine();
560                         }
561                    "}
562                    .to_string()
563                ],
564                rejected_patch: Some(
565                    indoc! {"
566                        --- a/src/main.rs
567                        +++ b/src/main.rs
568                        @@ -1,16 +1,16 @@
569                         fn main() {
570                             // comment 1
571                             one();
572                             two();
573                             // comment 4
574                             three();
575                             four();
576                             // comment 3
577                             five();
578                             six();
579                             seven();
580                             eight();
581                             // comment 2
582                             nine();
583                         }
584                    "}
585                    .to_string()
586                ),
587                captured_prompt_input: example.captured_prompt_input.clone(),
588                telemetry: None,
589                human_feedback: Vec::new(),
590                rating: None,
591            }
592        );
593
594        let prompt_input = example
595            .captured_prompt_input
596            .expect("should have captured prompt input");
597        assert!(
598            prompt_input.cursor_file_content.contains("fn main()"),
599            "cursor_file_content should contain file content"
600        );
601        assert_eq!(
602            prompt_input.cursor_offset, 0,
603            "cursor at Anchor::MIN should be offset 0"
604        );
605        assert_eq!(
606            prompt_input.cursor_row, 0,
607            "cursor at Anchor::MIN should be row 0"
608        );
609        assert_eq!(
610            prompt_input.cursor_column, 0,
611            "cursor at Anchor::MIN should be column 0"
612        );
613        assert!(prompt_input.events.len() > 0, "should have captured events");
614        assert_eq!(
615            prompt_input.related_files.len(),
616            0,
617            "should have no related files (none passed)"
618        );
619    }
620
621    fn init_test(cx: &mut TestAppContext) {
622        cx.update(|cx| {
623            let settings_store = SettingsStore::test(cx);
624            cx.set_global(settings_store);
625            zlog::init_test();
626            let http_client = FakeHttpClient::with_404_response();
627            let client = Client::new(Arc::new(FakeSystemClock::new()), http_client, cx);
628            language_model::init(client.clone(), cx);
629            let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
630            EditPredictionStore::global(&client, &user_store, cx);
631        })
632    }
633}