//! Interactive terminal UI. pub mod editor; pub mod picker; pub mod sessions; pub mod theme; pub mod transcript; use crossterm::event::{ Event as TEvent, EventStream, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, }; use editor::{Action, Editor}; use futures::StreamExt; 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 ratatui::layout::{Constraint, Layout, Rect}; use ratatui::style::Modifier; use ratatui::text::Line; use ratatui::text::Span; use ratatui::widgets::{Block, Borders, Clear, Paragraph, Wrap}; use std::collections::VecDeque; use std::sync::Arc; 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, /// Pricing lookup for the footer; None = unknown. pub pricing: fn(&str) -> Option, /// `/lsp` status lines. pub lsp_status: LspStatus, /// Extra slash commands (MCP prompts, `/mcp`): `(name, arg)` -> None = not mine, /// Some(Ok(Send(text))) = send as a user prompt, Some(Ok(Show(text))) = show, Some(Err) = error. pub commands: Commands, /// Everything completable/listed by `/help`: builtins, skills, MCP prompts, extensions. 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 { Send(String), Show(String), } pub type Commands = Box< dyn Fn( &str, &str, ) -> Option< std::pin::Pin> + Send>>, > + Send + Sync, >; pub type LspStatus = Box< dyn Fn() -> std::pin::Pin> + Send>> + Send, >; enum Ui { Ev(Event), Ask(String, tokio::sync::oneshot::Sender), Done(Result<(), String>), Compacted(Result), } /// Forwards agent events to the UI loop. struct Forward(mpsc::UnboundedSender); #[async_trait::async_trait] impl Hook for Forward { async fn on(&self, ev: &Event) -> HookAction { let _ = self.0.send(Ui::Ev(ev.clone())); HookAction::Continue } } struct App { t: Transcript, ed: Editor, files: Vec, /// lines scrolled up from the bottom scroll: u16, 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, /// 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)>, picker: Option, sessions: Option, /// session title for footer / terminal title; None until the first prompt title: Option, /// right-hand panel on wide terminals: (title, text) of the last listing / expanded output panel: Option<(String, String)>, session_path: std::path::PathBuf, /// terminal at least WIDE columns (set on draw) wide: bool, /// pending yes/no question from a tool ask: Option<(String, tokio::sync::oneshot::Sender)>, } 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"; /// Columns from which listings go to a side panel. const WIDE: u16 = 140; pub fn project_files(root: &std::path::Path) -> Vec { ignore::WalkBuilder::new(root) .hidden(true) .build() .flatten() .filter(|e| e.file_type().is_some_and(|t| t.is_file())) .filter_map(|e| { e.path() .strip_prefix(root) .ok() .map(|p| p.to_string_lossy().into_owned()) }) .take(20_000) .collect() } /// Expand `@path` mentions of existing files into attached contents. fn expand_mentions(s: &str, root: &std::path::Path) -> String { let mut att = String::new(); for w in s.split_whitespace().filter_map(|w| w.strip_prefix('@')) { let p = root.join(w); if let Ok(c) = std::fs::read_to_string(&p) && c.len() < 200_000 { att.push_str(&format!("\n\n\n{c}\n")); } } format!("{s}{att}") } pub async fn run(setup: Setup) -> std::io::Result<()> { let Setup { mut agent, kind, make_provider, pricing, lsp_status, commands, specs, open_sessions, models, auto_compact, } = setup; let (tx, mut rx) = mpsc::unbounded_channel(); agent.bus.add(Forward(tx.clone())); { let tx = tx.clone(); let _ = agent .cx .state .ask .set(std::sync::Arc::new(move |q: String| { let (otx, orx) = tokio::sync::oneshot::channel(); let _ = tx.send(Ui::Ask(q, otx)); Box::pin(async move { orx.await.unwrap_or(false) }) })); } let abort: AbortHandle = agent.abort_handle(); let cwd = agent.cx.cwd.clone(); let mut app = App { t: Transcript::default(), ed: Editor::default(), files: project_files(&cwd), scroll: 0, 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, since: Instant::now(), quit: false, hint: String::new(), specs, popup: None, picker: None, sessions: None, title: hx_core::session::title(&agent.session.messages()), panel: None, session_path: agent.session.path().to_path_buf(), wide: false, ask: None, }; 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))); 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, }; let mut term = ratatui::init(); let mut keys = EventStream::new(); let mut tick = tokio::time::interval(std::time::Duration::from_millis(50)); let mut dirty = true; let mut last_title = String::new(); while !app.quit { if std::mem::take(&mut dirty) { let t = format!("hx · {}", app.title.as_deref().unwrap_or("new session")); if t != last_title { // OSC 2: terminal window title use std::io::Write; let _ = write!(std::io::stdout(), "\x1b]2;{t}\x07"); last_title = t; } term.draw(|f| draw(f, &mut app))?; } tokio::select! { k = keys.next() => { let Some(Ok(ev)) = k else { break }; dirty = true; match ev { TEvent::Key(k) if k.kind != KeyEventKind::Release && app.ask.is_some() => { let yes = match k.code { KeyCode::Char('y' | 'Y') => Some(true), KeyCode::Char('n' | 'N') | KeyCode::Esc => Some(false), _ => None, }; if let Some(yes) = yes && let Some((q, reply)) = app.ask.take() { app.t.push(Item::Info(format!("{q} {}", if yes { "yes" } else { "no" }))); let _ = reply.send(yes); } } TEvent::Key(k) if k.kind != KeyEventKind::Release => { if let Some(line) = on_key(&mut app, k, &abort) { submit(&mut app, line, &ctx).await; } } TEvent::Paste(s) => app.ed.insert(&s), _ => {} } } Some(u) = rx.recv() => { dirty = true; match u { 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()); } 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.t.apply(&e); } Ui::Done(r) => { app.busy = false; match r { Err(e) if e == "aborted" => app.t.push(Item::Info("aborted".into())), Err(e) => app.t.push(Item::Error(e)), Ok(()) => {} } if let Some(next) = app.queue.pop_front() { submit(&mut app, next, &ctx).await; } } Ui::Compacted(r) => { app.busy = false; app.t.push(match r { Ok(true) => Item::Info("context compacted".into()), 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()); } } } _ = tick.tick(), if app.busy => dirty = true, } } ratatui::restore(); let a = agent.lock().await; let cost = pricing(&a.model) .map(|p| format!(" ${:.4}", app.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() ); Ok(()) } /// Sessions live next to the current one. fn sessions_dir(app: &App) -> &std::path::Path { app.session_path .parent() .unwrap_or(std::path::Path::new(".")) } fn open_sessions_picker(app: &mut App) { let dir = sessions_dir(app).to_path_buf(); let root = dir.parent().unwrap_or(&dir).to_path_buf(); app.picker = None; app.popup = None; app.sessions = Some(sessions::Sessions::new(&dir, &root, &app.session_path)); } /// Session picker keys. Returns `/resume ` to submit on enter. fn sessions_key(app: &mut App, k: KeyEvent) -> Option { match app.sessions.as_mut()?.key(k) { sessions::Act::None => None, sessions::Act::Close => { app.sessions = None; None } sessions::Act::Resume(p) => { app.sessions = None; (p != app.session_path).then(|| format!("/resume {}", p.display())) } } } /// Replace the agent's session (resume or new) and rebuild the transcript. 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.title = hx_core::session::title(&msgs); app.session_path = sess.path().to_path_buf(); a.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(); 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 } /// Show a listing: right panel on wide terminals, transcript otherwise. fn show(app: &mut App, title: &str, text: String) { if app.wide { app.panel = Some((title.into(), text)); } else { app.t.push(Item::Info(text)); } } /// Returns a line to submit, if any. fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option { let ctrl = k.modifiers.contains(KeyModifiers::CONTROL); let alt = k.modifiers.contains(KeyModifiers::ALT); let shift = k.modifiers.contains(KeyModifiers::SHIFT); app.hint.clear(); if app.sessions.is_some() { return sessions_key(app, k); } if app.picker.is_some() { return picker_key(app, k); } if ctrl && k.code == KeyCode::Char('p') { app.popup = None; app.picker = Some(picker::Picker::new( &app.specs, sessions_dir(app), &app.session_path, )); 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 => { app.popup = None; return None; } KeyCode::Tab => { 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, } } match k.code { KeyCode::Char('c') if ctrl => { if app.busy { app.queue.clear(); abort.abort(); } else if app.ed.buf.is_empty() { app.quit = true; } else { app.ed = std::mem::take(&mut app.ed); app.ed.buf.clear(); app.ed.cur = 0; } } KeyCode::Char('d') if ctrl && app.ed.buf.is_empty() && !app.busy => app.quit = true, KeyCode::Esc if app.busy => { app.queue.clear(); abort.abort(); } KeyCode::Char('o') if ctrl => app.expanded = !app.expanded, KeyCode::Esc if app.panel.is_some() => app.panel = None, KeyCode::Char('j') if ctrl => app.ed.insert("\n"), KeyCode::Enter if alt || shift => app.ed.insert("\n"), KeyCode::Enter => { if let Action::Submit(s) = app.ed.submit() { return Some(s); } } KeyCode::Char('u') if ctrl => app.ed.kill_line(), KeyCode::Char('w') if ctrl => app.ed.kill_word(), KeyCode::Char('a') if ctrl => app.ed.home(), KeyCode::Char('e') if ctrl => app.ed.end(), KeyCode::Char(c) if !ctrl => { app.ed.insert(c.encode_utf8(&mut [0; 4])); live_popup(app); } KeyCode::Backspace => { app.ed.backspace(); live_popup(app); } KeyCode::Delete => app.ed.delete(), KeyCode::Left => app.ed.left(), KeyCode::Right => app.ed.right(), KeyCode::Home => app.ed.home(), KeyCode::End => app.ed.end(), KeyCode::Up => app.ed.up(), KeyCode::Down => app.ed.down(), KeyCode::PageUp => app.scroll = app.scroll.saturating_add(10), KeyCode::PageDown => app.scroll = app.scroll.saturating_sub(10), KeyCode::Tab => { let c = completion(app); let labels: Vec<&str> = c.items.iter().map(|i| i.label.as_str()).collect(); match labels.len() { 0 => app.hint = "no match".into(), 1 => { let l = format!("{} ", labels[0]); app.ed.replace(c.start, &l); } _ => { let pre = cmd::common_prefix(&labels); if pre.len() > app.ed.cur - c.start { app.ed.replace(c.start, &pre); } app.popup = Some((completion(app), 0)); } } } _ => {} } None } fn completion(app: &App) -> Completion { cmd::complete(&app.ed.buf, app.ed.cur, &app.specs, &app.files) } /// Commands and their arguments complete as you type; `@file` waits for Tab (the file list is big). fn live_popup(app: &mut App) { app.popup = None; if !app.ed.buf.starts_with('/') || app.ed.buf.contains('\n') { 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)); } } fn accept(app: &mut App) { if let Some((c, sel)) = app.popup.take() { app.ed.replace(c.start, &format!("{} ", c.items[sel].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, } async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) { let Ctx { agent, tx, make_provider, models, auto_compact, cwd, lsp_status, commands, } = *c; app.scroll = 0; let shown = line.clone(); if let Some(cmd) = line.clone().strip_prefix('/') { let (c, arg) = cmd .split_once(' ') .map_or((cmd, ""), |(a, b)| (a, b.trim())); if app.busy && c != "quit" { app.t.push(Item::Error("busy; esc to abort first".into())); return; } match c { "quit" | "exit" => app.quit = true, "help" => { let h = format!("{}\n\nkeys: {KEYS} · ctrl-p picker", cmd::help(&app.specs)); show(app, "help", h); } "usage" => { let r = usage_report(app, now_secs()); show(app, "usage", r); } "skills" => { let dirs = hx_core::context::skill_dirs(&hx_core::context::hx_home(), cwd); let l = skills_list(&app.specs, &dirs); show(app, "skills", l); } "lsp" => { let st = lsp_status().await; let l = if st.is_empty() { "lsp: no servers started".into() } else { format!("lsp:\n{}", st.join("\n")) }; show(app, "lsp", l); } "resume" if !arg.is_empty() => match hx_core::session::Session::open(arg) { Ok(sess) => { switch_session(app, &mut *agent.lock().await, sess); app.t.push(Item::Info(format!("resumed {arg}"))); } Err(e) => app.t.push(Item::Error(format!("/resume: {e}"))), }, "sessions" | "resume" => open_sessions_picker(app), "new" | "clear" => { let p = hx_core::session::new_path(sessions_dir(app)); match hx_core::session::Session::open(&p) { Ok(sess) => { switch_session(app, &mut *agent.lock().await, sess); app.t.push(Item::Info("new session".into())); } 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" => { // 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(); app.t.push(Item::Info(format!( "model → {arg} ({k:?}) · context {}k", hx_ai::models::window(models, arg) / 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)) => { 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))); } Err(e) => app.t.push(Item::Error(e)), }, "compact" => { app.busy = true; app.since = Instant::now(); app.t.push(Item::Info("compacting…".into())); let (agent, tx) = (agent.clone(), tx.clone()); tokio::spawn(async move { let r = agent .lock() .await .compact(4) .await .map_err(|e| e.to_string()); let _ = tx.send(Ui::Compacted(r)); }); } _ if let Some(Source::Skill(p)) = app.specs.iter().find(|s| s.name == c).map(|s| &s.source) => { match cmd::skill_prompt(c, p, arg) { Ok(t) => line = t, Err(e) => app.t.push(Item::Error(format!("/{c}: {e}"))), } } _ => match commands(c, arg) { None => app .t .push(Item::Error(format!("unknown command /{c}; /help"))), Some(f) => match f.await { Ok(CmdOut::Show(t)) => show(app, c, t), Ok(CmdOut::Send(t)) => line = t, Err(e) => app.t.push(Item::Error(e)), }, }, } if line.starts_with('/') { return; } } if app.busy { app.t.push(Item::Info(format!( "queued: {}", line.lines().next().unwrap_or_default() ))); app.queue.push_back(line); return; } // a command that expanded into a prompt shows as typed if app.title.is_none() { app.title = hx_core::session::title(&[hx_ai::Message::user(shown.clone())]); } app.t.push(Item::User(if shown.starts_with('/') { shown } else { line.clone() })); app.busy = true; app.since = Instant::now(); let prompt = expand_mentions(&line, cwd); let (agent, tx) = (agent.clone(), tx.clone()); tokio::spawn(async move { let r = agent .lock() .await .run(prompt) .await .map(|_| ()) .map_err(|e| e.to_string()); let _ = tx.send(Ui::Done(r)); }); } fn draw(f: &mut ratatui::Frame, app: &mut App) { let th = theme::t(); let input_h = (app.ed.buf.lines().count().max(1) + usize::from(app.ed.buf.ends_with('\n'))) .min(10) as u16 + 2; let act_h = u16::from(app.busy); app.wide = f.area().width >= WIDE; let [main, act, input, status] = Layout::vertical([ Constraint::Min(3), Constraint::Length(act_h), Constraint::Length(input_h), Constraint::Length(1), ]) .areas(f.area()); let main = match &app.panel { Some((title, text)) if app.wide => { let [m, side] = Layout::horizontal([Constraint::Min(60), Constraint::Percentage(40)]).areas(main); f.render_widget( Paragraph::new(text.as_str()) .wrap(Wrap { trim: false }) .block( Block::new() .borders(Borders::LEFT) .border_style(th.dim()) .title(Span::styled(format!(" {title} · esc "), th.dim())), ), side, ); m } _ => main, }; let para = Paragraph::new(app.t.lines(app.expanded, main.width)).wrap(Wrap { trim: false }); let total = para.line_count(main.width) as u16; let max_up = total.saturating_sub(main.height); app.scroll = app.scroll.min(max_up); f.render_widget(para.scroll((max_up - app.scroll, 0)), main); if app.busy { let (what, t0) = app.t.running().unwrap_or(("thinking…".into(), app.since)); let frame = (app.since.elapsed().as_millis() / 80) as usize; f.render_widget(transcript::activity_line(&what, t0.elapsed(), frame), act); } let block = Block::default() .borders(Borders::TOP | Borders::BOTTOM) .border_style(th.dim()); let inner = block.inner(input); f.render_widget(block, input); let [gut, text] = Layout::horizontal([Constraint::Length(2), Constraint::Min(1)]).areas(inner); f.render_widget( Span::styled( format!("{} ", th.sym.user), th.accent().add_modifier(Modifier::BOLD), ), gut, ); let (r, c) = app.ed.cursor_rc(); let skip = (r as u16).saturating_sub(text.height.saturating_sub(1)); if app.ed.buf.is_empty() { f.render_widget(Span::styled(PLACEHOLDER, th.dim()), text); } 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 col = Span::raw( &app.ed.buf[app.ed.buf[..comp.start].rfind('\n').map_or(0, |i| i + 1)..comp.start], ) .width() as u16; draw_popup(f, comp, *sel, text.x + col, input.y); } f.set_cursor_position((text.x + c as u16, text.y + r as u16 - skip)); if let Some(p) = &app.picker { p.draw(f); } if let Some(s) = &mut app.sessions { s.draw(f); } } /// `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 .iter() .filter_map(|s| match &s.source { Source::Skill(p) => Some(format!("/{} — {}\n {}", s.name, s.summary, p.display())), _ => None, }) .collect(); let dirs: Vec = dirs .iter() .map(|d| { format!( " {}{}", d.display(), if d.is_dir() { "" } else { " (missing)" } ) }) .collect(); format!( "skills ({}):\n{}\nsearched (later wins):\n{}", sk.len(), sk.join("\n"), dirs.join("\n") ) } /// Bordered candidate list ending just above row `bottom`, starting at column `x` (the token). fn draw_popup(f: &mut ratatui::Frame, c: &Completion, sel: usize, x: u16, bottom: u16) { let th = theme::t(); let lw = c .items .iter() .map(|i| i.label.chars().count()) .max() .unwrap_or(0); let lines: Vec = c .items .iter() .enumerate() .map(|(n, i)| { let base = if n == sel { th.sel() } else { th.plain() }; Line::from(vec![ Span::styled(format!(" {:\nAAA")); assert!(!s.contains("nope\">")); } #[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, }; app.t.push(Item::User("hello".into())); app.t.push(Item::Assistant("hi **there**".into())); app.ed.insert("typing"); let mut term = ratatui::Terminal::new(TestBackend::new(40, 10)).unwrap(); term.draw(|f| draw(f, &mut app)).unwrap(); let buf = term.backend().buffer().clone(); let rows: Vec = (0..10) .map(|y| (0..40).map(|x| buf[(x, y)].symbol().to_string()).collect()) .collect(); let all = rows.join("\n"); assert!(all.contains("❯ hello"), "{all}"); assert!(all.contains("◆ hi there"), "{all}"); assert!(rows[7].starts_with("❯ typing"), "{all}"); assert!(rows[9].starts_with("ctx ▰▱▱▱▱▱▱▱▱▱ 12k/150k "), "{all}"); assert!(rows[9].ends_with("Claude · m1"), "{all}"); } fn key(app: &mut App, code: KeyCode) -> Option { on_key( app, KeyEvent::new(code, KeyModifiers::NONE), &AbortHandle::detached(), ) } fn test_app() -> App { App { t: Transcript::default(), ed: Editor::default(), files: vec!["src/main.rs".into(), "src/lib.rs".into()], scroll: 0, 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, since: Instant::now(), quit: false, hint: String::new(), specs: cmd::builtins(&["sonnet", "opus"]), popup: None, picker: None, sessions: None, title: None, panel: None, session_path: "/nonexistent/s.jsonl".into(), wide: false, ask: None, } } #[test] fn skills_listing() { let mut specs = cmd::builtins(&[]); specs.push(CmdSpec::new( "rev", "review code", Source::Skill("/s/rev/SKILL.md".into()), cmd::ArgKind::Free, )); let s = skills_list(&specs, &["/nonexistent-hx".into()]); assert!( s.starts_with("skills (1):\n/rev — review code\n /s/rev/SKILL.md"), "{s}" ); assert!(s.ends_with("/nonexistent-hx (missing)"), "{s}"); } #[test] fn popup_keys_and_render() { let mut app = test_app(); for c in "/c".chars() { key(&mut app, KeyCode::Char(c)); } let labels = |a: &App| { a.popup.as_ref().map(|(c, s)| { ( c.items.iter().map(|i| i.label.clone()).collect::>(), *s, ) }) }; assert_eq!( labels(&app), Some((vec!["/clear".into(), "/compact".into()], 0)) ); let mut term = ratatui::Terminal::new(TestBackend::new(40, 10)).unwrap(); term.draw(|f| draw(f, &mut app)).unwrap(); let buf = term.backend().buffer().clone(); let rows: Vec = (0..10) .map(|y| (0..40).map(|x| buf[(x, y)].symbol().to_string()).collect()) .collect(); assert_eq!( rows[3], " │ /clear alias of /new │ ", "{rows:#?}" ); assert!(rows[4].starts_with(" │ /compact summarize"), "{rows:#?}"); assert!(rows[9].ends_with("Claude · m1"), "{rows:#?}"); // footer at 100 cols, and a hint replacing only the right side app.hint = "no match".into(); let mut term = ratatui::Terminal::new(TestBackend::new(100, 10)).unwrap(); term.draw(|f| draw(f, &mut app)).unwrap(); let buf = term.backend().buffer().clone(); let last: String = (0..100).map(|x| buf[(x, 9)].symbol().to_string()).collect(); assert!( last.starts_with("ctx ▱▱▱▱▱▱▱▱▱▱ 0k/150k · 0↑ 0↓") && last.ends_with("no match"), "{last}" ); app.hint.clear(); let mut foot = |app: &mut App| { term.draw(|f| draw(f, app)).unwrap(); let buf = term.backend().buffer().clone(); (0..100) .map(|x| buf[(x, 9)].symbol().to_string()) .collect::() }; assert!(foot(&mut app).ends_with("new session · Claude · m1")); app.title = Some("fix the flaky rust-analyzer test".into()); let last = foot(&mut app); assert!( last.starts_with("ctx ▱") && last.ends_with("fix the flaky rust-analyzer test · Claude · m1"), "{last}" ); app.title = None; key(&mut app, KeyCode::Down); key(&mut app, KeyCode::Up); key(&mut app, KeyCode::Up); assert_eq!(labels(&app).unwrap().1, 1, "wraps"); assert_eq!( key(&mut app, KeyCode::Enter), None, "enter accepts partial token" ); assert_eq!(app.ed.buf, "/compact "); assert!(app.popup.is_none(), "no args for /compact"); assert_eq!(key(&mut app, KeyCode::Enter).as_deref(), Some("/compact ")); // args complete live; empty arg + enter submits (shows current model) for c in "/model ".chars() { key(&mut app, KeyCode::Char(c)); } assert_eq!(labels(&app).unwrap().0, ["opus", "sonnet"]); assert_eq!(key(&mut app, KeyCode::Enter).as_deref(), Some("/model ")); // @file waits for tab; esc closes; up with popup closed browses history for c in "x @src".chars() { key(&mut app, KeyCode::Char(c)); } assert!(app.popup.is_none()); key(&mut app, KeyCode::Tab); assert_eq!(app.ed.buf, "x @src/", "common prefix filled"); assert_eq!(labels(&app).unwrap().0.len(), 2); key(&mut app, KeyCode::Esc); assert!(app.popup.is_none()); key(&mut app, KeyCode::Char('m')); key(&mut app, KeyCode::Tab); assert_eq!(app.ed.buf, "x @src/main.rs "); key(&mut app, KeyCode::Up); assert_eq!(app.ed.buf, "/model "); } #[test] fn picker_and_wide_panel() { let mut app = test_app(); app.specs.push(CmdSpec::new( "lsp", "status", Source::Builtin, cmd::ArgKind::None, )); on_key( &mut app, KeyEvent::new(KeyCode::Char('p'), KeyModifiers::CONTROL), &AbortHandle::detached(), ); assert!(app.picker.is_some()); for c in "compa".chars() { assert_eq!( key(&mut app, KeyCode::Char(c)), None, "typing goes to the picker" ); } assert!(app.ed.buf.is_empty()); let mut term = ratatui::Terminal::new(TestBackend::new(60, 12)).unwrap(); term.draw(|f| draw(f, &mut app)).unwrap(); let buf = term.backend().buffer().clone(); let rows: Vec = (0..12) .map(|y| (0..60).map(|x| buf[(x, y)].symbol().to_string()).collect()) .collect(); assert!(rows[2].contains("❯ compa"), "{rows:#?}"); assert!( rows[4].contains("/compact summarize old context"), "{rows:#?}" ); assert_eq!(key(&mut app, KeyCode::Enter).as_deref(), Some("/compact")); assert!(app.picker.is_none()); on_key( &mut app, KeyEvent::new(KeyCode::Char('p'), KeyModifiers::CONTROL), &AbortHandle::detached(), ); key(&mut app, KeyCode::Esc); assert!(app.picker.is_none()); // wide: listings go to the side panel, esc closes it let mut term = ratatui::Terminal::new(TestBackend::new(160, 12)).unwrap(); term.draw(|f| draw(f, &mut app)).unwrap(); assert!(app.wide); show(&mut app, "skills", "skills (0):".into()); assert!(app.t.items.is_empty()); term.draw(|f| draw(f, &mut app)).unwrap(); let buf = term.backend().buffer().clone(); let row0: String = (0..160).map(|x| buf[(x, 0)].symbol().to_string()).collect(); assert!(row0.contains("│ skills · esc"), "{row0}"); let row1: String = (0..160).map(|x| buf[(x, 1)].symbol().to_string()).collect(); assert!(row1.contains("│skills (0):"), "{row1}"); key(&mut app, KeyCode::Esc); assert!(app.panel.is_none()); app.wide = false; show(&mut app, "skills", "x".into()); assert_eq!(app.t.items, [Item::Info("x".into())]); } #[tokio::test] async fn new_session_keeps_old_file() { let t = tempfile::tempdir().unwrap(); let old = t.path().join("1.jsonl"); let mut s = hx_core::session::Session::open(&old).unwrap(); s.append(hx_ai::Message::user("first")).unwrap(); let before = std::fs::read_to_string(&old).unwrap(); let (agent, _) = Agent::new( Arc::new(NoProvider), Default::default(), hx_core::session::Session::open(&old).unwrap(), hx_core::tool::ToolCtx { cwd: t.path().into(), state: Default::default(), }, ); 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, }; let mut app = test_app(); 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(); assert_ne!(new, old); assert_eq!((new.parent(), app.title.as_deref()), (old.parent(), None)); assert_eq!( std::fs::read_to_string(&old).unwrap(), before, "old file untouched" ); agent .lock() .await .session .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!(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); let t = tempfile::tempdir().unwrap(); let (agent, _) = Agent::new( Arc::new(NoProvider), Default::default(), hx_core::session::Session::open(t.path().join("s.jsonl")).unwrap(), hx_core::tool::ToolCtx { cwd: t.path().into(), state: Default::default(), }, ); let agent = Arc::new(Mutex::new(agent)); let (tx, _rx) = mpsc::unbounded_channel(); let mut models = hx_ai::models::fallback(Kind::Claude); 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, }; submit(&mut app, "/model gpt-5.6-terra".into(), &ctx).await; assert_eq!((app.kind, app.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 }; submit(&mut app, "/model gpt-5.6-terra".into(), &ctx).await; assert_eq!( (app.kind, app.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 submit(&mut app, "/model gpt-5.6-luna".into(), &ctx).await; assert_eq!(CODEX_CALLS.load(Ordering::SeqCst), 1); } struct NoProvider; #[async_trait::async_trait] impl Provider for NoProvider { async fn stream( &self, _: hx_ai::Request, ) -> hx_ai::Result>> { unimplemented!() } } }