From 79bd3b8ea73afa776417e9ad891fea211d5c8734 Mon Sep 17 00:00:00 2001 From: hermes Date: Fri, 9 Oct 2026 14:51:00 +0000 Subject: [PATCH 1/2] tui: new design (Catppuccin Mocha, header, framed input, 3-col popup, sessions picker, /lsp panel) --- crates/hx-tui/src/agents.rs | 7 +- crates/hx-tui/src/lib.rs | 495 ++++++++++++++++++++++++-------- crates/hx-tui/src/sessions.rs | 193 +++++++++---- crates/hx-tui/src/status.rs | 280 +++++++----------- crates/hx-tui/src/theme.rs | 189 ++++++++++-- crates/hx-tui/src/transcript.rs | 197 ++++++++----- tests/tui_smoke.py | 8 +- 7 files changed, 907 insertions(+), 462 deletions(-) diff --git a/crates/hx-tui/src/agents.rs b/crates/hx-tui/src/agents.rs index 3b13ea4..7cea768 100644 --- a/crates/hx-tui/src/agents.rs +++ b/crates/hx-tui/src/agents.rs @@ -61,9 +61,8 @@ fn dur(d: Duration) -> String { fn glyph(s: &Status, frame: usize) -> &'static str { let th = theme::t(); match s { - Status::Running if th.sym.ok == "+" => ["-", "\\", "|", "/"][frame % 4], - Status::Running => ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"][frame % 10], - Status::Done => th.sym.ok, + Status::Running => th.spin(frame), + Status::Done => th.sym.done, _ => th.sym.err, } } @@ -239,7 +238,7 @@ mod tests { assert!( 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('…')); } diff --git a/crates/hx-tui/src/lib.rs b/crates/hx-tui/src/lib.rs index cee9157..8ced469 100644 --- a/crates/hx-tui/src/lib.rs +++ b/crates/hx-tui/src/lib.rs @@ -188,6 +188,9 @@ struct App { sub_t: std::collections::HashMap, /// subagent list focused / one agent open agents: Option, + /// header: `~`-shortened cwd and (branch, dirty), refreshed after each run + cwd_label: String, + git: Option<(String, bool)>, } impl App { @@ -213,7 +216,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 · \ 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. const WIDE: u16 = 140; @@ -330,6 +333,8 @@ pub async fn run(setup: Setup) -> std::io::Result<()> { expanded: false, busy: false, queue: VecDeque::new(), + cwd_label: home_short(&cwd), + git: git_head(&cwd), st: status::Status { kind: switcher.kind(), model: agent.model().to_string(), @@ -503,6 +508,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> { } Ui::Done(r) => { app.busy = false; + app.git = git_head(&cwd); match r { Err(e) if e == "aborted" => app.t.push(Item::Info("aborted".into())), Err(e) => app.t.push(Item::Error(e)), @@ -584,6 +590,65 @@ pub async fn run(setup: Setup) -> std::io::Result<()> { } /// Sessions live next to the current one. +/// `left … right` across `w` columns. +fn spread_line(l: Span<'static>, r: Span<'static>, w: u16) -> Line<'static> { + let pad = (w as usize).saturating_sub(l.width() + r.width()).max(1); + Line::from(vec![l, Span::raw(" ".repeat(pad)), r]) +} + +/// `~/Repos/hx` for `$HOME/Repos/hx`. +fn home_short(p: &std::path::Path) -> String { + match std::env::var_os("HOME").map(std::path::PathBuf::from) { + Some(h) if p.starts_with(&h) => format!("~/{}", p.strip_prefix(&h).unwrap().display()) + .trim_end_matches('/') + .to_string(), + _ => p.display().to_string(), + } +} + +/// Current branch (or short hash) and whether the tree is dirty; None outside a repo. +fn git_head(cwd: &std::path::Path) -> Option<(String, bool)> { + let out = std::process::Command::new("git") + .args([ + "status", + "--porcelain=v1", + "--branch", + "--untracked-files=no", + ]) + .current_dir(cwd) + .output() + .ok() + .filter(|o| o.status.success())?; + let s = String::from_utf8_lossy(&out.stdout); + let mut ls = s.lines(); + let head = ls.next()?.strip_prefix("## ")?; + let b = head.split("...").next()?.split(' ').next()?; + let b = b.strip_prefix("No commits yet on ").unwrap_or(b); + Some((b.to_string(), ls.next().is_some())) +} + +/// `hx ~/Repos/hx ⎇ main● model` +fn header(app: &App, w: u16) -> Line<'static> { + let th = theme::t(); + let mut l = vec![ + Span::styled("hx", th.accent().add_modifier(Modifier::BOLD)), + Span::styled(format!(" {}", app.cwd_label), th.sec()), + ]; + if let Some((b, dirty)) = &app.git { + l.push(Span::styled(format!(" {}{b}", th.sym.branch), th.sec())); + if *dirty { + l.push(Span::styled(th.sym.dirty, th.accent())); + } + } + let m = Span::styled(app.st.model.clone(), th.sec()); + let lw: usize = l.iter().map(Span::width).sum(); + if lw + m.width() + 2 <= w as usize { + l.push(Span::raw(" ".repeat(w as usize - lw - m.width()))); + l.push(m); + } + Line::from(l) +} + fn sessions_dir(app: &App) -> &std::path::Path { app.session_path .parent() @@ -1366,10 +1431,6 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) { } } if app.busy { - app.t.push(Item::Info(format!( - "queued: {}", - line.lines().next().unwrap_or_default() - ))); app.queue.push_back(line); return; } @@ -1397,10 +1458,11 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) { fn draw(f: &mut ratatui::Frame, app: &mut App) { let th = theme::t(); - let 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 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; if let Some(agents::View::Detail { id, ed, scroll }) = &mut app.agents { let subs = app.state.subs.list(); @@ -1431,7 +1493,8 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) { .filter(|r| focused || r.ended.is_none_or(|e| e < agents::LINGER)) .collect(); let foot_h = status::rows_for(f.area().width, app.ask.is_some()); - let [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::Length(agents::list_height(sub_rows.len())), Constraint::Length(act_h), @@ -1439,6 +1502,7 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) { Constraint::Length(foot_h), ]) .areas(f.area()); + f.render_widget(header(app, head.width), head); let main = match &app.panel { Some((title, text)) if app.wide => { @@ -1447,9 +1511,24 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) { let block = Block::new() .borders(Borders::LEFT) .border_style(th.dim()) - .title(Span::styled(format!(" {title} · esc "), th.dim())); + .padding(ratatui::widgets::Padding::horizontal(1)); 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 .panel_scroll .resolve(para.line_count(body.width) as u16, body.height); @@ -1460,14 +1539,23 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) { } None if app.wide && app.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() .borders(Borders::LEFT) .border_style(th.dim()) - .title(Span::styled(" lens · ctrl-l ", th.dim())); + .padding(ratatui::widgets::Padding::horizontal(1)); let body = block.inner(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(); m } @@ -1497,18 +1585,40 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) { subs_area, ); } + // queued prompts, then the activity line, right above the input + let mut al: Vec = app + .queue + .iter() + .take(3) + .map(|q| { + Line::from(vec![ + Span::styled(format!("{} queued ", th.sym.queued), th.dim()), + Span::styled(q.lines().next().unwrap_or_default().to_string(), th.sec()), + ]) + }) + .collect(); if app.busy { - let (what, 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; - f.render_widget(transcript::activity_line(&what, t0.elapsed(), frame), act); + al.push(transcript::activity_line( + &what, + app.since.elapsed(), + frame, + act.width, + )); } + f.render_widget(Paragraph::new(al), act); - let block = Block::default() - .borders(Borders::TOP | Borders::BOTTOM) - .border_style(th.dim()); + let block = Block::bordered() + .border_type(ratatui::widgets::BorderType::Rounded) + .border_style(th.frame()); let inner = block.inner(input); f.render_widget(block, input); let [gut, text] = Layout::horizontal([Constraint::Length(2), Constraint::Min(1)]).areas(inner); + let text = Rect { + width: text.width.saturating_sub(1), + ..text + }; f.render_widget( Span::styled( format!("{} ", th.sym.user), @@ -1553,7 +1663,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], ) .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)); if let Some(p) = &app.picker { @@ -1576,41 +1686,125 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) { } } -/// Right-hand overview on wide terminals: lens state, context numbers, MCP servers. -fn side_lines(app: &App) -> Vec> { +/// Right-hand lens panel on wide terminals: servers, last turn's diagnostics and tests, +/// context numbers, MCP servers. Built from `/lsp` status lines and the last lens report. +fn side_lines(app: &App, w: usize) -> Vec> { let th = theme::t(); - let head = |t: &str| Line::styled(t.to_string(), th.accent()); - let mut l = vec![head("LSP / LINT")]; + let sec = |label: String| { + Line::styled( + th.rule(&label, w) + .replacen(th.sym.rule, "", 1) + .trim_start() + .to_string(), + th.dim(), + ) + }; + let mut l = vec![]; if app.lens_lines.is_empty() { - l.push(Line::styled("(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()), + ])); + } + // last lens report in the transcript + let last = app.t.items.iter().rev().find_map(|i| match i { + Item::Lens(v) => Some(v), + _ => None, + }); + let diag = last.and_then(|v| v.iter().find(|t| t.contains("diagnostics"))); + let tests = last.and_then(|v| v.iter().find(|t| t.contains("test"))); + if let Some(d) = diag { + let mut file = ""; + let mut items = vec![]; + for x in d.lines().skip(1) { + if let Some(f) = x.strip_suffix(':').filter(|_| !x.starts_with(' ')) { + file = f.rsplit('/').next().unwrap_or(f); + } else if let Some((pos, rest)) = x.trim().split_once(' ') { + let (mark, st) = if rest.starts_with("error") { + (th.sym.err, th.err()) + } else { + (th.sym.warn, th.warn()) + }; + let msg = rest.split_once(": ").map_or(rest, |p| p.1); + // drop the trailing `(server)` tag + let msg = msg.rsplit_once(" (").map_or(msg, |p| p.0); + items.push(Line::from(vec![ + Span::styled(format!("{mark} "), st), + Span::styled(format!("{file}:{pos}"), th.plain()), + ])); + items.push(Line::styled(format!(" {msg}"), th.sec())); + } + } + l.push(Line::default()); + l.push(sec(format!("diagnostics {}", items.len() / 2))); + l.extend(items); + } + if let Some(t) = tests { + let first = t.lines().next().unwrap_or_default(); + let first = first + .strip_prefix("[lens] ") + .unwrap_or(first) + .trim_end_matches(':'); + let bad = first.contains("failing"); + l.push(Line::default()); + l.push(sec("tests".into())); + l.push(Line::from(vec![ + Span::styled( + format!("{} ", if bad { th.sym.err } else { th.sym.ok }), + if bad { th.err() } else { th.ok() }, + ), + Span::styled(first.trim_start_matches("tests: ").to_string(), th.plain()), + ])); + l.extend( + t.lines() + .skip(1) + .map(|x| Line::styled(format!(" {}", x.trim()), th.sec())), + ); } - 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 tot = u.input_tokens + u.cache_read_tokens + u.cache_write_tokens; l.push(Line::default()); - l.push(head("CONTEXT")); - l.push(Line::raw(format!( - "window {}k / {}k", - app.st.ctx_tokens / 1000, - app.st.ctx_max / 1000 - ))); + l.push(sec("context".into())); + let mut ctx = format!("{}k / {}k", app.st.ctx_tokens / 1000, app.st.ctx_max / 1000); if let Some(p) = (100 * u.cache_read_tokens).checked_div(tot) { - 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() { l.push(Line::default()); - l.push(head("MCP")); + l.push(sec("mcp".into())); l.extend(app.mcp.iter().map(|(n, ok)| { Line::from(vec![ Span::styled( - if *ok { "● " } else { "○ " }, + format!("{} ", if *ok { th.sym.done } else { th.sym.err }), if *ok { th.ok() } else { th.err() }, ), - Span::raw(n.clone()), + Span::styled(n.clone(), th.plain()), ]) })); } @@ -1644,49 +1838,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). -fn draw_popup(f: &mut ratatui::Frame, c: &Completion, sel: usize, x: u16, bottom: u16) { +/// `(source tag, summary)` from a slash-command candidate's detail (`mcp · summary`). +fn split_source(label: &str, detail: &str) -> (&'static str, String) { + if !label.starts_with('/') { + return ("", detail.to_string()); + } + for (pre, tag) in [ + ("skill · ", "skill"), + ("mcp · ", "mcp prompt"), + ("ext · ", "ext"), + ] { + if let Some(r) = detail.strip_prefix(pre) { + return (tag, r.to_string()); + } + } + ("builtin", detail.to_string()) +} + +/// Framed candidate list ending just above row `bottom`, starting at column `x` (the token): +/// `commands · 4 of 19` header, name | summary | source columns, key hints underneath. +fn draw_popup( + f: &mut ratatui::Frame, + c: &Completion, + sel: usize, + x: u16, + bottom: u16, + total: usize, +) { let th = theme::t(); - let lw = c + let area = f.area(); + let rows_: Vec<(&str, &'static str, String)> = c .items .iter() - .map(|i| i.label.chars().count()) - .max() - .unwrap_or(0); - // scroll so the selected row stays visible when there are more items than rows - let rows = (bottom as usize).saturating_sub(2).max(1); + .map(|i| { + let (tag, d) = split_source(&i.label, &i.detail); + (i.label.as_str(), tag, d) + }) + .collect(); + let cw = + |f: &dyn Fn(&(&str, &'static str, String)) -> usize| rows_.iter().map(f).max().unwrap_or(0); + let lw = cw(&|r| r.0.chars().count()); + let tw = cw(&|r| r.1.chars().count()); + let max_w = area.width.saturating_sub(2) as usize; + // summary column takes what's left, capped so the box doesn't span huge terminals + let dw = cw(&|r| r.2.chars().count()) + .min(48) + .min(max_w.saturating_sub(lw + tw + 7)); + let inner_w = 1 + lw + 2 + dw + if tw > 0 { 2 + tw } else { 0 } + 1; + let cmds = c.items.first().is_some_and(|i| i.label.starts_with('/')); + let kind = if cmds { + "commands" + } else if c.items.first().is_some_and(|i| i.label.starts_with('@')) { + "files" + } else { + "values" + }; + let head = if cmds && total > 0 { + format!(" {kind} {} {} of {total}", th.sym.info, c.items.len()) + } else { + format!(" {kind} {} {}", th.sym.info, c.items.len()) + }; + // header + rows + hints, plus the frame; scroll so the selected row stays visible + let rows = (bottom as usize).saturating_sub(4).max(1); let off = (sel + 1) .saturating_sub(rows) .min(c.items.len().saturating_sub(rows)); - let lines: Vec = c - .items - .iter() - .enumerate() - .skip(off) - .take(rows) - .map(|(n, i)| { - let base = if n == sel { th.sel() } else { th.plain() }; - Line::from(vec![ - Span::styled(format!(" {: 0 { + let ts = if *tag == "builtin" { + th.dim() + } else { + th.link() + }; + v.push(Span::styled(format!(" {tag:>tw$}"), band.patch(ts))); + } + v.push(Span::styled(" ", band)); + lines.push(Line::from(v)); + } + lines.push(Line::styled( + format!(" ↑↓ select {0} tab/enter accept {0} esc close", th.sym.info), + th.dim(), + )); + let w = (inner_w.max(lines.last().map_or(0, Line::width) + 1) as u16 + 2).min(area.width); let h = (lines.len() as u16 + 2).min(bottom); let x = x.saturating_sub(1).min(area.width - w); let r = Rect::new(x, bottom - h, w, h); f.render_widget(Clear, r); f.render_widget( - Paragraph::new(lines).block(Block::bordered().border_style(th.dim())), + Paragraph::new(lines).block( + Block::bordered() + .border_type(ratatui::widgets::BorderType::Rounded) + .border_style(th.frame()), + ), r, ); } +/// Cut to `n` chars with an ellipsis. +fn cut_to(s: &str, n: usize) -> String { + if s.chars().count() <= n { + return s.into(); + } + let mut t: String = s.chars().take(n.saturating_sub(1)).collect(); + t.push('…'); + t +} + #[cfg(test)] mod tests { use super::*; @@ -1721,10 +1988,13 @@ mod tests { .collect(); let all = rows.join("\n"); assert!(all.contains("❯ hello"), "{all}"); - assert!(all.contains("◆ hi there"), "{all}"); - assert!(rows[7].starts_with("❯ typing"), "{all}"); - assert!(rows[9].starts_with("ctx ▰▱▱▱▱▱▱▱▱▱ 12k/150k "), "{all}"); - assert!(rows[9].ends_with("Claude · m1"), "{all}"); + assert!(all.contains(" hi there"), "{all}"); + assert!( + rows[0].starts_with("hx ~/w") && rows[0].ends_with("m1"), + "{all}" + ); + assert!(rows[7].starts_with("│❯ typing"), "{all}"); + assert!(rows[9].starts_with("m1 · ctx ▰▱▱▱▱▱▱▱▱▱ 8%"), "{all}"); } fn screen(app: &mut App, w: u16, h: u16) -> String { @@ -1798,10 +2068,15 @@ mod tests { let mut app = test_app(); app.mcp = vec![("git".into(), true), ("db".into(), false)]; app.lens_lines = vec!["rust-analyzer @ /p: running".into()]; - assert!(screen(&mut app, 160, 50).contains("MCP")); - assert!(!screen(&mut app, 80, 24).contains("MCP")); + let s = screen(&mut app, 160, 50); + assert!( + s.contains("/lsp") && s.contains("● rust-analyzer ready"), + "{s}" + ); + assert!(s.contains("mcp ┈") && s.contains("✗ db"), "{s}"); + assert!(!screen(&mut app, 80, 24).contains("/lsp")); app.side = false; - assert!(!screen(&mut app, 160, 50).contains("MCP")); + assert!(!screen(&mut app, 160, 50).contains("/lsp")); } #[test] @@ -1913,7 +2188,7 @@ mod tests { }) .collect(); assert!( - all.contains("✓ 1 explore") && all.contains("find x"), + all.contains("● 1 explore") && all.contains("find x"), "{all}" ); } @@ -1943,13 +2218,13 @@ mod tests { }; let rows = draw_at(&mut app, 60, 20); 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); 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[19].contains("↑8"), + rows[19].ends_with("↑7"), "footer shows lines behind: {}", rows[19] ); @@ -1958,17 +2233,17 @@ mod tests { long_chat(&mut app, 10); let rows = draw_at(&mut app, 60, 20); 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 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); let rows = draw_at(&mut app, 60, 20); assert!(rows.iter().any(|r| r.contains("line 0")), "{rows:#?}"); press(&mut app, KeyCode::End, KeyModifiers::CONTROL); let rows = draw_at(&mut app, 60, 20); assert!(rows[14].contains("line 9"), "bottom: {rows:#?}"); - assert!(rows[19].ends_with("Claude · m1"), "{}", rows[19]); + assert!(rows[19].starts_with("m1 · ctx"), "{}", rows[19]); // plain Home still edits text and doesn't scroll app.ed.insert("abc"); press(&mut app, KeyCode::Home, KeyModifiers::NONE); @@ -2056,6 +2331,8 @@ mod tests { fn test_app() -> App { App { + cwd_label: "~/w".into(), + git: None, t: Transcript::default(), ed: Editor::default(), files: vec!["src/main.rs".into(), "src/lib.rs".into()], @@ -2155,12 +2432,15 @@ mod tests { let rows: Vec = (0..10) .map(|y| (0..40).map(|x| buf[(x, y)].symbol().to_string()).collect()) .collect(); - assert_eq!( - rows[3], "│ /clear alias of /new │", - "{rows:#?}" + let all = rows.join("\n"); + // 10 rows: the popup scrolls to 2 candidates and covers the header + assert!(rows[1].contains("commands · 3 of"), "{all}"); + assert!( + rows[2].starts_with("│ /copy copy") && rows[2].contains("builtin"), + "{all}" ); - assert!(rows[4].starts_with("│ /compact summarize"), "{rows:#?}"); - assert!(rows[9].ends_with("Claude · m1"), "{rows:#?}"); + assert!(rows[4].contains("↑↓ select"), "{all}"); + assert!(rows[9].starts_with("m1 · ctx"), "{all}"); // footer at 100 cols, and a hint replacing only the right side app.hint = "no match".into(); @@ -2168,32 +2448,14 @@ mod tests { term.draw(|f| draw(f, &mut app)).unwrap(); let buf = term.backend().buffer().clone(); let row = |y| -> String { (0..100).map(|x| buf[(x, y)].symbol().to_string()).collect() }; - let (last, lens) = (row(8), row(9)); - assert!( - last.starts_with("ctx ▱▱▱▱▱▱▱▱▱▱ 0k/150k · 0↑ 0↓") && last.ends_with("no match"), - "{last}" - ); - assert!( - lens.starts_with("lens: starting") && lens.ends_with("Claude · m1"), - "{lens}" - ); + let (stat, hints) = (row(8), row(9)); + assert!(stat.starts_with("m1 · ctx ▱▱▱▱▱▱▱▱▱▱ 0%"), "{stat}"); + assert!(hints.starts_with("no match"), "{hints}"); app.hint.clear(); - let mut foot = |app: &mut App| { - term.draw(|f| draw(f, app)).unwrap(); - let buf = term.backend().buffer().clone(); - (0..100) - .map(|x| buf[(x, 9)].symbol().to_string()) - .collect::() - }; - 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; + term.draw(|f| draw(f, &mut app)).unwrap(); + let buf = term.backend().buffer().clone(); + let hints: String = (0..100).map(|x| buf[(x, 9)].symbol().to_string()).collect(); + assert!(hints.starts_with(status::KEYS), "{hints}"); key(&mut app, KeyCode::Down); key(&mut app, KeyCode::Up); key(&mut app, KeyCode::Up); @@ -2283,10 +2545,13 @@ mod tests { assert!(app.t.items.is_empty()); term.draw(|f| draw(f, &mut app)).unwrap(); let buf = term.backend().buffer().clone(); - let row0: String = (0..160).map(|x| buf[(x, 0)].symbol().to_string()).collect(); - assert!(row0.contains("│ skills · esc"), "{row0}"); - let row1: String = (0..160).map(|x| buf[(x, 1)].symbol().to_string()).collect(); - assert!(row1.contains("│skills (0):"), "{row1}"); + let row = |y| -> String { (0..160).map(|x| buf[(x, y)].symbol().to_string()).collect() }; + assert!( + row(1).contains("│ /skills") && row(1).ends_with("esc × "), + "{}", + row(1) + ); + assert!(row(3).contains("│ skills (0):"), "{}", row(3)); key(&mut app, KeyCode::Esc); assert!(app.panel.is_none()); app.wide = false; diff --git a/crates/hx-tui/src/sessions.rs b/crates/hx-tui/src/sessions.rs index 717d4b5..9542c92 100644 --- a/crates/hx-tui/src/sessions.rs +++ b/crates/hx-tui/src/sessions.rs @@ -4,8 +4,9 @@ use crate::theme; use crate::transcript::{Item, Transcript}; use hx_core::session::{self, Meta}; use ratatui::layout::{Constraint, Layout, Rect}; +use ratatui::style::{Modifier, Style}; 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::time::SystemTime; @@ -134,48 +135,62 @@ impl Sessions { Act::None } + /// Full-screen: scope tabs and count, framed query, list | preview, key hints. pub fn draw(&mut self, f: &mut ratatui::Frame) { let th = theme::t(); let a = f.area(); - let r = Rect::new(a.x + 1, a.y, a.width.saturating_sub(2), a.height); - let scope = if self.all_scope { - "this project ▸ all projects" - } else { - "this project ▸ all (tab)" - }; + f.render_widget(Clear, a); let ms: Vec = self.matches().into_iter().cloned().collect(); - let block = Block::bordered().border_style(th.dim()).title(Span::styled( - 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([ + let [tabs, q, body, help] = Layout::vertical([ Constraint::Length(1), - Constraint::Length(1), - Constraint::Length(list_h), - Constraint::Length(1), - Constraint::Min(0), + Constraint::Length(3), + Constraint::Min(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( Line::from(vec![ 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 .sel .saturating_sub(list.height.saturating_sub(1) as usize); let w = list.width as usize; let rows: Vec = if ms.is_empty() { - vec![Line::styled(" no sessions", th.dim())] + vec![Line::styled(" no sessions", th.dim())] } else { ms.iter() .enumerate() @@ -186,60 +201,118 @@ impl Sessions { }; f.render_widget(Paragraph::new(rows), list); f.render_widget( - Block::new().borders(Borders::TOP).border_style(th.dim()), - sep, + Block::new().borders(Borders::LEFT).border_style(th.dim()), + Rect { + x: rule.x + 1, + width: 1, + ..rule + }, ); if let Some(m) = ms.get(self.sel) { 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 { - let skip = ls.len().saturating_sub(prev.height as usize); - f.render_widget(Paragraph::new(ls[skip..].to_vec()), prev); + let pr = Rect { + x: prev.x + 1, + width: prev.width.saturating_sub(1), + ..prev + }; + let room = pr.height as usize; + let shown: Vec = 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 { Some(p) => Line::styled(format!("delete {}? [y/n]", p.display()), th.warn()), 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(), ), }; 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> { let th = theme::t(); - let st = if sel { th.sel() } else { th.plain() }; - let dim = if sel { st } else { th.dim() }; - 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) + let st = if sel { + th.sel().add_modifier(Modifier::BOLD) } else { - String::new() + th.plain() }; - let tail = if self.all_scope { - m.project.clone() + let band = if sel { th.sel() } else { Style::default() }; + let cur = if m.path == self.current { + th.sym.dirty } else { - m.model.clone().unwrap_or_default() + " " }; - let tail = tail.strip_prefix("claude-").unwrap_or(&tail); - let right = format!("{fork}{:>4} msg {:<16}", m.messages, cut(tail, 16)); - let left = format!("{mark}{cur} {:<9} ", ago(m.modified)); - let room = w.saturating_sub(left.chars().count() + right.chars().count() + 1); + let mut right = short_age(m.modified); + if self.all_scope { + right = format!("{} {right}", cut(&m.project, 16)); + } + let room = w.saturating_sub(right.chars().count() + 5); 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![ - Span::styled(left, dim), + Span::styled(format!(" {cur} "), band.patch(th.accent())), Span::styled(title, st), - Span::styled(" ".repeat(pad + 1), st), - Span::styled(right, dim), + Span::styled(" ".repeat(pad), band), + 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 { if s.chars().count() <= n { return s.into(); @@ -396,24 +469,28 @@ mod tests { let rows = screen(&mut s, 100, 20); let all = rows.join("\n"); 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}" ); - assert!(rows[1].contains("❯ pars"), "{all}"); + assert!(rows[2].contains("❯ pars"), "{all}"); assert!( - rows[3].contains("▸ just now parser: handle trailing commas") - && rows[3].contains("3 msg opus"), + rows[4].contains(" parser: handle trailing commas") && rows[4].contains(" now "), "{all}" ); + assert!(all.contains("opus · 3 msgs · just now"), "meta: {all}"); assert!( all.contains("❯ parser: handle trailing commas"), "preview: {all}" ); assert!( - all.contains("✓ edit src/parse.rs"), + all.contains("● edit src/parse.rs"), "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 s.query.clear(); @@ -421,20 +498,20 @@ mod tests { assert_eq!(titles(&s)[0], "elsewhere"); let rows = screen(&mut s, 100, 20); assert!( - rows[3].contains("elsewhere") && rows[3].contains("other"), + rows[4].contains("elsewhere") && rows[4].contains("other"), "{rows:#?}" ); s.key(k(KeyCode::Tab)); // current session is marked and can't be deleted; others need y 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)); assert!(s.confirm.is_none()); s.key(k(KeyCode::Down)); s.key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL)); 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'))); assert!(first.exists()); s.key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL)); diff --git a/crates/hx-tui/src/status.rs b/crates/hx-tui/src/status.rs index 1453cab..c458362 100644 --- a/crates/hx-tui/src/status.rs +++ b/crates/hx-tui/src/status.rs @@ -41,8 +41,11 @@ pub struct Chrome<'a> { pub lens_warn: bool, } -/// Terminals at least this wide get a second footer row. -pub const TWO_ROWS: u16 = 100; +/// Terminals at least this wide get the key-hint row under the status row. +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). 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) } -/// Footer lines: two rows on wide terminals (usage on top; lens left, session tail right), -/// else the single packed line from [`footer`]. A hint only replaces the top row's right side. +/// Footer: status row, then on terminals of [`TWO_ROWS`]+ a dim key-hint row with the lens +/// summary on the right. A transient hint replaces the key hints. pub fn rows(st: &Status, c: &Chrome, width: u16, now: u64) -> Vec> { - if rows_for(width, c.ask.is_some()) == 1 { - return vec![footer(st, c, width, now)]; - } - let th = theme::t(); - let w = width as usize; - let lw = |l: &[Span]| l.iter().map(Span::width).sum::(); - 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() + let mut v = vec![footer(st, c, width, now)]; + if rows_for(width, c.ask.is_some()) == 2 { + let th = theme::t(); + let (keys, kst) = if c.hint.is_empty() { + (KEYS, th.dim()) } else { - title.into() + (c.hint, th.accent()) }; - format!("{t} · {tail}") - } else { - tail - }; - let r = Span::styled(right, th.dim()); - bot.push(Span::raw( - " ".repeat(w.saturating_sub(lw(&bot) + r.width()).max(1)), - )); - bot.push(r); - vec![Line::from(top), Line::from(bot)] + v.push(spread( + vec![Span::styled(keys.to_string(), kst)], + vec![Span::styled( + c.lens.to_string(), + if c.lens_warn { th.warn() } else { th.dim() }, + )], + width as usize, + )); + } + v } -/// Context bar, quota windows, token counts and cost estimate. -fn left_spans(st: &Status, now: u64) -> Vec> { +/// `left … right` padded to `w`; the right side is dropped when both don't fit. +fn spread(mut left: Vec>, right: Vec>, 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> { 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 full = ((frac * 10.0).round() as usize).min(10); let bar_st = match frac { @@ -151,90 +134,48 @@ fn left_spans(st: &Status, now: u64) -> Vec> { .map(|p| format!(" ~${:.2}", st.usage.cost(&p))) .unwrap_or_default(), }; - let mut left = vec![ - Span::styled("ctx ", th.dim()), + let model = st.model.strip_prefix("claude-").unwrap_or(&st.model); + 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_empty.repeat(10 - full), th.dim()), - Span::styled( - 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 + Span::styled(format!(" {:.0}%{cost}", frac * 100.0), th.sec()), + ] } -/// `ctx ▰▰▰▱▱▱▱▱▱▱ 41k/150k · 12.3k↑ 2.1k↓ ~$0.08` left, `Claude · model · 1 queued` right. -/// Hints replace the right side; a pending y/n question takes the whole line. +/// Status row: `model · ctx ▰▰▰▱▱▱▱▱▱▱ 31%` left, quota / think / scroll right. +/// 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> { let th = theme::t(); if let Some(q) = c.ask { 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 lw = |l: &[Span]| l.iter().map(Span::width).sum::(); - if !c.hint.is_empty() { - let right = Span::styled(c.hint.to_string(), th.accent()); - if lw(&left) + right.width() + 1 > w { - return Line::from(right); + let mut right = vec![]; + if !c.hint.is_empty() && rows_for(width, false) == 1 { + right.push(Span::styled(c.hint.to_string(), th.accent())); + let l = spread(left_spans(st), right.clone(), w); + 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(); - left.push(Span::raw(" ".repeat(pad))); - left.push(right); - return Line::from(left); + right.push(Span::styled(t, th.sec())); } - let tail = tail(st, c); - 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) + spread(left_spans(st), right, w) } fn tail(st: &Status, c: &Chrome) -> Vec { - let mut t = vec![format!("{:?}", st.kind), st.model.clone()]; + let mut t = vec![]; if st.effort != hx_ai::Effort::Off { t.push(format!("think {}", st.effort.name())); } - if c.queued > 0 { - t.push(format!("{} queued", c.queued)); - } if c.scroll > 0 { - t.push(format!("↑{}", c.scroll)); + t.push(format!("{}{}", theme::t().sym.up, c.scroll)); } 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> { let th = theme::t(); let mut v = vec![]; + let sep = || Span::styled(format!(" {} ", th.sym.info), th.dim()); for w in &q.windows { let st = match w.used_pct { p if p >= 90.0 => th.err(), p if p >= 70.0 => th.warn(), - _ => th.dim(), + _ => th.sec(), }; let reset = w .resets_at .map(|r| format!(" {}{}", th.sym.reset, until(r, now))) .unwrap_or_default(); - v.push(Span::styled(" · ", th.dim())); + if !v.is_empty() { + v.push(sep()); + } v.push(Span::styled( format!("{} {:.0}%{reset}", w.label, w.used_pct), st, )); } 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 } @@ -325,7 +270,7 @@ mod tests { fn st() -> Status { Status { kind: Kind::Claude, - model: "m1".into(), + model: "claude-m1".into(), effort: hx_ai::Effort::Off, usage: Usage::default(), ctx_tokens: 0, @@ -360,15 +305,10 @@ mod tests { #[test] fn quota_spans_and_countdown() { let q = quota(); - let t: String = quota_spans(&q, 10_000) - .iter() - .map(|s| s.content.to_string()) - .collect(); - 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) - ); + let sp = quota_spans(&q, 10_000); + let t: String = sp.iter().map(|s| s.content.to_string()).collect(); + assert_eq!(t, "5h 42% ↻2h13m · week 91% ↻3d4h · credits: 37.5"); + assert_eq!(sp[2].style.fg, theme::t().err().fg); assert_eq!(until(10_030, 10_000), "1m"); } @@ -410,34 +350,35 @@ mod tests { ..Default::default() }; assert_eq!(text(footer(&st(), &c, 80, 0)), "[y/n] run rm?"); + assert_eq!(rows(&st(), &c, 120, 0).len(), 1); } #[test] - fn hint_replaces_right_side_and_narrow_drops_it() { + fn status_row_and_hint_row() { let c = Chrome { - hint: "saved", - ..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, + lens: "lsp 2/2 · lint 4", scroll: 5, - title: Some("fix the parser"), ..Default::default() }; - let l = text(footer(&st(), &c, 140, 0)); - assert!(l.ends_with("Claude · m1 · 2 queued · ↑5"), "{l}"); - assert!(l.contains("fix the parser"), "{l}"); - // too narrow for a title: it goes first, the tail stays - let l = text(footer(&st(), &c, 60, 0)); - assert!(!l.contains("fix the parser") && l.contains("m1"), "{l}"); + let r = rows(&st(), &c, 100, 0); + let (a, b) = (text(r[0].clone()), text(r[1].clone())); + assert!( + a.starts_with("m1 · ctx ▱▱▱▱▱▱▱▱▱▱ 0%") && a.ends_with("↑5"), + "{a}" + ); + 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] @@ -458,40 +399,13 @@ mod tests { 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] fn context_bar_fill_and_color() { let mut s = st(); s.ctx_tokens = 135_000; let l = footer(&s, &Chrome::default(), 140, 0); - assert!( - text(l.clone()).starts_with("ctx ▰▰▰▰▰▰▰▰▰▱ 135k/150k"), - "{}", - text(l.clone()) - ); - assert_eq!(l.spans[1].style.fg, Some(ratatui::style::Color::Red)); + let t = text(l.clone()); + assert!(t.starts_with("m1 · ctx ▰▰▰▰▰▰▰▰▰▱ 90%"), "{t}"); + assert_eq!(l.spans[1].style.fg, theme::t().err().fg); } } diff --git a/crates/hx-tui/src/theme.rs b/crates/hx-tui/src/theme.rs index cc7ef1b..f010b2f 100644 --- a/crates/hx-tui/src/theme.rs +++ b/crates/hx-tui/src/theme.rs @@ -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 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 user: &'static str, - pub asst: &'static str, pub ok: &'static str, + pub done: &'static str, pub err: &'static str, + pub warn: &'static str, pub pending: &'static str, + pub off: &'static str, pub more: &'static str, pub gutter: &'static str, pub bar_full: &'static str, @@ -17,14 +41,24 @@ pub struct Sym { pub ellipsis: &'static str, pub minus: &'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 { user: "❯", - asst: "◆", ok: "✓", + done: "●", err: "✗", + warn: "⚠", pending: "○", + off: "○", more: "▸", gutter: "│", bar_full: "▰", @@ -32,15 +66,25 @@ const UNICODE: Sym = Sym { info: "·", ellipsis: "…", minus: "−", - reset: "\u{f017} ", + reset: "↻", + queued: "⏎", + up: "↑", + down: "↓", + rule: "┈", + branch: "⎇ ", + dirty: "●", + vrule: "│", + spin: &["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"], }; const ASCII: Sym = Sym { user: ">", - asst: "*", - ok: "+", + ok: "v", + done: "*", err: "x", + warn: "!", pending: "o", + off: "o", more: ">", gutter: "|", bar_full: "#", @@ -49,73 +93,155 @@ const ASCII: Sym = Sym { ellipsis: "...", minus: "-", reset: "in ", + queued: ">>", + up: "^", + down: "v", + rule: "~", + branch: "@", + dirty: "*", + vrule: "|", + spin: &["-", "\\", "|", "/"], }; pub struct Theme { color: bool, + truecolor: bool, 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 { pub fn new(color: bool, ascii: bool) -> Self { + Self::with(color, true, ascii) + } + pub fn with(color: bool, truecolor: bool, ascii: bool) -> Self { Self { color, + truecolor, 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 { - Style::default().fg(c) + Style::default().fg(self.rgb(c)) } else { 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 { - 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 { - self.fg(Color::Cyan) + self.fg(mocha::PEACH) } + /// Decoration only: rules, hints. pub fn dim(&self) -> Style { if self.color { - self.fg(Color::DarkGray) + self.fg(mocha::OVERLAY0) } else { Style::default().add_modifier(Modifier::DIM) } } pub fn ok(&self) -> Style { - self.fg(Color::Green) + self.fg(mocha::GREEN) } pub fn warn(&self) -> Style { - self.fg(Color::Yellow) + self.fg(mocha::YELLOW) } 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 { - self.fg(Color::Green) + self.bg(self.fg(mocha::GREEN), mocha::ADD_BG) } pub fn del(&self) -> Style { - self.fg(Color::Red) + self.bg(self.fg(mocha::RED), mocha::DEL_BG) } pub fn hunk(&self) -> Style { - self.fg(Color::Cyan) + self.fg(mocha::MAUVE) } pub fn code(&self) -> Style { - self.fg(Color::Yellow) + self.fg(mocha::TEAL) } 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 { if self.color { - Style::default().bg(Color::DarkGray).fg(Color::White) + self.bg(self.plain(), mocha::SURFACE0) } else { 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. @@ -123,7 +249,8 @@ pub fn t() -> &'static Theme { static T: OnceLock = OnceLock::new(); T.get_or_init(|| { 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] fn fallbacks() { let c = Theme::new(true, false); - assert_eq!(c.err().fg, Some(Color::Red)); - assert_eq!(c.sym.ok, "✓"); + assert_eq!(c.err().fg, Some(Color::Rgb(0xf3, 0x8b, 0xa8))); + assert_eq!(c.sym.done, "●"); let n = Theme::new(false, true); assert_eq!(n.err().fg, None); assert!(n.dim().add_modifier.contains(Modifier::DIM)); 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(_)))); } } diff --git a/crates/hx-tui/src/transcript.rs b/crates/hx-tui/src/transcript.rs index b2df0f8..b18caf0 100644 --- a/crates/hx-tui/src/transcript.rs +++ b/crates/hx-tui/src/transcript.rs @@ -120,19 +120,22 @@ impl Transcript { } } -/// `⠹ bash 12s` — `frame` picks the spinner glyph, `elapsed` is shown in whole seconds. -pub fn activity_line(what: &str, elapsed: Duration, frame: usize) -> Line<'static> { - const SPIN: [&str; 10] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]; +/// `⠹ working 38s · bash esc to abort` — `frame` picks the spinner glyph. +pub fn activity_line(what: &str, elapsed: Duration, frame: usize, width: u16) -> Line<'static> { let th = theme::t(); - let g = if th.sym.ok == "+" { - ["-", "\\", "|", "/"][frame % 4] - } else { - SPIN[frame % 10] - }; - Line::from(vec![ - Span::styled(format!(" {g} "), th.accent()), - Span::styled(format!("{what} {}s", elapsed.as_secs()), th.dim()), - ]) + let left = vec![ + Span::styled(format!("{} ", th.spin(frame)), th.accent()), + Span::styled(format!("working {}s", elapsed.as_secs()), th.accent()), + Span::styled(format!(" {} {what}", th.sym.info), 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) } fn target(args: &Value) -> String { @@ -200,51 +203,55 @@ fn fit(s: &str, w: usize) -> String { 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( name: &str, args: &Value, result: &Option<(String, bool)>, + started: Instant, took: Option, folded: bool, width: usize, ) -> Line<'static> { let th = theme::t(); let (mark, st) = match result { - None => (th.sym.pending, th.warn()), - Some((_, false)) => (th.sym.ok, th.ok()), + None => ( + 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()), }; let mut right = match result { Some((c, e)) => outcome(name, c, *e), - None => String::new(), + None => format!("{}s", started.elapsed().as_secs()), }; if let Some(d) = took { - right = format!("{right} {}", fmt_dur(d)); + right = format!("{right} {} {}", th.sym.info, fmt_dur(d)); } if folded { 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 rw = Span::raw(right.as_str()).width(); let room = width.saturating_sub(lw + rw + 1).max(8); let tgt = fit(&target(args), room); let pad = width.saturating_sub(lw + Span::raw(tgt.as_str()).width() + rw); Line::from(vec![ - Span::styled(format!(" {mark} "), st), + Span::styled(format!("{mark} "), st), Span::styled( - format!("{name:<5} "), + format!("{name:<6} "), th.plain().add_modifier(Modifier::BOLD), ), - Span::raw(tgt), + Span::styled(tgt, th.sec()), Span::raw(" ".repeat(pad.max(1))), Span::styled( right, - if matches!(result, Some((_, true))) { - th.err() - } else { - th.dim() + match result { + Some((_, true)) => th.err(), + None => th.accent(), + _ => th.sec(), }, ), ]) @@ -279,7 +286,7 @@ fn render(it: &Item, expanded: bool, width: usize, out: &mut Vec>) Item::Assistant(s) => { let mut md = vec![]; markdown(s, &mut md); - lead(md, th.sym.asst, th.accent(), out); + lead(md, " ", th.plain(), out); } Item::Thinking(s) if expanded => { let st = th.dim().add_modifier(Modifier::ITALIC); @@ -301,6 +308,7 @@ fn render(it: &Item, expanded: bool, width: usize, out: &mut Vec>) name, args, result, + started, took, .. } => { @@ -309,7 +317,9 @@ fn render(it: &Item, expanded: bool, width: usize, out: &mut Vec>) Some((content, err)) => tool_body(name, content, *err, expanded, &mut body), 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); } } @@ -319,10 +329,7 @@ fn render(it: &Item, expanded: bool, width: usize, out: &mut Vec>) /// collapsed, the first findings; `ctrl-o` shows all. fn lens_block(texts: &[String], expanded: bool, width: usize, out: &mut Vec>) { let th = theme::t(); - let rule = if th.sym.ok == "+" { "-" } else { "┄" }; - let head = format!(" {rule} lens "); - let fill = rule.repeat(width.saturating_sub(Span::raw(head.as_str()).width())); - out.push(Line::styled(format!("{head}{fill}"), th.dim())); + out.push(Line::styled(th.rule("lens", width), th.dim())); for t in texts { let mut lines = t.lines(); let first = lines.next().unwrap_or_default(); @@ -338,7 +345,7 @@ fn lens_block(texts: &[String], expanded: bool, width: usize, out: &mut Vec 0 { (th.sym.err, th.err()) } else if warnings > 0 { - ("!", th.warn()) + (th.sym.warn, th.warn()) } else { (th.sym.ok, th.ok()) }; @@ -361,7 +368,7 @@ fn lens_block(texts: &[String], expanded: bool, width: usize, out: &mut Vec