tui: live bash output, token counter, structured lens view for side panel

This commit is contained in:
hermes committed 2026-10-09 15:10:59 +00:00
1 parent 79bd3b8ea7
commit c57d238f7b
7 files changed
+284 -67

No files matched your search

+94 -52
View File
@@ -188,6 +188,8 @@ struct App {
sub_t: std::collections::HashMap<usize, Transcript>,
/// subagent list focused / one agent open
agents: Option<agents::View>,
/// output tokens of the current run: finished requests + streamed estimate (chars/4)
run_tokens: (u64, u64),
/// header: `~`-shortened cwd and (branch, dirty), refreshed after each run
cwd_label: String,
git: Option<(String, bool)>,
@@ -333,6 +335,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
expanded: false,
busy: false,
queue: VecDeque::new(),
run_tokens: (0, 0),
cwd_label: home_short(&cwd),
git: git_head(&cwd),
st: status::Status {
@@ -500,7 +503,15 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
if let Event::Stream(hx_ai::StreamEvent::Quota(q)) = &e {
app.st.quota = Some(q.clone());
}
if let Event::Stream(
hx_ai::StreamEvent::TextDelta { text }
| hx_ai::StreamEvent::ThinkingDelta { text },
) = &e
{
app.run_tokens.1 += text.len() as u64;
}
if let Event::Stream(hx_ai::StreamEvent::Done { usage, .. }) = &e {
app.run_tokens = (app.run_tokens.0 + usage.output_tokens, 0);
app.st.usage.add(usage);
app.st.ctx_tokens = (usage.input_tokens + usage.cache_read_tokens + usage.cache_write_tokens + usage.output_tokens) as usize;
}
@@ -1395,6 +1406,7 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
"compact" => {
app.busy = true;
app.since = Instant::now();
app.run_tokens = (0, 0);
app.t.push(Item::Info("compacting…".into()));
let (agent, tx) = (agent.clone(), tx.clone());
tokio::spawn(async move {
@@ -1445,6 +1457,7 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
}));
app.busy = true;
app.since = Instant::now();
app.run_tokens = (0, 0);
let prompt = expand_mentions(&line, cwd);
let (agent, tx) = (agent.clone(), tx.clone());
let effort = app.st.effort;
@@ -1565,6 +1578,12 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
}
};
app.areas.chat = main;
app.t.live = app
.state
.live
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone();
let para = Paragraph::new(app.t.lines(app.expanded, main.width)).wrap(Wrap { trim: false });
let total = para.line_count(main.width) as u16;
let top = app.scroll.resolve(total, main.height);
@@ -1603,6 +1622,7 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
al.push(transcript::activity_line(
&what,
app.since.elapsed(),
app.run_tokens.0 + app.run_tokens.1 / 4,
frame,
act.width,
));
@@ -1686,8 +1706,11 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
}
}
const SIDE_DIAGS: usize = 8;
const SIDE_TESTS: usize = 6;
/// Right-hand lens panel on wide terminals: servers, last turn's diagnostics and tests,
/// context numbers, MCP servers. Built from `/lsp` status lines and the last lens report.
/// context numbers, MCP servers. Servers from `/lsp` status lines, findings from `State::lens`.
fn side_lines(app: &App, w: usize) -> Vec<Line<'static>> {
let th = theme::t();
let sec = |label: String| {
@@ -1731,60 +1754,58 @@ fn side_lines(app: &App, w: usize) -> Vec<Line<'static>> {
Span::styled(format!(" {word}"), th.sec()),
]));
}
// last lens report in the transcript
let last = app.t.items.iter().rev().find_map(|i| match i {
Item::Lens(v) => Some(v),
_ => None,
});
let diag = last.and_then(|v| v.iter().find(|t| t.contains("diagnostics")));
let tests = last.and_then(|v| v.iter().find(|t| t.contains("test")));
if let Some(d) = diag {
let mut file = "";
let mut items = vec![];
for x in d.lines().skip(1) {
if let Some(f) = x.strip_suffix(':').filter(|_| !x.starts_with(' ')) {
file = f.rsplit('/').next().unwrap_or(f);
} else if let Some((pos, rest)) = x.trim().split_once(' ') {
let (mark, st) = if rest.starts_with("error") {
(th.sym.err, th.err())
} else {
(th.sym.warn, th.warn())
};
let msg = rest.split_once(": ").map_or(rest, |p| p.1);
// drop the trailing `(server)` tag
let msg = msg.rsplit_once(" (").map_or(msg, |p| p.0);
items.push(Line::from(vec![
Span::styled(format!("{mark} "), st),
Span::styled(format!("{file}:{pos}"), th.plain()),
]));
items.push(Line::styled(format!(" {msg}"), th.sec()));
}
let view = app
.state
.lens
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone();
if !view.diags.is_empty() {
l.push(Line::default());
l.push(sec(format!("diagnostics {}", view.diags.len())));
let mut ds = view.diags.clone();
ds.sort_by_key(|d| (!d.error, d.file.clone(), d.line));
for d in ds.iter().take(SIDE_DIAGS) {
let (mark, st) = if d.error {
(th.sym.err, th.err())
} else {
(th.sym.warn, th.warn())
};
let file = d.file.rsplit('/').next().unwrap_or(&d.file);
l.push(Line::from(vec![
Span::styled(format!("{mark} "), st),
Span::styled(format!("{file}:{}:{}", d.line, d.col), th.plain()),
]));
l.push(Line::styled(format!(" {}", d.message), th.sec()));
}
if ds.len() > SIDE_DIAGS {
l.push(Line::styled(
format!(" {} {} more", th.sym.ellipsis, ds.len() - SIDE_DIAGS),
th.dim(),
));
}
l.push(Line::default());
l.push(sec(format!("diagnostics {}", items.len() / 2)));
l.extend(items);
}
if let Some(t) = tests {
let first = t.lines().next().unwrap_or_default();
let first = first
.strip_prefix("[lens] ")
.unwrap_or(first)
.trim_end_matches(':');
let bad = first.contains("failing");
if let Some(ts) = &view.tests {
let mut ts = ts.clone();
// failures first
ts.sort_by_key(|t| t.1);
l.push(Line::default());
l.push(sec("tests".into()));
l.push(Line::from(vec![
Span::styled(
format!("{} ", if bad { th.sym.err } else { th.sym.ok }),
if bad { th.err() } else { th.ok() },
),
Span::styled(first.trim_start_matches("tests: ").to_string(), th.plain()),
]));
l.extend(
t.lines()
.skip(1)
.map(|x| Line::styled(format!(" {}", x.trim()), th.sec())),
);
l.push(sec(format!("affected tests {}", ts.len())));
for (n, ok) in ts.iter().take(SIDE_TESTS) {
l.push(Line::from(vec![
Span::styled(
format!("{} ", if *ok { th.sym.ok } else { th.sym.err }),
if *ok { th.ok() } else { th.err() },
),
Span::styled(n.clone(), th.plain()),
]));
}
if ts.len() > SIDE_TESTS {
l.push(Line::styled(
format!(" {} {} more", th.sym.ellipsis, ts.len() - SIDE_TESTS),
th.dim(),
));
}
}
let u = &app.st.usage;
let tot = u.input_tokens + u.cache_read_tokens + u.cache_write_tokens;
@@ -2068,7 +2089,27 @@ mod tests {
let mut app = test_app();
app.mcp = vec![("git".into(), true), ("db".into(), false)];
app.lens_lines = vec!["rust-analyzer @ /p: running".into()];
*app.state.lens.lock().unwrap() = hx_core::LensView {
diags: vec![hx_core::Diag {
file: "crates/a/src/codemode.rs".into(),
line: 88,
col: 13,
error: false,
message: "unused variable".into(),
}],
tests: Some(vec![("a::ok".into(), true), ("a::bad".into(), false)]),
};
let s = screen(&mut app, 160, 50);
assert!(
s.contains("diagnostics 1 ┈") && s.contains("⚠ codemode.rs:88:13"),
"{s}"
);
assert!(
s.contains("affected tests 2 ┈") && s.contains("✗ a::bad"),
"{s}"
);
let bad = s.find("✗ a::bad").unwrap();
assert!(bad < s.find("✓ a::ok").unwrap(), "failures first");
assert!(
s.contains("/lsp") && s.contains("● rust-analyzer ready"),
"{s}"
@@ -2331,6 +2372,7 @@ mod tests {
fn test_app() -> App {
App {
run_tokens: (0, 0),
cwd_label: "~/w".into(),
git: None,
t: Transcript::default(),
+73 -5
View File
@@ -30,6 +30,8 @@ pub enum Item {
#[derive(Default)]
pub struct Transcript {
pub items: Vec<Item>,
/// live output tails of running bash calls by command (copied from `State::live` per draw)
pub live: std::collections::HashMap<String, String>,
/// true while the last Assistant/Thinking item is still streaming
streaming: bool,
}
@@ -97,6 +99,17 @@ impl Transcript {
let mut out = vec![];
for (n, it) in self.items.iter().enumerate() {
render(it, expanded, width as usize, &mut out);
if let Item::Tool {
name,
args,
result: None,
..
} = it
&& name == "bash"
&& let Some(tail) = args["command"].as_str().and_then(|c| self.live.get(c))
{
live_tail(tail, width as usize, &mut out);
}
// consecutive tool calls stack without a gap
let tool = |i: Option<&Item>| matches!(i, Some(Item::Tool { .. }));
if !(tool(Some(it)) && tool(self.items.get(n + 1))) {
@@ -120,13 +133,28 @@ impl Transcript {
}
}
/// `⠹ working 38s · bash esc to abort` — `frame` picks the spinner glyph.
pub fn activity_line(what: &str, elapsed: Duration, frame: usize, width: u16) -> Line<'static> {
/// `⠹ working 38s · bash · ↓ 4.1k tokens esc to abort` — `frame` picks the spinner
/// glyph, `tokens` = output tokens of this run so far.
pub fn activity_line(
what: &str,
elapsed: Duration,
tokens: u64,
frame: usize,
width: u16,
) -> Line<'static> {
let th = theme::t();
let tk = if tokens >= 1000 {
format!("{:.1}k", tokens as f64 / 1000.0)
} else {
tokens.to_string()
};
let left = vec![
Span::styled(format!("{} ", th.spin(frame)), th.accent()),
Span::styled(format!("working {}s", elapsed.as_secs()), th.accent()),
Span::styled(format!(" {} {what}", th.sym.info), th.sec()),
Span::styled(
format!(" {0} {what} {0} {1} {tk} tokens", th.sym.info, th.sym.down),
th.sec(),
),
];
let hint = Span::styled("esc to abort", th.dim());
let lw: usize = left.iter().map(Span::width).sum();
@@ -138,6 +166,25 @@ pub fn activity_line(what: &str, elapsed: Duration, frame: usize, width: u16) ->
Line::from(l)
}
/// Last [`LIVE_LINES`] non-empty lines of a running command, dim and indented.
fn live_tail(tail: &str, width: usize, out: &mut Vec<Line<'static>>) {
let th = theme::t();
// carriage returns (progress bars): keep what's after the last one per line
let ls: Vec<&str> = tail
.lines()
.map(|l| l.rsplit('\r').next().unwrap_or(l))
.filter(|l| !l.trim().is_empty())
.collect();
for l in &ls[ls.len().saturating_sub(LIVE_LINES)..] {
out.push(Line::styled(
format!(" {}", fit(l, width.saturating_sub(4))),
th.dim(),
));
}
}
const LIVE_LINES: usize = 2;
fn target(args: &Value) -> String {
let s = ["path", "command", "pattern", "query"]
.iter()
@@ -727,8 +774,29 @@ mod tests {
#[test]
fn activity() {
let l = activity_line("bash", Duration::from_millis(12_900), 2, 40);
assert_eq!(text(&[l]), ["⠹ working 12s · bash esc to abort"]);
let l = activity_line("bash", Duration::from_millis(12_900), 4130, 2, 60);
assert_eq!(
text(&[l]),
["⠹ working 12s · bash · ↓ 4.1k tokens esc to abort"]
);
}
#[test]
fn running_bash_shows_live_tail() {
let mut t = Transcript::default();
t.apply(&Event::ToolCall {
id: "1".into(),
name: "bash".into(),
args: json!({"command": "cargo test"}),
});
t.live.insert(
"cargo test".into(),
" Compiling a\n\n Compiling b\nprogress 10%\rprogress 90%\n".into(),
);
let s = text(&t.lines(false, 40));
assert_eq!(s[1..3], [" Compiling b", " progress 90%"], "{s:?}");
t.live.clear();
assert_eq!(t.lines(false, 40).len(), 2, "no tail when nothing is live");
}
#[test]