TUI: permission prompt, /diff review, /stats dashboard, lens/context/MCP side panel
ci / check (pull_request) Canceled after 0s
ci / check (push) Canceled after 0s

This commit is contained in:
hermes authored and Johannes Kresner committed 2026-10-02 23:31:55 +02:00
1 parent 4a8e920ab8
commit 5fd7044a2f
15 files changed
+945 -2

No files matched your search

+219
View File
@@ -3,10 +3,13 @@
pub mod agents;
pub mod choose;
pub mod editor;
pub mod permit_view;
pub mod picker;
pub mod popup;
pub mod review;
pub mod scroll;
pub mod sessions;
pub mod stats_view;
pub mod status;
pub mod theme;
pub mod transcript;
@@ -50,6 +53,8 @@ pub struct Setup {
pub open_sessions: bool,
/// Capture the mouse (wheel scrolling); terminal text selection then needs shift-drag.
pub mouse: bool,
/// MCP servers for the side panel: (name, connected).
pub mcp: Vec<(String, bool)>,
}
/// Screen regions of the last draw, for routing the mouse wheel.
@@ -85,6 +90,10 @@ pub type LspStatus = Box<
enum Ui {
Ev(Event),
Ask(String, tokio::sync::oneshot::Sender<bool>),
Permit(
hx_core::permit::Request,
tokio::sync::oneshot::Sender<hx_core::permit::Decision>,
),
Choose(
hx_core::Question,
tokio::sync::oneshot::Sender<Option<Vec<String>>>,
@@ -140,6 +149,17 @@ struct App {
/// condensed lens state for the footer, refreshed by a timer
lens: (String, bool),
/// open `ask_user` popup and where its answer goes
/// pending permission prompt for bash/write/edit
perm: Option<(
permit_view::Prompt,
tokio::sync::oneshot::Sender<hx_core::permit::Decision>,
)>,
review: Option<review::Review>,
stats: Option<(hx_core::stats::Summary, String)>,
/// lens/context/MCP side panel (ctrl-l), wide terminals only
side: bool,
lens_lines: Vec<String>,
mcp: Vec<(String, bool)>,
choose: Option<(
choose::Choose,
tokio::sync::oneshot::Sender<Option<Vec<String>>>,
@@ -214,6 +234,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
specs,
open_sessions,
mouse,
mcp,
} = setup;
let (tx, mut rx) = mpsc::unbounded_channel();
agent.bus.add(Forward(tx.clone()));
@@ -229,6 +250,14 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
Box::pin(async move { orx.await.unwrap_or(false) })
}));
}
{
let tx = tx.clone();
let _ = agent.cx.state.permit.set(std::sync::Arc::new(move |r| {
let (otx, orx) = tokio::sync::oneshot::channel();
let _ = tx.send(Ui::Permit(r, otx));
Box::pin(async move { orx.await.unwrap_or(hx_core::permit::Decision::Deny) })
}));
}
{
let tx = tx.clone();
let _ = agent.cx.state.choose.set(std::sync::Arc::new(move |q| {
@@ -275,6 +304,12 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
ask: None,
lens: (String::new(), false),
choose: None,
perm: None,
review: None,
stats: None,
side: true,
lens_lines: vec![],
mcp,
state: agent.cx.state.clone(),
sub_t: Default::default(),
agents: None,
@@ -321,6 +356,20 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
let Some(Ok(ev)) = k else { break };
dirty = true;
match ev {
TEvent::Key(k) if k.kind != KeyEventKind::Release && app.perm.is_some() => {
if let Some((p, _)) = &mut app.perm
&& let Some(d) = p.key(k)
&& let Some((p, reply)) = app.perm.take()
{
app.t.push(Item::Info(format!(
"{} {} {}",
permit_view::Prompt::label(d),
p.req.tool,
p.req.detail
)));
let _ = reply.send(d);
}
}
TEvent::Key(k) if k.kind != KeyEventKind::Release && app.choose.is_some() => {
if let Some((c, _)) = &mut app.choose
&& let choose::Act::Done(ans) = c.key(k)
@@ -357,6 +406,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
dirty = true;
match u {
Ui::Ask(q, reply) => app.ask = Some((q, reply)),
Ui::Permit(r, reply) => app.perm = Some((permit_view::Prompt::new(r), reply)),
Ui::Choose(q, reply) => app.choose = Some((choose::Choose::new(q), reply)),
Ui::Ev(e) => {
if let Event::SubUsage(u) = &e {
@@ -409,6 +459,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
let to = std::time::Duration::from_millis(200);
if let Ok(v) = tokio::time::timeout(to, lsp_status()).await {
let s = status::lens_summary(&v);
app.lens_lines = v;
dirty |= s != app.lens;
app.lens = s;
}
@@ -668,6 +719,32 @@ fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option<String> {
if app.sessions.is_some() {
return sessions_key(app, k);
}
if app.stats.is_some() {
if matches!(k.code, KeyCode::Esc | KeyCode::Char('q')) {
app.stats = None;
}
return None;
}
if let Some(r) = &mut app.review {
match r.key(k) {
review::Act::Close => app.review = None,
review::Act::Reverted(p) => {
app.state
.edits
.lock()
.unwrap_or_else(|e| e.into_inner())
.retain(|e| e.path != p);
app.t.push(Item::Info(format!("reverted {}", p.display())));
}
review::Act::Error(e) => app.t.push(Item::Error(e)),
review::Act::None => {}
}
return None;
}
if ctrl && k.code == KeyCode::Char('l') {
app.side = !app.side;
return None;
}
if ctrl && k.code == KeyCode::Char('g') {
app.popup = None;
app.agents = match (app.agents.take(), app.state.subs.list().len()) {
@@ -850,6 +927,23 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
let h = format!("{}\n\nkeys: {KEYS} · ctrl-p picker", cmd::help(&app.specs));
show(app, "help", h);
}
"stats" => {
let sess = agent.lock().await;
let sum = hx_core::stats::summary(sess.session());
app.stats = Some((sum, app.title.clone().unwrap_or_default()));
}
"diff" => {
let edits = app
.state
.edits
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone();
match review::Review::new(&edits) {
Some(r) => app.review = Some(r),
None => app.t.push(Item::Info("no edits to review".into())),
}
}
"usage" => {
let r = status::report(&app.st, status::now_secs());
show(app, "usage", r);
@@ -1052,6 +1146,19 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
app.areas.panel = side;
m
}
None if app.wide && app.side => {
let [m, side] =
Layout::horizontal([Constraint::Min(60), Constraint::Length(34)]).areas(main);
let block = Block::new()
.borders(Borders::LEFT)
.border_style(th.dim())
.title(Span::styled(" lens · ctrl-l ", th.dim()));
let body = block.inner(side);
f.render_widget(block, side);
f.render_widget(Paragraph::new(side_lines(app)), body);
app.areas.panel = Rect::default();
m
}
_ => {
app.areas.panel = Rect::default();
main
@@ -1142,6 +1249,56 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
if let Some(s) = &mut app.sessions {
s.draw(f);
}
if let Some((s, t)) = &app.stats {
stats_view::draw(f, s, t);
}
if let Some(r) = &app.review {
r.draw(f);
}
if let Some((p, _)) = &app.perm {
p.draw(f, input.y);
}
}
/// Right-hand overview on wide terminals: lens state, context numbers, MCP servers.
fn side_lines(app: &App) -> Vec<Line<'static>> {
let th = theme::t();
let head = |t: &str| Line::styled(t.to_string(), th.accent());
let mut l = vec![head("LSP / LINT")];
if app.lens_lines.is_empty() {
l.push(Line::styled("(none started)", th.dim()));
}
l.extend(app.lens_lines.iter().map(|x| {
let bad = x.contains("dead") || x.contains("error") || x.contains("missing");
Line::styled(x.clone(), if bad { th.warn() } else { th.plain() })
}));
let u = &app.st.usage;
let tot = u.input_tokens + u.cache_read_tokens + u.cache_write_tokens;
l.push(Line::default());
l.push(head("CONTEXT"));
l.push(Line::raw(format!(
"window {}k / {}k",
app.st.ctx_tokens / 1000,
app.st.ctx_max / 1000
)));
if let Some(p) = (100 * u.cache_read_tokens).checked_div(tot) {
l.push(Line::raw(format!("cache {p}%")));
}
l.push(Line::raw(format!("output {}k", u.output_tokens / 1000)));
if !app.mcp.is_empty() {
l.push(Line::default());
l.push(head("MCP"));
l.extend(app.mcp.iter().map(|(n, ok)| {
Line::from(vec![
Span::styled(
if *ok { "● " } else { "○ " },
if *ok { th.ok() } else { th.err() },
),
Span::raw(n.clone()),
])
}));
}
l
}
/// `/skills`: each skill with its file, then the searched dirs (so a missing skill is easy to debug).
@@ -1247,6 +1404,62 @@ mod tests {
assert!(rows[9].ends_with("Claude · m1"), "{all}");
}
fn screen(app: &mut App, w: u16, h: u16) -> String {
let mut term = ratatui::Terminal::new(TestBackend::new(w, h)).unwrap();
term.draw(|f| draw(f, app)).unwrap();
let b = term.backend().buffer().clone();
(0..h)
.map(|y| {
(0..w)
.map(|x| b[(x, y)].symbol().to_string())
.collect::<String>()
})
.collect::<Vec<_>>()
.join("\n")
}
#[test]
fn side_panel_only_on_wide_terminals() {
let mut app = test_app();
app.mcp = vec![("git".into(), true), ("db".into(), false)];
app.lens_lines = vec!["rust-analyzer @ /p: running".into()];
assert!(screen(&mut app, 160, 50).contains("MCP"));
assert!(!screen(&mut app, 80, 24).contains("MCP"));
app.side = false;
assert!(!screen(&mut app, 160, 50).contains("MCP"));
}
#[test]
fn overlays_render_at_both_sizes() {
let mut app = test_app();
app.review = review::Review::new(&[hx_core::permit::FileEdit {
path: "/x/a.rs".into(),
old: Some("a\n".into()),
new: "b\n".into(),
}]);
let (tx, _rx) = tokio::sync::oneshot::channel();
app.perm = Some((
permit_view::Prompt::new(hx_core::permit::Request {
tool: "bash".into(),
detail: "rm -rf target".into(),
rule: "bash:rm".into(),
}),
tx,
));
for (w, h) in [(80, 24), (160, 50)] {
let s = screen(&mut app, w, h);
assert!(
s.contains("permission") && s.contains("rm -rf target"),
"{s}"
);
assert!(s.contains("review · 1 files · +1 -1"), "{s}");
}
app.review = None;
app.perm = None;
app.stats = Some((hx_core::stats::Summary::default(), "s".into()));
assert!(screen(&mut app, 80, 24).contains("stats · s"));
}
#[tokio::test]
async fn ctrl_g_opens_agents_list_detail_and_back() {
use hx_core::tool::{Tool, ToolCtx};
@@ -1478,6 +1691,12 @@ mod tests {
ask: None,
lens: (String::new(), false),
choose: None,
perm: None,
review: None,
stats: None,
side: true,
lens_lines: vec![],
mcp: vec![],
state: Default::default(),
sub_t: Default::default(),
agents: None,
+121
View File
@@ -0,0 +1,121 @@
//! Permission popup for bash/write/edit.
use crate::theme;
use crossterm::event::{KeyCode, KeyEvent};
use hx_core::permit::{Decision, Request};
use ratatui::layout::Rect;
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Clear, Paragraph, Wrap};
pub struct Prompt {
pub req: Request,
sel: usize,
}
impl Prompt {
pub fn new(req: Request) -> Self {
Self { req, sel: 0 }
}
/// Some = decided.
pub fn key(&mut self, k: KeyEvent) -> Option<Decision> {
match k.code {
KeyCode::Char('y' | 'Y') => Some(Decision::Once),
KeyCode::Char('a' | 'A') => Some(Decision::Always),
KeyCode::Char('n' | 'N') | KeyCode::Esc => Some(Decision::Deny),
KeyCode::Up | KeyCode::Left => {
self.sel = (self.sel + 2) % 3;
None
}
KeyCode::Down | KeyCode::Right | KeyCode::Tab => {
self.sel = (self.sel + 1) % 3;
None
}
KeyCode::Enter => Some([Decision::Once, Decision::Always, Decision::Deny][self.sel]),
_ => None,
}
}
pub fn label(d: Decision) -> &'static str {
match d {
Decision::Once => "allowed",
Decision::Always => "allowed always",
Decision::Deny => "denied",
}
}
/// Centered in the first `bottom` rows.
pub fn draw(&self, f: &mut ratatui::Frame, bottom: u16) {
let th = theme::t();
let a = f.area();
let w = (a.width * 3 / 5).clamp(44, 100).min(a.width);
let opts = [
"[y] allow once".to_string(),
format!("[a] allow always: {}", self.req.rule),
"[n] deny".to_string(),
];
let mut lines = vec![
Line::styled("hx wants to run:", th.dim()),
Line::default(),
Line::from(vec![
Span::styled(format!("{} ", self.req.tool), th.accent()),
Span::raw(self.req.detail.clone()),
]),
Line::default(),
];
lines.extend(opts.iter().enumerate().map(|(i, o)| {
let (mark, st) = if i == self.sel {
("▶ ", th.sel())
} else {
(" ", th.plain())
};
Line::styled(format!("{mark}{o}"), st)
}));
let inner = w.saturating_sub(4).max(1);
let h = (Paragraph::new(lines.clone())
.wrap(Wrap { trim: false })
.line_count(inner) as u16
+ 2)
.min(bottom)
.max(3);
let r = Rect::new((a.width - w) / 2, (bottom - h) / 2, w, h);
f.render_widget(Clear, r);
f.render_widget(
Paragraph::new(lines).wrap(Wrap { trim: false }).block(
Block::bordered()
.border_style(th.warn())
.padding(ratatui::widgets::Padding::horizontal(1))
.title(Span::styled(" permission ", th.warn()))
.title_bottom(Span::styled(" ↑↓ select · ⏎ confirm ", th.dim())),
),
r,
);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crossterm::event::KeyModifiers;
fn p() -> Prompt {
Prompt::new(Request {
tool: "bash".into(),
detail: "rm -rf x".into(),
rule: "bash:rm".into(),
})
}
fn k(c: KeyCode) -> KeyEvent {
KeyEvent::new(c, KeyModifiers::NONE)
}
#[test]
fn letters_and_selection() {
assert_eq!(p().key(k(KeyCode::Char('y'))), Some(Decision::Once));
assert_eq!(p().key(k(KeyCode::Char('a'))), Some(Decision::Always));
assert_eq!(p().key(k(KeyCode::Esc)), Some(Decision::Deny));
let mut q = p();
assert_eq!(q.key(k(KeyCode::Down)), None);
assert_eq!(q.key(k(KeyCode::Enter)), Some(Decision::Always));
}
}
+3 -1
View File
@@ -133,7 +133,9 @@ impl Picker {
let th = theme::t();
let a = f.area();
// scales with the terminal: 60% of the width, 50..=110 cols, never wider than the screen
let w = (a.width * 6 / 10).clamp(50, 110).min(a.width.saturating_sub(4));
let w = (a.width * 6 / 10)
.clamp(50, 110)
.min(a.width.saturating_sub(4));
let ms = self.matches();
// borders + query line + spacer
let h = (ms.len() as u16 + 4)
+229
View File
@@ -0,0 +1,229 @@
//! `/diff`: file list + diff of this session's write/edit calls; reject reverts the file on disk.
use crate::theme;
use crossterm::event::{KeyCode, KeyEvent};
use hx_core::permit::FileEdit;
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Clear, Paragraph};
use std::path::PathBuf;
#[derive(Debug, Clone, PartialEq)]
pub enum State {
Pending,
Accepted,
Reverted,
}
pub struct File {
pub path: PathBuf,
old: Option<String>,
new: String,
pub state: State,
diff: Vec<String>,
pub add: usize,
pub del: usize,
}
pub enum Act {
None,
Close,
/// A file was put back; the app drops it from the edits log.
Reverted(PathBuf),
Error(String),
}
pub struct Review {
pub files: Vec<File>,
pub sel: usize,
scroll: u16,
}
impl Review {
/// One entry per path: first `old` to last `new`; no-op edits drop out. None = nothing to review.
pub fn new(edits: &[FileEdit]) -> Option<Self> {
let mut files: Vec<File> = vec![];
for e in edits {
match files.iter_mut().find(|f| f.path == e.path) {
Some(f) => f.new = e.new.clone(),
None => files.push(File {
path: e.path.clone(),
old: e.old.clone(),
new: e.new.clone(),
state: State::Pending,
diff: vec![],
add: 0,
del: 0,
}),
}
}
files.retain(|f| f.old.as_deref() != Some(f.new.as_str()));
for f in &mut files {
let d = similar::TextDiff::from_lines(f.old.as_deref().unwrap_or(""), &f.new)
.unified_diff()
.context_radius(3)
.to_string();
f.diff = d.lines().map(String::from).collect();
f.add = f.diff.iter().filter(|l| l.starts_with('+')).count();
f.del = f.diff.iter().filter(|l| l.starts_with('-')).count();
}
(!files.is_empty()).then_some(Self {
files,
sel: 0,
scroll: 0,
})
}
pub fn key(&mut self, k: KeyEvent) -> Act {
let n = self.files.len();
match k.code {
KeyCode::Esc | KeyCode::Char('q') => return Act::Close,
KeyCode::Char('n') | KeyCode::Tab => {
self.sel = (self.sel + 1) % n;
self.scroll = 0;
}
KeyCode::Char('p') | KeyCode::BackTab => {
self.sel = (self.sel + n - 1) % n;
self.scroll = 0;
}
KeyCode::Char('j') | KeyCode::Down => self.scroll = self.scroll.saturating_add(1),
KeyCode::Char('k') | KeyCode::Up => self.scroll = self.scroll.saturating_sub(1),
KeyCode::PageDown => self.scroll = self.scroll.saturating_add(10),
KeyCode::PageUp => self.scroll = self.scroll.saturating_sub(10),
KeyCode::Char('a') => self.files[self.sel].state = State::Accepted,
KeyCode::Char('r') => {
let f = &mut self.files[self.sel];
match revert(f) {
Ok(()) => {
f.state = State::Reverted;
return Act::Reverted(f.path.clone());
}
Err(e) => return Act::Error(e),
}
}
_ => {}
}
Act::None
}
pub fn draw(&self, f: &mut ratatui::Frame) {
let th = theme::t();
let a = f.area();
let (w, h) = (a.width * 9 / 10, a.height * 9 / 10);
let r = Rect::new(a.x + (a.width - w) / 2, a.y + (a.height - h) / 2, w, h);
let (add, del) = self
.files
.iter()
.fold((0, 0), |(a, d), f| (a + f.add, d + f.del));
let block = Block::bordered()
.border_style(th.dim())
.title(Line::from(vec![
Span::styled(format!(" review · {} files · ", self.files.len()), th.dim()),
Span::styled(format!("+{add} "), th.add()),
Span::styled(format!("-{del} "), th.del()),
]))
.title_bottom(Span::styled(
" a accept · r reject (revert) · n/p file · j/k scroll · esc close ",
th.dim(),
));
let inner = block.inner(r);
f.render_widget(Clear, r);
f.render_widget(block, r);
let lw = (inner.width / 3).clamp(16, 36);
let [left, right] =
Layout::horizontal([Constraint::Length(lw), Constraint::Min(10)]).areas(inner);
let list: Vec<Line> = self
.files
.iter()
.enumerate()
.map(|(i, x)| {
let tag = match x.state {
State::Pending => " ",
State::Accepted => "✓",
State::Reverted => "↩",
};
let name = x
.path
.file_name()
.map_or_else(String::new, |n| n.to_string_lossy().into());
let st = if i == self.sel { th.sel() } else { th.plain() };
Line::styled(format!("{tag} {name} +{} -{}", x.add, x.del), st)
})
.collect();
f.render_widget(Paragraph::new(list), left);
let cur = &self.files[self.sel];
let mut lines = vec![Line::styled(cur.path.display().to_string(), th.accent())];
lines.extend(cur.diff.iter().map(|l| {
let st = match l.chars().next() {
Some('+') => th.add(),
Some('-') => th.del(),
Some('@') => th.hunk(),
_ => th.plain(),
};
Line::styled(l.clone(), st)
}));
let max = lines.len().saturating_sub(right.height as usize) as u16;
f.render_widget(
Paragraph::new(lines).scroll((self.scroll.min(max), 0)),
right,
);
}
}
/// Put the file back to `old` (delete it when the agent created it). Refuses when the file is not
/// what the agent left, so manual edits are never overwritten.
fn revert(f: &File) -> Result<(), String> {
if f.state == State::Reverted {
return Err("already reverted".into());
}
let now = std::fs::read_to_string(&f.path).map_err(|e| format!("{}: {e}", f.path.display()))?;
if now != f.new {
return Err(format!(
"{} changed on disk since; not reverting",
f.path.display()
));
}
match &f.old {
Some(o) => std::fs::write(&f.path, o),
None => std::fs::remove_file(&f.path),
}
.map_err(|e| format!("{}: {e}", f.path.display()))
}
#[cfg(test)]
mod tests {
use super::*;
use crossterm::event::KeyModifiers;
fn key(c: char) -> KeyEvent {
KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE)
}
#[test]
fn collapses_counts_and_reverts() {
let d = tempfile::tempdir().unwrap();
let (p, q) = (d.path().join("a.txt"), d.path().join("b.txt"));
std::fs::write(&p, "one\nTWO\nthree\n").unwrap();
std::fs::write(&q, "new\n").unwrap();
let e = |path: &PathBuf, old: Option<&str>, new: &str| FileEdit {
path: path.clone(),
old: old.map(Into::into),
new: new.into(),
};
let mut r = Review::new(&[
e(&p, Some("one\ntwo\nthree\n"), "one\n2\nthree\n"),
e(&p, Some("one\n2\nthree\n"), "one\nTWO\nthree\n"),
e(&q, None, "new\n"),
e(&q, Some("same\n"), "same\n"),
])
.unwrap();
assert_eq!((r.files.len(), r.files[0].add, r.files[0].del), (2, 1, 1));
assert!(matches!(r.key(key('r')), Act::Reverted(_)));
assert_eq!(std::fs::read_to_string(&p).unwrap(), "one\ntwo\nthree\n");
r.key(key('n'));
std::fs::write(&q, "edited by hand").unwrap();
assert!(matches!(r.key(key('r')), Act::Error(_)));
assert!(q.exists());
assert!(Review::new(&[]).is_none());
}
}
+99
View File
@@ -0,0 +1,99 @@
//! `/stats` dashboard: token totals, cache hit, per-request table.
use crate::theme;
use hx_core::stats::Summary;
use ratatui::layout::Rect;
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Clear, Paragraph};
fn bar(v: u64, max: u64, w: usize) -> String {
let th = theme::t();
let n = (v * w as u64 / max.max(1)) as usize;
format!(
"{}{}",
th.sym.bar_full.repeat(n),
th.sym.bar_empty.repeat(w - n)
)
}
fn k(n: u64) -> String {
format!("{:.1}k", n as f64 / 1000.0)
}
pub fn lines(s: &Summary, rows: usize) -> Vec<Line<'static>> {
let th = theme::t();
let total = s.fresh + s.cache_read + s.cache_write;
let hit = 100 * s.cache_read / total.max(1);
let row = |name: &str, v: u64, extra: String| {
Line::from(vec![
Span::raw(format!("{name:<8}{:>7} ", k(v))),
Span::styled(bar(v, total.max(s.output), 20), th.accent()),
Span::styled(extra, th.ok()),
])
};
let mut l = vec![
row("input", total, String::new()),
row("output", s.output, String::new()),
row("cache r", s.cache_read, format!(" {hit}% hit")),
Line::default(),
Line::styled(
format!("{:<5}{:>9}{:>9}{:>8}", "req", "in", "out", "cache"),
th.dim(),
),
];
let skip = s.reqs.len().saturating_sub(rows);
for (i, (inp, out, h)) in s.reqs.iter().enumerate().skip(skip) {
l.push(Line::from(vec![
Span::raw(format!("#{:<4}{:>9}{:>9}", i + 1, k(*inp), k(*out))),
Span::styled(
format!("{:>7}%", h),
if *h >= 80 { th.ok() } else { th.warn() },
),
]));
}
l
}
pub fn draw(f: &mut ratatui::Frame, s: &Summary, title: &str) {
let th = theme::t();
let a = f.area();
let w = (a.width * 6 / 10).clamp(50, 90).min(a.width);
let h = (a.height * 7 / 10).clamp(12, 30).min(a.height);
let r = Rect::new(a.x + (a.width - w) / 2, a.y + (a.height - h) / 2, w, h);
let body = if s.reqs.is_empty() {
vec![Line::styled("no usage recorded yet", th.dim())]
} else {
lines(s, (h as usize).saturating_sub(9))
};
f.render_widget(Clear, r);
f.render_widget(
Paragraph::new(body).block(
Block::bordered()
.border_style(th.dim())
.padding(ratatui::widgets::Padding::horizontal(1))
.title(Span::styled(format!(" stats · {title} "), th.dim()))
.title_bottom(Span::styled(" esc close ", th.dim())),
),
r,
);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn table_keeps_latest_rows() {
let s = Summary {
fresh: 10,
cache_read: 90,
cache_write: 0,
output: 5,
reqs: (1..=10).map(|i| (100, 5, i)).collect(),
};
let l = lines(&s, 3);
assert_eq!(l.len(), 5 + 3);
assert!(l[2].to_string().contains("90% hit"));
assert!(l.last().unwrap().to_string().starts_with("#10"));
}
}