tui: /diff review with line numbers, word diff, line notes sent to agent

This commit is contained in:
hermes committed 2026-10-14 20:02:14 +00:00
1 parent 1ee8babbf5
commit dfdd1218b6
4 files changed
+417 -42

No files matched your search

+1 -1
View File
@@ -14,7 +14,7 @@ hx-core = { version = "0.1.0", path = "../hx-core" }
ignore = "0.4.33"
ratatui = { version = "0.30.2", features = ["unstable-rendered-line-info"] }
serde_json = "1.0.151"
similar = "3.2.0"
similar = { version = "3.2.0", features = ["inline"] }
tokio = { version = "1.53.1", features = ["rt", "macros", "sync", "time", "rt-multi-thread"] }
[lints]
+4
View File
@@ -1061,6 +1061,10 @@ fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option<String> {
app.t.push(Item::Info(format!("reverted {}", p.display())));
}
review::Act::Error(e) => app.t.push(Item::Error(e)),
review::Act::Send(text) => {
app.review = None;
return Some(text);
}
review::Act::None => {}
}
return None;
+401 -41
View File
@@ -1,11 +1,14 @@
//! `/diff`: file list + diff of this session's write/edit calls; reject reverts the file on disk.
//! `/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};
use ratatui::widgets::{Block, Clear, Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState};
use similar::ChangeTag;
use std::cell::Cell;
use std::path::PathBuf;
#[derive(Debug, Clone, PartialEq)]
@@ -15,12 +18,51 @@ pub enum State {
Reverted,
}
#[derive(Debug, Clone, Copy, PartialEq)]
enum Kind {
Hunk,
Add,
Del,
Ctx,
}
struct Row {
kind: Kind,
old: Option<usize>,
new: Option<usize>,
/// (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<usize> {
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<String>,
new: String,
pub state: State,
diff: Vec<String>,
rows: Vec<Row>,
cur: usize,
pub add: usize,
pub del: usize,
}
@@ -31,12 +73,70 @@ pub enum Act {
/// 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<File>,
pub sel: usize,
scroll: u16,
notes: Vec<Note>,
/// Note being typed for the cursor row.
input: Option<String>,
nums: bool,
words: bool,
collapsed: bool,
top: Cell<usize>,
}
fn rows(old: &str, new: &str) -> Vec<Row> {
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 {
@@ -51,7 +151,8 @@ impl Review {
old: e.old.clone(),
new: e.new.clone(),
state: State::Pending,
diff: vec![],
rows: vec![],
cur: 0,
add: 0,
del: 0,
}),
@@ -59,37 +160,181 @@ impl Review {
}
files.retain(|f| f.old.as_deref() != Some(f.new.as_str()));
for f in &mut files {
let d = similar::TextDiff::from_lines(f.old.as_deref().unwrap_or(""), &f.new)
.unified_diff()
.context_radius(3)
.to_string();
f.diff = d.lines().map(String::from).collect();
f.add = f.diff.iter().filter(|l| l.starts_with('+')).count();
f.del = f.diff.iter().filter(|l| l.starts_with('-')).count();
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,
scroll: 0,
notes: vec![],
input: None,
nums: true,
words: true,
collapsed: false,
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<usize> {
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
}
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;
self.scroll = 0;
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('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('p') | KeyCode::BackTab => {
self.sel = (self.sel + n - 1) % n;
self.scroll = 0;
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('j') | KeyCode::Down => self.scroll = self.scroll.saturating_add(1),
KeyCode::Char('k') | KeyCode::Up => self.scroll = self.scroll.saturating_sub(1),
KeyCode::PageDown => self.scroll = self.scroll.saturating_add(10),
KeyCode::PageUp => self.scroll = self.scroll.saturating_sub(10),
KeyCode::Char('a') => self.files[self.sel].state = State::Accepted,
KeyCode::Char('r') => {
let f = &mut self.files[self.sel];
@@ -106,6 +351,59 @@ impl Review {
Act::None
}
fn row_line(&self, r: &Row, width: usize, cur: bool) -> Line<'static> {
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 spans = vec![];
let mut used = 0;
if self.nums && r.kind != Kind::Hunk {
let n = |v: Option<usize>| v.map_or(" ".into(), |v| format!("{v:>4}"));
let g = format!("{} {} ", n(r.old), n(r.new));
used += g.chars().count();
spans.push(Span::styled(g, th.dim()));
}
if r.kind != Kind::Hunk {
spans.push(Span::styled(format!("{sign} "), base));
used += 2;
}
let budget = width.saturating_sub(used);
let mut left = budget;
let mut cut = false;
for (e, t) in &r.segs {
let t = t.replace('\t', " ");
let c = t.chars().count();
let take = if c > left {
cut = true;
left
} else {
c
};
let part: String = t.chars().take(take).collect();
left -= take;
spans.push(Span::styled(part, if *e && self.words { em } else { base }));
if cut {
break;
}
}
if cut && let Some(l) = spans.last_mut() {
let mut s: String = l.content.chars().collect();
s.pop();
s.push('»');
l.content = s.into();
}
let line = Line::from(spans);
if cur {
line.patch_style(th.sel())
} else {
line
}
}
pub fn draw(&self, f: &mut ratatui::Frame) {
let th = theme::t();
let a = f.area();
@@ -115,17 +413,21 @@ impl Review {
.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 · 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(
" a accept · r reject (revert) · n/p file · j/k scroll · esc close ",
th.dim(),
));
.title_bottom(Span::styled(hint, th.dim()));
let inner = block.inner(r);
f.render_widget(Clear, r);
f.render_widget(block, r);
@@ -152,21 +454,45 @@ impl Review {
.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())];
lines.extend(cur.diff.iter().map(|l| {
let st = match l.chars().next() {
Some('+') => th.add(),
Some('-') => th.del(),
Some('@') => th.hunk(),
_ => th.plain(),
};
Line::styled(l.clone(), st)
}));
let max = lines.len().saturating_sub(right.height as usize) as u16;
f.render_widget(
Paragraph::new(lines).scroll((self.scroll.min(max), 0)),
right,
);
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.push(self.row_line(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,
);
}
}
}
@@ -226,4 +552,38 @@ mod tests {
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"),
}
r.key(key('v'));
assert!(!r.shown(&r.files[0].rows[2]));
}
}
+11
View File
@@ -23,6 +23,9 @@ pub mod mocha {
/// Diff line backgrounds (green/red mixed into base).
pub const ADD_BG: u32 = 0x2b3a33;
pub const DEL_BG: u32 = 0x3d2a35;
/// Changed words inside a paired -/+ line.
pub const ADD_EM: u32 = 0x3f5c49;
pub const DEL_EM: u32 = 0x5e3a49;
}
pub struct Sym {
@@ -203,6 +206,14 @@ impl Theme {
pub fn del(&self) -> Style {
self.bg(self.fg(mocha::RED), mocha::DEL_BG)
}
pub fn add_em(&self) -> Style {
self.bg(self.fg(mocha::GREEN), mocha::ADD_EM)
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED)
}
pub fn del_em(&self) -> Style {
self.bg(self.fg(mocha::RED), mocha::DEL_EM)
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED)
}
pub fn hunk(&self) -> Style {
self.fg(mocha::MAUVE)
}