M9: theme, turn layout, footer, input, activity line
ci / check (push) Canceled after 0s
ci / check (pull_request) Canceled after 0s

Closes #76, closes #77, closes #79, closes #80, closes #81
This commit is contained in:
hermes committed 2026-10-01 08:56:27 +00:00
1 parent 33539f64ae
commit b0b22b4061
4 files changed
+667 -186

No files matched your search

+171 -79
View File
@@ -1,6 +1,7 @@
//! Interactive terminal UI.
pub mod editor;
pub mod theme;
pub mod transcript;
use crossterm::event::{
@@ -14,12 +15,13 @@ use hx_core::agent::{AbortHandle, Agent};
use hx_core::command::{self as cmd, CmdSpec, Completion, Source};
use hx_core::hook::{Event, Hook, HookAction};
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::{Color, Style};
use ratatui::style::Modifier;
use ratatui::text::Line;
use ratatui::text::Span;
use ratatui::widgets::{Block, Borders, Clear, Paragraph, Wrap};
use std::collections::VecDeque;
use std::sync::Arc;
use std::time::Instant;
use tokio::sync::{Mutex, mpsc};
use transcript::{Item, Transcript};
@@ -91,6 +93,11 @@ struct App {
model: String,
usage: Usage,
ctx_tokens: usize,
/// auto-compact threshold: the context bar's 100%
ctx_max: usize,
pricing: fn(&str) -> Option<hx_ai::Pricing>,
/// when the current run started (activity line)
since: Instant,
quit: bool,
hint: String,
specs: Vec<CmdSpec>,
@@ -100,8 +107,9 @@ struct App {
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 tools · pgup/pgdn scroll · \
tab complete @file / command · /help commands";
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";
pub fn project_files(root: &std::path::Path) -> Vec<String> {
ignore::WalkBuilder::new(root)
@@ -172,6 +180,9 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
model: agent.model.clone(),
usage: Usage::default(),
ctx_tokens: hx_core::agent::estimate_tokens(&agent.session.messages()),
ctx_max: agent.compact_at,
pricing,
since: Instant::now(),
quit: false,
hint: String::new(),
specs,
@@ -192,10 +203,8 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
}
}
}
app.t.push(Item::Info(format!(
"hx · {:?} · {} · {KEYS}",
app.kind, app.model
)));
app.t
.push(Item::Info(format!("hx · {:?} · {}", app.kind, app.model)));
let agent = Arc::new(Mutex::new(agent));
let ctx = Ctx {
@@ -495,6 +504,7 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
},
"compact" => {
app.busy = true;
app.since = Instant::now();
app.t.push(Item::Info("compacting…".into()));
let (agent, tx) = (agent.clone(), tx.clone());
tokio::spawn(async move {
@@ -552,6 +562,7 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
line.clone()
}));
app.busy = true;
app.since = Instant::now();
let prompt = expand_mentions(&line, cwd);
let (agent, tx) = (agent.clone(), tx.clone());
tokio::spawn(async move {
@@ -567,72 +578,128 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
}
fn draw(f: &mut ratatui::Frame, app: &mut App) {
let th = theme::t();
let input_h = (app.ed.buf.lines().count().max(1) + usize::from(app.ed.buf.ends_with('\n')))
.min(10) as u16
+ 2;
let [main, status, input] = Layout::vertical([
let act_h = u16::from(app.busy);
let [main, act, input, status] = Layout::vertical([
Constraint::Min(3),
Constraint::Length(1),
Constraint::Length(act_h),
Constraint::Length(input_h),
Constraint::Length(1),
])
.areas(f.area());
let para = Paragraph::new(app.t.lines(app.expanded)).wrap(Wrap { trim: false });
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);
app.scroll = app.scroll.min(max_up);
f.render_widget(para.scroll((max_up - app.scroll, 0)), main);
let spin = if app.busy {
["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"][(std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_millis()
/ 80
% 10) as usize]
} else {
" "
};
let q = if app.queue.is_empty() {
String::new()
} else {
format!(" · {} queued", app.queue.len())
};
let up = if app.scroll > 0 {
format!(" · ↑{}", app.scroll)
} else {
String::new()
};
let st = if let Some((q, _)) = &app.ask {
format!("[y/n] {q}")
} else if app.hint.is_empty() {
format!(
"{spin} {:?} · {} · ctx {}k · {}↑ {}↓{q}{up}",
app.kind,
app.model,
app.ctx_tokens / 1000,
app.usage.input_tokens + app.usage.cache_read_tokens,
app.usage.output_tokens
)
} else {
app.hint.clone()
};
f.render_widget(
Line::styled(st, Style::default().fg(Color::DarkGray)),
status,
);
if app.busy {
let (what, t0) = app.t.running().unwrap_or(("thinking…".into(), app.since));
let frame = (app.since.elapsed().as_millis() / 80) as usize;
f.render_widget(transcript::activity_line(&what, t0.elapsed(), frame), act);
}
let block = Block::default()
.borders(Borders::TOP | Borders::BOTTOM)
.border_style(Style::default().fg(Color::DarkGray));
.border_style(th.dim());
let inner = block.inner(input);
f.render_widget(Paragraph::new(app.ed.buf.as_str()).block(block), input);
if let Some((c, sel)) = &app.popup {
draw_popup(f, c, *sel, input);
}
f.render_widget(block, input);
let [gut, text] = Layout::horizontal([Constraint::Length(2), Constraint::Min(1)]).areas(inner);
f.render_widget(
Span::styled(
format!("{} ", th.sym.user),
th.accent().add_modifier(Modifier::BOLD),
),
gut,
);
let (r, c) = app.ed.cursor_rc();
let skip = (r as u16).saturating_sub(inner.height.saturating_sub(1));
f.set_cursor_position((inner.x + c as u16, inner.y + r as u16 - skip));
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 {
f.render_widget(Paragraph::new(app.ed.buf.as_str()).scroll((skip, 0)), text);
}
f.render_widget(footer(app, status.width), status);
if let Some((comp, sel)) = &app.popup {
let col = Span::raw(
&app.ed.buf[app.ed.buf[..comp.start].rfind('\n').map_or(0, |i| i + 1)..comp.start],
)
.width() as u16;
draw_popup(f, comp, *sel, text.x + col, input.y);
}
f.set_cursor_position((text.x + c as u16, text.y + r as u16 - skip));
}
/// `ctx ▰▰▰▱▱▱▱▱▱▱ 41k/150k · 12.3k↑ 2.1k↓ ~$0.08` left, `Claude · model · 1 queued` right.
/// Hints replace the right side; a pending y/n question takes the whole line.
fn footer(app: &App, width: u16) -> Line<'static> {
let th = theme::t();
if let Some((q, _)) = &app.ask {
return Line::styled(format!("[y/n] {q}"), th.warn().add_modifier(Modifier::BOLD));
}
let k = |n: u64| {
if n >= 1000 {
format!("{:.1}k", n as f64 / 1000.0)
} else {
n.to_string()
}
};
let frac = app.ctx_tokens as f64 / app.ctx_max.max(1) as f64;
let full = ((frac * 10.0).round() as usize).min(10);
let bar_st = match frac {
f if f >= 0.9 => th.err(),
f if f >= 0.7 => th.warn(),
_ => th.accent(),
};
let cost = (app.pricing)(&app.model)
.map(|p| format!(" ~${:.2}", app.usage.cost(&p)))
.unwrap_or_default();
let mut left = vec![
Span::styled("ctx ", th.dim()),
Span::styled(th.sym.bar_full.repeat(full), bar_st),
Span::styled(th.sym.bar_empty.repeat(10 - full), th.dim()),
Span::styled(
format!(" {}k/{}k", app.ctx_tokens / 1000, app.ctx_max / 1000),
th.dim(),
),
Span::styled(
format!(
" · {}↑ {}↓{cost}",
k(app.usage.input_tokens + app.usage.cache_read_tokens),
k(app.usage.output_tokens)
),
th.dim(),
),
];
let right = if app.hint.is_empty() {
let mut v = vec![format!("{:?}", app.kind), app.model.clone()];
if !app.queue.is_empty() {
v.push(format!("{} queued", app.queue.len()));
}
if app.scroll > 0 {
v.push(format!("↑{}", app.scroll));
}
Span::styled(v.join(" · "), th.dim())
} else {
Span::styled(app.hint.clone(), th.accent())
};
let w = width as usize;
let lw = |l: &[Span]| l.iter().map(Span::width).sum::<usize>();
// narrow terminals: drop token counts, then the whole left side
if lw(&left) + right.width() + 1 > w {
left.pop();
}
if lw(&left) + right.width() + 1 > w {
return Line::from(right);
}
let pad = w - lw(&left) - right.width();
left.push(Span::raw(" ".repeat(pad.max(1))));
left.push(right);
Line::from(left)
}
/// `/skills`: each skill with its file, then the searched dirs (so a missing skill is easy to debug).
@@ -662,35 +729,40 @@ fn skills_list(specs: &[CmdSpec], dirs: &[std::path::PathBuf]) -> String {
)
}
/// Candidates stacked just above the input box.
fn draw_popup(f: &mut ratatui::Frame, c: &Completion, sel: usize, input: Rect) {
let h = (c.items.len() as u16).min(input.y);
let w = c
/// Bordered candidate list ending just above row `bottom`, starting at column `x` (the token).
fn draw_popup(f: &mut ratatui::Frame, c: &Completion, sel: usize, x: u16, bottom: u16) {
let th = theme::t();
let lw = c
.items
.iter()
.map(|i| i.label.chars().count() + i.detail.chars().count() + 3)
.map(|i| i.label.chars().count())
.max()
.unwrap_or(0)
.min(f.area().width as usize) as u16;
let area = Rect::new(input.x, input.y - h, w, h);
.unwrap_or(0);
let lines: Vec<Line> = c
.items
.iter()
.enumerate()
.map(|(n, i)| {
let base = if n == sel {
Style::default().bg(Color::DarkGray).fg(Color::White)
} else {
Style::default()
};
let base = if n == sel { th.sel() } else { th.plain() };
Line::from(vec![
Span::styled(format!(" {} ", i.label), base),
Span::styled(format!("{} ", i.detail), base.fg(Color::Gray)),
Span::styled(format!(" {:<lw$} ", i.label), base),
Span::styled(
format!("{} ", i.detail),
if n == sel { base } else { th.dim() },
),
])
})
.collect();
f.render_widget(Clear, area);
f.render_widget(Paragraph::new(lines), area);
let area = f.area();
let w = (lines.iter().map(Line::width).max().unwrap_or(0) 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_style(th.dim())),
r,
);
}
#[cfg(test)]
@@ -722,6 +794,9 @@ mod tests {
model: "m1".into(),
usage: Usage::default(),
ctx_tokens: 12_000,
ctx_max: 150_000,
pricing: |_| None,
since: Instant::now(),
quit: false,
hint: String::new(),
specs: vec![],
@@ -738,10 +813,11 @@ mod tests {
.map(|y| (0..40).map(|x| buf[(x, y)].symbol().to_string()).collect())
.collect();
let all = rows.join("\n");
assert!(all.contains("> hello"), "{all}");
assert!(all.contains("hi there"), "{all}");
assert!(all.contains("Claude · m1 · ctx 12k"), "{all}");
assert!(rows[8].starts_with("typing"), "{all}");
assert!(all.contains("❯ hello"), "{all}");
assert!(all.contains("◆ hi there"), "{all}");
assert!(rows[7].starts_with("❯ typing"), "{all}");
assert!(rows[9].starts_with("ctx ▰▱▱▱▱▱▱▱▱▱ 12k/150k "), "{all}");
assert!(rows[9].ends_with("Claude · m1"), "{all}");
}
fn key(app: &mut App, code: KeyCode) -> Option<String> {
@@ -765,6 +841,9 @@ mod tests {
model: "m1".into(),
usage: Usage::default(),
ctx_tokens: 0,
ctx_max: 150_000,
pricing: |_| None,
since: Instant::now(),
quit: false,
hint: String::new(),
specs: cmd::builtins(&["sonnet", "opus"]),
@@ -814,11 +893,24 @@ mod tests {
let rows: Vec<String> = (0..10)
.map(|y| (0..40).map(|x| buf[(x, y)].symbol().to_string()).collect())
.collect();
assert!(
rows[5].starts_with(" /clear start an empty session"),
assert_eq!(
rows[3], " │ /clear start an empty session │ ",
"{rows:#?}"
);
assert!(rows[6].starts_with(" /compact summarize"), "{rows:#?}");
assert!(rows[4].starts_with(" │ /compact summarize"), "{rows:#?}");
assert!(rows[9].ends_with("Claude · m1"), "{rows:#?}");
// footer at 100 cols, and a hint replacing only the right side
app.hint = "no match".into();
let mut term = ratatui::Terminal::new(TestBackend::new(100, 10)).unwrap();
term.draw(|f| draw(f, &mut app)).unwrap();
let buf = term.backend().buffer().clone();
let last: String = (0..100).map(|x| buf[(x, 9)].symbol().to_string()).collect();
assert!(
last.starts_with("ctx ▱▱▱▱▱▱▱▱▱▱ 0k/150k · 0↑ 0↓") && last.ends_with("no match"),
"{last}"
);
app.hint.clear();
key(&mut app, KeyCode::Down);
key(&mut app, KeyCode::Up);
key(&mut app, KeyCode::Up);