//! Subagent overview (small list above the footer) and the per-agent detail view. use crate::editor::Editor; use crate::theme; use crate::transcript::Transcript; use hx_core::subagent::{Status, Sub}; use ratatui::layout::{Constraint, Layout}; use ratatui::text::{Line, Span}; use ratatui::widgets::{Block, Borders, Paragraph, Wrap}; use std::time::Duration; /// What the list needs per agent (plain data, so rendering is testable). #[derive(Clone, Debug, PartialEq)] pub struct Row { pub id: usize, pub kind: &'static str, pub prompt: String, pub status: Status, pub elapsed: Duration, /// time since it finished (`None` while running) pub ended: Option, pub calls: usize, pub tokens: u64, } pub fn row(s: &Sub) -> Row { let u = s.sh.usage.lock().unwrap_or_else(|e| e.into_inner()).clone(); Row { id: s.sh.id, kind: s.sh.kind, prompt: s.sh.prompt.lines().next().unwrap_or_default().to_string(), status: s.sh.status(), elapsed: s.sh.elapsed(), ended: s.sh.since_end(), calls: s.sh.calls.load(std::sync::atomic::Ordering::Relaxed), tokens: u.input_tokens + u.cache_read_tokens + u.cache_write_tokens + u.output_tokens, } } pub enum View { /// list focused, selected index List(usize), Detail { id: usize, ed: Editor, scroll: crate::scroll::Scroll, }, } pub const MAX_ROWS: usize = 5; /// Finished agents leave the passive list after this long (still reachable via ctrl-g). pub const LINGER: Duration = Duration::from_secs(20); fn dur(d: Duration) -> String { match d.as_secs() { s if s >= 60 => format!("{}m{:02}s", s / 60, s % 60), s => format!("{s}s"), } } fn glyph(s: &Status, frame: usize) -> &'static str { let th = theme::t(); match s { Status::Running if th.sym.ok == "+" => ["-", "\\", "|", "/"][frame % 4], Status::Running => ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"][frame % 10], Status::Done => th.sym.ok, _ => th.sym.err, } } /// Rows shown (the last `MAX_ROWS`, scrolled so `sel` is visible): `⠹ 1 explore grep auth 12s 8 calls`. pub fn lines(rows: &[Row], sel: Option, frame: usize, width: u16) -> Vec> { let th = theme::t(); let w = width as usize; let first = sel .map_or(rows.len(), |s| s + 1) .max(MAX_ROWS) .min(rows.len()) .saturating_sub(MAX_ROWS); rows.iter() .enumerate() .skip(first) .take(MAX_ROWS) .map(|(i, r)| { let tail = format!(" {} {}c {}k", dur(r.elapsed), r.calls, r.tokens / 1000); let head = format!(" {} {} {:<7} ", glyph(&r.status, frame), r.id, r.kind); let room = w.saturating_sub(head.chars().count() + tail.chars().count()); let mut p: String = r.prompt.chars().take(room).collect(); if r.prompt.chars().count() > room && room > 0 { p.pop(); p.push('…'); } let pad = " ".repeat(room.saturating_sub(p.chars().count())); let st = if sel == Some(i) { th.sel() } else { match r.status { Status::Running => th.plain(), Status::Done => th.dim(), _ => th.err(), } }; Line::from(vec![Span::styled(format!("{head}{p}{pad}{tail}"), st)]) }) .collect() } pub fn list_height(n: usize) -> u16 { n.min(MAX_ROWS) as u16 } /// Last assistant text of an agent's transcript, for ctrl-s. pub fn last_answer(t: &Transcript) -> Option { t.items.iter().rev().find_map(|i| match i { crate::transcript::Item::Assistant(s) if !s.trim().is_empty() => Some(s.clone()), _ => None, }) } pub fn help(running: bool) -> &'static str { if running { "enter queue for next turn · ctrl-s to main chat · ctrl-c abort agent · esc back" } else { "enter continue agent · ctrl-s to main chat · esc back" } } /// Full-screen view of one agent: header, its transcript, input, help. pub struct Detail<'a> { pub row: &'a Row, pub model: &'a str, pub t: &'a Transcript, pub ed: &'a Editor, pub expanded: bool, pub frame: usize, } pub fn draw_detail(f: &mut ratatui::Frame, d: &Detail, scroll: &mut crate::scroll::Scroll) { let Detail { row: r, model, t, ed, expanded, frame, } = *d; let th = theme::t(); let input_h = ed.buf.lines().count().clamp(1, 8) as u16 + 2; let [head, body, input, foot] = Layout::vertical([ Constraint::Length(1), Constraint::Min(3), Constraint::Length(input_h), Constraint::Length(1), ]) .areas(f.area()); f.render_widget( Line::from(vec![ Span::styled( format!( "{} agent {} · {} · {model}", glyph(&r.status, frame), r.id, r.kind ), th.accent(), ), Span::styled( format!( " · {:?} {} · {} calls · {}k tok", r.status, dur(r.elapsed), r.calls, r.tokens / 1000 ) .replace("Running", "running") .replace("Done", "done"), th.dim(), ), ]), head, ); let para = Paragraph::new(t.lines(expanded, body.width)).wrap(Wrap { trim: false }); let total = para.line_count(body.width) as u16; let top = scroll.resolve(total, body.height); f.render_widget(para.scroll((top, 0)), body); let block = Block::default() .borders(Borders::TOP | Borders::BOTTOM) .border_style(th.dim()); let inner = block.inner(input); f.render_widget(block, input); let (row, col) = ed.cursor_rc(); let skip = (row as u16).saturating_sub(inner.height.saturating_sub(1)); if ed.buf.is_empty() { let hint = if r.status == Status::Running { "message the agent (delivered at its next turn end)" } else { "prompt the agent to continue" }; f.render_widget(Span::styled(hint, th.dim()), inner); } else { f.render_widget(Paragraph::new(ed.buf.as_str()).scroll((skip, 0)), inner); } f.set_cursor_position((inner.x + col as u16, inner.y + row as u16 - skip)); f.render_widget( Span::styled(help(r.status == Status::Running), th.dim()), foot, ); } #[cfg(test)] mod tests { use super::*; fn r(id: usize, st: Status) -> Row { Row { id, kind: "explore", prompt: "grep the auth middleware for token expiry checks".into(), status: st, elapsed: Duration::from_secs(72), ended: None, calls: 8, tokens: 41_000, } } fn text(l: &Line) -> String { l.spans.iter().map(|s| s.content.to_string()).collect() } #[test] fn rows_fit_width_and_show_status() { let v = vec![r(1, Status::Running), r(2, Status::Done)]; for w in [40u16, 60, 100] { for l in lines(&v, None, 0, w) { assert_eq!(l.width(), w as usize, "{}", text(&l)); } } let l = lines(&v, None, 0, 60); assert!( text(&l[0]).starts_with(" ⠋ 1 explore ") && text(&l[0]).ends_with(" 1m12s 8c 41k") ); assert!(text(&l[1]).starts_with(" ✓ 2 explore "), "{}", text(&l[1])); assert!(text(&l[0]).contains('…')); } #[test] fn only_last_five_and_selection_stays_visible() { let v: Vec = (1..=8).map(|i| r(i, Status::Done)).collect(); let ids = |l: Vec| { l.iter() .map(|x| text(x).chars().nth(4).unwrap().to_string()) .collect::>() }; assert_eq!(ids(lines(&v, None, 0, 60)), ["4", "5", "6", "7", "8"]); assert_eq!(ids(lines(&v, Some(0), 0, 60)), ["1", "2", "3", "4", "5"]); assert_eq!(ids(lines(&v, Some(6), 0, 60)), ["3", "4", "5", "6", "7"]); } #[test] fn detail_renders_header_transcript_and_input() { use crate::transcript::Item; let mut t = Transcript::default(); t.push(Item::User("find it".into())); t.push(Item::Assistant("found in src/a.rs".into())); let mut ed = Editor::default(); ed.insert("and then?"); let mut sc = crate::scroll::Scroll::default(); let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(80, 12)).unwrap(); let row = r(3, Status::Running); let d = Detail { row: &row, model: "haiku", t: &t, ed: &ed, expanded: false, frame: 0, }; term.draw(|f| draw_detail(f, &d, &mut sc)).unwrap(); let b = term.backend().buffer().clone(); let rows: Vec = (0..12) .map(|y| (0..80).map(|x| b[(x, y)].symbol().to_string()).collect()) .collect(); assert!( rows[0].contains("agent 3 · explore · haiku") && rows[0].contains("running 1m12s"), "{}", rows[0] ); let all = rows.join("\n"); assert!( all.contains("find it") && all.contains("found in src/a.rs") && all.contains("and then?"), "{all}" ); assert!(rows[11].contains("queue for next turn")); assert_eq!(last_answer(&t).as_deref(), Some("found in src/a.rs")); } }