Merge main

This commit is contained in:
hermes committed 2026-10-09 19:35:46 +00:00
commit 8ccc189e9c
12 files changed
+1132 -470

No files matched your search

+3 -3
View File
@@ -730,9 +730,9 @@ async fn main() -> Result<()> {
agent.tools.add(hx_lens::LspTool::new(mgr.clone())); agent.tools.add(hx_lens::LspTool::new(mgr.clone()));
let tmode = lcfg.tests.unwrap_or(hx_lens::testrun::TestMode::TurnEnd); let tmode = lcfg.tests.unwrap_or(hx_lens::testrun::TestMode::TurnEnd);
if tmode != hx_lens::testrun::TestMode::Off { if tmode != hx_lens::testrun::TestMode::Off {
agent let tl = hx_lens::testrun::TestLens::new(cwd.clone(), tmode);
.bus let _ = tl.state.set(agent.cx.state.clone());
.add(hx_lens::testrun::TestLens::new(cwd.clone(), tmode)); agent.bus.add(tl);
} }
// rust-analyzer & co are slow to index: start servers for languages present at the top level now // rust-analyzer & co are slow to index: start servers for languages present at the top level now
let probe: Vec<_> = std::fs::read_dir(&cwd) let probe: Vec<_> = std::fs::read_dir(&cwd)
+24
View File
@@ -73,6 +73,30 @@ pub struct State {
pub sub_usage: Mutex<hx_ai::Usage>, pub sub_usage: Mutex<hx_ai::Usage>,
/// Subagents of this session (see [`subagent`]). /// Subagents of this session (see [`subagent`]).
pub subs: subagent::Subs, pub subs: subagent::Subs,
/// Last output lines of running `bash` calls, keyed by command (UI live view).
/// ponytail: keyed by command text, so two identical commands running at once share a tail;
/// key by call id once ToolCtx carries it.
pub live: Mutex<HashMap<String, String>>,
/// Structured last lens report for side panels.
pub lens: Mutex<LensView>,
}
/// Lens results of the last turn, structured (the injected text is for the model).
#[derive(Debug, Clone, Default, PartialEq)]
pub struct LensView {
pub diags: Vec<Diag>,
/// (test name, passed); None = no test run yet
pub tests: Option<Vec<(String, bool)>>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Diag {
/// workspace-relative
pub file: String,
pub line: u32,
pub col: u32,
pub error: bool,
pub message: String,
} }
impl State { impl State {
+15
View File
@@ -232,6 +232,7 @@ impl Lens {
let mut last = self.last.lock().await; let mut last = self.last.lock().await;
let mut sections = vec![]; let mut sections = vec![];
let mut fresh = vec![];
for f in &files { for f in &files {
let rel = PathBuf::from(self.rel(f)); let rel = PathBuf::from(self.rel(f));
let fseq = self.seq.file(f); let fseq = self.seq.file(f);
@@ -241,6 +242,13 @@ impl Lens {
.collect(); .collect();
mine.sort_by_key(|x| (x.severity, x.line, x.col)); mine.sort_by_key(|x| (x.severity, x.line, x.col));
mine.dedup_by(|a, b| a.line == b.line && a.message == b.message); mine.dedup_by(|a, b| a.line == b.line && a.message == b.message);
fresh.extend(mine.iter().map(|x| hx_core::Diag {
file: rel.display().to_string(),
line: x.line,
col: x.col,
error: x.severity == 1,
message: x.message.clone(),
}));
let body = format_findings(&mine); let body = format_findings(&mine);
// freshness gate: file changed on disk while we were checking -> label, don't trust // freshness gate: file changed on disk while we were checking -> label, don't trust
let stale = self.seq.file(f) > start_seq; let stale = self.seq.file(f) > start_seq;
@@ -266,6 +274,13 @@ impl Lens {
)); ));
} }
drop(last); drop(last);
// UI view: checked files get their current findings, others keep theirs
if let Some(st) = self.state.get() {
let checked: Vec<String> = files.iter().map(|f| self.rel(f)).collect();
let mut v = st.lens.lock().unwrap_or_else(|e| e.into_inner());
v.diags.retain(|d| !checked.contains(&d.file));
v.diags.extend(fresh);
}
let mut notes: Vec<String> = errs; let mut notes: Vec<String> = errs;
notes.extend( notes.extend(
self.notes self.notes
+30 -4
View File
@@ -30,6 +30,8 @@ pub struct Failure {
#[derive(Debug, Clone, PartialEq, Default)] #[derive(Debug, Clone, PartialEq, Default)]
pub struct Outcome { pub struct Outcome {
pub passed: usize, pub passed: usize,
/// names of passing tests, when the framework reports them
pub ok_names: Vec<String>,
pub failures: Vec<Failure>, pub failures: Vec<Failure>,
} }
@@ -207,7 +209,7 @@ pub fn parse_libtest(s: &str) -> Outcome {
for line in s.lines() { for line in s.lines() {
if let Some(rest) = line.strip_prefix("test ") { if let Some(rest) = line.strip_prefix("test ") {
if let Some(name) = rest.strip_suffix(" ... ok") { if let Some(name) = rest.strip_suffix(" ... ok") {
let _ = name; out.ok_names.push(name.to_string());
out.passed += 1; out.passed += 1;
} else if let Some(name) = rest.strip_suffix(" ... FAILED") { } else if let Some(name) = rest.strip_suffix(" ... FAILED") {
out.failures.push(Failure { out.failures.push(Failure {
@@ -307,7 +309,10 @@ pub fn parse_junit(s: &str, root: &Path) -> Outcome {
}); });
} }
None if body.contains("<skipped") => {} None if body.contains("<skipped") => {}
None => out.passed += 1, None => {
out.ok_names.push(name);
out.passed += 1
}
} }
rest = &rest[body_end.min(rest.len())..]; rest = &rest[body_end.min(rest.len())..];
} }
@@ -326,7 +331,11 @@ pub fn parse_jest(s: &str) -> Result<Outcome, String> {
.unwrap_or_default(); .unwrap_or_default();
for a in &asserts { for a in &asserts {
match a["status"].as_str() { match a["status"].as_str() {
Some("passed") => out.passed += 1, Some("passed") => {
out.ok_names
.push(a["fullName"].as_str().unwrap_or_default().to_string());
out.passed += 1
}
Some("failed") => out.failures.push(Failure { Some("failed") => out.failures.push(Failure {
name: a["fullName"].as_str().unwrap_or_default().to_string(), name: a["fullName"].as_str().unwrap_or_default().to_string(),
file: file.clone(), file: file.clone(),
@@ -371,7 +380,10 @@ pub fn parse_go(s: &str) -> Outcome {
.entry((pkg, test)) .entry((pkg, test))
.or_default() .or_default()
.push_str(e["Output"].as_str().unwrap_or_default()), .push_str(e["Output"].as_str().unwrap_or_default()),
Some("pass") if !test.is_empty() => out.passed += 1, Some("pass") if !test.is_empty() => {
out.ok_names.push(format!("{pkg}.{test}"));
out.passed += 1
}
Some("fail") => { Some("fail") => {
// package-level fail without tests = build failure; with tests it's just the summary // package-level fail without tests = build failure; with tests it's just the summary
let has_test_fail = out.failures.iter().any(|f| f.name.starts_with(&pkg)); let has_test_fail = out.failures.iter().any(|f| f.name.starts_with(&pkg));
@@ -478,6 +490,8 @@ pub struct TestLens {
pending: tokio::sync::Mutex<Vec<PathBuf>>, pending: tokio::sync::Mutex<Vec<PathBuf>>,
/// last report, so an unchanged failure set isn't repeated every turn /// last report, so an unchanged failure set isn't repeated every turn
last: tokio::sync::Mutex<String>, last: tokio::sync::Mutex<String>,
/// agent state: each run's per-test results go to `state.lens.tests` for the UI
pub state: std::sync::OnceLock<std::sync::Arc<hx_core::State>>,
} }
impl TestLens { impl TestLens {
@@ -489,6 +503,7 @@ impl TestLens {
cap: 3000, cap: 3000,
pending: Default::default(), pending: Default::default(),
last: Default::default(), last: Default::default(),
state: Default::default(),
} }
} }
@@ -509,6 +524,7 @@ impl TestLens {
let mut fails = vec![]; let mut fails = vec![];
let mut notes = vec![]; let mut notes = vec![];
let mut passed = 0; let mut passed = 0;
let mut ok_names = vec![];
let mut ran = 0; let mut ran = 0;
for r in &runs { for r in &runs {
if !installed(r.adapter, &r.root) { if !installed(r.adapter, &r.root) {
@@ -525,6 +541,7 @@ impl TestLens {
match run(r, self.timeout).await { match run(r, self.timeout).await {
Ok(o) => { Ok(o) => {
passed += o.passed; passed += o.passed;
ok_names.extend(o.ok_names);
fails.extend(o.failures); fails.extend(o.failures);
} }
Err(e) => fails.push(Failure { Err(e) => fails.push(Failure {
@@ -534,6 +551,14 @@ impl TestLens {
}), }),
} }
} }
if ran > 0
&& let Some(st) = self.state.get()
{
let mut v: Vec<(String, bool)> =
fails.iter().map(|f| (f.name.clone(), false)).collect();
v.extend(ok_names.into_iter().map(|n| (n, true)));
st.lens.lock().unwrap_or_else(|e| e.into_inner()).tests = Some(v);
}
let stale = snap(&changed) != before; let stale = snap(&changed) != before;
let mut last = self.last.lock().await; let mut last = self.last.lock().await;
let body = if fails.is_empty() { let body = if fails.is_empty() {
@@ -633,6 +658,7 @@ mod t {
let s = "running 3 tests\ntest a::ok ... ok\ntest a::bad ... FAILED\ntest b ... ignored\n\nfailures:\n\n---- a::bad stdout ----\n\nthread 'a::bad' panicked at src/lib.rs:9:5:\nassertion `left == right` failed\n left: 5\n right: 4\nnote: run with `RUST_BACKTRACE=1` environment variable to display a backtrace\n\n\nfailures:\n a::bad\n\ntest result: FAILED. 1 passed; 1 failed\n"; let s = "running 3 tests\ntest a::ok ... ok\ntest a::bad ... FAILED\ntest b ... ignored\n\nfailures:\n\n---- a::bad stdout ----\n\nthread 'a::bad' panicked at src/lib.rs:9:5:\nassertion `left == right` failed\n left: 5\n right: 4\nnote: run with `RUST_BACKTRACE=1` environment variable to display a backtrace\n\n\nfailures:\n a::bad\n\ntest result: FAILED. 1 passed; 1 failed\n";
let o = parse_libtest(s); let o = parse_libtest(s);
assert_eq!(o.passed, 1); assert_eq!(o.passed, 1);
assert_eq!(o.ok_names, ["a::ok"]);
assert_eq!(o.failures.len(), 1); assert_eq!(o.failures.len(), 1);
assert_eq!(o.failures[0].name, "a::bad"); assert_eq!(o.failures[0].name, "a::bad");
assert!( assert!(
+45 -3
View File
@@ -314,6 +314,9 @@ impl Tool for AskUser {
} }
} }
/// Bytes of running bash output kept for the live view.
const LIVE_TAIL: usize = 2048;
pub struct Bash; pub struct Bash;
#[async_trait] #[async_trait]
impl Tool for Bash { impl Tool for Bash {
@@ -340,14 +343,37 @@ impl Tool for Bash {
// own process group so timeouts kill children too // own process group so timeouts kill children too
#[cfg(unix)] #[cfg(unix)]
c.process_group(0); c.process_group(0);
let child = match c.spawn() { let mut child = match c.spawn() {
Ok(c) => c, Ok(c) => c,
Err(e) => return ToolResult::err(format!("spawn: {e}")), Err(e) => return ToolResult::err(format!("spawn: {e}")),
}; };
let pid = child.id(); let pid = child.id();
let res = tokio::time::timeout(Duration::from_secs(secs), child.wait_with_output()).await; // read output as it comes so the UI can show the last lines live (state.live)
let mut so = child.stdout.take().expect("piped");
let live = &cx.state.live;
let run = async {
use tokio::io::AsyncReadExt;
let mut out = vec![];
let mut chunk = [0u8; 8192];
loop {
match so.read(&mut chunk).await {
Ok(0) | Err(_) => break,
Ok(n) => {
out.extend_from_slice(&chunk[..n]);
let start = out.len().saturating_sub(LIVE_TAIL);
live.lock().unwrap_or_else(|e| e.into_inner()).insert(
cmd.to_string(),
String::from_utf8_lossy(&out[start..]).into(),
);
}
}
}
child.wait().await.map(|st| (out, st))
};
let res = tokio::time::timeout(Duration::from_secs(secs), run).await;
live.lock().unwrap_or_else(|e| e.into_inner()).remove(cmd);
let (out, code) = match res { let (out, code) = match res {
Ok(Ok(o)) => (o.stdout, o.status.code()), Ok(Ok((o, st))) => (o, st.code()),
Ok(Err(e)) => return ToolResult::err(format!("wait: {e}")), Ok(Err(e)) => return ToolResult::err(format!("wait: {e}")),
Err(_) => { Err(_) => {
#[cfg(unix)] #[cfg(unix)]
@@ -451,6 +477,22 @@ mod tests {
use super::*; use super::*;
use std::time::Instant; use std::time::Instant;
#[tokio::test]
async fn bash_streams_live_tail() {
let d = tempfile::tempdir().unwrap();
let c = cx(d.path());
let cmd = "echo one; sleep 0.4; echo two";
let st = c.state.clone();
let peek = tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(200)).await;
st.live.lock().unwrap().get(cmd).cloned()
});
let r = Bash.call(json!({"command": cmd}), &c).await;
assert_eq!(peek.await.unwrap().as_deref(), Some("one\n"));
assert_eq!(r.content, "one\ntwo\n");
assert!(c.state.live.lock().unwrap().is_empty(), "cleared when done");
}
fn cx(d: &Path) -> ToolCtx { fn cx(d: &Path) -> ToolCtx {
ToolCtx { ToolCtx {
cwd: d.into(), cwd: d.into(),
+3 -4
View File
@@ -61,9 +61,8 @@ fn dur(d: Duration) -> String {
fn glyph(s: &Status, frame: usize) -> &'static str { fn glyph(s: &Status, frame: usize) -> &'static str {
let th = theme::t(); let th = theme::t();
match s { match s {
Status::Running if th.sym.ok == "+" => ["-", "\\", "|", "/"][frame % 4], Status::Running => th.spin(frame),
Status::Running => ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"][frame % 10], Status::Done => th.sym.done,
Status::Done => th.sym.ok,
_ => th.sym.err, _ => th.sym.err,
} }
} }
@@ -239,7 +238,7 @@ mod tests {
assert!( assert!(
text(&l[0]).starts_with(" ⠋ 1 explore ") && text(&l[0]).ends_with(" 1m12s 8c 41k") text(&l[0]).starts_with(" ⠋ 1 explore ") && text(&l[0]).ends_with(" 1m12s 8c 41k")
); );
assert!(text(&l[1]).starts_with(" ✓ 2 explore "), "{}", text(&l[1])); assert!(text(&l[1]).starts_with(" ● 2 explore "), "{}", text(&l[1]));
assert!(text(&l[0]).contains('…')); assert!(text(&l[0]).contains('…'));
} }
+422 -115
View File
@@ -188,6 +188,11 @@ struct App {
sub_t: std::collections::HashMap<usize, Transcript>, sub_t: std::collections::HashMap<usize, Transcript>,
/// subagent list focused / one agent open /// subagent list focused / one agent open
agents: Option<agents::View>, agents: Option<agents::View>,
/// 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 { impl App {
@@ -213,7 +218,7 @@ impl App {
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 · \ 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"; tab complete @file / command";
const PLACEHOLDER: &str = "/ commands · @ files · ctrl-p picker · /help keys"; const PLACEHOLDER: &str = "message · / commands · @ files";
/// Columns from which listings go to a side panel. /// Columns from which listings go to a side panel.
const WIDE: u16 = 140; const WIDE: u16 = 140;
@@ -330,6 +335,9 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
expanded: false, expanded: false,
busy: false, busy: false,
queue: VecDeque::new(), queue: VecDeque::new(),
run_tokens: (0, 0),
cwd_label: home_short(&cwd),
git: git_head(&cwd),
st: status::Status { st: status::Status {
kind: switcher.kind(), kind: switcher.kind(),
model: agent.model().to_string(), model: agent.model().to_string(),
@@ -495,7 +503,15 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
if let Event::Stream(hx_ai::StreamEvent::Quota(q)) = &e { if let Event::Stream(hx_ai::StreamEvent::Quota(q)) = &e {
app.st.quota = Some(q.clone()); 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 { 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.usage.add(usage);
app.st.ctx_tokens = (usage.input_tokens + usage.cache_read_tokens + usage.cache_write_tokens + usage.output_tokens) as usize; app.st.ctx_tokens = (usage.input_tokens + usage.cache_read_tokens + usage.cache_write_tokens + usage.output_tokens) as usize;
} }
@@ -503,6 +519,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
} }
Ui::Done(r) => { Ui::Done(r) => {
app.busy = false; app.busy = false;
app.git = git_head(&cwd);
match r { match r {
Err(e) if e == "aborted" => app.t.push(Item::Info("aborted".into())), Err(e) if e == "aborted" => app.t.push(Item::Info("aborted".into())),
Err(e) => app.t.push(Item::Error(e)), Err(e) => app.t.push(Item::Error(e)),
@@ -584,6 +601,65 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
} }
/// Sessions live next to the current one. /// 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 { fn sessions_dir(app: &App) -> &std::path::Path {
app.session_path app.session_path
.parent() .parent()
@@ -1337,6 +1413,7 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
"compact" => { "compact" => {
app.busy = true; app.busy = true;
app.since = Instant::now(); app.since = Instant::now();
app.run_tokens = (0, 0);
app.t.push(Item::Info("compacting…".into())); app.t.push(Item::Info("compacting…".into()));
let (agent, tx) = (agent.clone(), tx.clone()); let (agent, tx) = (agent.clone(), tx.clone());
tokio::spawn(async move { tokio::spawn(async move {
@@ -1373,10 +1450,6 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
} }
} }
if app.busy { if app.busy {
app.t.push(Item::Info(format!(
"queued: {}",
line.lines().next().unwrap_or_default()
)));
app.queue.push_back(line); app.queue.push_back(line);
return; return;
} }
@@ -1391,6 +1464,7 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
})); }));
app.busy = true; app.busy = true;
app.since = Instant::now(); app.since = Instant::now();
app.run_tokens = (0, 0);
let prompt = expand_mentions(&line, cwd); let prompt = expand_mentions(&line, cwd);
let (agent, tx) = (agent.clone(), tx.clone()); let (agent, tx) = (agent.clone(), tx.clone());
let effort = app.st.effort; let effort = app.st.effort;
@@ -1404,10 +1478,11 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
fn draw(f: &mut ratatui::Frame, app: &mut App) { fn draw(f: &mut ratatui::Frame, app: &mut App) {
let th = theme::t(); let th = theme::t();
let text_w = f.area().width.saturating_sub(2) as usize; // 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 (rows, (cur_r, cur_c)) = app.ed.wrapped(text_w);
let input_h = rows.len().min(10) as u16 + 2; let input_h = rows.len().min(10) as u16 + 2;
let act_h = u16::from(app.busy); let act_h = u16::from(app.busy) + app.queue.len().min(3) as u16;
app.wide = f.area().width >= WIDE; app.wide = f.area().width >= WIDE;
if let Some(agents::View::Detail { id, ed, scroll }) = &mut app.agents { if let Some(agents::View::Detail { id, ed, scroll }) = &mut app.agents {
let subs = app.state.subs.list(); let subs = app.state.subs.list();
@@ -1438,7 +1513,8 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
.filter(|r| focused || r.ended.is_none_or(|e| e < agents::LINGER)) .filter(|r| focused || r.ended.is_none_or(|e| e < agents::LINGER))
.collect(); .collect();
let foot_h = status::rows_for(f.area().width, app.ask.is_some()); let foot_h = status::rows_for(f.area().width, app.ask.is_some());
let [main, subs_area, act, input, status_row] = Layout::vertical([ let [head, main, subs_area, act, input, status_row] = Layout::vertical([
Constraint::Length(1),
Constraint::Min(3), Constraint::Min(3),
Constraint::Length(agents::list_height(sub_rows.len())), Constraint::Length(agents::list_height(sub_rows.len())),
Constraint::Length(act_h), Constraint::Length(act_h),
@@ -1446,6 +1522,7 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
Constraint::Length(foot_h), Constraint::Length(foot_h),
]) ])
.areas(f.area()); .areas(f.area());
f.render_widget(header(app, head.width), head);
let main = match &app.panel { let main = match &app.panel {
Some((title, text)) if app.wide => { Some((title, text)) if app.wide => {
@@ -1454,9 +1531,24 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
let block = Block::new() let block = Block::new()
.borders(Borders::LEFT) .borders(Borders::LEFT)
.border_style(th.dim()) .border_style(th.dim())
.title(Span::styled(format!(" {title} · esc "), th.dim())); .padding(ratatui::widgets::Padding::horizontal(1));
let body = block.inner(side); let body = block.inner(side);
let para = Paragraph::new(text.as_str()).wrap(Wrap { trim: false }); 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 let top = app
.panel_scroll .panel_scroll
.resolve(para.line_count(body.width) as u16, body.height); .resolve(para.line_count(body.width) as u16, body.height);
@@ -1467,14 +1559,23 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
} }
None if app.wide && app.side => { None if app.wide && app.side => {
let [m, side] = let [m, side] =
Layout::horizontal([Constraint::Min(60), Constraint::Length(34)]).areas(main); Layout::horizontal([Constraint::Min(60), Constraint::Length(40)]).areas(main);
let block = Block::new() let block = Block::new()
.borders(Borders::LEFT) .borders(Borders::LEFT)
.border_style(th.dim()) .border_style(th.dim())
.title(Span::styled(" lens · ctrl-l ", th.dim())); .padding(ratatui::widgets::Padding::horizontal(1));
let body = block.inner(side); let body = block.inner(side);
f.render_widget(block, side); f.render_widget(block, side);
f.render_widget(Paragraph::new(side_lines(app)), body); 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(); app.areas.panel = Rect::default();
m m
} }
@@ -1484,6 +1585,12 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
} }
}; };
app.areas.chat = 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 para = Paragraph::new(app.t.lines(app.expanded, main.width)).wrap(Wrap { trim: false });
let total = para.line_count(main.width) as u16; let total = para.line_count(main.width) as u16;
let top = app.scroll.resolve(total, main.height); let top = app.scroll.resolve(total, main.height);
@@ -1504,18 +1611,41 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
subs_area, subs_area,
); );
} }
// queued prompts, then the activity line, right above the input
let mut al: Vec<Line> = 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 { if app.busy {
let (what, t0) = app.t.running().unwrap_or(("thinking…".into(), app.since)); let what = app.t.running().map_or("thinking".into(), |r| r.0);
let frame = (app.since.elapsed().as_millis() / 80) as usize; let frame = (app.since.elapsed().as_millis() / 80) as usize;
f.render_widget(transcript::activity_line(&what, t0.elapsed(), frame), act); 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::default() let block = Block::bordered()
.borders(Borders::TOP | Borders::BOTTOM) .border_type(ratatui::widgets::BorderType::Rounded)
.border_style(th.dim()); .border_style(th.frame());
let inner = block.inner(input); let inner = block.inner(input);
f.render_widget(block, input); f.render_widget(block, input);
let [gut, text] = Layout::horizontal([Constraint::Length(2), Constraint::Min(1)]).areas(inner); 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( f.render_widget(
Span::styled( Span::styled(
format!("{} ", th.sym.user), format!("{} ", th.sym.user),
@@ -1560,7 +1690,7 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
&app.ed.buf[app.ed.buf[..comp.start].rfind('\n').map_or(0, |i| i + 1)..comp.start], &app.ed.buf[app.ed.buf[..comp.start].rfind('\n').map_or(0, |i| i + 1)..comp.start],
) )
.width() as u16; .width() as u16;
draw_popup(f, comp, *sel, text.x + col, input.y); 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)); f.set_cursor_position((text.x + c as u16, text.y + r as u16 - skip));
if let Some(p) = &app.picker { if let Some(p) = &app.picker {
@@ -1583,41 +1713,126 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
} }
} }
/// Right-hand overview on wide terminals: lens state, context numbers, MCP servers. const SIDE_DIAGS: usize = 8;
fn side_lines(app: &App) -> Vec<Line<'static>> { 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<Line<'static>> {
let th = theme::t(); let th = theme::t();
let head = |t: &str| Line::styled(t.to_string(), th.accent()); let sec = |label: String| {
let mut l = vec![head("LSP / LINT")]; 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() { if app.lens_lines.is_empty() {
l.push(Line::styled("(none started)", th.dim())); 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(),
));
}
} }
l.extend(app.lens_lines.iter().map(|x| {
let bad = x.contains("dead") || x.contains("error") || x.contains("missing");
Line::styled(x.clone(), if bad { th.warn() } else { th.plain() })
}));
let u = &app.st.usage; let u = &app.st.usage;
let tot = u.input_tokens + u.cache_read_tokens + u.cache_write_tokens; let tot = u.input_tokens + u.cache_read_tokens + u.cache_write_tokens;
l.push(Line::default()); l.push(Line::default());
l.push(head("CONTEXT")); l.push(sec("context".into()));
l.push(Line::raw(format!( let mut ctx = format!("{}k / {}k", app.st.ctx_tokens / 1000, app.st.ctx_max / 1000);
"window {}k / {}k",
app.st.ctx_tokens / 1000,
app.st.ctx_max / 1000
)));
if let Some(p) = (100 * u.cache_read_tokens).checked_div(tot) { if let Some(p) = (100 * u.cache_read_tokens).checked_div(tot) {
l.push(Line::raw(format!("cache {p}%"))); ctx += &format!(" {} cache {p}%", th.sym.info);
} }
l.push(Line::raw(format!("output {}k", u.output_tokens / 1000))); l.push(Line::styled(ctx, th.sec()));
if !app.mcp.is_empty() { if !app.mcp.is_empty() {
l.push(Line::default()); l.push(Line::default());
l.push(head("MCP")); l.push(sec("mcp".into()));
l.extend(app.mcp.iter().map(|(n, ok)| { l.extend(app.mcp.iter().map(|(n, ok)| {
Line::from(vec![ Line::from(vec![
Span::styled( Span::styled(
if *ok { "● " } else { "○ " }, format!("{} ", if *ok { th.sym.done } else { th.sym.err }),
if *ok { th.ok() } else { th.err() }, if *ok { th.ok() } else { th.err() },
), ),
Span::raw(n.clone()), Span::styled(n.clone(), th.plain()),
]) ])
})); }));
} }
@@ -1651,49 +1866,122 @@ fn skills_list(specs: &[CmdSpec], dirs: &[std::path::PathBuf]) -> String {
) )
} }
/// Bordered candidate list ending just above row `bottom`, starting at column `x` (the token). /// `(source tag, summary)` from a slash-command candidate's detail (`mcp · summary`).
fn draw_popup(f: &mut ratatui::Frame, c: &Completion, sel: usize, x: u16, bottom: u16) { 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 th = theme::t();
let lw = c let area = f.area();
let rows_: Vec<(&str, &'static str, String)> = c
.items .items
.iter() .iter()
.map(|i| i.label.chars().count()) .map(|i| {
.max() let (tag, d) = split_source(&i.label, &i.detail);
.unwrap_or(0); (i.label.as_str(), tag, d)
// scroll so the selected row stays visible when there are more items than rows })
let rows = (bottom as usize).saturating_sub(2).max(1); .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) let off = (sel + 1)
.saturating_sub(rows) .saturating_sub(rows)
.min(c.items.len().saturating_sub(rows)); .min(c.items.len().saturating_sub(rows));
let lines: Vec<Line> = c let mut lines = vec![Line::styled(head, th.dim())];
.items for (n, (label, tag, d)) in rows_.iter().enumerate().skip(off).take(rows) {
.iter() let band = if n == sel {
.enumerate() th.sel()
.skip(off) } else {
.take(rows) ratatui::style::Style::default()
.map(|(n, i)| { };
let base = if n == sel { th.sel() } else { th.plain() }; let mut v = vec![
Line::from(vec![ Span::styled(format!(" {label:<lw$} "), band.patch(th.accent())),
Span::styled(format!(" {:<lw$} ", i.label), base), Span::styled(format!("{:<dw$}", cut_to(d, dw)), band.patch(th.sec())),
Span::styled( ];
format!("{} ", i.detail), if tw > 0 {
if n == sel { base } else { th.dim() }, let ts = if *tag == "builtin" {
), th.dim()
]) } else {
}) th.link()
.collect(); };
let area = f.area(); v.push(Span::styled(format!(" {tag:>tw$}"), band.patch(ts)));
let w = (lines.iter().map(Line::width).max().unwrap_or(0) as u16 + 2).min(area.width); }
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 h = (lines.len() as u16 + 2).min(bottom);
let x = x.saturating_sub(1).min(area.width - w); let x = x.saturating_sub(1).min(area.width - w);
let r = Rect::new(x, bottom - h, w, h); let r = Rect::new(x, bottom - h, w, h);
f.render_widget(Clear, r); f.render_widget(Clear, r);
f.render_widget( f.render_widget(
Paragraph::new(lines).block(Block::bordered().border_style(th.dim())), Paragraph::new(lines).block(
Block::bordered()
.border_type(ratatui::widgets::BorderType::Rounded)
.border_style(th.frame()),
),
r, 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)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -1728,10 +2016,13 @@ mod tests {
.collect(); .collect();
let all = rows.join("\n"); let all = rows.join("\n");
assert!(all.contains("❯ hello"), "{all}"); assert!(all.contains("❯ hello"), "{all}");
assert!(all.contains("◆ hi there"), "{all}"); assert!(all.contains(" hi there"), "{all}");
assert!(rows[7].starts_with("❯ typing"), "{all}"); assert!(
assert!(rows[9].starts_with("ctx ▰▱▱▱▱▱▱▱▱▱ 12k/150k "), "{all}"); rows[0].starts_with("hx ~/w") && rows[0].ends_with("m1"),
assert!(rows[9].ends_with("Claude · m1"), "{all}"); "{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 { fn screen(app: &mut App, w: u16, h: u16) -> String {
@@ -1805,10 +2096,35 @@ mod tests {
let mut app = test_app(); let mut app = test_app();
app.mcp = vec![("git".into(), true), ("db".into(), false)]; app.mcp = vec![("git".into(), true), ("db".into(), false)];
app.lens_lines = vec!["rust-analyzer @ /p: running".into()]; app.lens_lines = vec!["rust-analyzer @ /p: running".into()];
assert!(screen(&mut app, 160, 50).contains("MCP")); *app.state.lens.lock().unwrap() = hx_core::LensView {
assert!(!screen(&mut app, 80, 24).contains("MCP")); 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; app.side = false;
assert!(!screen(&mut app, 160, 50).contains("MCP")); assert!(!screen(&mut app, 160, 50).contains("/lsp"));
} }
#[test] #[test]
@@ -1920,7 +2236,7 @@ mod tests {
}) })
.collect(); .collect();
assert!( assert!(
all.contains("✓ 1 explore") && all.contains("find x"), all.contains("● 1 explore") && all.contains("find x"),
"{all}" "{all}"
); );
} }
@@ -1950,13 +2266,13 @@ mod tests {
}; };
let rows = draw_at(&mut app, 60, 20); let rows = draw_at(&mut app, 60, 20);
assert!(rows.iter().any(|r| r.contains("line 99")), "follows bottom"); assert!(rows.iter().any(|r| r.contains("line 99")), "follows bottom");
// main area is 20 - input(3) - footer(1) = 16 rows: half page = 8 // main area is 20 - header(1) - input(3) - footer(1) = 15 rows: half page = 7
press(&mut app, KeyCode::PageUp, KeyModifiers::NONE); press(&mut app, KeyCode::PageUp, KeyModifiers::NONE);
let rows = draw_at(&mut app, 60, 20); let rows = draw_at(&mut app, 60, 20);
assert_eq!(app.scroll.behind(), 8); assert_eq!(app.scroll.behind(), 7);
assert!(!rows.iter().any(|r| r.contains("line 99")), "{rows:#?}"); assert!(!rows.iter().any(|r| r.contains("line 99")), "{rows:#?}");
assert!( assert!(
rows[19].contains("↑8"), rows[19].ends_with("↑7"),
"footer shows lines behind: {}", "footer shows lines behind: {}",
rows[19] rows[19]
); );
@@ -1965,17 +2281,17 @@ mod tests {
long_chat(&mut app, 10); long_chat(&mut app, 10);
let rows = draw_at(&mut app, 60, 20); let rows = draw_at(&mut app, 60, 20);
assert_eq!(rows[..16], pinned[..]); assert_eq!(rows[..16], pinned[..]);
assert!(rows[19].contains("↑28"), "{}", rows[19]); assert!(rows[19].ends_with("↑27"), "{}", rows[19]);
// alt+up: 3 lines; ctrl+home: top; ctrl+end: back to following // alt+up: 3 lines; ctrl+home: top; ctrl+end: back to following
press(&mut app, KeyCode::Up, KeyModifiers::ALT); press(&mut app, KeyCode::Up, KeyModifiers::ALT);
assert_eq!(app.scroll.behind(), 31); assert_eq!(app.scroll.behind(), 30);
press(&mut app, KeyCode::Home, KeyModifiers::CONTROL); press(&mut app, KeyCode::Home, KeyModifiers::CONTROL);
let rows = draw_at(&mut app, 60, 20); let rows = draw_at(&mut app, 60, 20);
assert!(rows.iter().any(|r| r.contains("line 0")), "{rows:#?}"); assert!(rows.iter().any(|r| r.contains("line 0")), "{rows:#?}");
press(&mut app, KeyCode::End, KeyModifiers::CONTROL); press(&mut app, KeyCode::End, KeyModifiers::CONTROL);
let rows = draw_at(&mut app, 60, 20); let rows = draw_at(&mut app, 60, 20);
assert!(rows[14].contains("line 9"), "bottom: {rows:#?}"); assert!(rows[14].contains("line 9"), "bottom: {rows:#?}");
assert!(rows[19].ends_with("Claude · m1"), "{}", rows[19]); assert!(rows[19].starts_with("m1 · ctx"), "{}", rows[19]);
// plain Home still edits text and doesn't scroll // plain Home still edits text and doesn't scroll
app.ed.insert("abc"); app.ed.insert("abc");
press(&mut app, KeyCode::Home, KeyModifiers::NONE); press(&mut app, KeyCode::Home, KeyModifiers::NONE);
@@ -2063,6 +2379,9 @@ mod tests {
fn test_app() -> App { fn test_app() -> App {
App { App {
run_tokens: (0, 0),
cwd_label: "~/w".into(),
git: None,
t: Transcript::default(), t: Transcript::default(),
ed: Editor::default(), ed: Editor::default(),
files: vec!["src/main.rs".into(), "src/lib.rs".into()], files: vec!["src/main.rs".into(), "src/lib.rs".into()],
@@ -2157,12 +2476,15 @@ mod tests {
let rows: Vec<String> = (0..10) let rows: Vec<String> = (0..10)
.map(|y| (0..40).map(|x| buf[(x, y)].symbol().to_string()).collect()) .map(|y| (0..40).map(|x| buf[(x, y)].symbol().to_string()).collect())
.collect(); .collect();
assert_eq!( let all = rows.join("\n");
rows[3], "│ /clear alias of /new │", // 10 rows: the popup scrolls to 2 candidates and covers the header
"{rows:#?}" assert!(rows[1].contains("commands · 3 of"), "{all}");
assert!(
rows[2].starts_with("│ /copy copy") && rows[2].contains("builtin"),
"{all}"
); );
assert!(rows[4].starts_with("│ /compact summarize"), "{rows:#?}"); assert!(rows[4].contains("↑↓ select"), "{all}");
assert!(rows[9].ends_with("Claude · m1"), "{rows:#?}"); assert!(rows[9].starts_with("m1 · ctx"), "{all}");
// footer at 100 cols, and a hint replacing only the right side // footer at 100 cols, and a hint replacing only the right side
app.hint = "no match".into(); app.hint = "no match".into();
@@ -2170,32 +2492,14 @@ mod tests {
term.draw(|f| draw(f, &mut app)).unwrap(); term.draw(|f| draw(f, &mut app)).unwrap();
let buf = term.backend().buffer().clone(); let buf = term.backend().buffer().clone();
let row = |y| -> String { (0..100).map(|x| buf[(x, y)].symbol().to_string()).collect() }; let row = |y| -> String { (0..100).map(|x| buf[(x, y)].symbol().to_string()).collect() };
let (last, lens) = (row(8), row(9)); let (stat, hints) = (row(8), row(9));
assert!( assert!(stat.starts_with("m1 · ctx ▱▱▱▱▱▱▱▱▱▱ 0%"), "{stat}");
last.starts_with("ctx ▱▱▱▱▱▱▱▱▱▱ 0k/150k · 0↑ 0↓") && last.ends_with("no match"), assert!(hints.starts_with("no match"), "{hints}");
"{last}"
);
assert!(
lens.starts_with("lens: starting") && lens.ends_with("Claude · m1"),
"{lens}"
);
app.hint.clear(); app.hint.clear();
let mut foot = |app: &mut App| { term.draw(|f| draw(f, &mut app)).unwrap();
term.draw(|f| draw(f, app)).unwrap(); let buf = term.backend().buffer().clone();
let buf = term.backend().buffer().clone(); let hints: String = (0..100).map(|x| buf[(x, 9)].symbol().to_string()).collect();
(0..100) assert!(hints.starts_with(status::KEYS), "{hints}");
.map(|x| buf[(x, 9)].symbol().to_string())
.collect::<String>()
};
assert!(foot(&mut app).ends_with("new session · Claude · m1"));
app.title = Some("fix the flaky rust-analyzer test".into());
let last = foot(&mut app);
assert!(
last.starts_with("lens: ")
&& last.ends_with("fix the flaky rust-analyzer test · Claude · m1"),
"{last}"
);
app.title = None;
key(&mut app, KeyCode::Down); key(&mut app, KeyCode::Down);
key(&mut app, KeyCode::Up); key(&mut app, KeyCode::Up);
key(&mut app, KeyCode::Up); key(&mut app, KeyCode::Up);
@@ -2285,10 +2589,13 @@ mod tests {
assert!(app.t.items.is_empty()); assert!(app.t.items.is_empty());
term.draw(|f| draw(f, &mut app)).unwrap(); term.draw(|f| draw(f, &mut app)).unwrap();
let buf = term.backend().buffer().clone(); let buf = term.backend().buffer().clone();
let row0: String = (0..160).map(|x| buf[(x, 0)].symbol().to_string()).collect(); let row = |y| -> String { (0..160).map(|x| buf[(x, y)].symbol().to_string()).collect() };
assert!(row0.contains("│ skills · esc"), "{row0}"); assert!(
let row1: String = (0..160).map(|x| buf[(x, 1)].symbol().to_string()).collect(); row(1).contains("│ /skills") && row(1).ends_with("esc × "),
assert!(row1.contains("│skills (0):"), "{row1}"); "{}",
row(1)
);
assert!(row(3).contains("│ skills (0):"), "{}", row(3));
key(&mut app, KeyCode::Esc); key(&mut app, KeyCode::Esc);
assert!(app.panel.is_none()); assert!(app.panel.is_none());
app.wide = false; app.wide = false;
+135 -58
View File
@@ -4,8 +4,9 @@ use crate::theme;
use crate::transcript::{Item, Transcript}; use crate::transcript::{Item, Transcript};
use hx_core::session::{self, Meta}; use hx_core::session::{self, Meta};
use ratatui::layout::{Constraint, Layout, Rect}; use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span}; use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Clear, Paragraph}; use ratatui::widgets::{Block, BorderType, Borders, Clear, Paragraph};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::time::SystemTime; use std::time::SystemTime;
@@ -134,48 +135,62 @@ impl Sessions {
Act::None Act::None
} }
/// Full-screen: scope tabs and count, framed query, list | preview, key hints.
pub fn draw(&mut self, f: &mut ratatui::Frame) { pub fn draw(&mut self, f: &mut ratatui::Frame) {
let th = theme::t(); let th = theme::t();
let a = f.area(); let a = f.area();
let r = Rect::new(a.x + 1, a.y, a.width.saturating_sub(2), a.height); f.render_widget(Clear, a);
let scope = if self.all_scope {
"this project ▸ all projects"
} else {
"this project ▸ all (tab)"
};
let ms: Vec<Meta> = self.matches().into_iter().cloned().collect(); let ms: Vec<Meta> = self.matches().into_iter().cloned().collect();
let block = Block::bordered().border_style(th.dim()).title(Span::styled( let [tabs, q, body, help] = Layout::vertical([
format!(" sessions · {scope} · {} ", ms.len()),
th.dim(),
));
let inner = block.inner(r);
f.render_widget(Clear, r);
f.render_widget(block, r);
let list_h = (ms.len() as u16).clamp(1, (inner.height / 2).max(3));
let [q, _, list, sep, prev, help] = Layout::vertical([
Constraint::Length(1), Constraint::Length(1),
Constraint::Length(1), Constraint::Length(3),
Constraint::Length(list_h), Constraint::Min(1),
Constraint::Length(1),
Constraint::Min(0),
Constraint::Length(1), Constraint::Length(1),
]) ])
.areas(inner); .areas(a);
let (on, off) = (th.plain(), th.dim());
let count = Span::styled(format!("{} of {}", ms.len(), self.pool().len()), th.sec());
let left = vec![
Span::styled("sessions", th.accent().add_modifier(Modifier::BOLD)),
Span::raw(" "),
Span::styled("this project", if self.all_scope { off } else { on }),
Span::styled(format!(" {} ", th.sym.info), th.dim()),
Span::styled("all projects", if self.all_scope { on } else { off }),
];
let lw: usize = left.iter().map(Span::width).sum();
let mut l = left;
l.push(Span::raw(" ".repeat(
(tabs.width as usize).saturating_sub(lw + count.width()),
)));
l.push(count);
f.render_widget(Line::from(l), tabs);
let frame = Block::bordered()
.border_type(BorderType::Rounded)
.border_style(th.frame());
let qi = frame.inner(q);
f.render_widget(frame, q);
f.render_widget( f.render_widget(
Line::from(vec![ Line::from(vec![
Span::styled(format!("{} ", th.sym.user), th.accent()), Span::styled(format!("{} ", th.sym.user), th.accent()),
Span::raw(self.query.clone()), Span::styled(self.query.clone(), th.plain()),
]), ]),
q, qi,
); );
f.set_cursor_position((q.x + 2 + self.query.chars().count() as u16, q.y)); f.set_cursor_position((qi.x + 2 + self.query.chars().count() as u16, qi.y));
let [list, rule, prev] = Layout::horizontal([
Constraint::Percentage(45),
Constraint::Length(2),
Constraint::Min(1),
])
.areas(body);
let top = self let top = self
.sel .sel
.saturating_sub(list.height.saturating_sub(1) as usize); .saturating_sub(list.height.saturating_sub(1) as usize);
let w = list.width as usize; let w = list.width as usize;
let rows: Vec<Line> = if ms.is_empty() { let rows: Vec<Line> = if ms.is_empty() {
vec![Line::styled(" no sessions", th.dim())] vec![Line::styled(" no sessions", th.dim())]
} else { } else {
ms.iter() ms.iter()
.enumerate() .enumerate()
@@ -186,60 +201,118 @@ impl Sessions {
}; };
f.render_widget(Paragraph::new(rows), list); f.render_widget(Paragraph::new(rows), list);
f.render_widget( f.render_widget(
Block::new().borders(Borders::TOP).border_style(th.dim()), Block::new().borders(Borders::LEFT).border_style(th.dim()),
sep, Rect {
x: rule.x + 1,
width: 1,
..rule
},
); );
if let Some(m) = ms.get(self.sel) { if let Some(m) = ms.get(self.sel) {
if self.preview.as_ref().is_none_or(|(p, _)| *p != m.path) { if self.preview.as_ref().is_none_or(|(p, _)| *p != m.path) {
self.preview = Some((m.path.clone(), preview(&m.path, prev.width))); let mut ls = vec![
Line::styled(m.title.clone(), th.plain().add_modifier(Modifier::BOLD)),
Line::styled(self.meta_line(m), th.sec()),
Line::default(),
];
ls.extend(preview(&m.path, prev.width.saturating_sub(1)));
self.preview = Some((m.path.clone(), ls));
} }
if let Some((_, ls)) = &self.preview { if let Some((_, ls)) = &self.preview {
let skip = ls.len().saturating_sub(prev.height as usize); let pr = Rect {
f.render_widget(Paragraph::new(ls[skip..].to_vec()), prev); x: prev.x + 1,
width: prev.width.saturating_sub(1),
..prev
};
let room = pr.height as usize;
let shown: Vec<Line> = if ls.len() > room && room > 4 {
// head of the session plus a count of what's cut
let mut v = ls[..room - 1].to_vec();
v.push(Line::styled(
format!("{} more lines", th.sym.ellipsis),
th.dim(),
));
v
} else {
ls.clone()
};
f.render_widget(Paragraph::new(shown), pr);
} }
} }
let help_text = match &self.confirm { let help_text = match &self.confirm {
Some(p) => Line::styled(format!("delete {}? [y/n]", p.display()), th.warn()), Some(p) => Line::styled(format!("delete {}? [y/n]", p.display()), th.warn()),
None => Line::styled( None => Line::styled(
"enter resume · tab scope · ctrl-d delete · esc close", "type filter · tab project/all · ↑↓ select · enter resume · ctrl-d delete · esc close",
th.dim(), th.dim(),
), ),
}; };
f.render_widget(help_text, help); f.render_widget(help_text, help);
} }
/// `~/Repos/hx · sonnet-5-5 · 14 msgs · 2h ago`
fn meta_line(&self, m: &Meta) -> String {
let mut v = vec![];
if self.all_scope {
v.push(m.project.clone());
}
if let Some(md) = &m.model {
v.push(md.strip_prefix("claude-").unwrap_or(md).to_string());
}
v.push(format!("{} msgs", m.messages));
if m.branches > 1 {
v.push(format!("{} branches", m.branches));
}
v.push(ago(m.modified));
v.join(&format!(" {} ", theme::t().sym.info))
}
/// ` ● title ····· 2h` — band on the selected row, `●` marks the open session.
fn row(&self, m: &Meta, sel: bool, w: usize) -> Line<'static> { fn row(&self, m: &Meta, sel: bool, w: usize) -> Line<'static> {
let th = theme::t(); let th = theme::t();
let st = if sel { th.sel() } else { th.plain() }; let st = if sel {
let dim = if sel { st } else { th.dim() }; th.sel().add_modifier(Modifier::BOLD)
let mark = if sel { th.sym.more } else { " " };
let cur = if m.path == self.current { "●" } else { " " };
let fork = if m.branches > 1 {
format!("⑂{} ", m.branches)
} else { } else {
String::new() th.plain()
}; };
let tail = if self.all_scope { let band = if sel { th.sel() } else { Style::default() };
m.project.clone() let cur = if m.path == self.current {
th.sym.dirty
} else { } else {
m.model.clone().unwrap_or_default() " "
}; };
let tail = tail.strip_prefix("claude-").unwrap_or(&tail); let mut right = short_age(m.modified);
let right = format!("{fork}{:>4} msg {:<16}", m.messages, cut(tail, 16)); if self.all_scope {
let left = format!("{mark}{cur} {:<9} ", ago(m.modified)); right = format!("{} {right}", cut(&m.project, 16));
let room = w.saturating_sub(left.chars().count() + right.chars().count() + 1); }
let room = w.saturating_sub(right.chars().count() + 5);
let title = cut(&m.title, room); let title = cut(&m.title, room);
let pad = room.saturating_sub(title.chars().count()); let pad = w.saturating_sub(title.chars().count() + right.chars().count() + 4);
Line::from(vec![ Line::from(vec![
Span::styled(left, dim), Span::styled(format!(" {cur} "), band.patch(th.accent())),
Span::styled(title, st), Span::styled(title, st),
Span::styled(" ".repeat(pad + 1), st), Span::styled(" ".repeat(pad), band),
Span::styled(right, dim), Span::styled(right, band.patch(th.sec())),
Span::styled(" ", band),
]) ])
} }
} }
/// `now`, `5m`, `2h`, `1d`, `3w`.
fn short_age(t: SystemTime) -> String {
let s = SystemTime::now()
.duration_since(t)
.unwrap_or_default()
.as_secs();
match s {
0..60 => "now".into(),
60..3600 => format!("{}m", s / 60),
3600..86400 => format!("{}h", s / 3600),
86400..604800 => format!("{}d", s / 86400),
_ => format!("{}w", s / 604800),
}
}
fn cut(s: &str, n: usize) -> String { fn cut(s: &str, n: usize) -> String {
if s.chars().count() <= n { if s.chars().count() <= n {
return s.into(); return s.into();
@@ -396,24 +469,28 @@ mod tests {
let rows = screen(&mut s, 100, 20); let rows = screen(&mut s, 100, 20);
let all = rows.join("\n"); let all = rows.join("\n");
assert!( assert!(
rows[0].contains("sessions · this project ▸ all (tab) · 1"), rows[0].starts_with("sessions this project · all projects")
&& rows[0].ends_with("1 of 2"),
"{all}" "{all}"
); );
assert!(rows[1].contains("❯ pars"), "{all}"); assert!(rows[2].contains("❯ pars"), "{all}");
assert!( assert!(
rows[3].contains("▸ just now parser: handle trailing commas") rows[4].contains(" parser: handle trailing commas") && rows[4].contains(" now "),
&& rows[3].contains("3 msg opus"),
"{all}" "{all}"
); );
assert!(all.contains("opus · 3 msgs · just now"), "meta: {all}");
assert!( assert!(
all.contains("❯ parser: handle trailing commas"), all.contains("❯ parser: handle trailing commas"),
"preview: {all}" "preview: {all}"
); );
assert!( assert!(
all.contains("✓ edit src/parse.rs"), all.contains("● edit src/parse.rs"),
"preview tool line: {all}" "preview tool line: {all}"
); );
assert!(rows[18].contains("enter resume · tab scope"), "{all}"); assert!(
rows[19].starts_with("type filter · tab project/all"),
"{all}"
);
// all projects scope shows the project column // all projects scope shows the project column
s.query.clear(); s.query.clear();
@@ -421,20 +498,20 @@ mod tests {
assert_eq!(titles(&s)[0], "elsewhere"); assert_eq!(titles(&s)[0], "elsewhere");
let rows = screen(&mut s, 100, 20); let rows = screen(&mut s, 100, 20);
assert!( assert!(
rows[3].contains("elsewhere") && rows[3].contains("other"), rows[4].contains("elsewhere") && rows[4].contains("other"),
"{rows:#?}" "{rows:#?}"
); );
s.key(k(KeyCode::Tab)); s.key(k(KeyCode::Tab));
// current session is marked and can't be deleted; others need y // current session is marked and can't be deleted; others need y
let rows = screen(&mut s, 100, 20); let rows = screen(&mut s, 100, 20);
assert!(rows[3].contains("▸● just now review PR 73"), "{rows:#?}"); assert!(rows[4].starts_with(" ● review PR 73"), "{rows:#?}");
s.key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL)); s.key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL));
assert!(s.confirm.is_none()); assert!(s.confirm.is_none());
s.key(k(KeyCode::Down)); s.key(k(KeyCode::Down));
s.key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL)); s.key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL));
assert_eq!(s.confirm.as_ref(), Some(&first)); assert_eq!(s.confirm.as_ref(), Some(&first));
assert!(screen(&mut s, 100, 20)[18].contains("[y/n]")); assert!(screen(&mut s, 100, 20)[19].contains("[y/n]"));
s.key(k(KeyCode::Char('n'))); s.key(k(KeyCode::Char('n')));
assert!(first.exists()); assert!(first.exists());
s.key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL)); s.key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL));
+97 -183
View File
@@ -41,8 +41,11 @@ pub struct Chrome<'a> {
pub lens_warn: bool, pub lens_warn: bool,
} }
/// Terminals at least this wide get a second footer row. /// Terminals at least this wide get the key-hint row under the status row.
pub const TWO_ROWS: u16 = 100; pub const TWO_ROWS: u16 = 80;
/// Default key hints (second footer row).
pub const KEYS: &str = "enter send · shift-enter newline · ctrl-o expand · ctrl-p palette";
/// Footer height for this width (the ask line always takes one row). /// Footer height for this width (the ask line always takes one row).
pub fn rows_for(width: u16, ask: bool) -> u16 { pub fn rows_for(width: u16, ask: bool) -> u16 {
@@ -80,63 +83,43 @@ pub fn lens_summary(lines: &[String]) -> (String, bool) {
(v.join(" · "), up < total || notes > 0) (v.join(" · "), up < total || notes > 0)
} }
/// Footer lines: two rows on wide terminals (usage on top; lens left, session tail right), /// Footer: status row, then on terminals of [`TWO_ROWS`]+ a dim key-hint row with the lens
/// else the single packed line from [`footer`]. A hint only replaces the top row's right side. /// summary on the right. A transient hint replaces the key hints.
pub fn rows(st: &Status, c: &Chrome, width: u16, now: u64) -> Vec<Line<'static>> { pub fn rows(st: &Status, c: &Chrome, width: u16, now: u64) -> Vec<Line<'static>> {
if rows_for(width, c.ask.is_some()) == 1 { let mut v = vec![footer(st, c, width, now)];
return vec![footer(st, c, width, now)]; if rows_for(width, c.ask.is_some()) == 2 {
} let th = theme::t();
let th = theme::t(); let (keys, kst) = if c.hint.is_empty() {
let w = width as usize; (KEYS, th.dim())
let lw = |l: &[Span]| l.iter().map(Span::width).sum::<usize>();
let mut top = left_spans(st, now);
if !c.hint.is_empty() {
let r = Span::styled(c.hint.to_string(), th.accent());
top.push(Span::raw(
" ".repeat(w.saturating_sub(lw(&top) + r.width()).max(1)),
));
top.push(r);
}
let lens = if c.lens.is_empty() {
"lens: starting"
} else {
c.lens
};
let mut bot = vec![Span::styled(
lens.to_string(),
if c.lens_warn { th.warn() } else { th.dim() },
)];
let tail = tail(st, c).join(" · ");
let room = w.saturating_sub(lw(&bot) + tail.chars().count() + 4);
let title = c.title.unwrap_or("new session");
let right = if room >= 12 {
let t: String = if title.chars().count() > room.min(40) {
title.chars().take(room.min(40) - 1).chain(['…']).collect()
} else { } else {
title.into() (c.hint, th.accent())
}; };
format!("{t} · {tail}") v.push(spread(
} else { vec![Span::styled(keys.to_string(), kst)],
tail vec![Span::styled(
}; c.lens.to_string(),
let r = Span::styled(right, th.dim()); if c.lens_warn { th.warn() } else { th.dim() },
bot.push(Span::raw( )],
" ".repeat(w.saturating_sub(lw(&bot) + r.width()).max(1)), width as usize,
)); ));
bot.push(r); }
vec![Line::from(top), Line::from(bot)] v
} }
/// Context bar, quota windows, token counts and cost estimate. /// `left … right` padded to `w`; the right side is dropped when both don't fit.
fn left_spans(st: &Status, now: u64) -> Vec<Span<'static>> { fn spread(mut left: Vec<Span<'static>>, right: Vec<Span<'static>>, w: usize) -> Line<'static> {
let lw: usize = left.iter().map(Span::width).sum();
let rw: usize = right.iter().map(Span::width).sum();
if rw > 0 && lw + rw < w {
left.push(Span::raw(" ".repeat(w - lw - rw)));
left.extend(right);
}
Line::from(left)
}
/// `model · ctx ▰▰▰▱▱▱▱▱▱▱ 31% ~$0.08`.
fn left_spans(st: &Status) -> Vec<Span<'static>> {
let th = theme::t(); let th = theme::t();
let k = |n: u64| {
if n >= 1000 {
format!("{:.1}k", n as f64 / 1000.0)
} else {
n.to_string()
}
};
let frac = st.ctx_tokens as f64 / st.ctx_max.max(1) as f64; let frac = st.ctx_tokens as f64 / st.ctx_max.max(1) as f64;
let full = ((frac * 10.0).round() as usize).min(10); let full = ((frac * 10.0).round() as usize).min(10);
let bar_st = match frac { let bar_st = match frac {
@@ -151,90 +134,48 @@ fn left_spans(st: &Status, now: u64) -> Vec<Span<'static>> {
.map(|p| format!(" ~${:.2}", st.usage.cost(&p))) .map(|p| format!(" ~${:.2}", st.usage.cost(&p)))
.unwrap_or_default(), .unwrap_or_default(),
}; };
let mut left = vec![ let model = st.model.strip_prefix("claude-").unwrap_or(&st.model);
Span::styled("ctx ", th.dim()), vec![
Span::styled(format!("{model} {} ctx ", th.sym.info), th.sec()),
Span::styled(th.sym.bar_full.repeat(full), bar_st), Span::styled(th.sym.bar_full.repeat(full), bar_st),
Span::styled(th.sym.bar_empty.repeat(10 - full), th.dim()), Span::styled(th.sym.bar_empty.repeat(10 - full), th.dim()),
Span::styled( Span::styled(format!(" {:.0}%{cost}", frac * 100.0), th.sec()),
format!(" {}k/{}k", st.ctx_tokens / 1000, st.ctx_max / 1000), ]
th.dim(),
),
];
if let Some(q) = &st.quota {
left.extend(quota_spans(q, now));
}
left.extend([Span::styled(
format!(
" · {}↑ {}↓{cost}",
k(st.usage.input_tokens + st.usage.cache_read_tokens),
k(st.usage.output_tokens)
),
th.dim(),
)]);
left
} }
/// `ctx ▰▰▰▱▱▱▱▱▱▱ 41k/150k · 12.3k↑ 2.1k↓ ~$0.08` left, `Claude · model · 1 queued` right. /// Status row: `model · ctx ▰▰▰▱▱▱▱▱▱▱ 31%` left, quota / think / scroll right.
/// Hints replace the right side; a pending y/n question takes the whole line. /// A pending y/n question takes the whole line; narrow terminals put a hint on the right.
pub fn footer(st: &Status, c: &Chrome, width: u16, now: u64) -> Line<'static> { pub fn footer(st: &Status, c: &Chrome, width: u16, now: u64) -> Line<'static> {
let th = theme::t(); let th = theme::t();
if let Some(q) = c.ask { if let Some(q) = c.ask {
return Line::styled(format!("[y/n] {q}"), th.warn().add_modifier(Modifier::BOLD)); return Line::styled(format!("[y/n] {q}"), th.warn().add_modifier(Modifier::BOLD));
} }
let mut left = left_spans(st, now);
let w = width as usize; let w = width as usize;
let lw = |l: &[Span]| l.iter().map(Span::width).sum::<usize>(); let mut right = vec![];
if !c.hint.is_empty() { if !c.hint.is_empty() && rows_for(width, false) == 1 {
let right = Span::styled(c.hint.to_string(), th.accent()); right.push(Span::styled(c.hint.to_string(), th.accent()));
if lw(&left) + right.width() + 1 > w { let l = spread(left_spans(st), right.clone(), w);
return Line::from(right); return if l.width() > w { Line::from(right) } else { l };
}
if let Some(q) = &st.quota {
right.extend(quota_spans(q, now));
}
for t in tail(st, c) {
if !right.is_empty() {
right.push(Span::styled(format!(" {} ", th.sym.info), th.dim()));
} }
let pad = w - lw(&left) - right.width(); right.push(Span::styled(t, th.sec()));
left.push(Span::raw(" ".repeat(pad)));
left.push(right);
return Line::from(left);
} }
let tail = tail(st, c); spread(left_spans(st), right, w)
let title = c.title.unwrap_or("new session");
// drop in order until it fits: token counts, title, context bar
let mut title_room = w.saturating_sub(lw(&left) + tail.join(" · ").chars().count() + 4);
if title_room < 12 {
left.pop();
title_room = w.saturating_sub(lw(&left) + tail.join(" · ").chars().count() + 4);
}
let mut right = tail.join(" · ");
if title_room >= 12 {
let t: String = if title.chars().count() > title_room.min(40) {
title
.chars()
.take(title_room.min(40) - 1)
.chain(['…'])
.collect()
} else {
title.into()
};
right = format!("{t} · {right}");
}
let right = Span::styled(right, th.dim());
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)
} }
fn tail(st: &Status, c: &Chrome) -> Vec<String> { fn tail(st: &Status, c: &Chrome) -> Vec<String> {
let mut t = vec![format!("{:?}", st.kind), st.model.clone()]; let mut t = vec![];
if st.effort != hx_ai::Effort::Off { if st.effort != hx_ai::Effort::Off {
t.push(format!("think {}", st.effort.name())); t.push(format!("think {}", st.effort.name()));
} }
if c.queued > 0 {
t.push(format!("{} queued", c.queued));
}
if c.scroll > 0 { if c.scroll > 0 {
t.push(format!("↑{}", c.scroll)); t.push(format!("{}{}", theme::t().sym.up, c.scroll));
} }
t t
} }
@@ -256,28 +197,32 @@ fn until(at: u64, now: u64) -> String {
} }
} }
/// ` · 5h 42% 2h13m · week 13%`, then credits; warn at 70%, error at 90%. /// `5h 42% ↻2h13m · week 13%`, then credits; warn at 70%, error at 90%.
fn quota_spans(q: &hx_ai::Quota, now: u64) -> Vec<Span<'static>> { fn quota_spans(q: &hx_ai::Quota, now: u64) -> Vec<Span<'static>> {
let th = theme::t(); let th = theme::t();
let mut v = vec![]; let mut v = vec![];
let sep = || Span::styled(format!(" {} ", th.sym.info), th.dim());
for w in &q.windows { for w in &q.windows {
let st = match w.used_pct { let st = match w.used_pct {
p if p >= 90.0 => th.err(), p if p >= 90.0 => th.err(),
p if p >= 70.0 => th.warn(), p if p >= 70.0 => th.warn(),
_ => th.dim(), _ => th.sec(),
}; };
let reset = w let reset = w
.resets_at .resets_at
.map(|r| format!(" {}{}", th.sym.reset, until(r, now))) .map(|r| format!(" {}{}", th.sym.reset, until(r, now)))
.unwrap_or_default(); .unwrap_or_default();
v.push(Span::styled(" · ", th.dim())); if !v.is_empty() {
v.push(sep());
}
v.push(Span::styled( v.push(Span::styled(
format!("{} {:.0}%{reset}", w.label, w.used_pct), format!("{} {:.0}%{reset}", w.label, w.used_pct),
st, st,
)); ));
} }
if let Some(c) = &q.credits { if let Some(c) = &q.credits {
v.push(Span::styled(format!(" · {c}"), th.dim())); v.push(sep());
v.push(Span::styled(c.clone(), th.sec()));
} }
v v
} }
@@ -325,7 +270,7 @@ mod tests {
fn st() -> Status { fn st() -> Status {
Status { Status {
kind: Kind::Claude, kind: Kind::Claude,
model: "m1".into(), model: "claude-m1".into(),
effort: hx_ai::Effort::Off, effort: hx_ai::Effort::Off,
usage: Usage::default(), usage: Usage::default(),
ctx_tokens: 0, ctx_tokens: 0,
@@ -360,15 +305,10 @@ mod tests {
#[test] #[test]
fn quota_spans_and_countdown() { fn quota_spans_and_countdown() {
let q = quota(); let q = quota();
let t: String = quota_spans(&q, 10_000) let sp = quota_spans(&q, 10_000);
.iter() let t: String = sp.iter().map(|s| s.content.to_string()).collect();
.map(|s| s.content.to_string()) assert_eq!(t, "5h 42% ↻2h13m · week 91% ↻3d4h · credits: 37.5");
.collect(); assert_eq!(sp[2].style.fg, theme::t().err().fg);
assert_eq!(t, " · 5h 42%  2h13m · week 91%  3d4h · credits: 37.5");
assert_eq!(
quota_spans(&q, 10_000)[3].style.fg,
Some(ratatui::style::Color::Red)
);
assert_eq!(until(10_030, 10_000), "1m"); assert_eq!(until(10_030, 10_000), "1m");
} }
@@ -410,34 +350,35 @@ mod tests {
..Default::default() ..Default::default()
}; };
assert_eq!(text(footer(&st(), &c, 80, 0)), "[y/n] run rm?"); assert_eq!(text(footer(&st(), &c, 80, 0)), "[y/n] run rm?");
assert_eq!(rows(&st(), &c, 120, 0).len(), 1);
} }
#[test] #[test]
fn hint_replaces_right_side_and_narrow_drops_it() { fn status_row_and_hint_row() {
let c = Chrome { let c = Chrome {
hint: "saved", lens: "lsp 2/2 · lint 4",
..Default::default()
};
let wide = text(footer(&st(), &c, 100, 0));
assert!(wide.starts_with("ctx ") && wide.ends_with("saved") && !wide.contains("m1"));
let narrow = text(footer(&st(), &c, 10, 0));
assert_eq!(narrow, "saved");
}
#[test]
fn tail_shows_model_queue_scroll_and_title_when_it_fits() {
let c = Chrome {
queued: 2,
scroll: 5, scroll: 5,
title: Some("fix the parser"),
..Default::default() ..Default::default()
}; };
let l = text(footer(&st(), &c, 140, 0)); let r = rows(&st(), &c, 100, 0);
assert!(l.ends_with("Claude · m1 · 2 queued · ↑5"), "{l}"); let (a, b) = (text(r[0].clone()), text(r[1].clone()));
assert!(l.contains("fix the parser"), "{l}"); assert!(
// too narrow for a title: it goes first, the tail stays a.starts_with("m1 · ctx ▱▱▱▱▱▱▱▱▱▱ 0%") && a.ends_with("↑5"),
let l = text(footer(&st(), &c, 60, 0)); "{a}"
assert!(!l.contains("fix the parser") && l.contains("m1"), "{l}"); );
assert_eq!(a.chars().count(), 100);
assert!(
b.starts_with(KEYS) && b.ends_with("lsp 2/2 · lint 4"),
"{b}"
);
// a hint replaces the key hints, the status row stays
let h = Chrome { hint: "saved", ..c };
let r = rows(&st(), &h, 100, 0);
assert!(text(r[1].clone()).starts_with("saved"));
// narrow: one row, hint on the right of the status
assert_eq!(rows(&st(), &h, 60, 0).len(), 1);
assert!(text(footer(&st(), &h, 60, 0)).ends_with("saved"));
assert_eq!(text(footer(&st(), &h, 10, 0)), "saved");
} }
#[test] #[test]
@@ -458,40 +399,13 @@ mod tests {
assert_eq!(lens_summary(&[]), (String::new(), false)); assert_eq!(lens_summary(&[]), (String::new(), false));
} }
#[test]
fn wide_has_two_rows_and_hint_keeps_usage() {
let mut c = Chrome {
lens: "lsp 2/2 · lint 4",
hint: "saved",
title: Some("fix"),
..Default::default()
};
let r = rows(&st(), &c, 120, 0);
let (a, b) = (text(r[0].clone()), text(r[1].clone()));
assert!(
a.starts_with("ctx ") && a.contains("0↑ 0↓") && a.ends_with("saved"),
"{a}"
);
assert!(
b.starts_with("lsp 2/2") && b.ends_with("fix · Claude · m1"),
"{b}"
);
assert_eq!(b.chars().count(), 120);
assert_eq!(rows(&st(), &c, 80, 0).len(), 1);
c.ask = Some("rm?");
assert_eq!(rows(&st(), &c, 120, 0).len(), 1);
}
#[test] #[test]
fn context_bar_fill_and_color() { fn context_bar_fill_and_color() {
let mut s = st(); let mut s = st();
s.ctx_tokens = 135_000; s.ctx_tokens = 135_000;
let l = footer(&s, &Chrome::default(), 140, 0); let l = footer(&s, &Chrome::default(), 140, 0);
assert!( let t = text(l.clone());
text(l.clone()).starts_with("ctx ▰▰▰▰▰▰▰▰▰▱ 135k/150k"), assert!(t.starts_with("m1 · ctx ▰▰▰▰▰▰▰▰▰▱ 90%"), "{t}");
"{}", assert_eq!(l.spans[1].style.fg, theme::t().err().fg);
text(l.clone())
);
assert_eq!(l.spans[1].style.fg, Some(ratatui::style::Color::Red));
} }
} }
+164 -25
View File
@@ -1,14 +1,38 @@
//! Styles and symbols. `NO_COLOR` drops colours (modifiers stay); `HX_ASCII=1` swaps in ASCII symbols. //! Styles and symbols: Catppuccin Mocha, colour marks status only.
//! `NO_COLOR` drops colours (modifiers stay); `HX_ASCII=1` swaps in ASCII symbols;
//! without `COLORTERM=truecolor|24bit` colours map to the nearest xterm-256 entry.
//! The background is never painted, so the terminal's own ground shows through.
use ratatui::style::{Color, Modifier, Style}; use ratatui::style::{Color, Modifier, Style};
use std::sync::OnceLock; use std::sync::OnceLock;
/// Catppuccin Mocha.
pub mod mocha {
pub const TEXT: u32 = 0xcdd6f4;
pub const SUBTEXT0: u32 = 0xa6adc8;
pub const OVERLAY0: u32 = 0x6c7086;
pub const SURFACE1: u32 = 0x45475a;
pub const SURFACE0: u32 = 0x313244;
pub const PEACH: u32 = 0xfab387;
pub const YELLOW: u32 = 0xf9e2af;
pub const GREEN: u32 = 0xa6e3a1;
pub const RED: u32 = 0xf38ba8;
pub const BLUE: u32 = 0x89b4fa;
pub const MAUVE: u32 = 0xcba6f7;
pub const TEAL: u32 = 0x94e2d5;
/// Diff line backgrounds (green/red mixed into base).
pub const ADD_BG: u32 = 0x2b3a33;
pub const DEL_BG: u32 = 0x3d2a35;
}
pub struct Sym { pub struct Sym {
pub user: &'static str, pub user: &'static str,
pub asst: &'static str,
pub ok: &'static str, pub ok: &'static str,
pub done: &'static str,
pub err: &'static str, pub err: &'static str,
pub warn: &'static str,
pub pending: &'static str, pub pending: &'static str,
pub off: &'static str,
pub more: &'static str, pub more: &'static str,
pub gutter: &'static str, pub gutter: &'static str,
pub bar_full: &'static str, pub bar_full: &'static str,
@@ -17,14 +41,24 @@ pub struct Sym {
pub ellipsis: &'static str, pub ellipsis: &'static str,
pub minus: &'static str, pub minus: &'static str,
pub reset: &'static str, pub reset: &'static str,
pub queued: &'static str,
pub up: &'static str,
pub down: &'static str,
pub rule: &'static str,
pub branch: &'static str,
pub dirty: &'static str,
pub vrule: &'static str,
pub spin: &'static [&'static str],
} }
const UNICODE: Sym = Sym { const UNICODE: Sym = Sym {
user: "❯", user: "❯",
asst: "◆",
ok: "✓", ok: "✓",
done: "●",
err: "✗", err: "✗",
warn: "⚠",
pending: "○", pending: "○",
off: "○",
more: "▸", more: "▸",
gutter: "│", gutter: "│",
bar_full: "▰", bar_full: "▰",
@@ -32,15 +66,25 @@ const UNICODE: Sym = Sym {
info: "·", info: "·",
ellipsis: "…", ellipsis: "…",
minus: "−", minus: "−",
reset: "\u{f017} ", reset: "↻",
queued: "⏎",
up: "↑",
down: "↓",
rule: "┈",
branch: "⎇ ",
dirty: "●",
vrule: "│",
spin: &["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"],
}; };
const ASCII: Sym = Sym { const ASCII: Sym = Sym {
user: ">", user: ">",
asst: "*", ok: "v",
ok: "+", done: "*",
err: "x", err: "x",
warn: "!",
pending: "o", pending: "o",
off: "o",
more: ">", more: ">",
gutter: "|", gutter: "|",
bar_full: "#", bar_full: "#",
@@ -49,73 +93,155 @@ const ASCII: Sym = Sym {
ellipsis: "...", ellipsis: "...",
minus: "-", minus: "-",
reset: "in ", reset: "in ",
queued: ">>",
up: "^",
down: "v",
rule: "~",
branch: "@",
dirty: "*",
vrule: "|",
spin: &["-", "\\", "|", "/"],
}; };
pub struct Theme { pub struct Theme {
color: bool, color: bool,
truecolor: bool,
pub sym: &'static Sym, pub sym: &'static Sym,
} }
/// Nearest xterm-256 colour (6x6x6 cube or grey ramp).
fn to_256(rgb: u32) -> u8 {
let (r, g, b) = (
(rgb >> 16) as i32 & 255,
(rgb >> 8) as i32 & 255,
rgb as i32 & 255,
);
let lv = [0, 95, 135, 175, 215, 255];
let near = |v: i32| (0..6).min_by_key(|&i| (lv[i] - v).abs()).unwrap();
let (ri, gi, bi) = (near(r), near(g), near(b));
let cube = (lv[ri], lv[gi], lv[bi]);
let avg = (r + g + b) / 3;
let gi_ = ((avg - 8).max(0) / 10).min(23);
let grey = 8 + gi_ * 10;
let d = |(x, y, z): (i32, i32, i32)| (x - r).pow(2) + (y - g).pow(2) + (z - b).pow(2);
if d((grey, grey, grey)) < d(cube) {
232 + gi_ as u8
} else {
16 + (36 * ri + 6 * gi + bi) as u8
}
}
impl Theme { impl Theme {
pub fn new(color: bool, ascii: bool) -> Self { pub fn new(color: bool, ascii: bool) -> Self {
Self::with(color, true, ascii)
}
pub fn with(color: bool, truecolor: bool, ascii: bool) -> Self {
Self { Self {
color, color,
truecolor,
sym: if ascii { &ASCII } else { &UNICODE }, sym: if ascii { &ASCII } else { &UNICODE },
} }
} }
fn fg(&self, c: Color) -> Style { pub fn ascii(&self) -> bool {
std::ptr::eq(self.sym, &ASCII)
}
pub fn rgb(&self, c: u32) -> Color {
if self.truecolor {
Color::Rgb((c >> 16) as u8, (c >> 8) as u8, c as u8)
} else {
Color::Indexed(to_256(c))
}
}
fn fg(&self, c: u32) -> Style {
if self.color { if self.color {
Style::default().fg(c) Style::default().fg(self.rgb(c))
} else { } else {
Style::default() Style::default()
} }
} }
fn bg(&self, s: Style, c: u32) -> Style {
if self.color { s.bg(self.rgb(c)) } else { s }
}
/// Body text.
pub fn plain(&self) -> Style { pub fn plain(&self) -> Style {
Style::default() self.fg(mocha::TEXT)
} }
/// Secondary: paths, metadata, assistant-adjacent detail.
pub fn sec(&self) -> Style {
self.fg(mocha::SUBTEXT0)
}
/// Prompt, focus, working.
pub fn accent(&self) -> Style { pub fn accent(&self) -> Style {
self.fg(Color::Cyan) self.fg(mocha::PEACH)
} }
/// Decoration only: rules, hints.
pub fn dim(&self) -> Style { pub fn dim(&self) -> Style {
if self.color { if self.color {
self.fg(Color::DarkGray) self.fg(mocha::OVERLAY0)
} else { } else {
Style::default().add_modifier(Modifier::DIM) Style::default().add_modifier(Modifier::DIM)
} }
} }
pub fn ok(&self) -> Style { pub fn ok(&self) -> Style {
self.fg(Color::Green) self.fg(mocha::GREEN)
} }
pub fn warn(&self) -> Style { pub fn warn(&self) -> Style {
self.fg(Color::Yellow) self.fg(mocha::YELLOW)
} }
pub fn err(&self) -> Style { pub fn err(&self) -> Style {
self.fg(Color::Red) self.fg(mocha::RED)
}
/// Links, other-origin tags.
pub fn link(&self) -> Style {
self.fg(mocha::BLUE)
} }
pub fn add(&self) -> Style { pub fn add(&self) -> Style {
self.fg(Color::Green) self.bg(self.fg(mocha::GREEN), mocha::ADD_BG)
} }
pub fn del(&self) -> Style { pub fn del(&self) -> Style {
self.fg(Color::Red) self.bg(self.fg(mocha::RED), mocha::DEL_BG)
} }
pub fn hunk(&self) -> Style { pub fn hunk(&self) -> Style {
self.fg(Color::Cyan) self.fg(mocha::MAUVE)
} }
pub fn code(&self) -> Style { pub fn code(&self) -> Style {
self.fg(Color::Yellow) self.fg(mocha::TEAL)
} }
pub fn block_code(&self) -> Style { pub fn block_code(&self) -> Style {
self.fg(Color::Cyan) self.fg(mocha::TEAL)
} }
/// Selected row in lists. /// Selected row in lists: a band, text colours kept.
pub fn sel(&self) -> Style { pub fn sel(&self) -> Style {
if self.color { if self.color {
Style::default().bg(Color::DarkGray).fg(Color::White) self.bg(self.plain(), mocha::SURFACE0)
} else { } else {
Style::default().add_modifier(Modifier::REVERSED) Style::default().add_modifier(Modifier::REVERSED)
} }
} }
/// Border of boxes that carry input.
pub fn frame(&self) -> Style {
self.fg(mocha::SURFACE1)
}
/// `⠋`… spinner frame.
pub fn spin(&self, frame: usize) -> &'static str {
self.sym.spin[frame % self.sym.spin.len()]
}
/// `┈ label ┈┈┈` to `width` columns.
pub fn rule(&self, label: &str, width: usize) -> String {
let head = if label.is_empty() {
String::new()
} else {
format!("{} {label} ", self.sym.rule)
};
let n = width.saturating_sub(unicode_w(&head));
format!("{head}{}", self.sym.rule.repeat(n))
}
}
fn unicode_w(s: &str) -> usize {
ratatui::text::Span::raw(s).width()
} }
/// The process-wide theme, read from the environment once. /// The process-wide theme, read from the environment once.
@@ -123,7 +249,8 @@ pub fn t() -> &'static Theme {
static T: OnceLock<Theme> = OnceLock::new(); static T: OnceLock<Theme> = OnceLock::new();
T.get_or_init(|| { T.get_or_init(|| {
let set = |k| std::env::var_os(k).is_some_and(|v| !v.is_empty() && v != "0"); let set = |k| std::env::var_os(k).is_some_and(|v| !v.is_empty() && v != "0");
Theme::new(!set("NO_COLOR"), set("HX_ASCII")) let tc = std::env::var("COLORTERM").is_ok_and(|v| v == "truecolor" || v == "24bit");
Theme::with(!set("NO_COLOR"), tc, set("HX_ASCII"))
}) })
} }
@@ -134,12 +261,24 @@ mod tests {
#[test] #[test]
fn fallbacks() { fn fallbacks() {
let c = Theme::new(true, false); let c = Theme::new(true, false);
assert_eq!(c.err().fg, Some(Color::Red)); assert_eq!(c.err().fg, Some(Color::Rgb(0xf3, 0x8b, 0xa8)));
assert_eq!(c.sym.ok, "✓"); assert_eq!(c.sym.done, "●");
let n = Theme::new(false, true); let n = Theme::new(false, true);
assert_eq!(n.err().fg, None); assert_eq!(n.err().fg, None);
assert!(n.dim().add_modifier.contains(Modifier::DIM)); assert!(n.dim().add_modifier.contains(Modifier::DIM));
assert!(n.sel().add_modifier.contains(Modifier::REVERSED)); assert!(n.sel().add_modifier.contains(Modifier::REVERSED));
assert_eq!((n.sym.ok, n.sym.user), ("+", ">")); assert_eq!((n.sym.ok, n.sym.user, n.sym.warn), ("v", ">", "!"));
assert!(n.ascii() && !c.ascii());
assert_eq!(c.rule("lens", 10), "┈ lens ┈┈┈");
}
#[test]
fn indexed_fallback() {
assert_eq!(to_256(0x000000), 16);
assert_eq!(to_256(0xffffff), 231);
assert_eq!(to_256(0xff0000), 196);
assert_eq!(to_256(0x303030), 236);
let t = Theme::with(true, false, false);
assert!(matches!(t.ok().fg, Some(Color::Indexed(_))));
} }
} }
+190 -71
View File
@@ -30,6 +30,8 @@ pub enum Item {
#[derive(Default)] #[derive(Default)]
pub struct Transcript { pub struct Transcript {
pub items: Vec<Item>, pub items: Vec<Item>,
/// live output tails of running bash calls by command (copied from `State::live` per draw)
pub live: std::collections::HashMap<String, String>,
/// true while the last Assistant/Thinking item is still streaming /// true while the last Assistant/Thinking item is still streaming
streaming: bool, streaming: bool,
} }
@@ -97,6 +99,17 @@ impl Transcript {
let mut out = vec![]; let mut out = vec![];
for (n, it) in self.items.iter().enumerate() { for (n, it) in self.items.iter().enumerate() {
render(it, expanded, width as usize, &mut out); render(it, expanded, width as usize, &mut out);
if let Item::Tool {
name,
args,
result: None,
..
} = it
&& name == "bash"
&& let Some(tail) = args["command"].as_str().and_then(|c| self.live.get(c))
{
live_tail(tail, width as usize, &mut out);
}
// consecutive tool calls stack without a gap // consecutive tool calls stack without a gap
let tool = |i: Option<&Item>| matches!(i, Some(Item::Tool { .. })); let tool = |i: Option<&Item>| matches!(i, Some(Item::Tool { .. }));
if !(tool(Some(it)) && tool(self.items.get(n + 1))) { if !(tool(Some(it)) && tool(self.items.get(n + 1))) {
@@ -120,21 +133,58 @@ impl Transcript {
} }
} }
/// `⠹ bash 12s` — `frame` picks the spinner glyph, `elapsed` is shown in whole seconds. /// `⠹ working 38s · bash · ↓ 4.1k tokens esc to abort` — `frame` picks the spinner
pub fn activity_line(what: &str, elapsed: Duration, frame: usize) -> Line<'static> { /// glyph, `tokens` = output tokens of this run so far.
const SPIN: [&str; 10] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]; pub fn activity_line(
what: &str,
elapsed: Duration,
tokens: u64,
frame: usize,
width: u16,
) -> Line<'static> {
let th = theme::t(); let th = theme::t();
let g = if th.sym.ok == "+" { let tk = if tokens >= 1000 {
["-", "\\", "|", "/"][frame % 4] format!("{:.1}k", tokens as f64 / 1000.0)
} else { } else {
SPIN[frame % 10] tokens.to_string()
}; };
Line::from(vec![ let left = vec![
Span::styled(format!(" {g} "), th.accent()), Span::styled(format!("{} ", th.spin(frame)), th.accent()),
Span::styled(format!("{what} {}s", elapsed.as_secs()), th.dim()), Span::styled(format!("working {}s", elapsed.as_secs()), th.accent()),
]) Span::styled(
format!(" {0} {what} {0} {1} {tk} tokens", th.sym.info, th.sym.down),
th.sec(),
),
];
let hint = Span::styled("esc to abort", th.dim());
let lw: usize = left.iter().map(Span::width).sum();
let mut l = left;
if let Some(pad) = (width as usize).checked_sub(lw + hint.width() + 1) {
l.push(Span::raw(" ".repeat(pad + 1)));
l.push(hint);
}
Line::from(l)
} }
/// Last [`LIVE_LINES`] non-empty lines of a running command, dim and indented.
fn live_tail(tail: &str, width: usize, out: &mut Vec<Line<'static>>) {
let th = theme::t();
// carriage returns (progress bars): keep what's after the last one per line
let ls: Vec<&str> = tail
.lines()
.map(|l| l.rsplit('\r').next().unwrap_or(l))
.filter(|l| !l.trim().is_empty())
.collect();
for l in &ls[ls.len().saturating_sub(LIVE_LINES)..] {
out.push(Line::styled(
format!(" {}", fit(l, width.saturating_sub(4))),
th.dim(),
));
}
}
const LIVE_LINES: usize = 2;
fn target(args: &Value) -> String { fn target(args: &Value) -> String {
let s = ["path", "command", "pattern", "query"] let s = ["path", "command", "pattern", "query"]
.iter() .iter()
@@ -200,51 +250,55 @@ fn fit(s: &str, w: usize) -> String {
out + ell out + ell
} }
/// ` ✓ edit src/a.rs ············ +3 −1 0.2s ▸` /// `● edit src/a.rs ············ +3 −1 · 0.2s ▸`; running: spinner and live seconds.
fn tool_header( fn tool_header(
name: &str, name: &str,
args: &Value, args: &Value,
result: &Option<(String, bool)>, result: &Option<(String, bool)>,
started: Instant,
took: Option<Duration>, took: Option<Duration>,
folded: bool, folded: bool,
width: usize, width: usize,
) -> Line<'static> { ) -> Line<'static> {
let th = theme::t(); let th = theme::t();
let (mark, st) = match result { let (mark, st) = match result {
None => (th.sym.pending, th.warn()), None => (
Some((_, false)) => (th.sym.ok, th.ok()), th.spin((started.elapsed().as_millis() / 80) as usize),
th.accent(),
),
Some((_, false)) => (th.sym.done, th.ok()),
Some((_, true)) => (th.sym.err, th.err()), Some((_, true)) => (th.sym.err, th.err()),
}; };
let mut right = match result { let mut right = match result {
Some((c, e)) => outcome(name, c, *e), Some((c, e)) => outcome(name, c, *e),
None => String::new(), None => format!("{}s", started.elapsed().as_secs()),
}; };
if let Some(d) = took { if let Some(d) = took {
right = format!("{right} {}", fmt_dur(d)); right = format!("{right} {} {}", th.sym.info, fmt_dur(d));
} }
if folded { if folded {
right = format!("{right} {}", th.sym.more); right = format!("{right} {}", th.sym.more);
} }
let left = format!(" {mark} {name:<5} "); let left = format!("{mark} {name:<6} ");
let lw = Span::raw(left.as_str()).width(); let lw = Span::raw(left.as_str()).width();
let rw = Span::raw(right.as_str()).width(); let rw = Span::raw(right.as_str()).width();
let room = width.saturating_sub(lw + rw + 1).max(8); let room = width.saturating_sub(lw + rw + 1).max(8);
let tgt = fit(&target(args), room); let tgt = fit(&target(args), room);
let pad = width.saturating_sub(lw + Span::raw(tgt.as_str()).width() + rw); let pad = width.saturating_sub(lw + Span::raw(tgt.as_str()).width() + rw);
Line::from(vec![ Line::from(vec![
Span::styled(format!(" {mark} "), st), Span::styled(format!("{mark} "), st),
Span::styled( Span::styled(
format!("{name:<5} "), format!("{name:<6} "),
th.plain().add_modifier(Modifier::BOLD), th.plain().add_modifier(Modifier::BOLD),
), ),
Span::raw(tgt), Span::styled(tgt, th.sec()),
Span::raw(" ".repeat(pad.max(1))), Span::raw(" ".repeat(pad.max(1))),
Span::styled( Span::styled(
right, right,
if matches!(result, Some((_, true))) { match result {
th.err() Some((_, true)) => th.err(),
} else { None => th.accent(),
th.dim() _ => th.sec(),
}, },
), ),
]) ])
@@ -279,7 +333,7 @@ fn render(it: &Item, expanded: bool, width: usize, out: &mut Vec<Line<'static>>)
Item::Assistant(s) => { Item::Assistant(s) => {
let mut md = vec![]; let mut md = vec![];
markdown(s, &mut md); markdown(s, &mut md);
lead(md, th.sym.asst, th.accent(), out); lead(md, " ", th.plain(), out);
} }
Item::Thinking(s) if expanded => { Item::Thinking(s) if expanded => {
let st = th.dim().add_modifier(Modifier::ITALIC); let st = th.dim().add_modifier(Modifier::ITALIC);
@@ -301,6 +355,7 @@ fn render(it: &Item, expanded: bool, width: usize, out: &mut Vec<Line<'static>>)
name, name,
args, args,
result, result,
started,
took, took,
.. ..
} => { } => {
@@ -309,7 +364,9 @@ fn render(it: &Item, expanded: bool, width: usize, out: &mut Vec<Line<'static>>)
Some((content, err)) => tool_body(name, content, *err, expanded, &mut body), Some((content, err)) => tool_body(name, content, *err, expanded, &mut body),
None => false, None => false,
}; };
out.push(tool_header(name, args, result, *took, folded, width)); out.push(tool_header(
name, args, result, *started, *took, folded, width,
));
out.extend(body); out.extend(body);
} }
} }
@@ -319,10 +376,7 @@ fn render(it: &Item, expanded: bool, width: usize, out: &mut Vec<Line<'static>>)
/// collapsed, the first findings; `ctrl-o` shows all. /// collapsed, the first findings; `ctrl-o` shows all.
fn lens_block(texts: &[String], expanded: bool, width: usize, out: &mut Vec<Line<'static>>) { fn lens_block(texts: &[String], expanded: bool, width: usize, out: &mut Vec<Line<'static>>) {
let th = theme::t(); let th = theme::t();
let rule = if th.sym.ok == "+" { "-" } else { "┄" }; out.push(Line::styled(th.rule("lens", width), th.dim()));
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 { for t in texts {
let mut lines = t.lines(); let mut lines = t.lines();
let first = lines.next().unwrap_or_default(); let first = lines.next().unwrap_or_default();
@@ -338,7 +392,7 @@ fn lens_block(texts: &[String], expanded: bool, width: usize, out: &mut Vec<Line
let (mark, st) = if title.contains("failing") || errors > 0 { let (mark, st) = if title.contains("failing") || errors > 0 {
(th.sym.err, th.err()) (th.sym.err, th.err())
} else if warnings > 0 { } else if warnings > 0 {
("!", th.warn()) (th.sym.warn, th.warn())
} else { } else {
(th.sym.ok, th.ok()) (th.sym.ok, th.ok())
}; };
@@ -361,7 +415,7 @@ fn lens_block(texts: &[String], expanded: bool, width: usize, out: &mut Vec<Line
format!(" · {}", counts.join(", ")) format!(" · {}", counts.join(", "))
}; };
out.push(Line::from(vec![ out.push(Line::from(vec![
Span::styled(format!(" {mark} "), st), Span::styled(format!("{mark} "), st),
Span::raw(title.to_string()), Span::raw(title.to_string()),
Span::styled(counts, th.dim()), Span::styled(counts, th.dim()),
])); ]));
@@ -379,16 +433,17 @@ fn lens_block(texts: &[String], expanded: bool, width: usize, out: &mut Vec<Line
th.dim() th.dim()
}; };
out.push(Line::from(vec![ out.push(Line::from(vec![
Span::styled(format!(" {} ", th.sym.gutter), th.dim()), Span::styled(format!(" {} ", th.sym.gutter), th.dim()),
Span::styled(l.trim_start().to_string(), ls), Span::styled(l.trim_start().to_string(), ls),
])); ]));
} }
if n < rest.len() { if n < rest.len() {
out.push(Line::styled( out.push(Line::styled(
format!( format!(
" {} {} more lines (ctrl-o)", " {} {} more lines {} ctrl-o expand",
th.sym.ellipsis, th.sym.ellipsis,
rest.len() - n rest.len() - n,
th.sym.info
), ),
th.dim(), th.dim(),
)); ));
@@ -401,7 +456,8 @@ const DIFF_PREVIEW: usize = 6;
const ERR_TAIL: usize = 5; const ERR_TAIL: usize = 5;
/// Body lines behind a gutter. Collapsed: edit diff preview, error tail, nothing otherwise. /// Body lines behind a gutter. Collapsed: edit diff preview, error tail, nothing otherwise.
/// Returns true when output was hidden (header shows the fold marker). /// Diffs get new-file line numbers from the `@@` headers. Returns true when output was
/// hidden (header shows the fold marker).
fn tool_body( fn tool_body(
name: &str, name: &str,
content: &str, content: &str,
@@ -424,42 +480,80 @@ fn tool_body(
} else { } else {
(&lines[..0], 0, lines.len()) (&lines[..0], 0, lines.len())
}; };
let g = |st: Style| Span::styled(format!(" {} ", th.sym.gutter), st); // number column wide enough for the biggest new-file line in the hunks
let note = |s: String| Line::from(vec![g(th.dim()), Span::styled(s, th.dim())]); let nw = if is_diff {
lines
.iter()
.filter_map(|l| hunk_start(l))
.map(|n| (n + lines.len()).to_string().len())
.max()
.unwrap_or(0)
} else {
0
};
let g = |n: Option<usize>| {
let num = n.map_or(String::new(), |n| n.to_string());
Span::styled(format!(" {num:>nw$} {} ", th.sym.gutter), th.dim())
};
let note = |s: String| Line::from(vec![g(None), Span::styled(s, th.dim())]);
if before > 0 { if before > 0 {
out.push(note(format!( out.push(note(format!(
"{} {before} earlier lines (ctrl-o)", "{} {before} earlier lines {} ctrl-o expand",
th.sym.ellipsis th.sym.ellipsis, th.sym.info
))); )));
} }
let mut new_ln: Option<usize> = None;
for l in &lines[..before] {
new_ln = advance(new_ln, l);
}
for l in show { for l in show {
let st = if is_diff { let (st, num) = if is_diff {
let cur = new_ln.filter(|_| !l.starts_with('-') && !l.starts_with('@'));
new_ln = advance(new_ln, l);
match l.as_bytes().first() { match l.as_bytes().first() {
Some(b'+') if !l.starts_with("+++") => th.add(), Some(b'+') if !l.starts_with("+++") => (th.add(), cur),
Some(b'-') if !l.starts_with("---") => th.del(), Some(b'-') if !l.starts_with("---") => (th.del(), None),
Some(b'@') => th.hunk(), Some(b'@') => (th.hunk(), None),
_ => th.dim(), _ => (th.sec(), cur),
} }
} else if err { } else if err {
th.err() (th.err(), None)
} else { } else {
th.dim() (th.sec(), None)
}; };
out.push(Line::from(vec![ out.push(Line::from(vec![g(num), Span::styled(l.to_string(), st)]));
g(th.dim()),
Span::styled(l.to_string(), st),
]));
} }
if after > 0 && is_diff { if after > 0 && is_diff {
out.push(note(format!( out.push(note(format!(
"{} {after} more lines (ctrl-o)", "{} {after} more lines {} ctrl-o expand",
th.sym.ellipsis th.sym.ellipsis, th.sym.info
))); )));
} }
// write output is just the header's "N lines" // write output is just the header's "N lines"
!expanded && after > 0 && !is_diff && name != "write" !expanded && after > 0 && !is_diff && name != "write"
} }
/// `@@ -a,b +c,d @@` → `c`.
fn hunk_start(l: &str) -> Option<usize> {
let r = l
.strip_prefix("@@ ")?
.split(' ')
.nth(1)?
.strip_prefix('+')?;
r.split(',').next()?.parse().ok()
}
/// New-file line number for the line after `l`.
fn advance(cur: Option<usize>, l: &str) -> Option<usize> {
if let Some(n) = hunk_start(l) {
return Some(n);
}
match l.as_bytes().first() {
Some(b'-') => cur,
_ => cur.map(|n| n + 1),
}
}
/// Minimal markdown: fenced code, headings, bullets, inline `code` and **bold**. /// Minimal markdown: fenced code, headings, bullets, inline `code` and **bold**.
fn markdown(s: &str, out: &mut Vec<Line<'static>>) { fn markdown(s: &str, out: &mut Vec<Line<'static>>) {
let mut code = false; let mut code = false;
@@ -520,7 +614,6 @@ fn inline(l: &str) -> Line<'static> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use ratatui::style::Color;
use serde_json::json; use serde_json::json;
fn text(ls: &[Line]) -> Vec<String> { fn text(ls: &[Line]) -> Vec<String> {
@@ -569,9 +662,9 @@ mod tests {
let ls = t.lines(false, 40); let ls = t.lines(false, 40);
let s = text(&ls); let s = text(&ls);
assert_eq!(s[..2], ["❯ hi", " there"]); assert_eq!(s[..2], ["❯ hi", " there"]);
assert_eq!(s[3], "◆ Hello"); assert_eq!(s[3], " Hello");
assert!( assert!(
s[5].starts_with(" ✓ edit a.rs ") && s[5].contains("+1 −1 0.0s"), s[5].starts_with("● edit a.rs ") && s[5].contains("+1 −1 · 0.0s"),
"{s:?}" "{s:?}"
); );
assert_eq!(s[5].chars().count(), 40, "header fills the width"); assert_eq!(s[5].chars().count(), 40, "header fills the width");
@@ -579,7 +672,9 @@ mod tests {
.iter() .iter()
.find(|l| text(std::slice::from_ref(l))[0] == " │ -old") .find(|l| text(std::slice::from_ref(l))[0] == " │ -old")
.unwrap(); .unwrap();
assert_eq!(minus.spans[1].style.fg, Some(Color::Red)); assert_eq!(minus.spans[1].style.fg, theme::t().err().fg);
// new-file line numbers from the hunk header
assert!(s.contains(&" 1 │ +new".to_string()), "{s:?}");
} }
#[test] #[test]
@@ -596,7 +691,7 @@ mod tests {
let s = text(&out); let s = text(&out);
assert_eq!(s[0].chars().count(), w, "{s:?}"); assert_eq!(s[0].chars().count(), w, "{s:?}");
assert!( assert!(
s[0].starts_with(" ✗ bash cargo") && s[0].ends_with("exit 101 1.2s"), s[0].starts_with("✗ bash cargo") && s[0].ends_with("exit 101 · 1.2s"),
"{s:?}" "{s:?}"
); );
} }
@@ -612,7 +707,7 @@ mod tests {
let mut out = vec![]; let mut out = vec![];
render(&w, false, 50, &mut out); render(&w, false, 50, &mut out);
assert!( assert!(
text(&out)[0].ends_with(" 3 lines 1.2s"), text(&out)[0].ends_with(" 3 lines · 1.2s"),
"{:?}", "{:?}",
text(&out) text(&out)
); );
@@ -620,7 +715,7 @@ mod tests {
let mut out = vec![]; let mut out = vec![];
render(&r, false, 50, &mut out); render(&r, false, 50, &mut out);
assert_eq!(out.len(), 1); assert_eq!(out.len(), 1);
assert!(text(&out)[0].ends_with("2 lines 1.2s ▸"), "folded marker"); assert!(text(&out)[0].ends_with("2 lines · 1.2s ▸"), "folded marker");
} }
#[test] #[test]
@@ -629,8 +724,8 @@ mod tests {
let mut out = vec![]; let mut out = vec![];
assert!(!tool_body("bash", &body, true, false, &mut out)); assert!(!tool_body("bash", &body, true, false, &mut out));
let s = text(&out); let s = text(&out);
assert_eq!(s[0], " │ … 15 earlier lines (ctrl-o)"); assert_eq!(s[0], " │ … 15 earlier lines · ctrl-o expand");
assert_eq!(s.last().unwrap(), " │ l20"); assert_eq!(s.last().unwrap(), " │ l20");
out.clear(); out.clear();
assert!(tool_body("bash", &body, false, false, &mut out) && out.is_empty()); assert!(tool_body("bash", &body, false, false, &mut out) && out.is_empty());
assert!(!tool_body("bash", &body, false, true, &mut out)); assert!(!tool_body("bash", &body, false, true, &mut out));
@@ -640,7 +735,10 @@ mod tests {
"edited a\n".to_string() + &(1..=10).map(|i| format!("+l{i}\n")).collect::<String>(); "edited a\n".to_string() + &(1..=10).map(|i| format!("+l{i}\n")).collect::<String>();
tool_body("edit", &diff, false, false, &mut out); tool_body("edit", &diff, false, false, &mut out);
assert_eq!(out.len(), DIFF_PREVIEW + 1); assert_eq!(out.len(), DIFF_PREVIEW + 1);
assert_eq!(text(&out).last().unwrap(), " │ … 4 more lines (ctrl-o)"); assert_eq!(
text(&out).last().unwrap(),
" │ … 4 more lines · ctrl-o expand"
);
let mut out = vec![]; let mut out = vec![];
render(&Item::Thinking("a b c".into()), false, 40, &mut out); render(&Item::Thinking("a b c".into()), false, 40, &mut out);
assert_eq!(text(&out), [" thought · 3 words ▸"]); assert_eq!(text(&out), [" thought · 3 words ▸"]);
@@ -658,15 +756,15 @@ mod tests {
])); ]));
let s = text(&t.lines(false, 30)); let s = text(&t.lines(false, 30));
assert_eq!(s[0].chars().count(), 30); assert_eq!(s[0].chars().count(), 30);
assert!(s[0].starts_with(" ┄ lens ┄")); assert!(s[0].starts_with("┈ lens ┈"));
assert_eq!( assert_eq!(
s[1], s[1],
" ✗ diagnostics for files changed this turn · 1 error, 4 warnings" "✗ diagnostics for files changed this turn · 1 error, 4 warnings"
); );
assert_eq!(s[2], " │ src/a.rs:"); assert_eq!(s[2], " │ src/a.rs:");
assert_eq!(s[3], " │ 3:1 error: E0308 mismatched (rust-analyzer)"); assert_eq!(s[3], " │ 3:1 error: E0308 mismatched (rust-analyzer)");
assert_eq!(s[6], " … 2 more lines (ctrl-o)"); assert_eq!(s[6], " … 2 more lines · ctrl-o expand");
assert_eq!(s[7], " ✓ tests: all 21 selected tests pass now"); assert_eq!(s[7], "✓ tests: all 21 selected tests pass now");
assert_eq!( assert_eq!(
text(&t.lines(true, 30)).len(), text(&t.lines(true, 30)).len(),
10, 10,
@@ -676,14 +774,35 @@ mod tests {
#[test] #[test]
fn activity() { fn activity() {
let l = activity_line("bash", Duration::from_millis(12_900), 2); let l = activity_line("bash", Duration::from_millis(12_900), 4130, 2, 60);
assert_eq!(text(&[l]), [" ⠹ bash 12s"]); assert_eq!(
text(&[l]),
["⠹ working 12s · bash · ↓ 4.1k tokens esc to abort"]
);
}
#[test]
fn running_bash_shows_live_tail() {
let mut t = Transcript::default();
t.apply(&Event::ToolCall {
id: "1".into(),
name: "bash".into(),
args: json!({"command": "cargo test"}),
});
t.live.insert(
"cargo test".into(),
" Compiling a\n\n Compiling b\nprogress 10%\rprogress 90%\n".into(),
);
let s = text(&t.lines(false, 40));
assert_eq!(s[1..3], [" Compiling b", " progress 90%"], "{s:?}");
t.live.clear();
assert_eq!(t.lines(false, 40).len(), 2, "no tail when nothing is live");
} }
#[test] #[test]
fn inline_md() { fn inline_md() {
assert_eq!(text(&[inline("a `b` **c** d")]), ["a b c d"]); assert_eq!(text(&[inline("a `b` **c** d")]), ["a b c d"]);
assert_eq!(inline("a `b` c").spans[1].style.fg, Some(Color::Yellow)); assert_eq!(inline("a `b` c").spans[1].style.fg, theme::t().code().fg);
assert_eq!(text(&[inline("x ` unclosed")]), ["x ` unclosed"]); assert_eq!(text(&[inline("x ` unclosed")]), ["x ` unclosed"]);
} }
} }
+4 -4
View File
@@ -55,7 +55,6 @@ def check(label, needle):
pump(1.5) pump(1.5)
check("startup footer", "Claude") check("startup footer", "Claude")
check("latest default model", "claude-sonnet-5-5") check("latest default model", "claude-sonnet-5-5")
check("1M window", "/900k")
send(b"l1"); send(b"\x1b[13;2u"); send(b"l2") # shift-enter as CSI-u (kitty protocol) send(b"l1"); send(b"\x1b[13;2u"); send(b"l2") # shift-enter as CSI-u (kitty protocol)
check("shift-enter is a newline, not a submit", "l1") check("shift-enter is a newline, not a submit", "l1")
send(b"\x15\x7f\x15") # kill line 2, join, kill line 1 send(b"\x15\x7f\x15") # kill line 2, join, kill line 1
@@ -78,12 +77,13 @@ check("file written", "") if os.path.exists(f"{tmp}/repo/hello.txt") else (print
check("quota in footer", "5h 42%") check("quota in footer", "5h 42%")
send(b"/usage\r") send(b"/usage\r")
check("usage report", "58% left, resets in 2h1") check("usage report", "58% left, resets in 2h1")
check("1M window", "of 900k")
send(b"/model claude-opus-5-5\r") send(b"/model claude-opus-5-5\r")
check("model switch", "model → claude-opus-5-5 (Claude) · context 1000k") check("model switch", "opus-5-5 (Claude) · context 1000k")
send(b"/model gpt-5.6-sol\r") send(b"/model gpt-5.6-sol\r")
check("gpt model needs codex login", "not logged in to Codex") check("gpt model needs codex login", "not logged in to Codex")
send(b"/model claude-sonnet-5-6-preview\r") send(b"/model claude-sonnet-5-6-preview\r")
check("live catalog window", "context 2000k") check("live catalog window", "2000k")
check("live catalog cached", "") if os.path.exists(f"{tmp}/home/.hx/models-claude.json") else (print("FAIL no model cache"), globals().update(ok=False)) check("live catalog cached", "") if os.path.exists(f"{tmp}/home/.hx/models-claude.json") else (print("FAIL no model cache"), globals().update(ok=False))
buf = b"" buf = b""
send(b"/provider ") send(b"/provider ")
@@ -102,7 +102,7 @@ check("picker resumes session", "hx · OLDPROMPT about parsers")
send(b"/new\r") send(b"/new\r")
check("new session", "new session") check("new session", "new session")
send(b"/sessions\r") send(b"/sessions\r")
check("sessions picker", "enter resume · tab scope") check("sessions picker", "all projects")
send(b"make", 0.8) send(b"make", 0.8)
check("sessions filter", "make hello.txt") check("sessions filter", "make hello.txt")
send(b"\r", 1) send(b"\r", 1)