Deepen Agent, compaction, switching and TUI modules
- Agent: make session/usage/provider/model/system/max_tokens/compact_at private; add set_provider, set_model, replace_session, fork, clear, fit_window. Fixes stale context-token reading after resume/new session. - hx-core::compact: ContextMeter, plan/apply and estimate_tokens split out of agent.rs, testable without provider or session. - hx-core::switch: Switcher shared by TUI and RPC for model/provider switches; RPC set_model now also refits the compaction threshold. - hx-tui: status.rs (footer, /usage as pure functions), popup.rs, and Picker::key returning an Act. - tests/tui_smoke.py: resolve the temp dir (macOS /var symlink) and match the resume via the OSC window title instead of split screen text.
This commit is contained in:
1 parent
fe308e0f36
commit
eaa6e22fbd
11 files changed
+1407
-632
No files matched your search
@@ -0,0 +1,348 @@
|
||||
//! 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>,
|
||||
}
|
||||
|
||||
/// `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 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(),
|
||||
)]);
|
||||
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 mut tail = vec![format!("{:?}", st.kind), st.model.clone()];
|
||||
if c.queued > 0 {
|
||||
tail.push(format!("{} queued", c.queued));
|
||||
}
|
||||
if c.scroll > 0 {
|
||||
tail.push(format!("↑{}", c.scroll));
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
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 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));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user