//! Interactive terminal UI. pub mod agents; pub mod btw_view; pub mod choose; pub mod doc_view; pub mod editor; pub mod permit_view; pub mod picker; pub mod popup; pub mod review; pub mod scroll; pub mod select; 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, MouseButton, }; 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::buffer::Buffer; 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, Widget, 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, pub reload: Reload, /// 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, drag-select + copy in the chat via OSC 52). pub mouse: bool, /// No permission prompts (`--yolo`). pub yolo: bool, /// Auto permission mode from the start (`--auto`, `permissions = "auto"`). pub auto: 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, >; /// Rebuilds `(system prompt, slash commands)` from disk for `/reload`. pub type Reload = Box Result<(String, Vec), String> + 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), Btw(Result<(String, hx_ai::Usage), String>), } /// 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, /// chat text selection (content coordinates) and whether the button is still down sel: Option, drag: bool, /// last left press for double/triple click: (when, content pos, count) click: Option<(Instant, (u16, u16), u8)>, 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, /// plan view and where the chosen label goes (Implement / Keep planning / Feedback) doc: Option<( doc_view::DocView, hx_core::Question, tokio::sync::oneshot::Sender>>, )>, /// `/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)>, /// `/btw` overlay and the agent's live snapshot it answers from btw: Option, snap: Option>>, /// 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, /// output tokens of the current run: finished requests + streamed estimate (chars/4) run_tokens: (u64, u64), /// header: `~`-shortened cwd and (branch, dirty), refreshed after each run cwd_label: String, git: Option<(String, bool)>, } impl App { /// Mirror a model/provider switch into what the footer shows. fn apply_switch(&mut self, sw: &hx_core::switch::Switched) { self.st.auto = self.sw.is_auto(); self.st.kind = sw.kind; self.st.model = sw.model.clone(); // keep the level when the new provider has it, else its first (Codex has no "off") if !hx_ai::Effort::levels(sw.kind).contains(&self.st.effort) { self.st.effort = hx_ai::Effort::levels(sw.kind)[0]; self.sw.remember_effort(self.st.effort); } 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 = "message · / commands · @ files"; /// 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(cmd::expand_home(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, reload, commands, specs, open_sessions, mouse, yolo, auto, 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(); hx_core::herdr::blocked(q.clone()); let _ = tx.send(Ui::Ask(q, otx)); Box::pin(async move { let r = orx.await.unwrap_or(false); hx_core::herdr::working(); r }) })); } 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(); hx_core::herdr::blocked(format!("{}: {}", r.tool, r.detail)); let _ = tx.send(Ui::Permit(r, otx)); Box::pin(async move { let d = orx.await.unwrap_or(hx_core::permit::Decision::Deny); hx_core::herdr::working(); d }) })); } { let tx = tx.clone(); let _ = agent.cx.state.choose.set(std::sync::Arc::new(move |q| { let (otx, orx) = tokio::sync::oneshot::channel(); hx_core::herdr::blocked("choose an option"); let _ = tx.send(Ui::Choose(q, otx)); Box::pin(async move { let c = orx.await.unwrap_or(None); hx_core::herdr::working(); c }) })); } 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); agent .cx .state .allow .lock() .unwrap_or_else(|e| e.into_inner()) .set_auto(auto && !yolo); let mut app = App { t: Transcript::default(), ed: Editor::default(), files: project_files(&cwd), scroll: Default::default(), panel_scroll: Default::default(), areas: Default::default(), sel: None, drag: false, click: None, expanded: false, busy: false, queue: VecDeque::new(), run_tokens: (0, 0), cwd_label: home_short(&cwd), git: git_head(&cwd), st: status::Status { auto: switcher.is_auto(), kind: switcher.kind(), model: agent.model().to_string(), effort: agent.effort(), 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, doc: None, probe: false, kbd, stats: None, btw: None, snap: Some(agent.snap()), 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, reload: &reload, 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 ); let _ = crossterm::execute!(std::io::stdout(), crossterm::event::DisableBracketedPaste); prev(i) })); } if mouse { let _ = crossterm::execute!(std::io::stdout(), crossterm::event::EnableMouseCapture); } // one Paste event per paste instead of a key event (and redraw) per char; newlines no longer submit let _ = crossterm::execute!(std::io::stdout(), crossterm::event::EnableBracketedPaste); 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(); // a paste without bracketed-paste support is a flood of key events; draw at most ~60/s so input stays ahead of the redraw const FRAME: std::time::Duration = std::time::Duration::from_millis(16); let mut last_draw = std::time::Instant::now() - FRAME; while !app.quit { if dirty && last_draw.elapsed() >= FRAME { dirty = false; last_draw = std::time::Instant::now(); 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! { _ = tokio::time::sleep_until((last_draw + FRAME).into()), if dirty => {} 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 k.code == KeyCode::Char('!') { let mut a = app.state.allow.lock().unwrap_or_else(|e| e.into_inner()); if !a.yolo_on() { a.toggle_yolo(); } drop(a); if let Some((p, reply)) = app.perm.take() { app.t.push(Item::Info(format!("yolo on; allowed {} {}", p.req.tool, p.req.detail))); let _ = reply.send(hx_core::permit::Decision::Once); } continue; } 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.doc.is_some() => { if let Some((v, _, _)) = &mut app.doc && let doc_view::Act::Pick(l) = v.key(k) && let Some((_, mut q, reply)) = app.doc.take() { if l == "Feedback" { q.plan = None; q.text = "What should change in the plan?".into(); q.options = vec![]; app.choose = Some((choose::Choose::input(q), reply)); } else { app.t.push(Item::Info(format!("plan: {l}"))); let _ = reply.send(Some(vec![l])); } } } 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) if app.choose.is_some() => { if let Some((c, _)) = &mut app.choose { c.paste(&s); } } TEvent::Paste(s) if app.perm.is_none() && app.choose.is_none() && app.ask.is_none() => app.ed.insert(&s), TEvent::Resize(..) => app.sel = None, _ => {} } } 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) => { if let Some(p) = &q.plan { let mut md = vec![]; transcript::markdown(p, &mut md); let v = doc_view::DocView::new( "plan", md, vec![ (KeyCode::Enter, "enter", "Implement"), (KeyCode::Char('f'), "f", "Feedback"), (KeyCode::Esc, "esc", "Keep planning"), ], ); app.doc = Some((v, q, reply)); } else { 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.sw.note_quota(app.st.kind, q); app.st.quota = Some(q.clone()); } if let Event::Stream( hx_ai::StreamEvent::TextDelta { text } | hx_ai::StreamEvent::ThinkingDelta { text }, ) = &e { app.run_tokens.1 += text.len() as u64; } if let Event::Stream(hx_ai::StreamEvent::Done { usage, .. }) = &e { app.run_tokens = (app.run_tokens.0 + usage.output_tokens, 0); 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; { let mut a = agent.lock().await; if let Some(sw) = app.sw.end_turn(&mut a) { app.apply_switch(&sw); app.st.effort = a.effort(); app.ctx_max_from(&a); } } app.git = git_head(&cwd); 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::Btw(r) => { if let Some(b) = &mut app.btw { b.a = Some(match r { Ok((t, u)) => { app.st.usage.add(&u); Ok(t) } Err(e) => Err(e), }); } } 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; } } } } let _ = crossterm::execute!(std::io::stdout(), crossterm::event::DisableBracketedPaste); 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. /// `left … right` across `w` columns. fn spread_line(l: Span<'static>, r: Span<'static>, w: u16) -> Line<'static> { let pad = (w as usize).saturating_sub(l.width() + r.width()).max(1); Line::from(vec![l, Span::raw(" ".repeat(pad)), r]) } /// `~/Repos/hx` for `$HOME/Repos/hx`. fn home_short(p: &std::path::Path) -> String { match std::env::var_os("HOME").map(std::path::PathBuf::from) { Some(h) if p.starts_with(&h) => format!("~/{}", p.strip_prefix(&h).unwrap().display()) .trim_end_matches('/') .to_string(), _ => p.display().to_string(), } } /// Current branch (or short hash) and whether the tree is dirty; None outside a repo. fn git_head(cwd: &std::path::Path) -> Option<(String, bool)> { let out = std::process::Command::new("git") .args([ "status", "--porcelain=v1", "--branch", "--untracked-files=no", ]) .current_dir(cwd) .output() .ok() .filter(|o| o.status.success())?; let s = String::from_utf8_lossy(&out.stdout); let mut ls = s.lines(); let head = ls.next()?.strip_prefix("## ")?; let b = head.split("...").next()?.split(' ').next()?; let b = b.strip_prefix("No commits yet on ").unwrap_or(b); Some((b.to_string(), ls.next().is_some())) } /// `hx ~/Repos/hx ⎇ main● model` fn header(app: &App, w: u16) -> Line<'static> { let th = theme::t(); let mut l = vec![ Span::styled("hx", th.accent().add_modifier(Modifier::BOLD)), Span::styled(format!(" {}", app.cwd_label), th.sec()), ]; if let Some((b, dirty)) = &app.git { l.push(Span::styled(format!(" {}{b}", th.sym.branch), th.sec())); if *dirty { l.push(Span::styled(th.sym.dirty, th.accent())); } } let m = Span::styled(app.st.model.clone(), th.sec()); let lw: usize = l.iter().map(Span::width).sum(); if lw + m.width() + 2 <= w as usize { l.push(Span::raw(" ".repeat(w as usize - lw - m.width()))); l.push(m); } Line::from(l) } 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, op: impl FnOnce(&mut Agent) -> Result<(), hx_core::agent::Error>, ) -> Result<(), hx_core::agent::Error> { op(a)?; app.t = Transcript::default(); let msgs = a.session().messages(); sessions::history(&mut app.t, &msgs); app.title = hx_core::session::title(&msgs); app.session_path = a.session().path().to_path_buf(); app.st.ctx_tokens = a.context_tokens(); Ok(()) } /// 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::{Down, Drag, ScrollDown, ScrollUp, Up}; match m.kind { ScrollUp => wheel(app, m, true), ScrollDown => wheel(app, m, false), Down(MouseButton::Left) | Drag(MouseButton::Left) | Up(MouseButton::Left) => { select_mouse(app, m) } _ => {} } } /// The chat text as drawn, full height (for extracting a selection). /// Off-screen chat render plus, per row, whether it continues a soft-wrapped line. fn chat_buf(app: &App) -> (Buffer, Vec) { let w = app.areas.chat.width; let lines = app.t.lines(app.expanded, w); let mut cont = vec![]; for l in &lines { let n = Paragraph::new(l.clone()) .wrap(Wrap { trim: false }) .line_count(w) .max(1); cont.push(false); cont.extend(std::iter::repeat(true).take(n - 1)); } let para = Paragraph::new(lines).wrap(Wrap { trim: false }); let r = Rect::new(0, 0, w, para.line_count(w) as u16); let mut b = Buffer::empty(r); Widget::render(para, r, &mut b); (b, cont) } /// Put `t` on the clipboard (OSC 52) and say so in the footer. fn copy(app: &mut App, t: &str) { let t = select::clamp(t); if t.is_empty() { return; } if !cfg!(test) { use std::io::Write; let mut o = std::io::stdout(); let _ = o.write_all(select::osc52(t).as_bytes()); let _ = o.flush(); } app.hint = format!("copied {} chars", t.chars().count()); } /// Left button in the chat: drag selects, release copies; double click = word, triple = line. fn select_mouse(app: &mut App, m: crossterm::event::MouseEvent) { use crossterm::event::MouseEventKind::{Down, Drag}; if app.agents.is_some() || app.picker.is_some() || app.sessions.is_some() || app.choose.is_some() || app.review.is_some() || app.doc.is_some() || app.perm.is_some() { return; } let c = app.areas.chat; if c.width == 0 || c.height == 0 { return; } if matches!(m.kind, Down(_)) { app.sel = None; app.drag = false; if !inside(c, m.column, m.row) { return; } } else if !app.drag { return; } else if matches!(m.kind, Drag(_)) { // dragging past the top/bottom edge scrolls if m.row <= c.y { app.scroll.up(1); } else if m.row + 1 >= c.y + c.height { app.scroll.down(1); } } let x = m.column.clamp(c.x, c.x + c.width - 1) - c.x; let y = m.row.clamp(c.y, c.y + c.height - 1) - c.y; let p = (app.scroll.top().saturating_add(y), x); match m.kind { Down(_) => { let now = Instant::now(); let n = match app.click { Some((t, q, n)) if q == p && now.duration_since(t).as_millis() < 400 => n % 3 + 1, _ => 1, }; app.click = Some((now, p, n)); if n == 1 { app.sel = Some(select::Sel { anchor: p, head: p }); app.drag = true; } else { let (b, cont) = chat_buf(app); let s = if n == 2 { select::word(&b, p.0, p.1) } else { select::line(&b, p.0) }; let t = select::text(&b, &s, &cont); app.sel = Some(s); copy(app, &t); } } Drag(_) => { if let Some(s) = &mut app.sel { s.head = p; } } _ => { app.drag = false; match app.sel { Some(s) if s.anchor != p => { let (b, cont) = chat_buf(app); let t = select::text(&b, &s, &cont); copy(app, &t); } _ => app.sel = None, } } } } /// Mouse wheel scrolls the region under the pointer: agent detail, side panel, or chat. fn wheel(app: &mut App, m: crossterm::event::MouseEvent, up: bool) { let s = if let Some(agents::View::Detail { scroll, .. }) = &mut app.agents { scroll } else if let Some((v, _, _)) = &mut app.doc { v.wheel(up); return; } 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. /// Accepted files leave the edits log, so the next `/diff` lists only what is still open. fn drop_accepted(app: &App) { let Some(r) = &app.review else { return }; let acc = r.accepted(); app.state .edits .lock() .unwrap_or_else(|e| e.into_inner()) .retain(|e| !acc.contains(&e.path)); } 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(); app.sel = None; app.drag = false; 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 let Some(b) = &mut app.btw { match k.code { KeyCode::Esc | KeyCode::Char('q') | KeyCode::Enter => { if let Some(b) = app.btw.take() { b.close(); } } KeyCode::Up => b.scroll = b.scroll.saturating_sub(1), KeyCode::Down => b.scroll = b.scroll.saturating_add(1), _ => {} } return None; } 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 => { drop_accepted(app); 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::Send(text) => { drop_accepted(app); app.review = None; return Some(text); } 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.state.subs.any_running() { app.state.subs.abort_all(); } 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::Esc if app.state.subs.any_running() => app.state.subs.abort_all(), 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 if app.ed.buf.is_empty() => { app.st.effort = app.st.effort.next(app.st.kind); app.sw.remember_effort(app.st.effort); app.hint = format!("thinking: {}", app.st.effort.name()); } 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 = if labels[0].ends_with('/') { labels[0].to_string() } else { 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.contains('\n') { return; } let c = completion(app); let tok = &app.ed.buf[c.start..app.ed.cur]; let fs = cmd::is_fs_path(tok.strip_prefix('@').unwrap_or(tok)); if fs || (app.ed.buf.starts_with('/') && !tok.starts_with('@')) { app.popup = popup::Popup::new(c); } } fn accept(app: &mut App) { if let Some(p) = app.popup.take() { let l = p.selected_label(); let sp = if l.ends_with('/') { "" } else { " " }; app.ed.replace(p.comp.start, &format!("{l}{sp}")); 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, reload: &'a Reload, commands: &'a Commands, } async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) { let Ctx { agent, tx, cwd, lsp_status, reload, 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 && !matches!(c, "quit" | "btw" | "yolo" | "auto" | "plan") { 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())), } } "btw" => { if arg.is_empty() { app.t.push(Item::Info("usage: /btw ".into())); } else { let Some(snap) = app.snap.as_ref().map(|r| r.borrow().clone()) else { return; }; let (q, tx) = (arg.to_string(), tx.clone()); let q2 = q.clone(); let task = tokio::spawn(async move { let r = snap.btw(&q2).await.map_err(|e| e.to_string()); let _ = tx.send(Ui::Btw(r)); }); app.btw = Some(btw_view::Btw { q, a: None, scroll: 0, task, }); } } "copy" => { let last = app.t.items.iter().rev().find_map(|i| match i { Item::Assistant(t) => Some(t.clone()), _ => None, }); match last { Some(t) => copy(app, &t), None => app.hint = "nothing to copy".into(), } } "usage" => { let r = status::report(&app.st, status::now_secs()); show(app, "usage", r); } "reload" => match reload() { Err(e) => app.t.push(Item::Error(format!("/reload: {e}"))), Ok((sys, specs)) => { let mut a = agent.lock().await; // unchanged prompt: leave it alone, a rewrite would drop the prompt cache let same = a.system() == sys; if !same { a.set_system(sys); } let (old, new) = (app.specs.len(), specs.len()); app.specs = specs; app.t.push(Item::Info(format!( "reloaded: prompt {}, commands {old} → {new}", if same { "unchanged" } else { "updated" } ))); } }, "skills" => { let dirs = hx_core::context::skill_dirs(&hx_core::context::hx_home(), cwd); let mut l = skills_list(&app.specs, &dirs); for w in hx_core::context::scan_skills(&dirs).1 { l.push_str(&format!("\nwarning: {w}")); } show(app, "skills", l); } "sandbox" => { use hx_core::sandbox as sb; let r = match arg { "" => Ok(()), "on" => sb::set_enabled(true), "off" => sb::set_enabled(false), "claude" => { sb::set_claude_sandboxed(!sb::claude_sandboxed()); Ok(()) } _ => Err("usage: /sandbox [on|off|claude]".into()), }; app.t.push(match r { Ok(()) => Item::Info(format!( "sandbox {} · claude {}{}", if sb::active().is_some() { "on" } else { "off" }, if sb::claude_sandboxed() { "sandboxed" } else { "unconfined" }, if arg.is_empty() { "" } else { " · applies to new processes (restart LSP with /lsp)" } )), Err(e) => Item::Error(e), }); } "auto" => { let mut al = app.state.allow.lock().unwrap_or_else(|e| e.into_inner()); let m = match arg { "log" => { let b = al.blocks(); if b.is_empty() { "auto: nothing blocked yet".to_string() } else { format!("auto blocked (newest last):\n{}", b.join("\n")) } } _ => { let on = match arg { "on" => true, "off" => false, _ => !al.auto_on(), }; al.set_auto(on); if on { "auto on: dangerous calls are refused, routine ones run, unclear ones are judged or asked (/auto log lists blocks)".into() } else { "auto off: everything unknown asks".into() } } }; drop(al); app.t.push(Item::Info(m)); } "plan" => { let mut al = app.state.allow.lock().unwrap_or_else(|e| e.into_inner()); let on = match arg { "on" => true, "off" => false, _ => !al.plan_on(), }; al.set_plan(on); drop(al); app.t.push(Item::Info( if on { "plan on: read-only; the plan is shown in full for approval when ready" } else { "plan off" } .into(), )); } "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() => { let r = switch_session(app, &mut *agent.lock().await, |a| { a.resume(std::path::Path::new(arg)) }); match r { Ok(()) => 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 r = switch_session(app, &mut *agent.lock().await, Agent::new_session_here); match r { Ok(()) => app.t.push(Item::Info("new session".into())), Err(e) => app.t.push(Item::Error(format!("/new: {e}"))), } } "effort" if arg.is_empty() => app.t.push(Item::Info(format!( "thinking: {} (off, low, medium, high)", app.st.effort.name() ))), "effort" => match arg.parse::() { Ok(e) if hx_ai::Effort::levels(app.st.kind).contains(&e) => { app.st.effort = e; app.sw.remember_effort(e); app.t.push(Item::Info(format!("thinking → {}", e.name()))); } Ok(_) => app.t.push(Item::Error(format!( "{:?} cannot turn thinking off", app.st.kind ))), Err(e) => app.t.push(Item::Error(e)), }, "model" if arg.is_empty() => app.t.push(Item::Info(format!( "model: {}{}", app.st.model, if app.st.auto { " (auto)" } else { "" } ))), "model" if arg == "auto" => { app.sw.set_auto(true); app.st.auto = true; app.t.push(Item::Info( "model: auto. Picked per prompt across logged-in providers; `@opus ...`, `@codex ...`, `@fast ...` force one turn.".into(), )); } "fable" if arg.is_empty() => app.t.push(Item::Info(format!( "fable in auto mode: {}", if app.sw.fable() { "on" } else { "off" } ))), "fable" if arg == "on" || arg == "off" => { app.sw.set_fable(arg == "on"); app.t.push(Item::Info(if arg == "on" { "fable on: auto escalates to Fable after 2 failed turns in a row or a very hard prompt ($10/$50 per Mtok). `@fable ...` always works.".into() } else { "fable off".into() })); } "fable" => app.t.push(Item::Error("/fable on|off".into())), "model" => { let mut a = agent.lock().await; match app.sw.set_model(&mut a, arg) { Ok(sw) => { app.st.auto = false; 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.run_tokens = (0, 0); app.t.push(Item::Info("compacting…".into())); let (agent, tx) = (agent.clone(), tx.clone()); tokio::spawn(async move { let r = agent .lock() .await .compact_now() .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.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() })); // auto mode / `@opus ...` override: choose model and thinking for this prompt let routed = { let mut a = agent.lock().await; let is_file = |w: &str| cwd.join(w).is_file(); match app.sw.begin_turn(&mut a, &line, &is_file) { Ok(r) => { if let Some(r) = &r { app.apply_switch(&r.sw); app.st.effort = r.pick.effort; app.ctx_max_from(&a); } r } Err(e) => { app.t.push(Item::Error(format!("model choice: {e}"))); None } } }; if let Some(r) = routed { app.t.push(Item::Info(format!( "{} {} ({:?}, think {}): {}", if r.forced { "forced" } else { "auto" }, r.pick.model, r.pick.kind, r.pick.effort.name(), r.pick.why ))); line = r.prompt; } // a prompt starting with the word `plan` turns plan mode on if line .split_whitespace() .next() .is_some_and(|w| w.eq_ignore_ascii_case("plan")) { let mut al = app.state.allow.lock().unwrap_or_else(|e| e.into_inner()); if !al.plan_on() { al.set_plan(true); drop(al); app.t.push(Item::Info( "plan on (prompt starts with `plan`): read-only until the plan is approved".into(), )); } } if app .state .allow .lock() .unwrap_or_else(|e| e.into_inner()) .plan_on() { line = format!( "[plan mode: read-only. Research, then call exit_plan with the complete plan.]\n{line}" ); } app.busy = true; app.since = Instant::now(); app.run_tokens = (0, 0); let prompt = expand_mentions(&line, cwd); let (agent, tx) = (agent.clone(), tx.clone()); let effort = app.st.effort; tokio::spawn(async move { let mut a = agent.lock().await; a.set_effort(effort); let r = a.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(); // rounded frame (2) + `❯ ` gutter (2) + right pad (1) let text_w = f.area().width.saturating_sub(5) 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.queue.len().min(3) as u16; 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 focused = app.agents.is_some(); let sub_rows: Vec = app .state .subs .list() .iter() .map(|s| agents::row(s)) .filter(|r| focused || r.ended.is_none_or(|e| e < agents::LINGER)) .collect(); let foot_h = status::rows_for(f.area().width, app.ask.is_some()); let [head, main, subs_area, act, input, status_row] = Layout::vertical([ Constraint::Length(1), 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()); f.render_widget(header(app, head.width), head); 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()) .padding(ratatui::widgets::Padding::horizontal(1)); let body = block.inner(side); let mut ls = vec![ spread_line( Span::styled( format!("/{title}"), th.accent().add_modifier(Modifier::BOLD), ), Span::styled("esc ×", th.dim()), body.width, ), Line::default(), ]; ls.extend( text.lines() .map(|x| Line::styled(x.to_string(), th.plain())), ); let para = Paragraph::new(ls).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(40)]).areas(main); let block = Block::new() .borders(Borders::LEFT) .border_style(th.dim()) .padding(ratatui::widgets::Padding::horizontal(1)); let body = block.inner(side); f.render_widget(block, side); let mut ls = vec![ spread_line( Span::styled("/lsp", th.accent().add_modifier(Modifier::BOLD)), Span::styled("ctrl-l ×", th.dim()), body.width, ), Line::default(), ]; ls.extend(side_lines(app, body.width as usize)); f.render_widget(Paragraph::new(ls).wrap(Wrap { trim: false }), body); app.areas.panel = Rect::default(); m } _ => { app.areas.panel = Rect::default(); main } }; app.areas.chat = main; app.t.live = app .state .live .lock() .unwrap_or_else(|e| e.into_inner()) .clone(); 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 let Some(s) = &app.sel { select::paint(f.buffer_mut(), main, top, s); } if !sub_rows.is_empty() { let w = subs_area.width; 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; f.render_widget( Paragraph::new(agents::lines(&sub_rows, sel, frame, w)), subs_area, ); } // queued prompts, then the activity line, right above the input let mut al: Vec = app .queue .iter() .take(3) .map(|q| { Line::from(vec![ Span::styled(format!("{} queued ", th.sym.queued), th.dim()), Span::styled(q.lines().next().unwrap_or_default().to_string(), th.sec()), ]) }) .collect(); if app.busy { let what = app.t.running().map_or("thinking".into(), |r| r.0); let frame = (app.since.elapsed().as_millis() / 80) as usize; al.push(transcript::activity_line( &what, app.since.elapsed(), app.run_tokens.0 + app.run_tokens.1 / 4, frame, act.width, )); } f.render_widget(Paragraph::new(al), act); let block = Block::bordered() .border_type(ratatui::widgets::BorderType::Rounded) .border_style(th.frame()); let inner = block.inner(input); f.render_widget(block, input); let [gut, text] = Layout::horizontal([Constraint::Length(2), Constraint::Min(1)]).areas(inner); let text = Rect { width: text.width.saturating_sub(1), ..text }; 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, app.specs.len()); } 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(b) = &app.btw { b.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((v, _, _)) = &mut app.doc { v.draw(f); } if let Some((p, _)) = &app.perm { p.draw(f, input.y); } } const SIDE_DIAGS: usize = 8; const SIDE_TESTS: usize = 6; /// Right-hand lens panel on wide terminals: servers, last turn's diagnostics and tests, /// context numbers, MCP servers. Servers from `/lsp` status lines, findings from `State::lens`. fn side_lines(app: &App, w: usize) -> Vec> { let th = theme::t(); let sec = |label: String| { Line::styled( th.rule(&label, w) .replacen(th.sym.rule, "", 1) .trim_start() .to_string(), th.dim(), ) }; let mut l = vec![]; if app.lens_lines.is_empty() { l.push(Line::styled("no servers started", th.dim())); } for x in &app.lens_lines { // `rust-analyzer @ /root: running, 2 open` / `marked …` / `runners: …` / notes let (name, state) = match x.split_once(" @ ") { Some((n, r)) => (n.to_string(), r.rsplit_once(": ").map_or("", |p| p.1)), None => (x.clone(), ""), }; let (mark, st, word) = if state.starts_with("running") { (th.sym.done, th.ok(), "ready") } else if state.is_empty() { (th.sym.info, th.dim(), "") } else if state == "stopped" { (th.sym.off, th.dim(), "stopped") } else { (th.sym.err, th.err(), state) }; l.push(Line::from(vec![ Span::styled(format!("{mark} "), st), Span::styled( format!("{name:<16}"), if word.is_empty() { th.sec() } else { th.plain() }, ), Span::styled(format!(" {word}"), th.sec()), ])); } let view = app .state .lens .lock() .unwrap_or_else(|e| e.into_inner()) .clone(); if !view.diags.is_empty() { l.push(Line::default()); l.push(sec(format!("diagnostics {}", view.diags.len()))); let mut ds = view.diags.clone(); ds.sort_by_key(|d| (!d.error, d.file.clone(), d.line)); for d in ds.iter().take(SIDE_DIAGS) { let (mark, st) = if d.error { (th.sym.err, th.err()) } else { (th.sym.warn, th.warn()) }; let file = d.file.rsplit('/').next().unwrap_or(&d.file); l.push(Line::from(vec![ Span::styled(format!("{mark} "), st), Span::styled(format!("{file}:{}:{}", d.line, d.col), th.plain()), ])); l.push(Line::styled(format!(" {}", d.message), th.sec())); } if ds.len() > SIDE_DIAGS { l.push(Line::styled( format!(" {} {} more", th.sym.ellipsis, ds.len() - SIDE_DIAGS), th.dim(), )); } } if let Some(ts) = &view.tests { let mut ts = ts.clone(); // failures first ts.sort_by_key(|t| t.1); l.push(Line::default()); l.push(sec(format!("affected tests {}", ts.len()))); for (n, ok) in ts.iter().take(SIDE_TESTS) { l.push(Line::from(vec![ Span::styled( format!("{} ", if *ok { th.sym.ok } else { th.sym.err }), if *ok { th.ok() } else { th.err() }, ), Span::styled(n.clone(), th.plain()), ])); } if ts.len() > SIDE_TESTS { l.push(Line::styled( format!(" {} {} more", th.sym.ellipsis, ts.len() - SIDE_TESTS), th.dim(), )); } } let u = &app.st.usage; let tot = u.input_tokens + u.cache_read_tokens + u.cache_write_tokens; l.push(Line::default()); l.push(sec("context".into())); let mut ctx = format!("{}k / {}k", app.st.ctx_tokens / 1000, app.st.ctx_max / 1000); if let Some(p) = (100 * u.cache_read_tokens).checked_div(tot) { ctx += &format!(" {} cache {p}%", th.sym.info); } l.push(Line::styled(ctx, th.sec())); if !app.mcp.is_empty() { l.push(Line::default()); l.push(sec("mcp".into())); l.extend(app.mcp.iter().map(|(n, ok)| { Line::from(vec![ Span::styled( format!("{} ", if *ok { th.sym.done } else { th.sym.err }), if *ok { th.ok() } else { th.err() }, ), Span::styled(n.clone(), th.plain()), ]) })); } 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") ) } /// `(source tag, summary)` from a slash-command candidate's detail (`mcp · summary`). fn split_source(label: &str, detail: &str) -> (&'static str, String) { if !label.starts_with('/') { return ("", detail.to_string()); } for (pre, tag) in [ ("skill · ", "skill"), ("mcp · ", "mcp prompt"), ("ext · ", "ext"), ] { if let Some(r) = detail.strip_prefix(pre) { return (tag, r.to_string()); } } ("builtin", detail.to_string()) } /// Framed candidate list ending just above row `bottom`, starting at column `x` (the token): /// `commands · 4 of 19` header, name | summary | source columns, key hints underneath. fn draw_popup( f: &mut ratatui::Frame, c: &Completion, sel: usize, x: u16, bottom: u16, total: usize, ) { let th = theme::t(); let area = f.area(); let rows_: Vec<(&str, &'static str, String)> = c .items .iter() .map(|i| { let (tag, d) = split_source(&i.label, &i.detail); (i.label.as_str(), tag, d) }) .collect(); let cw = |f: &dyn Fn(&(&str, &'static str, String)) -> usize| rows_.iter().map(f).max().unwrap_or(0); let lw = cw(&|r| r.0.chars().count()); let tw = cw(&|r| r.1.chars().count()); let max_w = area.width.saturating_sub(2) as usize; // summary column takes what's left, capped so the box doesn't span huge terminals let dw = cw(&|r| r.2.chars().count()) .min(48) .min(max_w.saturating_sub(lw + tw + 7)); let inner_w = 1 + lw + 2 + dw + if tw > 0 { 2 + tw } else { 0 } + 1; let cmds = c.items.first().is_some_and(|i| i.label.starts_with('/')); let kind = if cmds { "commands" } else if c.items.first().is_some_and(|i| i.label.starts_with('@')) { "files" } else { "values" }; let head = if cmds && total > 0 { format!(" {kind} {} {} of {total}", th.sym.info, c.items.len()) } else { format!(" {kind} {} {}", th.sym.info, c.items.len()) }; // header + rows + hints, plus the frame; scroll so the selected row stays visible let rows = (bottom as usize).saturating_sub(4).max(1); let off = (sel + 1) .saturating_sub(rows) .min(c.items.len().saturating_sub(rows)); let mut lines = vec![Line::styled(head, th.dim())]; for (n, (label, tag, d)) in rows_.iter().enumerate().skip(off).take(rows) { let band = if n == sel { th.sel() } else { ratatui::style::Style::default() }; let mut v = vec![ Span::styled(format!(" {label: 0 { let ts = if *tag == "builtin" { th.dim() } else { th.link() }; v.push(Span::styled(format!(" {tag:>tw$}"), band.patch(ts))); } v.push(Span::styled(" ", band)); lines.push(Line::from(v)); } lines.push(Line::styled( format!(" ↑↓ select {0} tab/enter accept {0} esc close", th.sym.info), th.dim(), )); let w = (inner_w.max(lines.last().map_or(0, Line::width) + 1) as u16 + 2).min(area.width); let h = (lines.len() as u16 + 2).min(bottom); let x = x.saturating_sub(1).min(area.width - w); let r = Rect::new(x, bottom - h, w, h); f.render_widget(Clear, r); f.render_widget( Paragraph::new(lines).block( Block::bordered() .border_type(ratatui::widgets::BorderType::Rounded) .border_style(th.frame()), ), r, ); } /// Cut to `n` chars with an ellipsis. fn cut_to(s: &str, n: usize) -> String { if s.chars().count() <= n { return s.into(); } let mut t: String = s.chars().take(n.saturating_sub(1)).collect(); t.push('…'); t } #[cfg(test)] mod tests { use super::*; use hx_ai::Provider; use hx_core::switch::MakeProvider; 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 = 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[0].starts_with("hx ~/w") && rows[0].ends_with("m1"), "{all}" ); assert!(rows[7].starts_with("│❯ typing"), "{all}"); assert!(rows[9].starts_with("m1 · ctx ▰▱▱▱▱▱▱▱▱▱ 8%"), "{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()]; *app.state.lens.lock().unwrap() = hx_core::LensView { diags: vec![hx_core::Diag { file: "crates/a/src/codemode.rs".into(), line: 88, col: 13, error: false, message: "unused variable".into(), }], tests: Some(vec![("a::ok".into(), true), ("a::bad".into(), false)]), }; let s = screen(&mut app, 160, 50); assert!( s.contains("diagnostics 1 ┈") && s.contains("⚠ codemode.rs:88:13"), "{s}" ); assert!( s.contains("affected tests 2 ┈") && s.contains("✗ a::bad"), "{s}" ); let bad = s.find("✗ a::bad").unwrap(); assert!(bad < s.find("✓ a::ok").unwrap(), "failures first"); assert!( s.contains("/lsp") && s.contains("● rust-analyzer ready"), "{s}" ); assert!(s.contains("mcp ┈") && s.contains("✗ db"), "{s}"); assert!(!screen(&mut app, 80, 24).contains("/lsp")); app.side = false; assert!(!screen(&mut app, 160, 50).contains("/lsp")); } #[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 - header(1) - input(3) - footer(1) = 15 rows: half page = 7 press(&mut app, KeyCode::PageUp, KeyModifiers::NONE); let rows = draw_at(&mut app, 60, 20); assert_eq!(app.scroll.behind(), 7); assert!(!rows.iter().any(|r| r.contains("line 99")), "{rows:#?}"); assert!( rows[19].ends_with("↑7"), "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].ends_with("↑27"), "{}", 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(), 30); 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].starts_with("m1 · ctx"), "{}", 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_drag_selects_and_click_clears() { use crossterm::event::{MouseEvent, MouseEventKind::*}; let ev = |kind, column, row| MouseEvent { kind, column, row, modifiers: KeyModifiers::NONE, }; let mut app = test_app(); long_chat(&mut app, 30); draw_at(&mut app, 80, 20); let c = app.areas.chat; let l = MouseButton::Left; on_mouse(&mut app, ev(Down(l), c.x + 1, c.y)); on_mouse(&mut app, ev(Drag(l), c.x + 5, c.y + 2)); assert!(app.drag && app.sel.is_some()); on_mouse(&mut app, ev(Up(l), c.x + 5, c.y + 2)); assert!(!app.drag && app.sel.is_some() && app.hint.starts_with("copied")); // a plain click (no drag) clears; a key press clears too on_mouse(&mut app, ev(Down(l), c.x + 9, c.y + 4)); on_mouse(&mut app, ev(Up(l), c.x + 9, c.y + 4)); assert!(app.sel.is_none()); // presses outside the chat start nothing on_mouse(&mut app, ev(Down(l), 5, 19)); assert!(!app.drag); } #[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 { run_tokens: (0, 0), cwd_label: "~/w".into(), git: None, 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(), sel: None, drag: false, click: None, expanded: false, busy: false, queue: VecDeque::new(), st: status::Status { auto: false, kind: Kind::Claude, model: "m1".into(), effort: hx_ai::Effort::Off, 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)))), 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, doc: None, probe: false, kbd: false, stats: None, btw: None, snap: 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 fs_path_popup_opens_live_and_dirs_keep_going() { let d = tempfile::tempdir().unwrap(); std::fs::create_dir_all(d.path().join("alpha/inner")).unwrap(); let mut app = test_app(); for c in format!("look {}/al", d.path().display()).chars() { key(&mut app, KeyCode::Char(c)); } assert!(app.popup.is_some()); key(&mut app, KeyCode::Tab); assert!(app.ed.buf.ends_with("/alpha/"), "{}", app.ed.buf); key(&mut app, KeyCode::Tab); assert!(app.ed.buf.ends_with("/alpha/inner/"), "{}", app.ed.buf); } #[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!["/copy".into(), "/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(); let all = rows.join("\n"); // 10 rows: the popup scrolls to 2 candidates and covers the header assert!(rows[1].contains("commands · 3 of"), "{all}"); assert!( rows[2].starts_with("│ /copy copy") && rows[2].contains("builtin"), "{all}" ); assert!(rows[4].contains("↑↓ select"), "{all}"); assert!(rows[9].starts_with("m1 · ctx"), "{all}"); // 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 (stat, hints) = (row(8), row(9)); assert!(stat.starts_with("m1 · ctx ▱▱▱▱▱▱▱▱▱▱ 0%"), "{stat}"); assert!(hints.starts_with("no match"), "{hints}"); app.hint.clear(); term.draw(|f| draw(f, &mut app)).unwrap(); let buf = term.backend().buffer().clone(); let hints: String = (0..100).map(|x| buf[(x, 9)].symbol().to_string()).collect(); assert!(hints.starts_with(status::KEYS), "{hints}"); key(&mut app, KeyCode::Down); key(&mut app, KeyCode::Up); key(&mut app, KeyCode::Up); assert_eq!(labels(&app).unwrap().1, 2, "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, ["auto", "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 row = |y| -> String { (0..160).map(|x| buf[(x, y)].symbol().to_string()).collect() }; assert!( row(1).contains("│ /skills") && row(1).ends_with("esc × "), "{}", row(1) ); assert!(row(3).contains("│ skills (0):"), "{}", row(3)); 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 rl: Reload = Box::new(|| Ok(("sys".into(), cmd::builtins(&[])))); let ctx = Ctx { agent: &agent, tx: &tx, cwd: t.path(), lsp_status: &ls, reload: &rl, commands: &cmds, }; let mut app = test_app(); app.session_path = old.clone(); app.title = Some("first".into()); // /reload swaps prompt + commands; same prompt twice is reported unchanged app.specs = vec![]; submit(&mut app, "/reload".into(), &ctx).await; assert_eq!(agent.lock().await.system(), "sys"); assert!(app.specs.iter().any(|s| s.name == "reload")); submit(&mut app, "/reload".into(), &ctx).await; assert!( matches!(app.t.items.last(), Some(Item::Info(m)) if m.contains("prompt unchanged")) ); 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 rl: Reload = Box::new(|| Ok(("sys".into(), cmd::builtins(&[])))); let ctx = Ctx { agent: &agent, tx: &tx, cwd: t.path(), lsp_status: &ls, reload: &rl, 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); // 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)))); 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!() } } }