Add ACP agent steps, JUnit reports and session detail screen
- acp.rs: ACP client for hx serve --acp, hx/* events into the event table - tests/fake_acp_hx.py: Python fake hx for the runner tests - runner.rs: agent steps, blocked catches, failure context, junit test events - junit.rs: JUnit XML parser (counts, failing tests, locations) - detail.rs + tui/session.rs: session detail screen with machine view - tui: enter/esc navigation, pagers for test output, diff and transcript Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d66a014bc5
commit
5b659fa8ba
14 files changed
+2676
-91
No files matched your search
+406
-31
@@ -1,9 +1,11 @@
|
||||
//! Terminal UI. Everything on screen comes from the event table and the machine files via `view::build`.
|
||||
|
||||
mod overview;
|
||||
mod session;
|
||||
mod theme;
|
||||
|
||||
use crate::db::{Db, Event};
|
||||
use crate::detail::{self, Detail};
|
||||
use crate::machine::Machine;
|
||||
use crate::view::{self, Overview};
|
||||
use anyhow::{Result, bail};
|
||||
@@ -24,6 +26,19 @@ pub fn run() -> Result<()> {
|
||||
res
|
||||
}
|
||||
|
||||
enum Screen {
|
||||
Overview,
|
||||
/// Session detail for this session id.
|
||||
Session(String),
|
||||
}
|
||||
|
||||
/// A scrollable text overlay: full test output, diff, agent transcript.
|
||||
struct Pager {
|
||||
title: String,
|
||||
lines: Vec<String>,
|
||||
scroll: usize,
|
||||
}
|
||||
|
||||
struct App {
|
||||
repo: PathBuf,
|
||||
/// Opened lazily: launching `orch` in a directory without a goal must not create `.hx/orch.db`.
|
||||
@@ -33,6 +48,9 @@ struct App {
|
||||
overview: Overview,
|
||||
rev: String,
|
||||
sel: usize,
|
||||
screen: Screen,
|
||||
detail: Option<Detail>,
|
||||
pager: Option<Pager>,
|
||||
}
|
||||
|
||||
impl App {
|
||||
@@ -46,6 +64,9 @@ impl App {
|
||||
overview: Overview::default(),
|
||||
rev,
|
||||
sel: 0,
|
||||
screen: Screen::Overview,
|
||||
detail: None,
|
||||
pager: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,16 +75,24 @@ impl App {
|
||||
if self.db.is_none() && path.exists() {
|
||||
self.db = Db::open(&path).ok();
|
||||
}
|
||||
if let Some(db) = &self.db
|
||||
&& let Ok(o) = snapshot(
|
||||
db,
|
||||
&self.repo,
|
||||
&mut self.events,
|
||||
&mut self.machines,
|
||||
crate::state::now_ms(),
|
||||
)
|
||||
{
|
||||
self.overview = o;
|
||||
if let Some(db) = &self.db {
|
||||
let now = crate::state::now_ms();
|
||||
if let Ok(o) = snapshot(db, &self.repo, &mut self.events, &mut self.machines, now) {
|
||||
self.overview = o;
|
||||
}
|
||||
self.detail = match &self.screen {
|
||||
Screen::Session(id) => session_detail(
|
||||
db,
|
||||
&self.repo,
|
||||
&mut self.events,
|
||||
&mut self.machines,
|
||||
id,
|
||||
now,
|
||||
)
|
||||
.ok()
|
||||
.flatten(),
|
||||
Screen::Overview => None,
|
||||
};
|
||||
}
|
||||
self.sel = self.sel.min(self.overview.rows.len().saturating_sub(1));
|
||||
}
|
||||
@@ -83,14 +112,20 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads what is new in the database since the last call and builds the overview.
|
||||
fn snapshot(
|
||||
/// Everything read from the database for one screen update, plus the loaded machine files.
|
||||
struct Loaded {
|
||||
tasks: Vec<crate::db::Task>,
|
||||
sessions: Vec<crate::db::Session>,
|
||||
goal: Option<String>,
|
||||
}
|
||||
|
||||
/// Reads what is new in the database since the last call and loads missing machine files.
|
||||
fn load(
|
||||
db: &Db,
|
||||
repo: &Path,
|
||||
events: &mut Vec<Event>,
|
||||
machines: &mut HashMap<String, Machine>,
|
||||
now_ms: u64,
|
||||
) -> Result<Overview> {
|
||||
) -> Result<Loaded> {
|
||||
let last = events.last().map_or(0, |e| e.id);
|
||||
events.extend(db.events(None, last)?);
|
||||
let (tasks, sessions) = (db.tasks()?, db.sessions()?);
|
||||
@@ -101,17 +136,53 @@ fn snapshot(
|
||||
machines.insert(t.machine.clone(), m);
|
||||
}
|
||||
}
|
||||
let goal = db.goal()?;
|
||||
Ok(Loaded {
|
||||
tasks,
|
||||
sessions,
|
||||
goal: db.goal()?,
|
||||
})
|
||||
}
|
||||
|
||||
fn snapshot(
|
||||
db: &Db,
|
||||
repo: &Path,
|
||||
events: &mut Vec<Event>,
|
||||
machines: &mut HashMap<String, Machine>,
|
||||
now_ms: u64,
|
||||
) -> Result<Overview> {
|
||||
let l = load(db, repo, events, machines)?;
|
||||
Ok(view::build(&view::Input {
|
||||
goal: goal.as_deref(),
|
||||
tasks: &tasks,
|
||||
sessions: &sessions,
|
||||
goal: l.goal.as_deref(),
|
||||
tasks: &l.tasks,
|
||||
sessions: &l.sessions,
|
||||
events,
|
||||
machines,
|
||||
now_ms,
|
||||
}))
|
||||
}
|
||||
|
||||
fn session_detail(
|
||||
db: &Db,
|
||||
repo: &Path,
|
||||
events: &mut Vec<Event>,
|
||||
machines: &mut HashMap<String, Machine>,
|
||||
id: &str,
|
||||
now_ms: u64,
|
||||
) -> Result<Option<Detail>> {
|
||||
let l = load(db, repo, events, machines)?;
|
||||
Ok(detail::build(
|
||||
&view::Input {
|
||||
goal: l.goal.as_deref(),
|
||||
tasks: &l.tasks,
|
||||
sessions: &l.sessions,
|
||||
events,
|
||||
machines,
|
||||
now_ms,
|
||||
},
|
||||
id,
|
||||
))
|
||||
}
|
||||
|
||||
fn git_rev(repo: &Path) -> String {
|
||||
let git = |a: &[&str]| crate::run::git(repo, a).map(|s| s.trim().to_string());
|
||||
match (
|
||||
@@ -123,12 +194,216 @@ fn git_rev(repo: &Path) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
fn draw(f: &mut ratatui::Frame, app: &App, header: &Header) {
|
||||
match (&app.screen, &app.detail) {
|
||||
(Screen::Session(_), Some(d)) => session::draw(f, d, header),
|
||||
_ => overview::draw(f, &app.overview, header, app.sel),
|
||||
}
|
||||
if let Some(p) = &app.pager {
|
||||
draw_pager(f, p);
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_pager(f: &mut ratatui::Frame, p: &Pager) {
|
||||
use ratatui::style::Style;
|
||||
use ratatui::text::{Line, Span};
|
||||
use ratatui::widgets::{Block, Clear, Paragraph};
|
||||
let area = f.area().inner(ratatui::layout::Margin::new(2, 1));
|
||||
f.render_widget(Clear, area);
|
||||
let hint = format!(
|
||||
" {} · {}/{} · j/k scroll · esc close ",
|
||||
p.title,
|
||||
(p.scroll + 1).min(p.lines.len().max(1)),
|
||||
p.lines.len().max(1)
|
||||
);
|
||||
let block = Block::bordered()
|
||||
.border_style(theme::fg(theme::RUN))
|
||||
.title(Span::styled(hint, theme::bold(theme::TEXT)))
|
||||
.style(Style::new().bg(theme::BG));
|
||||
let inner = block.inner(area);
|
||||
f.render_widget(block, area);
|
||||
let lines: Vec<Line> = p
|
||||
.lines
|
||||
.iter()
|
||||
.skip(p.scroll)
|
||||
.take(inner.height as usize)
|
||||
.map(|l| {
|
||||
let color = if l.starts_with("+++") || l.starts_with("---") || l.starts_with("diff ") {
|
||||
theme::DIM
|
||||
} else if l.starts_with('+') {
|
||||
theme::OK
|
||||
} else if l.starts_with('-') {
|
||||
theme::ERR
|
||||
} else if l.starts_with("@@") {
|
||||
theme::RUN
|
||||
} else {
|
||||
theme::TEXT
|
||||
};
|
||||
Line::from(Span::styled(l.clone(), theme::fg(color)))
|
||||
})
|
||||
.collect();
|
||||
f.render_widget(Paragraph::new(lines), inner);
|
||||
}
|
||||
|
||||
fn lines_of(text: &str) -> Vec<String> {
|
||||
text.lines().map(|l| l.replace('\t', " ")).collect()
|
||||
}
|
||||
|
||||
/// Output of the last test step (the whole tail kept in the event), else of the last failed step.
|
||||
fn test_output(app: &App, id: &str) -> Pager {
|
||||
let mine = || app.events.iter().rev().filter(|e| e.session == id);
|
||||
let step_name = mine()
|
||||
.find(|e| e.kind == "test")
|
||||
.and_then(|e| e.payload["step"].as_str());
|
||||
let found = mine().find(|e| {
|
||||
e.kind == "step"
|
||||
&& match step_name {
|
||||
Some(n) => e.payload["step"] == n,
|
||||
None => e.payload["ok"] == false,
|
||||
}
|
||||
});
|
||||
let (title, text) = match found {
|
||||
Some(e) => (
|
||||
format!("output of {}", e.payload["step"].as_str().unwrap_or("step")),
|
||||
e.payload["output"].as_str().unwrap_or_default().to_string(),
|
||||
),
|
||||
None => ("test output".into(), "no test or failed step yet".into()),
|
||||
};
|
||||
Pager {
|
||||
title,
|
||||
lines: lines_of(&text),
|
||||
scroll: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn diff_of(worktree: &str) -> Pager {
|
||||
let git = |a: &[&str]| crate::run::git(Path::new(worktree), a);
|
||||
let mut text = String::new();
|
||||
match git(&["status", "--short"]) {
|
||||
Ok(s) if !s.trim().is_empty() => text.push_str(&format!("{s}\n")),
|
||||
Ok(_) => {}
|
||||
Err(e) => text.push_str(&format!("{e:#}\n")),
|
||||
}
|
||||
match git(&["diff", "HEAD"]) {
|
||||
Ok(s) if s.trim().is_empty() && text.is_empty() => text.push_str("no changes yet"),
|
||||
Ok(s) => text.push_str(&s),
|
||||
Err(e) => text.push_str(&format!("{e:#}")),
|
||||
}
|
||||
Pager {
|
||||
title: "diff".into(),
|
||||
lines: lines_of(&text),
|
||||
scroll: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn transcript(app: &App, id: &str) -> Pager {
|
||||
let lines = app
|
||||
.overview
|
||||
.events
|
||||
.iter()
|
||||
.filter(|e| e.session == id)
|
||||
.map(|e| format!("{} {:<10} {}", view::hms(e.at_ms), e.kind, e.text))
|
||||
.collect();
|
||||
Pager {
|
||||
title: format!("{id} events"),
|
||||
lines,
|
||||
scroll: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens hx in the worktree: the TUI steps aside for the time hx runs.
|
||||
fn open_in_hx(term: &mut ratatui::DefaultTerminal, worktree: &str) -> Option<String> {
|
||||
let hx = crate::profile::Profile::load("default").map_or_else(|_| "hx".into(), |p| p.hx);
|
||||
let mut parts = hx.split_whitespace();
|
||||
let mut cmd = std::process::Command::new(parts.next()?);
|
||||
cmd.args(parts).current_dir(worktree);
|
||||
ratatui::restore();
|
||||
let res = cmd.status();
|
||||
*term = ratatui::init();
|
||||
res.err().map(|e| format!("could not start {hx}: {e}"))
|
||||
}
|
||||
|
||||
/// Handles one key; returns true to quit.
|
||||
fn on_key(
|
||||
app: &mut App,
|
||||
term: &mut ratatui::DefaultTerminal,
|
||||
k: crossterm::event::KeyEvent,
|
||||
) -> Result<bool> {
|
||||
use crossterm::event::{KeyCode, KeyModifiers};
|
||||
if k.code == KeyCode::Char('c') && k.modifiers.contains(KeyModifiers::CONTROL) {
|
||||
return Ok(true);
|
||||
}
|
||||
if let Some(p) = &mut app.pager {
|
||||
let max = p.lines.len().saturating_sub(1);
|
||||
match k.code {
|
||||
KeyCode::Esc | KeyCode::Char('q') => p.scroll = usize::MAX, // closed below
|
||||
KeyCode::Char('j') | KeyCode::Down => p.scroll = (p.scroll + 1).min(max),
|
||||
KeyCode::Char('k') | KeyCode::Up => p.scroll = p.scroll.saturating_sub(1),
|
||||
KeyCode::PageDown | KeyCode::Char(' ') => p.scroll = (p.scroll + 20).min(max),
|
||||
KeyCode::PageUp => p.scroll = p.scroll.saturating_sub(20),
|
||||
KeyCode::Char('g') | KeyCode::Home => p.scroll = 0,
|
||||
KeyCode::Char('G') | KeyCode::End => p.scroll = max,
|
||||
_ => {}
|
||||
}
|
||||
if p.scroll == usize::MAX {
|
||||
app.pager = None;
|
||||
}
|
||||
return Ok(false);
|
||||
}
|
||||
match &app.screen {
|
||||
Screen::Overview => {
|
||||
let last = app.overview.rows.len().saturating_sub(1);
|
||||
match k.code {
|
||||
KeyCode::Char('q') => return Ok(true),
|
||||
KeyCode::Char('j') | KeyCode::Down => app.sel = (app.sel + 1).min(last),
|
||||
KeyCode::Char('k') | KeyCode::Up => app.sel = app.sel.saturating_sub(1),
|
||||
KeyCode::Enter => {
|
||||
if let Some(r) = app.overview.rows.get(app.sel) {
|
||||
app.screen = Screen::Session(r.id.clone());
|
||||
app.refresh();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Screen::Session(id) => {
|
||||
let id = id.clone();
|
||||
match k.code {
|
||||
KeyCode::Esc | KeyCode::Char('q') => {
|
||||
app.screen = Screen::Overview;
|
||||
app.detail = None;
|
||||
}
|
||||
KeyCode::Char('t') => app.pager = Some(test_output(app, &id)),
|
||||
KeyCode::Char('l') => app.pager = Some(transcript(app, &id)),
|
||||
KeyCode::Char('d') => {
|
||||
if let Some(d) = &app.detail {
|
||||
app.pager = Some(diff_of(&d.worktree));
|
||||
}
|
||||
}
|
||||
KeyCode::Char('o') => {
|
||||
if let Some(d) = &app.detail
|
||||
&& let Some(err) = open_in_hx(term, &d.worktree.clone())
|
||||
{
|
||||
app.pager = Some(Pager {
|
||||
title: "open worktree".into(),
|
||||
lines: vec![err],
|
||||
scroll: 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
fn event_loop(term: &mut ratatui::DefaultTerminal, app: &mut App) -> Result<()> {
|
||||
use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};
|
||||
use crossterm::event::{self, Event, KeyEventKind};
|
||||
app.refresh();
|
||||
loop {
|
||||
let header = app.header();
|
||||
term.draw(|f| overview::draw(f, &app.overview, &header, app.sel))?;
|
||||
term.draw(|f| draw(f, app, &header))?;
|
||||
if !event::poll(Duration::from_millis(250))? {
|
||||
app.refresh();
|
||||
continue;
|
||||
@@ -136,16 +411,8 @@ fn event_loop(term: &mut ratatui::DefaultTerminal, app: &mut App) -> Result<()>
|
||||
let Event::Key(k) = event::read()? else {
|
||||
continue;
|
||||
};
|
||||
if k.kind != KeyEventKind::Press {
|
||||
continue;
|
||||
}
|
||||
let last = app.overview.rows.len().saturating_sub(1);
|
||||
match k.code {
|
||||
KeyCode::Char('q') => return Ok(()),
|
||||
KeyCode::Char('c') if k.modifiers.contains(KeyModifiers::CONTROL) => return Ok(()),
|
||||
KeyCode::Char('j') | KeyCode::Down => app.sel = (app.sel + 1).min(last),
|
||||
KeyCode::Char('k') | KeyCode::Up => app.sel = app.sel.saturating_sub(1),
|
||||
_ => {}
|
||||
if k.kind == KeyEventKind::Press && on_key(app, term, k)? {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -353,7 +620,8 @@ mod tests {
|
||||
db.set_goal("ship the thing").unwrap();
|
||||
let s = crate::runner::create(&db, &dir.join("wt"), "demo", "", "m").unwrap();
|
||||
let m = Machine::find("m", &repo).unwrap();
|
||||
crate::runner::run_session(&db, &m, &s.id, &repo, "").unwrap();
|
||||
let profile = crate::profile::Profile::parse("").unwrap();
|
||||
crate::runner::run_session(&db, &m, &s.id, &repo, "", &profile).unwrap();
|
||||
|
||||
let (mut events, mut machines) = (vec![], HashMap::new());
|
||||
let o = snapshot(
|
||||
@@ -383,4 +651,111 @@ mod tests {
|
||||
assert_eq!(events.len(), n);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failing_tests_flow_from_junit_report_to_session_screen_and_pagers() {
|
||||
let dir = std::env::temp_dir().join(format!("orch-tui-detail-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let repo = dir.join("repo");
|
||||
std::fs::create_dir_all(repo.join(".hx/machines")).unwrap();
|
||||
crate::run::git(&repo, &["init", "-q", "-b", "main"]).unwrap();
|
||||
std::fs::write(
|
||||
repo.join(".hx/machines/m.toml"),
|
||||
r#"name = "m"
|
||||
[[state]]
|
||||
name = "code"
|
||||
kind = "start"
|
||||
steps = [{ name = "edit", run = "computer", cmd = "echo x >> n" }]
|
||||
next = "test"
|
||||
[[state]]
|
||||
name = "test"
|
||||
steps = [{ name = "cargo test", run = "computer", sets = "testing", report = "junit", cmd = "printf '<testsuite><testcase name=\"a::ok\"/><testcase name=\"a::bad\"><failure message=\"nope\">at src/x.rs:9:1</failure></testcase></testsuite>' > {{report}}; echo to-stdout; exit 1" }]
|
||||
catch = { TestsFailed = "code" }
|
||||
retry = { TestsFailed = { max = 3, then = "stuck" } }
|
||||
next = "merge"
|
||||
[[state]]
|
||||
name = "merge"
|
||||
kind = "exit"
|
||||
end = "merged"
|
||||
[[state]]
|
||||
name = "stuck"
|
||||
kind = "exit"
|
||||
only_on = ["TestsFailed x3"]
|
||||
end = "escalated"
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
crate::run::git(&repo, &["add", "-A"]).unwrap();
|
||||
crate::run::git(&repo, &["commit", "-qm", "init"]).unwrap();
|
||||
let db = Db::open(&repo.join(".hx/orch.db")).unwrap();
|
||||
let s = crate::runner::create(&db, &dir.join("wt"), "demo", "", "m").unwrap();
|
||||
let m = Machine::find("m", &repo).unwrap();
|
||||
let profile = crate::profile::Profile::parse("").unwrap();
|
||||
let status = crate::runner::run_session(&db, &m, &s.id, &repo, "", &profile).unwrap();
|
||||
assert_eq!(status, "escalated");
|
||||
|
||||
let mut app = App::new(repo.clone());
|
||||
app.screen = Screen::Session("s1".into());
|
||||
app.refresh();
|
||||
let d = app.detail.as_ref().expect("detail loads").clone();
|
||||
let mut t = Terminal::new(TestBackend::new(160, 45)).unwrap();
|
||||
let h = Header {
|
||||
repo: "~/r".into(),
|
||||
rev: "main@abc".into(),
|
||||
now_ms: 0,
|
||||
};
|
||||
t.draw(|f| session::draw(f, &d, &h)).unwrap();
|
||||
let b = t.backend().buffer();
|
||||
let text = b
|
||||
.content()
|
||||
.chunks(b.area.width as usize)
|
||||
.map(|r| {
|
||||
r.iter()
|
||||
.map(|c| c.symbol())
|
||||
.collect::<String>()
|
||||
.trim_end()
|
||||
.to_string()
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
if std::env::var_os("ORCH_DUMP").is_some() {
|
||||
println!("{text}"); // `ORCH_DUMP=1 cargo test -- --nocapture` shows the screen
|
||||
}
|
||||
for want in [
|
||||
"s1 demo",
|
||||
"m.toml",
|
||||
"state / step",
|
||||
"code · start",
|
||||
"catch TestsFailed",
|
||||
"hit 3×",
|
||||
"catch TestsFailed ×3",
|
||||
"│ only on TestsFailed ×3",
|
||||
"Last test run",
|
||||
"1 passed",
|
||||
"1 failed",
|
||||
"✗ a::bad",
|
||||
"src/x.rs:9",
|
||||
"failed in the first run, fix 1 too",
|
||||
"retries",
|
||||
"3 / 3",
|
||||
"path",
|
||||
"code → test ✗ → code → test ✗ → code → test ✗ → stuck",
|
||||
"full test output",
|
||||
] {
|
||||
assert!(text.contains(want), "missing {want:?} in:\n{text}");
|
||||
}
|
||||
|
||||
let out = test_output(&app, "s1");
|
||||
assert_eq!(out.title, "output of cargo test");
|
||||
assert!(
|
||||
out.lines.iter().any(|l| l == "to-stdout"),
|
||||
"{:?}",
|
||||
out.lines
|
||||
);
|
||||
let tr = transcript(&app, "s1");
|
||||
assert!(tr.lines.last().unwrap().contains("ended: escalated"));
|
||||
// the agent's (here: the shell's) untracked file shows up in the diff view
|
||||
assert!(diff_of(&d.worktree).lines.iter().any(|l| l == "?? n"));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user