M2: interactive TUI, config, model switching, compaction
ci / check (push) Canceled after 0s

- 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:
hermes committed 2026-09-30 10:37:56 +00:00
1 parent 21d4d2bb3d
commit 89c9833e43
13 files changed
+2875 -48

No files matched your search

+303
View File
@@ -0,0 +1,303 @@
//! Multi-line input editor with history and `@file` completion.
#[derive(Default)]
pub struct Editor {
pub buf: String,
/// byte offset, always on a char boundary
pub cur: usize,
history: Vec<String>,
/// index into history while browsing; None = editing a fresh line
hist_pos: Option<usize>,
stash: String,
}
pub enum Action {
None,
Submit(String),
}
impl Editor {
pub fn insert(&mut self, s: &str) {
// normalize pasted CRLF
let s = s.replace("\r\n", "\n").replace('\r', "\n");
self.buf.insert_str(self.cur, &s);
self.cur += s.len();
}
fn prev_boundary(&self) -> usize {
self.buf[..self.cur]
.char_indices()
.next_back()
.map_or(0, |(i, _)| i)
}
fn next_boundary(&self) -> usize {
self.buf[self.cur..]
.chars()
.next()
.map_or(self.cur, |c| self.cur + c.len_utf8())
}
fn line_start(&self) -> usize {
self.buf[..self.cur].rfind('\n').map_or(0, |i| i + 1)
}
fn line_end(&self) -> usize {
self.buf[self.cur..]
.find('\n')
.map_or(self.buf.len(), |i| self.cur + i)
}
pub fn backspace(&mut self) {
if self.cur > 0 {
let p = self.prev_boundary();
self.buf.replace_range(p..self.cur, "");
self.cur = p;
}
}
pub fn delete(&mut self) {
let n = self.next_boundary();
self.buf.replace_range(self.cur..n, "");
}
pub fn left(&mut self) {
self.cur = self.prev_boundary();
}
pub fn right(&mut self) {
self.cur = self.next_boundary();
}
pub fn home(&mut self) {
self.cur = self.line_start();
}
pub fn end(&mut self) {
self.cur = self.line_end();
}
/// Delete from line start to cursor.
pub fn kill_line(&mut self) {
let s = self.line_start();
self.buf.replace_range(s..self.cur, "");
self.cur = s;
}
pub fn kill_word(&mut self) {
let before = &self.buf[..self.cur];
let trimmed = before.trim_end();
let s = trimmed.rfind(char::is_whitespace).map_or(0, |i| i + 1);
self.buf.replace_range(s..self.cur, "");
self.cur = s;
}
/// Up: previous line in a multi-line buffer, else history.
pub fn up(&mut self) {
let ls = self.line_start();
if ls > 0 {
let col = self.buf[ls..self.cur].chars().count();
let pls = self.buf[..ls - 1].rfind('\n').map_or(0, |i| i + 1);
self.cur = advance(&self.buf, pls, ls - 1, col);
return;
}
if self.history.is_empty() {
return;
}
let i = match self.hist_pos {
None => {
self.stash = std::mem::take(&mut self.buf);
self.history.len() - 1
}
Some(0) => 0,
Some(i) => i - 1,
};
self.hist_pos = Some(i);
self.buf = self.history[i].clone();
self.cur = self.buf.len();
}
pub fn down(&mut self) {
let le = self.line_end();
if le < self.buf.len() {
let col = self.buf[self.line_start()..self.cur].chars().count();
let nle = self.buf[le + 1..]
.find('\n')
.map_or(self.buf.len(), |i| le + 1 + i);
self.cur = advance(&self.buf, le + 1, nle, col);
return;
}
match self.hist_pos {
None => {}
Some(i) if i + 1 < self.history.len() => {
self.hist_pos = Some(i + 1);
self.buf = self.history[i + 1].clone();
}
Some(_) => {
self.hist_pos = None;
self.buf = std::mem::take(&mut self.stash);
}
}
self.cur = self.buf.len();
}
pub fn submit(&mut self) -> Action {
let s = std::mem::take(&mut self.buf);
self.cur = 0;
self.hist_pos = None;
if s.trim().is_empty() {
return Action::None;
}
if self.history.last() != Some(&s) {
self.history.push(s.clone());
}
Action::Submit(s)
}
/// The `@partial` token ending at the cursor, if any: (start byte, text after '@').
pub fn at_token(&self) -> Option<(usize, &str)> {
let before = &self.buf[..self.cur];
let start = before
.rfind(|c: char| c.is_whitespace())
.map_or(0, |i| i + 1);
before[start..].strip_prefix('@').map(|t| (start, t))
}
/// Replace the current `@token` with `@path`.
pub fn complete(&mut self, path: &str, done: bool) {
if let Some((s, _)) = self.at_token() {
let rep = if done {
format!("@{path} ")
} else {
format!("@{path}")
};
self.buf.replace_range(s..self.cur, &rep);
self.cur = s + rep.len();
}
}
/// (row, col) of the cursor in chars.
pub fn cursor_rc(&self) -> (usize, usize) {
let before = &self.buf[..self.cur];
(
before.matches('\n').count(),
before[self.line_start()..].chars().count(),
)
}
}
/// Byte offset `col` chars into `buf[from..to]`, clamped to `to`.
fn advance(buf: &str, from: usize, to: usize, col: usize) -> usize {
buf[from..to]
.char_indices()
.nth(col)
.map_or(to, |(i, _)| from + i)
}
/// Case-insensitive subsequence match; shorter paths and basename hits rank first.
pub fn fuzzy<'a>(files: &'a [String], q: &str, n: usize) -> Vec<&'a String> {
let q = q.to_lowercase();
let mut hits: Vec<(usize, &String)> = files
.iter()
.filter_map(|f| {
let l = f.to_lowercase();
let mut it = l.chars();
if !q.chars().all(|c| it.any(|x| x == c)) {
return None;
}
let base = l.rsplit('/').next().unwrap_or(&l);
let bonus = if base.contains(&q) {
0
} else if l.contains(&q) {
1000
} else {
2000
};
Some((bonus + f.len(), f))
})
.collect();
hits.sort();
hits.into_iter().take(n).map(|(_, f)| f).collect()
}
pub fn common_prefix(xs: &[&String]) -> String {
let Some(first) = xs.first() else {
return String::new();
};
let mut end = first.len();
for x in &xs[1..] {
end = end.min(
first
.bytes()
.zip(x.bytes())
.take_while(|(a, b)| a == b)
.count(),
);
}
while !first.is_char_boundary(end) {
end -= 1;
}
first[..end].to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn edit_and_multiline_nav() {
let mut e = Editor::default();
e.insert("héllo");
e.left();
e.backspace();
assert_eq!(e.buf, "hélo");
e.insert("\r\nworld");
assert_eq!(e.buf, "hél\r\nworldo".replace("\r\n", "\n"));
assert_eq!(e.cursor_rc(), (1, 5));
e.up();
assert_eq!(e.cursor_rc(), (0, 3));
e.down();
assert_eq!(e.cursor_rc(), (1, 3));
e.end();
e.kill_line();
assert_eq!(e.buf, "hél\n");
e.insert("a b");
e.kill_word();
assert_eq!(e.buf, "hél\na ");
}
#[test]
fn history_and_submit() {
let mut e = Editor::default();
assert!(matches!(e.submit(), Action::None));
for s in ["a", "b"] {
e.insert(s);
assert!(matches!(e.submit(), Action::Submit(x) if x == s));
}
e.insert("draft");
e.up();
assert_eq!(e.buf, "b");
e.up();
e.up();
assert_eq!(e.buf, "a");
e.down();
e.down();
assert_eq!(e.buf, "draft");
}
#[test]
fn at_completion() {
let files: Vec<String> = [
"src/main.rs",
"src/lib.rs",
"crates/x/src/main.rs",
"README.md",
]
.map(String::from)
.into();
assert_eq!(fuzzy(&files, "main", 5), [&files[0], &files[2]]);
assert_eq!(fuzzy(&files, "srlib", 5), [&files[1]]);
let mut e = Editor::default();
e.insert("look at @mai");
assert_eq!(e.at_token(), Some((8, "mai")));
let hits = fuzzy(&files, "mai", 5);
assert_eq!(common_prefix(&hits), "");
e.complete("src/main.rs", true);
assert_eq!(e.buf, "look at @src/main.rs ");
assert_eq!(e.at_token(), None);
assert_eq!(
common_prefix(&[&"src/a".to_string(), &"src/b".to_string()]),
"src/"
);
}
}
+491 -5
View File
@@ -1,14 +1,500 @@
pub fn add(left: u64, right: u64) -> u64 {
left + right
//! Interactive terminal UI.
pub mod editor;
pub mod transcript;
use crossterm::event::{
Event as TEvent, EventStream, KeyCode, KeyEvent, KeyEventKind, KeyModifiers,
};
use editor::{Action, Editor};
use futures::StreamExt;
use hx_ai::auth::Kind;
use hx_ai::{Provider, Usage};
use hx_core::agent::{AbortHandle, Agent};
use hx_core::hook::{Event, Hook, HookAction};
use ratatui::layout::{Constraint, Layout};
use ratatui::style::{Color, Style};
use ratatui::text::Line;
use ratatui::widgets::{Block, Borders, Paragraph, Wrap};
use std::collections::VecDeque;
use std::sync::Arc;
use tokio::sync::{Mutex, mpsc};
use transcript::{Item, Transcript};
pub type MakeProvider = Box<dyn Fn(Kind) -> hx_ai::Result<Arc<dyn Provider>> + Send>;
pub struct Setup {
pub agent: Agent,
pub kind: Kind,
pub make_provider: MakeProvider,
/// Default model per provider, used on `/provider`.
pub default_model: fn(Kind) -> String,
/// Pricing lookup for the footer; None = unknown.
pub pricing: fn(&str) -> Option<hx_ai::Pricing>,
}
enum Ui {
Ev(Event),
Done(Result<(), String>),
Compacted(Result<bool, String>),
}
/// Forwards agent events to the UI loop.
struct Forward(mpsc::UnboundedSender<Ui>);
#[async_trait::async_trait]
impl Hook for Forward {
async fn on(&self, ev: &Event) -> HookAction {
let _ = self.0.send(Ui::Ev(ev.clone()));
HookAction::Continue
}
}
struct App {
t: Transcript,
ed: Editor,
files: Vec<String>,
/// lines scrolled up from the bottom
scroll: u16,
expanded: bool,
busy: bool,
queue: VecDeque<String>,
kind: Kind,
model: String,
usage: Usage,
ctx_tokens: usize,
quit: bool,
hint: String,
}
const HELP: &str = "enter send · alt-enter/ctrl-j newline · esc/ctrl-c abort · ctrl-o expand tools · pgup/pgdn scroll · tab @file · \
/model <m> · /provider claude|codex · /compact · /clear · /quit";
fn project_files(root: &std::path::Path) -> Vec<String> {
ignore::WalkBuilder::new(root)
.hidden(true)
.build()
.flatten()
.filter(|e| e.file_type().is_some_and(|t| t.is_file()))
.filter_map(|e| {
e.path()
.strip_prefix(root)
.ok()
.map(|p| p.to_string_lossy().into_owned())
})
.take(20_000)
.collect()
}
/// Expand `@path` mentions of existing files into attached contents.
fn expand_mentions(s: &str, root: &std::path::Path) -> String {
let mut att = String::new();
for w in s.split_whitespace().filter_map(|w| w.strip_prefix('@')) {
let p = root.join(w);
if let Ok(c) = std::fs::read_to_string(&p)
&& c.len() < 200_000
{
att.push_str(&format!("\n\n<file path=\"{w}\">\n{c}\n</file>"));
}
}
format!("{s}{att}")
}
pub async fn run(setup: Setup) -> std::io::Result<()> {
let Setup {
mut agent,
kind,
make_provider,
default_model,
pricing,
} = setup;
let (tx, mut rx) = mpsc::unbounded_channel();
agent.bus.add(Forward(tx.clone()));
let abort: AbortHandle = agent.abort_handle();
let cwd = agent.cx.cwd.clone();
let mut app = App {
t: Transcript::default(),
ed: Editor::default(),
files: project_files(&cwd),
scroll: 0,
expanded: false,
busy: false,
queue: VecDeque::new(),
kind,
model: agent.model.clone(),
usage: Usage::default(),
ctx_tokens: hx_core::agent::estimate_tokens(&agent.session.messages()),
quit: false,
hint: String::new(),
};
// show resumed history
for m in agent.session.messages() {
for b in &m.content {
match (m.role, b) {
(hx_ai::Role::User, hx_ai::ContentBlock::Text { text }) => {
app.t.push(Item::User(text.clone()))
}
(hx_ai::Role::Assistant, hx_ai::ContentBlock::Text { text }) => {
app.t.push(Item::Assistant(text.clone()))
}
_ => {}
}
}
}
app.t.push(Item::Info(format!(
"hx · {:?} · {} · {HELP}",
app.kind, app.model
)));
let agent = Arc::new(Mutex::new(agent));
let mut term = ratatui::init();
let mut keys = EventStream::new();
let mut tick = tokio::time::interval(std::time::Duration::from_millis(50));
let mut dirty = true;
while !app.quit {
if std::mem::take(&mut dirty) {
term.draw(|f| draw(f, &mut app))?;
}
tokio::select! {
k = keys.next() => {
let Some(Ok(ev)) = k else { break };
dirty = true;
match ev {
TEvent::Key(k) if k.kind != KeyEventKind::Release => {
if let Some(line) = on_key(&mut app, k, &abort) {
submit(&mut app, line, &agent, &tx, &make_provider, default_model, &cwd).await;
}
}
TEvent::Paste(s) => app.ed.insert(&s),
_ => {}
}
}
Some(u) = rx.recv() => {
dirty = true;
match u {
Ui::Ev(e) => {
if let Event::Stream(hx_ai::StreamEvent::Done { usage, .. }) = &e {
app.usage.add(usage);
app.ctx_tokens = (usage.input_tokens + usage.cache_read_tokens + usage.cache_write_tokens + usage.output_tokens) as usize;
}
app.t.apply(&e);
}
Ui::Done(r) => {
app.busy = false;
match r {
Err(e) if e == "aborted" => app.t.push(Item::Info("aborted".into())),
Err(e) => app.t.push(Item::Error(e)),
Ok(()) => {}
}
if let Some(next) = app.queue.pop_front() {
submit(&mut app, next, &agent, &tx, &make_provider, default_model, &cwd).await;
}
}
Ui::Compacted(r) => {
app.busy = false;
app.t.push(match r {
Ok(true) => Item::Info("context compacted".into()),
Ok(false) => Item::Info("nothing to compact".into()),
Err(e) => Item::Error(e),
});
app.ctx_tokens = hx_core::agent::estimate_tokens(&agent.lock().await.session.messages());
}
}
}
_ = tick.tick(), if app.busy => dirty = true,
}
}
ratatui::restore();
let a = agent.lock().await;
let cost = pricing(&a.model)
.map(|p| format!(" ${:.4}", app.usage.cost(&p)))
.unwrap_or_default();
eprintln!(
"[{} in / {} out tokens{cost}; session {}]",
app.usage.input_tokens + app.usage.cache_read_tokens,
app.usage.output_tokens,
a.session.path().display()
);
Ok(())
}
/// Returns a line to submit, if any.
fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option<String> {
let ctrl = k.modifiers.contains(KeyModifiers::CONTROL);
let alt = k.modifiers.contains(KeyModifiers::ALT);
let shift = k.modifiers.contains(KeyModifiers::SHIFT);
app.hint.clear();
match k.code {
KeyCode::Char('c') if ctrl => {
if app.busy {
app.queue.clear();
abort.abort();
} else if app.ed.buf.is_empty() {
app.quit = true;
} else {
app.ed = std::mem::take(&mut app.ed);
app.ed.buf.clear();
app.ed.cur = 0;
}
}
KeyCode::Char('d') if ctrl && app.ed.buf.is_empty() && !app.busy => app.quit = true,
KeyCode::Esc if app.busy => {
app.queue.clear();
abort.abort();
}
KeyCode::Char('o') if ctrl => app.expanded = !app.expanded,
KeyCode::Char('j') if ctrl => app.ed.insert("\n"),
KeyCode::Enter if alt || shift => app.ed.insert("\n"),
KeyCode::Enter => {
if let Action::Submit(s) = app.ed.submit() {
return Some(s);
}
}
KeyCode::Char('u') if ctrl => app.ed.kill_line(),
KeyCode::Char('w') if ctrl => app.ed.kill_word(),
KeyCode::Char('a') if ctrl => app.ed.home(),
KeyCode::Char('e') if ctrl => app.ed.end(),
KeyCode::Char(c) if !ctrl => app.ed.insert(c.encode_utf8(&mut [0; 4])),
KeyCode::Backspace => app.ed.backspace(),
KeyCode::Delete => app.ed.delete(),
KeyCode::Left => app.ed.left(),
KeyCode::Right => app.ed.right(),
KeyCode::Home => app.ed.home(),
KeyCode::End => app.ed.end(),
KeyCode::Up => app.ed.up(),
KeyCode::Down => app.ed.down(),
KeyCode::PageUp => app.scroll = app.scroll.saturating_add(10),
KeyCode::PageDown => app.scroll = app.scroll.saturating_sub(10),
KeyCode::Tab => {
if let Some((_, q)) = app.ed.at_token() {
let hits = editor::fuzzy(&app.files, q, 8);
match hits.len() {
0 => app.hint = "no match".into(),
1 => {
let h = hits[0].clone();
app.ed.complete(&h, true);
}
_ => {
let pre = editor::common_prefix(&hits);
if pre.len() > q.len() {
app.ed.complete(&pre, false);
}
app.hint = hits
.iter()
.map(|s| s.as_str())
.collect::<Vec<_>>()
.join(" ");
}
}
}
}
_ => {}
}
None
}
async fn submit(
app: &mut App,
line: String,
agent: &Arc<Mutex<Agent>>,
tx: &mpsc::UnboundedSender<Ui>,
make_provider: &MakeProvider,
default_model: fn(Kind) -> String,
cwd: &std::path::Path,
) {
app.scroll = 0;
if let Some(cmd) = line.strip_prefix('/') {
let (c, arg) = cmd
.split_once(' ')
.map_or((cmd, ""), |(a, b)| (a, b.trim()));
if app.busy && c != "quit" {
app.t.push(Item::Error("busy; esc to abort first".into()));
return;
}
match c {
"quit" | "exit" => app.quit = true,
"help" => app.t.push(Item::Info(HELP.into())),
"model" if arg.is_empty() => app.t.push(Item::Info(format!("model: {}", app.model))),
"model" => {
agent.lock().await.model = arg.into();
app.model = arg.into();
app.t.push(Item::Info(format!("model → {arg}")));
}
"provider" => match arg
.parse::<Kind>()
.map_err(|e| e.to_string())
.and_then(|k| make_provider(k).map(|p| (k, p)).map_err(|e| e.to_string()))
{
Ok((k, p)) => {
let mut a = agent.lock().await;
a.provider = p;
a.model = default_model(k);
app.kind = k;
app.model = a.model.clone();
app.t
.push(Item::Info(format!("provider → {k:?} ({})", app.model)));
}
Err(e) => app.t.push(Item::Error(e)),
},
"compact" => {
app.busy = true;
app.t.push(Item::Info("compacting…".into()));
let (agent, tx) = (agent.clone(), tx.clone());
tokio::spawn(async move {
let r = agent
.lock()
.await
.compact(4)
.await
.map_err(|e| e.to_string());
let _ = tx.send(Ui::Compacted(r));
});
}
"clear" => {
let mut a = agent.lock().await;
let _ = a.session.rebase(vec![]);
app.t = Transcript::default();
app.ctx_tokens = 0;
app.t.push(Item::Info("cleared".into()));
}
_ => app
.t
.push(Item::Error(format!("unknown command /{c}; /help"))),
}
return;
}
if app.busy {
app.t.push(Item::Info(format!(
"queued: {}",
line.lines().next().unwrap_or_default()
)));
app.queue.push_back(line);
return;
}
app.t.push(Item::User(line.clone()));
app.busy = true;
let prompt = expand_mentions(&line, cwd);
let (agent, tx) = (agent.clone(), tx.clone());
tokio::spawn(async move {
let r = agent
.lock()
.await
.run(prompt)
.await
.map(|_| ())
.map_err(|e| e.to_string());
let _ = tx.send(Ui::Done(r));
});
}
fn draw(f: &mut ratatui::Frame, app: &mut App) {
let input_h = (app.ed.buf.lines().count().max(1) + usize::from(app.ed.buf.ends_with('\n')))
.min(10) as u16
+ 2;
let [main, status, input] = Layout::vertical([
Constraint::Min(3),
Constraint::Length(1),
Constraint::Length(input_h),
])
.areas(f.area());
let para = Paragraph::new(app.t.lines(app.expanded)).wrap(Wrap { trim: false });
let total = para.line_count(main.width) as u16;
let max_up = total.saturating_sub(main.height);
app.scroll = app.scroll.min(max_up);
f.render_widget(para.scroll((max_up - app.scroll, 0)), main);
let spin = if app.busy {
["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"][(std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_millis()
/ 80
% 10) as usize]
} else {
" "
};
let q = if app.queue.is_empty() {
String::new()
} else {
format!(" · {} queued", app.queue.len())
};
let up = if app.scroll > 0 {
format!(" · ↑{}", app.scroll)
} else {
String::new()
};
let st = if app.hint.is_empty() {
format!(
"{spin} {:?} · {} · ctx {}k · {}↑ {}↓{q}{up}",
app.kind,
app.model,
app.ctx_tokens / 1000,
app.usage.input_tokens + app.usage.cache_read_tokens,
app.usage.output_tokens
)
} else {
app.hint.clone()
};
f.render_widget(
Line::styled(st, Style::default().fg(Color::DarkGray)),
status,
);
let block = Block::default()
.borders(Borders::TOP | Borders::BOTTOM)
.border_style(Style::default().fg(Color::DarkGray));
let inner = block.inner(input);
f.render_widget(Paragraph::new(app.ed.buf.as_str()).block(block), input);
let (r, c) = app.ed.cursor_rc();
let skip = (r as u16).saturating_sub(inner.height.saturating_sub(1));
f.set_cursor_position((inner.x + c as u16, inner.y + r as u16 - skip));
}
#[cfg(test)]
mod tests {
use super::*;
use ratatui::backend::TestBackend;
#[test]
fn it_works() {
let result = add(2, 2);
assert_eq!(result, 4);
fn mentions() {
let d = std::env::temp_dir().join(format!("hx-tui-{}", std::process::id()));
std::fs::create_dir_all(&d).unwrap();
std::fs::write(d.join("a.txt"), "AAA").unwrap();
let s = expand_mentions("see @a.txt and @nope", &d);
assert!(s.starts_with("see @a.txt and @nope") && s.contains("<file path=\"a.txt\">\nAAA"));
assert!(!s.contains("nope\">"));
}
#[test]
fn draw_snapshot() {
let mut app = App {
t: Transcript::default(),
ed: Editor::default(),
files: vec![],
scroll: 0,
expanded: false,
busy: false,
queue: VecDeque::new(),
kind: Kind::Claude,
model: "m1".into(),
usage: Usage::default(),
ctx_tokens: 12_000,
quit: false,
hint: String::new(),
};
app.t.push(Item::User("hello".into()));
app.t.push(Item::Assistant("hi **there**".into()));
app.ed.insert("typing");
let mut term = ratatui::Terminal::new(TestBackend::new(40, 10)).unwrap();
term.draw(|f| draw(f, &mut app)).unwrap();
let buf = term.backend().buffer().clone();
let rows: Vec<String> = (0..10)
.map(|y| (0..40).map(|x| buf[(x, y)].symbol().to_string()).collect())
.collect();
let all = rows.join("\n");
assert!(all.contains("> hello"), "{all}");
assert!(all.contains("hi there"), "{all}");
assert!(all.contains("Claude · m1 · ctx 12k"), "{all}");
assert!(rows[8].starts_with("typing"), "{all}");
}
}
+326
View File
@@ -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"]);
}
}