Files
hx/crates/hx-tui/src/lib.rs
T
hermes 99dc90fd3b
ci / check (pull_request) Canceled after 0s
ci / check (push) Canceled after 0s
M6: native MCP client, lazy index, mcp-serve (closes #42-#51)
2026-09-30 15:51:25 +00:00

565 lines
19 KiB
Rust

//! 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::hook::{Event, Hook, HookAction};
use ratatui::layout::{Constraint, Layout};
use ratatui::style::{Color, Style};
use ratatui::text::Line;
use ratatui::widgets::{Block, Borders, Paragraph, Wrap};
use std::collections::VecDeque;
use std::sync::Arc;
use tokio::sync::{Mutex, mpsc};
use transcript::{Item, Transcript};
pub type MakeProvider = Box<dyn Fn(Kind) -> hx_ai::Result<Arc<dyn Provider>> + Send>;
pub struct Setup {
pub agent: Agent,
pub kind: Kind,
pub make_provider: MakeProvider,
/// 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<hx_ai::Pricing>,
/// `/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,
}
pub enum CmdOut {
Send(String),
Show(String),
}
pub type Commands = Box<
dyn Fn(
&str,
&str,
) -> Option<
std::pin::Pin<Box<dyn std::future::Future<Output = Result<CmdOut, String>> + Send>>,
> + Send
+ Sync,
>;
pub type LspStatus = Box<
dyn Fn() -> std::pin::Pin<Box<dyn std::future::Future<Output = Vec<String>> + Send>> + Send,
>;
enum Ui {
Ev(Event),
Done(Result<(), String>),
Compacted(Result<bool, String>),
}
/// Forwards agent events to the UI loop.
struct Forward(mpsc::UnboundedSender<Ui>);
#[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<String>,
/// lines scrolled up from the bottom
scroll: u16,
expanded: bool,
busy: bool,
queue: VecDeque<String>,
kind: Kind,
model: String,
usage: Usage,
ctx_tokens: usize,
quit: bool,
hint: String,
}
const HELP: &str = "enter send · alt-enter/ctrl-j newline · esc/ctrl-c abort · ctrl-o expand tools · pgup/pgdn scroll · tab @file · \
/model <m> · /provider claude|codex · /compact · /clear · /lsp · /quit";
fn project_files(root: &std::path::Path) -> Vec<String> {
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<file path=\"{w}\">\n{c}\n</file>"));
}
}
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,
} = setup;
let (tx, mut rx) = mpsc::unbounded_channel();
agent.bus.add(Forward(tx.clone()));
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(),
};
// 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 · {:?} · {} · {HELP}",
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 => {
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::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<String> {
let ctrl = k.modifiers.contains(KeyModifiers::CONTROL);
let alt = k.modifiers.contains(KeyModifiers::ALT);
let shift = k.modifiers.contains(KeyModifiers::SHIFT);
app.hint.clear();
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])),
KeyCode::Backspace => app.ed.backspace(),
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 => {
if let Some((_, q)) = app.ed.at_token() {
let hits = editor::fuzzy(&app.files, q, 8);
match hits.len() {
0 => app.hint = "no match".into(),
1 => {
let h = hits[0].clone();
app.ed.complete(&h, true);
}
_ => {
let pre = editor::common_prefix(&hits);
if pre.len() > q.len() {
app.ed.complete(&pre, false);
}
app.hint = hits
.iter()
.map(|s| s.as_str())
.collect::<Vec<_>>()
.join(" ");
}
}
}
}
_ => {}
}
None
}
/// Everything `submit` needs besides the app state.
struct Ctx<'a> {
agent: &'a Arc<Mutex<Agent>>,
tx: &'a mpsc::UnboundedSender<Ui>,
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;
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(HELP.into())),
"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::<Kind>()
.map_err(|e| e.to_string())
.and_then(|k| make_provider(k).map(|p| (k, p)).map_err(|e| e.to_string()))
{
Ok((k, p)) => {
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()));
}
_ => 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;
}
app.t.push(Item::User(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 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);
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));
}
#[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("<file path=\"a.txt\">\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(),
};
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<String> = (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}");
}
}