//! 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, /// 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); // 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, }) } } /// `⠹ bash 12s` — `frame` picks the spinner glyph, `elapsed` is shown in whole seconds. pub fn activity_line(what: &str, elapsed: Duration, frame: usize) -> Line<'static> { const SPIN: [&str; 10] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]; let th = theme::t(); let g = if th.sym.ok == "+" { ["-", "\\", "|", "/"][frame % 4] } else { SPIN[frame % 10] }; Line::from(vec![ Span::styled(format!(" {g} "), th.accent()), Span::styled(format!("{what} {}s", elapsed.as_secs()), th.dim()), ]) } 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()), _ => "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 ▸` fn tool_header( name: &str, args: &Value, result: &Option<(String, bool)>, took: Option, folded: bool, width: usize, ) -> Line<'static> { let th = theme::t(); let (mark, st) = match result { None => (th.sym.pending, th.warn()), Some((_, false)) => (th.sym.ok, th.ok()), Some((_, true)) => (th.sym.err, th.err()), }; let mut right = match result { Some((c, e)) => outcome(name, c, *e), None => String::new(), }; if let Some(d) = took { right = format!("{right} {}", fmt_dur(d)); } if folded { right = format!("{right} {}", th.sym.more); } let left = format!(" {mark} {name:<5} "); 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:<5} "), th.plain().add_modifier(Modifier::BOLD), ), Span::raw(tgt), Span::raw(" ".repeat(pad.max(1))), Span::styled( right, if matches!(result, Some((_, true))) { th.err() } else { th.dim() }, ), ]) } /// 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![]; markdown(s, &mut md); lead(md, th.sym.asst, th.accent(), 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, 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, *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(); let rule = if th.sym.ok == "+" { "-" } else { "┄" }; let head = format!(" {rule} lens "); let fill = rule.repeat(width.saturating_sub(Span::raw(head.as_str()).width())); out.push(Line::styled(format!("{head}{fill}"), 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.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)", th.sym.ellipsis, rest.len() - n ), 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. /// 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()) }; let g = |st: Style| Span::styled(format!(" {} ", th.sym.gutter), st); let note = |s: String| Line::from(vec![g(th.dim()), Span::styled(s, th.dim())]); if before > 0 { out.push(note(format!( "{} {before} earlier lines (ctrl-o)", th.sym.ellipsis ))); } for l in show { let st = if is_diff { match l.as_bytes().first() { Some(b'+') if !l.starts_with("+++") => th.add(), Some(b'-') if !l.starts_with("---") => th.del(), Some(b'@') => th.hunk(), _ => th.dim(), } } else if err { th.err() } else { th.dim() }; out.push(Line::from(vec![ g(th.dim()), Span::styled(l.to_string(), st), ])); } if after > 0 && is_diff { out.push(note(format!( "{} {after} more lines (ctrl-o)", th.sym.ellipsis ))); } // write output is just the header's "N lines" !expanded && after > 0 && !is_diff && name != "write" } /// Minimal markdown: fenced code, headings, bullets, inline `code` and **bold**. fn markdown(s: &str, out: &mut Vec>) { let mut code = false; for l in s.lines() { if l.trim_start().starts_with("```") { code = !code; out.push(Line::styled(l.to_string(), theme::t().dim())); continue; } if code { out.push(Line::styled(l.to_string(), theme::t().block_code())); } else if l.starts_with('#') { out.push(Line::styled( l.trim_start_matches('#').trim().to_string(), theme::t() .plain() .add_modifier(Modifier::BOLD | Modifier::UNDERLINED), )); } else { out.push(inline(l)); } } } fn inline(l: &str) -> Line<'static> { let mut spans = vec![]; let mut rest = l; while !rest.is_empty() { let next = [ ("`", theme::t().code()), ("**", theme::t().plain().add_modifier(Modifier::BOLD)), ] .into_iter() .filter_map(|(d, st)| { let i = rest.find(d)?; let j = rest[i + d.len()..].find(d)?; Some((i, j, d, st)) }) .min_by_key(|x| x.0); match next { Some((i, j, d, st)) => { spans.push(Span::raw(rest[..i].to_string())); spans.push(Span::styled( rest[i + d.len()..i + d.len() + j].to_string(), st, )); rest = &rest[i + d.len() * 2 + j..]; } None => { spans.push(Span::raw(rest.to_string())); break; } } } Line::from(spans) } #[cfg(test)] mod tests { use super::*; use ratatui::style::Color; 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, Some(Color::Red)); } #[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)"); 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)"); 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)"); 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), 2); assert_eq!(text(&[l]), [" ⠹ bash 12s"]); } #[test] fn inline_md() { assert_eq!(text(&[inline("a `b` **c** d")]), ["a b c d"]); assert_eq!(inline("a `b` c").spans[1].style.fg, Some(Color::Yellow)); assert_eq!(text(&[inline("x ` unclosed")]), ["x ` unclosed"]); } }