//! Interactive terminal UI. pub mod editor; 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::{Color, Style}; 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 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, /// Default model per provider, used on `/provider`. pub default_model: fn(Kind) -> String, /// 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, } 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, quit: bool, hint: String, specs: Vec, /// open completion popup and selected row popup: Option<(Completion, usize)>, /// 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 tools · pgup/pgdn scroll · \ tab complete @file / command · /help commands"; 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, default_model, pricing, lsp_status, commands, specs, } = 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()), quit: false, hint: String::new(), specs, popup: None, ask: None, }; // show resumed history for m in agent.session.messages() { for b in &m.content { match (m.role, b) { (hx_ai::Role::User, hx_ai::ContentBlock::Text { text }) => { app.t.push(Item::User(text.clone())) } (hx_ai::Role::Assistant, hx_ai::ContentBlock::Text { text }) => { app.t.push(Item::Assistant(text.clone())) } _ => {} } } } app.t.push(Item::Info(format!( "hx · {:?} · {} · {KEYS}", app.kind, app.model ))); let agent = Arc::new(Mutex::new(agent)); let ctx = Ctx { agent: &agent, tx: &tx, make_provider: &make_provider, default_model, 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; while !app.quit { if std::mem::take(&mut dirty) { 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::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(()) } /// 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 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::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); } } /// Everything `submit` needs besides the app state. struct Ctx<'a> { agent: &'a Arc>, tx: &'a mpsc::UnboundedSender, make_provider: &'a MakeProvider, default_model: fn(Kind) -> String, 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, default_model, 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" => app .t .push(Item::Info(format!("{}\n{KEYS}", cmd::help(&app.specs)))), "lsp" => { let st = lsp_status().await; app.t.push(Item::Info(if st.is_empty() { "lsp: no servers started".into() } else { format!("lsp:\n{}", st.join("\n")) })); } "model" if arg.is_empty() => app.t.push(Item::Info(format!("model: {}", app.model))), "model" => { agent.lock().await.model = arg.into(); app.model = arg.into(); app.t.push(Item::Info(format!("model → {arg}"))); } "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 = default_model(k); 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.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)); }); } "clear" => { let mut a = agent.lock().await; let _ = a.session.rebase(vec![]); app.t = Transcript::default(); app.ctx_tokens = 0; app.t.push(Item::Info("cleared".into())); } _ 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)) => app.t.push(Item::Info(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 app.t.push(Item::User(if shown.starts_with('/') { shown } else { line.clone() })); app.busy = true; 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 input_h = (app.ed.buf.lines().count().max(1) + usize::from(app.ed.buf.ends_with('\n'))) .min(10) as u16 + 2; let [main, status, input] = Layout::vertical([ Constraint::Min(3), Constraint::Length(1), Constraint::Length(input_h), ]) .areas(f.area()); let para = Paragraph::new(app.t.lines(app.expanded)).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); let spin = if app.busy { ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"][(std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap_or_default() .as_millis() / 80 % 10) as usize] } else { " " }; let q = if app.queue.is_empty() { String::new() } else { format!(" · {} queued", app.queue.len()) }; let up = if app.scroll > 0 { format!(" · ↑{}", app.scroll) } else { String::new() }; let st = if let Some((q, _)) = &app.ask { format!("[y/n] {q}") } else if app.hint.is_empty() { format!( "{spin} {:?} · {} · ctx {}k · {}↑ {}↓{q}{up}", app.kind, app.model, app.ctx_tokens / 1000, app.usage.input_tokens + app.usage.cache_read_tokens, app.usage.output_tokens ) } else { app.hint.clone() }; f.render_widget( Line::styled(st, Style::default().fg(Color::DarkGray)), status, ); let block = Block::default() .borders(Borders::TOP | Borders::BOTTOM) .border_style(Style::default().fg(Color::DarkGray)); let inner = block.inner(input); f.render_widget(Paragraph::new(app.ed.buf.as_str()).block(block), input); if let Some((c, sel)) = &app.popup { draw_popup(f, c, *sel, input); } let (r, c) = app.ed.cursor_rc(); let skip = (r as u16).saturating_sub(inner.height.saturating_sub(1)); f.set_cursor_position((inner.x + c as u16, inner.y + r as u16 - skip)); } /// Candidates stacked just above the input box. fn draw_popup(f: &mut ratatui::Frame, c: &Completion, sel: usize, input: Rect) { let h = (c.items.len() as u16).min(input.y); let w = c .items .iter() .map(|i| i.label.chars().count() + i.detail.chars().count() + 3) .max() .unwrap_or(0) .min(f.area().width as usize) as u16; let area = Rect::new(input.x, input.y - h, w, h); let lines: Vec = c .items .iter() .enumerate() .map(|(n, i)| { let base = if n == sel { Style::default().bg(Color::DarkGray).fg(Color::White) } else { Style::default() }; Line::from(vec![ Span::styled(format!(" {} ", i.label), base), Span::styled(format!("{} ", i.detail), base.fg(Color::Gray)), ]) }) .collect(); f.render_widget(Clear, area); f.render_widget(Paragraph::new(lines), area); } #[cfg(test)] mod tests { use super::*; use ratatui::backend::TestBackend; #[test] fn mentions() { let d = std::env::temp_dir().join(format!("hx-tui-{}", std::process::id())); std::fs::create_dir_all(&d).unwrap(); std::fs::write(d.join("a.txt"), "AAA").unwrap(); let s = expand_mentions("see @a.txt and @nope", &d); assert!(s.starts_with("see @a.txt and @nope") && s.contains("\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, quit: false, hint: String::new(), specs: vec![], popup: None, 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!(all.contains("Claude · m1 · ctx 12k"), "{all}"); assert!(rows[8].starts_with("typing"), "{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, quit: false, hint: String::new(), specs: cmd::builtins(&["sonnet", "opus"]), popup: None, ask: None, } } #[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!( rows[5].starts_with(" /clear start an empty session"), "{rows:#?}" ); assert!(rows[6].starts_with(" /compact summarize"), "{rows:#?}"); 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 "); } }