493 lines
16 KiB
Rust
493 lines
16 KiB
Rust
//! Status line and `/usage` report: pure functions from session numbers (and the clock) to text.
|
|
//!
|
|
//! Nothing here touches the terminal or the clock itself: callers pass `now` (unix seconds), so
|
|
//! every layout and threshold is testable with fixed inputs.
|
|
|
|
use crate::theme;
|
|
use hx_ai::Usage;
|
|
use hx_ai::auth::Kind;
|
|
use ratatui::style::Modifier;
|
|
use ratatui::text::{Line, Span};
|
|
|
|
/// What the status line and `/usage` report about the running session.
|
|
pub struct Status {
|
|
pub kind: Kind,
|
|
pub model: String,
|
|
pub usage: Usage,
|
|
pub ctx_tokens: usize,
|
|
/// auto-compact threshold: the context bar's 100%
|
|
pub ctx_max: usize,
|
|
/// last subscription limits reported by the provider
|
|
pub quota: Option<hx_ai::Quota>,
|
|
pub pricing: fn(&str) -> Option<hx_ai::Pricing>,
|
|
}
|
|
|
|
/// Transient UI state the footer also shows.
|
|
#[derive(Default)]
|
|
pub struct Chrome<'a> {
|
|
/// pending yes/no question from a tool; takes the whole line
|
|
pub ask: Option<&'a str>,
|
|
/// replaces the right side when non-empty
|
|
pub hint: &'a str,
|
|
pub queued: usize,
|
|
/// lines scrolled up from the bottom
|
|
pub scroll: u16,
|
|
/// None until the first prompt
|
|
pub title: Option<&'a str>,
|
|
/// `lsp 2/2 · lint 4`; empty until the first poll
|
|
pub lens: &'a str,
|
|
/// a server is dead/breaker-open or a runner binary is missing
|
|
pub lens_warn: bool,
|
|
}
|
|
|
|
/// Terminals at least this wide get a second footer row.
|
|
pub const TWO_ROWS: u16 = 100;
|
|
|
|
/// Footer height for this width (the ask line always takes one row).
|
|
pub fn rows_for(width: u16, ask: bool) -> u16 {
|
|
if width >= TWO_ROWS && !ask { 2 } else { 1 }
|
|
}
|
|
|
|
/// Condense `/lsp` lines into `lsp 2/3 · lint 4 · 1 marked`; bool = something needs attention.
|
|
pub fn lens_summary(lines: &[String]) -> (String, bool) {
|
|
let (mut up, mut total, mut marked, mut notes, mut lint) = (0, 0, 0, 0, 0);
|
|
for l in lines {
|
|
if let Some(r) = l.strip_prefix("runners: ") {
|
|
lint = r.split(", ").filter(|x| !x.is_empty()).count();
|
|
} else if l.starts_with("marked ") {
|
|
marked += 1;
|
|
} else if l.contains(" @ ") {
|
|
total += 1;
|
|
up += usize::from(l.contains(": running"));
|
|
} else {
|
|
notes += 1;
|
|
}
|
|
}
|
|
let mut v = vec![];
|
|
if total > 0 {
|
|
v.push(format!("lsp {up}/{total}"));
|
|
}
|
|
if lint > 0 {
|
|
v.push(format!("lint {lint}"));
|
|
}
|
|
if marked > 0 {
|
|
v.push(format!("{marked} marked"));
|
|
}
|
|
if notes > 0 {
|
|
v.push(format!("{notes} missing"));
|
|
}
|
|
(v.join(" · "), up < total || notes > 0)
|
|
}
|
|
|
|
/// Footer lines: two rows on wide terminals (usage on top; lens left, session tail right),
|
|
/// else the single packed line from [`footer`]. A hint only replaces the top row's right side.
|
|
pub fn rows(st: &Status, c: &Chrome, width: u16, now: u64) -> Vec<Line<'static>> {
|
|
if rows_for(width, c.ask.is_some()) == 1 {
|
|
return vec![footer(st, c, width, now)];
|
|
}
|
|
let th = theme::t();
|
|
let w = width as usize;
|
|
let lw = |l: &[Span]| l.iter().map(Span::width).sum::<usize>();
|
|
let mut top = left_spans(st, now);
|
|
if !c.hint.is_empty() {
|
|
let r = Span::styled(c.hint.to_string(), th.accent());
|
|
top.push(Span::raw(
|
|
" ".repeat(w.saturating_sub(lw(&top) + r.width()).max(1)),
|
|
));
|
|
top.push(r);
|
|
}
|
|
let lens = if c.lens.is_empty() {
|
|
"lens: starting"
|
|
} else {
|
|
c.lens
|
|
};
|
|
let mut bot = vec![Span::styled(
|
|
lens.to_string(),
|
|
if c.lens_warn { th.warn() } else { th.dim() },
|
|
)];
|
|
let tail = tail(st, c).join(" · ");
|
|
let room = w.saturating_sub(lw(&bot) + tail.chars().count() + 4);
|
|
let title = c.title.unwrap_or("new session");
|
|
let right = if room >= 12 {
|
|
let t: String = if title.chars().count() > room.min(40) {
|
|
title.chars().take(room.min(40) - 1).chain(['…']).collect()
|
|
} else {
|
|
title.into()
|
|
};
|
|
format!("{t} · {tail}")
|
|
} else {
|
|
tail
|
|
};
|
|
let r = Span::styled(right, th.dim());
|
|
bot.push(Span::raw(
|
|
" ".repeat(w.saturating_sub(lw(&bot) + r.width()).max(1)),
|
|
));
|
|
bot.push(r);
|
|
vec![Line::from(top), Line::from(bot)]
|
|
}
|
|
|
|
/// Context bar, quota windows, token counts and cost estimate.
|
|
fn left_spans(st: &Status, now: u64) -> Vec<Span<'static>> {
|
|
let th = theme::t();
|
|
let k = |n: u64| {
|
|
if n >= 1000 {
|
|
format!("{:.1}k", n as f64 / 1000.0)
|
|
} else {
|
|
n.to_string()
|
|
}
|
|
};
|
|
let frac = st.ctx_tokens as f64 / st.ctx_max.max(1) as f64;
|
|
let full = ((frac * 10.0).round() as usize).min(10);
|
|
let bar_st = match frac {
|
|
f if f >= 0.9 => th.err(),
|
|
f if f >= 0.7 => th.warn(),
|
|
_ => th.accent(),
|
|
};
|
|
// subscription quota replaces the API-equivalent cost estimate once the provider reports it
|
|
let cost = match st.quota {
|
|
Some(_) => String::new(),
|
|
None => (st.pricing)(&st.model)
|
|
.map(|p| format!(" ~${:.2}", st.usage.cost(&p)))
|
|
.unwrap_or_default(),
|
|
};
|
|
let mut left = vec![
|
|
Span::styled("ctx ", th.dim()),
|
|
Span::styled(th.sym.bar_full.repeat(full), bar_st),
|
|
Span::styled(th.sym.bar_empty.repeat(10 - full), th.dim()),
|
|
Span::styled(
|
|
format!(" {}k/{}k", st.ctx_tokens / 1000, st.ctx_max / 1000),
|
|
th.dim(),
|
|
),
|
|
];
|
|
if let Some(q) = &st.quota {
|
|
left.extend(quota_spans(q, now));
|
|
}
|
|
left.extend([Span::styled(
|
|
format!(
|
|
" · {}↑ {}↓{cost}",
|
|
k(st.usage.input_tokens + st.usage.cache_read_tokens),
|
|
k(st.usage.output_tokens)
|
|
),
|
|
th.dim(),
|
|
)]);
|
|
left
|
|
}
|
|
|
|
/// `ctx ▰▰▰▱▱▱▱▱▱▱ 41k/150k · 12.3k↑ 2.1k↓ ~$0.08` left, `Claude · model · 1 queued` right.
|
|
/// Hints replace the right side; a pending y/n question takes the whole line.
|
|
pub fn footer(st: &Status, c: &Chrome, width: u16, now: u64) -> Line<'static> {
|
|
let th = theme::t();
|
|
if let Some(q) = c.ask {
|
|
return Line::styled(format!("[y/n] {q}"), th.warn().add_modifier(Modifier::BOLD));
|
|
}
|
|
let mut left = left_spans(st, now);
|
|
let w = width as usize;
|
|
let lw = |l: &[Span]| l.iter().map(Span::width).sum::<usize>();
|
|
if !c.hint.is_empty() {
|
|
let right = Span::styled(c.hint.to_string(), th.accent());
|
|
if lw(&left) + right.width() + 1 > w {
|
|
return Line::from(right);
|
|
}
|
|
let pad = w - lw(&left) - right.width();
|
|
left.push(Span::raw(" ".repeat(pad)));
|
|
left.push(right);
|
|
return Line::from(left);
|
|
}
|
|
let tail = tail(st, c);
|
|
let title = c.title.unwrap_or("new session");
|
|
// drop in order until it fits: token counts, title, context bar
|
|
let mut title_room = w.saturating_sub(lw(&left) + tail.join(" · ").chars().count() + 4);
|
|
if title_room < 12 {
|
|
left.pop();
|
|
title_room = w.saturating_sub(lw(&left) + tail.join(" · ").chars().count() + 4);
|
|
}
|
|
let mut right = tail.join(" · ");
|
|
if title_room >= 12 {
|
|
let t: String = if title.chars().count() > title_room.min(40) {
|
|
title
|
|
.chars()
|
|
.take(title_room.min(40) - 1)
|
|
.chain(['…'])
|
|
.collect()
|
|
} else {
|
|
title.into()
|
|
};
|
|
right = format!("{t} · {right}");
|
|
}
|
|
let right = Span::styled(right, th.dim());
|
|
if lw(&left) + right.width() + 1 > w {
|
|
return Line::from(right);
|
|
}
|
|
let pad = w - lw(&left) - right.width();
|
|
left.push(Span::raw(" ".repeat(pad.max(1))));
|
|
left.push(right);
|
|
Line::from(left)
|
|
}
|
|
|
|
fn tail(st: &Status, c: &Chrome) -> Vec<String> {
|
|
let mut t = vec![format!("{:?}", st.kind), st.model.clone()];
|
|
if c.queued > 0 {
|
|
t.push(format!("{} queued", c.queued));
|
|
}
|
|
if c.scroll > 0 {
|
|
t.push(format!("↑{}", c.scroll));
|
|
}
|
|
t
|
|
}
|
|
|
|
pub fn now_secs() -> u64 {
|
|
std::time::SystemTime::now()
|
|
.duration_since(std::time::UNIX_EPOCH)
|
|
.map_or(0, |d| d.as_secs())
|
|
}
|
|
|
|
/// `2h13m`, `3d4h`, `45m` until `at`.
|
|
fn until(at: u64, now: u64) -> String {
|
|
let s = at.saturating_sub(now);
|
|
let (d, h, m) = (s / 86_400, s % 86_400 / 3600, s % 3600 / 60);
|
|
match (d, h) {
|
|
(0, 0) => format!("{}m", m.max(1)),
|
|
(0, _) => format!("{h}h{m:02}m"),
|
|
_ => format!("{d}d{h}h"),
|
|
}
|
|
}
|
|
|
|
/// ` · 5h 42% 2h13m · week 13%`, then credits; warn at 70%, error at 90%.
|
|
fn quota_spans(q: &hx_ai::Quota, now: u64) -> Vec<Span<'static>> {
|
|
let th = theme::t();
|
|
let mut v = vec![];
|
|
for w in &q.windows {
|
|
let st = match w.used_pct {
|
|
p if p >= 90.0 => th.err(),
|
|
p if p >= 70.0 => th.warn(),
|
|
_ => th.dim(),
|
|
};
|
|
let reset = w
|
|
.resets_at
|
|
.map(|r| format!(" {}{}", th.sym.reset, until(r, now)))
|
|
.unwrap_or_default();
|
|
v.push(Span::styled(" · ", th.dim()));
|
|
v.push(Span::styled(
|
|
format!("{} {:.0}%{reset}", w.label, w.used_pct),
|
|
st,
|
|
));
|
|
}
|
|
if let Some(c) = &q.credits {
|
|
v.push(Span::styled(format!(" · {c}"), th.dim()));
|
|
}
|
|
v
|
|
}
|
|
|
|
/// `/usage`: every window with its reset time, credits, and this session's tokens.
|
|
pub fn report(st: &Status, now: u64) -> String {
|
|
let mut out = vec![format!("{:?} · {}", st.kind, st.model)];
|
|
match &st.quota {
|
|
None => out.push("subscription limits: not reported yet (send a prompt first)".into()),
|
|
Some(q) => {
|
|
for w in &q.windows {
|
|
let reset = w
|
|
.resets_at
|
|
.map(|r| format!(", resets in {}", until(r, now)))
|
|
.unwrap_or_default();
|
|
out.push(format!(
|
|
"{:<5} {:>3.0}% used, {:.0}% left{reset}",
|
|
w.label,
|
|
w.used_pct,
|
|
100.0 - w.used_pct
|
|
));
|
|
}
|
|
if let Some(c) = &q.credits {
|
|
out.push(c.clone());
|
|
}
|
|
}
|
|
}
|
|
out.push(format!(
|
|
"context {}k of {}k before auto-compact",
|
|
st.ctx_tokens / 1000,
|
|
st.ctx_max / 1000
|
|
));
|
|
out.push(format!(
|
|
"session tokens: {} in, {} out",
|
|
st.usage.input_tokens + st.usage.cache_read_tokens,
|
|
st.usage.output_tokens
|
|
));
|
|
out.join("\n")
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn st() -> Status {
|
|
Status {
|
|
kind: Kind::Claude,
|
|
model: "m1".into(),
|
|
usage: Usage::default(),
|
|
ctx_tokens: 0,
|
|
ctx_max: 150_000,
|
|
quota: None,
|
|
pricing: |_| None,
|
|
}
|
|
}
|
|
|
|
fn text(l: Line) -> String {
|
|
l.spans.iter().map(|s| s.content.to_string()).collect()
|
|
}
|
|
|
|
fn quota() -> hx_ai::Quota {
|
|
hx_ai::Quota {
|
|
windows: vec![
|
|
hx_ai::QuotaWindow {
|
|
label: "5h".into(),
|
|
used_pct: 42.0,
|
|
resets_at: Some(10_000 + 2 * 3600 + 13 * 60),
|
|
},
|
|
hx_ai::QuotaWindow {
|
|
label: "week".into(),
|
|
used_pct: 91.0,
|
|
resets_at: Some(10_000 + 3 * 86_400 + 4 * 3600),
|
|
},
|
|
],
|
|
credits: Some("credits: 37.5".into()),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn quota_spans_and_countdown() {
|
|
let q = quota();
|
|
let t: String = quota_spans(&q, 10_000)
|
|
.iter()
|
|
.map(|s| s.content.to_string())
|
|
.collect();
|
|
assert_eq!(t, " · 5h 42% 2h13m · week 91% 3d4h · credits: 37.5");
|
|
assert_eq!(
|
|
quota_spans(&q, 10_000)[3].style.fg,
|
|
Some(ratatui::style::Color::Red)
|
|
);
|
|
assert_eq!(until(10_030, 10_000), "1m");
|
|
}
|
|
|
|
#[test]
|
|
fn usage_report_lists_windows() {
|
|
let mut s = st();
|
|
assert!(report(&s, 10_000).contains("not reported yet"));
|
|
s.quota = Some(quota());
|
|
let r = report(&s, 10_000);
|
|
assert!(
|
|
r.contains("5h 42% used, 58% left, resets in 2h13m"),
|
|
"{r}"
|
|
);
|
|
assert!(
|
|
r.contains("week 91% used, 9% left, resets in 3d4h"),
|
|
"{r}"
|
|
);
|
|
assert!(
|
|
r.contains("credits: 37.5") && r.contains("context 0k of 150k"),
|
|
"{r}"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn quota_replaces_cost_estimate() {
|
|
let mut s = st();
|
|
s.pricing = |_| Some(hx_ai::Pricing::default());
|
|
let c = Chrome::default();
|
|
assert!(text(footer(&s, &c, 140, 10_000)).contains('$'));
|
|
s.quota = Some(quota());
|
|
let l = text(footer(&s, &c, 140, 10_000));
|
|
assert!(l.contains("5h 42%") && !l.contains('$'), "{l}");
|
|
}
|
|
|
|
#[test]
|
|
fn pending_question_takes_the_line() {
|
|
let c = Chrome {
|
|
ask: Some("run rm?"),
|
|
..Default::default()
|
|
};
|
|
assert_eq!(text(footer(&st(), &c, 80, 0)), "[y/n] run rm?");
|
|
}
|
|
|
|
#[test]
|
|
fn hint_replaces_right_side_and_narrow_drops_it() {
|
|
let c = Chrome {
|
|
hint: "saved",
|
|
..Default::default()
|
|
};
|
|
let wide = text(footer(&st(), &c, 100, 0));
|
|
assert!(wide.starts_with("ctx ") && wide.ends_with("saved") && !wide.contains("m1"));
|
|
let narrow = text(footer(&st(), &c, 10, 0));
|
|
assert_eq!(narrow, "saved");
|
|
}
|
|
|
|
#[test]
|
|
fn tail_shows_model_queue_scroll_and_title_when_it_fits() {
|
|
let c = Chrome {
|
|
queued: 2,
|
|
scroll: 5,
|
|
title: Some("fix the parser"),
|
|
..Default::default()
|
|
};
|
|
let l = text(footer(&st(), &c, 140, 0));
|
|
assert!(l.ends_with("Claude · m1 · 2 queued · ↑5"), "{l}");
|
|
assert!(l.contains("fix the parser"), "{l}");
|
|
// too narrow for a title: it goes first, the tail stays
|
|
let l = text(footer(&st(), &c, 60, 0));
|
|
assert!(!l.contains("fix the parser") && l.contains("m1"), "{l}");
|
|
}
|
|
|
|
#[test]
|
|
fn lens_summary_counts() {
|
|
let v: Vec<String> = [
|
|
"rust-analyzer @ /w: running, 2 open",
|
|
"pyright @ /w: dead",
|
|
"marked Ignore: k (r)",
|
|
"runners: clippy, ruff, shellcheck",
|
|
"ruff not installed",
|
|
]
|
|
.map(String::from)
|
|
.into();
|
|
assert_eq!(
|
|
lens_summary(&v),
|
|
("lsp 1/2 · lint 3 · 1 marked · 1 missing".into(), true)
|
|
);
|
|
assert_eq!(lens_summary(&[]), (String::new(), false));
|
|
}
|
|
|
|
#[test]
|
|
fn wide_has_two_rows_and_hint_keeps_usage() {
|
|
let mut c = Chrome {
|
|
lens: "lsp 2/2 · lint 4",
|
|
hint: "saved",
|
|
title: Some("fix"),
|
|
..Default::default()
|
|
};
|
|
let r = rows(&st(), &c, 120, 0);
|
|
let (a, b) = (text(r[0].clone()), text(r[1].clone()));
|
|
assert!(
|
|
a.starts_with("ctx ") && a.contains("0↑ 0↓") && a.ends_with("saved"),
|
|
"{a}"
|
|
);
|
|
assert!(
|
|
b.starts_with("lsp 2/2") && b.ends_with("fix · Claude · m1"),
|
|
"{b}"
|
|
);
|
|
assert_eq!(b.chars().count(), 120);
|
|
assert_eq!(rows(&st(), &c, 80, 0).len(), 1);
|
|
c.ask = Some("rm?");
|
|
assert_eq!(rows(&st(), &c, 120, 0).len(), 1);
|
|
}
|
|
|
|
#[test]
|
|
fn context_bar_fill_and_color() {
|
|
let mut s = st();
|
|
s.ctx_tokens = 135_000;
|
|
let l = footer(&s, &Chrome::default(), 140, 0);
|
|
assert!(
|
|
text(l.clone()).starts_with("ctx ▰▰▰▰▰▰▰▰▰▱ 135k/150k"),
|
|
"{}",
|
|
text(l.clone())
|
|
);
|
|
assert_eq!(l.spans[1].style.fg, Some(ratatui::style::Color::Red));
|
|
}
|
|
}
|