416 lines
13 KiB
Rust
416 lines
13 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 {
|
|
/// `/model auto` is on: the model shown was picked for the last prompt
|
|
pub auto: bool,
|
|
pub kind: Kind,
|
|
pub model: String,
|
|
pub effort: hx_ai::Effort,
|
|
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 the key-hint row under the status row.
|
|
pub const TWO_ROWS: u16 = 80;
|
|
|
|
/// Default key hints (second footer row).
|
|
pub const KEYS: &str = "enter send · shift-enter newline · ctrl-o expand · ctrl-p palette";
|
|
|
|
/// 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: status row, then on terminals of [`TWO_ROWS`]+ a dim key-hint row with the lens
|
|
/// summary on the right. A transient hint replaces the key hints.
|
|
pub fn rows(st: &Status, c: &Chrome, width: u16, now: u64) -> Vec<Line<'static>> {
|
|
let mut v = vec![footer(st, c, width, now)];
|
|
if rows_for(width, c.ask.is_some()) == 2 {
|
|
let th = theme::t();
|
|
let (keys, kst) = if c.hint.is_empty() {
|
|
(KEYS, th.dim())
|
|
} else {
|
|
(c.hint, th.accent())
|
|
};
|
|
v.push(spread(
|
|
vec![Span::styled(keys.to_string(), kst)],
|
|
vec![Span::styled(
|
|
c.lens.to_string(),
|
|
if c.lens_warn { th.warn() } else { th.dim() },
|
|
)],
|
|
width as usize,
|
|
));
|
|
}
|
|
v
|
|
}
|
|
|
|
/// `left … right` padded to `w`; the right side is dropped when both don't fit.
|
|
fn spread(mut left: Vec<Span<'static>>, right: Vec<Span<'static>>, w: usize) -> Line<'static> {
|
|
let lw: usize = left.iter().map(Span::width).sum();
|
|
let rw: usize = right.iter().map(Span::width).sum();
|
|
if rw > 0 && lw + rw < w {
|
|
left.push(Span::raw(" ".repeat(w - lw - rw)));
|
|
left.extend(right);
|
|
}
|
|
Line::from(left)
|
|
}
|
|
|
|
/// `model · ctx ▰▰▰▱▱▱▱▱▱▱ 31% ~$0.08`.
|
|
fn left_spans(st: &Status) -> Vec<Span<'static>> {
|
|
let th = theme::t();
|
|
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 model = st.model.strip_prefix("claude-").unwrap_or(&st.model);
|
|
let auto = if st.auto { "auto→" } else { "" };
|
|
vec![
|
|
Span::styled(format!("{auto}{model} {} ctx ", th.sym.info), th.sec()),
|
|
Span::styled(th.sym.bar_full.repeat(full), bar_st),
|
|
Span::styled(th.sym.bar_empty.repeat(10 - full), th.dim()),
|
|
Span::styled(format!(" {:.0}%{cost}", frac * 100.0), th.sec()),
|
|
]
|
|
}
|
|
|
|
/// Status row: `model · ctx ▰▰▰▱▱▱▱▱▱▱ 31%` left, quota / think / scroll right.
|
|
/// A pending y/n question takes the whole line; narrow terminals put a hint on the right.
|
|
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 w = width as usize;
|
|
let mut right = vec![];
|
|
if !c.hint.is_empty() && rows_for(width, false) == 1 {
|
|
right.push(Span::styled(c.hint.to_string(), th.accent()));
|
|
let l = spread(left_spans(st), right.clone(), w);
|
|
return if l.width() > w { Line::from(right) } else { l };
|
|
}
|
|
if let Some(q) = &st.quota {
|
|
right.extend(quota_spans(q, now));
|
|
}
|
|
for t in tail(st, c) {
|
|
if !right.is_empty() {
|
|
right.push(Span::styled(format!(" {} ", th.sym.info), th.dim()));
|
|
}
|
|
right.push(Span::styled(t, th.sec()));
|
|
}
|
|
spread(left_spans(st), right, w)
|
|
}
|
|
|
|
fn tail(st: &Status, c: &Chrome) -> Vec<String> {
|
|
let mut t = vec![];
|
|
if st.effort != hx_ai::Effort::Off {
|
|
t.push(format!("think {}", st.effort.name()));
|
|
}
|
|
if c.scroll > 0 {
|
|
t.push(format!("{}{}", theme::t().sym.up, 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![];
|
|
let sep = || Span::styled(format!(" {} ", th.sym.info), th.dim());
|
|
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.sec(),
|
|
};
|
|
let reset = w
|
|
.resets_at
|
|
.map(|r| format!(" {}{}", th.sym.reset, until(r, now)))
|
|
.unwrap_or_default();
|
|
if !v.is_empty() {
|
|
v.push(sep());
|
|
}
|
|
v.push(Span::styled(
|
|
format!("{} {:.0}%{reset}", w.label, w.used_pct),
|
|
st,
|
|
));
|
|
}
|
|
if let Some(c) = &q.credits {
|
|
v.push(sep());
|
|
v.push(Span::styled(c.clone(), th.sec()));
|
|
}
|
|
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 {
|
|
auto: false,
|
|
kind: Kind::Claude,
|
|
model: "claude-m1".into(),
|
|
effort: hx_ai::Effort::Off,
|
|
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 sp = quota_spans(&q, 10_000);
|
|
let t: String = sp.iter().map(|s| s.content.to_string()).collect();
|
|
assert_eq!(t, "5h 42% ↻2h13m · week 91% ↻3d4h · credits: 37.5");
|
|
assert_eq!(sp[2].style.fg, theme::t().err().fg);
|
|
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?");
|
|
assert_eq!(rows(&st(), &c, 120, 0).len(), 1);
|
|
}
|
|
|
|
#[test]
|
|
fn status_row_and_hint_row() {
|
|
let c = Chrome {
|
|
lens: "lsp 2/2 · lint 4",
|
|
scroll: 5,
|
|
..Default::default()
|
|
};
|
|
let r = rows(&st(), &c, 100, 0);
|
|
let (a, b) = (text(r[0].clone()), text(r[1].clone()));
|
|
assert!(
|
|
a.starts_with("m1 · ctx ▱▱▱▱▱▱▱▱▱▱ 0%") && a.ends_with("↑5"),
|
|
"{a}"
|
|
);
|
|
assert_eq!(a.chars().count(), 100);
|
|
assert!(
|
|
b.starts_with(KEYS) && b.ends_with("lsp 2/2 · lint 4"),
|
|
"{b}"
|
|
);
|
|
// a hint replaces the key hints, the status row stays
|
|
let h = Chrome { hint: "saved", ..c };
|
|
let r = rows(&st(), &h, 100, 0);
|
|
assert!(text(r[1].clone()).starts_with("saved"));
|
|
// narrow: one row, hint on the right of the status
|
|
assert_eq!(rows(&st(), &h, 60, 0).len(), 1);
|
|
assert!(text(footer(&st(), &h, 60, 0)).ends_with("saved"));
|
|
assert_eq!(text(footer(&st(), &h, 10, 0)), "saved");
|
|
}
|
|
|
|
#[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 context_bar_fill_and_color() {
|
|
let mut s = st();
|
|
s.ctx_tokens = 135_000;
|
|
let l = footer(&s, &Chrome::default(), 140, 0);
|
|
let t = text(l.clone());
|
|
assert!(t.starts_with("m1 · ctx ▰▰▰▰▰▰▰▰▰▱ 90%"), "{t}");
|
|
assert_eq!(l.spans[1].style.fg, theme::t().err().fg);
|
|
}
|
|
}
|