//! Screen 2: session detail (ORCHESTRATOR.md 7.2, `Session.dc.html`). use super::overview::Header; use super::theme::{self, bold, fg, inverted}; use crate::detail::{Block as Blk, Detail, LineKind, MLine, TestRun}; use crate::machine::RunOn; use crate::view::{Status, ago, hms}; use ratatui::Frame; use ratatui::layout::{Constraint, Layout, Rect}; use ratatui::style::{Color, Modifier, Style}; use ratatui::text::{Line, Span}; use ratatui::widgets::{Block, Paragraph}; use unicode_width::UnicodeWidthStr; const W_TEXT: usize = 31; const W_EXEC: usize = 9; const W_SETS: usize = 14; pub fn draw(f: &mut Frame, d: &Detail, h: &Header) { let area = f.area(); f.render_widget( Block::new().style(Style::new().bg(theme::BG).fg(theme::TEXT)), area, ); let [head, body, keys] = Layout::vertical([ Constraint::Length(1), Constraint::Fill(1), Constraint::Length(1), ]) .areas(area); let [left, right] = Layout::horizontal([Constraint::Length(90), Constraint::Fill(1)]).areas(body); f.render_widget(header(d, h, head.width as usize), head); machine_box(f, left, d); let test_h = match &d.test { Some(t) => (3 + t.failures.len() * 3).clamp(4, 16) as u16, None => 3, }; let files_h = (d.files.len().clamp(1, 6) + 2) as u16; // the loop detector box only exists while the session loops let loop_h = if d.looping.is_some() { 7 } else { 0 }; let [loop_area, test, now, files, budget] = Layout::vertical([ Constraint::Length(loop_h), Constraint::Length(test_h), Constraint::Length(4), Constraint::Length(files_h), Constraint::Min(6), ]) .areas(right); if let Some(l) = &d.looping { loop_box(f, loop_area, d, l); } test_box(f, test, d.test.as_ref()); now_box(f, now, d); files_box(f, files, d); budget_box(f, budget, d); f.render_widget(key_bar(d.looping.is_some()), keys); } fn loop_box(f: &mut Frame, area: Rect, d: &Detail, l: &crate::detail::LoopView) { let b = Block::bordered().border_style(fg(theme::WAIT)); let inner = b.inner(area); f.render_widget(b, area); let mut what = format!( "The last {} test runs failed on the same {} tests.", l.runs, l.tests ); if let Some(file) = &l.file { what.push_str(&format!(" The agent keeps editing {file}.")); } // the sentence wraps (two lines fit); the keys get a line each so none is cut f.render_widget( Paragraph::new(vec![ Line::from(Span::styled(" ◆ Loop detector", bold(theme::WAIT))), Line::from(Span::raw(format!(" {what}"))), Line::from(Span::styled( format!( " [r] re-plan from {} [m] send hint to agent", d.start.to_uppercase() ), fg(theme::DIM), )), Line::from(Span::styled(" [k] kill and hand over", fg(theme::DIM))), ]) .wrap(ratatui::widgets::Wrap { trim: false }), inner, ); } fn status_color(s: Status) -> Color { match s { Status::Done => theme::OK, Status::Fix | Status::Fail => theme::ERR, Status::Wait => theme::WAIT, Status::Run => theme::RUN, Status::Blocked => theme::AGENT, } } fn header(d: &Detail, h: &Header, width: usize) -> Line<'static> { let pid = d.pid.map_or(String::new(), |p| format!(" · pid {p}")); let info = format!("branch {} · worktree {}{pid}", d.branch, d.worktree); let clock = hms(h.now_ms); let fixed = " hx·orch ".width() + " ‹ sessions / ".width() + format!("{} {}", d.id, d.task).width() + 2 + d.status.label().width() + 2 + clock.width() + 2; let info = fit(&info, width.saturating_sub(fixed)); let gap = width.saturating_sub(fixed - 2 + info.width()).max(1); Line::from(vec![ Span::styled(" hx·orch ", inverted(theme::RUN)), Span::styled(" ‹ sessions / ", fg(theme::DIM)), Span::styled(format!("{} {}", d.id, d.task), bold(theme::TEXT)), Span::raw(" "), Span::styled(d.status.label(), bold(status_color(d.status))), Span::raw(" "), Span::styled(info, fg(theme::DIM)), Span::raw(" ".repeat(gap)), Span::raw(clock), ]) } fn fit(s: &str, w: usize) -> String { if s.width() <= w { return s.to_string(); } let mut out = String::new(); for c in s.chars() { if out.width() + 1 >= w { break; } out.push(c); } out.push('…'); out } fn titled<'a>(title: &str, sub: &str, border: Color) -> Block<'a> { let mut t = vec![Span::styled(format!(" {title}"), bold(theme::TEXT))]; if !sub.is_empty() { t.push(Span::styled(format!(" {sub}"), fg(theme::DIM))); } t.push(Span::raw(" ")); Block::bordered() .border_style(fg(border)) .title(Line::from(t)) } fn pad(spans: &mut Vec>, parts: Vec>, w: usize) { let used: usize = parts.iter().map(|s| s.width()).sum(); spans.extend(parts); spans.push(Span::raw(" ".repeat((w + 1).saturating_sub(used)))); } fn machine_line(l: &MLine) -> Line<'static> { if l.kind == LineKind::Blank { return Line::raw(""); } let todo = l.block == Blk::Todo; let text_style = match l.kind { LineKind::Header => bold(theme::RUN), LineKind::Only => fg(theme::WAIT), LineKind::End => fg(theme::DIM), _ if todo => fg(theme::DIM), _ => fg(theme::TEXT), }; let bar = if l.block == Blk::Cur { Span::styled("▌", fg(theme::RUN)) } else { Span::raw(" ") }; let mut v = vec![bar]; let mut text = vec![Span::styled(l.text.clone(), text_style)]; if !l.to.is_empty() { text.push(Span::styled(l.to.clone(), fg(theme::RUN))); } pad(&mut v, text, W_TEXT); let exec = l.exec.map_or_else( || Span::raw(""), |e| { let (name, c) = match e { RunOn::Computer => ("computer", theme::TEXT), RunOn::Agent => ("agent", theme::AGENT), RunOn::Human => ("human", theme::WAIT), }; Span::styled(name, fg(c)) }, ); pad(&mut v, vec![exec], W_EXEC); let sets_color = if todo { theme::DIM } else { theme::RUN }; pad( &mut v, vec![Span::styled(l.sets.clone(), fg(sets_color))], W_SETS, ); let live_color = if l.hit || l.block == Blk::Fail { theme::ERR } else if l.block == Blk::Cur { theme::RUN } else { theme::OK }; let live_style = if l.hit { bold(live_color) } else { fg(live_color) }; v.push(Span::styled(l.live.clone(), live_style)); let line = Line::from(v); if l.block == Blk::Cur { line.style(Style::new().bg(theme::SEL)) } else { line } } fn machine_box(f: &mut Frame, area: Rect, d: &Detail) { let mut sub = d.machine_file.clone(); if let Some(a) = &d.on_abort { sub.push_str(&format!(" · on abort → {a}")); } if let Some(b) = &d.on_budget { sub.push_str(&format!(" · on budget → {b}")); } let block = titled("Machine", &sub, theme::BORDER); let inner = block.inner(area); f.render_widget(block, area); let [head, lines, path] = Layout::vertical([ Constraint::Length(1), Constraint::Fill(1), Constraint::Length(3), ]) .areas(inner); let mut hv = vec![Span::raw(" ")]; pad(&mut hv, vec![Span::raw("state / step")], W_TEXT); pad(&mut hv, vec![Span::raw("runs on")], W_EXEC); pad(&mut hv, vec![Span::raw("sets")], W_SETS); hv.push(Span::raw("live")); f.render_widget(Line::from(hv).style(fg(theme::DIM)), head); // keep the current state in view when the machine is longer than the box let all: Vec = d.lines.iter().map(machine_line).collect(); let h = lines.height as usize; let cur = d .lines .iter() .position(|l| l.block == Blk::Cur && l.kind == LineKind::Header) .unwrap_or(0); let start = if all.len() > h { cur.saturating_sub(h / 3).min(all.len() - h) } else { 0 }; f.render_widget(Paragraph::new(all[start..].to_vec()), lines); let mut p = vec![Span::styled(" path ", fg(theme::DIM))]; for (i, s) in d.path.iter().enumerate() { if i > 0 { p.push(Span::raw(" → ")); } let label = if s.failed { format!("{} ✗", s.name) } else { s.name.clone() }; p.push(if s.current { Span::styled(format!(" {label} "), inverted(theme::RUN)) } else if s.failed { Span::styled(label, fg(theme::ERR)) } else { Span::styled(label, fg(theme::OK)) }); } let sep = Block::new() .borders(ratatui::widgets::Borders::TOP) .border_style(fg(theme::BORDER)); f.render_widget( Paragraph::new(Line::from(p)) .block(sep) .wrap(ratatui::widgets::Wrap { trim: false }), path, ); } fn test_box(f: &mut Frame, area: Rect, t: Option<&TestRun>) { let Some(t) = t else { let b = titled("Last test run", "", theme::BORDER); let inner = b.inner(area); f.render_widget(b, area); f.render_widget(Span::styled(" no test report yet", fg(theme::DIM)), inner); return; }; let border = if t.failed > 0 { theme::ERR } else { theme::OK }; let b = titled( "Last test run", &format!("{} · {}", t.step, hms(t.at_ms)), border, ); let inner = b.inner(area); f.render_widget(b, area); let total = (t.passed + t.failed).max(1) as usize; let width = 40usize; let red = ((t.failed as usize * width).div_ceil(total)).min(width); let red = if t.failed > 0 { red.max(1) } else { 0 }; let mut lines = vec![Line::from(vec![ Span::raw(" "), Span::styled(format!("{} passed", t.passed), fg(theme::OK)), Span::raw(" "), Span::styled( format!("{} failed", t.failed), if t.failed > 0 { bold(theme::ERR) } else { fg(theme::DIM) }, ), Span::styled( format!(" {} skipped · {:.1}s ", t.skipped, t.secs), fg(theme::DIM), ), Span::styled("█".repeat(width - red), fg(theme::OK)), Span::styled("█".repeat(red), fg(theme::ERR)), ])]; for fl in &t.failures { lines.push(Line::from(Span::styled( format!(" ✗ {}", fl.name), fg(theme::ERR), ))); lines.push(Line::from(Span::styled( format!( " {}", fit(&fl.message, (inner.width as usize).saturating_sub(6)) ), fg(theme::DIM), ))); let mut where_ = fl.location.clone(); if !fl.repeats.is_empty() { if !where_.is_empty() { where_.push_str(" · "); } where_.push_str(&fl.repeats); } lines.push(Line::from(Span::styled( format!(" {where_}"), fg(theme::DIM), ))); } f.render_widget(Paragraph::new(lines), inner); } fn now_box(f: &mut Frame, area: Rect, d: &Detail) { let b = titled("Now", "", theme::BORDER); let inner = b.inner(area); f.render_widget(b, area); let who_color = if d.now.who == "agent" { theme::AGENT } else { theme::TEXT }; let first = if d.now.who.is_empty() { Line::from(Span::styled(" idle", fg(theme::DIM))) } else { Line::from(vec![ Span::raw(" "), Span::styled(format!("{:<9}", d.now.who), fg(who_color)), Span::raw(fit(&d.now.line, (inner.width as usize).saturating_sub(11))), ]) }; let second = Line::from(vec![ Span::raw(" "), Span::styled("intent ", fg(theme::DIM)), Span::raw(fit( &d.now.intent, (inner.width as usize).saturating_sub(11), )), ]); f.render_widget(Paragraph::new(vec![first, second]), inner); } fn files_box(f: &mut Frame, area: Rect, d: &Detail) { let (a, r): (u32, u32) = d .files .iter() .fold((0, 0), |(a, r), x| (a + x.added, r + x.removed)); let b = titled( "Changed files", &format!("{} · +{a} −{r}", d.files.len()), theme::BORDER, ); let inner = b.inner(area); f.render_widget(b, area); let lines: Vec = d .files .iter() .take(inner.height as usize) .map(|x| { Line::from(vec![ Span::raw(format!(" {:<30}", fit(&x.path, 29))), Span::styled(format!("{:<6}", format!("+{}", x.added)), fg(theme::OK)), Span::styled(format!("{:<6}", format!("−{}", x.removed)), fg(theme::ERR)), Span::styled( "■".repeat((x.added as usize).div_ceil(6).min(12)), fg(theme::OK), ), Span::styled( "■".repeat((x.removed as usize).div_ceil(6).min(12)), fg(theme::ERR), ), ]) }) .collect(); if lines.is_empty() { f.render_widget(Span::styled(" no edits yet", fg(theme::DIM)), inner); } else { f.render_widget(Paragraph::new(lines), inner); } } fn bar(used: usize, total: usize, n: usize, color: Color) -> Span<'static> { let on = (used * n).checked_div(total).unwrap_or(0).min(n); Span::styled( format!("{}{}", "▰".repeat(on), "▱".repeat(n - on)), fg(color), ) } fn k(n: u64) -> String { if n >= 1000 { format!("{}k", n / 1000) } else { n.to_string() } } fn budget_box(f: &mut Frame, area: Rect, d: &Detail) { let b = titled("Budget", "", theme::BORDER); let inner = b.inner(area); f.render_widget(b, area); let label = |s: &str| Span::styled(format!(" {s:<10}"), fg(theme::DIM)); let mut lines = vec![]; lines.push(match d.budget.ctx { Some((u, l)) => { let pct = (u * 100).checked_div(l).unwrap_or(0); let c = if pct > 65 { theme::WAIT } else { theme::DIM }; Line::from(vec![ label("context"), bar(u as usize, l as usize, 10, c), Span::raw(format!(" {} / {}", k(u), k(l))), Span::styled( d.budget .compact_at .map_or(String::new(), |c| format!(" compact at {c}%")), fg(theme::DIM), ), ]) } None => Line::from(vec![label("context"), Span::styled("—", fg(theme::DIM))]), }); lines.push(match d.budget.retries { Some((n, max)) => Line::from(vec![ label("retries"), bar(n as usize, max as usize, max as usize, theme::ERR), Span::raw(format!(" {n} / {max}")), ]), None => Line::from(vec![ label("retries"), Span::styled("none yet", fg(theme::DIM)), ]), }); // a cap turns the plain number into a bar; red once it is passed let over = |used: f64, cap: f64| if used > cap { theme::ERR } else { theme::RUN }; lines.push(match d.budget.wall_cap { Some(cap) => { let c = over(d.budget.wall_secs as f64, cap as f64); Line::from(vec![ label("wall time"), bar(d.budget.wall_secs as usize, cap as usize, 10, c), Span::raw(format!(" {} / {} cap", ago(d.budget.wall_secs), ago(cap))), ]) } None => Line::from(vec![ label("wall time"), Span::styled(ago(d.budget.wall_secs), fg(theme::RUN)), Span::styled(" no cap set", fg(theme::DIM)), ]), }); lines.push(match d.budget.cost_cap { Some(cap) => { let c = over(d.budget.cost, cap); Line::from(vec![ label("cost"), bar( (d.budget.cost * 100.0) as usize, (cap * 100.0) as usize, 10, c, ), Span::raw(format!(" ${:.2} / ${cap:.2}", d.budget.cost)), ]) } None => Line::from(vec![ label("cost"), Span::styled(format!("${:.2}", d.budget.cost), fg(theme::RUN)), Span::styled(" no cap set", fg(theme::DIM)), ]), }); f.render_widget(Paragraph::new(lines), inner); } fn key_bar(looping: bool) -> Line<'static> { let mut v = vec![Span::raw(" ")]; for (key, what) in [ ("esc", "back"), ("t", "full test output"), ("d", "diff"), ("l", "transcript"), ("i", "interrupt"), ("m", "message"), ("s", "state"), ("k", "kill"), ("o", "open in hx"), ] .into_iter() .chain(looping.then_some(("r", "re-plan"))) { v.push(Span::styled( format!(" {key} "), Style::new() .fg(theme::BG) .bg(theme::DIM) .add_modifier(Modifier::empty()), )); v.push(Span::styled(format!(" {what} "), fg(theme::DIM))); } Line::from(v) }