M9: theme, turn layout, footer, input, activity line
ci / check (push) Canceled after 0s
ci / check (pull_request) Canceled after 0s

Closes #76, closes #77, closes #79, closes #80, closes #81
This commit is contained in:
hermes committed 2026-10-01 08:56:27 +00:00
1 parent 33539f64ae
commit b0b22b4061
4 files changed
+667 -186

No files matched your search

+352 -106
View File
@@ -1,10 +1,12 @@
//! 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::{Color, Modifier, Style};
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 {
@@ -16,6 +18,8 @@ pub enum Item {
name: String,
args: Value,
result: Option<(String, bool)>,
started: Instant,
took: Option<Duration>,
},
Info(String),
Error(String),
@@ -56,6 +60,8 @@ impl Transcript {
name: name.clone(),
args: args.clone(),
result: None,
started: Instant::now(),
took: None,
}),
Event::ToolResult {
id,
@@ -63,13 +69,19 @@ impl Transcript {
is_error,
..
} => {
if let Some(Item::Tool { result, .. }) = self
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())),
@@ -77,125 +89,283 @@ impl Transcript {
}
}
pub fn lines(&self, expanded: bool) -> Vec<Line<'static>> {
/// Rendered lines for a transcript `width` columns wide (tool headers right-align to it).
pub fn lines(&self, expanded: bool, width: u16) -> Vec<Line<'static>> {
let mut out = vec![];
for it in &self.items {
render(it, expanded, &mut out);
out.push(Line::default());
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,
})
}
}
fn dim() -> Style {
Style::default().fg(Color::DarkGray)
/// `⠹ 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 summary(name: &str, args: &Value) -> String {
fn target(args: &Value) -> String {
let s = ["path", "command", "pattern", "query"]
.iter()
.find_map(|k| args[*k].as_str());
let s = s.map_or_else(|| args.to_string(), str::to_string);
let first = s.lines().next().unwrap_or_default();
let mut t: String = first.chars().take(120).collect();
if t.len() < s.len() {
t.push('…');
}
format!("{name} {t}")
.find_map(|k| args[*k].as_str())
.map_or_else(|| args.to_string(), str::to_string);
s.lines().next().unwrap_or_default().to_string()
}
fn render(it: &Item, expanded: bool, out: &mut Vec<Line<'static>>) {
/// 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<Duration>,
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<Line<'static>>, mark: &str, st: Style, out: &mut Vec<Line<'static>>) {
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<Line<'static>>) {
let th = theme::t();
match it {
Item::User(s) => {
for (i, l) in s.lines().enumerate() {
let p = if i == 0 { "> " } else { " " };
out.push(Line::from(vec![
Span::styled(
p,
Style::default()
.fg(Color::Cyan)
.add_modifier(Modifier::BOLD),
),
Span::styled(l.to_string(), Style::default().add_modifier(Modifier::BOLD)),
]));
}
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) => markdown(s, out),
Item::Thinking(s) => {
for l in s.lines() {
out.push(Line::styled(
l.to_string(),
dim().add_modifier(Modifier::ITALIC),
));
}
Item::Assistant(s) => {
let mut md = vec![];
markdown(s, &mut md);
lead(md, th.sym.asst, th.accent(), out);
}
Item::Info(s) => out.push(Line::styled(format!("· {s}"), dim())),
Item::Error(s) => out.push(Line::styled(
format!("error: {s}"),
Style::default().fg(Color::Red),
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::Error(s) => out.push(Line::styled(format!("{} {s}", th.sym.err), th.err())),
Item::Tool {
name, args, result, ..
name,
args,
result,
took,
..
} => {
let (mark, color) = match result {
None => ("○", Color::Yellow),
Some((_, false)) => ("●", Color::Green),
Some((_, true)) => ("●", Color::Red),
let mut body = vec![];
let folded = match result {
Some((content, err)) => tool_body(name, content, *err, expanded, &mut body),
None => false,
};
out.push(Line::from(vec![
Span::styled(format!("{mark} "), Style::default().fg(color)),
Span::styled(
summary(name, args),
Style::default().add_modifier(Modifier::BOLD),
),
]));
if let Some((content, err)) = result {
tool_body(name, content, *err, expanded, out);
}
out.push(tool_header(name, args, result, *took, folded, width));
out.extend(body);
}
}
}
/// Collapsed: diffs in full (edits are what you want to review), bash tail, others 1 line.
fn tool_body(name: &str, content: &str, err: bool, expanded: bool, out: &mut Vec<Line<'static>>) {
let lines: Vec<&str> = content.lines().collect();
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<Line<'static>>,
) -> bool {
let th = theme::t();
let is_diff = name == "edit" && !err;
let (show, skipped_front): (Vec<&str>, usize) = if expanded || is_diff {
(lines.clone(), 0)
} else if name == "bash" || err {
let n = lines.len().saturating_sub(5);
(lines[n..].to_vec(), n)
// 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.iter().take(1).copied().collect(), 0)
(&lines[..0], 0, lines.len())
};
let hidden = lines.len() - show.len();
if skipped_front > 0 {
out.push(Line::styled(
format!(" ⋮ {skipped_front} earlier lines (ctrl-o)"),
dim(),
));
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 style = if is_diff {
for l in show {
let st = if is_diff {
match l.as_bytes().first() {
Some(b'+') if !l.starts_with("+++") => Style::default().fg(Color::Green),
Some(b'-') if !l.starts_with("---") => Style::default().fg(Color::Red),
Some(b'@') => Style::default().fg(Color::Cyan),
_ => dim(),
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 {
Style::default().fg(Color::Red)
th.err()
} else {
dim()
th.dim()
};
out.push(Line::styled(format!(" {l}"), style));
out.push(Line::from(vec![
g(th.dim()),
Span::styled(l.to_string(), st),
]));
}
if hidden > 0 && skipped_front == 0 {
out.push(Line::styled(
format!(" … {hidden} more lines (ctrl-o)"),
dim(),
));
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**.
@@ -204,18 +374,17 @@ fn markdown(s: &str, out: &mut Vec<Line<'static>>) {
for l in s.lines() {
if l.trim_start().starts_with("```") {
code = !code;
out.push(Line::styled(l.to_string(), dim()));
out.push(Line::styled(l.to_string(), theme::t().dim()));
continue;
}
if code {
out.push(Line::styled(
l.to_string(),
Style::default().fg(Color::Cyan),
));
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(),
Style::default().add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
theme::t()
.plain()
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
));
} else {
out.push(inline(l));
@@ -228,8 +397,8 @@ fn inline(l: &str) -> Line<'static> {
let mut rest = l;
while !rest.is_empty() {
let next = [
("`", Style::default().fg(Color::Yellow)),
("**", Style::default().add_modifier(Modifier::BOLD)),
("`", theme::t().code()),
("**", theme::t().plain().add_modifier(Modifier::BOLD)),
]
.into_iter()
.filter_map(|(d, st)| {
@@ -259,6 +428,7 @@ fn inline(l: &str) -> Line<'static> {
#[cfg(test)]
mod tests {
use super::*;
use ratatui::style::Color;
use serde_json::json;
fn text(ls: &[Line]) -> Vec<String> {
@@ -267,10 +437,21 @@ mod tests {
.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".into()));
t.push(Item::User("hi\nthere".into()));
for d in ["Hel", "lo"] {
t.apply(&Event::Stream(StreamEvent::TextDelta { text: d.into() }));
}
@@ -279,6 +460,7 @@ mod tests {
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(),
@@ -286,35 +468,99 @@ mod tests {
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);
let ls = t.lines(false, 40);
let s = text(&ls);
assert!(s.contains(&"● edit a.rs".to_string()));
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")
.find(|l| text(std::slice::from_ref(l))[0] == " │ -old")
.unwrap();
assert_eq!(minus.style.fg, Some(Color::Red));
assert_eq!(minus.spans[1].style.fg, Some(Color::Red));
}
#[test]
fn collapse_bash_tail() {
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();
tool_body("bash", &body, false, false, &mut out);
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");
assert_eq!(s[0], " │ … 15 earlier lines (ctrl-o)");
assert_eq!(s.last().unwrap(), " │ l20");
out.clear();
tool_body("bash", &body, false, true, &mut out);
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();
tool_body("read", &body, false, false, &mut out);
assert_eq!(text(&out), [" l1", " … 19 more lines (ctrl-o)"]);
let diff: String =
"edited a\n".to_string() + &(1..=10).map(|i| format!("+l{i}\n")).collect::<String>();
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 activity() {
let l = activity_line("bash", Duration::from_millis(12_900), 2);
assert_eq!(text(&[l]), [" ⠹ bash 12s"]);
}
#[test]