7 Commits
9 changed files with 661 additions and 49 deletions

No files matched your search

+1 -1
View File
@@ -85,7 +85,7 @@ tests = "turn_end" # affected tests: turn_end | agent_end | off
Permissions: only writes ask. `write`/`edit` and unknown `bash` commands prompt; `read` and read-only `bash` (`ls cat head tail wc grep rg fd pwd echo stat file du df which tree diff`, `git status|log|diff|show|branch|blame|ls-files|rev-parse`) run freely, unless chained/redirected or a path looks secret (`.env*`, `.ssh/`, `.aws/`, `*.pem`, `*.key`, `id_rsa*`, `.netrc`, `.git-credentials`, `auth.json`), which asks first. `--yolo` skips all prompts.
The model can call `task(prompt, kind)` to run a subagent with a fresh context and get back only its final answer (cut at 8 KB), so big searches don't fill the main context. `explore` (default) is read-only (`read`, `lsp`, `bash`) on the provider's cheapest model (`explore_model` in config); `general` has the parent's tools and model, and the lens runs on its edits. Up to 3 run in parallel, none can start another, a parent abort stops them. Their sessions are written to `<session>.sub/`; `hx stats` lists them and the footer token counts include them. **Overview:** while any subagent exists, a list sits above the footer (bottom right: spinner/✓, id, kind, task, time, calls, tokens). `ctrl-g` focuses it (`↑↓`, `enter` opens, `esc` closes); the detail view shows that agent's live transcript. Typing there messages the agent: while it runs the text is delivered at its next turn end (like steering the main agent), after it finished it continues that agent's conversation. `ctrl-c` aborts that agent only; `ctrl-s` sends its last answer to the main chat as `[subagent N] …`. NDJSON/RPC carry no per-agent events yet.
The model can call `task(prompt, kind)` (or `task(prompts=[…], kind)` to fan out: one subagent per prompt, parallel, answers returned numbered; a lone task blocks the parent, so the tool description steers the model to batches) to run a subagent with a fresh context and get back only its final answer (cut at 8 KB), so big searches don't fill the main context. `explore` (default) is read-only (`read`, `lsp`, `bash`) on the provider's cheapest model (`explore_model` in config); `general` has the parent's tools and model, and the lens runs on its edits. Up to 3 run in parallel, none can start another, a parent abort stops them. Their sessions are written to `<session>.sub/`; `hx stats` shows `task` usage (calls, lone vs. batched turns) and lists them and the footer token counts include them. **Overview:** while any subagent exists, a list sits above the footer (bottom right: spinner/✓, id, kind, task, time, calls, tokens). `ctrl-g` focuses it (`↑↓`, `enter` opens, `esc` closes); the detail view shows that agent's live transcript. Typing there messages the agent: while it runs the text is delivered at its next turn end (like steering the main agent), after it finished it continues that agent's conversation. `ctrl-c` aborts that agent only; `ctrl-s` sends its last answer to the main chat as `[subagent N] …`. NDJSON/RPC carry no per-agent events yet.
A child starts with a cold prompt cache and costs tokens of its own: it saves *main-context* size, not total tokens.
+1
View File
@@ -413,6 +413,7 @@ async fn main() -> Result<()> {
Some(Cmd::Logout { provider }) => return Ok(auth::logout(provider)?),
Some(Cmd::Stats { session }) => {
print!("{}", hx_core::stats::report(&Session::open(&session)?));
print!("{}", hx_core::stats::task_report(&Session::open(&session)?));
print!("{}", hx_core::stats::sub_report(&session));
return Ok(());
}
+64
View File
@@ -6,6 +6,46 @@ use hx_ai::{ContentBlock, Role};
use std::collections::HashMap;
use std::fmt::Write;
/// How `task` was used in the parent session: calls per assistant turn (1 = parent waits on a
/// lone child), kinds, and bytes of answers carried back. Empty when `task` was never called.
pub fn task_report(s: &Session) -> String {
let (mut single, mut batch, mut calls, mut explore, mut bytes) = (0, 0, 0, 0, 0);
let mut ids = std::collections::HashSet::new();
for m in s.messages() {
let mut n = 0;
for b in &m.content {
match b {
ContentBlock::ToolUse { id, name, input } if name == "task" => {
n += 1;
ids.insert(id.clone());
if input["kind"].as_str().unwrap_or("explore") == "explore" {
explore += 1;
}
}
ContentBlock::ToolResult {
tool_use_id,
content,
..
} if ids.contains(tool_use_id) => bytes += content.len(),
_ => {}
}
}
calls += n;
match n {
0 => {}
1 => single += 1,
_ => batch += 1,
}
}
if calls == 0 {
return String::new();
}
format!(
"task calls: {calls} ({explore} explore, {} general); turns with one task {single}, with several {batch}; answers {bytes} bytes\n",
calls - explore
)
}
/// One line per subagent log in `<session>.sub/` (empty when there are none).
pub fn sub_report(session_path: &std::path::Path) -> String {
let mut files: Vec<_> = std::fs::read_dir(session_path.with_extension("sub"))
@@ -276,6 +316,30 @@ mod tests {
use super::*;
use hx_ai::{Message, Usage};
#[test]
fn task_report_counts_lone_and_batched_turns() {
let d = tempfile::tempdir().unwrap();
let mut s = Session::open(d.path().join("s.jsonl")).unwrap();
let tu = |id: &str, k: &str| ContentBlock::ToolUse {
id: id.into(),
name: "task".into(),
input: serde_json::json!({"kind": k}),
};
for c in [
vec![tu("a", "explore")],
vec![tu("b", "explore"), tu("c", "general")],
] {
s.append(Message {
role: Role::Assistant,
content: c,
})
.unwrap();
}
let r = task_report(&s);
assert!(r.contains("task calls: 3 (2 explore, 1 general)"), "{r}");
assert!(r.contains("one task 1, with several 1"), "{r}");
}
#[test]
fn report_counts() {
let d = tempfile::tempdir().unwrap();
+62 -4
View File
@@ -252,11 +252,12 @@ impl Task {
pub fn spec() -> ToolSpec {
ToolSpec {
name: "task".into(),
description: "Run a subagent in a fresh context; you get back only its final answer. kind=explore (default): read-only research on a cheaper model; use it for searching/reading that would fill your context (many files or >10k tokens). kind=general: same tools as you, may edit. The subagent sees nothing of this conversation: make the prompt self-contained. Several task calls in one turn run in parallel. Not for small lookups.".into(),
description: "Run a subagent in a fresh context; you get back only its final answer. kind=explore (default): read-only research on a cheaper model; use it for searching/reading that would fill your context (many files or >10k tokens). kind=general: same tools as you, may edit. The subagent sees nothing of this conversation: make every prompt self-contained. You are blocked until it answers, so a single task you then wait on only pays off when the search would put >10k tokens in your context; otherwise do it yourself. Prefer splitting work into 2+ independent subtasks: pass `prompts` (array) or several task calls in one turn, they run in parallel. Not for small lookups.".into(),
input_schema: json!({"type":"object","properties":{
"prompt":{"type":"string"},
"prompts":{"type":"array","items":{"type":"string"},"description":"several independent subtasks: one subagent each, run in parallel, answers returned numbered"},
"kind":{"type":"string","enum":["explore","general"]}},
"required":["prompt"]}),
}),
}
}
@@ -266,8 +267,38 @@ impl Tool for Task {
spec()
}
async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult {
let prompt = a["prompt"].as_str().unwrap_or_default();
let (kind, role) = match a["kind"].as_str() {
let Some(ps) = a["prompts"].as_array() else {
return self
.run(
a["prompt"].as_str().unwrap_or_default(),
a["kind"].as_str(),
cx,
)
.await;
};
// fan-out: one child per prompt, concurrent (the semaphore caps how many run at once)
let kind = a["kind"].as_str();
let rs = futures::future::join_all(
ps.iter()
.map(|p| self.run(p.as_str().unwrap_or_default(), kind, cx)),
)
.await;
let mut out = String::new();
let mut err = !rs.is_empty();
for (i, r) in rs.into_iter().enumerate() {
err &= r.is_error;
out.push_str(&format!("## {}\n{}\n\n", i + 1, r.content));
}
ToolResult {
content: out,
is_error: err,
}
}
}
impl Task {
async fn run(&self, prompt: &str, kind: Option<&str>, cx: &ToolCtx) -> ToolResult {
let (kind, role) = match kind {
None | Some("explore") => ("explore", &self.explore),
Some("general") => ("general", &self.general),
Some(k) => return ToolResult::err(format!("unknown kind `{k}` (explore | general)")),
@@ -488,6 +519,33 @@ mod tests {
assert!(d.path().join("s.sub/001-explore.jsonl").exists());
}
#[tokio::test]
async fn prompts_fan_out_into_numbered_answers() {
let d = tempfile::tempdir().unwrap();
let p = Arc::new(Script(
Mutex::new(vec![text("one"), text("two")]),
Default::default(),
));
let t = Task::new(
role(&p, "cheap"),
role(&p, "main"),
d.path().join("s.sub"),
3,
);
let cx = ToolCtx {
cwd: d.path().into(),
state: Default::default(),
};
let r = t.call(json!({"prompts":["a","b"]}), &cx).await;
assert!(!r.is_error, "{r:?}");
assert!(
r.content.starts_with("## 1\n") && r.content.contains("## 2\n"),
"{}",
r.content
);
assert_eq!(cx.state.subs.list().len(), 2);
}
#[tokio::test]
async fn kind_picks_role_unknown_errors_long_answer_cut() {
let d = tempfile::tempdir().unwrap();
+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]
+16
View File
@@ -20,6 +20,11 @@ impl Editor {
pub fn insert(&mut self, s: &str) {
// normalize pasted CRLF
let s = s.replace("\r\n", "\n").replace('\r', "\n");
// drop ESC etc. so pasted escape sequences cannot act on the terminal
let s: String = s
.chars()
.filter(|c| !c.is_control() || matches!(c, '\n' | '\t'))
.collect();
self.buf.insert_str(self.cur, &s);
self.cur += s.len();
}
@@ -278,3 +283,14 @@ mod tests {
assert_eq!((e.buf.as_str(), e.cur), ("look at @src/main.rs ", 21));
}
}
#[cfg(test)]
mod paste_tests {
use super::*;
#[test]
fn paste_multiline_keeps_text_and_strips_controls() {
let mut e = Editor::default();
e.insert("a\r\nb\x1b[31m\tc\x07");
assert_eq!(e.buf, "a\nb[31m\tc");
}
}
+25 -2
View File
@@ -416,12 +416,15 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
std::io::stdout(),
crossterm::event::PopKeyboardEnhancementFlags
);
let _ = crossterm::execute!(std::io::stdout(), crossterm::event::DisableBracketedPaste);
prev(i)
}));
}
if mouse {
let _ = crossterm::execute!(std::io::stdout(), crossterm::event::EnableMouseCapture);
}
// one Paste event per paste instead of a key event (and redraw) per char; newlines no longer submit
let _ = crossterm::execute!(std::io::stdout(), crossterm::event::EnableBracketedPaste);
let mut keys = EventStream::new();
let mut tick = tokio::time::interval(std::time::Duration::from_millis(50));
let mut lens_tick = tokio::time::interval(std::time::Duration::from_secs(2));
@@ -485,7 +488,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
}
}
TEvent::Mouse(m) => on_mouse(&mut app, m),
TEvent::Paste(s) => app.ed.insert(&s),
TEvent::Paste(s) if app.perm.is_none() && app.choose.is_none() && app.ask.is_none() => app.ed.insert(&s),
TEvent::Resize(..) => app.sel = None,
_ => {}
}
@@ -574,6 +577,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
}
}
}
let _ = crossterm::execute!(std::io::stdout(), crossterm::event::DisableBracketedPaste);
if mouse {
let _ = crossterm::execute!(std::io::stdout(), crossterm::event::DisableMouseCapture);
}
@@ -1000,6 +1004,17 @@ fn show(app: &mut App, title: &str, text: String) {
}
/// Returns a line to submit, if any.
/// Accepted files leave the edits log, so the next `/diff` lists only what is still open.
fn drop_accepted(app: &App) {
let Some(r) = &app.review else { return };
let acc = r.accepted();
app.state
.edits
.lock()
.unwrap_or_else(|e| e.into_inner())
.retain(|e| !acc.contains(&e.path));
}
fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option<String> {
let ctrl = k.modifiers.contains(KeyModifiers::CONTROL);
let alt = k.modifiers.contains(KeyModifiers::ALT);
@@ -1047,7 +1062,10 @@ fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option<String> {
}
if let Some(r) = &mut app.review {
match r.key(k) {
review::Act::Close => app.review = None,
review::Act::Close => {
drop_accepted(app);
app.review = None;
}
review::Act::Reverted(p) => {
app.state
.edits
@@ -1057,6 +1075,11 @@ 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) => {
drop_accepted(app);
app.review = None;
return Some(text);
}
review::Act::None => {}
}
return None;
+480 -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,73 @@ 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,
wrap: bool,
/// Horizontal scroll in chars (only when not wrapping).
xoff: usize,
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 +154,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 +163,203 @@ 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,
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<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
}
/// Paths marked accepted; the app drops them from the edits log when the review ends.
pub fn accepted(&self) -> Vec<PathBuf> {
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;
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('w') => {
self.wrap = !self.wrap;
self.xoff = 0;
}
KeyCode::Char('p') | KeyCode::BackTab => {
self.sel = (self.sel + n - 1) % n;
self.scroll = 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('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 +376,95 @@ impl Review {
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<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 gutter = String::new();
if self.nums && r.kind != Kind::Hunk {
let n = |v: Option<usize>| 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::<Vec<_>>()
})
.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();
@@ -115,17 +474,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 · 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(
" 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 +515,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.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,
);
}
}
}
@@ -226,4 +613,56 @@ 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"),
}
// 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<Line>| ls.iter().map(|l| l.to_string()).collect::<Vec<_>>();
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]));
}
}
+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)
}