diff --git a/crates/hx-cli/src/main.rs b/crates/hx-cli/src/main.rs index 010cbf0..cc71aff 100644 --- a/crates/hx-cli/src/main.rs +++ b/crates/hx-cli/src/main.rs @@ -1155,11 +1155,28 @@ async fn main() -> Result<()> { open_sessions, yolo: cli.yolo || cfg.permissions.as_deref() == Some("yolo"), auto: cli.auto || cfg.permissions.as_deref() == Some("auto"), - mcp: mcp - .servers - .iter() - .map(|(n, s)| (n.clone(), s.st().error.is_none())) - .collect(), + mcp: { + let mcp = mcp.clone(); + Box::new(move || { + mcp.servers + .iter() + .map(|(n, s)| { + let st = s.st(); + hx_tui::side::McpRow { + name: n.clone(), + state: match (&st.error, st.pending) { + (Some(_), _) => hx_tui::side::McpState::Failed, + (None, true) => hx_tui::side::McpState::Pending, + (None, false) => hx_tui::side::McpState::Ok, + }, + tools: st.tools.len(), + prompts: st.prompts.len(), + error: st.error.clone(), + } + }) + .collect() + }) + }, mouse: cfg.mouse.unwrap_or(true) && std::env::var_os("HX_MOUSE").is_none_or(|v| v != "0"), commands: { diff --git a/crates/hx-tui/src/lib.rs b/crates/hx-tui/src/lib.rs index 732a4c4..98ce67e 100644 --- a/crates/hx-tui/src/lib.rs +++ b/crates/hx-tui/src/lib.rs @@ -11,6 +11,7 @@ pub mod review; pub mod scroll; pub mod select; pub mod sessions; +pub mod side; pub mod stats_view; pub mod status; pub mod theme; @@ -51,7 +52,7 @@ pub struct Setup { pub mouse: bool, pub yolo: bool, pub auto: bool, - pub mcp: Vec<(String, bool)>, + pub mcp: side::McpStatus, } #[derive(Default, Clone, Copy)] @@ -154,7 +155,11 @@ struct App { snap: Option>>, side: bool, lens_lines: Vec, - mcp: Vec<(String, bool)>, + mcp: Vec, + log: side::LogRing, + consult: Option, + seen_subs: std::collections::HashMap, + mode: &'static str, choose: Option<( choose::Choose, tokio::sync::oneshot::Sender>>, @@ -179,6 +184,58 @@ impl App { if sw.provider_changed { self.st.quota = None; } + self.log.push("main", format!("model {}", self.st.model)); + } + + fn sync_log(&mut self) { + for s in self.state.subs.list() { + let st = match s.sh.status() { + hx_core::subagent::Status::Running => "started".to_string(), + hx_core::subagent::Status::Done => { + format!("done {}s", s.sh.elapsed().as_secs()) + } + hx_core::subagent::Status::Failed(e) => format!("failed {e}"), + hx_core::subagent::Status::Aborted => "aborted".into(), + }; + let key = format!("{} {}", s.sh.model, st); + if self.seen_subs.get(&s.sh.id) != Some(&key) { + self.log.push( + format!("{} {}", s.sh.kind, s.sh.model), + st, + ); + self.seen_subs.insert(s.sh.id, key); + } + } + } + + fn sync_lens_log(&mut self, new: &[String]) { + let state = |x: &str| { + x.split_once(" @ ") + .map(|(n, r)| (n.to_string(), r.rsplit_once(": ").map_or("", |p| p.1).to_string())) + .unwrap_or_else(|| (x.to_string(), String::new())) + }; + for x in new { + let (n, s) = state(x); + let old = self.lens_lines.iter().map(|o| state(o)).find(|o| o.0 == n); + if old.as_ref().map(|o| &o.1) != Some(&s) && !s.is_empty() { + self.log.push("lsp", format!("{n} {s}")); + } + } + } + + fn sync_mcp(&mut self, new: Vec) { + for m in &new { + let old = self.mcp.iter().find(|o| o.name == m.name).map(|o| o.state); + if old != Some(m.state) && m.state != side::McpState::Pending { + let what = match (&m.state, &m.error) { + (side::McpState::Failed, Some(e)) => format!("{} failed: {e}", m.name), + (side::McpState::Failed, None) => format!("{} failed", m.name), + _ => format!("{} up {} tools", m.name, m.tools), + }; + self.log.push("mcp", what); + } + } + self.mcp = new; } fn ctx_max_from(&mut self, a: &Agent) { @@ -233,7 +290,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> { mouse, yolo, auto, - mcp, + mcp: mcp_status, } = setup; let kbd = crossterm::terminal::supports_keyboard_enhancement().unwrap_or(false); let (tx, mut rx) = mpsc::unbounded_channel(); @@ -350,12 +407,25 @@ pub async fn run(setup: Setup) -> std::io::Result<()> { snap: Some(agent.snap()), side: true, lens_lines: vec![], - mcp, + mcp: vec![], + log: Default::default(), + consult: None, + seen_subs: Default::default(), + mode: if yolo { + "yolo" + } else if auto { + "auto" + } else { + "ask" + }, state: agent.cx.state.clone(), sub_t: Default::default(), agents: None, }; sessions::history(&mut app.t, &agent.session().messages()); + let first = mcp_status(); + app.sync_mcp(first); + app.log.push("main", format!("model {}", app.st.model)); if open_sessions { open_sessions_picker(&mut app); } @@ -601,15 +671,23 @@ pub async fn run(setup: Setup) -> std::io::Result<()> { } t.apply(&ev); } - _ = tick.tick(), if app.busy || subs_running(&app) => dirty = true, + _ = tick.tick(), if app.busy || subs_running(&app) => { + app.sync_log(); + dirty = true; + } _ = lens_tick.tick() => { let to = std::time::Duration::from_millis(200); if let Ok(v) = tokio::time::timeout(to, lsp_status()).await { let s = status::lens_summary(&v); + app.sync_lens_log(&v); app.lens_lines = v; dirty |= s != app.lens; app.lens = s; } + let m = mcp_status(); + dirty |= m != app.mcp; + app.sync_mcp(m); + app.sync_log(); } } } @@ -1806,14 +1884,32 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) { f.render_widget(block, side); let mut ls = vec![ spread_line( - Span::styled("/lsp", th.accent().add_modifier(Modifier::BOLD)), + Span::styled("/status", 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); + let lens = app + .state + .lens + .lock() + .unwrap_or_else(|e| e.into_inner()) + .clone(); + let subs = app.state.subs.list(); + ls.extend(side::lines(&side::View { + st: &app.st, + mode: app.mode, + lens_lines: &app.lens_lines, + lens: &lens, + mcp: &app.mcp, + subs: &subs, + consult: app.consult.as_ref(), + log: &app.log, + w: body.width as usize, + h: (body.height as usize).saturating_sub(2), + })); + f.render_widget(Paragraph::new(ls), body); app.areas.panel = Rect::default(); m } @@ -1953,128 +2049,6 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) { } } -const SIDE_DIAGS: usize = 8; -const SIDE_TESTS: usize = 6; - -fn side_lines(app: &App, w: usize) -> Vec> { - let th = theme::t(); - 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("no servers started", th.dim())); - } - for x in &app.lens_lines { - 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(); - 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(), - )); - } - } - let u = &app.st.usage; - let tot = u.input_tokens + u.cache_read_tokens + u.cache_write_tokens; - l.push(Line::default()); - 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) { - ctx += &format!(" {} cache {p}%", th.sym.info); - } - l.push(Line::styled(ctx, th.sec())); - if !app.mcp.is_empty() { - l.push(Line::default()); - l.push(sec("mcp".into())); - l.extend(app.mcp.iter().map(|(n, ok)| { - Line::from(vec![ - Span::styled( - format!("{} ", if *ok { th.sym.done } else { th.sym.err }), - if *ok { th.ok() } else { th.err() }, - ), - Span::styled(n.clone(), th.plain()), - ]) - })); - } - l -} - fn skills_list(specs: &[CmdSpec], dirs: &[std::path::PathBuf]) -> String { let sk: Vec = specs .iter() @@ -2322,7 +2296,23 @@ mod tests { #[test] fn side_panel_only_on_wide_terminals() { let mut app = test_app(); - app.mcp = vec![("git".into(), true), ("db".into(), false)]; + app.mcp = vec![ + side::McpRow { + name: "git".into(), + state: side::McpState::Ok, + tools: 3, + prompts: 0, + error: None, + }, + side::McpRow { + name: "db".into(), + state: side::McpState::Failed, + tools: 0, + prompts: 0, + error: Some("refused".into()), + }, + ]; + app.log.push("lsp", "rust-analyzer running"); app.lens_lines = vec!["rust-analyzer @ /p: running".into()]; *app.state.lens.lock().unwrap() = hx_core::LensView { diags: vec![hx_core::Diag { @@ -2336,23 +2326,21 @@ mod tests { }; 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.contains("LSP") && s.contains("⚠ codemode.rs:88 unused variable"), "{s}" ); + assert!(s.contains("TESTS") && 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.contains("/status") && s.contains("● rust-analyzer") && s.contains("ready"), "{s}" ); - assert!(s.contains("mcp ┈") && s.contains("✗ db"), "{s}"); - assert!(!screen(&mut app, 80, 24).contains("/lsp")); + assert!(s.contains("MCP") && s.contains("✗ db"), "{s}"); + assert!(s.contains("MODEL") && s.contains("SESSION LOG"), "{s}"); + assert!(!screen(&mut app, 80, 24).contains("/status")); app.side = false; - assert!(!screen(&mut app, 160, 50).contains("/lsp")); + assert!(!screen(&mut app, 160, 50).contains("/status")); } #[test] @@ -2647,6 +2635,10 @@ mod tests { side: true, lens_lines: vec![], mcp: vec![], + log: Default::default(), + consult: None, + seen_subs: Default::default(), + mode: "ask", state: Default::default(), sub_t: Default::default(), agents: None, diff --git a/crates/hx-tui/src/side.rs b/crates/hx-tui/src/side.rs new file mode 100644 index 0000000..4609bf8 --- /dev/null +++ b/crates/hx-tui/src/side.rs @@ -0,0 +1,672 @@ +use crate::status::Status; +use crate::theme; +use hx_core::LensView; +use hx_core::subagent::{Status as SubStatus, Sub}; +use ratatui::style::{Modifier, Style}; +use ratatui::text::{Line, Span}; +use std::collections::VecDeque; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +const DIAGS: usize = 6; +const TESTS: usize = 5; +const LOG_ROWS: usize = 8; +const LOG_CAP: usize = 50; + +#[derive(Clone, Copy, PartialEq, Debug)] +pub enum McpState { + Pending, + Ok, + Failed, +} + +#[derive(Clone, PartialEq, Debug)] +pub struct McpRow { + pub name: String, + pub state: McpState, + pub tools: usize, + pub prompts: usize, + pub error: Option, +} + +pub type McpStatus = Box Vec + Send>; + +#[derive(Clone, PartialEq, Debug)] +pub struct Consult { + pub model: String, + pub advising: bool, + pub consults: u32, + pub last: Option<(Duration, Duration)>, + pub triggers: Vec<(String, bool)>, +} + +pub struct LogRing { + start: Instant, + items: VecDeque<(Duration, String, String)>, +} + +impl Default for LogRing { + fn default() -> Self { + LogRing { + start: Instant::now(), + items: VecDeque::new(), + } + } +} + +impl LogRing { + pub fn push(&mut self, src: impl Into, text: impl Into) { + let (src, text) = (src.into(), text.into()); + if self.items.back().is_some_and(|l| l.1 == src && l.2 == text) { + return; + } + if self.items.len() == LOG_CAP { + self.items.pop_front(); + } + self.items.push_back((self.start.elapsed(), src, text)); + } + + pub fn len(&self) -> usize { + self.items.len() + } + + pub fn is_empty(&self) -> bool { + self.items.is_empty() + } +} + +pub struct View<'a> { + pub st: &'a Status, + pub mode: &'a str, + pub lens_lines: &'a [String], + pub lens: &'a LensView, + pub mcp: &'a [McpRow], + pub subs: &'a [Arc], + pub consult: Option<&'a Consult>, + pub log: &'a LogRing, + pub w: usize, + pub h: usize, +} + +fn short(model: &str) -> &str { + model.strip_prefix("claude-").unwrap_or(model) +} + +fn clock(d: Duration) -> String { + let s = d.as_secs(); + format!("{}:{:02}", s / 60, s % 60) +} + +fn tokens(n: u64) -> String { + match n { + n if n >= 1_000_000 => format!("{:.1}M", n as f64 / 1e6), + n if n >= 1000 => format!("{}k", n / 1000), + n => n.to_string(), + } +} + +fn clip(s: &str, w: usize) -> String { + let th = theme::t(); + if Span::raw(s).width() <= w { + return s.to_string(); + } + let keep = w.saturating_sub(Span::raw(th.sym.ellipsis).width()); + let mut out = String::new(); + for c in s.chars() { + if Span::raw(format!("{out}{c}")).width() > keep { + break; + } + out.push(c); + } + out + th.sym.ellipsis +} + +fn fit(l: Line<'static>, w: usize) -> Line<'static> { + if l.width() <= w { + return l; + } + let mut left = w; + let mut out = vec![]; + for s in l.spans { + let sw = s.width(); + if sw <= left { + left -= sw; + out.push(s); + continue; + } + out.push(Span::styled(clip(&s.content, left), s.style)); + break; + } + Line::from(out) +} + +fn bar(frac: f64, n: usize, st: Style) -> Vec> { + let th = theme::t(); + let full = ((frac.clamp(0.0, 1.0) * n as f64).round() as usize).min(n); + vec![ + Span::styled(th.sym.bar_full.repeat(full), st), + Span::styled(th.sym.bar_empty.repeat(n - full), th.dim()), + ] +} + +fn load_style(frac: f64) -> Style { + let th = theme::t(); + match frac { + f if f >= 0.9 => th.err(), + f if f >= 0.7 => th.warn(), + _ => th.accent(), + } +} + +pub fn card( + title: &str, + right: &str, + border: Style, + body: Vec>, + w: usize, +) -> Vec> { + let th = theme::t(); + let [h, v, tl, _, tr, _, _, _, bl, _, br] = th.sym.tbl; + let inner = w.saturating_sub(2); + let head = format!(" {title} "); + let tail = if right.is_empty() { + String::new() + } else { + format!(" {} ", clip(right, inner.saturating_sub(head.len() + 3))) + }; + let fill = inner.saturating_sub(Span::raw(&head).width() + Span::raw(&tail).width() + 1); + let mut out = vec![Line::from(vec![ + Span::styled(format!("{tl}{h}"), border), + Span::styled(head, border.add_modifier(Modifier::BOLD)), + Span::styled(h.repeat(fill), border), + Span::styled(tail, th.sec()), + Span::styled(tr, border), + ])]; + let cw = inner.saturating_sub(2); + for l in body { + let l = fit(l, cw); + let pad = cw.saturating_sub(l.width()); + let mut spans = vec![Span::styled(format!("{v} "), border)]; + spans.extend(l.spans); + spans.push(Span::raw(" ".repeat(pad))); + spans.push(Span::styled(format!(" {v}"), border)); + out.push(Line::from(spans)); + } + out.push(Line::styled(format!("{bl}{}{br}", h.repeat(inner)), border)); + out +} + +fn model_card(c: &View) -> Vec> { + let th = theme::t(); + let st = c.st; + let mut b = vec![Line::from(vec![ + Span::styled(short(&st.model).to_string(), th.plain()), + Span::styled( + format!( + " {} think {} {} {}", + th.sym.info, + st.effort.name(), + th.sym.info, + c.mode + ), + th.sec(), + ), + ])]; + let frac = st.ctx_tokens as f64 / st.ctx_max.max(1) as f64; + let mut ctx = vec![Span::styled("ctx ", th.sec())]; + ctx.extend(bar(frac, 10, load_style(frac))); + ctx.push(Span::styled( + format!( + " {:.0}% {}/{}", + frac * 100.0, + tokens(st.ctx_tokens as u64), + tokens(st.ctx_max as u64) + ), + th.sec(), + )); + b.push(Line::from(ctx)); + let u = &st.usage; + let tot = u.input_tokens + u.cache_read_tokens + u.cache_write_tokens; + let mut extra = vec![]; + if let Some(p) = (100 * u.cache_read_tokens).checked_div(tot) { + extra.push(format!("cache {p}%")); + } + if let Some(p) = (st.pricing)(&st.model) { + extra.push(format!("${:.2}", u.cost(&p))); + } + if !extra.is_empty() { + b.push(Line::styled( + extra.join(&format!(" {} ", th.sym.info)), + th.sec(), + )); + } + if let Some(q) = &st.quota { + for w in &q.windows { + let f = w.used_pct / 100.0; + let mut l = vec![Span::styled(format!("{:<4}", w.label), th.sec())]; + l.extend(bar(f, 10, load_style(f))); + l.push(Span::styled(format!(" {:.0}%", w.used_pct), th.sec())); + b.push(Line::from(l)); + } + } + card("MODEL", "", th.accent(), b, c.w) +} + +fn consult_card(c: &View) -> Option>> { + let k = c.consult?; + let th = theme::t(); + let mut b = vec![Line::styled(short(&k.model).to_string(), th.plain())]; + if let Some((ago, took)) = k.last { + b.push(Line::styled( + format!( + "last {} ago {} took {}", + clock(ago), + th.sym.info, + clock(took) + ), + th.sec(), + )); + } + if !k.triggers.is_empty() { + let mut spans = vec![]; + for (n, on) in &k.triggers { + if !spans.is_empty() { + spans.push(Span::raw(" ")); + } + let (m, st) = if *on { + (th.sym.done, th.accent().add_modifier(Modifier::BOLD)) + } else { + (th.sym.off, th.dim()) + }; + spans.push(Span::styled(format!("{m} {n}"), st)); + } + b.push(Line::from(spans)); + } + let (state, border) = if k.advising { + ("advising", th.accent()) + } else { + ("on call", th.dim()) + }; + Some(card( + "CONSULTANT", + &format!("{state} {} {}", th.sym.info, k.consults), + border, + b, + c.w, + )) +} + +fn runs_card(c: &View) -> Vec> { + let th = theme::t(); + let u = &c.st.usage; + let mut b = vec![Line::from(vec![ + Span::styled(format!("{} ", th.sym.done), th.accent()), + Span::styled(format!("{:<8}", "main"), th.sec()), + Span::styled(short(&c.st.model).to_string(), th.plain()), + Span::styled( + format!( + " {}", + tokens(u.input_tokens + u.cache_read_tokens + u.output_tokens) + ), + th.dim(), + ), + ])]; + let mut running = 0; + for s in c.subs.iter().rev().take(4).rev() { + let (mark, st) = match s.sh.status() { + SubStatus::Running => { + running += 1; + (th.sym.pending, th.accent()) + } + SubStatus::Done => (th.sym.done, th.ok()), + _ => (th.sym.err, th.err()), + }; + b.push(Line::from(vec![ + Span::styled(format!("{mark} "), st), + Span::styled(format!("{:<8}", s.sh.kind), th.sec()), + Span::styled(short(&s.sh.model).to_string(), th.plain()), + Span::styled(format!(" {}", clock(s.sh.elapsed())), th.dim()), + ])); + } + let right = if c.subs.is_empty() { + String::new() + } else { + format!("{running} running {} {} total", th.sym.info, c.subs.len()) + }; + card("MODELS RUN", &right, th.dim(), b, c.w) +} + +fn lsp_card(c: &View) -> Vec> { + let th = theme::t(); + let mut b = vec![]; + let (mut up, mut bad) = (0, false); + for x in c.lens_lines { + 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") { + up += 1; + (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 { + bad = true; + (th.sym.err, th.err(), state) + }; + b.push(Line::from(vec![ + Span::styled(format!("{mark} "), st), + Span::styled(format!("{name:<16}"), th.plain()), + Span::styled(format!(" {word}"), th.sec()), + ])); + } + if b.is_empty() { + b.push(Line::styled("no servers started", th.dim())); + } + let (errs, warns) = c.lens.diags.iter().fold((0, 0), |(e, w), d| { + if d.error { (e + 1, w) } else { (e, w + 1) } + }); + if errs + warns > 0 { + let mut ds = c.lens.diags.clone(); + ds.sort_by_key(|d| (!d.error, d.file.clone(), d.line)); + for d in ds.iter().take(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); + b.push(Line::from(vec![ + Span::styled(format!("{mark} "), st), + Span::styled(format!("{file}:{} ", d.line), th.plain()), + Span::styled(d.message.lines().next().unwrap_or("").to_string(), th.sec()), + ])); + } + if ds.len() > DIAGS { + b.push(Line::styled( + format!("{} {} more", th.sym.ellipsis, ds.len() - DIAGS), + th.dim(), + )); + } + } + let mut right = format!("{up}/{} ready", c.lens_lines.len()); + if errs + warns > 0 { + right += &format!(" {} {}{errs} {}{warns}", th.sym.info, th.sym.err, th.sym.warn); + } + let border = if bad || errs > 0 { + th.err() + } else if up > 0 { + th.ok() + } else { + th.dim() + }; + card("LSP", &right, border, b, c.w) +} + +fn mcp_card(c: &View) -> Option>> { + if c.mcp.is_empty() { + return None; + } + let th = theme::t(); + let mut b = vec![]; + for m in c.mcp { + let (mark, st) = match m.state { + McpState::Ok => (th.sym.done, th.ok()), + McpState::Pending => (th.sym.pending, th.dim()), + McpState::Failed => (th.sym.err, th.err()), + }; + let note = match m.state { + McpState::Ok => format!("{} tools", m.tools), + McpState::Pending => "connecting".into(), + McpState::Failed => "failed".into(), + }; + b.push(Line::from(vec![ + Span::styled(format!("{mark} "), st), + Span::styled(format!("{:<14}", m.name), th.plain()), + Span::styled(format!(" {note}"), th.sec()), + ])); + if let Some(e) = &m.error { + b.push(Line::styled( + format!(" {}", e.lines().next().unwrap_or("")), + th.err(), + )); + } + } + let up = c.mcp.iter().filter(|m| m.state == McpState::Ok).count(); + let border = if c.mcp.iter().any(|m| m.state == McpState::Failed) { + th.err() + } else if up == c.mcp.len() { + th.ok() + } else { + th.dim() + }; + Some(card( + "MCP", + &format!("{up}/{} up", c.mcp.len()), + border, + b, + c.w, + )) +} + +fn tests_card(c: &View) -> Option>> { + let ts = c.lens.tests.as_ref()?; + let th = theme::t(); + let mut ts = ts.clone(); + ts.sort_by_key(|t| t.1); + let failed = ts.iter().filter(|t| !t.1).count(); + let mut b: Vec> = ts + .iter() + .take(TESTS) + .map(|(n, ok)| { + 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()), + ]) + }) + .collect(); + if ts.len() > TESTS { + b.push(Line::styled( + format!("{} {} more", th.sym.ellipsis, ts.len() - TESTS), + th.dim(), + )); + } + let border = if failed > 0 { th.err() } else { th.ok() }; + Some(card( + "TESTS", + &format!("{} ok {} {failed} failed", ts.len() - failed, th.sym.info), + border, + b, + c.w, + )) +} + +fn log_card(c: &View) -> Option>> { + if c.log.is_empty() { + return None; + } + let th = theme::t(); + let skip = c.log.items.len().saturating_sub(LOG_ROWS); + let b = c + .log + .items + .iter() + .skip(skip) + .map(|(t, src, text)| { + Line::from(vec![ + Span::styled(format!("{:>5} ", clock(*t)), th.dim()), + Span::styled(format!("{src} "), th.accent()), + Span::styled(text.clone(), th.sec()), + ]) + }) + .collect(); + Some(card( + "SESSION LOG", + &format!("{}", c.log.len()), + th.dim(), + b, + c.w, + )) +} + +pub fn lines(c: &View) -> Vec> { + let cards = [ + Some(model_card(c)), + consult_card(c), + Some(runs_card(c)), + Some(lsp_card(c)), + mcp_card(c), + tests_card(c), + log_card(c), + ]; + let mut out: Vec> = vec![]; + for card in cards.into_iter().flatten() { + let need = card.len() + usize::from(!out.is_empty()); + if !out.is_empty() && out.len() + need > c.h { + break; + } + if !out.is_empty() { + out.push(Line::default()); + } + out.extend(card); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn text(ls: &[Line]) -> String { + ls.iter() + .map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect::()) + .collect::>() + .join("\n") + } + + fn status() -> Status { + Status { + auto: false, + kind: hx_ai::auth::Kind::Claude, + model: "claude-opus-5-5".into(), + effort: hx_ai::Effort::Off, + usage: Default::default(), + ctx_tokens: 500_000, + ctx_max: 1_000_000, + quota: None, + pricing: |_| None, + } + } + + fn view<'a>( + st: &'a Status, + lens: &'a LensView, + mcp: &'a [McpRow], + log: &'a LogRing, + h: usize, + ) -> View<'a> { + View { + st, + mode: "auto", + lens_lines: &[], + lens, + mcp, + subs: &[], + consult: None, + log, + w: 37, + h, + } + } + + #[test] + fn cards_never_exceed_width() { + let l = card( + "LSP", + "a very long right label that will not fit", + Style::default(), + vec![Line::raw("x".repeat(100))], + 37, + ); + assert!(l.iter().all(|l| l.width() == 37), "{}", text(&l)); + } + + #[test] + fn mcp_rows_show_state_and_error() { + let (st, lens, log) = (status(), LensView::default(), LogRing::default()); + let mcp = vec![ + McpRow { + name: "git".into(), + state: McpState::Ok, + tools: 12, + prompts: 0, + error: None, + }, + McpRow { + name: "db".into(), + state: McpState::Failed, + tools: 0, + prompts: 0, + error: Some("connection refused".into()), + }, + McpRow { + name: "web".into(), + state: McpState::Pending, + tools: 0, + prompts: 0, + error: None, + }, + ]; + let s = text(&lines(&view(&st, &lens, &mcp, &log, 80))); + assert!(s.contains("MCP") && s.contains("1/3 up"), "{s}"); + assert!(s.contains("git") && s.contains("12 tools"), "{s}"); + assert!(s.contains("connection refused") && s.contains("connecting"), "{s}"); + } + + #[test] + fn log_ring_caps_and_skips_repeats() { + let mut r = LogRing::default(); + r.push("lsp", "up"); + r.push("lsp", "up"); + assert_eq!(r.len(), 1); + for i in 0..80 { + r.push("x", format!("{i}")); + } + assert_eq!(r.len(), LOG_CAP); + assert_eq!(r.items.back().unwrap().2, "79"); + } + + #[test] + fn consultant_hidden_without_data_and_marks_active_trigger() { + let (st, lens, log) = (status(), LensView::default(), LogRing::default()); + let mut v = view(&st, &lens, &[], &log, 80); + assert!(!text(&lines(&v)).contains("CONSULTANT")); + let k = Consult { + model: "claude-fable-5-2".into(), + advising: true, + consults: 2, + last: Some((Duration::from_secs(7), Duration::from_secs(27))), + triggers: vec![("before a plan".into(), false), ("before done".into(), true)], + }; + v.consult = Some(&k); + let s = text(&lines(&v)); + assert!(s.contains("CONSULTANT") && s.contains("advising"), "{s}"); + assert!(s.contains("● before done") && s.contains("○ before a plan"), "{s}"); + } + + #[test] + fn short_panels_drop_lowest_cards_first() { + let (st, lens) = (status(), LensView::default()); + let mut log = LogRing::default(); + log.push("lsp", "up"); + let tall = text(&lines(&view(&st, &lens, &[], &log, 80))); + assert!(tall.contains("SESSION LOG"), "{tall}"); + let short = text(&lines(&view(&st, &lens, &[], &log, 12))); + assert!(short.contains("MODEL") && !short.contains("SESSION LOG"), "{short}"); + } +}