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
+169
-463
@@ -2,7 +2,9 @@
|
||||
|
||||
pub mod editor;
|
||||
pub mod picker;
|
||||
pub mod popup;
|
||||
pub mod sessions;
|
||||
pub mod status;
|
||||
pub mod theme;
|
||||
pub mod transcript;
|
||||
|
||||
@@ -11,11 +13,12 @@ use crossterm::event::{
|
||||
};
|
||||
use editor::{Action, Editor};
|
||||
use futures::StreamExt;
|
||||
use hx_ai::Usage;
|
||||
use hx_ai::auth::Kind;
|
||||
use hx_ai::{Provider, Usage};
|
||||
use hx_core::agent::{AbortHandle, Agent};
|
||||
use hx_core::command::{self as cmd, CmdSpec, Completion, Source};
|
||||
use hx_core::hook::{Event, Hook, HookAction};
|
||||
use hx_core::switch::Switcher;
|
||||
use ratatui::layout::{Constraint, Layout, Rect};
|
||||
use ratatui::style::Modifier;
|
||||
use ratatui::text::Line;
|
||||
@@ -27,12 +30,10 @@ use std::time::Instant;
|
||||
use tokio::sync::{Mutex, mpsc};
|
||||
use transcript::{Item, Transcript};
|
||||
|
||||
pub type MakeProvider = Box<dyn Fn(Kind) -> hx_ai::Result<Arc<dyn Provider>> + Send>;
|
||||
|
||||
pub struct Setup {
|
||||
pub agent: Agent,
|
||||
pub kind: Kind,
|
||||
pub make_provider: MakeProvider,
|
||||
/// Switches model and provider; also knows the current provider and the model catalog.
|
||||
pub switcher: Switcher,
|
||||
/// Pricing lookup for the footer; None = unknown.
|
||||
pub pricing: fn(&str) -> Option<hx_ai::Pricing>,
|
||||
/// `/lsp` status lines.
|
||||
@@ -44,11 +45,6 @@ pub struct Setup {
|
||||
pub specs: Vec<CmdSpec>,
|
||||
/// Open the session picker at startup (`hx -r`).
|
||||
pub open_sessions: bool,
|
||||
/// Model catalog of logged-in providers: `/provider` defaults, context windows.
|
||||
pub models: Vec<hx_ai::models::ModelInfo>,
|
||||
/// Re-derive the compaction threshold from the window when the model changes
|
||||
/// (false when `compact_at` is configured).
|
||||
pub auto_compact: bool,
|
||||
}
|
||||
|
||||
pub enum CmdOut {
|
||||
@@ -96,22 +92,17 @@ struct App {
|
||||
expanded: bool,
|
||||
busy: bool,
|
||||
queue: VecDeque<String>,
|
||||
kind: Kind,
|
||||
model: String,
|
||||
usage: Usage,
|
||||
ctx_tokens: usize,
|
||||
/// auto-compact threshold: the context bar's 100%
|
||||
ctx_max: usize,
|
||||
/// last subscription limits reported by the provider
|
||||
quota: Option<hx_ai::Quota>,
|
||||
pricing: fn(&str) -> Option<hx_ai::Pricing>,
|
||||
/// numbers the footer and `/usage` show
|
||||
st: status::Status,
|
||||
/// model/provider switching (`/model`, `/provider`)
|
||||
sw: Switcher,
|
||||
/// when the current run started (activity line)
|
||||
since: Instant,
|
||||
quit: bool,
|
||||
hint: String,
|
||||
specs: Vec<CmdSpec>,
|
||||
/// open completion popup and selected row
|
||||
popup: Option<(Completion, usize)>,
|
||||
popup: Option<popup::Popup>,
|
||||
picker: Option<picker::Picker>,
|
||||
sessions: Option<sessions::Sessions>,
|
||||
/// session title for footer / terminal title; None until the first prompt
|
||||
@@ -125,6 +116,22 @@ struct App {
|
||||
ask: Option<(String, tokio::sync::oneshot::Sender<bool>)>,
|
||||
}
|
||||
|
||||
impl App {
|
||||
/// Mirror a model/provider switch into what the footer shows.
|
||||
fn apply_switch(&mut self, sw: &hx_core::switch::Switched) {
|
||||
self.st.kind = sw.kind;
|
||||
self.st.model = sw.model.clone();
|
||||
if sw.provider_changed {
|
||||
self.st.quota = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// The context bar's 100% is the agent's compaction threshold.
|
||||
fn ctx_max_from(&mut self, a: &Agent) {
|
||||
self.st.ctx_max = a.compact_at();
|
||||
}
|
||||
}
|
||||
|
||||
const KEYS: &str = "enter send · alt-enter/ctrl-j newline · esc/ctrl-c abort · ctrl-o expand · pgup/pgdn scroll · \
|
||||
tab complete @file / command";
|
||||
const PLACEHOLDER: &str = "/ commands · @ files · ctrl-p picker · /help keys";
|
||||
@@ -164,15 +171,12 @@ fn expand_mentions(s: &str, root: &std::path::Path) -> String {
|
||||
pub async fn run(setup: Setup) -> std::io::Result<()> {
|
||||
let Setup {
|
||||
mut agent,
|
||||
kind,
|
||||
make_provider,
|
||||
switcher,
|
||||
pricing,
|
||||
lsp_status,
|
||||
commands,
|
||||
specs,
|
||||
open_sessions,
|
||||
models,
|
||||
auto_compact,
|
||||
} = setup;
|
||||
let (tx, mut rx) = mpsc::unbounded_channel();
|
||||
agent.bus.add(Forward(tx.clone()));
|
||||
@@ -198,13 +202,16 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
||||
expanded: false,
|
||||
busy: false,
|
||||
queue: VecDeque::new(),
|
||||
kind,
|
||||
model: agent.model.clone(),
|
||||
usage: Usage::default(),
|
||||
ctx_tokens: hx_core::agent::estimate_tokens(&agent.session.messages()),
|
||||
ctx_max: agent.compact_at,
|
||||
quota: None,
|
||||
pricing,
|
||||
st: status::Status {
|
||||
kind: switcher.kind(),
|
||||
model: agent.model().to_string(),
|
||||
usage: Usage::default(),
|
||||
ctx_tokens: hx_core::compact::estimate_tokens(&agent.session().messages()),
|
||||
ctx_max: agent.compact_at(),
|
||||
quota: None,
|
||||
pricing,
|
||||
},
|
||||
sw: switcher,
|
||||
since: Instant::now(),
|
||||
quit: false,
|
||||
hint: String::new(),
|
||||
@@ -212,26 +219,25 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
||||
popup: None,
|
||||
picker: None,
|
||||
sessions: None,
|
||||
title: hx_core::session::title(&agent.session.messages()),
|
||||
title: hx_core::session::title(&agent.session().messages()),
|
||||
panel: None,
|
||||
session_path: agent.session.path().to_path_buf(),
|
||||
session_path: agent.session().path().to_path_buf(),
|
||||
wide: false,
|
||||
ask: None,
|
||||
};
|
||||
sessions::history(&mut app.t, &agent.session.messages());
|
||||
sessions::history(&mut app.t, &agent.session().messages());
|
||||
if open_sessions {
|
||||
open_sessions_picker(&mut app);
|
||||
}
|
||||
app.t
|
||||
.push(Item::Info(format!("hx · {:?} · {}", app.kind, app.model)));
|
||||
app.t.push(Item::Info(format!(
|
||||
"hx · {:?} · {}",
|
||||
app.st.kind, app.st.model
|
||||
)));
|
||||
let agent = Arc::new(Mutex::new(agent));
|
||||
|
||||
let ctx = Ctx {
|
||||
agent: &agent,
|
||||
tx: &tx,
|
||||
make_provider: &make_provider,
|
||||
models: &models,
|
||||
auto_compact,
|
||||
cwd: &cwd,
|
||||
lsp_status: &lsp_status,
|
||||
commands: &commands,
|
||||
@@ -285,11 +291,11 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
||||
Ui::Ask(q, reply) => app.ask = Some((q, reply)),
|
||||
Ui::Ev(e) => {
|
||||
if let Event::Stream(hx_ai::StreamEvent::Quota(q)) = &e {
|
||||
app.quota = Some(q.clone());
|
||||
app.st.quota = Some(q.clone());
|
||||
}
|
||||
if let Event::Stream(hx_ai::StreamEvent::Done { usage, .. }) = &e {
|
||||
app.usage.add(usage);
|
||||
app.ctx_tokens = (usage.input_tokens + usage.cache_read_tokens + usage.cache_write_tokens + usage.output_tokens) as usize;
|
||||
app.st.usage.add(usage);
|
||||
app.st.ctx_tokens = (usage.input_tokens + usage.cache_read_tokens + usage.cache_write_tokens + usage.output_tokens) as usize;
|
||||
}
|
||||
app.t.apply(&e);
|
||||
}
|
||||
@@ -311,7 +317,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
||||
Ok(false) => Item::Info("nothing to compact".into()),
|
||||
Err(e) => Item::Error(e),
|
||||
});
|
||||
app.ctx_tokens = hx_core::agent::estimate_tokens(&agent.lock().await.session.messages());
|
||||
app.st.ctx_tokens = hx_core::compact::estimate_tokens(&agent.lock().await.session().messages());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -320,14 +326,14 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
||||
}
|
||||
ratatui::restore();
|
||||
let a = agent.lock().await;
|
||||
let cost = pricing(&a.model)
|
||||
.map(|p| format!(" ${:.4}", app.usage.cost(&p)))
|
||||
let cost = pricing(a.model())
|
||||
.map(|p| format!(" ${:.4}", app.st.usage.cost(&p)))
|
||||
.unwrap_or_default();
|
||||
eprintln!(
|
||||
"[{} in / {} out tokens{cost}; session {}]",
|
||||
app.usage.input_tokens + app.usage.cache_read_tokens,
|
||||
app.usage.output_tokens,
|
||||
a.session.path().display()
|
||||
app.st.usage.input_tokens + app.st.usage.cache_read_tokens,
|
||||
app.st.usage.output_tokens,
|
||||
a.session().path().display()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -367,45 +373,32 @@ fn switch_session(app: &mut App, a: &mut Agent, sess: hx_core::session::Session)
|
||||
app.t = Transcript::default();
|
||||
let msgs = sess.messages();
|
||||
sessions::history(&mut app.t, &msgs);
|
||||
app.ctx_tokens = hx_core::agent::estimate_tokens(&msgs);
|
||||
app.st.ctx_tokens = hx_core::compact::estimate_tokens(&msgs);
|
||||
app.title = hx_core::session::title(&msgs);
|
||||
app.session_path = sess.path().to_path_buf();
|
||||
a.session = sess;
|
||||
a.replace_session(sess);
|
||||
}
|
||||
|
||||
/// Picker keys. Returns a line to submit when an entry runs.
|
||||
fn picker_key(app: &mut App, k: KeyEvent) -> Option<String> {
|
||||
let p = app.picker.as_mut()?;
|
||||
match k.code {
|
||||
KeyCode::Esc => app.picker = None,
|
||||
KeyCode::Char('c' | 'p') if k.modifiers.contains(KeyModifiers::CONTROL) => {
|
||||
app.picker = None
|
||||
}
|
||||
KeyCode::Up => p.move_sel(-1),
|
||||
KeyCode::Down | KeyCode::Tab => p.move_sel(1),
|
||||
KeyCode::Backspace => {
|
||||
p.query.pop();
|
||||
p.sel = 0;
|
||||
}
|
||||
KeyCode::Char(c) => {
|
||||
p.query.push(c);
|
||||
p.sel = 0;
|
||||
}
|
||||
KeyCode::Enter => {
|
||||
let pick = p.selected();
|
||||
match app.picker.as_mut()?.key(k) {
|
||||
picker::Act::None => None,
|
||||
picker::Act::Close => {
|
||||
app.picker = None;
|
||||
match pick? {
|
||||
picker::Pick::Run(l) => return Some(l),
|
||||
picker::Pick::Insert(l) => {
|
||||
app.ed.buf = l;
|
||||
app.ed.cur = app.ed.buf.len();
|
||||
live_popup(app);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
picker::Act::Run(l) => {
|
||||
app.picker = None;
|
||||
Some(l)
|
||||
}
|
||||
picker::Act::Insert(l) => {
|
||||
app.picker = None;
|
||||
app.ed.buf = l;
|
||||
app.ed.cur = app.ed.buf.len();
|
||||
live_popup(app);
|
||||
None
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Show a listing: right panel on wide terminals, transcript otherwise.
|
||||
@@ -438,36 +431,18 @@ fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option<String> {
|
||||
));
|
||||
return None;
|
||||
}
|
||||
if let Some((c, sel)) = &mut app.popup {
|
||||
let n = c.items.len();
|
||||
match k.code {
|
||||
KeyCode::Up => {
|
||||
*sel = (*sel + n - 1) % n;
|
||||
return None;
|
||||
}
|
||||
KeyCode::Down => {
|
||||
*sel = (*sel + 1) % n;
|
||||
return None;
|
||||
}
|
||||
KeyCode::Esc => {
|
||||
if let Some(p) = &mut app.popup {
|
||||
match p.key(k, &app.ed.buf, app.ed.cur) {
|
||||
popup::Act::Consumed => return None,
|
||||
popup::Act::Close => {
|
||||
app.popup = None;
|
||||
return None;
|
||||
}
|
||||
KeyCode::Tab => {
|
||||
popup::Act::Accept => {
|
||||
accept(app);
|
||||
return None;
|
||||
}
|
||||
// Enter accepts a partly typed token; on an empty or complete one it submits
|
||||
KeyCode::Enter
|
||||
if !alt
|
||||
&& !shift
|
||||
&& !matches!(&app.ed.buf[c.start..app.ed.cur], "" | "/" | "@")
|
||||
&& app.ed.buf[c.start..app.ed.cur] != c.items[*sel].label =>
|
||||
{
|
||||
accept(app);
|
||||
return None;
|
||||
}
|
||||
_ => app.popup = None,
|
||||
popup::Act::Pass => app.popup = None,
|
||||
}
|
||||
}
|
||||
match k.code {
|
||||
@@ -532,7 +507,7 @@ fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option<String> {
|
||||
if pre.len() > app.ed.cur - c.start {
|
||||
app.ed.replace(c.start, &pre);
|
||||
}
|
||||
app.popup = Some((completion(app), 0));
|
||||
app.popup = popup::Popup::new(completion(app));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -552,34 +527,23 @@ fn live_popup(app: &mut App) {
|
||||
return;
|
||||
}
|
||||
let c = completion(app);
|
||||
if !c.items.is_empty() && !app.ed.buf[c.start..app.ed.cur].starts_with('@') {
|
||||
app.popup = Some((c, 0));
|
||||
if !app.ed.buf[c.start..app.ed.cur].starts_with('@') {
|
||||
app.popup = popup::Popup::new(c);
|
||||
}
|
||||
}
|
||||
|
||||
fn accept(app: &mut App) {
|
||||
if let Some((c, sel)) = app.popup.take() {
|
||||
app.ed.replace(c.start, &format!("{} ", c.items[sel].label));
|
||||
if let Some(p) = app.popup.take() {
|
||||
app.ed
|
||||
.replace(p.comp.start, &format!("{} ", p.selected_label()));
|
||||
live_popup(app);
|
||||
}
|
||||
}
|
||||
|
||||
/// Context bar max and (unless configured) the compaction threshold follow the model's window.
|
||||
fn set_window(app: &mut App, a: &mut Agent, models: &[hx_ai::models::ModelInfo], auto: bool) {
|
||||
let w = hx_ai::models::window(models, &a.model);
|
||||
if auto {
|
||||
a.compact_at = hx_ai::models::compact_threshold(w, a.max_tokens);
|
||||
}
|
||||
app.ctx_max = a.compact_at;
|
||||
}
|
||||
|
||||
/// Everything `submit` needs besides the app state.
|
||||
struct Ctx<'a> {
|
||||
agent: &'a Arc<Mutex<Agent>>,
|
||||
tx: &'a mpsc::UnboundedSender<Ui>,
|
||||
make_provider: &'a MakeProvider,
|
||||
models: &'a [hx_ai::models::ModelInfo],
|
||||
auto_compact: bool,
|
||||
cwd: &'a std::path::Path,
|
||||
lsp_status: &'a LspStatus,
|
||||
commands: &'a Commands,
|
||||
@@ -589,9 +553,6 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
|
||||
let Ctx {
|
||||
agent,
|
||||
tx,
|
||||
make_provider,
|
||||
models,
|
||||
auto_compact,
|
||||
cwd,
|
||||
lsp_status,
|
||||
commands,
|
||||
@@ -613,7 +574,7 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
|
||||
show(app, "help", h);
|
||||
}
|
||||
"usage" => {
|
||||
let r = usage_report(app, now_secs());
|
||||
let r = status::report(&app.st, status::now_secs());
|
||||
show(app, "usage", r);
|
||||
}
|
||||
"skills" => {
|
||||
@@ -648,49 +609,37 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
|
||||
Err(e) => app.t.push(Item::Error(format!("/new: {e}"))),
|
||||
}
|
||||
}
|
||||
"model" if arg.is_empty() => app.t.push(Item::Info(format!("model: {}", app.model))),
|
||||
"model" if arg.is_empty() => app.t.push(Item::Info(format!("model: {}", app.st.model))),
|
||||
"model" => {
|
||||
// a model belongs to one provider: switch provider with it
|
||||
let k = hx_ai::models::kind_of(models, arg).unwrap_or(app.kind);
|
||||
let p = if k == app.kind {
|
||||
Ok(None)
|
||||
} else {
|
||||
make_provider(k).map(Some).map_err(|e| e.to_string())
|
||||
};
|
||||
match p {
|
||||
Ok(p) => {
|
||||
let mut a = agent.lock().await;
|
||||
if let Some(p) = p {
|
||||
a.provider = p;
|
||||
app.kind = k;
|
||||
app.quota = None;
|
||||
}
|
||||
a.model = arg.into();
|
||||
set_window(app, &mut a, models, auto_compact);
|
||||
app.model = arg.into();
|
||||
let mut a = agent.lock().await;
|
||||
match app.sw.set_model(&mut a, arg) {
|
||||
Ok(sw) => {
|
||||
app.apply_switch(&sw);
|
||||
app.ctx_max_from(&a);
|
||||
app.t.push(Item::Info(format!(
|
||||
"model → {arg} ({k:?}) · context {}k",
|
||||
hx_ai::models::window(models, arg) / 1000
|
||||
"model → {} ({:?}) · context {}k",
|
||||
sw.model,
|
||||
sw.kind,
|
||||
sw.window / 1000
|
||||
)));
|
||||
}
|
||||
Err(e) => app.t.push(Item::Error(format!("/model {arg}: {e}"))),
|
||||
}
|
||||
}
|
||||
"provider" => match arg
|
||||
.parse::<Kind>()
|
||||
.map_err(|e| e.to_string())
|
||||
.and_then(|k| make_provider(k).map(|p| (k, p)).map_err(|e| e.to_string()))
|
||||
{
|
||||
Ok((k, p)) => {
|
||||
"provider" => match arg.parse::<Kind>().map_err(|e| e.to_string()) {
|
||||
Ok(k) => {
|
||||
let mut a = agent.lock().await;
|
||||
a.provider = p;
|
||||
a.model = hx_ai::models::default_for(k, models);
|
||||
set_window(app, &mut a, models, auto_compact);
|
||||
app.quota = None;
|
||||
app.kind = k;
|
||||
app.model = a.model.clone();
|
||||
app.t
|
||||
.push(Item::Info(format!("provider → {k:?} ({})", app.model)));
|
||||
match app.sw.set_provider(&mut a, k) {
|
||||
Ok(sw) => {
|
||||
app.apply_switch(&sw);
|
||||
app.ctx_max_from(&a);
|
||||
app.t.push(Item::Info(format!(
|
||||
"provider → {:?} ({})",
|
||||
sw.kind, sw.model
|
||||
)));
|
||||
}
|
||||
Err(e) => app.t.push(Item::Error(e)),
|
||||
}
|
||||
}
|
||||
Err(e) => app.t.push(Item::Error(e)),
|
||||
},
|
||||
@@ -772,7 +721,7 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
|
||||
+ 2;
|
||||
let act_h = u16::from(app.busy);
|
||||
app.wide = f.area().width >= WIDE;
|
||||
let [main, act, input, status] = Layout::vertical([
|
||||
let [main, act, input, status_row] = Layout::vertical([
|
||||
Constraint::Min(3),
|
||||
Constraint::Length(act_h),
|
||||
Constraint::Length(input_h),
|
||||
@@ -831,8 +780,18 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
|
||||
} else {
|
||||
f.render_widget(Paragraph::new(app.ed.buf.as_str()).scroll((skip, 0)), text);
|
||||
}
|
||||
f.render_widget(footer(app, status.width), status);
|
||||
if let Some((comp, sel)) = &app.popup {
|
||||
let chrome = status::Chrome {
|
||||
ask: app.ask.as_ref().map(|(q, _)| q.as_str()),
|
||||
hint: &app.hint,
|
||||
queued: app.queue.len(),
|
||||
scroll: app.scroll,
|
||||
title: app.title.as_deref(),
|
||||
};
|
||||
f.render_widget(
|
||||
status::footer(&app.st, &chrome, status_row.width, status::now_secs()),
|
||||
status_row,
|
||||
);
|
||||
if let Some(popup::Popup { comp, sel }) = &app.popup {
|
||||
let col = Span::raw(
|
||||
&app.ed.buf[app.ed.buf[..comp.start].rfind('\n').map_or(0, |i| i + 1)..comp.start],
|
||||
)
|
||||
@@ -848,182 +807,6 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
|
||||
}
|
||||
}
|
||||
|
||||
/// `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.
|
||||
fn footer(app: &App, width: u16) -> Line<'static> {
|
||||
let th = theme::t();
|
||||
if let Some((q, _)) = &app.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 = app.ctx_tokens as f64 / app.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 app.quota {
|
||||
Some(_) => String::new(),
|
||||
None => (app.pricing)(&app.model)
|
||||
.map(|p| format!(" ~${:.2}", app.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", app.ctx_tokens / 1000, app.ctx_max / 1000),
|
||||
th.dim(),
|
||||
),
|
||||
];
|
||||
if let Some(q) = &app.quota {
|
||||
left.extend(quota_spans(q, now_secs()));
|
||||
}
|
||||
left.extend([Span::styled(
|
||||
format!(
|
||||
" · {}↑ {}↓{cost}",
|
||||
k(app.usage.input_tokens + app.usage.cache_read_tokens),
|
||||
k(app.usage.output_tokens)
|
||||
),
|
||||
th.dim(),
|
||||
)]);
|
||||
let w = width as usize;
|
||||
let lw = |l: &[Span]| l.iter().map(Span::width).sum::<usize>();
|
||||
if !app.hint.is_empty() {
|
||||
let right = Span::styled(app.hint.clone(), 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!("{:?}", app.kind), app.model.clone()];
|
||||
if !app.queue.is_empty() {
|
||||
tail.push(format!("{} queued", app.queue.len()));
|
||||
}
|
||||
if app.scroll > 0 {
|
||||
tail.push(format!("↑{}", app.scroll));
|
||||
}
|
||||
let title = app.title.as_deref().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 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.
|
||||
fn usage_report(app: &App, now: u64) -> String {
|
||||
let mut out = vec![format!("{:?} · {}", app.kind, app.model)];
|
||||
match &app.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",
|
||||
app.ctx_tokens / 1000,
|
||||
app.ctx_max / 1000
|
||||
));
|
||||
out.push(format!(
|
||||
"session tokens: {} in, {} out",
|
||||
app.usage.input_tokens + app.usage.cache_read_tokens,
|
||||
app.usage.output_tokens
|
||||
));
|
||||
out.join("\n")
|
||||
}
|
||||
|
||||
/// `/skills`: each skill with its file, then the searched dirs (so a missing skill is easy to debug).
|
||||
fn skills_list(specs: &[CmdSpec], dirs: &[std::path::PathBuf]) -> String {
|
||||
let sk: Vec<String> = specs
|
||||
@@ -1090,6 +873,8 @@ fn draw_popup(f: &mut ratatui::Frame, c: &Completion, sel: usize, x: u16, bottom
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use hx_ai::Provider;
|
||||
use hx_core::switch::MakeProvider;
|
||||
use ratatui::backend::TestBackend;
|
||||
|
||||
#[test]
|
||||
@@ -1104,34 +889,10 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn draw_snapshot() {
|
||||
let mut app = App {
|
||||
t: Transcript::default(),
|
||||
ed: Editor::default(),
|
||||
files: vec![],
|
||||
scroll: 0,
|
||||
expanded: false,
|
||||
busy: false,
|
||||
queue: VecDeque::new(),
|
||||
kind: Kind::Claude,
|
||||
model: "m1".into(),
|
||||
usage: Usage::default(),
|
||||
ctx_tokens: 12_000,
|
||||
ctx_max: 150_000,
|
||||
quota: None,
|
||||
pricing: |_| None,
|
||||
since: Instant::now(),
|
||||
quit: false,
|
||||
hint: String::new(),
|
||||
specs: vec![],
|
||||
popup: None,
|
||||
picker: None,
|
||||
sessions: None,
|
||||
title: None,
|
||||
panel: None,
|
||||
session_path: "/nonexistent/s.jsonl".into(),
|
||||
wide: false,
|
||||
ask: None,
|
||||
};
|
||||
let mut app = test_app();
|
||||
app.files = vec![];
|
||||
app.specs = vec![];
|
||||
app.st.ctx_tokens = 12_000;
|
||||
app.t.push(Item::User("hello".into()));
|
||||
app.t.push(Item::Assistant("hi **there**".into()));
|
||||
app.ed.insert("typing");
|
||||
@@ -1166,16 +927,24 @@ mod tests {
|
||||
expanded: false,
|
||||
busy: false,
|
||||
queue: VecDeque::new(),
|
||||
kind: Kind::Claude,
|
||||
model: "m1".into(),
|
||||
usage: Usage::default(),
|
||||
ctx_tokens: 0,
|
||||
ctx_max: 150_000,
|
||||
quota: None,
|
||||
pricing: |_| None,
|
||||
st: status::Status {
|
||||
kind: Kind::Claude,
|
||||
model: "m1".into(),
|
||||
usage: Usage::default(),
|
||||
ctx_tokens: 0,
|
||||
ctx_max: 150_000,
|
||||
quota: None,
|
||||
pricing: |_| None,
|
||||
},
|
||||
since: Instant::now(),
|
||||
quit: false,
|
||||
hint: String::new(),
|
||||
sw: Switcher::new(
|
||||
Kind::Claude,
|
||||
vec![],
|
||||
Box::new(|_| Ok(Arc::new(NoProvider))),
|
||||
true,
|
||||
),
|
||||
specs: cmd::builtins(&["sonnet", "opus"]),
|
||||
popup: None,
|
||||
picker: None,
|
||||
@@ -1212,7 +981,7 @@ mod tests {
|
||||
key(&mut app, KeyCode::Char(c));
|
||||
}
|
||||
let labels = |a: &App| {
|
||||
a.popup.as_ref().map(|(c, s)| {
|
||||
a.popup.as_ref().map(|popup::Popup { comp: c, sel: s }| {
|
||||
(
|
||||
c.items.iter().map(|i| i.label.clone()).collect::<Vec<_>>(),
|
||||
*s,
|
||||
@@ -1381,15 +1150,11 @@ mod tests {
|
||||
);
|
||||
let agent = Arc::new(Mutex::new(agent));
|
||||
let (tx, _rx) = mpsc::unbounded_channel();
|
||||
let mp: MakeProvider = Box::new(|_| Ok(Arc::new(NoProvider)));
|
||||
let ls: LspStatus = Box::new(|| Box::pin(async { vec![] }));
|
||||
let cmds: Commands = Box::new(|_, _| None);
|
||||
let ctx = Ctx {
|
||||
agent: &agent,
|
||||
tx: &tx,
|
||||
make_provider: &mp,
|
||||
models: &[],
|
||||
auto_compact: true,
|
||||
cwd: t.path(),
|
||||
lsp_status: &ls,
|
||||
commands: &cmds,
|
||||
@@ -1398,7 +1163,7 @@ mod tests {
|
||||
app.session_path = old.clone();
|
||||
app.title = Some("first".into());
|
||||
submit(&mut app, "/clear".into(), &ctx).await;
|
||||
let new = agent.lock().await.session.path().to_path_buf();
|
||||
let new = agent.lock().await.session().path().to_path_buf();
|
||||
assert_ne!(new, old);
|
||||
assert_eq!((new.parent(), app.title.as_deref()), (old.parent(), None));
|
||||
assert_eq!(
|
||||
@@ -1406,77 +1171,21 @@ mod tests {
|
||||
before,
|
||||
"old file untouched"
|
||||
);
|
||||
agent
|
||||
.lock()
|
||||
.await
|
||||
.session
|
||||
// a second handle on the same file: the agent's session is read-only from outside
|
||||
hx_core::session::Session::open(&new)
|
||||
.unwrap()
|
||||
.append(hx_ai::Message::user("second"))
|
||||
.unwrap();
|
||||
let l = hx_core::session::list(t.path());
|
||||
assert_eq!(l.len(), 2);
|
||||
assert_eq!(l[0].path, new, "newest first, so `hx -c` picks it");
|
||||
submit(&mut app, format!("/resume {}", old.display()), &ctx).await;
|
||||
assert_eq!(agent.lock().await.session.path(), old);
|
||||
assert_eq!(agent.lock().await.session().path(), old);
|
||||
assert_eq!(app.title.as_deref(), Some("first"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quota_footer_and_usage() {
|
||||
let q = 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()),
|
||||
};
|
||||
let text: String = quota_spans(&q, 10_000)
|
||||
.iter()
|
||||
.map(|s| s.content.to_string())
|
||||
.collect();
|
||||
assert_eq!(text, " · 5h 42% ↻2h13m · week 91% ↻3d4h · credits: 37.5");
|
||||
assert_eq!(
|
||||
quota_spans(&q, 10_000)[3].style.fg,
|
||||
Some(ratatui::style::Color::Red)
|
||||
);
|
||||
let mut app = test_app();
|
||||
assert!(usage_report(&app, 10_000).contains("not reported yet"));
|
||||
app.quota = Some(q);
|
||||
let r = usage_report(&app, 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}"
|
||||
);
|
||||
// quota replaces the $ estimate in the footer
|
||||
app.pricing = |_| Some(hx_ai::Pricing::default());
|
||||
let line: String = footer(&app, 140)
|
||||
.spans
|
||||
.iter()
|
||||
.map(|s| s.content.to_string())
|
||||
.collect();
|
||||
assert!(line.contains("5h 42%") && !line.contains('$'), "{line}");
|
||||
assert_eq!(until(10_030, 10_000), "1m");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn model_switch_follows_provider() {
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
static CODEX_CALLS: AtomicUsize = AtomicUsize::new(0);
|
||||
async fn model_switch_shows_in_footer_state() {
|
||||
let t = tempfile::tempdir().unwrap();
|
||||
let (agent, _) = Agent::new(
|
||||
Arc::new(NoProvider),
|
||||
@@ -1493,45 +1202,42 @@ mod tests {
|
||||
models.extend(hx_ai::models::fallback(Kind::Codex));
|
||||
let ls: LspStatus = Box::new(|| Box::pin(async { vec![] }));
|
||||
let cmds: Commands = Box::new(|_, _| None);
|
||||
let mut app = test_app();
|
||||
app.kind = Kind::Claude;
|
||||
|
||||
// codex not logged in: error, nothing changes
|
||||
let fail: MakeProvider =
|
||||
Box::new(|_| Err(hx_ai::Error::Http("not logged in to Codex".into())));
|
||||
let ctx = Ctx {
|
||||
agent: &agent,
|
||||
tx: &tx,
|
||||
make_provider: &fail,
|
||||
models: &models,
|
||||
auto_compact: true,
|
||||
cwd: t.path(),
|
||||
lsp_status: &ls,
|
||||
commands: &cmds,
|
||||
};
|
||||
let mut app = test_app();
|
||||
let fail: MakeProvider =
|
||||
Box::new(|_| Err(hx_ai::Error::Http("not logged in to Codex".into())));
|
||||
app.sw = Switcher::new(Kind::Claude, models.clone(), fail, true);
|
||||
|
||||
// codex not logged in: error shown, footer state unchanged
|
||||
submit(&mut app, "/model gpt-5.6-terra".into(), &ctx).await;
|
||||
assert_eq!((app.kind, app.model.as_str()), (Kind::Claude, "m1"));
|
||||
assert_eq!((app.st.kind, app.st.model.as_str()), (Kind::Claude, "m1"));
|
||||
assert!(matches!(app.t.items.last(), Some(Item::Error(e)) if e.contains("not logged in")));
|
||||
|
||||
let ok: MakeProvider = Box::new(|k| {
|
||||
assert_eq!(k, Kind::Codex);
|
||||
CODEX_CALLS.fetch_add(1, Ordering::SeqCst);
|
||||
Ok(Arc::new(NoProvider))
|
||||
});
|
||||
let ctx = Ctx {
|
||||
make_provider: &ok,
|
||||
..ctx
|
||||
};
|
||||
app.sw = Switcher::new(
|
||||
Kind::Claude,
|
||||
models,
|
||||
Box::new(|_| Ok(Arc::new(NoProvider))),
|
||||
true,
|
||||
);
|
||||
app.st.quota = Some(Default::default());
|
||||
submit(&mut app, "/model gpt-5.6-terra".into(), &ctx).await;
|
||||
assert_eq!(
|
||||
(app.kind, app.model.as_str()),
|
||||
(app.st.kind, app.st.model.as_str()),
|
||||
(Kind::Codex, "gpt-5.6-terra")
|
||||
);
|
||||
assert_eq!(agent.lock().await.model, "gpt-5.6-terra");
|
||||
assert_eq!(CODEX_CALLS.load(Ordering::SeqCst), 1);
|
||||
// same provider: no new client
|
||||
assert!(app.st.quota.is_none(), "quota belongs to the old provider");
|
||||
assert_eq!(agent.lock().await.model(), "gpt-5.6-terra");
|
||||
assert_eq!(app.st.ctx_max, agent.lock().await.compact_at());
|
||||
// same provider: quota survives
|
||||
app.st.quota = Some(Default::default());
|
||||
submit(&mut app, "/model gpt-5.6-luna".into(), &ctx).await;
|
||||
assert_eq!(CODEX_CALLS.load(Ordering::SeqCst), 1);
|
||||
assert!(app.st.quota.is_some());
|
||||
}
|
||||
|
||||
struct NoProvider;
|
||||
|
||||
@@ -22,10 +22,22 @@ pub struct Entry {
|
||||
pub pick: Pick,
|
||||
}
|
||||
|
||||
/// What a key press asks the app to do with the picker.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Act {
|
||||
None,
|
||||
/// Dismiss the picker.
|
||||
Close,
|
||||
/// Dismiss the picker and submit this line.
|
||||
Run(String),
|
||||
/// Dismiss the picker and put this into the editor.
|
||||
Insert(String),
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Picker {
|
||||
pub query: String,
|
||||
pub sel: usize,
|
||||
query: String,
|
||||
sel: usize,
|
||||
all: Vec<Entry>,
|
||||
}
|
||||
|
||||
@@ -79,11 +91,40 @@ impl Picker {
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn selected(&self) -> Option<Pick> {
|
||||
/// Edit the query, move the selection, or pick; everything else is ignored.
|
||||
pub fn key(&mut self, k: crossterm::event::KeyEvent) -> Act {
|
||||
use crossterm::event::{KeyCode, KeyModifiers};
|
||||
let ctrl = k.modifiers.contains(KeyModifiers::CONTROL);
|
||||
match k.code {
|
||||
KeyCode::Esc => return Act::Close,
|
||||
KeyCode::Char('c' | 'p') if ctrl => return Act::Close,
|
||||
KeyCode::Up => self.move_sel(-1),
|
||||
KeyCode::Down | KeyCode::Tab => self.move_sel(1),
|
||||
KeyCode::Backspace => {
|
||||
self.query.pop();
|
||||
self.sel = 0;
|
||||
}
|
||||
KeyCode::Char(c) => {
|
||||
self.query.push(c);
|
||||
self.sel = 0;
|
||||
}
|
||||
KeyCode::Enter => {
|
||||
return match self.selected() {
|
||||
Some(Pick::Run(l)) => Act::Run(l),
|
||||
Some(Pick::Insert(l)) => Act::Insert(l),
|
||||
None => Act::Close,
|
||||
};
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Act::None
|
||||
}
|
||||
|
||||
fn selected(&self) -> Option<Pick> {
|
||||
self.matches().get(self.sel).map(|e| e.pick.clone())
|
||||
}
|
||||
|
||||
pub fn move_sel(&mut self, d: isize) {
|
||||
fn move_sel(&mut self, d: isize) {
|
||||
let n = self.matches().len().max(1) as isize;
|
||||
self.sel = (self.sel as isize + d).rem_euclid(n) as usize;
|
||||
}
|
||||
@@ -207,4 +248,49 @@ mod tests {
|
||||
p.move_sel(-1);
|
||||
assert_eq!(p.sel, p.matches().len() - 1, "wraps to the end");
|
||||
}
|
||||
|
||||
fn press(code: crossterm::event::KeyCode) -> crossterm::event::KeyEvent {
|
||||
crossterm::event::KeyEvent::new(code, crossterm::event::KeyModifiers::NONE)
|
||||
}
|
||||
|
||||
fn type_str(p: &mut Picker, s: &str) {
|
||||
for c in s.chars() {
|
||||
assert_eq!(p.key(press(crossterm::event::KeyCode::Char(c))), Act::None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keys_filter_move_and_pick() {
|
||||
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
||||
let t = tempfile::tempdir().unwrap();
|
||||
let mut p = Picker::new(
|
||||
&cmd::builtins(&["opus", "sonnet"]),
|
||||
t.path(),
|
||||
&t.path().join("x"),
|
||||
);
|
||||
// a command without args runs, one with args goes to the editor
|
||||
type_str(&mut p, "comp");
|
||||
assert_eq!(p.key(press(KeyCode::Enter)), Act::Run("/compact".into()));
|
||||
p.key(press(KeyCode::Backspace));
|
||||
p.key(press(KeyCode::Backspace));
|
||||
p.key(press(KeyCode::Backspace));
|
||||
p.key(press(KeyCode::Backspace));
|
||||
type_str(&mut p, "/model");
|
||||
assert_eq!(p.key(press(KeyCode::Enter)), Act::Insert("/model ".into()));
|
||||
// typing resets the selection; down moves it
|
||||
for _ in 0..6 {
|
||||
p.key(press(KeyCode::Backspace));
|
||||
}
|
||||
p.key(press(KeyCode::Down));
|
||||
assert_eq!(p.sel, 1);
|
||||
type_str(&mut p, "m");
|
||||
assert_eq!(p.sel, 0);
|
||||
// no match: enter just closes
|
||||
type_str(&mut p, "zzzzzz");
|
||||
assert_eq!(p.key(press(KeyCode::Enter)), Act::Close);
|
||||
assert_eq!(p.key(press(KeyCode::Esc)), Act::Close);
|
||||
let ctrl = |c| KeyEvent::new(KeyCode::Char(c), KeyModifiers::CONTROL);
|
||||
assert_eq!(p.key(ctrl('p')), Act::Close);
|
||||
assert_eq!(p.key(ctrl('c')), Act::Close);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
//! Completion popup state and its keys: a [`Completion`] plus the selected row.
|
||||
|
||||
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
||||
use hx_core::command::Completion;
|
||||
|
||||
/// What the app should do after a key reached the popup.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum Act {
|
||||
/// The popup used the key (moved the selection).
|
||||
Consumed,
|
||||
/// Close the popup; the key is spent.
|
||||
Close,
|
||||
/// Insert the selected candidate into the editor.
|
||||
Accept,
|
||||
/// Not a popup key: the popup closes and the key goes to the editor as usual.
|
||||
Pass,
|
||||
}
|
||||
|
||||
pub struct Popup {
|
||||
pub comp: Completion,
|
||||
pub sel: usize,
|
||||
}
|
||||
|
||||
impl Popup {
|
||||
/// `None` when there is nothing to offer.
|
||||
pub fn new(comp: Completion) -> Option<Self> {
|
||||
(!comp.items.is_empty()).then_some(Self { comp, sel: 0 })
|
||||
}
|
||||
|
||||
pub fn selected_label(&self) -> &str {
|
||||
&self.comp.items[self.sel].label
|
||||
}
|
||||
|
||||
/// `buf`/`cur` are the editor line and cursor: Enter accepts a partly typed token,
|
||||
/// but on an empty or already complete one it passes through and submits.
|
||||
pub fn key(&mut self, k: KeyEvent, buf: &str, cur: usize) -> Act {
|
||||
let n = self.comp.items.len();
|
||||
match k.code {
|
||||
KeyCode::Up => self.sel = (self.sel + n - 1) % n,
|
||||
KeyCode::Down => self.sel = (self.sel + 1) % n,
|
||||
KeyCode::Esc => return Act::Close,
|
||||
KeyCode::Tab => return Act::Accept,
|
||||
KeyCode::Enter
|
||||
if !k
|
||||
.modifiers
|
||||
.intersects(KeyModifiers::ALT | KeyModifiers::SHIFT)
|
||||
&& !matches!(&buf[self.comp.start..cur], "" | "/" | "@")
|
||||
&& buf[self.comp.start..cur] != *self.selected_label() =>
|
||||
{
|
||||
return Act::Accept;
|
||||
}
|
||||
_ => return Act::Pass,
|
||||
}
|
||||
Act::Consumed
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use hx_core::command::Candidate;
|
||||
|
||||
fn pop() -> Popup {
|
||||
let item = |l: &str| Candidate {
|
||||
label: l.into(),
|
||||
detail: String::new(),
|
||||
};
|
||||
Popup::new(Completion {
|
||||
start: 0,
|
||||
items: vec![item("/clear"), item("/compact")],
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn press(code: KeyCode) -> KeyEvent {
|
||||
KeyEvent::new(code, KeyModifiers::NONE)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_completion_has_no_popup() {
|
||||
assert!(Popup::new(Completion::default()).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrows_wrap() {
|
||||
let mut p = pop();
|
||||
assert_eq!(p.key(press(KeyCode::Up), "/c", 2), Act::Consumed);
|
||||
assert_eq!(p.selected_label(), "/compact");
|
||||
assert_eq!(p.key(press(KeyCode::Down), "/c", 2), Act::Consumed);
|
||||
assert_eq!(p.selected_label(), "/clear");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tab_accepts_esc_closes_others_pass() {
|
||||
let mut p = pop();
|
||||
assert_eq!(p.key(press(KeyCode::Tab), "/c", 2), Act::Accept);
|
||||
assert_eq!(p.key(press(KeyCode::Esc), "/c", 2), Act::Close);
|
||||
assert_eq!(p.key(press(KeyCode::Char('x')), "/c", 2), Act::Pass);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enter_accepts_only_a_partial_token() {
|
||||
let mut p = pop();
|
||||
assert_eq!(p.key(press(KeyCode::Enter), "/c", 2), Act::Accept);
|
||||
// already complete, or nothing typed: submit
|
||||
assert_eq!(p.key(press(KeyCode::Enter), "/clear", 6), Act::Pass);
|
||||
assert_eq!(p.key(press(KeyCode::Enter), "/", 1), Act::Pass);
|
||||
// alt/shift-enter is a newline
|
||||
let alt = KeyEvent::new(KeyCode::Enter, KeyModifiers::ALT);
|
||||
assert_eq!(p.key(alt, "/c", 2), Act::Pass);
|
||||
}
|
||||
}
|
||||
@@ -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