Skip to main content

vtcode_core/tools/file_ops/
diff_preview.rs

1//! Diff preview utilities for file operations.
2
3use crate::config::constants::diff;
4use serde_json::{Value, json};
5use std::time::Instant;
6use vtcode_diff::{
7    DiffDisplayKind, DiffDisplayLine, DiffDocument, DiffHunk, DiffOptions, count_diff_changes,
8    display_lines_from_unified_diff, format_unified_hunks,
9};
10
11/// Create a diff preview response when content exceeds the size limit.
12pub fn diff_preview_size_skip() -> Value {
13    json!({
14        "skipped": true,
15        "reason": "content_exceeds_preview_limit",
16        "max_bytes": diff::MAX_PREVIEW_BYTES
17    })
18}
19
20/// Stable machine-readable reason for suppressed diff previews.
21///
22/// Kept stable for `ThreadEvent`/API consumers. Renderers must show
23/// [`diff_preview_user_message`] instead of this code.
24pub const SUPPRESSED_PREVIEW_REASON: &str = "too_many_changes";
25
26/// Create a diff preview response when inline diffs are suppressed due to too many changes.
27pub fn diff_preview_suppressed(additions: usize, deletions: usize, line_count: usize) -> Value {
28    json!({
29        "skipped": true,
30        "suppressed": true,
31        "reason": SUPPRESSED_PREVIEW_REASON,
32        "message": diff::SUPPRESSION_MESSAGE,
33        "summary": {
34            "additions": additions,
35            "deletions": deletions,
36            "total_lines": line_count
37        }
38    })
39}
40
41/// User-facing one-line summary for a skipped/suppressed diff entry.
42///
43/// Prefers the producer-supplied `message`, maps known `reason` codes to
44/// friendly text, and humanizes unknown snake_case codes. The stable `reason`
45/// code itself is never surfaced for known cases.
46pub fn diff_preview_user_message(preview: &Value) -> String {
47    if let Some(message) = preview
48        .get("message")
49        .and_then(Value::as_str)
50        .map(str::trim)
51        .filter(|s| !s.is_empty())
52    {
53        return message.to_owned();
54    }
55    let reason = preview.get("reason").and_then(Value::as_str).map(str::trim).unwrap_or_default();
56    match reason {
57        "too_many_changes" => {
58            let additions = preview
59                .get("additions")
60                .and_then(Value::as_u64)
61                .or_else(|| preview.get("summary").and_then(|s| s.get("additions")).and_then(Value::as_u64));
62            let deletions = preview
63                .get("deletions")
64                .and_then(Value::as_u64)
65                .or_else(|| preview.get("summary").and_then(|s| s.get("deletions")).and_then(Value::as_u64));
66            match (additions, deletions) {
67                (Some(a), Some(d)) => {
68                    format!("Large change — preview suppressed (+{a} -{d}); use `git diff` for the full view")
69                }
70                _ => "Large change — preview suppressed; use `git diff` for the full view".to_owned(),
71            }
72        }
73        "content_exceeds_preview_limit" => "Preview skipped — file exceeds the preview size limit".to_owned(),
74        "" => "preview skipped".to_owned(),
75        other => other.replace('_', " "),
76    }
77}
78
79/// Create a diff preview response when an error prevents diff generation.
80pub fn diff_preview_error_skip(reason: &str, detail: Option<&str>) -> Value {
81    match detail {
82        Some(value) => json!({
83            "skipped": true,
84            "reason": reason,
85            "detail": value
86        }),
87        None => json!({
88            "skipped": true,
89            "reason": reason
90        }),
91    }
92}
93
94/// Return the canonical bounded diff entries from a file-operation response.
95///
96/// `diff[]` is the shared response contract for multi-file operations. The
97/// legacy `diff_preview` object is normalized into a one-entry list so older
98/// write/create responses render and persist through the same path.
99pub fn canonical_diff_previews(output: &Value) -> Vec<Value> {
100    if let Some(diffs) = output.get("diff").and_then(Value::as_array) {
101        return diffs.clone();
102    }
103
104    let Some(preview) = output.get("diff_preview") else {
105        return Vec::new();
106    };
107
108    let mut entry = preview.clone();
109    if let Some(fields) = entry.as_object_mut() {
110        if !fields.contains_key("path")
111            && let Some(path) = output.get("path").and_then(Value::as_str)
112        {
113            fields.insert("path".to_string(), Value::String(path.to_string()));
114        }
115        if !fields.contains_key("operation") {
116            let operation = if output.get("created").and_then(Value::as_bool) == Some(true)
117                || output.get("file_existed").and_then(Value::as_bool) == Some(false)
118            {
119                "created"
120            } else {
121                "updated"
122            };
123            fields.insert("operation".to_string(), Value::String(operation.to_string()));
124        }
125    }
126
127    vec![entry]
128}
129
130/// Determine whether a canonical diff contract represents an effective
131/// mutation. `None` means the response is not a file-operation response and
132/// callers should use the tool's normal success semantics.
133pub fn diff_output_has_effective_change(output: &Value) -> Option<bool> {
134    if output.get("skipped").and_then(Value::as_bool) == Some(true)
135        || output.get("conflict").and_then(Value::as_bool) == Some(true)
136        || output.get("success").and_then(Value::as_bool) == Some(false)
137    {
138        return Some(false);
139    }
140
141    if output.get("diff").is_none() && output.get("diff_preview").is_none() {
142        return None;
143    }
144
145    Some(canonical_diff_previews(output).iter().any(diff_preview_has_effective_change))
146}
147
148fn diff_preview_has_effective_change(preview: &Value) -> bool {
149    if preview.get("is_empty").and_then(Value::as_bool) == Some(true) {
150        return matches!(preview.get("operation").and_then(Value::as_str), Some("created" | "deleted"));
151    }
152
153    if preview
154        .get("content")
155        .and_then(Value::as_str)
156        .is_some_and(|content| !content.is_empty())
157    {
158        return true;
159    }
160
161    // A skipped preview still represents a completed mutation when the
162    // operation itself succeeded; only an explicit `is_empty` preview is a
163    // no-op. This covers bounded/suppressed previews without over-counting
164    // writes that were skipped or conflicted at the response level.
165    preview.get("skipped").and_then(Value::as_bool) == Some(true)
166        || preview
167            .get("summary")
168            .and_then(|summary| summary.get("additions"))
169            .and_then(Value::as_u64)
170            .is_some_and(|additions| additions > 0)
171        || preview
172            .get("summary")
173            .and_then(|summary| summary.get("deletions"))
174            .and_then(Value::as_u64)
175            .is_some_and(|deletions| deletions > 0)
176}
177
178/// Build a unified diff preview between before and after content.
179pub fn build_diff_preview(path: &str, before: Option<&str>, after: &str) -> Value {
180    let started = Instant::now();
181    let previous = before.unwrap_or("");
182    let old_label = format!("a/{path}");
183    let new_label = format!("b/{path}");
184
185    let options = DiffOptions {
186        context_lines: diff::CONTEXT_RADIUS,
187        old_label: Some(old_label.as_str()),
188        new_label: Some(new_label.as_str()),
189        missing_newline_hint: true,
190        ..DiffOptions::default()
191    };
192    // Unified formatting normalizes `\r\n` to `\n` with no marker, so the
193    // recorded bytes cannot reproduce the original exactly when a `\r` was
194    // present. Exact-reversal consumers refuse such recordings.
195    let normalized_terminators = previous.contains('\r') || after.contains('\r');
196    let document = DiffDocument::between(previous, after, options.clone());
197    // Tool responses carry a plain unified diff. The terminal/UI renderers
198    // apply colors, gutters, and syntax highlighting after parsing the diff;
199    // embedding ANSI here would hide hunk markers and line prefixes from that
200    // parser and make apply_patch previews fall back to raw text.
201    let formatted = format_unified_hunks(&document.hunks, &options);
202
203    if formatted.trim().is_empty() {
204        tracing::debug!(
205            target: "vtcode.tools.diff",
206            path,
207            before_bytes = previous.len(),
208            after_bytes = after.len(),
209            additions = 0,
210            deletions = 0,
211            line_count = 0,
212            truncated = false,
213            suppressed = false,
214            elapsed_ms = started.elapsed().as_millis(),
215            "diff preview generated"
216        );
217
218        return json!({
219            "content": "",
220            "truncated": false,
221            "omitted_line_count": 0,
222            "skipped": false,
223            "is_empty": true,
224            "normalized_terminators": normalized_terminators,
225            "additions": 0,
226            "deletions": 0
227        });
228    }
229
230    let line_count = formatted.lines().count();
231    let counts = count_diff_changes(&document.hunks);
232    let additions = counts.additions;
233    let deletions = counts.deletions;
234    if line_count > diff::MAX_PREVIEW_LINES {
235        let lines: Vec<&str> = formatted.lines().collect();
236        let head_count = diff::HEAD_LINE_COUNT.min(lines.len());
237        let base_tail_count = diff::TAIL_LINE_COUNT.min(lines.len().saturating_sub(head_count));
238        let full_display = (document.hunks.len() > 1).then(|| display_lines_from_unified_diff(&formatted));
239        let mut tail_count = base_tail_count;
240        let mut tail_hunk_header = full_display.as_ref().and_then(|display| {
241            bounded_tail_hunk_header(display, &document.hunks, lines.len().saturating_sub(tail_count))
242        });
243        if tail_hunk_header.is_some() && tail_count > 0 {
244            tail_count = tail_count.saturating_sub(1);
245            tail_hunk_header = full_display.as_ref().and_then(|display| {
246                bounded_tail_hunk_header(display, &document.hunks, lines.len().saturating_sub(tail_count))
247            });
248            if tail_hunk_header.is_none() {
249                tail_count = base_tail_count;
250            }
251        }
252        let omitted = lines.len().saturating_sub(head_count + tail_count);
253
254        let diff_output = if omitted > 0 {
255            let mut result = lines[..head_count].join("\n");
256            result.push_str(&format!("\n... {omitted} lines omitted ...\n"));
257            if let Some(header) = tail_hunk_header {
258                result.push_str(&header);
259                result.push('\n');
260            }
261            result.push_str(&lines[lines.len().saturating_sub(tail_count)..].join("\n"));
262            result
263        } else {
264            lines.join("\n")
265        };
266
267        let elapsed = started.elapsed().as_millis();
268
269        tracing::debug!(
270            target: "vtcode.tools.diff",
271            path,
272            before_bytes = previous.len(),
273            after_bytes = after.len(),
274            additions,
275            deletions,
276            line_count,
277            omitted_lines = omitted,
278            truncated = true,
279            suppressed = false,
280            elapsed_ms = elapsed,
281            "diff preview generated"
282        );
283
284        json!({
285            "content": diff_output,
286            "truncated": true,
287            "omitted_line_count": omitted,
288            "skipped": false,
289            "normalized_terminators": normalized_terminators,
290            "additions": additions,
291            "deletions": deletions
292        })
293    } else {
294        let elapsed = started.elapsed().as_millis();
295
296        tracing::debug!(
297            target: "vtcode.tools.diff",
298            path,
299            before_bytes = previous.len(),
300            after_bytes = after.len(),
301            additions,
302            deletions,
303            line_count,
304            truncated = false,
305            suppressed = false,
306            elapsed_ms = elapsed,
307            "diff preview generated"
308        );
309
310        json!({
311            "content": formatted,
312            "truncated": false,
313            "omitted_line_count": 0,
314            "skipped": false,
315            "normalized_terminators": normalized_terminators,
316            "additions": additions,
317            "deletions": deletions
318        })
319    }
320}
321
322fn bounded_tail_hunk_header(display: &[DiffDisplayLine], hunks: &[DiffHunk], tail_start: usize) -> Option<String> {
323    let tail = display.get(tail_start..)?;
324    let first_body_offset = tail.iter().position(DiffDisplayLine::is_diff)?;
325    if tail[..first_body_offset]
326        .iter()
327        .any(|line| line.kind == DiffDisplayKind::HunkHeader)
328    {
329        return None;
330    }
331
332    let first_body_index = tail_start + first_body_offset;
333    let hunk_header_index = display[..first_body_index]
334        .iter()
335        .rposition(|line| line.kind == DiffDisplayKind::HunkHeader)?;
336    let hunk_index = display[..first_body_index]
337        .iter()
338        .filter(|line| line.kind == DiffDisplayKind::HunkHeader)
339        .count()
340        .checked_sub(1)?;
341    let hunk = hunks.get(hunk_index)?;
342    let prefix_line_count = display[hunk_header_index + 1..first_body_index]
343        .iter()
344        .filter(|line| line.is_diff())
345        .count();
346    let prefix = hunk.lines.get(..prefix_line_count)?;
347    let mut old_start = hunk.old_start;
348    let mut new_start = hunk.new_start;
349    for line in prefix {
350        if line.kind != vtcode_diff::DiffLineKind::Addition {
351            old_start = old_start.saturating_add(1);
352        }
353        if line.kind != vtcode_diff::DiffLineKind::Deletion {
354            new_start = new_start.saturating_add(1);
355        }
356    }
357
358    let tail_lines = tail[first_body_offset..]
359        .iter()
360        .take_while(|line| line.kind != DiffDisplayKind::HunkHeader)
361        .filter(|line| line.is_diff());
362    let mut old_lines = 0usize;
363    let mut new_lines = 0usize;
364    for line in tail_lines {
365        if line.kind != DiffDisplayKind::Addition {
366            old_lines = old_lines.saturating_add(1);
367        }
368        if line.kind != DiffDisplayKind::Deletion {
369            new_lines = new_lines.saturating_add(1);
370        }
371    }
372    (old_lines > 0 || new_lines > 0).then(|| format!("@@ -{old_start},{old_lines} +{new_start},{new_lines} @@"))
373}
374
375#[cfg(test)]
376mod tests {
377    use serde_json::json;
378    use vtcode_commons::ansi::strip_ansi;
379
380    use super::*;
381
382    #[test]
383    fn canonical_diff_previews_normalize_legacy_write_output() {
384        let previews = canonical_diff_previews(&json!({
385            "path": "README.md",
386            "file_existed": true,
387            "diff_preview": {"content": "diff", "skipped": false}
388        }));
389
390        assert_eq!(previews.len(), 1);
391        assert_eq!(previews[0]["path"], "README.md");
392        assert_eq!(previews[0]["operation"], "updated");
393    }
394
395    #[test]
396    fn effective_change_distinguishes_noop_skipped_and_empty_file_operations() {
397        assert_eq!(
398            diff_output_has_effective_change(&json!({
399                "success": true,
400                "diff": [{"operation": "updated", "is_empty": true}]
401            })),
402            Some(false)
403        );
404        assert_eq!(
405            diff_output_has_effective_change(&json!({"success": true, "skipped": true, "diff": []})),
406            Some(false)
407        );
408        assert_eq!(
409            diff_output_has_effective_change(&json!({
410                "success": true,
411                "diff": [{"operation": "created", "is_empty": true}]
412            })),
413            Some(true)
414        );
415    }
416
417    #[test]
418    fn suppressed_preview_user_message_prefers_message_and_maps_reason_codes() {
419        let suppressed = diff_preview_suppressed(12, 3, 40);
420        assert_eq!(suppressed["reason"], SUPPRESSED_PREVIEW_REASON);
421        let rendered = diff_preview_user_message(&suppressed);
422        assert_eq!(rendered, diff::SUPPRESSION_MESSAGE);
423        assert!(!rendered.contains("too_many_changes"));
424
425        let reason_only = json!({
426            "skipped": true,
427            "reason": SUPPRESSED_PREVIEW_REASON,
428            "summary": {"additions": 12, "deletions": 3}
429        });
430        let fallback = diff_preview_user_message(&reason_only);
431        assert!(fallback.contains("+12 -3"), "fallback should keep counts: {fallback}");
432        assert!(!fallback.contains("too_many_changes"));
433
434        let oversized = json!({"skipped": true, "reason": "content_exceeds_preview_limit"});
435        assert_eq!(diff_preview_user_message(&oversized), "Preview skipped — file exceeds the preview size limit");
436
437        let unknown = json!({"skipped": true, "reason": "custom_retry_later"});
438        assert_eq!(diff_preview_user_message(&unknown), "custom retry later");
439    }
440
441    #[test]
442    fn build_diff_preview_keeps_serialized_content_plain_for_ui_parsing() {
443        let preview = build_diff_preview("README.md", Some("before\n"), "after\n");
444        let content = preview
445            .get("content")
446            .and_then(Value::as_str)
447            .expect("changed preview should contain diff content");
448
449        assert_eq!(content, strip_ansi(content));
450        assert!(content.contains("-before"));
451        assert!(content.contains("+after"));
452    }
453
454    #[test]
455    fn large_change_uses_bounded_head_tail_instead_of_suppression() {
456        let before = (0..=diff::MAX_SINGLE_FILE_CHANGES)
457            .map(|index| format!("old-{index}\n"))
458            .collect::<String>();
459        let after = (0..=diff::MAX_SINGLE_FILE_CHANGES)
460            .map(|index| format!("new-{index}\n"))
461            .collect::<String>();
462
463        let preview = build_diff_preview("large.txt", Some(&before), &after);
464
465        assert_eq!(preview["skipped"], false);
466        assert_eq!(preview["truncated"], true);
467        assert!(preview["omitted_line_count"].as_u64().is_some_and(|count| count > 0));
468        let content = preview["content"].as_str().expect("bounded diff content");
469        assert!(content.contains("lines omitted"));
470        assert!(content.contains("old-0"));
471        assert!(content.contains(&format!("new-{}", diff::MAX_SINGLE_FILE_CHANGES)));
472
473        let display_lines = display_lines_from_unified_diff(content);
474        let tail = display_lines
475            .iter()
476            .find(|line| line.text.starts_with("new-200"))
477            .expect("tail line");
478        assert_eq!(tail.new_line, Some(201));
479    }
480
481    #[test]
482    fn large_multi_hunk_preview_keeps_tail_hunk_numbers() {
483        let before = (0..600).map(|index| format!("old-{index}\n")).collect::<String>();
484        let mut after_lines = (0..600).map(|index| format!("old-{index}\n")).collect::<Vec<_>>();
485        for (index, line) in after_lines.iter_mut().enumerate().take(220).skip(100) {
486            *line = format!("new-{index}\n");
487        }
488        for (index, line) in after_lines.iter_mut().enumerate().take(520).skip(400) {
489            *line = format!("new-{index}\n");
490        }
491
492        let preview = build_diff_preview("large-multi.txt", Some(&before), &after_lines.concat());
493        let content = preview["content"].as_str().expect("bounded diff content");
494        let display_lines = display_lines_from_unified_diff(content);
495        let tail = display_lines
496            .iter()
497            .find(|line| line.text.starts_with("new-519"))
498            .expect("tail hunk line");
499        assert_eq!(tail.new_line, Some(520));
500    }
501
502    #[test]
503    fn build_preview_flags_normalized_terminators() {
504        let clean = build_diff_preview("lf.txt", Some("a\nb\n"), "a\nB\n");
505        assert_eq!(clean["normalized_terminators"], false);
506
507        let crlf_before = build_diff_preview("crlf.txt", Some("a\r\nb\r\n"), "a\r\nB\r\n");
508        assert_eq!(crlf_before["normalized_terminators"], true);
509
510        // Converted endings still flag: the recorded old side no longer
511        // reproduces the original bytes.
512        let converted = build_diff_preview("conv.txt", Some("a\r\nb\r\n"), "a\nB\n");
513        assert_eq!(converted["normalized_terminators"], true);
514
515        let empty = build_diff_preview("empty.txt", Some(""), "");
516        assert_eq!(empty["normalized_terminators"], false);
517    }
518}