//! Transcript model and rendering (markdown-ish text, tool calls, diffs). use crate::theme; use hx_ai::StreamEvent; use hx_core::hook::Event; use ratatui::style::{Modifier, Style}; use ratatui::text::{Line, Span}; use serde_json::Value; use std::time::{Duration, Instant}; #[derive(Debug, Clone, PartialEq)] pub enum Item { User(String), Assistant(String), Thinking(String), Tool { id: String, name: String, args: Value, result: Option<(String, bool)>, started: Instant, took: Option, }, Info(String), Error(String), /// Hook reports injected at turn end (`[lens] …`), shown as the lens block. Lens(Vec), } #[derive(Default)] pub struct Transcript { pub items: Vec, /// live output tails of running bash calls by command (copied from `State::live` per draw) pub live: std::collections::HashMap, /// true while the last Assistant/Thinking item is still streaming streaming: bool, } impl Transcript { pub fn push(&mut self, i: Item) { self.streaming = false; self.items.push(i); } pub fn apply(&mut self, ev: &Event) { match ev { Event::Stream(StreamEvent::TextDelta { text }) => match self.items.last_mut() { Some(Item::Assistant(s)) if self.streaming => s.push_str(text), _ => { self.push(Item::Assistant(text.clone())); self.streaming = true; } }, Event::Stream(StreamEvent::ThinkingDelta { text }) => match self.items.last_mut() { Some(Item::Thinking(s)) if self.streaming => s.push_str(text), _ => { self.push(Item::Thinking(text.clone())); self.streaming = true; } }, Event::Stream(StreamEvent::Done { .. }) => self.streaming = false, Event::ToolCall { id, name, args } => self.push(Item::Tool { id: id.clone(), name: name.clone(), args: args.clone(), result: None, started: Instant::now(), took: None, }), Event::ToolResult { id, content, is_error, .. } => { if let Some(Item::Tool { result, started, took, .. }) = self .items .iter_mut() .rev() .find(|i| matches!(i, Item::Tool { id: x, .. } if x == id)) { *result = Some((content.clone(), *is_error)); *took = Some(started.elapsed()); } } Event::Info(s) => self.push(Item::Info(s.clone())), Event::Injected(t) => self.push(Item::Lens(t.clone())), _ => {} } } /// Rendered lines for a transcript `width` columns wide (tool headers right-align to it). pub fn lines(&self, expanded: bool, width: u16) -> Vec> { 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))) { out.push(Line::default()); } } out } /// The tool running right now, for the activity line. pub fn running(&self) -> Option<(String, Instant)> { self.items.iter().rev().find_map(|i| match i { Item::Tool { name, result: None, started, .. } => Some((name.clone(), *started)), _ => None, }) } } /// `⠹ 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!(" {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(); let mut l = left; if let Some(pad) = (width as usize).checked_sub(lw + hint.width() + 1) { l.push(Span::raw(" ".repeat(pad + 1))); l.push(hint); } 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>) { 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() .find_map(|k| args[*k].as_str()) .map_or_else(|| args.to_string(), str::to_string); s.lines().next().unwrap_or_default().to_string() } /// Right-aligned outcome on the tool header: `+3 −1`, `12 lines`, `ok`, `exit 2`. fn outcome(name: &str, content: &str, err: bool) -> String { let m = theme::t().sym.minus; if err { return content .rsplit_once("[exit ") .and_then(|(_, r)| r.split_once(']')) .map_or("error".into(), |(n, _)| format!("exit {n}")); } match name { "edit" => { let n = |c: u8, skip: &str| { content .lines() .filter(|l| l.as_bytes().first() == Some(&c) && !l.starts_with(skip)) .count() }; format!("+{} {m}{}", n(b'+', "+++"), n(b'-', "---")) } "write" => content .rsplit_once('(') .map_or("ok".into(), |(_, r)| r.trim_end_matches(')').to_string()), "read" => format!("{} lines", content.lines().count()), // `[task explore · 12 tool calls · 41k tok · 38s]` is the last line of a task result "task" => content .lines() .last() .and_then(|l| l.strip_prefix("[task ")?.strip_suffix(']')) .map_or("ok".into(), str::to_string), _ => "ok".into(), } } fn fmt_dur(d: Duration) -> String { if d.as_secs() >= 60 { format!("{}m{:02}s", d.as_secs() / 60, d.as_secs() % 60) } else { format!("{:.1}s", d.as_secs_f32()) } } /// Truncate to `w` display columns, adding an ellipsis when cut. fn fit(s: &str, w: usize) -> String { if Span::raw(s).width() <= w { return s.to_string(); } let ell = theme::t().sym.ellipsis; let mut out = String::new(); for c in s.chars() { if Span::raw(format!("{out}{c}{ell}")).width() > w { break; } out.push(c); } out + ell } /// `● edit src/a.rs ············ +3 −1 · 0.2s ▸`; running: spinner and live seconds. fn tool_header( name: &str, args: &Value, result: &Option<(String, bool)>, started: Instant, took: Option, folded: bool, width: usize, ) -> Line<'static> { let th = theme::t(); let (mark, st) = match result { None => ( th.spin((started.elapsed().as_millis() / 80) as usize), th.accent(), ), Some((_, false)) => (th.sym.done, th.ok()), Some((_, true)) => (th.sym.err, th.err()), }; let mut right = match result { Some((c, e)) => outcome(name, c, *e), None => format!("{}s", started.elapsed().as_secs()), }; if let Some(d) = took { right = format!("{right} {} {}", th.sym.info, fmt_dur(d)); } if folded { right = format!("{right} {}", th.sym.more); } let left = format!("{mark} {name:<6} "); let lw = Span::raw(left.as_str()).width(); let rw = Span::raw(right.as_str()).width(); let room = width.saturating_sub(lw + rw + 1).max(8); let tgt = fit(&target(args), room); let pad = width.saturating_sub(lw + Span::raw(tgt.as_str()).width() + rw); Line::from(vec![ Span::styled(format!("{mark} "), st), Span::styled( format!("{name:<6} "), th.plain().add_modifier(Modifier::BOLD), ), Span::styled(tgt, th.sec()), Span::raw(" ".repeat(pad.max(1))), Span::styled( right, match result { Some((_, true)) => th.err(), None => th.accent(), _ => th.sec(), }, ), ]) } /// Prefix the first line with `mark` (styled) and indent the rest by two columns. fn lead(lines: Vec>, mark: &str, st: Style, out: &mut Vec>) { for (i, mut l) in lines.into_iter().enumerate() { let p = if i == 0 { Span::styled(format!("{mark} "), st) } else { Span::raw(" ") }; l.spans.insert(0, p); out.push(l); } } fn render(it: &Item, expanded: bool, width: usize, out: &mut Vec>) { let th = theme::t(); match it { Item::User(s) => { let b = th.plain().add_modifier(Modifier::BOLD); let ls = s.lines().map(|l| Line::styled(l.to_string(), b)).collect(); lead( ls, th.sym.user, th.accent().add_modifier(Modifier::BOLD), out, ); } Item::Assistant(s) => { let mut md = vec![]; crate::markdown::render(s, width.saturating_sub(2), &mut md); lead(md, " ", th.plain(), out); } Item::Thinking(s) if expanded => { let st = th.dim().add_modifier(Modifier::ITALIC); let ls = s.lines().map(|l| Line::styled(l.to_string(), st)).collect(); lead(ls, " ", st, out); } Item::Thinking(s) => out.push(Line::styled( format!( " thought · {} words {}", s.split_whitespace().count(), th.sym.more ), th.dim().add_modifier(Modifier::ITALIC), )), Item::Info(s) => out.push(Line::styled(format!("{} {s}", th.sym.info), th.dim())), Item::Lens(texts) => lens_block(texts, expanded, width, out), Item::Error(s) => out.push(Line::styled(format!("{} {s}", th.sym.err), th.err())), Item::Tool { name, args, result, started, took, .. } => { let mut body = vec![]; let folded = match result { Some((content, err)) => tool_body(name, content, *err, expanded, &mut body), None => false, }; out.push(tool_header( name, args, result, *started, *took, folded, width, )); out.extend(body); } } } /// `┄ lens ┄┄┄` rule, then per report a summary line (errors red, all-pass green) and, /// collapsed, the first findings; `ctrl-o` shows all. fn lens_block(texts: &[String], expanded: bool, width: usize, out: &mut Vec>) { let th = theme::t(); out.push(Line::styled(th.rule("lens", width), th.dim())); for t in texts { let mut lines = t.lines(); let first = lines.next().unwrap_or_default(); let title = first .strip_prefix("[lens] ") .unwrap_or(first) .trim_end_matches(':'); let rest: Vec<&str> = lines.collect(); // counts only mean something for diagnostics; test output quotes compiler lines let diag = title.starts_with("diagnostics"); let count = |k: &str| rest.iter().filter(|l| diag && l.contains(k)).count(); let (errors, warnings) = (count(" error: "), count(" warning: ")); let (mark, st) = if title.contains("failing") || errors > 0 { (th.sym.err, th.err()) } else if warnings > 0 { (th.sym.warn, th.warn()) } else { (th.sym.ok, th.ok()) }; let mut counts = vec![]; if errors > 0 { counts.push(format!( "{errors} error{}", if errors == 1 { "" } else { "s" } )); } if warnings > 0 { counts.push(format!( "{warnings} warning{}", if warnings == 1 { "" } else { "s" } )); } let counts = if counts.is_empty() { String::new() } else { format!(" · {}", counts.join(", ")) }; out.push(Line::from(vec![ Span::styled(format!("{mark} "), st), Span::raw(title.to_string()), Span::styled(counts, th.dim()), ])); let n = if expanded { rest.len() } else { rest.len().min(LENS_PREVIEW) }; for l in &rest[..n] { let ls = if l.contains(" error: ") { th.err() } else if l.contains(" warning: ") { th.warn() } else { th.dim() }; out.push(Line::from(vec![ Span::styled(format!(" {} ", th.sym.gutter), th.dim()), Span::styled(l.trim_start().to_string(), ls), ])); } if n < rest.len() { out.push(Line::styled( format!( " {} {} more lines {} ctrl-o expand", th.sym.ellipsis, rest.len() - n, th.sym.info ), th.dim(), )); } } } const LENS_PREVIEW: usize = 4; const DIFF_PREVIEW: usize = 6; const ERR_TAIL: usize = 5; /// Body lines behind a gutter. Collapsed: edit diff preview, error tail, nothing otherwise. /// Diffs get new-file line numbers from the `@@` headers. Returns true when output was /// hidden (header shows the fold marker). fn tool_body( name: &str, content: &str, err: bool, expanded: bool, out: &mut Vec>, ) -> bool { let th = theme::t(); let is_diff = name == "edit" && !err; // the edit tool's first line ("edited x") repeats the header let lines: Vec<&str> = content.lines().skip(usize::from(is_diff)).collect(); let (show, before, after) = if expanded { (&lines[..], 0, 0) } else if is_diff { let n = lines.len().min(DIFF_PREVIEW); (&lines[..n], 0, lines.len() - n) } else if err { let n = lines.len().saturating_sub(ERR_TAIL); (&lines[n..], n, 0) } else { (&lines[..0], 0, lines.len()) }; // number column wide enough for the biggest new-file line in the hunks let nw = if is_diff { lines .iter() .filter_map(|l| hunk_start(l)) .map(|n| (n + lines.len()).to_string().len()) .max() .unwrap_or(0) } else { 0 }; let g = |n: Option| { let num = n.map_or(String::new(), |n| n.to_string()); Span::styled(format!(" {num:>nw$} {} ", th.sym.gutter), th.dim()) }; let note = |s: String| Line::from(vec![g(None), Span::styled(s, th.dim())]); if before > 0 { out.push(note(format!( "{} {before} earlier lines {} ctrl-o expand", th.sym.ellipsis, th.sym.info ))); } let mut new_ln: Option = None; for l in &lines[..before] { new_ln = advance(new_ln, l); } for l in show { let (st, num) = if is_diff { let cur = new_ln.filter(|_| !l.starts_with('-') && !l.starts_with('@')); new_ln = advance(new_ln, l); match l.as_bytes().first() { Some(b'+') if !l.starts_with("+++") => (th.add(), cur), Some(b'-') if !l.starts_with("---") => (th.del(), None), Some(b'@') => (th.hunk(), None), _ => (th.sec(), cur), } } else if err { (th.err(), None) } else { (th.sec(), None) }; out.push(Line::from(vec![g(num), Span::styled(l.to_string(), st)])); } if after > 0 && is_diff { out.push(note(format!( "{} {after} more lines {} ctrl-o expand", th.sym.ellipsis, th.sym.info ))); } // write output is just the header's "N lines" !expanded && after > 0 && !is_diff && name != "write" } /// `@@ -a,b +c,d @@` → `c`. fn hunk_start(l: &str) -> Option { let r = l .strip_prefix("@@ ")? .split(' ') .nth(1)? .strip_prefix('+')?; r.split(',').next()?.parse().ok() } /// New-file line number for the line after `l`. fn advance(cur: Option, l: &str) -> Option { if let Some(n) = hunk_start(l) { return Some(n); } match l.as_bytes().first() { Some(b'-') => cur, _ => cur.map(|n| n + 1), } } #[cfg(test)] mod tests { use super::*; use serde_json::json; fn text(ls: &[Line]) -> Vec { ls.iter() .map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect()) .collect() } fn tool(name: &str, args: Value, out: &str, err: bool) -> Item { Item::Tool { id: "1".into(), name: name.into(), args, result: Some((out.into(), err)), started: Instant::now(), took: Some(Duration::from_millis(1234)), } } #[test] fn stream_and_tools() { let mut t = Transcript::default(); t.push(Item::User("hi\nthere".into())); for d in ["Hel", "lo"] { t.apply(&Event::Stream(StreamEvent::TextDelta { text: d.into() })); } t.apply(&Event::ToolCall { id: "1".into(), name: "edit".into(), args: json!({"path": "a.rs"}), }); assert_eq!(t.running().unwrap().0, "edit"); t.apply(&Event::ToolResult { id: "1".into(), name: "edit".into(), args: json!({}), content: "edited a.rs\n@@ -1 +1 @@\n-old\n+new".into(), is_error: false, }); assert!(t.running().is_none()); t.apply(&Event::Stream(StreamEvent::TextDelta { text: "After".into(), })); assert_eq!(t.items[1], Item::Assistant("Hello".into())); assert_eq!(t.items[3], Item::Assistant("After".into())); let ls = t.lines(false, 40); let s = text(&ls); assert_eq!(s[..2], ["❯ hi", " there"]); assert_eq!(s[3], " Hello"); assert!( s[5].starts_with("● edit a.rs ") && s[5].contains("+1 −1 · 0.0s"), "{s:?}" ); assert_eq!(s[5].chars().count(), 40, "header fills the width"); let minus = ls .iter() .find(|l| text(std::slice::from_ref(l))[0] == " │ -old") .unwrap(); assert_eq!(minus.spans[1].style.fg, theme::t().err().fg); // new-file line numbers from the hunk header assert!(s.contains(&" 1 │ +new".to_string()), "{s:?}"); } #[test] fn headers_at_two_widths() { let b = tool( "bash", json!({"command": "cargo test -p hx-lens rust_analyzer"}), "x\n[exit 101]", true, ); for w in [40, 80] { let mut out = vec![]; render(&b, false, w, &mut out); let s = text(&out); assert_eq!(s[0].chars().count(), w, "{s:?}"); assert!( s[0].starts_with("✗ bash cargo") && s[0].ends_with("exit 101 · 1.2s"), "{s:?}" ); } let mut out = vec![]; render(&b, false, 40, &mut out); assert!(text(&out)[0].contains("…"), "target truncated at 40 cols"); let w = tool( "write", json!({"path": "h.txt"}), "wrote h.txt (3 lines)", false, ); let mut out = vec![]; render(&w, false, 50, &mut out); assert!( text(&out)[0].ends_with(" 3 lines · 1.2s"), "{:?}", text(&out) ); let r = tool("read", json!({"path": "a"}), "1\n2", false); let mut out = vec![]; render(&r, false, 50, &mut out); assert_eq!(out.len(), 1); assert!(text(&out)[0].ends_with("2 lines · 1.2s ▸"), "folded marker"); } #[test] fn collapse_rules() { let body: String = (1..=20).map(|i| format!("l{i}\n")).collect(); let mut out = vec![]; assert!(!tool_body("bash", &body, true, false, &mut out)); let s = text(&out); assert_eq!(s[0], " │ … 15 earlier lines · ctrl-o expand"); assert_eq!(s.last().unwrap(), " │ l20"); out.clear(); assert!(tool_body("bash", &body, false, false, &mut out) && out.is_empty()); assert!(!tool_body("bash", &body, false, true, &mut out)); assert_eq!(out.len(), 20); out.clear(); let diff: String = "edited a\n".to_string() + &(1..=10).map(|i| format!("+l{i}\n")).collect::(); tool_body("edit", &diff, false, false, &mut out); assert_eq!(out.len(), DIFF_PREVIEW + 1); assert_eq!( text(&out).last().unwrap(), " │ … 4 more lines · ctrl-o expand" ); let mut out = vec![]; render(&Item::Thinking("a b c".into()), false, 40, &mut out); assert_eq!(text(&out), [" thought · 3 words ▸"]); let mut out = vec![]; render(&Item::Thinking("a b c".into()), true, 40, &mut out); assert_eq!(text(&out), [" a b c"]); } #[test] fn lens() { let mut t = Transcript::default(); t.apply(&Event::Injected(vec![ "[lens] diagnostics for files changed this turn:\nsrc/a.rs:\n 3:1 error: E0308 mismatched (rust-analyzer)\n 9:2 warning: unused (rust-analyzer)\n 10:2 warning: x (r)\n 11:2 warning: y (r)\n 12:2 warning: z (r)".into(), "[lens] tests: all 21 selected tests pass now".into(), ])); let s = text(&t.lines(false, 30)); assert_eq!(s[0].chars().count(), 30); assert!(s[0].starts_with("┈ lens ┈")); assert_eq!( s[1], "✗ diagnostics for files changed this turn · 1 error, 4 warnings" ); assert_eq!(s[2], " │ src/a.rs:"); assert_eq!(s[3], " │ 3:1 error: E0308 mismatched (rust-analyzer)"); assert_eq!(s[6], " … 2 more lines · ctrl-o expand"); assert_eq!(s[7], "✓ tests: all 21 selected tests pass now"); assert_eq!( text(&t.lines(true, 30)).len(), 10, "expanded shows every finding" ); } #[test] fn activity() { 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"); } }