//! `/diff`: review of this session's write/edit calls. Per-file accept/revert, line cursor with //! old/new numbers, word-level highlights, and line notes that go back to the agent (`s`). use crate::theme; use crossterm::event::{KeyCode, KeyEvent}; use hx_core::permit::FileEdit; use ratatui::layout::{Constraint, Layout, Rect}; use ratatui::text::{Line, Span}; use ratatui::widgets::{Block, Clear, Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState}; use similar::ChangeTag; use std::cell::Cell; use std::path::PathBuf; #[derive(Debug, Clone, PartialEq)] pub enum State { Pending, Accepted, Reverted, } #[derive(Debug, Clone, Copy, PartialEq)] enum Kind { Hunk, Add, Del, Ctx, } struct Row { kind: Kind, old: Option, new: Option, /// (changed-word, text) segments; one unemphasized segment when nothing to highlight. segs: Vec<(bool, String)>, } impl Row { fn text(&self) -> String { self.segs.iter().map(|(_, t)| t.as_str()).collect() } /// Line number the agent can find: new side for add/context, old side for removals. fn line(&self) -> Option { if self.kind == Kind::Del { self.old } else { self.new } } } struct Note { file: usize, kind: Kind, line: usize, code: String, text: String, } pub struct File { pub path: PathBuf, old: Option, new: String, pub state: State, rows: Vec, cur: usize, pub add: usize, pub del: usize, } pub enum Act { None, Close, /// A file was put back; the app drops it from the edits log. Reverted(PathBuf), Error(String), /// Notes as one user message for the agent. Send(String), } pub struct Review { pub files: Vec, pub sel: usize, notes: Vec, /// Note being typed for the cursor row. input: Option, nums: bool, words: bool, collapsed: bool, wrap: bool, /// Horizontal scroll in chars (only when not wrapping). xoff: usize, top: Cell, } fn rows(old: &str, new: &str) -> Vec { let d = similar::TextDiff::from_lines(old, new); let mut out = vec![]; for g in d.grouped_ops(3) { let (o, n) = (g[0].old_range(), g[0].new_range()); let (oe, ne) = ( g[g.len() - 1].old_range().end, g[g.len() - 1].new_range().end, ); out.push(Row { kind: Kind::Hunk, old: None, new: None, segs: vec![( false, format!( "@@ -{},{} +{},{} @@", o.start + 1, oe - o.start, n.start + 1, ne - n.start ), )], }); for op in &g { for c in d.iter_inline_changes(op) { let kind = match c.tag() { ChangeTag::Insert => Kind::Add, ChangeTag::Delete => Kind::Del, ChangeTag::Equal => Kind::Ctx, }; let mut segs: Vec<(bool, String)> = c .iter_strings_lossy() .map(|(em, t)| (em, t.into_owned())) .collect(); if let Some((_, t)) = segs.last_mut() { *t = t.trim_end_matches(['\n', '\r']).to_string(); } out.push(Row { kind, old: c.old_index().map(|i| i + 1), new: c.new_index().map(|i| i + 1), segs, }); } } } out } impl Review { /// One entry per path: first `old` to last `new`; no-op edits drop out. None = nothing to review. pub fn new(edits: &[FileEdit]) -> Option { let mut files: Vec = vec![]; for e in edits { match files.iter_mut().find(|f| f.path == e.path) { Some(f) => f.new = e.new.clone(), None => files.push(File { path: e.path.clone(), old: e.old.clone(), new: e.new.clone(), state: State::Pending, rows: vec![], cur: 0, add: 0, del: 0, }), } } files.retain(|f| f.old.as_deref() != Some(f.new.as_str())); for f in &mut files { f.rows = rows(f.old.as_deref().unwrap_or(""), &f.new); f.add = f.rows.iter().filter(|r| r.kind == Kind::Add).count(); f.del = f.rows.iter().filter(|r| r.kind == Kind::Del).count(); f.cur = f .rows .iter() .position(|r| r.kind != Kind::Hunk) .unwrap_or(0); } (!files.is_empty()).then_some(Self { files, sel: 0, notes: vec![], input: None, nums: true, words: true, collapsed: false, wrap: false, xoff: 0, top: Cell::new(0), }) } fn shown(&self, r: &Row) -> bool { !(self.collapsed && r.kind == Kind::Del) } /// Move the cursor `by` visible rows (clamped). fn step(&mut self, by: isize) { let collapsed = self.collapsed; let f = &mut self.files[self.sel]; let ok = |r: &Row| !(collapsed && r.kind == Kind::Del); let mut i = f.cur; let dir = by.signum(); for _ in 0..by.unsigned_abs() { let mut j = i; loop { match j.checked_add_signed(dir) { Some(n) if n < f.rows.len() => j = n, _ => break, } if ok(&f.rows[j]) { i = j; break; } } } f.cur = i; } fn hunk(&mut self, dir: isize) { let f = &mut self.files[self.sel]; let mut hs = f .rows .iter() .enumerate() .filter(|(_, r)| r.kind == Kind::Hunk) .map(|(i, _)| i); let t = if dir > 0 { hs.find(|&i| i > f.cur) } else { hs.rfind(|&i| i < f.cur) }; if let Some(i) = t { f.cur = i; } } fn note_at(&self, file: usize, row: &Row) -> Option { self.notes .iter() .position(|n| n.file == file && n.kind == row.kind && Some(n.line) == row.line()) } fn commit_note(&mut self, text: String) { let (file, row) = ( self.sel, &self.files[self.sel].rows[self.files[self.sel].cur], ); let Some(line) = row.line() else { return }; let at = self.note_at(file, row); let text = text.trim().to_string(); match (at, text.is_empty()) { (Some(i), true) => { self.notes.remove(i); } (Some(i), false) => self.notes[i].text = text, (None, false) => { let (kind, code) = (row.kind, row.text()); self.notes.push(Note { file, kind, line, code, text, }); } (None, true) => {} } } fn message(&self) -> String { let mut s = String::from("Review notes on your edits; address each:\n"); for n in &self.notes { let k = match n.kind { Kind::Add => "added", Kind::Del => "removed", _ => "context", }; s += &format!( "- {}:{} ({k}) `{}`: {}\n", self.files[n.file].path.display(), n.line, n.code.trim(), n.text ); } s } /// Paths marked accepted; the app drops them from the edits log when the review ends. pub fn accepted(&self) -> Vec { let ok = |f: &&File| f.state == State::Accepted; self.files .iter() .filter(ok) .map(|f| f.path.clone()) .collect() } pub fn key(&mut self, k: KeyEvent) -> Act { if let Some(buf) = &mut self.input { match k.code { KeyCode::Esc => self.input = None, KeyCode::Enter => { let t = std::mem::take(buf); self.input = None; self.commit_note(t); } KeyCode::Backspace => { buf.pop(); } KeyCode::Char(c) => buf.push(c), _ => {} } return Act::None; } let n = self.files.len(); match k.code { KeyCode::Esc | KeyCode::Char('q') => return Act::Close, KeyCode::Char('n') | KeyCode::Tab => self.sel = (self.sel + 1) % n, KeyCode::Char('p') | KeyCode::BackTab => self.sel = (self.sel + n - 1) % n, KeyCode::Char('j') | KeyCode::Down => self.step(1), KeyCode::Char('k') | KeyCode::Up => self.step(-1), KeyCode::PageDown => self.step(10), KeyCode::PageUp => self.step(-10), KeyCode::Char('g') | KeyCode::Home => self.step(-(isize::MAX / 2)), KeyCode::Char('G') | KeyCode::End => self.step(isize::MAX / 2), KeyCode::Char(']') => self.hunk(1), KeyCode::Char('[') => self.hunk(-1), KeyCode::Char('w') => { self.wrap = !self.wrap; self.xoff = 0; } KeyCode::Char('h') | KeyCode::Left => self.xoff = self.xoff.saturating_sub(8), KeyCode::Char('l') | KeyCode::Right if !self.wrap => { let f = &self.files[self.sel]; let len = f.rows[f.cur].text().chars().count(); self.xoff = (self.xoff + 8).min(len.saturating_sub(1)); } KeyCode::Char('L') => self.nums = !self.nums, KeyCode::Char('W') => self.words = !self.words, KeyCode::Char('v') => { self.collapsed = !self.collapsed; self.step(0); let f = &mut self.files[self.sel]; if self.collapsed && f.rows[f.cur].kind == Kind::Del { self.step(1); } } KeyCode::Char('c') | KeyCode::Enter => { let f = &self.files[self.sel]; let row = &f.rows[f.cur]; if row.line().is_some() { let old = self .note_at(self.sel, row) .map(|i| self.notes[i].text.clone()); self.input = Some(old.unwrap_or_default()); } } KeyCode::Char('s') => { return if self.notes.is_empty() { Act::Close } else { Act::Send(self.message()) }; } KeyCode::Char('a') => self.files[self.sel].state = State::Accepted, KeyCode::Char('r') => { let f = &mut self.files[self.sel]; match revert(f) { Ok(()) => { f.state = State::Reverted; return Act::Reverted(f.path.clone()); } Err(e) => return Act::Error(e), } } _ => {} } Act::None } /// One screen line per row (cut with `«`/`»`), or several with `↪` when wrapping. fn row_lines(&self, r: &Row, width: usize, cur: bool) -> Vec> { let th = theme::t(); let (base, em, sign) = match r.kind { Kind::Add => (th.add(), th.add_em(), '+'), Kind::Del => (th.del(), th.del_em(), '-'), Kind::Hunk => (th.hunk(), th.hunk(), ' '), Kind::Ctx => (th.plain(), th.plain(), ' '), }; let mut gutter = String::new(); if self.nums && r.kind != Kind::Hunk { let n = |v: Option| v.map_or(" ".into(), |v| format!("{v:>4}")); gutter = format!("{} {} ", n(r.old), n(r.new)); } let sign = if r.kind == Kind::Hunk { String::new() } else { format!("{sign} ") }; let used = gutter.chars().count() + sign.chars().count(); let budget = width.saturating_sub(used).max(1); let cells: Vec<(char, bool)> = r .segs .iter() .flat_map(|(e, t)| { t.replace('\t', " ") .chars() .map(|c| (c, *e)) .collect::>() }) .collect(); let chunks: Vec<&[(char, bool)]> = if self.wrap { if cells.is_empty() { vec![&[]] } else { cells.chunks(budget - usize::from(budget > 1)).collect() } } else { vec![&cells[self.xoff.min(cells.len())..]] }; let mut out = vec![]; for (i, ch) in chunks.into_iter().enumerate() { let mut spans = vec![]; if i == 0 { spans.push(Span::styled(gutter.clone(), th.dim())); spans.push(Span::styled(sign.clone(), base)); } else { spans.push(Span::styled(format!("{:>w$}", "↪ ", w = used), th.dim())); } let (mut shown, cut) = if !self.wrap && ch.len() > budget { (&ch[..budget], true) } else { (ch, false) }; let lead = !self.wrap && self.xoff > 0 && !cells.is_empty(); let mut buf: Vec<(char, bool)> = shown.to_vec(); if lead && let Some(f) = buf.first_mut() { f.0 = '«'; } if cut && let Some(l) = buf.last_mut() { l.0 = '»'; } shown = &buf; let mut run = String::new(); let mut run_em = shown.first().is_some_and(|c| c.1); for &(c, e) in shown { if e != run_em { spans.push(Span::styled( std::mem::take(&mut run), if run_em && self.words { em } else { base }, )); run_em = e; } run.push(c); } spans.push(Span::styled( run, if run_em && self.words { em } else { base }, )); let line = Line::from(spans); out.push(if cur { line.patch_style(th.sel()) } else { line }); } out } pub fn draw(&self, f: &mut ratatui::Frame) { let th = theme::t(); let a = f.area(); let (w, h) = (a.width * 9 / 10, a.height * 9 / 10); let r = Rect::new(a.x + (a.width - w) / 2, a.y + (a.height - h) / 2, w, h); let (add, del) = self .files .iter() .fold((0, 0), |(a, d), f| (a + f.add, d + f.del)); let hint = if self.input.is_some() { " enter save note (empty deletes) · esc cancel ".to_string() } else { " c note · s send notes · a accept · r revert · n/p file · j/k ]/[ move · L nums · W words · w wrap · h/l pan · v collapse · esc close " .to_string() }; let block = Block::bordered() .border_style(th.dim()) .title(Line::from(vec![ Span::styled(format!(" review · {} files · ", self.files.len()), th.dim()), Span::styled(format!("+{add} "), th.add()), Span::styled(format!("-{del} "), th.del()), Span::styled(format!("· {} notes ", self.notes.len()), th.dim()), ])) .title_bottom(Span::styled(hint, th.dim())); let inner = block.inner(r); f.render_widget(Clear, r); f.render_widget(block, r); let lw = (inner.width / 3).clamp(16, 36); let [left, right] = Layout::horizontal([Constraint::Length(lw), Constraint::Min(10)]).areas(inner); let list: Vec = self .files .iter() .enumerate() .map(|(i, x)| { let tag = match x.state { State::Pending => " ", State::Accepted => "✓", State::Reverted => "↩", }; let name = x .path .file_name() .map_or_else(String::new, |n| n.to_string_lossy().into()); let st = if i == self.sel { th.sel() } else { th.plain() }; Line::styled(format!("{tag} {name} +{} -{}", x.add, x.del), st) }) .collect(); f.render_widget(Paragraph::new(list), left); let cur = &self.files[self.sel]; let width = right.width.saturating_sub(1) as usize; let mut lines = vec![Line::styled(cur.path.display().to_string(), th.accent())]; let mut cur_line = 1; for (i, row) in cur.rows.iter().enumerate().filter(|(_, r)| self.shown(r)) { if i == cur.cur { cur_line = lines.len(); } lines.extend(self.row_lines(row, width, i == cur.cur)); if let Some(n) = self.note_at(self.sel, row) { lines.push(Line::styled( format!(" ✎ {}", self.notes[n].text), th.warn(), )); } if i == cur.cur && let Some(buf) = &self.input { lines.push(Line::styled(format!(" ✎ {buf}▏"), th.accent())); cur_line = lines.len() - 1; } } let hgt = right.height as usize; let mut top = self.top.get().min(lines.len().saturating_sub(1)); if cur_line < top { top = cur_line; } else if cur_line >= top + hgt { top = cur_line + 1 - hgt; } self.top.set(top); let total = lines.len(); f.render_widget(Paragraph::new(lines).scroll((top as u16, 0)), right); if total > hgt { let mut st = ScrollbarState::new(total - hgt).position(top); f.render_stateful_widget( Scrollbar::new(ScrollbarOrientation::VerticalRight).style(th.dim()), right, &mut st, ); } } } /// Put the file back to `old` (delete it when the agent created it). Refuses when the file is not /// what the agent left, so manual edits are never overwritten. fn revert(f: &File) -> Result<(), String> { if f.state == State::Reverted { return Err("already reverted".into()); } let now = std::fs::read_to_string(&f.path).map_err(|e| format!("{}: {e}", f.path.display()))?; if now != f.new { return Err(format!( "{} changed on disk since; not reverting", f.path.display() )); } match &f.old { Some(o) => std::fs::write(&f.path, o), None => std::fs::remove_file(&f.path), } .map_err(|e| format!("{}: {e}", f.path.display())) } #[cfg(test)] mod tests { use super::*; use crossterm::event::KeyModifiers; fn key(c: char) -> KeyEvent { KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE) } #[test] fn collapses_counts_and_reverts() { let d = tempfile::tempdir().unwrap(); let (p, q) = (d.path().join("a.txt"), d.path().join("b.txt")); std::fs::write(&p, "one\nTWO\nthree\n").unwrap(); std::fs::write(&q, "new\n").unwrap(); let e = |path: &PathBuf, old: Option<&str>, new: &str| FileEdit { path: path.clone(), old: old.map(Into::into), new: new.into(), }; let mut r = Review::new(&[ e(&p, Some("one\ntwo\nthree\n"), "one\n2\nthree\n"), e(&p, Some("one\n2\nthree\n"), "one\nTWO\nthree\n"), e(&q, None, "new\n"), e(&q, Some("same\n"), "same\n"), ]) .unwrap(); assert_eq!((r.files.len(), r.files[0].add, r.files[0].del), (2, 1, 1)); assert!(matches!(r.key(key('r')), Act::Reverted(_))); assert_eq!(std::fs::read_to_string(&p).unwrap(), "one\ntwo\nthree\n"); r.key(key('n')); std::fs::write(&q, "edited by hand").unwrap(); assert!(matches!(r.key(key('r')), Act::Error(_))); assert!(q.exists()); assert!(Review::new(&[]).is_none()); } #[test] fn numbers_words_and_notes() { let e = FileEdit { path: "/x/a.rs".into(), old: Some("a\nlet x = 1;\nb\n".into()), new: "a\nlet x = 2;\nb\n".into(), }; let mut r = Review::new(&[e]).unwrap(); let rs = &r.files[0].rows; assert_eq!(rs[0].kind, Kind::Hunk); assert_eq!(rs[0].text(), "@@ -1,3 +1,3 @@"); let del = rs.iter().find(|x| x.kind == Kind::Del).unwrap(); let add = rs.iter().find(|x| x.kind == Kind::Add).unwrap(); assert_eq!( (del.old, del.new, add.old, add.new), (Some(2), None, None, Some(2)) ); assert!(add.segs.iter().any(|(em, t)| *em && t.contains('2'))); // cursor starts on first ctx row; step to the added line and annotate it r.step(2); assert_eq!(r.files[0].rows[r.files[0].cur].kind, Kind::Add); r.key(key('c')); for c in "use 3".chars() { r.key(key(c)); } r.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); match r.key(key('s')) { Act::Send(m) => assert!(m.contains("/x/a.rs:2 (added) `let x = 2;`: use 3"), "{m}"), _ => panic!("expected Send"), } // long line: cut with », panned with «, wrapped with ↪ let long = "x".repeat(100); let mut r2 = Review::new(&[FileEdit { path: "/y".into(), old: None, new: format!("{long}\n"), }]) .unwrap(); let row = &r2.files[0].rows[1]; let txt = |ls: Vec| ls.iter().map(|l| l.to_string()).collect::>(); assert!(txt(r2.row_lines(row, 40, false))[0].ends_with('»')); r2.key(key('l')); assert!(txt(r2.row_lines(&r2.files[0].rows[1], 40, false))[0].contains('«')); r2.key(key('w')); let w = txt(r2.row_lines(&r2.files[0].rows[1], 40, false)); assert!(w.len() > 2 && w[1].contains('↪'), "{w:?}"); r.key(key('a')); assert_eq!(r.accepted(), vec![PathBuf::from("/x/a.rs")]); r.key(key('v')); assert!(!r.shown(&r.files[0].rows[2])); } }