Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix(agent): give edit diffs real file context and colour them in the TUI (#8600)

Akarshan Biswas67ab688c229d
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 32dbe49a9..9df5c8964 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -52,6 +52,7 @@ dependencies = [
"serde_json",
"serde_yaml",
"sha2",
+ "similar",
"sqlx",
"syntect",
"tar",
@@ -6480,6 +6481,12 @@ version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
+[[package]]
+name = "similar"
+version = "2.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa"
+
[[package]]
name = "siphasher"
version = "0.3.11"
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index cb77d309a..8f8067895 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -176,6 +176,7 @@ base64 = "0.22"
glob = "0.3"
regex = "1"
ignore = "0.4"
+similar = "2.6"
clap = { version = "4", features = ["derive"] }
env_logger = { version = "0.11", optional = true }
indicatif = { version = "0.17", optional = true }
diff --git a/src-tauri/src/core/agent/tools/handlers.rs b/src-tauri/src/core/agent/tools/handlers.rs
index 6d1385fbf..3c497c5be 100644
--- a/src-tauri/src/core/agent/tools/handlers.rs
+++ b/src-tauri/src/core/agent/tools/handlers.rs
@@ -174,7 +174,8 @@ pub async fn execute_builtin(
/// its position in the file; `None` for other tools or when nothing would
/// change. Used to show the change in the permission prompt. Both variants read
/// the prior file: `write` to show its `created`/`overwrote` header, `edit` to
-/// locate `old_string` and number the hunk against real file lines.
+/// locate `old_string`, number the hunk against real file lines, and surround it
+/// with context lines the arguments alone do not carry.
pub(crate) async fn preview_diff(
tool: &BuiltinTool,
args: &serde_json::Value,
@@ -240,10 +241,22 @@ fn line_number_at(text: &str, pos: usize) -> usize {
text[..pos].matches('\n').count() + 1
}
-/// Per-edit `-old`/`+new` hunks, each line numbered against its position in
-/// `prior` (the file content before this call's edits are applied). Multiple
-/// edits are separated by `@@ edit i/n @@` and applied in order so later edits
-/// number against the state left by earlier ones, matching what `edit()` does.
+/// Lines of surrounding file context kept around a change, and the threshold
+/// past which one edit's hunk is split with a `...` gap. Matches the feel of a
+/// unified diff without the `@@ -a,b +c,d @@` range header (the existing
+/// `@@ edit i/n @@` marker already identifies the hunk).
+const DIFF_CONTEXT: usize = 2;
+
+/// Per-edit hunks computed with a real line-level diff (`similar`), so a
+/// one-line change inside a large `old_string`/`new_string` pair shows only the
+/// lines that actually differ instead of the whole block as removed and
+/// re-added. The compared blocks are widened from the raw arguments to whole
+/// lines plus up to `DIFF_CONTEXT` unchanged lines taken from the file, so a
+/// change is shown in place even when `old_string` carries no context of its
+/// own. Deleted lines are numbered against the file before the edit, kept and
+/// inserted lines against the file after it. Multiple edits are separated by
+/// `@@ edit i/n @@` and applied in order so later edits number against the
+/// state left by earlier ones, matching what `edit()` does.
fn render_edit_diff(edits: &[serde_json::Value], prior: &str) -> String {
let n = edits.len();
let mut working = prior.to_string();
@@ -254,18 +267,100 @@ fn render_edit_diff(edits: &[serde_json::Value], prior: &str) -> String {
if n > 1 {
out.push_str(&format!("@@ edit {}/{} @@\n", i + 1, n));
}
- let start = working.find(old).map(|pos| line_number_at(&working, pos)).unwrap_or(1);
- for (j, line) in old.lines().enumerate() {
- out.push_str(&format!("- {:>4} | {line}\n", start + j));
+ match working.find(old) {
+ Some(pos) => {
+ let (old_block, new_block, start) = expand_hunk(&working, pos, old, new);
+ out.push_str(&render_hunk_diff(&old_block, &new_block, start));
+ working.replace_range(pos..pos + old.len(), new);
+ }
+ // `edit()` will reject this call, but the arguments are still worth
+ // showing; there is no file position to number them against.
+ None => out.push_str(&render_hunk_diff(old, new, 1)),
}
- for (j, line) in new.lines().enumerate() {
- out.push_str(&format!("+ {:>4} | {line}\n", start + j));
+ }
+ out.trim_end().to_string()
+}
+
+/// Widen the replacement of `old` at `pos` in `text` to whole lines plus
+/// `DIFF_CONTEXT` lines of surrounding file context, returning the before and
+/// after blocks and the 1-based line the blocks start at. Both blocks share the
+/// context verbatim, so the diff renders it as unchanged lines; whole-line
+/// bounds keep a match that starts or ends mid-line from being diffed against a
+/// line fragment.
+fn expand_hunk(text: &str, pos: usize, old: &str, new: &str) -> (String, String, usize) {
+ let end = pos + old.len();
+ let mut ctx_start = text[..pos].rfind('\n').map_or(0, |i| i + 1);
+ for _ in 0..DIFF_CONTEXT {
+ if ctx_start == 0 {
+ break;
}
- if let Some(pos) = working.find(old) {
- working.replace_range(pos..pos + old.len(), new);
+ ctx_start = text[..ctx_start - 1].rfind('\n').map_or(0, |i| i + 1);
+ }
+ let mut ctx_end = text[end..].find('\n').map_or(text.len(), |i| end + i);
+ for _ in 0..DIFF_CONTEXT {
+ if ctx_end >= text.len() {
+ break;
}
+ ctx_end = text[ctx_end + 1..]
+ .find('\n')
+ .map_or(text.len(), |i| ctx_end + 1 + i);
}
- out.trim_end().to_string()
+ let old_block = text[ctx_start..ctx_end].to_string();
+ let new_block = format!("{}{new}{}", &text[ctx_start..pos], &text[end..ctx_end]);
+ (old_block, new_block, line_number_at(text, ctx_start))
+}
+
+/// Line-diff `old` against `new`, rendering each changed/context line with its
+/// real line number (`start`-based on both sides, since old and new begin at
+/// the same position). Groups distant changes with a `...` gap.
+fn render_hunk_diff(old: &str, new: &str, start: usize) -> String {
+ use similar::{ChangeTag, TextDiff};
+
+ // `old_string`/`new_string` are exact source snippets and often lack a
+ // trailing newline on their last line. `from_lines` tokenizes by keeping
+ // each line's newline, so a shared last line would otherwise mismatch
+ // (`"b"` vs `"b\n"`) and show as a spurious delete+insert instead of
+ // context. Padding both sides equally doesn't change indices or output,
+ // since `\n` is stripped again before each line is printed.
+ let pad = |s: &str| {
+ if s.is_empty() || s.ends_with('\n') {
+ s.to_string()
+ } else {
+ format!("{s}\n")
+ }
+ };
+ let (old, new) = (pad(old), pad(new));
+ let diff = TextDiff::from_lines(&old, &new);
+ let mut out = String::new();
+ for (gi, group) in diff.grouped_ops(DIFF_CONTEXT).iter().enumerate() {
+ if gi > 0 {
+ out.push_str(" ...\n");
+ }
+ for op in group {
+ for change in diff.iter_changes(op) {
+ let text = change.value();
+ let text = text.strip_suffix('\n').unwrap_or(text);
+ match change.tag() {
+ // Numbered on the new side: context below an insertion or
+ // deletion has moved, and an old-side number there would
+ // run backwards against the `+` lines just above it.
+ ChangeTag::Equal => {
+ let line = start + change.new_index().unwrap_or(0);
+ out.push_str(&format!(" {line:>4} | {text}\n"));
+ }
+ ChangeTag::Delete => {
+ let line = start + change.old_index().unwrap_or(0);
+ out.push_str(&format!("- {line:>4} | {text}\n"));
+ }
+ ChangeTag::Insert => {
+ let line = start + change.new_index().unwrap_or(0);
+ out.push_str(&format!("+ {line:>4} | {text}\n"));
+ }
+ }
+ }
+ }
+ }
+ out
}
/// Whole-file `+` preview for a write, headed by created/overwrote, each line
@@ -1191,7 +1286,68 @@ mod tests {
);
assert_eq!(
d,
- "@@ edit 1/2 @@\n- 1 | a\n- 2 | b\n+ 1 | A\n@@ edit 2/2 @@\n- 2 | c\n+ 2 | C\n+ 3 | D"
+ "@@ edit 1/2 @@\n- 1 | a\n- 2 | b\n+ 1 | A\n 2 | c\n@@ edit 2/2 @@\n 1 | A\n- 2 | c\n+ 2 | C\n+ 3 | D"
+ );
+ }
+
+ /// Two edits far apart in one call: each hunk carries its own file context
+ /// and nothing in between, and the second is numbered against the state the
+ /// first left behind (edit 1 adds a line, so `eight` is renumbered 8 -> 9).
+ #[test]
+ fn edit_diff_numbers_later_edits_against_earlier_ones() {
+ let d = render_edit_diff(
+ &[
+ json!({"old_string": "two", "new_string": "TWO\nTWO.5"}),
+ json!({"old_string": "eight", "new_string": "EIGHT"}),
+ ],
+ "one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\nnine\n",
+ );
+ assert_eq!(
+ d,
+ concat!(
+ "@@ edit 1/2 @@\n",
+ " 1 | one\n",
+ "- 2 | two\n",
+ "+ 2 | TWO\n",
+ "+ 3 | TWO.5\n",
+ " 4 | three\n",
+ " 5 | four\n",
+ "@@ edit 2/2 @@\n",
+ " 7 | six\n",
+ " 8 | seven\n",
+ "- 9 | eight\n",
+ "+ 9 | EIGHT\n",
+ " 10 | nine",
+ )
+ );
+ }
+
+ /// A later edit may target text an earlier one inserted, since both run
+ /// against the same `working` copy that `edit()` mutates in order.
+ #[test]
+ fn edit_diff_lets_a_later_edit_target_inserted_text() {
+ let d = render_edit_diff(
+ &[
+ json!({"old_string": "b", "new_string": "b\nBETA"}),
+ json!({"old_string": "BETA", "new_string": "GAMMA"}),
+ ],
+ "a\nb\nc",
+ );
+ assert_eq!(
+ d,
+ concat!(
+ "@@ edit 1/2 @@\n",
+ " 1 | a\n",
+ " 2 | b\n",
+ "+ 3 | BETA\n",
+ " 4 | c\n",
+ "@@ edit 2/2 @@\n",
+ " 1 | a\n",
+ " 2 | b\n",
+ "- 3 | BETA\n",
+ "+ 3 | GAMMA\n",
+ " 4 | c",
+ )
);
}
@@ -1201,7 +1357,93 @@ mod tests {
&[json!({"old_string": "two", "new_string": "TWO"})],
"one\ntwo\nthree",
);
- assert_eq!(d, "- 2 | two\n+ 2 | TWO");
+ assert_eq!(
+ d,
+ " 1 | one\n- 2 | two\n+ 2 | TWO\n 3 | three"
+ );
+ }
+
+ /// The context around a change comes from the file, not just from whatever
+ /// `old_string` happened to include, and stops at `DIFF_CONTEXT` lines.
+ #[test]
+ fn edit_diff_pads_hunk_with_file_context() {
+ let d = render_edit_diff(
+ &[json!({"old_string": "four", "new_string": "FOUR"})],
+ "one\ntwo\nthree\nfour\nfive\nsix\nseven",
+ );
+ assert_eq!(
+ d,
+ " 2 | two\n 3 | three\n- 4 | four\n+ 4 | FOUR\n 5 | five\n 6 | six"
+ );
+ }
+
+ /// A match that starts and ends mid-line is diffed as the whole lines it
+ /// sits in, so the surrounding text on those lines is visible.
+ #[test]
+ fn edit_diff_widens_a_mid_line_match_to_whole_lines() {
+ let d = render_edit_diff(
+ &[json!({"old_string": "b = 1", "new_string": "b = 2"})],
+ "let a = 0;\nlet b = 1;\nlet c = 0;\n",
+ );
+ assert_eq!(
+ d,
+ " 1 | let a = 0;\n- 2 | let b = 1;\n+ 2 | let b = 2;\n 3 | let c = 0;"
+ );
+ }
+
+ /// Distant changes inside one edit stay in one hunk, split by a `...` gap
+ /// rather than dumping the untouched lines between them.
+ #[test]
+ fn edit_diff_splits_distant_changes_with_a_gap() {
+ let d = render_edit_diff(
+ &[json!({
+ "old_string": "a\nb\nc\nd\ne\nf\ng\nh\ni",
+ "new_string": "A\nb\nc\nd\ne\nf\ng\nh\nI",
+ })],
+ "a\nb\nc\nd\ne\nf\ng\nh\ni",
+ );
+ assert_eq!(
+ d,
+ "- 1 | a\n+ 1 | A\n 2 | b\n 3 | c\n ...\n 7 | g\n 8 | h\n- 9 | i\n+ 9 | I"
+ );
+ }
+
+ /// Nothing to show when the arguments do not change the file: the caller
+ /// turns an empty diff into `None`.
+ #[test]
+ fn edit_diff_is_empty_for_a_no_op_edit() {
+ let d = render_edit_diff(
+ &[json!({"old_string": "two", "new_string": "two"})],
+ "one\ntwo\nthree",
+ );
+ assert!(d.is_empty(), "unexpected: {d}");
+ }
+
+ #[test]
+ fn edit_diff_shows_only_the_changed_line_amid_shared_context() {
+ let d = render_edit_diff(
+ &[json!({
+ "old_string": "one\ntwo\nthree",
+ "new_string": "one\nTWO\nthree",
+ })],
+ "one\ntwo\nthree",
+ );
+ assert_eq!(
+ d,
+ " 1 | one\n- 2 | two\n+ 2 | TWO\n 3 | three"
+ );
+ }
+
+ #[test]
+ fn edit_diff_numbers_inserted_lines_against_new_content() {
+ let d = render_edit_diff(
+ &[json!({"old_string": "b", "new_string": "b\nc\nd"})],
+ "a\nb\ne",
+ );
+ assert_eq!(
+ d,
+ " 1 | a\n 2 | b\n+ 3 | c\n+ 4 | d\n 5 | e"
+ );
}
#[test]
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index 8e11d3600..7eaea5b74 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -125,6 +125,7 @@ impl Pending {
Some(d) => diff_lines(
d,
(inner as usize).saturating_sub(4).max(1),
+ DIFF_PREVIEW_MAX_ROWS,
"",
self.path.as_deref(),
),
@@ -1722,7 +1723,7 @@ impl App {
]));
if let Some(diff) = diff {
let lang = self.diff_paths.remove(&id);
- for line in diff_lines(&diff, max, "│ ", lang.as_deref()) {
+ for line in diff_lines(&diff, max, DIFF_MAX_ROWS, "│ ", lang.as_deref()) {
self.push(line);
}
}
@@ -2208,25 +2209,42 @@ fn summarize_result(s: &str, max: usize) -> String {
}
}
-/// Max diff rows rendered under a tool result before collapsing the tail.
-const DIFF_MAX_ROWS: usize = 20;
+/// Max diff rows rendered under a tool result before collapsing the tail. The
+/// transcript scrolls, so a whole edit is worth showing; only pathological
+/// machine-generated diffs hit this.
+const DIFF_MAX_ROWS: usize = 1000;
+
+/// Max diff rows in the permission prompt, which does not scroll: its box grows
+/// upward into the transcript and shares the space with the decision list, so a
+/// long diff has to collapse rather than crowd out the options.
+const DIFF_PREVIEW_MAX_ROWS: usize = 20;
/// Max chars shown for a bash/shell/exec command label in the transcript.
const COMMAND_LABEL_MAX: usize = 80;
+/// Diff row backgrounds. Dark and desaturated on purpose: the syntax-highlighted
+/// foreground is drawn on top of them, so the tint has to read as added/removed
+/// at a glance without swallowing the code.
+const DIFF_ADD_BG: Color = Color::Rgb(22, 52, 32);
+const DIFF_DEL_BG: Color = Color::Rgb(66, 26, 30);
+
/// Render focused-diff text as a boxed panel: a light rule frames the change,
-/// `-` lines red, `+` green, `@@` headers dim-cyan. Content is truncated to
-/// `max` and each row padded so the right border aligns. Collapses to
-/// `DIFF_MAX_ROWS` with a `(+N more)` tail before the closing rule. `gutter`
-/// indents the panel (tool-row alignment under a result; empty in the prompt).
+/// `+` rows on a green background and `-` rows on a red one across the whole row
+/// (so the change reads as a band), `@@` headers dim-cyan. Every row keeps its
+/// syntax highlighting, changed or not; only the background says what happened.
+/// Content is truncated to `max` and each row padded so the right border aligns.
+/// Collapses to `max_rows` with a `(+N more)` tail before the closing rule.
+/// `gutter` indents the panel (tool-row alignment under a result; empty in the
+/// prompt).
fn diff_lines(
diff: &str,
max: usize,
+ max_rows: usize,
gutter: &'static str,
lang: Option<&str>,
) -> Vec<Line<'static>> {
let all: Vec<&str> = diff.lines().collect();
- let shown = all.len().min(DIFF_MAX_ROWS);
+ let shown = all.len().min(max_rows);
let truncated = all.len() > shown;
// Truncate before highlighting so the width arithmetic is unchanged.
@@ -2244,24 +2262,39 @@ fn diff_lines(
let mut rows: Vec<Line<'static>> = Vec::with_capacity(shown + 1);
for (i, line) in kept.iter().enumerate() {
let (marker, body) = split_diff_marker(line);
- let marker_style = match marker.as_bytes().first() {
- Some(b'-') => Style::new().red(),
- Some(b'+') => Style::new().green(),
- _ => Style::new().dim(),
- };
if marker.starts_with('@') {
rows.push(Line::styled(line.clone(), Style::new().cyan().dim()));
continue;
}
+ let bg = match marker.as_bytes().first() {
+ Some(b'-') => Some(DIFF_DEL_BG),
+ Some(b'+') => Some(DIFF_ADD_BG),
+ _ => None,
+ };
let mut spans = Vec::with_capacity(2);
if !marker.is_empty() {
+ // On a tinted row the marker takes the strong colour and the code
+ // keeps its own; elsewhere it recedes.
+ let marker_style = match marker.as_bytes().first() {
+ Some(b'-') => Style::new().red().bold(),
+ Some(b'+') => Style::new().green().bold(),
+ _ => Style::new().dim(),
+ };
spans.push(Span::styled(marker.to_string(), marker_style));
}
match &highlighted {
Some(h) => spans.extend(h[i].iter().cloned()),
+ // Dimming an unhighlighted body would fight the tint behind it.
+ None if bg.is_some() => spans.push(Span::raw(body.to_string())),
None => spans.push(Span::styled(body.to_string(), Style::new().dim())),
}
- rows.push(Line::from(spans));
+ // The tint rides on the line so `boxed_panel` can carry it across the
+ // padding too, making the band reach the right border.
+ let row = Line::from(spans);
+ rows.push(match bg {
+ Some(bg) => row.style(Style::new().bg(bg)),
+ None => row,
+ });
}
if truncated {
rows.push(Line::styled(
@@ -2291,7 +2324,11 @@ fn row_width(row: &Line<'_>) -> usize {
/// Frame styled rows in a light box, right-padded to the widest row (clamped to
/// `max`). Rows carry their own spans so style can vary within a row (syntax
-/// highlighting); `gutter` prefixes every line to indent the panel.
+/// highlighting); `gutter` prefixes every line to indent the panel. A row's
+/// line-level style is folded into its spans, since the framed line replaces it
+/// with the border's own style, and a row-level background also fills the
+/// interior padding so a highlighted row reads as a band from border to border
+/// rather than stopping at the end of its text.
fn boxed_panel(rows: Vec<Line<'static>>, max: usize, gutter: &'static str) -> Vec<Line<'static>> {
let inner = rows
.iter()
@@ -2307,12 +2344,26 @@ fn boxed_panel(rows: Vec<Line<'static>>, max: usize, gutter: &'static str) -> Ve
]));
for row in rows {
let pad = inner.saturating_sub(row_width(&row));
+ let row_style = row.style;
+ // Interior spacing carries the row's background but not its foreground:
+ // the frame itself stays neutral, so only the padding between the
+ // borders is tinted.
+ let fill = match row_style.bg {
+ Some(bg) => border.bg(bg),
+ None => border,
+ };
let mut spans = vec![
Span::styled(gutter, border),
- Span::styled("│ ", border),
+ Span::styled("│", border),
+ Span::styled(" ", fill),
];
- spans.extend(row.spans);
- spans.push(Span::styled(format!("{} │", " ".repeat(pad)), border));
+ spans.extend(
+ row.spans
+ .into_iter()
+ .map(|s| Span::styled(s.content, row_style.patch(s.style))),
+ );
+ spans.push(Span::styled(format!("{} ", " ".repeat(pad)), fill));
+ spans.push(Span::styled("│", border));
out.push(Line::from(spans));
}
out.push(Line::from(vec![
@@ -2789,7 +2840,7 @@ fn group_detail_lines(group: &ToolGroup, width: u16) -> Vec<Line<'static>> {
]));
}
if let Some(diff) = &call.diff {
- for line in diff_lines(diff, max, cont_gutter, None) {
+ for line in diff_lines(diff, max, DIFF_MAX_ROWS, cont_gutter, None) {
out.push(line);
}
}
@@ -6760,7 +6811,8 @@ mod tests {
tool_activity, tool_finished,
transcript_top_padding,
user_content_parts, App, CurrentRun, Pending, PendingImage, PickerKind, ResumeTarget,
- SnapshotJob, Status, DIFF_MAX_ROWS, KEY_BINDINGS, SLASH_COMMANDS, SPINNER,
+ SnapshotJob, Status, DIFF_ADD_BG, DIFF_DEL_BG, DIFF_MAX_ROWS, DIFF_PREVIEW_MAX_ROWS,
+ KEY_BINDINGS, SLASH_COMMANDS, SPINNER,
SPINNER_ADVANCE_MS,
};
use std::time::{Duration, Instant};
@@ -8603,27 +8655,79 @@ mod tests {
.collect()
}
+ /// The row containing `needle`, panicking if there is none.
+ fn diff_row(rows: &[Line<'static>], needle: &str) -> Line<'static> {
+ rows.iter()
+ .find(|l| line_text(l).contains(needle))
+ .unwrap_or_else(|| panic!("no row containing {needle:?}"))
+ .clone()
+ }
+
+ /// Backgrounds of a row's spans, skipping the box frame and the gutter so
+ /// only the banded interior is left.
+ fn row_backgrounds(rows: &[Line<'static>], needle: &str) -> Vec<Option<ratatui::style::Color>> {
+ diff_row(rows, needle)
+ .spans
+ .iter()
+ .filter(|s| !s.content.is_empty() && !s.content.contains('│'))
+ .map(|s| s.style.bg)
+ .collect()
+ }
+
+ /// A changed row is banded by its background, from the left border to the
+ /// right one -- including the padding past the end of the text, or the band
+ /// would stop mid-row on every short line.
#[test]
- fn a_write_diff_is_syntax_highlighted_from_its_path() {
- let diff = "+fn main() {\n+ let x = 1;\n+}";
- let out = diff_lines(diff, 80, "", Some("src/main.rs"));
+ fn changed_diff_rows_are_banded_by_background() {
+ let diff = " 1 | keep\n- 2 | before\n+ 2 | a much longer added line";
+ let out = diff_lines(diff, 80, DIFF_MAX_ROWS, "│ ", None);
assert!(
- !diff_syntax_colours(&out).is_empty(),
- "diff body not highlighted: {:?}",
- out.iter().map(line_text).collect::<Vec<_>>()
+ row_backgrounds(&out, "before")
+ .iter()
+ .all(|bg| *bg == Some(DIFF_DEL_BG)),
+ "removed row not fully banded: {:?}",
+ row_backgrounds(&out, "before")
+ );
+ assert!(
+ row_backgrounds(&out, "added line")
+ .iter()
+ .all(|bg| *bg == Some(DIFF_ADD_BG)),
+ "added row not fully banded"
+ );
+ // Unchanged context is left alone, so the bands stand out against it.
+ assert!(
+ row_backgrounds(&out, "keep").iter().all(|bg| bg.is_none()),
+ "context row was banded"
);
- // The add/remove markers must stay legible as such.
- let greens = out
- .iter()
- .flat_map(|l| l.spans.iter())
- .filter(|s| s.content.starts_with('+') && s.style.fg == Some(ratatui::style::Color::Green))
- .count();
- assert_eq!(greens, 3, "one green marker per added line");
+ }
+
+ /// The band is a background only: the code inside a changed row keeps the
+ /// same syntax highlighting it has as context, which is what makes it
+ /// readable on top of the tint.
+ #[test]
+ fn changed_diff_rows_keep_their_syntax_highlighting() {
+ use ratatui::style::Color;
+ let diff = " 1 | fn main() {\n- 2 | let x = 1;\n+ 2 | let y = 2;";
+ let out = diff_lines(diff, 80, DIFF_MAX_ROWS, "", Some("src/main.rs"));
+ for needle in ["let x = 1;", "let y = 2;"] {
+ let row = diff_row(&out, needle);
+ assert!(
+ row.spans
+ .iter()
+ .any(|s| matches!(s.style.fg, Some(Color::Rgb(..)))),
+ "changed row {needle:?} lost its highlighting: {row:?}"
+ );
+ }
+ // The marker itself stays red/green, so the sign reads without colour
+ // vision doing all the work.
+ let marker = diff_row(&out, "let y = 2;").spans[3].clone();
+ assert_eq!(marker.content.as_ref(), "+");
+ assert_eq!(marker.style.fg, Some(Color::Green));
}
#[test]
fn a_diff_without_a_known_language_stays_plain() {
- let out = diff_lines("+ foo\n- bar", 80, "", None);
+ let out = diff_lines("+ foo\n- bar", 80, DIFF_MAX_ROWS, "", None);
assert!(
diff_syntax_colours(&out).is_empty(),
"unexpected highlighting without a language"
@@ -8632,7 +8736,13 @@ mod tests {
#[test]
fn a_hunk_header_is_not_syntax_highlighted() {
- let out = diff_lines("@@ -1,2 +1,3 @@\n+let x = 1;", 80, "", Some("a.rs"));
+ let out = diff_lines(
+ "@@ -1,2 +1,3 @@\n 1 | let x = 1;",
+ 80,
+ DIFF_MAX_ROWS,
+ "",
+ Some("a.rs"),
+ );
let header = out
.iter()
.find(|l| line_text(l).contains("@@"))
@@ -8669,7 +8779,7 @@ mod tests {
id: "c1".into(),
content: "wrote 3 lines".into(),
is_error: false,
- diff: Some("+fn main() {\n+ let x = 1;\n+}".into()),
+ diff: Some(" 1 | fn main() {\n- 2 | let x = 1;\n+ 2 | let x = 2;".into()),
});
assert!(
!diff_syntax_colours(&app.transcript).is_empty(),
@@ -8680,7 +8790,7 @@ mod tests {
#[test]
fn diff_lines_renders_all_when_under_cap() {
- let out = diff_lines("- foo\n+ bar", 80, "│ ", None);
+ let out = diff_lines("- foo\n+ bar", 80, DIFF_MAX_ROWS, "│ ", None);
// 2 content rows framed by a top and bottom border.
assert_eq!(out.len(), 4);
assert!(line_text(&out[0]).contains('┌'), "top: {}", line_text(&out[0]));
@@ -8691,20 +8801,39 @@ mod tests {
);
}
- #[test]
- fn diff_lines_collapses_tail_past_cap() {
- let diff = (0..30)
+ fn plus_rows(n: usize) -> String {
+ (0..n)
.map(|i| format!("+ line {i}"))
.collect::<Vec<_>>()
- .join("\n");
- let out = diff_lines(&diff, 80, "│ ", None);
- // DIFF_MAX_ROWS content rows + a `(+N more)` row, framed by 2 borders.
- assert_eq!(out.len(), DIFF_MAX_ROWS + 1 + 2);
+ .join("\n")
+ }
+
+ #[test]
+ fn diff_lines_collapses_tail_past_cap() {
+ let out = diff_lines(&plus_rows(30), 80, 20, "│ ", None);
+ // 20 content rows + a `(+N more)` row, framed by 2 borders.
+ assert_eq!(out.len(), 20 + 1 + 2);
// The tail sits just above the closing border.
let tail = line_text(&out[out.len() - 2]);
assert!(tail.contains("(+10 more)"), "tail: {tail}");
}
+ /// The transcript scrolls, so a long edit is shown in full there; the
+ /// permission prompt does not, and keeps the tight cap so the decision list
+ /// is never crowded out.
+ #[test]
+ fn the_result_cap_is_generous_and_the_prompt_cap_is_not() {
+ assert_eq!(DIFF_MAX_ROWS, 1000);
+ let long = plus_rows(400);
+ let result = diff_lines(&long, 80, DIFF_MAX_ROWS, "│ ", None);
+ assert_eq!(result.len(), 400 + 2, "result diff must not collapse");
+
+ let mut prompt = pending(true);
+ prompt.diff = Some(long);
+ let preview = prompt.diff_preview(80);
+ assert_eq!(preview.len(), DIFF_PREVIEW_MAX_ROWS + 1 + 2);
+ }
+
#[test]
fn cancel_clears_pending_run_start() {
let mut app = test_app();