diff --git a/Cargo.lock b/Cargo.lock index 536f165..b6edb19 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1064,6 +1064,7 @@ dependencies = [ "ignore", "ratatui", "serde_json", + "tempfile", "tokio", ] diff --git a/README.md b/README.md index e8e8d3b..374e6c9 100644 --- a/README.md +++ b/README.md @@ -13,10 +13,13 @@ hx -c # continue last session in this directory ``` TUI: `enter` send, `alt-enter`/`ctrl-j` newline, `esc` abort, `ctrl-o` expand tool output, `pgup`/`pgdn` scroll. -`/help` lists commands: builtins (`/model`, `/provider`, `/compact`, `/clear`, `/lsp`, `/mcp`, `/skills`, `/quit`), MCP +`/help` lists commands: builtins (`/model`, `/provider`, `/compact`, `/clear`, `/lsp`, `/mcp`, `/skills`, `/resume`, `/quit`), MCP prompts (`/server:prompt`) and skills. Typing `/` opens a completion popup for commands and their arguments (`up`/`down` select, `tab`/`enter` accept, `esc` close); `tab` completes `@file` (mentioned files are -attached). Messages typed while the agent works are queued. +attached). `ctrl-p` opens a picker over commands, skills, models and recent sessions (enter resumes one). +Lens findings and affected-test results appear after each turn as a `┄ lens ┄` block. At 140+ columns, +`/help`, `/skills`, `/lsp`, `/mcp` open in a side panel (`esc` closes). `NO_COLOR` disables colour, +`HX_ASCII=1` uses ASCII symbols. Messages typed while the agent works are queued. Config: `~/.hx/config.toml`, overridden per project by `.hx/config.toml`: @@ -136,6 +139,7 @@ One JSON object per line on stdout. `type` is one of: | `tool_call` | `id`, `name`, `args` | | `tool_result` | `id`, `name`, `args`, `content`, `is_error` (blocked calls: `is_error: true`, content `blocked: `) | | `info` | `text` | +| `injected` | `texts`: hook reports added to the conversation at turn end (lens diagnostics, affected tests) | | `done` (last line) | `error` (null on success), `usage`, `session` | ### RPC (`hx --mode rpc`) diff --git a/crates/hx-core/src/agent.rs b/crates/hx-core/src/agent.rs index f8ea83f..6a6e1bf 100644 --- a/crates/hx-core/src/agent.rs +++ b/crates/hx-core/src/agent.rs @@ -253,6 +253,7 @@ impl Agent { if o.inject.is_empty() || stop == StopReason::MaxTokens { return Ok(msg); } + self.emit(Event::Injected(o.inject.clone())).await; self.push(Message::user(o.inject.join("\n\n")))?; continue; } @@ -318,6 +319,9 @@ impl Agent { } let mut content: Vec = results.into_iter().flatten().collect(); let o = self.emit(Event::TurnEnd).await; + if !o.inject.is_empty() { + self.emit(Event::Injected(o.inject.clone())).await; + } content.extend(o.inject.into_iter().map(|text| ContentBlock::Text { text })); self.push(Message { role: Role::User, diff --git a/crates/hx-core/src/command.rs b/crates/hx-core/src/command.rs index e95a970..e3d3104 100644 --- a/crates/hx-core/src/command.rs +++ b/crates/hx-core/src/command.rs @@ -60,6 +60,11 @@ pub fn builtins(models: &[&str]) -> Vec { b("clear", "start an empty session", None), b("lsp", "language server status", None), b("skills", "list skills and where they load from", None), + b( + "resume", + "switch to a session file (ctrl-p lists recent)", + Path, + ), b("quit", "exit hx", None), b("exit", "exit hx", None), ] diff --git a/crates/hx-core/src/hook.rs b/crates/hx-core/src/hook.rs index 21998c7..5a6153d 100644 --- a/crates/hx-core/src/hook.rs +++ b/crates/hx-core/src/hook.rs @@ -31,6 +31,8 @@ pub enum Event { Message(Message), /// Human-readable notice for the UI (compaction etc). Info(String), + /// Text hooks injected at turn/agent end (lens reports etc), for display. + Injected(Vec), } impl Event { @@ -56,6 +58,7 @@ impl Event { Event::Stream(e) => json!({"type": "stream", "event": e}), Event::Message(m) => json!({"type": "message", "message": m}), Event::Info(t) => json!({"type": "info", "text": t}), + Event::Injected(t) => json!({"type": "injected", "texts": t}), } } @@ -71,6 +74,7 @@ impl Event { Event::Stream(_) => "stream", Event::Message(_) => "message", Event::Info(_) => "info", + Event::Injected(_) => "injected", } } } diff --git a/crates/hx-tui/Cargo.toml b/crates/hx-tui/Cargo.toml index e3dfc3e..e72a358 100644 --- a/crates/hx-tui/Cargo.toml +++ b/crates/hx-tui/Cargo.toml @@ -17,3 +17,6 @@ tokio = { version = "1.53.1", features = ["rt", "macros", "sync", "time", "rt-mu [lints] workspace = true + +[dev-dependencies] +tempfile = "3.27.0" diff --git a/crates/hx-tui/src/lib.rs b/crates/hx-tui/src/lib.rs index 877fab2..571055d 100644 --- a/crates/hx-tui/src/lib.rs +++ b/crates/hx-tui/src/lib.rs @@ -1,6 +1,7 @@ //! Interactive terminal UI. pub mod editor; +pub mod picker; pub mod theme; pub mod transcript; @@ -103,13 +104,21 @@ struct App { specs: Vec, /// open completion popup and selected row popup: Option<(Completion, usize)>, + picker: Option, + /// right-hand panel on wide terminals: (title, text) of the last listing / expanded output + panel: Option<(String, String)>, + session_path: std::path::PathBuf, + /// terminal at least WIDE columns (set on draw) + wide: bool, /// pending yes/no question from a tool ask: Option<(String, tokio::sync::oneshot::Sender)>, } const KEYS: &str = "enter send · alt-enter/ctrl-j newline · esc/ctrl-c abort · ctrl-o expand · pgup/pgdn scroll · \ tab complete @file / command"; -const PLACEHOLDER: &str = "/ commands · @ files · /help keys"; +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) @@ -187,22 +196,13 @@ pub async fn run(setup: Setup) -> std::io::Result<()> { hint: String::new(), specs, popup: None, + picker: None, + panel: None, + session_path: agent.session.path().to_path_buf(), + wide: false, ask: None, }; - // show resumed history - for m in agent.session.messages() { - for b in &m.content { - match (m.role, b) { - (hx_ai::Role::User, hx_ai::ContentBlock::Text { text }) => { - app.t.push(Item::User(text.clone())) - } - (hx_ai::Role::Assistant, hx_ai::ContentBlock::Text { text }) => { - app.t.push(Item::Assistant(text.clone())) - } - _ => {} - } - } - } + show_history(&mut app.t, &agent.session.messages()); app.t .push(Item::Info(format!("hx · {:?} · {}", app.kind, app.model))); let agent = Arc::new(Mutex::new(agent)); @@ -301,12 +301,92 @@ pub async fn run(setup: Setup) -> std::io::Result<()> { Ok(()) } +/// Text of user/assistant messages, for a resumed session. +fn show_history(t: &mut Transcript, msgs: &[hx_ai::Message]) { + for m in msgs { + for b in &m.content { + match (m.role, b) { + (hx_ai::Role::User, hx_ai::ContentBlock::Text { text }) => { + t.push(Item::User(text.clone())) + } + (hx_ai::Role::Assistant, hx_ai::ContentBlock::Text { text }) => { + t.push(Item::Assistant(text.clone())) + } + _ => {} + } + } + } +} + +/// 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(".")) +} + +/// Picker keys. Returns a line to submit when an entry runs. +fn picker_key(app: &mut App, k: KeyEvent) -> Option { + let p = app.picker.as_mut()?; + match k.code { + KeyCode::Esc => app.picker = None, + KeyCode::Char('c' | 'p') if k.modifiers.contains(KeyModifiers::CONTROL) => { + app.picker = None + } + KeyCode::Up => p.move_sel(-1), + KeyCode::Down | KeyCode::Tab => p.move_sel(1), + KeyCode::Backspace => { + p.query.pop(); + p.sel = 0; + } + KeyCode::Char(c) => { + p.query.push(c); + p.sel = 0; + } + KeyCode::Enter => { + let pick = p.selected(); + app.picker = None; + match pick? { + picker::Pick::Run(l) => return Some(l), + picker::Pick::Insert(l) => { + app.ed.buf = l; + app.ed.cur = app.ed.buf.len(); + live_popup(app); + } + } + } + _ => {} + } + None +} + +/// Show a listing: right panel on wide terminals, transcript otherwise. +fn show(app: &mut App, title: &str, text: String) { + if app.wide { + app.panel = Some((title.into(), text)); + } else { + app.t.push(Item::Info(text)); + } +} + /// Returns a line to submit, if any. fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option { let ctrl = k.modifiers.contains(KeyModifiers::CONTROL); let alt = k.modifiers.contains(KeyModifiers::ALT); let shift = k.modifiers.contains(KeyModifiers::SHIFT); app.hint.clear(); + if app.picker.is_some() { + return picker_key(app, k); + } + if ctrl && k.code == KeyCode::Char('p') { + app.popup = None; + app.picker = Some(picker::Picker::new( + &app.specs, + sessions_dir(app), + &app.session_path, + )); + return None; + } if let Some((c, sel)) = &mut app.popup { let n = c.items.len(); match k.code { @@ -358,6 +438,7 @@ fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option { 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 => { @@ -465,21 +546,36 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) { } match c { "quit" | "exit" => app.quit = true, - "help" => app - .t - .push(Item::Info(format!("{}\n{KEYS}", cmd::help(&app.specs)))), + "help" => { + let h = format!("{}\n\nkeys: {KEYS} · ctrl-p picker", cmd::help(&app.specs)); + show(app, "help", h); + } "skills" => { let dirs = hx_core::context::skill_dirs(&hx_core::context::hx_home(), cwd); - app.t.push(Item::Info(skills_list(&app.specs, &dirs))); + let l = skills_list(&app.specs, &dirs); + show(app, "skills", l); } "lsp" => { let st = lsp_status().await; - app.t.push(Item::Info(if st.is_empty() { + 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) => { + let mut a = agent.lock().await; + app.t = Transcript::default(); + show_history(&mut app.t, &sess.messages()); + app.ctx_tokens = hx_core::agent::estimate_tokens(&sess.messages()); + app.session_path = sess.path().to_path_buf(); + a.session = sess; + app.t.push(Item::Info(format!("resumed {arg}"))); + } + Err(e) => app.t.push(Item::Error(format!("/resume: {e}"))), + }, "model" if arg.is_empty() => app.t.push(Item::Info(format!("model: {}", app.model))), "model" => { agent.lock().await.model = arg.into(); @@ -537,7 +633,7 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) { .t .push(Item::Error(format!("unknown command /{c}; /help"))), Some(f) => match f.await { - Ok(CmdOut::Show(t)) => app.t.push(Item::Info(t)), + Ok(CmdOut::Show(t)) => show(app, c, t), Ok(CmdOut::Send(t)) => line = t, Err(e) => app.t.push(Item::Error(e)), }, @@ -583,6 +679,7 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) { .min(10) as u16 + 2; let act_h = u16::from(app.busy); + app.wide = f.area().width >= WIDE; let [main, act, input, status] = Layout::vertical([ Constraint::Min(3), Constraint::Length(act_h), @@ -591,6 +688,25 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) { ]) .areas(f.area()); + let main = match &app.panel { + Some((title, text)) if app.wide => { + let [m, side] = + Layout::horizontal([Constraint::Min(60), Constraint::Percentage(40)]).areas(main); + f.render_widget( + Paragraph::new(text.as_str()) + .wrap(Wrap { trim: false }) + .block( + Block::new() + .borders(Borders::LEFT) + .border_style(th.dim()) + .title(Span::styled(format!(" {title} · esc "), th.dim())), + ), + side, + ); + m + } + _ => main, + }; let para = Paragraph::new(app.t.lines(app.expanded, main.width)).wrap(Wrap { trim: false }); let total = para.line_count(main.width) as u16; let max_up = total.saturating_sub(main.height); @@ -632,6 +748,9 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) { 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); + } } /// `ctx ▰▰▰▱▱▱▱▱▱▱ 41k/150k · 12.3k↑ 2.1k↓ ~$0.08` left, `Claude · model · 1 queued` right. @@ -801,6 +920,10 @@ mod tests { hint: String::new(), specs: vec![], popup: None, + picker: None, + panel: None, + session_path: "/nonexistent/s.jsonl".into(), + wide: false, ask: None, }; app.t.push(Item::User("hello".into())); @@ -848,6 +971,10 @@ mod tests { hint: String::new(), specs: cmd::builtins(&["sonnet", "opus"]), popup: None, + picker: None, + panel: None, + session_path: "/nonexistent/s.jsonl".into(), + wide: false, ask: None, } } @@ -947,4 +1074,67 @@ mod tests { 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())]); + } } diff --git a/crates/hx-tui/src/picker.rs b/crates/hx-tui/src/picker.rs new file mode 100644 index 0000000..2def895 --- /dev/null +++ b/crates/hx-tui/src/picker.rs @@ -0,0 +1,241 @@ +//! `ctrl-p` picker: one fuzzy list over commands, skills, models and past sessions. + +use crate::theme; +use hx_core::command::{self as cmd, ArgKind, CmdSpec, Source}; +use ratatui::layout::Rect; +use ratatui::text::{Line, Span}; +use ratatui::widgets::{Block, Clear, Paragraph}; +use std::path::{Path, PathBuf}; +use std::time::SystemTime; + +#[derive(Debug, Clone, PartialEq)] +pub enum Pick { + /// Put this into the editor (command that takes args). + Insert(String), + /// Submit this line. + Run(String), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Entry { + pub label: String, + pub detail: String, + pub pick: Pick, +} + +#[derive(Default)] +pub struct Picker { + pub query: String, + pub sel: usize, + all: Vec, +} + +const SESSIONS: usize = 50; + +impl Picker { + pub fn new(specs: &[CmdSpec], sessions_dir: &Path, current: &Path) -> Self { + let mut all = vec![]; + for s in specs { + let tag = match s.source { + Source::Skill(_) => "skill · ", + Source::Mcp => "mcp · ", + _ => "", + }; + all.push(Entry { + label: format!("/{}", s.name), + detail: format!("{tag}{}", s.summary), + pick: match s.args { + ArgKind::None => Pick::Run(format!("/{}", s.name)), + _ => Pick::Insert(format!("/{} ", s.name)), + }, + }); + if let (ArgKind::Enum(v), "model") = (&s.args, s.name.as_str()) { + all.extend(v.iter().map(|m| Entry { + label: format!("model {m}"), + detail: "switch model".into(), + pick: Pick::Run(format!("/model {m}")), + })); + } + } + all.extend(sessions(sessions_dir, current)); + Self { + all, + ..Default::default() + } + } + + /// Entries matching the query, best first. + pub fn matches(&self) -> Vec<&Entry> { + if self.query.is_empty() { + return self.all.iter().collect(); + } + let labels: Vec = self + .all + .iter() + .map(|e| format!("{} {}", e.label, e.detail)) + .collect(); + cmd::rank(labels.iter().map(String::as_str), &self.query, usize::MAX) + .into_iter() + .filter_map(|l| labels.iter().position(|x| x == l).map(|i| &self.all[i])) + .collect() + } + + pub fn selected(&self) -> Option { + self.matches().get(self.sel).map(|e| e.pick.clone()) + } + + pub fn move_sel(&mut self, d: isize) { + let n = self.matches().len().max(1) as isize; + self.sel = (self.sel as isize + d).rem_euclid(n) as usize; + } + + pub fn draw(&self, f: &mut ratatui::Frame) { + let th = theme::t(); + let a = f.area(); + let w = a.width.saturating_sub(4).min(80); + let ms = self.matches(); + // borders + query line + spacer + let h = (ms.len() as u16 + 4).min(a.height.saturating_sub(2)).max(5); + let r = Rect::new(a.x + (a.width - w) / 2, a.y + 1, w, h); + let rows = (h - 4) as usize; + let top = self.sel.saturating_sub(rows.saturating_sub(1)); + let lw = ms + .iter() + .map(|e| e.label.chars().count()) + .max() + .unwrap_or(0) + .min(w as usize / 2); + let mut lines = vec![ + Line::from(vec![ + Span::styled(format!("{} ", th.sym.user), th.accent()), + Span::raw(self.query.clone()), + ]), + Line::default(), + ]; + lines.extend(ms.iter().enumerate().skip(top).take(rows).map(|(i, e)| { + let st = if i == self.sel { th.sel() } else { th.plain() }; + let label: String = e.label.chars().take(lw).collect(); + Line::from(vec![ + Span::styled(format!(" {label: Vec { + let mut v: Vec<(SystemTime, PathBuf)> = std::fs::read_dir(dir) + .into_iter() + .flatten() + .flatten() + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|x| x == "jsonl") && p != current) + .filter_map(|p| Some((std::fs::metadata(&p).ok()?.modified().ok()?, p))) + .collect(); + v.sort_by_key(|a| std::cmp::Reverse(a.0)); + v.into_iter() + .take(SESSIONS) + .filter_map(|(t, p)| { + let first = first_prompt(&p)?; + Some(Entry { + label: format!("session {}", ago(t)), + detail: first, + pick: Pick::Run(format!("/resume {}", p.display())), + }) + }) + .collect() +} + +fn first_prompt(p: &Path) -> Option { + let s = hx_core::session::Session::open(p).ok()?; + s.messages().into_iter().find_map(|m| { + (m.role == hx_ai::Role::User).then_some(())?; + m.content.iter().find_map(|b| match b { + hx_ai::ContentBlock::Text { text } => Some( + text.lines() + .next() + .unwrap_or_default() + .chars() + .take(80) + .collect(), + ), + _ => None, + }) + }) +} + +fn ago(t: SystemTime) -> String { + let s = SystemTime::now() + .duration_since(t) + .unwrap_or_default() + .as_secs(); + match s { + 0..60 => "just now".into(), + 60..3600 => format!("{}m ago", s / 60), + 3600..86400 => format!("{}h ago", s / 3600), + _ => format!("{}d ago", s / 86400), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn entries_filter_and_sessions() { + let t = tempfile::tempdir().unwrap(); + let mut s = hx_core::session::Session::open(t.path().join("1.jsonl")).unwrap(); + s.append(hx_ai::Message::user("review PR 73\nmore".to_string())) + .unwrap(); + hx_core::session::Session::open(t.path().join("2.jsonl")) + .unwrap() + .append(hx_ai::Message::user("current".to_string())) + .unwrap(); + let p = Picker::new( + &cmd::builtins(&["opus", "sonnet"]), + t.path(), + &t.path().join("2.jsonl"), + ); + let labels = |p: &Picker| { + p.matches() + .iter() + .map(|e| e.label.clone()) + .collect::>() + }; + assert!(labels(&p).contains(&"model opus".to_string())); + let sess: Vec<_> = p + .all + .iter() + .filter(|e| e.label.starts_with("session")) + .collect(); + assert_eq!(sess.len(), 1, "current session skipped"); + assert_eq!(sess[0].detail, "review PR 73"); + assert_eq!( + sess[0].pick, + Pick::Run(format!("/resume {}", t.path().join("1.jsonl").display())) + ); + + let mut p = p; + p.query = "PR 73".into(); + assert_eq!(labels(&p)[0], "session just now"); + p.query = "comp".into(); + assert_eq!(p.selected(), Some(Pick::Run("/compact".into()))); + p.query = "/model".into(); + assert_eq!(p.selected(), Some(Pick::Insert("/model ".into()))); + p.query.clear(); + p.sel = 0; + p.move_sel(-1); + assert_eq!(p.sel, p.matches().len() - 1, "wraps to the end"); + } +} diff --git a/crates/hx-tui/src/transcript.rs b/crates/hx-tui/src/transcript.rs index 493d678..ecb58d8 100644 --- a/crates/hx-tui/src/transcript.rs +++ b/crates/hx-tui/src/transcript.rs @@ -23,6 +23,8 @@ pub enum Item { }, Info(String), Error(String), + /// Hook reports injected at turn end (`[lens] …`), shown as the lens block. + Lens(Vec), } #[derive(Default)] @@ -85,6 +87,7 @@ impl Transcript { } } Event::Info(s) => self.push(Item::Info(s.clone())), + Event::Injected(t) => self.push(Item::Lens(t.clone())), _ => {} } } @@ -286,6 +289,7 @@ fn render(it: &Item, expanded: bool, width: usize, out: &mut Vec>) th.dim().add_modifier(Modifier::ITALIC), )), Item::Info(s) => out.push(Line::styled(format!("{} {s}", th.sym.info), th.dim())), + Item::Lens(texts) => lens_block(texts, expanded, width, out), Item::Error(s) => out.push(Line::styled(format!("{} {s}", th.sym.err), th.err())), Item::Tool { name, @@ -305,6 +309,88 @@ fn render(it: &Item, expanded: bool, width: usize, out: &mut Vec>) } } +/// `┄ lens ┄┄┄` rule, then per report a summary line (errors red, all-pass green) and, +/// collapsed, the first findings; `ctrl-o` shows all. +fn lens_block(texts: &[String], expanded: bool, width: usize, out: &mut Vec>) { + let th = theme::t(); + let rule = if th.sym.ok == "+" { "-" } else { "┄" }; + let head = format!(" {rule} lens "); + let fill = rule.repeat(width.saturating_sub(Span::raw(head.as_str()).width())); + out.push(Line::styled(format!("{head}{fill}"), th.dim())); + for t in texts { + let mut lines = t.lines(); + let first = lines.next().unwrap_or_default(); + let title = first + .strip_prefix("[lens] ") + .unwrap_or(first) + .trim_end_matches(':'); + let rest: Vec<&str> = lines.collect(); + // counts only mean something for diagnostics; test output quotes compiler lines + let diag = title.starts_with("diagnostics"); + let count = |k: &str| rest.iter().filter(|l| diag && l.contains(k)).count(); + let (errors, warnings) = (count(" error: "), count(" warning: ")); + let (mark, st) = if title.contains("failing") || errors > 0 { + (th.sym.err, th.err()) + } else if warnings > 0 { + ("!", th.warn()) + } else { + (th.sym.ok, th.ok()) + }; + let mut counts = vec![]; + if errors > 0 { + counts.push(format!( + "{errors} error{}", + if errors == 1 { "" } else { "s" } + )); + } + if warnings > 0 { + counts.push(format!( + "{warnings} warning{}", + if warnings == 1 { "" } else { "s" } + )); + } + let counts = if counts.is_empty() { + String::new() + } else { + format!(" · {}", counts.join(", ")) + }; + out.push(Line::from(vec![ + Span::styled(format!(" {mark} "), st), + Span::raw(title.to_string()), + Span::styled(counts, th.dim()), + ])); + let n = if expanded { + rest.len() + } else { + rest.len().min(LENS_PREVIEW) + }; + for l in &rest[..n] { + let ls = if l.contains(" error: ") { + th.err() + } else if l.contains(" warning: ") { + th.warn() + } else { + th.dim() + }; + out.push(Line::from(vec![ + Span::styled(format!(" {} ", th.sym.gutter), th.dim()), + Span::styled(l.trim_start().to_string(), ls), + ])); + } + if n < rest.len() { + out.push(Line::styled( + format!( + " {} {} more lines (ctrl-o)", + th.sym.ellipsis, + rest.len() - n + ), + th.dim(), + )); + } + } +} + +const LENS_PREVIEW: usize = 4; const DIFF_PREVIEW: usize = 6; const ERR_TAIL: usize = 5; @@ -557,6 +643,31 @@ mod tests { assert_eq!(text(&out), [" a b c"]); } + #[test] + fn lens() { + let mut t = Transcript::default(); + t.apply(&Event::Injected(vec![ + "[lens] diagnostics for files changed this turn:\nsrc/a.rs:\n 3:1 error: E0308 mismatched (rust-analyzer)\n 9:2 warning: unused (rust-analyzer)\n 10:2 warning: x (r)\n 11:2 warning: y (r)\n 12:2 warning: z (r)".into(), + "[lens] tests: all 21 selected tests pass now".into(), + ])); + let s = text(&t.lines(false, 30)); + assert_eq!(s[0].chars().count(), 30); + assert!(s[0].starts_with(" ┄ lens ┄")); + assert_eq!( + s[1], + " ✗ diagnostics for files changed this turn · 1 error, 4 warnings" + ); + assert_eq!(s[2], " │ src/a.rs:"); + assert_eq!(s[3], " │ 3:1 error: E0308 mismatched (rust-analyzer)"); + assert_eq!(s[6], " … 2 more lines (ctrl-o)"); + assert_eq!(s[7], " ✓ tests: all 21 selected tests pass now"); + assert_eq!( + text(&t.lines(true, 30)).len(), + 10, + "expanded shows every finding" + ); + } + #[test] fn activity() { let l = activity_line("bash", Duration::from_millis(12_900), 2); diff --git a/tests/lens_e2e.sh b/tests/lens_e2e.sh index b5511ed..9ea92ed 100755 --- a/tests/lens_e2e.sh +++ b/tests/lens_e2e.sh @@ -17,4 +17,13 @@ HOME="$tmp/home" HX_BASE_URL="http://127.0.0.1:$port" "$root/target/debug/hx" -p grep -q "FINISHED lens=clean" "$tmp/out" || { echo "--- out"; cat "$tmp/out"; echo "--- err"; cat "$tmp/err"; exit 1; } grep -q "42" src/lib.rs curl -s "http://127.0.0.1:$port/" | grep -q 'mismatched types' +# same run in json mode: the lens report reaches UIs as an `injected` event +kill $srv; python3 "$root/tests/fake_lens.py" $port & srv=$!; sleep 0.5 +git checkout -q -- . 2>/dev/null || rm -f src/lib.rs +HOME="$tmp/home" HX_BASE_URL="http://127.0.0.1:$port" "$root/target/debug/hx" -p "add f" --mode json > "$tmp/json" 2> "$tmp/err" || { cat "$tmp/err"; exit 1; } +python3 - "$tmp/json" <<'PY' || { echo "FAIL: no injected lens event"; exit 1; } +import json, sys +ev = [json.loads(l) for l in open(sys.argv[1])] +assert any(e["type"] == "injected" and any("[lens]" in t and "mismatched types" in t for t in e["texts"]) for e in ev) +PY echo "lens e2e ok" diff --git a/tests/tui_smoke.py b/tests/tui_smoke.py index 5b71134..8e91704 100644 --- a/tests/tui_smoke.py +++ b/tests/tui_smoke.py @@ -9,6 +9,9 @@ os.makedirs(f"{tmp}/home/.hx"); os.makedirs(f"{tmp}/repo") open(f"{tmp}/home/.hx/auth.json", "w").write(json.dumps({"claude": {"access": "fake-token", "refresh": "r", "expires": 99999999999999}})) open(f"{tmp}/repo/notes.md", "w").write("NOTES\n") os.makedirs(f"{tmp}/home/.agents/skills/deploy") +slug = "".join(c if c.isascii() and c.isalnum() else "-" for c in f"{tmp}/repo").strip("-") +os.makedirs(f"{tmp}/home/.hx/sessions/{slug}") +open(f"{tmp}/home/.hx/sessions/{slug}/1.jsonl", "w").write(json.dumps({"id": 0, "parent": None, "message": {"role": "user", "content": [{"type": "text", "text": "OLDPROMPT about parsers"}]}}) + "\n") os.makedirs(f"{tmp}/repo/.agents/skills/lint") open(f"{tmp}/repo/.agents/skills/lint/SKILL.md", "w").write("---\nname: lint\ndescription: project lint\n---\nBODY\n") open(f"{tmp}/home/.agents/skills/deploy/SKILL.md", "w").write("---\nname: deploy\ndescription: ship it\n---\nBODY\n") @@ -64,6 +67,11 @@ send(b"/model claude-opus-4-1\r") check("model switch", "model → claude-opus-4-1") send(b"/bogus\r") check("unknown cmd", "unknown command /bogus") +send(b"\x10") # ctrl-p +send(b"OLDPROMPT") +check("picker lists past session", "session just now") +send(b"\r", 1) +check("picker resumes session", "resumed ") send(b"\x03", 1) # ctrl-c on empty -> quit try: _, st = os.waitpid(pid, 0)