M9: lens block, ctrl-p picker, /resume, wide side panel
ci / check (push) Canceled after 0s
ci / check (pull_request) Canceled after 0s

Closes #78, closes #82, closes #83
This commit is contained in:
hermes committed 2026-10-01 09:16:59 +00:00
1 parent b3960a09ed
commit d7aeaf0bb9
11 files changed
+604 -24

No files matched your search

+212 -22
View File
@@ -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<CmdSpec>,
/// open completion popup and selected row
popup: Option<(Completion, usize)>,
picker: Option<picker::Picker>,
/// 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<bool>)>,
}
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<String> {
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<String> {
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<String> {
let ctrl = k.modifiers.contains(KeyModifiers::CONTROL);
let alt = k.modifiers.contains(KeyModifiers::ALT);
let shift = k.modifiers.contains(KeyModifiers::SHIFT);
app.hint.clear();
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<String> {
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<String> = (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())]);
}
}
+241
View File
@@ -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<Entry>,
}
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<String> = 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<Pick> {
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:<lw$} "), st),
Span::styled(e.detail.clone(), if i == self.sel { st } else { th.dim() }),
])
}));
f.render_widget(Clear, r);
f.render_widget(
Paragraph::new(lines).block(
Block::bordered()
.border_style(th.dim())
.title(Span::styled(" ctrl-p ", th.dim())),
),
r,
);
f.set_cursor_position((r.x + 3 + self.query.chars().count() as u16, r.y + 1));
}
}
/// Recent sessions in `dir` (newest first, current one skipped): label = age, detail = first prompt.
fn sessions(dir: &Path, current: &Path) -> Vec<Entry> {
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<String> {
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::<Vec<_>>()
};
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");
}
}
+111
View File
@@ -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<String>),
}
#[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<Line<'static>>)
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<Line<'static>>)
}
}
/// `┄ 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<Line<'static>>) {
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);