//! Interactive terminal UI. pub mod agents; pub mod choose; pub mod editor; pub mod permit_view; pub mod picker; pub mod popup; pub mod review; pub mod scroll; pub mod sessions; pub mod stats_view; pub mod status; 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::Usage; use hx_ai::auth::Kind; 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; 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 struct Setup { pub agent: Agent, /// 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. 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, /// Capture the mouse (wheel scrolling); terminal text selection then needs shift-drag. pub mouse: bool, /// No permission prompts (`--yolo`). pub yolo: bool, /// MCP servers for the side panel: (name, connected). pub mcp: Vec<(String, bool)>, } /// Screen regions of the last draw, for routing the mouse wheel. #[derive(Default, Clone, Copy)] struct Areas { chat: Rect, panel: Rect, /// agent detail body (the whole view while it is open) detail: Rect, } const WHEEL: u16 = 3; 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), Permit( hx_core::permit::Request, tokio::sync::oneshot::Sender, ), Choose( hx_core::Question, 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, scroll: scroll::Scroll, /// side panel scroll panel_scroll: scroll::Scroll, /// where the chat / side panel / agent detail were last drawn (mouse wheel targets) areas: Areas, expanded: bool, busy: bool, queue: VecDeque, /// 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, 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)>, /// condensed lens state for the footer, refreshed by a timer lens: (String, bool), /// open `ask_user` popup and where its answer goes /// pending permission prompt for bash/write/edit perm: Option<( permit_view::Prompt, tokio::sync::oneshot::Sender, )>, review: Option, /// `/keys`: show every key as hx receives it until esc probe: bool, /// keyboard protocol was switched on (shift-enter is distinguishable) kbd: bool, stats: Option<(hx_core::stats::Summary, String)>, /// lens/context/MCP side panel (ctrl-l), wide terminals only side: bool, lens_lines: Vec, mcp: Vec<(String, bool)>, choose: Option<( choose::Choose, tokio::sync::oneshot::Sender>>, )>, /// shared agent state: the subagent registry lives in it state: Arc, /// transcripts of subagents, fed by their events sub_t: std::collections::HashMap, /// subagent list focused / one agent open agents: Option, } 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 = "ctrl-g agents · enter send · shift-enter/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, switcher, pricing, lsp_status, commands, specs, open_sessions, mouse, yolo, mcp, } = setup; // asked before the alternate screen; terminals that do not answer return false let kbd = crossterm::terminal::supports_keyboard_enhancement().unwrap_or(false); 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) }) })); } if !yolo { let tx = tx.clone(); let _ = agent.cx.state.permit.set(std::sync::Arc::new(move |r| { let (otx, orx) = tokio::sync::oneshot::channel(); let _ = tx.send(Ui::Permit(r, otx)); Box::pin(async move { orx.await.unwrap_or(hx_core::permit::Decision::Deny) }) })); } { let tx = tx.clone(); let _ = agent.cx.state.choose.set(std::sync::Arc::new(move |q| { let (otx, orx) = tokio::sync::oneshot::channel(); let _ = tx.send(Ui::Choose(q, otx)); Box::pin(async move { orx.await.unwrap_or(None) }) })); } let (stx, mut srx) = mpsc::unbounded_channel(); let _ = agent.cx.state.subs.events.set(stx); let abort: AbortHandle = agent.abort_handle(); let cwd = agent.cx.cwd.clone(); *agent .cx .state .allow .lock() .unwrap_or_else(|e| e.into_inner()) = hx_core::permit::Allow::load(&cwd); let mut app = App { t: Transcript::default(), ed: Editor::default(), files: project_files(&cwd), scroll: Default::default(), panel_scroll: Default::default(), areas: Default::default(), expanded: false, busy: false, queue: VecDeque::new(), st: status::Status { kind: switcher.kind(), model: agent.model().to_string(), usage: Usage::default(), ctx_tokens: agent.context_tokens(), ctx_max: agent.compact_at(), quota: None, pricing, }, sw: switcher, 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, lens: (String::new(), false), choose: None, perm: None, review: None, probe: false, kbd, stats: None, side: true, lens_lines: vec![], mcp, state: agent.cx.state.clone(), sub_t: Default::default(), agents: 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.st.kind, app.st.model ))); let agent = Arc::new(Mutex::new(agent)); let ctx = Ctx { agent: &agent, tx: &tx, cwd: &cwd, lsp_status: &lsp_status, commands: &commands, }; let mut term = ratatui::init(); // Kitty keyboard protocol (pushed on the alternate screen): shift-enter arrives as Enter+SHIFT (ghostty, kitty, wezterm, iTerm2, // foot, alacritty, zellij). Not pushed when the terminal does not answer the query. // tmux does not speak the kitty protocol; it forwards shift-enter only after the app asks // xterm-style (modifyOtherKeys), and as `ESC[13;2u` only with `extended-keys-format csi-u`. let tmux = !kbd && std::env::var_os("TMUX").is_some(); if tmux { print!("\x1b[>4;2m"); } if kbd { use crossterm::event::{KeyboardEnhancementFlags as F, PushKeyboardEnhancementFlags}; let _ = crossterm::execute!( std::io::stdout(), PushKeyboardEnhancementFlags(F::DISAMBIGUATE_ESCAPE_CODES) ); // a crash must not leave the shell in this mode let prev = std::panic::take_hook(); std::panic::set_hook(Box::new(move |i| { let _ = crossterm::execute!( std::io::stdout(), crossterm::event::PopKeyboardEnhancementFlags ); prev(i) })); } if mouse { let _ = crossterm::execute!(std::io::stdout(), crossterm::event::EnableMouseCapture); } let mut keys = EventStream::new(); let mut tick = tokio::time::interval(std::time::Duration::from_millis(50)); let mut lens_tick = tokio::time::interval(std::time::Duration::from_secs(2)); 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.perm.is_some() => { if let Some((p, _)) = &mut app.perm && let Some(d) = p.key(k) && let Some((p, reply)) = app.perm.take() { app.t.push(Item::Info(format!( "{} {} {}", permit_view::Prompt::label(d), p.req.tool, p.req.detail ))); let _ = reply.send(d); } } TEvent::Key(k) if k.kind != KeyEventKind::Release && app.choose.is_some() => { if let Some((c, _)) = &mut app.choose && let choose::Act::Done(ans) = c.key(k) && let Some((c, reply)) = app.choose.take() { app.t.push(Item::Info(c.summary(&ans))); let _ = reply.send(ans); } } 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::Mouse(m) => on_mouse(&mut app, m), 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::Permit(r, reply) => app.perm = Some((permit_view::Prompt::new(r), reply)), Ui::Choose(q, reply) => app.choose = Some((choose::Choose::new(q), reply)), Ui::Ev(e) => { if let Event::SubUsage(u) = &e { app.st.usage.add(u); } if let Event::Stream(hx_ai::StreamEvent::Quota(q)) = &e { app.st.quota = Some(q.clone()); } if let Event::Stream(hx_ai::StreamEvent::Done { usage, .. }) = &e { 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); } 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.st.ctx_tokens = agent.lock().await.context_tokens(); } } } Some((id, ev)) = srx.recv() => { dirty = true; let t = app.sub_t.entry(id).or_default(); if t.items.is_empty() && let Some(s) = app.state.subs.get(id) { t.push(Item::User(s.sh.prompt.clone())); } t.apply(&ev); } _ = tick.tick(), if app.busy || subs_running(&app) => dirty = true, _ = lens_tick.tick() => { // short timeout: the manager lock can be held while a server starts let to = std::time::Duration::from_millis(200); if let Ok(v) = tokio::time::timeout(to, lsp_status()).await { let s = status::lens_summary(&v); app.lens_lines = v; dirty |= s != app.lens; app.lens = s; } } } } if mouse { let _ = crossterm::execute!(std::io::stdout(), crossterm::event::DisableMouseCapture); } if tmux { print!("\x1b[>4;0m"); } if kbd { let _ = crossterm::execute!( std::io::stdout(), crossterm::event::PopKeyboardEnhancementFlags ); } ratatui::restore(); let a = agent.lock().await; let cost = pricing(a.model()) .map(|p| format!(" ${:.4}", app.st.usage.cost(&p))) .unwrap_or_default(); eprintln!( "[{} in / {} out tokens{cost}; session {}]", app.st.usage.input_tokens + app.st.usage.cache_read_tokens, app.st.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.title = hx_core::session::title(&msgs); app.session_path = sess.path().to_path_buf(); a.replace_session(sess); app.st.ctx_tokens = a.context_tokens(); } /// Picker keys. Returns a line to submit when an entry runs. fn subs_running(app: &App) -> bool { app.state .subs .list() .iter() .any(|s| s.sh.status() == hx_core::subagent::Status::Running) } /// Keys while the agent list or an agent's detail view has focus. fn agents_key(app: &mut App, k: KeyEvent) -> Option { let ctrl = k.modifiers.contains(KeyModifiers::CONTROL); let subs = app.state.subs.list(); match app.agents.as_mut()? { agents::View::List(sel) => { *sel = (*sel).min(subs.len().saturating_sub(1)); match k.code { KeyCode::Up | KeyCode::Char('k') => *sel = sel.saturating_sub(1), KeyCode::Down | KeyCode::Char('j') => { *sel = (*sel + 1).min(subs.len().saturating_sub(1)); } KeyCode::Enter => { if let Some(s) = subs.get(*sel) { app.agents = Some(agents::View::Detail { id: s.sh.id, ed: Editor::default(), scroll: Default::default(), }); } } KeyCode::Esc | KeyCode::Char('q') => app.agents = None, _ => {} } } agents::View::Detail { id, ed, scroll } => { let sub = subs.iter().find(|s| s.sh.id == *id); match k.code { KeyCode::Esc => app.agents = None, KeyCode::Char('c') if ctrl => { if let Some(s) = sub { s.abort(); } } KeyCode::Char('s') if ctrl => { if let Some(a) = app.sub_t.get(id).and_then(agents::last_answer) { let line = format!("[subagent {id}] {a}"); app.agents = None; return Some(line); } app.hint = "agent has no answer yet".into(); } KeyCode::Char('o') if ctrl => app.expanded = !app.expanded, KeyCode::Char('j') if ctrl => ed.insert("\n"), KeyCode::Enter if k.modifiers .intersects(KeyModifiers::ALT | KeyModifiers::SHIFT) => { ed.insert("\n"); } KeyCode::Enter => { if let Action::Submit(text) = ed.submit() && let Some(s) = sub { app.sub_t .entry(*id) .or_default() .push(Item::User(text.clone())); s.prompt(text); } } KeyCode::Char('u') if ctrl => ed.kill_line(), KeyCode::Char('w') if ctrl => ed.kill_word(), KeyCode::Char(c) if !ctrl => ed.insert(c.encode_utf8(&mut [0; 4])), KeyCode::Backspace => ed.backspace(), KeyCode::Delete => ed.delete(), KeyCode::Left => ed.left(), KeyCode::Right => ed.right(), KeyCode::PageUp | KeyCode::PageDown | KeyCode::Home | KeyCode::End | KeyCode::Up | KeyCode::Down if scroll_key(&k, false, scroll, &mut Default::default()) => {} KeyCode::Home => ed.home(), KeyCode::End => ed.end(), KeyCode::Up => ed.up(), KeyCode::Down => ed.down(), _ => {} } } } None } /// Scroll keys: PgUp/PgDn half a page, alt+PgUp/PgDn a full page, alt+Up/Down 3 lines, /// ctrl+Home/End first/last line. Plain Home/End/Up/Down stay with the editor (false). fn scroll_key( k: &KeyEvent, panel: bool, chat: &mut scroll::Scroll, side: &mut scroll::Scroll, ) -> bool { let (ctrl, alt) = ( k.modifiers.contains(KeyModifiers::CONTROL), k.modifiers.contains(KeyModifiers::ALT), ); let s = if panel { side } else { chat }; match k.code { KeyCode::PageUp => s.up(if alt { s.page() } else { s.half_page() }), KeyCode::PageDown => s.down(if alt { s.page() } else { s.half_page() }), KeyCode::Up if alt => s.up(WHEEL), KeyCode::Down if alt => s.down(WHEEL), KeyCode::Home if ctrl => s.start(), KeyCode::End if ctrl => s.end(), _ => return false, } true } /// The side panel takes the scroll keys while it is open and the editor is empty. fn panel_focus(app: &App) -> bool { app.panel.is_some() && app.wide && app.ed.buf.is_empty() } fn inside(r: Rect, x: u16, y: u16) -> bool { x >= r.x && x < r.x + r.width && y >= r.y && y < r.y + r.height } /// Mouse wheel scrolls the region under the pointer: agent detail, side panel, or chat. fn on_mouse(app: &mut App, m: crossterm::event::MouseEvent) { use crossterm::event::MouseEventKind::{ScrollDown, ScrollUp}; let up = match m.kind { ScrollUp => true, ScrollDown => false, _ => return, }; let s = if let Some(agents::View::Detail { scroll, .. }) = &mut app.agents { scroll } else if app.picker.is_some() || app.sessions.is_some() || app.choose.is_some() { return; } else if app.panel.is_some() && inside(app.areas.panel, m.column, m.row) { &mut app.panel_scroll } else if inside(app.areas.chat, m.column, m.row) { &mut app.scroll } else { return; }; if up { s.up(WHEEL); } else { s.down(WHEEL); } } fn picker_key(app: &mut App, k: KeyEvent) -> Option { match app.picker.as_mut()?.key(k) { picker::Act::None => None, picker::Act::Close => { app.picker = None; 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 } } } /// 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)); app.panel_scroll.start(); } 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.probe { if k.code == KeyCode::Esc { app.probe = false; } app.t.push(Item::Info(format!( "key: {:?} {:?}{}", k.code, k.modifiers, if k.code == KeyCode::Esc { " (probe off)" } else { "" } ))); return None; } if app.sessions.is_some() { return sessions_key(app, k); } if app.stats.is_some() { if matches!(k.code, KeyCode::Esc | KeyCode::Char('q')) { app.stats = None; } return None; } if let Some(r) = &mut app.review { match r.key(k) { review::Act::Close => app.review = None, review::Act::Reverted(p) => { app.state .edits .lock() .unwrap_or_else(|e| e.into_inner()) .retain(|e| e.path != p); app.t.push(Item::Info(format!("reverted {}", p.display()))); } review::Act::Error(e) => app.t.push(Item::Error(e)), review::Act::None => {} } return None; } if ctrl && k.code == KeyCode::Char('l') { app.side = !app.side; return None; } if ctrl && k.code == KeyCode::Char('g') { app.popup = None; app.agents = match (app.agents.take(), app.state.subs.list().len()) { (_, 0) => { app.hint = "no subagents yet".into(); None } (None, n) => Some(agents::View::List(n - 1)), (Some(_), _) => None, }; return None; } if app.agents.is_some() { return agents_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(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; } popup::Act::Accept => { accept(app); return None; } popup::Act::Pass => 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 app.ed.continue_line() => {} 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::PageUp | KeyCode::PageDown | KeyCode::Home | KeyCode::End | KeyCode::Up | KeyCode::Down if scroll_key(&k, panel_focus(app), &mut app.scroll, &mut app.panel_scroll) => {} 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::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 = popup::Popup::new(completion(app)); } } } _ => {} } None } /// Footer hint while the agent list has focus, else the transient hint. fn agents_hint(app: &App) -> &str { match app.agents { Some(agents::View::List(_)) => "↑↓ select · enter open · esc close", _ => &app.hint, } } 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 !app.ed.buf[c.start..app.ed.cur].starts_with('@') { app.popup = popup::Popup::new(c); } } fn accept(app: &mut App) { if let Some(p) = app.popup.take() { app.ed .replace(p.comp.start, &format!("{} ", p.selected_label())); live_popup(app); } } /// Everything `submit` needs besides the app state. struct Ctx<'a> { agent: &'a Arc>, tx: &'a mpsc::UnboundedSender, 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, cwd, lsp_status, commands, } = *c; app.scroll.end(); 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); } "keys" => { app.probe = true; app.t.push(Item::Info(format!( "keyboard protocol: {}. Press keys (try shift-enter); esc ends. `enter` shows as {{Enter, NONE}} when the terminal or multiplexer cannot tell shift-enter apart.", if app.kbd { "on" } else { "off (use alt-enter, ctrl-j or a trailing \\)" } ))); } "stats" => { let sess = agent.lock().await; let sum = hx_core::stats::summary(sess.session()); app.stats = Some((sum, app.title.clone().unwrap_or_default())); } "diff" => { let edits = app .state .edits .lock() .unwrap_or_else(|e| e.into_inner()) .clone(); match review::Review::new(&edits) { Some(r) => app.review = Some(r), None => app.t.push(Item::Info("no edits to review".into())), } } "usage" => { let r = status::report(&app.st, status::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); } "yolo" => { let on = app .state .allow .lock() .unwrap_or_else(|e| e.into_inner()) .toggle_yolo(); let m = if on { "yolo on: nothing asks" } else { "yolo off" }; app.t.push(Item::Info(m.into())); } "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.st.model))), "model" => { 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 → {} ({:?}) · 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()) { Ok(k) => { let mut a = agent.lock().await; 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)), }, "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 text_w = f.area().width.saturating_sub(2) as usize; let (rows, (cur_r, cur_c)) = app.ed.wrapped(text_w); let input_h = rows.len().min(10) as u16 + 2; let act_h = u16::from(app.busy); app.wide = f.area().width >= WIDE; if let Some(agents::View::Detail { id, ed, scroll }) = &mut app.agents { let subs = app.state.subs.list(); if let Some(s) = subs.iter().find(|s| s.sh.id == *id) { let t = app.sub_t.entry(*id).or_default(); let row = agents::row(s); let d = agents::Detail { row: &row, model: &s.sh.model, t, ed, expanded: app.expanded, frame: (app.since.elapsed().as_millis() / 80) as usize, }; agents::draw_detail(f, &d, scroll); app.areas.detail = f.area(); return; } app.agents = None; } let sub_rows: Vec = app .state .subs .list() .iter() .map(|s| agents::row(s)) .collect(); let foot_h = status::rows_for(f.area().width, app.ask.is_some()); let [main, subs_area, act, input, status_row] = Layout::vertical([ Constraint::Min(3), Constraint::Length(agents::list_height(sub_rows.len())), Constraint::Length(act_h), Constraint::Length(input_h), Constraint::Length(foot_h), ]) .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); let block = Block::new() .borders(Borders::LEFT) .border_style(th.dim()) .title(Span::styled(format!(" {title} · esc "), th.dim())); let body = block.inner(side); let para = Paragraph::new(text.as_str()).wrap(Wrap { trim: false }); let top = app .panel_scroll .resolve(para.line_count(body.width) as u16, body.height); f.render_widget(block, side); f.render_widget(para.scroll((top, 0)), body); app.areas.panel = side; m } None if app.wide && app.side => { let [m, side] = Layout::horizontal([Constraint::Min(60), Constraint::Length(34)]).areas(main); let block = Block::new() .borders(Borders::LEFT) .border_style(th.dim()) .title(Span::styled(" lens · ctrl-l ", th.dim())); let body = block.inner(side); f.render_widget(block, side); f.render_widget(Paragraph::new(side_lines(app)), body); app.areas.panel = Rect::default(); m } _ => { app.areas.panel = Rect::default(); main } }; app.areas.chat = 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 top = app.scroll.resolve(total, main.height); f.render_widget(para.scroll((top, 0)), main); if !sub_rows.is_empty() { let w = subs_area.width.min(56); let sel = match &app.agents { Some(agents::View::List(s)) => Some((*s).min(sub_rows.len() - 1)), _ => None, }; let frame = (app.since.elapsed().as_millis() / 80) as usize; let r = Rect::new( subs_area.x + subs_area.width - w, subs_area.y, w, subs_area.height, ); f.render_widget(Paragraph::new(agents::lines(&sub_rows, sel, frame, w)), r); } 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) = (cur_r, cur_c); 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 { let lines: Vec = rows.into_iter().map(Line::raw).collect(); f.render_widget(Paragraph::new(lines).scroll((skip, 0)), text); } let chrome = status::Chrome { ask: app.ask.as_ref().map(|(q, _)| q.as_str()), hint: app .choose .as_ref() .map_or_else(|| agents_hint(app), |(c, _)| c.help()), queued: app.queue.len(), scroll: app.scroll.behind(), title: app.title.as_deref(), lens: &app.lens.0, lens_warn: app.lens.1, }; f.render_widget( Paragraph::new(status::rows( &app.st, &chrome, status_row.width, status::now_secs(), )), status_row, ); if let Some((c, _)) = &app.choose { c.draw(f, input.y); } 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], ) .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); } if let Some((s, t)) = &app.stats { stats_view::draw(f, s, t); } if let Some(r) = &app.review { r.draw(f); } if let Some((p, _)) = &app.perm { p.draw(f, input.y); } } /// Right-hand overview on wide terminals: lens state, context numbers, MCP servers. fn side_lines(app: &App) -> Vec> { let th = theme::t(); let head = |t: &str| Line::styled(t.to_string(), th.accent()); let mut l = vec![head("LSP / LINT")]; if app.lens_lines.is_empty() { l.push(Line::styled("(none started)", th.dim())); } l.extend(app.lens_lines.iter().map(|x| { let bad = x.contains("dead") || x.contains("error") || x.contains("missing"); Line::styled(x.clone(), if bad { th.warn() } else { th.plain() }) })); let u = &app.st.usage; let tot = u.input_tokens + u.cache_read_tokens + u.cache_write_tokens; l.push(Line::default()); l.push(head("CONTEXT")); l.push(Line::raw(format!( "window {}k / {}k", app.st.ctx_tokens / 1000, app.st.ctx_max / 1000 ))); if let Some(p) = (100 * u.cache_read_tokens).checked_div(tot) { l.push(Line::raw(format!("cache {p}%"))); } l.push(Line::raw(format!("output {}k", u.output_tokens / 1000))); if !app.mcp.is_empty() { l.push(Line::default()); l.push(head("MCP")); l.extend(app.mcp.iter().map(|(n, ok)| { Line::from(vec![ Span::styled( if *ok { "● " } else { "○ " }, if *ok { th.ok() } else { th.err() }, ), Span::raw(n.clone()), ]) })); } l } /// `/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); // scroll so the selected row stays visible when there are more items than rows let rows = (bottom as usize).saturating_sub(2).max(1); let off = (sel + 1) .saturating_sub(rows) .min(c.items.len().saturating_sub(rows)); let lines: Vec = c .items .iter() .enumerate() .skip(off) .take(rows) .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 = 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"); 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 screen(app: &mut App, w: u16, h: u16) -> String { let mut term = ratatui::Terminal::new(TestBackend::new(w, h)).unwrap(); term.draw(|f| draw(f, app)).unwrap(); let b = term.backend().buffer().clone(); (0..h) .map(|y| { (0..w) .map(|x| b[(x, y)].symbol().to_string()) .collect::() }) .collect::>() .join("\n") } #[test] fn shift_enter_newline_enter_submits_backslash_continues() { let mut app = test_app(); let ab = AbortHandle::detached(); let press = |app: &mut App, c, m| on_key(app, KeyEvent::new(c, m), &ab); app.ed.insert("a"); assert!(press(&mut app, KeyCode::Enter, KeyModifiers::SHIFT).is_none()); app.ed.insert("b\\"); assert!(press(&mut app, KeyCode::Enter, KeyModifiers::NONE).is_none()); app.ed.insert("c"); assert_eq!(app.ed.buf, "a\nb\nc"); assert_eq!( press(&mut app, KeyCode::Enter, KeyModifiers::NONE).as_deref(), Some("a\nb\nc") ); } #[test] fn input_wraps_and_grows() { let mut app = test_app(); app.ed.insert(&"x".repeat(45)); app.ed.insert("\nend"); let s = screen(&mut app, 20, 12); // 45 chars at width 18 = 3 rows, plus "end" = 4 rows; cursor on the last let rows: Vec<&str> = s.lines().collect(); assert!(rows.iter().any(|r| r.contains("end")), "{s}"); assert_eq!( rows.iter().filter(|r| r.contains("xxxxxx")).count(), 3, "{s}" ); } #[test] fn keys_probe_reports_and_ends_on_esc() { let mut app = test_app(); let ab = AbortHandle::detached(); app.probe = true; on_key( &mut app, KeyEvent::new(KeyCode::Enter, KeyModifiers::SHIFT), &ab, ); assert!(app.probe && app.ed.buf.is_empty()); on_key( &mut app, KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE), &ab, ); assert!(!app.probe); } #[test] fn side_panel_only_on_wide_terminals() { let mut app = test_app(); app.mcp = vec![("git".into(), true), ("db".into(), false)]; app.lens_lines = vec!["rust-analyzer @ /p: running".into()]; assert!(screen(&mut app, 160, 50).contains("MCP")); assert!(!screen(&mut app, 80, 24).contains("MCP")); app.side = false; assert!(!screen(&mut app, 160, 50).contains("MCP")); } #[test] fn overlays_render_at_both_sizes() { let mut app = test_app(); app.review = review::Review::new(&[hx_core::permit::FileEdit { path: "/x/a.rs".into(), old: Some("a\n".into()), new: "b\n".into(), }]); let (tx, _rx) = tokio::sync::oneshot::channel(); app.perm = Some(( permit_view::Prompt::new(hx_core::permit::Request { tool: "bash".into(), detail: "rm -rf target".into(), rule: "bash:rm".into(), }), tx, )); for (w, h) in [(80, 24), (160, 50)] { let s = screen(&mut app, w, h); assert!( s.contains("permission") && s.contains("rm -rf target"), "{s}" ); assert!(s.contains("review · 1 files · +1 -1"), "{s}"); } app.review = None; app.perm = None; app.stats = Some((hx_core::stats::Summary::default(), "s".into())); assert!(screen(&mut app, 80, 24).contains("stats · s")); } #[tokio::test] async fn ctrl_g_opens_agents_list_detail_and_back() { use hx_core::tool::{Tool, ToolCtx}; let mut app = test_app(); let ctrl_g = || KeyEvent::new(KeyCode::Char('g'), KeyModifiers::CONTROL); let ab = AbortHandle::detached(); on_key(&mut app, ctrl_g(), &ab); assert_eq!( (app.hint.as_str(), app.agents.is_none()), ("no subagents yet", true) ); // register one finished child through the real tool struct P; #[async_trait::async_trait] impl Provider for P { async fn stream( &self, _: hx_ai::Request, ) -> hx_ai::Result>> { use futures::StreamExt; let m = hx_ai::Message { role: hx_ai::Role::Assistant, content: vec![hx_ai::ContentBlock::Text { text: "answer".into(), }], }; Ok(futures::stream::iter(vec![Ok(hx_ai::StreamEvent::Done { message: m, stop: hx_ai::StopReason::EndTurn, usage: Usage::default(), })]) .boxed()) } } let d = tempfile::tempdir().unwrap(); let role = || hx_core::subagent::Role { provider: Arc::new(P), model: "m".into(), tools: Default::default(), system: String::new(), }; let task = hx_core::subagent::Task::new(role(), role(), d.path().join("s.sub"), 1); let cx = ToolCtx { cwd: d.path().into(), state: app.state.clone(), }; task.call(serde_json::json!({"prompt": "find x"}), &cx) .await; on_key(&mut app, ctrl_g(), &ab); assert!(matches!(app.agents, Some(agents::View::List(0)))); key(&mut app, KeyCode::Enter); assert!(matches!( app.agents, Some(agents::View::Detail { id: 1, .. }) )); // typing goes to the agent's editor, not the main one key(&mut app, KeyCode::Char('h')); assert!(app.ed.buf.is_empty()); key(&mut app, KeyCode::Esc); assert!(app.agents.is_none()); // ctrl-g in the list closes it again on_key(&mut app, ctrl_g(), &ab); on_key(&mut app, ctrl_g(), &ab); assert!(app.agents.is_none()); // the overview row is drawn bottom right let mut term = ratatui::Terminal::new(TestBackend::new(100, 12)).unwrap(); term.draw(|f| draw(f, &mut app)).unwrap(); let b = term.backend().buffer().clone(); let all: String = (0..12) .map(|y| { (0..100) .map(|x| b[(x, y)].symbol().to_string()) .collect::() + "\n" }) .collect(); assert!( all.contains("✓ 1 explore") && all.contains("find x"), "{all}" ); } fn long_chat(app: &mut App, n: usize) { for i in 0..n { app.t.push(Item::Info(format!("line {i}"))); } } fn draw_at(app: &mut App, w: u16, h: u16) -> Vec { let mut term = ratatui::Terminal::new(TestBackend::new(w, h)).unwrap(); term.draw(|f| draw(f, app)).unwrap(); let b = term.backend().buffer().clone(); (0..h) .map(|y| (0..w).map(|x| b[(x, y)].symbol().to_string()).collect()) .collect() } #[test] fn scroll_keys_page_pin_and_jump() { let mut app = test_app(); long_chat(&mut app, 100); let ab = AbortHandle::detached(); let press = |app: &mut App, code, m| { on_key(app, KeyEvent::new(code, m), &ab); }; let rows = draw_at(&mut app, 60, 20); assert!(rows.iter().any(|r| r.contains("line 99")), "follows bottom"); // main area is 20 - input(3) - footer(1) = 16 rows: half page = 8 press(&mut app, KeyCode::PageUp, KeyModifiers::NONE); let rows = draw_at(&mut app, 60, 20); assert_eq!(app.scroll.behind(), 8); assert!(!rows.iter().any(|r| r.contains("line 99")), "{rows:#?}"); assert!( rows[19].contains("↑8"), "footer shows lines behind: {}", rows[19] ); let pinned: Vec = rows[..16].to_vec(); // new streamed text (20 more rows) doesn't move the pinned view, the gap grows long_chat(&mut app, 10); let rows = draw_at(&mut app, 60, 20); assert_eq!(rows[..16], pinned[..]); assert!(rows[19].contains("↑28"), "{}", rows[19]); // alt+up: 3 lines; ctrl+home: top; ctrl+end: back to following press(&mut app, KeyCode::Up, KeyModifiers::ALT); assert_eq!(app.scroll.behind(), 31); press(&mut app, KeyCode::Home, KeyModifiers::CONTROL); let rows = draw_at(&mut app, 60, 20); assert!(rows.iter().any(|r| r.contains("line 0")), "{rows:#?}"); press(&mut app, KeyCode::End, KeyModifiers::CONTROL); let rows = draw_at(&mut app, 60, 20); assert!(rows[14].contains("line 9"), "bottom: {rows:#?}"); assert!(rows[19].ends_with("Claude · m1"), "{}", rows[19]); // plain Home still edits text and doesn't scroll app.ed.insert("abc"); press(&mut app, KeyCode::Home, KeyModifiers::NONE); assert_eq!((app.ed.cur, app.scroll.behind()), (0, 0)); } #[test] fn mouse_wheel_goes_to_region_under_pointer() { use crossterm::event::{MouseEvent, MouseEventKind}; let wheel = |kind, column, row| MouseEvent { kind, column, row, modifiers: KeyModifiers::NONE, }; let mut app = test_app(); long_chat(&mut app, 100); app.panel = Some(("help".into(), (0..100).map(|i| format!("p{i}\n")).collect())); app.panel_scroll.start(); let rows = draw_at(&mut app, 160, 20); assert!(app.wide && app.areas.panel.width > 0); let (chat, panel) = (app.areas.chat, app.areas.panel); assert!(chat.x + chat.width <= panel.x); on_mouse(&mut app, wheel(MouseEventKind::ScrollUp, chat.x + 1, 2)); assert_eq!( (app.scroll.behind(), app.panel_scroll.behind() > 0), (3, true) ); let before = app.panel_scroll.behind(); on_mouse(&mut app, wheel(MouseEventKind::ScrollDown, panel.x + 3, 2)); assert_eq!( (app.scroll.behind(), app.panel_scroll.behind()), (3, before - 3) ); // outside both (input row) and non-wheel events do nothing on_mouse(&mut app, wheel(MouseEventKind::ScrollUp, 5, 18)); on_mouse(&mut app, wheel(MouseEventKind::Moved, chat.x + 1, 2)); assert_eq!(app.scroll.behind(), 3); // PgUp goes to the panel while it is open and the editor is empty let ab = AbortHandle::detached(); on_key( &mut app, KeyEvent::new(KeyCode::PageDown, KeyModifiers::NONE), &ab, ); assert_eq!(app.scroll.behind(), 3); assert!(rows.len() == 20); } 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: Default::default(), panel_scroll: Default::default(), areas: Default::default(), expanded: false, busy: false, queue: VecDeque::new(), 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, sessions: None, title: None, panel: None, session_path: "/nonexistent/s.jsonl".into(), wide: false, ask: None, lens: (String::new(), false), choose: None, perm: None, review: None, probe: false, kbd: false, stats: None, side: true, lens_lines: vec![], mcp: vec![], state: Default::default(), sub_t: Default::default(), agents: 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(|popup::Popup { comp: c, sel: 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 row = |y| -> String { (0..100).map(|x| buf[(x, y)].symbol().to_string()).collect() }; let (last, lens) = (row(8), row(9)); assert!( last.starts_with("ctx ▱▱▱▱▱▱▱▱▱▱ 0k/150k · 0↑ 0↓") && last.ends_with("no match"), "{last}" ); assert!( lens.starts_with("lens: starting") && lens.ends_with("Claude · m1"), "{lens}" ); 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("lens: ") && 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 ls: LspStatus = Box::new(|| Box::pin(async { vec![] })); let cmds: Commands = Box::new(|_, _| None); let ctx = Ctx { agent: &agent, tx: &tx, 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" ); // 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!(app.title.as_deref(), Some("first")); } #[tokio::test] async fn model_switch_shows_in_footer_state() { 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 ctx = Ctx { agent: &agent, tx: &tx, 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.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"))); 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.st.kind, app.st.model.as_str()), (Kind::Codex, "gpt-5.6-terra") ); 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!(app.st.quota.is_some()); } struct NoProvider; #[async_trait::async_trait] impl Provider for NoProvider { async fn stream( &self, _: hx_ai::Request, ) -> hx_ai::Result>> { unimplemented!() } } }