From eaa6e22fbd386df3a04039bb48dd1dea7e674a36 Mon Sep 17 00:00:00 2001 From: Johannes Kresner Date: Fri, 2 Oct 2026 00:10:41 +0200 Subject: [PATCH] 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. --- crates/hx-cli/src/main.rs | 48 +-- crates/hx-cli/src/rpc.rs | 50 ++- crates/hx-core/src/agent.rs | 275 ++++++++------- crates/hx-core/src/compact.rs | 242 +++++++++++++ crates/hx-core/src/lib.rs | 2 + crates/hx-core/src/switch.rs | 229 ++++++++++++ crates/hx-tui/src/lib.rs | 632 +++++++++------------------------- crates/hx-tui/src/picker.rs | 94 ++++- crates/hx-tui/src/popup.rs | 112 ++++++ crates/hx-tui/src/status.rs | 348 +++++++++++++++++++ tests/tui_smoke.py | 7 +- 11 files changed, 1407 insertions(+), 632 deletions(-) create mode 100644 crates/hx-core/src/compact.rs create mode 100644 crates/hx-core/src/switch.rs create mode 100644 crates/hx-tui/src/popup.rs create mode 100644 crates/hx-tui/src/status.rs diff --git a/crates/hx-cli/src/main.rs b/crates/hx-cli/src/main.rs index cea51c9..efec8c1 100644 --- a/crates/hx-cli/src/main.rs +++ b/crates/hx-cli/src/main.rs @@ -7,6 +7,7 @@ use hx_core::agent::Agent; use hx_core::context; use hx_core::hook::{Event, Hook, HookAction}; use hx_core::session::Session; +use hx_core::switch::Switcher; use hx_core::tool::ToolCtx; use std::io::Write; @@ -448,8 +449,12 @@ async fn main() -> Result<()> { Session::open(&path)?, cx, ); - agent.model = model; - agent.system = context::system_prompt(cfg.system_prompt.as_deref(), &context::hx_home(), &cwd); + agent.set_model(model); + agent.set_system(context::system_prompt( + cfg.system_prompt.as_deref(), + &context::hx_home(), + &cwd, + )); let mcp = Arc::new( hx_mcp::Hub::start( hx_mcp::config::load(&context::hx_home(), &cwd).map_err(anyhow::Error::msg)?, @@ -459,8 +464,7 @@ async fn main() -> Result<()> { mcp.register(&mut agent.tools); let idx = mcp.system_prompt(); if !idx.is_empty() { - agent.system.push_str("\n\n"); - agent.system.push_str(&idx); + agent.append_system(&idx); } for (n, s) in &mcp.servers { if let Some(e) = &s.error { @@ -468,14 +472,12 @@ async fn main() -> Result<()> { } } if let Some(n) = cfg.max_tokens { - agent.max_tokens = n; + agent.set_max_tokens(n); + } + match cfg.compact_at { + Some(n) => agent.set_compact_at(n), + None => agent.fit_window(hx_ai::models::window(&models, agent.model())), } - agent.compact_at = cfg.compact_at.unwrap_or_else(|| { - hx_ai::models::compact_threshold( - hx_ai::models::window(&models, &agent.model), - agent.max_tokens, - ) - }); for e in &cfg.extensions { let x = hx_core::ext::Extension::start(e, &cwd) .await @@ -546,8 +548,12 @@ async fn main() -> Result<()> { specs, files: hx_tui::project_files(&cwd), session_dir: dir, - models: models.clone(), - make_provider: provider, + switcher: Switcher::new( + kind, + models.clone(), + Box::new(provider), + cfg.compact_at.is_none(), + ), }, ) .await; @@ -560,13 +566,15 @@ async fn main() -> Result<()> { let Some(prompt) = cli.print else { hx_tui::run(hx_tui::Setup { agent, - kind, - make_provider: Box::new(provider), + switcher: Switcher::new( + kind, + models.clone(), + Box::new(provider), + cfg.compact_at.is_none(), + ), pricing, specs, open_sessions, - models: models.clone(), - auto_compact: cfg.compact_at.is_none(), commands: { let mcp = mcp.clone(); Box::new(move |name: &str, arg: &str| { @@ -644,11 +652,11 @@ async fn main() -> Result<()> { if cli.mode == Mode::Json { rpc::emit( &serde_json::json!({"type": "done", "error": r.as_ref().err().map(|e| e.to_string()), - "usage": agent.usage, "session": path}), + "usage": agent.usage(), "session": path}), ); } - let u = &agent.usage; - let cost = pricing(&agent.model) + let u = &agent.usage(); + let cost = pricing(agent.model()) .map(|p| format!(" ~${:.4}", u.cost(&p))) .unwrap_or_default(); eprintln!( diff --git a/crates/hx-cli/src/rpc.rs b/crates/hx-cli/src/rpc.rs index 4b05add..49f7647 100644 --- a/crates/hx-cli/src/rpc.rs +++ b/crates/hx-cli/src/rpc.rs @@ -51,8 +51,7 @@ pub struct Ctx { pub specs: Vec, pub files: Vec, pub session_dir: std::path::PathBuf, - pub models: Vec, - pub make_provider: fn(hx_ai::auth::Kind) -> hx_ai::Result>, + pub switcher: hx_core::switch::Switcher, } pub async fn serve(mut agent: Agent, abort: AbortHandle, cx: Ctx) -> Result<()> { @@ -60,8 +59,7 @@ pub async fn serve(mut agent: Agent, abort: AbortHandle, cx: Ctx) -> Result<()> specs, files, session_dir, - models, - make_provider, + mut switcher, } = cx; agent.bus.add(Notify); let agent = Arc::new(Mutex::new(agent)); @@ -116,7 +114,7 @@ pub async fn serve(mut agent: Agent, abort: AbortHandle, cx: Ctx) -> Result<()> busy.store(false, std::sync::atomic::Ordering::SeqCst); reply( &id, - r.map(|m| json!({"message": m, "usage": a.usage})) + r.map(|m| json!({"message": m, "usage": a.usage()})) .map_err(|e| e.to_string()), ); })); @@ -129,35 +127,31 @@ pub async fn serve(mut agent: Agent, abort: AbortHandle, cx: Ctx) -> Result<()> let mut a = agent.lock().await; let r = match method { "state" => Ok(json!({ - "model": a.model, "session": a.session.path(), "head": a.session.head(), - "title": hx_core::session::title(&a.session.messages()), - "messages": a.session.messages().len(), "usage": a.usage, + "model": a.model(), "session": a.session().path(), "head": a.session().head(), + "title": hx_core::session::title(&a.session().messages()), + "messages": a.session().messages().len(), "usage": a.usage(), "tools": a.tools.specs().into_iter().map(|t| t.name).collect::>(), })), - "messages" => Ok(json!(a.session.messages())), + "messages" => Ok(json!(a.session().messages())), "fork" => match p["id"].as_u64() { - Some(n) if a.session.fork(n) => Ok(json!({"head": a.session.head()})), + Some(n) if a.fork(n) => Ok(json!({"head": a.session().head()})), _ => Err("unknown entry id".into()), }, "clear" => a - .session - .rebase(vec![]) + .clear() .map(|_| json!({})) .map_err(|e| e.to_string()), "set_model" => match p["model"].as_str() { - // switch provider too when the model belongs to another one - Some(m) => match hx_ai::models::kind_of(&models, m) { - Some(k) => make_provider(k).map(|prov| { - a.provider = prov; - a.model = m.into(); - json!({"model": m, "provider": format!("{k:?}").to_lowercase()}) + // switches provider too when the model belongs to another one + Some(m) => switcher + .set_model(&mut a, m) + .map(|sw| { + let mut r = json!({"model": sw.model}); + if sw.provider_changed { + r["provider"] = json!(format!("{:?}", sw.kind).to_lowercase()); + } + r }), - None => { - a.model = m.into(); - Ok(json!({"model": m})) - } - } - .map_err(|e| e.to_string()), None => Err("params.model required".into()), }, "compact" => a @@ -179,15 +173,15 @@ pub async fn serve(mut agent: Agent, abort: AbortHandle, cx: Ctx) -> Result<()> } "new" => hx_core::session::Session::open(hx_core::session::new_path(&session_dir)) .map(|s| { - a.session = s; - json!({"session": a.session.path()}) + a.replace_session(s); + json!({"session": a.session().path()}) }) .map_err(|e| e.to_string()), "resume" => match p["path"].as_str() { Some(path) => hx_core::session::Session::open(path) .map(|s| { - a.session = s; - json!({"session": a.session.path(), "messages": a.session.messages().len()}) + a.replace_session(s); + json!({"session": a.session().path(), "messages": a.session().messages().len()}) }) .map_err(|e| e.to_string()), None => Err("params.path required".into()), diff --git a/crates/hx-core/src/agent.rs b/crates/hx-core/src/agent.rs index 60b2879..fa67764 100644 --- a/crates/hx-core/src/agent.rs +++ b/crates/hx-core/src/agent.rs @@ -1,5 +1,6 @@ //! Agent loop: stream -> tool calls -> hooks -> results -> repeat. +use crate::compact::{self, ContextMeter}; use crate::hook::{Bus, Event}; use crate::session::Session; use crate::tool::{Registry, ToolCtx}; @@ -23,86 +24,23 @@ pub enum Error { } pub struct Agent { - pub provider: Arc, + provider: Arc, pub tools: Registry, pub bus: Bus, pub cx: ToolCtx, - pub model: String, - pub system: String, - pub max_tokens: u32, - pub max_turns: u32, - pub usage: Usage, - pub session: Session, + model: String, + system: String, + max_tokens: u32, + max_turns: u32, + usage: Usage, + session: Session, /// Auto-compact when the estimated context exceeds this many tokens. - pub compact_at: usize, - /// (real input+output tokens of the last request, message count it covered); None until the - /// first request and after compaction. Beats the bytes/4 guess for the compact trigger. - last_ctx: Option<(usize, usize)>, + compact_at: usize, + ctx: ContextMeter, abort: watch::Receiver, abort_tx: Arc>, } -const SUMMARY_PROMPT: &str = "Summarize the conversation below for a coding agent that will continue the work. \ -Keep: the user's goals and constraints, decisions made, files touched and why, current state, open problems, next steps. \ -Be concise and factual. Output only the summary."; - -/// Context size: real usage of the last request plus a bytes/4 estimate of what was added since; -/// pure estimate when there is no usage yet. -fn context_tokens(last: Option<(usize, usize)>, msgs: &[Message]) -> usize { - match last { - Some((t, n)) if n <= msgs.len() => t + estimate_tokens(&msgs[n..]), - _ => estimate_tokens(msgs), - } -} - -/// Rough token estimate (bytes / 4). -pub fn estimate_tokens(msgs: &[Message]) -> usize { - serde_json::to_string(msgs).map_or(0, |s| s.len() / 4) -} - -fn is_prompt(m: &Message) -> bool { - m.role == Role::User - && !m - .content - .iter() - .any(|b| matches!(b, ContentBlock::ToolResult { .. })) -} - -fn transcript(msgs: &[Message]) -> String { - let cut = |s: &str| -> String { - if s.len() > 800 { - format!("{}…", s.chars().take(800).collect::()) - } else { - s.to_string() - } - }; - let mut t = String::new(); - for m in msgs { - let who = if m.role == Role::User { - "USER" - } else { - "ASSISTANT" - }; - for b in &m.content { - match b { - ContentBlock::Text { text } => t.push_str(&format!("{who}: {text}\n")), - ContentBlock::ToolUse { name, input, .. } => { - t.push_str(&format!("TOOL CALL {name}: {}\n", cut(&input.to_string()))) - } - ContentBlock::ToolResult { - content, is_error, .. - } => t.push_str(&format!( - "TOOL RESULT{}: {}\n", - if *is_error { " (error)" } else { "" }, - cut(content) - )), - _ => {} - } - } - } - t -} - /// Cheap handle to cancel a running `Agent::run`. #[derive(Clone)] pub struct AbortHandle(Arc>); @@ -137,7 +75,7 @@ impl Agent { usage: Usage::default(), session, compact_at: 150_000, - last_ctx: None, + ctx: ContextMeter::default(), abort: rx, abort_tx: tx.clone(), }; @@ -148,27 +86,90 @@ impl Agent { AbortHandle(self.abort_tx.clone()) } + pub fn session(&self) -> &Session { + &self.session + } + + /// Cumulative usage of every request this agent made (turns and compaction summaries). + pub fn usage(&self) -> &Usage { + &self.usage + } + + pub fn model(&self) -> &str { + &self.model + } + + /// Use another model of the current provider. For a different provider use [`set_provider`](Self::set_provider). + pub fn set_model(&mut self, model: impl Into) { + self.model = model.into(); + } + + pub fn set_system(&mut self, system: impl Into) { + self.system = system.into(); + } + + /// Append a section to the system prompt. + pub fn append_system(&mut self, section: &str) { + self.system.push_str("\n\n"); + self.system.push_str(section); + } + + /// Cap on tokens per reply. Set it before [`fit_window`](Self::fit_window), which reserves room for it. + pub fn set_max_tokens(&mut self, n: u32) { + self.max_tokens = n; + } + + pub fn compact_at(&self) -> usize { + self.compact_at + } + + /// Auto-compact once the context exceeds `n` tokens. + pub fn set_compact_at(&mut self, n: usize) { + self.compact_at = n; + } + + /// Derive the compaction threshold from the model's context window (leaving room for a reply). + pub fn fit_window(&mut self, window: u64) { + self.compact_at = hx_ai::models::compact_threshold(window, self.max_tokens); + } + + /// Switch provider and model together; a model id is only meaningful to its provider. + pub fn set_provider(&mut self, provider: Arc, model: impl Into) { + self.provider = provider; + self.set_model(model); + } + + /// Continue in another session (resume or new). Drops token usage measured on the old history. + pub fn replace_session(&mut self, session: Session) { + self.session = session; + self.ctx.reset(); + } + + /// Move the session head to entry `id`. False (and no change) if there is no such entry. + pub fn fork(&mut self, id: u64) -> bool { + let ok = self.session.fork(id); + if ok { + self.ctx.reset(); + } + ok + } + + /// Start over: empty the conversation, keeping the session file's history. + pub fn clear(&mut self) -> Result<(), Error> { + self.session.rebase(vec![])?; + self.ctx.reset(); + Ok(()) + } + /// Summarize everything before the most recent user prompts, keeping at least `keep` messages verbatim. /// The session file keeps full history; the head moves to a new root. Returns false if nothing to cut. /// Cuts at the latest user prompt; inside one long tool loop (no prompt to cut at) it cuts before an /// assistant message and the summary becomes its own leading user message. pub async fn compact(&mut self, keep: usize) -> Result { - let msgs = self.session.messages(); - let range = 1..=msgs.len().saturating_sub(keep); - let prompt_cut = range.clone().rev().find(|&i| is_prompt(&msgs[i])); - let Some(cut) = - prompt_cut.or_else(|| range.rev().find(|&i| msgs[i].role == Role::Assistant)) - else { + let Some(plan) = compact::plan(&self.session.messages(), keep) else { return Ok(false); }; - let req = Request { - model: self.model.clone(), - system: SUMMARY_PROMPT.into(), - messages: vec![Message::user(transcript(&msgs[..cut]))], - tools: vec![], - max_tokens: 4096, - }; - let mut s = self.provider.stream(req).await?; + let mut s = self.provider.stream(plan.request(&self.model)).await?; let mut summary = None; while let Some(ev) = s.next().await { if let StreamEvent::Done { message, usage, .. } = ev? { @@ -177,15 +178,8 @@ impl Agent { } } let summary = summary.ok_or(Error::Truncated)?; - let note = format!("[Summary of earlier conversation]\n{summary}\n[End of summary]"); - let mut kept = msgs[cut..].to_vec(); - if prompt_cut.is_some() { - kept[0].content.insert(0, ContentBlock::Text { text: note }); - } else { - kept.insert(0, Message::user(note)); - } - self.session.rebase(kept)?; - self.last_ctx = None; + self.session.rebase(plan.apply(&summary))?; + self.ctx.reset(); Ok(true) } @@ -222,7 +216,7 @@ impl Agent { if self.aborted() { return Err(Error::Aborted); } - if context_tokens(self.last_ctx, &self.session.messages()) > self.compact_at + if self.ctx.tokens(&self.session.messages()) > self.compact_at && self.compact(6).await? { self.emit(Event::Info("context compacted".into())).await; @@ -260,7 +254,7 @@ impl Agent { + usage.cache_write_tokens + usage.output_tokens) as usize; self.push_with(msg.clone(), Some(usage))?; - self.last_ctx = Some((total, self.session.messages().len())); + self.ctx.record(total, self.session.messages().len()); self.emit(Event::Message(msg.clone())).await; let calls: Vec<(String, String, serde_json::Value)> = msg @@ -535,21 +529,6 @@ mod tests { assert!(matches!(a.run("again").await, Err(Error::Aborted))); } - #[test] - fn context_uses_real_usage() { - let m = vec![ - Message::user("x".repeat(400)), - Message::user("y".repeat(40)), - ]; - assert_eq!(context_tokens(None, &m), estimate_tokens(&m)); - // 1000 real tokens covered the first message; only the second is estimated - assert_eq!( - context_tokens(Some((1000, 1)), &m), - 1000 + estimate_tokens(&m[1..]) - ); - assert_eq!(context_tokens(Some((1000, 5)), &m), estimate_tokens(&m)); - } - #[tokio::test] async fn compaction_inside_tool_loop() { let text = |t: &str| asst(vec![ContentBlock::Text { text: t.into() }]); @@ -578,7 +557,7 @@ mod tests { ); a.run("go").await.unwrap(); // p, a1, r1, a2, r2, fin assert!(a.compact(3).await.unwrap()); - let m = a.session.messages(); + let m = a.session().messages(); // summary(user), a2, r2, fin -> alternates, tool_use still has its result assert_eq!(m.len(), 4); assert_eq!(m[0].role, Role::User); @@ -610,7 +589,7 @@ mod tests { a.run("p2").await.unwrap(); assert!(!a.compact(10).await.unwrap(), "nothing old enough to cut"); assert!(a.compact(2).await.unwrap()); - let m = a.session.messages(); + let m = a.session().messages(); assert_eq!(m.len(), 2); assert!(m[0].text().contains("SUMMARY") && m[0].text().ends_with("p2")); { @@ -621,4 +600,70 @@ mod tests { a.run("p3").await.unwrap(); assert_eq!(Session::open(&path).unwrap().messages().len(), 4); } + + #[tokio::test] + async fn replacing_the_session_drops_stale_context_usage() { + let text = |t: &str| asst(vec![ContentBlock::Text { text: t.into() }]); + let script = Arc::new(Script( + Mutex::new(vec![text("r1"), text("SUMMARY"), text("r2")]), + Mutex::new(vec![]), + )); + let dir = tempfile::tempdir().unwrap(); + let cx = ToolCtx { + cwd: dir.path().into(), + state: Default::default(), + }; + let (mut a, _h) = Agent::new( + script.clone(), + Registry::default(), + Session::open(dir.path().join("a.jsonl")).unwrap(), + cx, + ); + a.compact_at = 5_000; + a.run("hi").await.unwrap(); // real usage now covers 2 messages + // another session whose first two messages are huge and the rest tiny + let mut other = Session::open(dir.path().join("b.jsonl")).unwrap(); + let big = "x".repeat(40_000); + for i in 0..8 { + let t = if i < 2 { big.as_str() } else { "." }; + other + .append(if i % 2 == 0 { + Message::user(t) + } else { + text(t) + }) + .unwrap(); + } + a.replace_session(other); + a.run("go").await.unwrap(); + let reqs = script.1.lock().unwrap(); + assert!( + reqs.iter() + .any(|r| r.system.starts_with("Summarize the conversation")), + "oversized history must trigger compaction" + ); + } + + #[tokio::test] + async fn settings_through_the_interface() { + let dir = tempfile::tempdir().unwrap(); + let cx = ToolCtx { + cwd: dir.path().into(), + state: Default::default(), + }; + let (mut a, _h) = Agent::new( + Arc::new(Script(Mutex::new(vec![]), Mutex::new(vec![]))), + Registry::default(), + Session::open(dir.path().join("s.jsonl")).unwrap(), + cx, + ); + a.set_system("base"); + a.append_system("more"); + assert_eq!(a.system, "base\n\nmore"); + a.set_max_tokens(10_000); + a.fit_window(100_000); + assert_eq!(a.compact_at(), 90_000, "90% of the window"); + a.fit_window(20_000); + assert_eq!(a.compact_at(), 10_000, "leaves room for the reply"); + } } diff --git a/crates/hx-core/src/compact.rs b/crates/hx-core/src/compact.rs new file mode 100644 index 0000000..201e416 --- /dev/null +++ b/crates/hx-core/src/compact.rs @@ -0,0 +1,242 @@ +//! Context compaction: measure how big the conversation is, and turn its old part into a summary. +//! +//! Pure data in, data out. The agent owns the provider call and the session; this module decides +//! *when* to compact, *what* to summarize, and *what history remains* afterwards. + +use hx_ai::{ContentBlock, Message, Request, Role}; + +const SUMMARY_PROMPT: &str = "Summarize the conversation below for a coding agent that will continue the work. \ +Keep: the user's goals and constraints, decisions made, files touched and why, current state, open problems, next steps. \ +Be concise and factual. Output only the summary."; + +/// Rough token estimate (bytes / 4). +pub fn estimate_tokens(msgs: &[Message]) -> usize { + serde_json::to_string(msgs).map_or(0, |s| s.len() / 4) +} + +/// Tracks the real token count the provider reported, so the compact trigger beats the bytes/4 guess. +/// +/// Invariant: a reading describes one specific history. Call [`reset`](Self::reset) whenever that +/// history is replaced or rewritten (new session, fork, clear, compaction); until the next +/// [`record`](Self::record) the meter falls back to the estimate. +#[derive(Default, Debug, Clone, Copy)] +pub struct ContextMeter(Option<(usize, usize)>); + +impl ContextMeter { + /// `total` real tokens (input + output) after a request that covered the first `msg_count` messages. + pub fn record(&mut self, total: usize, msg_count: usize) { + self.0 = Some((total, msg_count)); + } + + pub fn reset(&mut self) { + self.0 = None; + } + + /// Context size: the last real reading plus an estimate of what was added since; + /// pure estimate when there is no (applicable) reading. + pub fn tokens(&self, msgs: &[Message]) -> usize { + match self.0 { + Some((t, n)) if n <= msgs.len() => t + estimate_tokens(&msgs[n..]), + _ => estimate_tokens(msgs), + } + } +} + +/// A decided compaction: which part of the history gets summarized and which stays verbatim. +pub struct Plan { + transcript: String, + kept: Vec, + /// Kept history starts at a user prompt, so the summary can be folded into it. + folds_into_prompt: bool, +} + +/// Plan the compaction of `msgs`, keeping at least `keep` trailing messages verbatim. +/// `None` when there is nothing old enough to cut. +/// +/// Cuts at the latest user prompt; inside one long tool loop (no prompt to cut at) it cuts before an +/// assistant message and the summary becomes its own leading user message. +pub fn plan(msgs: &[Message], keep: usize) -> Option { + let range = 1..=msgs.len().saturating_sub(keep); + let prompt_cut = range.clone().rev().find(|&i| is_prompt(&msgs[i])); + let cut = prompt_cut.or_else(|| range.rev().find(|&i| msgs[i].role == Role::Assistant))?; + Some(Plan { + transcript: transcript(&msgs[..cut]), + kept: msgs[cut..].to_vec(), + folds_into_prompt: prompt_cut.is_some(), + }) +} + +impl Plan { + /// The summarization request to send to the model. + pub fn request(&self, model: &str) -> Request { + Request { + model: model.into(), + system: SUMMARY_PROMPT.into(), + messages: vec![Message::user(self.transcript.clone())], + tools: vec![], + max_tokens: 4096, + } + } + + /// The new history once the model has produced `summary`. + pub fn apply(self, summary: &str) -> Vec { + let note = format!("[Summary of earlier conversation]\n{summary}\n[End of summary]"); + let mut kept = self.kept; + if self.folds_into_prompt { + kept[0].content.insert(0, ContentBlock::Text { text: note }); + } else { + kept.insert(0, Message::user(note)); + } + kept + } +} + +fn is_prompt(m: &Message) -> bool { + m.role == Role::User + && !m + .content + .iter() + .any(|b| matches!(b, ContentBlock::ToolResult { .. })) +} + +fn transcript(msgs: &[Message]) -> String { + let cut = |s: &str| -> String { + if s.len() > 800 { + format!("{}…", s.chars().take(800).collect::()) + } else { + s.to_string() + } + }; + let mut t = String::new(); + for m in msgs { + let who = if m.role == Role::User { + "USER" + } else { + "ASSISTANT" + }; + for b in &m.content { + match b { + ContentBlock::Text { text } => t.push_str(&format!("{who}: {text}\n")), + ContentBlock::ToolUse { name, input, .. } => { + t.push_str(&format!("TOOL CALL {name}: {}\n", cut(&input.to_string()))) + } + ContentBlock::ToolResult { + content, is_error, .. + } => t.push_str(&format!( + "TOOL RESULT{}: {}\n", + if *is_error { " (error)" } else { "" }, + cut(content) + )), + _ => {} + } + } + } + t +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn text(role: Role, t: &str) -> Message { + Message { + role, + content: vec![ContentBlock::Text { text: t.into() }], + } + } + fn call(id: &str) -> Message { + Message { + role: Role::Assistant, + content: vec![ContentBlock::ToolUse { + id: id.into(), + name: "echo".into(), + input: json!({}), + }], + } + } + fn result(id: &str) -> Message { + Message { + role: Role::User, + content: vec![ContentBlock::ToolResult { + tool_use_id: id.into(), + content: "ok".into(), + is_error: false, + }], + } + } + + #[test] + fn meter_uses_real_usage() { + let m = vec![ + Message::user("x".repeat(400)), + Message::user("y".repeat(40)), + ]; + let mut c = ContextMeter::default(); + assert_eq!(c.tokens(&m), estimate_tokens(&m)); + // 1000 real tokens covered the first message; only the second is estimated + c.record(1000, 1); + assert_eq!(c.tokens(&m), 1000 + estimate_tokens(&m[1..])); + c.reset(); + assert_eq!(c.tokens(&m), estimate_tokens(&m)); + // a reading that covers more messages than exist is stale + c.record(1000, 5); + assert_eq!(c.tokens(&m), estimate_tokens(&m)); + } + + #[test] + fn nothing_old_enough_to_cut() { + let m = vec![text(Role::User, "p1"), text(Role::Assistant, "r1")]; + assert!(plan(&m, 10).is_none()); + assert!(plan(&m, 2).is_none(), "the first message is never cut"); + } + + #[test] + fn cuts_at_latest_prompt_and_folds_summary_into_it() { + let m = vec![ + text(Role::User, "p1"), + text(Role::Assistant, "r1"), + text(Role::User, "p2"), + text(Role::Assistant, "r2"), + ]; + let p = plan(&m, 2).unwrap(); + let req = p.request("m"); + let t = req.messages[0].text(); + assert!(t.contains("USER: p1") && t.contains("ASSISTANT: r1") && !t.contains("p2")); + assert_eq!(req.model, "m"); + let h = p.apply("SUM"); + assert_eq!(h.len(), 2); + assert!(h[0].text().contains("SUM") && h[0].text().ends_with("p2")); + } + + #[test] + fn inside_a_tool_loop_the_summary_is_its_own_message() { + // p, a1, r1, a2, r2, fin: no prompt in the cuttable range + let m = vec![ + text(Role::User, "go"), + call("1"), + result("1"), + call("2"), + result("2"), + text(Role::Assistant, "fin"), + ]; + let h = plan(&m, 3).unwrap().apply("SUM"); + // summary(user), a2, r2, fin: roles alternate and the tool_use still has its result + assert_eq!(h.len(), 4); + assert_eq!(h[0].role, Role::User); + assert!(h[0].text().contains("SUM")); + assert_eq!(h[1].role, Role::Assistant); + assert!(matches!(h[2].content[0], ContentBlock::ToolResult { .. })); + } + + #[test] + fn transcript_truncates_long_tool_output() { + let mut r = result("1"); + if let ContentBlock::ToolResult { content, .. } = &mut r.content[0] { + *content = "z".repeat(2000); + } + let t = transcript(&[call("1"), r]); + assert!(t.contains("TOOL CALL echo") && t.contains("TOOL RESULT")); + assert!(t.len() < 1000 && t.contains('…')); + } +} diff --git a/crates/hx-core/src/lib.rs b/crates/hx-core/src/lib.rs index eb29ab5..50976cc 100644 --- a/crates/hx-core/src/lib.rs +++ b/crates/hx-core/src/lib.rs @@ -2,12 +2,14 @@ pub mod agent; pub mod command; +pub mod compact; pub mod context; pub mod ext; pub mod hook; pub mod mask; pub mod session; pub mod stats; +pub mod switch; pub mod tool; use std::collections::HashMap; diff --git a/crates/hx-core/src/switch.rs b/crates/hx-core/src/switch.rs new file mode 100644 index 0000000..0734a92 --- /dev/null +++ b/crates/hx-core/src/switch.rs @@ -0,0 +1,229 @@ +//! Switching the agent's model or provider at runtime. +//! +//! A model id only means something to one provider, so changing the model can mean changing the +//! provider too. And a new model has a new context window, so the compaction threshold has to +//! follow. [`Switcher`] does all of that behind two calls; the TUI and the RPC server share it. + +use crate::agent::Agent; +use hx_ai::Provider; +use hx_ai::auth::Kind; +use hx_ai::models::{self, ModelInfo}; +use std::sync::Arc; + +pub type MakeProvider = Box hx_ai::Result> + Send>; + +/// What a switch did. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Switched { + pub kind: Kind, + pub model: String, + /// The provider client was rebuilt, not just the model: provider-specific state (quota) is stale. + pub provider_changed: bool, + /// Context window of the new model, in tokens. + pub window: u64, +} + +pub struct Switcher { + kind: Kind, + models: Vec, + make_provider: MakeProvider, + auto_compact: bool, +} + +impl Switcher { + /// `kind` is the provider the agent starts with. `auto_compact`: re-derive the compaction + /// threshold from the model's window on every switch (false when it is configured explicitly). + pub fn new( + kind: Kind, + models: Vec, + make_provider: MakeProvider, + auto_compact: bool, + ) -> Self { + Self { + kind, + models, + make_provider, + auto_compact, + } + } + + /// The provider the agent currently uses. + pub fn kind(&self) -> Kind { + self.kind + } + + /// Use model `id`, on whichever provider it belongs to (the current one if unknown). + /// On error the agent and the switcher are unchanged. + pub fn set_model(&mut self, agent: &mut Agent, id: &str) -> Result { + let kind = models::kind_of(&self.models, id).unwrap_or(self.kind); + self.apply(agent, kind, id.to_string(), false) + } + + /// Use provider `kind` with its default model. The client is rebuilt even for the current + /// provider, which picks up refreshed credentials after a re-login. + pub fn set_provider(&mut self, agent: &mut Agent, kind: Kind) -> Result { + let model = models::default_for(kind, &self.models); + self.apply(agent, kind, model, true) + } + + fn apply( + &mut self, + agent: &mut Agent, + kind: Kind, + model: String, + rebuild: bool, + ) -> Result { + let provider_changed = rebuild || kind != self.kind; + if provider_changed { + let p = (self.make_provider)(kind).map_err(|e| e.to_string())?; + agent.set_provider(p, model.as_str()); + self.kind = kind; + } else { + agent.set_model(model.as_str()); + } + let window = models::window(&self.models, &model); + if self.auto_compact { + agent.fit_window(window); + } + Ok(Switched { + kind, + model, + provider_changed, + window, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::session::Session; + use crate::tool::{Registry, ToolCtx}; + use std::sync::Mutex; + + struct Nop; + #[async_trait::async_trait] + impl Provider for Nop { + async fn stream( + &self, + _: hx_ai::Request, + ) -> hx_ai::Result>> + { + unreachable!() + } + } + + fn catalog() -> Vec { + let m = |id: &str, kind, w| ModelInfo { + id: id.into(), + kind, + context_window: w, + }; + vec![ + m("claude-sonnet-x", Kind::Claude, 200_000), + m("claude-haiku-x", Kind::Claude, 100_000), + m("gpt-x", Kind::Codex, 400_000), + ] + } + + /// Switcher whose factory records the kinds it was asked for, and an agent to switch. + fn setup( + auto: bool, + fail: bool, + ) -> (Switcher, Agent, Arc>>, tempfile::TempDir) { + let made = Arc::new(Mutex::new(vec![])); + let m2 = made.clone(); + let sw = Switcher::new( + Kind::Claude, + catalog(), + Box::new(move |k| { + m2.lock().unwrap().push(k); + if fail { + Err(hx_ai::Error::Http("not logged in".into())) + } else { + Ok(Arc::new(Nop)) + } + }), + auto, + ); + let dir = tempfile::tempdir().unwrap(); + let cx = ToolCtx { + cwd: dir.path().into(), + state: Default::default(), + }; + let (mut a, _h) = Agent::new( + Arc::new(Nop), + Registry::default(), + Session::open(dir.path().join("s.jsonl")).unwrap(), + cx, + ); + a.set_model("claude-sonnet-x"); + (sw, a, made, dir) + } + + #[test] + fn same_provider_keeps_it_and_refits_the_window() { + let (mut sw, mut a, made, _d) = setup(true, false); + let s = sw.set_model(&mut a, "claude-haiku-x").unwrap(); + assert_eq!( + s, + Switched { + kind: Kind::Claude, + model: "claude-haiku-x".into(), + provider_changed: false, + window: 100_000 + } + ); + assert!(made.lock().unwrap().is_empty(), "no new provider needed"); + assert_eq!(a.model(), "claude-haiku-x"); + assert!(a.compact_at() <= 90_000, "threshold follows the window"); + } + + #[test] + fn model_of_another_provider_switches_provider() { + let (mut sw, mut a, made, _d) = setup(true, false); + let s = sw.set_model(&mut a, "gpt-x").unwrap(); + assert!(s.provider_changed && s.kind == Kind::Codex); + assert_eq!(*made.lock().unwrap(), vec![Kind::Codex]); + assert_eq!((sw.kind(), a.model()), (Kind::Codex, "gpt-x")); + // back on the same provider: no second factory call + sw.set_model(&mut a, "gpt-y-unknown").unwrap(); + assert_eq!(made.lock().unwrap().len(), 1); + } + + #[test] + fn provider_switch_uses_its_default_model() { + let (mut sw, mut a, _m, _d) = setup(true, false); + let s = sw.set_provider(&mut a, Kind::Codex).unwrap(); + assert_eq!((s.model.as_str(), s.provider_changed), ("gpt-x", true)); + assert_eq!(a.model(), "gpt-x"); + } + + #[test] + fn explicit_provider_switch_rebuilds_even_the_current_one() { + let (mut sw, mut a, made, _d) = setup(true, false); + let s = sw.set_provider(&mut a, Kind::Claude).unwrap(); + assert!(s.provider_changed, "fresh client, so quota is stale"); + assert_eq!(*made.lock().unwrap(), vec![Kind::Claude]); + } + + #[test] + fn failure_changes_nothing() { + let (mut sw, mut a, _m, _d) = setup(true, true); + let before = a.compact_at(); + let e = sw.set_model(&mut a, "gpt-x").unwrap_err(); + assert!(e.contains("not logged in"), "{e}"); + assert_eq!( + (sw.kind(), a.model(), a.compact_at()), + (Kind::Claude, "claude-sonnet-x", before) + ); + } + + #[test] + fn configured_threshold_is_left_alone() { + let (mut sw, mut a, _m, _d) = setup(false, false); + a.set_compact_at(12_345); + sw.set_model(&mut a, "claude-haiku-x").unwrap(); + assert_eq!(a.compact_at(), 12_345); + } +} diff --git a/crates/hx-tui/src/lib.rs b/crates/hx-tui/src/lib.rs index ff12fae..77e3aaa 100644 --- a/crates/hx-tui/src/lib.rs +++ b/crates/hx-tui/src/lib.rs @@ -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 hx_ai::Result> + 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, /// `/lsp` status lines. @@ -44,11 +45,6 @@ pub struct Setup { pub specs: Vec, /// 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, - /// 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, - 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, - pricing: fn(&str) -> Option, + /// 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, /// open completion popup and selected row - popup: Option<(Completion, usize)>, + popup: Option, picker: Option, sessions: Option, /// session title for footer / terminal title; None until the first prompt @@ -125,6 +116,22 @@ struct App { ask: Option<(String, tokio::sync::oneshot::Sender)>, } +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 { - 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 { )); 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 { 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>, tx: &'a mpsc::UnboundedSender, - 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::() - .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::().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::(); - 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> { - 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 = 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::>(), *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; diff --git a/crates/hx-tui/src/picker.rs b/crates/hx-tui/src/picker.rs index ed8586f..cbf4912 100644 --- a/crates/hx-tui/src/picker.rs +++ b/crates/hx-tui/src/picker.rs @@ -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, } @@ -79,11 +91,40 @@ impl Picker { .collect() } - pub fn selected(&self) -> Option { + /// 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 { 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); + } } diff --git a/crates/hx-tui/src/popup.rs b/crates/hx-tui/src/popup.rs new file mode 100644 index 0000000..edf5c35 --- /dev/null +++ b/crates/hx-tui/src/popup.rs @@ -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 { + (!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); + } +} diff --git a/crates/hx-tui/src/status.rs b/crates/hx-tui/src/status.rs new file mode 100644 index 0000000..423cbfc --- /dev/null +++ b/crates/hx-tui/src/status.rs @@ -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, + pub pricing: fn(&str) -> Option, +} + +/// 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::(); + 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> { + 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)); + } +} diff --git a/tests/tui_smoke.py b/tests/tui_smoke.py index 33e091f..f95a5c2 100644 --- a/tests/tui_smoke.py +++ b/tests/tui_smoke.py @@ -4,7 +4,8 @@ import os, pty, sys, time, subprocess, select, re, json, tempfile, signal root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) port = 20000 + os.getpid() % 20000 srv = subprocess.Popen([sys.executable, f"{root}/tests/fake_anthropic.py", str(port)]) -tmp = tempfile.mkdtemp() +# resolved: hx sees the real cwd (macOS /var -> /private/var) and derives the session dir slug from it +tmp = os.path.realpath(tempfile.mkdtemp()) os.makedirs(f"{tmp}/home/.hx"); os.makedirs(f"{tmp}/repo") open(f"{tmp}/home/.hx/auth.json", "w").write(json.dumps({"claude": {"access": "fake-token", "refresh": "r", "expires": 99999999999999}})) open(f"{tmp}/repo/notes.md", "w").write("NOTES\n") @@ -86,7 +87,9 @@ send(b"\x10") # ctrl-p send(b"OLDPROMPT") check("picker lists past session", "session just now") send(b"\r", 1) -check("picker resumes session", "resumed ") +# screen text can be split by ratatui's cursor-move diffing; the OSC window title is written whole +# and only carries the old prompt once the session is resumed +check("picker resumes session", "hx · OLDPROMPT about parsers") send(b"/new\r") check("new session", "new session") send(b"/sessions\r")