- hx-tui: ratatui app with streaming transcript, markdown-ish rendering, tool call status, colored edit diffs, collapsible bash/read output (ctrl-o), scrollback, spinner + footer (provider, model, ctx, tokens) - editor: multi-line, history, word/line kill, bracketed paste, @file fuzzy tab completion; mentioned files attached - message queue while agent runs; esc/ctrl-c abort; /model /provider /compact /clear /help /quit; resumed history shown - hx-core: compaction (summarize older prompts, keep recent verbatim, session rebase keeps full file history), auto-compact at threshold; abort only ends current run - config: ~/.hx/config.toml + project .hx/config.toml (provider, per-provider models, compact_at, max_tokens, system_prompt) - API-equivalent cost estimate in exit summary - tests/tui_smoke.py drives the real TUI in a pty against the fake API Closes #15, closes #16, closes #17, closes #18, closes #19
This commit is contained in:
1 parent
21d4d2bb3d
commit
89c9833e43
13 files changed
+2875
-48
No files matched your search
@@ -0,0 +1,326 @@
|
||||
//! Transcript model and rendering (markdown-ish text, tool calls, diffs).
|
||||
|
||||
use hx_ai::StreamEvent;
|
||||
use hx_core::hook::Event;
|
||||
use ratatui::style::{Color, Modifier, Style};
|
||||
use ratatui::text::{Line, Span};
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Item {
|
||||
User(String),
|
||||
Assistant(String),
|
||||
Thinking(String),
|
||||
Tool {
|
||||
id: String,
|
||||
name: String,
|
||||
args: Value,
|
||||
result: Option<(String, bool)>,
|
||||
},
|
||||
Info(String),
|
||||
Error(String),
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Transcript {
|
||||
pub items: Vec<Item>,
|
||||
/// 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,
|
||||
}),
|
||||
Event::ToolResult {
|
||||
id,
|
||||
content,
|
||||
is_error,
|
||||
..
|
||||
} => {
|
||||
if let Some(Item::Tool { result, .. }) = self
|
||||
.items
|
||||
.iter_mut()
|
||||
.rev()
|
||||
.find(|i| matches!(i, Item::Tool { id: x, .. } if x == id))
|
||||
{
|
||||
*result = Some((content.clone(), *is_error));
|
||||
}
|
||||
}
|
||||
Event::Info(s) => self.push(Item::Info(s.clone())),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn lines(&self, expanded: bool) -> Vec<Line<'static>> {
|
||||
let mut out = vec![];
|
||||
for it in &self.items {
|
||||
render(it, expanded, &mut out);
|
||||
out.push(Line::default());
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
fn dim() -> Style {
|
||||
Style::default().fg(Color::DarkGray)
|
||||
}
|
||||
|
||||
fn summary(name: &str, 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}")
|
||||
}
|
||||
|
||||
fn render(it: &Item, expanded: bool, out: &mut Vec<Line<'static>>) {
|
||||
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)),
|
||||
]));
|
||||
}
|
||||
}
|
||||
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::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::Tool {
|
||||
name, args, result, ..
|
||||
} => {
|
||||
let (mark, color) = match result {
|
||||
None => ("○", Color::Yellow),
|
||||
Some((_, false)) => ("●", Color::Green),
|
||||
Some((_, true)) => ("●", Color::Red),
|
||||
};
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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();
|
||||
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)
|
||||
} else {
|
||||
(lines.iter().take(1).copied().collect(), 0)
|
||||
};
|
||||
let hidden = lines.len() - show.len();
|
||||
if skipped_front > 0 {
|
||||
out.push(Line::styled(
|
||||
format!(" ⋮ {skipped_front} earlier lines (ctrl-o)"),
|
||||
dim(),
|
||||
));
|
||||
}
|
||||
for l in &show {
|
||||
let style = 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(),
|
||||
}
|
||||
} else if err {
|
||||
Style::default().fg(Color::Red)
|
||||
} else {
|
||||
dim()
|
||||
};
|
||||
out.push(Line::styled(format!(" {l}"), style));
|
||||
}
|
||||
if hidden > 0 && skipped_front == 0 {
|
||||
out.push(Line::styled(
|
||||
format!(" … {hidden} more lines (ctrl-o)"),
|
||||
dim(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// Minimal markdown: fenced code, headings, bullets, inline `code` and **bold**.
|
||||
fn markdown(s: &str, out: &mut Vec<Line<'static>>) {
|
||||
let mut code = false;
|
||||
for l in s.lines() {
|
||||
if l.trim_start().starts_with("```") {
|
||||
code = !code;
|
||||
out.push(Line::styled(l.to_string(), dim()));
|
||||
continue;
|
||||
}
|
||||
if code {
|
||||
out.push(Line::styled(
|
||||
l.to_string(),
|
||||
Style::default().fg(Color::Cyan),
|
||||
));
|
||||
} else if l.starts_with('#') {
|
||||
out.push(Line::styled(
|
||||
l.trim_start_matches('#').trim().to_string(),
|
||||
Style::default().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 = [
|
||||
("`", Style::default().fg(Color::Yellow)),
|
||||
("**", Style::default().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 serde_json::json;
|
||||
|
||||
fn text(ls: &[Line]) -> Vec<String> {
|
||||
ls.iter()
|
||||
.map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stream_and_tools() {
|
||||
let mut t = Transcript::default();
|
||||
t.push(Item::User("hi".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"}),
|
||||
});
|
||||
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,
|
||||
});
|
||||
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 s = text(&ls);
|
||||
assert!(s.contains(&"● edit a.rs".to_string()));
|
||||
let minus = ls
|
||||
.iter()
|
||||
.find(|l| text(std::slice::from_ref(l))[0] == " -old")
|
||||
.unwrap();
|
||||
assert_eq!(minus.style.fg, Some(Color::Red));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collapse_bash_tail() {
|
||||
let mut out = vec![];
|
||||
let body: String = (1..=20).map(|i| format!("l{i}\n")).collect();
|
||||
tool_body("bash", &body, false, false, &mut out);
|
||||
let s = text(&out);
|
||||
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_eq!(out.len(), 20);
|
||||
out.clear();
|
||||
tool_body("read", &body, false, false, &mut out);
|
||||
assert_eq!(text(&out), [" l1", " … 19 more lines (ctrl-o)"]);
|
||||
}
|
||||
|
||||
#[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"]);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user