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:
johannesandClaude Sonnet 5.5 committed 2026-11-14 12:14:25 +01:00
1 parent d66a014bc5
commit 5b659fa8ba
14 files changed
+2676 -91

No files matched your search

Generated
+10
View File
@@ -904,6 +904,7 @@ dependencies = [
"crossterm", "crossterm",
"indexmap", "indexmap",
"libc", "libc",
"quick-xml",
"ratatui", "ratatui",
"rusqlite", "rusqlite",
"serde", "serde",
@@ -1125,6 +1126,15 @@ dependencies = [
"cc", "cc",
] ]
[[package]]
name = "quick-xml"
version = "0.42.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b"
dependencies = [
"memchr",
]
[[package]] [[package]]
name = "quote" name = "quote"
version = "1.0.47" version = "1.0.47"
+1
View File
@@ -10,6 +10,7 @@ clap = { version = "4", features = ["derive"] }
crossterm = "0.29.0" crossterm = "0.29.0"
indexmap = { version = "2.14.2", features = ["serde"] } indexmap = { version = "2.14.2", features = ["serde"] }
libc = "0.2" libc = "0.2"
quick-xml = "0.42.0"
ratatui = "0.30.2" ratatui = "0.30.2"
rusqlite = { version = "0.42.0", features = ["bundled"] } rusqlite = { version = "0.42.0", features = ["bundled"] }
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
+9
View File
@@ -43,6 +43,15 @@ kind = "cmd"
command = "python3 /work/adapters/gitea.py" command = "python3 /work/adapters/gitea.py"
``` ```
## State-machine sessions and the TUI
`orch` without a subcommand opens the TUI: sessions overview (`enter` on a row opens the session detail, `esc` goes
back; `t` full test output, `d` diff, `l` event transcript, `o` open the worktree in hx). It reads `.hx/orch.db` of the
current directory. `orch session --repo . --machine task --name NAME [--profile P]` creates a session and runs it.
Machines are TOML files in `.hx/machines/` or `~/.hx/machines/` (examples in `examples/machines/`). A `computer` step
with `report = "junit"` writes its JUnit XML to `$ORCH_REPORT` (also available as `{{report}}` in `cmd`); orch parses
it into counts and failing tests. See ORCHESTRATOR.md for the whole design.
## More ## More
- [docs/cmd-protocol.md](docs/cmd-protocol.md): task sources and result sinks as external commands (+ JSON schema) - [docs/cmd-protocol.md](docs/cmd-protocol.md): task sources and result sinks as external commands (+ JSON schema)
+201
View File
@@ -0,0 +1,201 @@
//! ACP client (ORCHESTRATOR.md section 5): JSON-RPC 2.0, one JSON object per line, over the stdio of
//! `hx serve --acp`. Standard ACP messages (`initialize`, `session/new`, `session/update`,
//! `session/request_permission`) plus the custom `hx/*` messages. `hx/step` is acknowledged at once; the
//! outcome arrives later as the `hx/step_result` notification.
use crate::profile::Profile;
use crate::run::hx_env;
use anyhow::{Context, Result, anyhow, bail};
use serde_json::{Value, json};
use std::io::{BufRead, Write};
use std::os::unix::process::CommandExt;
use std::path::Path;
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::mpsc;
/// Receives what hx reports while a step runs.
pub trait Sink {
/// Notifications: `hx/intent`, `hx/edit`, `hx/usage`, `hx/decision`, `hx/plan`, `session/update`.
fn notify(&mut self, method: &str, params: &Value) -> Result<()>;
/// `session/request_permission`: returns the chosen `optionId`, or None to cancel the request.
fn permission(&mut self, params: &Value) -> Option<String>;
}
#[derive(Debug, PartialEq)]
pub struct StepResult {
/// done | blocked | needs_input
pub status: String,
pub catch: Option<String>,
pub question: Option<String>,
pub summary: String,
}
pub struct Acp {
child: Child,
stdin: ChildStdin,
rx: mpsc::Receiver<Value>,
next_id: u64,
session: String,
}
impl Acp {
/// Starts `hx serve --acp --cwd <worktree> --session <id>` and opens an ACP session.
pub fn spawn(p: &Profile, worktree: &Path, id: &str) -> Result<Self> {
let mut parts = p.hx.split_whitespace();
let mut cmd = Command::new(parts.next().context("empty hx command")?);
cmd.args(parts)
.args(["serve", "--acp", "--cwd"])
.arg(worktree)
.args(["--session", id]);
// same cleared environment as the batch runner: orch's secrets never reach the agent
cmd.env_clear().envs(hx_env(std::env::vars(), p));
if let Some(h) = &p.home {
cmd.env("HOME", h);
}
let log = std::fs::File::create(format!("{}.agent.log", worktree.display()))?;
let mut child = cmd
.current_dir(worktree)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::from(log))
.process_group(0) // own group: kill takes hx and its tool children together
.spawn()
.with_context(|| format!("spawn {}", p.hx))?;
let stdin = child.stdin.take().expect("piped");
let out = child.stdout.take().expect("piped");
let (tx, rx) = mpsc::channel();
std::thread::spawn(move || {
for l in std::io::BufReader::new(out).lines().map_while(Result::ok) {
if let Ok(v) = serde_json::from_str::<Value>(&l)
&& tx.send(v).is_err()
{
break;
}
}
});
let mut a = Self {
child,
stdin,
rx,
next_id: 1,
session: String::new(),
};
a.request(
"initialize",
json!({"protocolVersion": 1, "clientCapabilities": {}}),
)?;
let new = a.request("session/new", json!({"cwd": worktree, "mcpServers": []}))?;
a.session = new["sessionId"].as_str().unwrap_or(id).to_string();
Ok(a)
}
fn send(&mut self, v: Value) -> Result<()> {
let mut line = v.to_string();
line.push('\n');
self.stdin
.write_all(line.as_bytes())
.and_then(|()| self.stdin.flush())
.context("write to hx (did it exit?)")
}
/// Sends a request and returns its result. Only used for the handshake, before any step runs, so
/// nothing hx sends in between has a sink to go to and is dropped.
fn request(&mut self, method: &str, params: Value) -> Result<Value> {
let id = self.next_id;
self.next_id += 1;
self.send(json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}))?;
loop {
let m = self.recv()?;
if m.get("method").is_none() && m["id"] == json!(id) {
if let Some(e) = m.get("error") {
bail!("hx {method}: {}", e["message"].as_str().unwrap_or("error"));
}
return Ok(m["result"].clone());
}
self.dispatch(&m, None)?;
}
}
fn recv(&mut self) -> Result<Value> {
self.rx
.recv()
.map_err(|_| anyhow!("hx closed its output (exited or crashed)"))
}
/// Handles one message that is not the response we wait for. Returns a step result if it was one.
fn dispatch(&mut self, m: &Value, sink: Option<&mut dyn Sink>) -> Result<Option<StepResult>> {
let Some(method) = m["method"].as_str() else {
return Ok(None); // a late response (e.g. the ack of hx/step)
};
let params = &m["params"];
if m.get("id").is_some() {
// a request from hx
let reply = if method == "session/request_permission" {
let chosen = sink.and_then(|s| s.permission(params));
let outcome = match chosen {
Some(o) => json!({"outcome": "selected", "optionId": o}),
None => json!({"outcome": "cancelled"}),
};
json!({"jsonrpc": "2.0", "id": m["id"], "result": {"outcome": outcome}})
} else {
json!({"jsonrpc": "2.0", "id": m["id"], "error": {"code": -32601, "message": format!("unsupported: {method}")}})
};
self.send(reply)?;
return Ok(None);
}
if method == "hx/step_result" {
let s = |k: &str| params[k].as_str().map(String::from);
return Ok(Some(StepResult {
status: s("status").unwrap_or_default(),
catch: s("catch"),
question: s("question"),
summary: s("summary").unwrap_or_default(),
}));
}
if let Some(s) = sink {
s.notify(method, params)?;
}
Ok(None)
}
/// Runs one agent step and waits for its `hx/step_result`.
pub fn step(
&mut self,
prompt: &str,
instruction: &str,
context: Value,
limits: Value,
sink: &mut dyn Sink,
) -> Result<StepResult> {
let id = self.next_id;
self.next_id += 1;
self.send(
json!({"jsonrpc": "2.0", "id": id, "method": "hx/step", "params": {
"sessionId": self.session, "prompt": prompt, "instruction": instruction,
"context": context, "limits": limits,
}}),
)?;
loop {
let m = self.recv()?;
if m.get("method").is_none() && m["id"] == json!(id) {
if let Some(e) = m.get("error") {
bail!(
"hx/step rejected: {}",
e["message"].as_str().unwrap_or("error")
);
}
continue; // the ack
}
if let Some(r) = self.dispatch(&m, Some(&mut *sink))? {
return Ok(r);
}
}
}
}
impl Drop for Acp {
fn drop(&mut self) {
crate::state::kill_group(self.child.id());
let _ = self.child.wait();
}
}
+18
View File
@@ -189,6 +189,24 @@ impl Db {
Ok(self.conn.last_insert_rowid()) Ok(self.conn.last_insert_rowid())
} }
/// A choice an agent reported with `hx/decision`; the goal view lists them for veto.
pub fn add_decision(&self, session: &str, text: &str, state: &str) -> Result<()> {
self.conn.execute(
"insert into decisions(session_id, text, state, at) values (?1, ?2, ?3, ?4)",
params![session, text, state, crate::state::now_ms() as i64],
)?;
Ok(())
}
pub fn decision_count(&self, session: &str) -> Result<usize> {
let n: i64 = self.conn.query_row(
"select count(*) from decisions where session_id = ?1",
[session],
|r| r.get(0),
)?;
Ok(n as usize)
}
/// Events oldest first, optionally one session, only those after `after` (event id). /// Events oldest first, optionally one session, only those after `after` (event id).
pub fn events(&self, session: Option<&str>, after: i64) -> Result<Vec<Event>> { pub fn events(&self, session: Option<&str>, after: i64) -> Result<Vec<Event>> {
let mut q = self.conn.prepare( let mut q = self.conn.prepare(
+744
View File
@@ -0,0 +1,744 @@
//! View model of the session detail screen (ORCHESTRATOR.md 7.2, `Session.dc.html`): the machine rendered as
//! text with a live column, the path taken, the last test run, what the agent does now, changed files, budgets.
//! Pure, like `view.rs`: events and the machine file in, lines out.
use crate::db::Event;
use crate::machine::{Kind, RunOn};
use crate::view::{Input, Status};
use std::collections::HashMap;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum LineKind {
Header,
Step,
Catch,
End,
Only,
Blank,
}
/// Which block color a line gets: the current state is highlighted, failed ones are red.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Block {
Done,
Cur,
Fail,
Todo,
}
#[derive(Clone, PartialEq, Debug)]
pub struct MLine {
pub kind: LineKind,
pub text: String,
/// ` → target` of a catch line, drawn in the state color.
pub to: String,
pub exec: Option<RunOn>,
pub sets: String,
pub live: String,
pub block: Block,
/// A catch that fired: its live text is drawn bold red.
pub hit: bool,
}
#[derive(Clone, PartialEq, Debug)]
pub struct PathStep {
pub name: String,
pub failed: bool,
pub current: bool,
}
#[derive(Clone, PartialEq, Debug)]
pub struct FailView {
pub name: String,
pub message: String,
pub location: String,
/// `failed in fix 1 too`, or empty.
pub repeats: String,
}
#[derive(Clone, PartialEq, Debug)]
pub struct TestRun {
pub step: String,
pub at_ms: u64,
pub passed: u32,
pub failed: u32,
pub skipped: u32,
pub secs: f64,
pub failures: Vec<FailView>,
}
#[derive(Clone, PartialEq, Debug, Default)]
pub struct Now {
/// `agent`, `computer` or empty.
pub who: String,
pub line: String,
pub intent: String,
}
#[derive(Clone, PartialEq, Debug)]
pub struct FileChange {
pub path: String,
pub added: u32,
pub removed: u32,
}
#[derive(Clone, PartialEq, Debug, Default)]
pub struct Budget {
/// (used, limit) context tokens.
pub ctx: Option<(u64, u64)>,
/// (fix count, max) of the busiest retry loop.
pub retries: Option<(u32, u32)>,
pub wall_secs: u64,
pub cost: f64,
}
#[derive(Clone, PartialEq, Debug)]
pub struct Detail {
pub id: String,
pub task: String,
pub status: Status,
pub branch: String,
pub worktree: String,
pub pid: Option<u32>,
pub machine_file: String,
pub on_abort: Option<String>,
pub on_budget: Option<String>,
pub lines: Vec<MLine>,
pub path: Vec<PathStep>,
pub test: Option<TestRun>,
pub now: Now,
pub files: Vec<FileChange>,
pub budget: Budget,
}
/// `6.2s`, `0m59s`, `4m10s`.
pub fn dur(ms: u64) -> String {
if ms < 10_000 {
format!("{:.1}s", ms as f64 / 1000.0)
} else {
let s = ms / 1000;
format!("{}m{:02}s", s / 60, s % 60)
}
}
/// One stay in a state: from the `state` event to the next one.
struct Visit<'a> {
state: &'a str,
/// (step, ms, ok)
steps: Vec<(&'a str, u64, bool)>,
caught: Option<&'a str>,
test: Option<(u64, u64)>,
}
fn s<'a>(v: &'a serde_json::Value, k: &str) -> &'a str {
v[k].as_str().unwrap_or_default()
}
pub fn build(i: &Input, id: &str) -> Option<Detail> {
let sess = i.sessions.iter().find(|x| x.id == id)?;
let task = i.tasks.iter().find(|t| t.id == sess.task_id)?;
let machine = i.machines.get(&task.machine)?;
let overview = crate::view::build(i);
let status = overview.rows.iter().find(|r| r.id == id)?.status;
let evs: Vec<&Event> = i.events.iter().filter(|e| e.session == id).collect();
let mut visits: Vec<Visit> = vec![];
for e in &evs {
let p = &e.payload;
match e.kind.as_str() {
"state" => visits.push(Visit {
state: s(p, "to"),
steps: vec![],
caught: None,
test: None,
}),
"step" => {
if let Some(v) = visits.last_mut() {
v.steps
.push((s(p, "step"), p["ms"].as_u64().unwrap_or(0), p["ok"] == true));
}
}
"catch" => {
if let Some(v) = visits.last_mut() {
v.caught = Some(s(p, "catch"));
}
}
"test" => {
if let Some(v) = visits.last_mut() {
v.test = Some((
p["passed"].as_u64().unwrap_or(0),
p["failed"].as_u64().unwrap_or(0),
));
}
}
_ => {}
}
}
let active = matches!(sess.status.as_str(), "running" | "waiting");
let cur_state = if active {
visits.last().map(|v| v.state)
} else {
None
};
let last_at = evs.last().map_or(0, |e| e.at);
let first_at = evs.first().map_or(last_at, |e| e.at);
let hits = |state: &str, catch: &str| {
evs.iter()
.filter(|e| {
e.kind == "catch"
&& s(&e.payload, "state") == state
&& s(&e.payload, "catch") == catch
})
.count() as u32
};
let mut lines: Vec<MLine> = vec![];
let mut running_step: Option<(&str, RunOn, Option<&str>)> = None;
let line = |kind, text: String| MLine {
kind,
text,
to: String::new(),
exec: None,
sets: String::new(),
live: String::new(),
block: Block::Todo,
hit: false,
};
// main flow first, then the only_on states, like the machine file reads
let ordered = machine
.states
.iter()
.filter(|st| st.only_on.is_empty())
.chain(machine.states.iter().filter(|st| !st.only_on.is_empty()));
for st in ordered {
let mine: Vec<&Visit> = visits.iter().filter(|v| v.state == st.name).collect();
let last = mine.last();
let is_cur = cur_state == Some(st.name.as_str());
let block = if is_cur {
Block::Cur
} else if let Some(v) = last {
let died_here =
sess.status == "failed" && visits.last().is_some_and(|l| l.state == st.name);
if v.caught.is_some() || died_here {
Block::Fail
} else {
Block::Done
}
} else {
Block::Todo
};
let only = !st.only_on.is_empty();
let bar = if only { "│ " } else { "" };
if !lines.is_empty() {
lines.push(line(LineKind::Blank, String::new()));
}
if only {
let when = st.only_on.join(", ").replace(" x", " ×");
lines.push(line(LineKind::Only, format!("│ only on {when}")));
}
let tag = match st.kind {
Kind::Start => " · start",
Kind::Gate => " · gate",
Kind::Exit => " · exit",
Kind::Abort => " · abort",
Kind::Normal => "",
};
let mut h = line(LineKind::Header, format!("{bar}{}{tag}", st.name));
h.block = block;
h.live = match (block, last) {
(Block::Cur, _) if mine.len() > 1 => format!("▶ fix {}", mine.len() - 1),
(Block::Cur, _) => "▶".into(),
(Block::Fail, Some(v)) => match v.test {
Some((p, f)) => format!("✗ {p}/{}", p + f),
None => "✗".into(),
},
(Block::Done, Some(v)) => {
let total: u64 = v.steps.iter().map(|x| x.1).sum();
let times = if mine.len() > 1 {
format!(" ×{}", mine.len())
} else {
String::new()
};
format!("✓ {}{times}", dur(total))
}
_ => String::new(),
};
lines.push(h);
// the step that runs right now: the first one of the current visit without a result
let done_in_visit = if is_cur {
last.map_or(0, |v| v.steps.len())
} else {
0
};
for (n, step) in st.steps.iter().enumerate() {
let mut l = line(LineKind::Step, format!("{bar} {}", step.name));
l.exec = Some(step.run);
l.sets = step
.sets
.as_ref()
.map(|x| format!("■ {x}"))
.unwrap_or_default();
l.block = block;
let rec = last.and_then(|v| v.steps.iter().find(|x| x.0 == step.name));
l.live = match rec {
Some(&(_, ms, true)) if !is_cur || n < done_in_visit => format!("✓ {}", dur(ms)),
Some(&(_, ms, false)) if !is_cur || n < done_in_visit => format!("✗ {}", dur(ms)),
_ if is_cur && n == done_in_visit => {
running_step = Some((&step.name, step.run, step.cmd.as_deref()));
format!("▶ {}", dur(i.now_ms.saturating_sub(last_at)))
}
_ => String::new(),
};
lines.push(l);
}
for (c, target) in &st.catch {
let n = hits(&st.name, c);
let mut l = line(LineKind::Catch, format!("{bar} catch {c}"));
l.to = format!(" → {target}");
l.block = block;
if n > 0 {
l.live = format!("hit {n}×");
l.hit = true;
}
lines.push(l);
if let Some(r) = st.retry.get(c) {
let mut l = line(LineKind::Catch, format!("{bar} catch {c} ×{}", r.max));
l.to = format!(" → {}", r.then);
l.block = if n + 1 >= r.max { Block::Fail } else { block };
if n + 1 == r.max {
l.live = "next".into();
}
lines.push(l);
}
}
if let (true, Some(end)) = (matches!(st.kind, Kind::Exit | Kind::Abort), &st.end) {
let mut l = line(LineKind::End, format!("{bar} end: {end}"));
l.block = block;
lines.push(l);
}
}
let mut path: Vec<PathStep> = visits
.iter()
.map(|v| PathStep {
name: v.state.to_string(),
failed: v.caught.is_some(),
current: false,
})
.collect();
if let Some(l) = path.last_mut() {
if cur_state.is_some() {
l.current = true;
} else if sess.status == "failed" {
l.failed = true;
}
}
// test runs, oldest first; failures remember in which earlier runs they failed too
let runs: Vec<&&Event> = evs.iter().filter(|e| e.kind == "test").collect();
let test = runs.last().map(|e| {
let p = &e.payload;
let mut earlier: HashMap<&str, Vec<usize>> = HashMap::new();
for (n, r) in runs[..runs.len() - 1].iter().enumerate() {
for f in r.payload["failures"].as_array().into_iter().flatten() {
earlier.entry(s(f, "name")).or_default().push(n);
}
}
let failures = p["failures"]
.as_array()
.into_iter()
.flatten()
.map(|f| {
let name = s(f, "name");
let repeats = match earlier.get(name) {
Some(v) if !v.is_empty() => {
let which: Vec<String> = v
.iter()
.map(|&n| {
if n == 0 {
"the first run".into()
} else {
format!("fix {n}")
}
})
.collect();
format!("failed in {} too", which.join(", "))
}
_ => String::new(),
};
FailView {
name: name.into(),
message: s(f, "message").into(),
location: s(f, "location").into(),
repeats,
}
})
.collect();
TestRun {
step: s(p, "step").into(),
at_ms: e.at,
passed: p["passed"].as_u64().unwrap_or(0) as u32,
failed: p["failed"].as_u64().unwrap_or(0) as u32,
skipped: p["skipped"].as_u64().unwrap_or(0) as u32,
secs: p["secs"].as_f64().unwrap_or(0.0),
failures,
}
});
let mut now = Now::default();
if let Some((name, run, cmd)) = running_step {
match run {
RunOn::Agent => {
now.who = "agent".into();
now.line = evs
.iter()
.rev()
.find_map(|e| match e.kind.as_str() {
"tool" => Some(s(&e.payload, "title").to_string()),
"edit" => Some(format!(
"edit {} +{} −{}",
s(&e.payload, "path"),
e.payload["added"],
e.payload["removed"]
)),
_ => None,
})
.unwrap_or_else(|| name.to_string());
}
RunOn::Computer => {
now.who = "computer".into();
now.line = cmd.unwrap_or(name).to_string();
}
RunOn::Human => {
now.who = "human".into();
now.line = name.to_string();
}
}
}
now.intent = evs
.iter()
.rev()
.find(|e| e.kind == "intent")
.map(|e| s(&e.payload, "text").to_string())
.unwrap_or_default();
let mut files: Vec<FileChange> = vec![];
for e in evs.iter().filter(|e| e.kind == "edit") {
let (path, a, r) = (
s(&e.payload, "path"),
e.payload["added"].as_u64().unwrap_or(0) as u32,
e.payload["removed"].as_u64().unwrap_or(0) as u32,
);
match files.iter_mut().find(|f| f.path == path) {
Some(f) => {
f.added += a;
f.removed += r;
}
None => files.push(FileChange {
path: path.into(),
added: a,
removed: r,
}),
}
}
let usage = evs.iter().rev().find(|e| e.kind == "usage");
let retries = machine
.states
.iter()
.flat_map(|st| {
st.retry
.iter()
.map(move |(c, r)| (st.name.as_str(), c.as_str(), r.max))
})
.map(|(st, c, max)| (hits(st, c), max))
.filter(|&(n, _)| n > 0)
.max_by_key(|&(n, _)| n);
let budget = Budget {
ctx: usage.map(|e| {
(
e.payload["ctx_used"].as_u64().unwrap_or(0),
e.payload["ctx_limit"].as_u64().unwrap_or(0),
)
}),
retries,
wall_secs: i.now_ms.saturating_sub(first_at) / 1000,
cost: usage
.and_then(|e| e.payload["cost"].as_f64())
.unwrap_or(0.0),
};
Some(Detail {
id: id.into(),
task: task.name.clone(),
status,
branch: sess.branch.clone(),
worktree: sess.worktree.clone(),
pid: sess.pid,
machine_file: format!("{}.toml", machine.name),
on_abort: machine.on_abort.clone(),
on_budget: machine.on_budget.clone(),
lines,
path,
test,
now,
files,
budget,
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::db::{Session, Task};
use crate::machine::Machine;
use serde_json::json;
fn ev(id: i64, kind: &str, payload: serde_json::Value) -> Event {
Event {
id,
session: "s2".into(),
at: 1000 * id as u64,
kind: kind.into(),
payload,
}
}
fn state(id: i64, from: &str, to: &str) -> Event {
ev(id, "state", json!({"from": from, "to": to}))
}
fn step(id: i64, st: &str, name: &str, ms: u64, ok: bool) -> Event {
ev(
id,
"step",
json!({"state": st, "step": name, "ms": ms, "ok": ok}),
)
}
fn test_run(id: i64, names: &[&str]) -> Event {
let failures: Vec<_> = names
.iter()
.map(|n| json!({"name": n, "message": format!("{n} broke"), "location": "src/a.rs:1"}))
.collect();
ev(
id,
"test",
json!({"state": "test", "step": "cargo test", "passed": 39, "failed": names.len(), "skipped": 0, "secs": 6.2, "failures": failures}),
)
}
fn catch(id: i64) -> Event {
ev(
id,
"catch",
json!({"state": "test", "catch": "TestsFailed"}),
)
}
/// plan, code, build, test (2 failing) -> code; again; now in code for the third time.
fn scenario() -> Vec<Event> {
vec![
state(1, "", "plan"),
step(2, "plan", "read-goal", 200, true),
step(3, "plan", "draft-plan", 250_000, true),
state(4, "plan", "code"),
step(5, "code", "edit", 59_000, true),
state(6, "code", "build"),
step(7, "build", "cargo build", 38_000, true),
state(8, "build", "test"),
test_run(9, &["a::one", "a::two"]),
step(10, "test", "cargo test", 6_200, false),
catch(11),
state(12, "test", "code"),
step(13, "code", "edit", 59_000, true),
state(14, "code", "build"),
step(15, "build", "cargo build", 38_000, true),
state(16, "build", "test"),
test_run(17, &["a::one", "a::two"]),
step(18, "test", "cargo test", 6_200, false),
catch(19),
state(20, "test", "code"),
ev(21, "intent", json!({"text": "rotate the key"})),
ev(
22,
"edit",
json!({"path": "src/auth/token.rs", "added": 6, "removed": 2}),
),
ev(
23,
"edit",
json!({"path": "src/auth/token.rs", "added": 4, "removed": 0}),
),
ev(
24,
"edit",
json!({"path": "src/auth/mod.rs", "added": 1, "removed": 1}),
),
ev(25, "tool", json!({"title": "edit src/auth/token.rs"})),
ev(
26,
"usage",
json!({"ctx_used": 142_000, "ctx_limit": 200_000, "cost": 1.12}),
),
]
}
fn detail(events: &[Event], status: &str, state: &str) -> Detail {
let m = HashMap::from([(
"task".to_string(),
Machine::parse(include_str!("../examples/machines/task.toml")).unwrap(),
)]);
let tasks = [Task {
id: "s2".into(),
name: "oauth".into(),
subtitle: String::new(),
machine: "task".into(),
depends_on: vec![],
}];
let sessions = [Session {
id: "s2".into(),
task_id: "s2".into(),
branch: "hx/s2-oauth".into(),
worktree: "/wt/s2".into(),
pid: Some(7),
state: state.into(),
status: status.into(),
}];
build(
&Input {
goal: None,
tasks: &tasks,
sessions: &sessions,
events,
machines: &m,
now_ms: 36_000,
},
"s2",
)
.unwrap()
}
fn find<'a>(d: &'a Detail, text: &str) -> &'a MLine {
d.lines
.iter()
.find(|l| l.text.trim_end() == text)
.unwrap_or_else(|| panic!("no line {text:?}"))
}
#[test]
fn machine_lines_follow_the_mockup() {
let d = detail(&scenario(), "running", "code");
let plan = find(&d, "plan · start");
assert_eq!((plan.block, plan.live.as_str()), (Block::Done, "✓ 4m10s"));
let draft = find(&d, " draft-plan");
assert_eq!(
(draft.exec, draft.sets.as_str(), draft.live.as_str()),
(Some(RunOn::Agent), "■ planning", "✓ 4m10s")
);
let code = find(&d, "code");
assert_eq!((code.block, code.live.as_str()), (Block::Cur, "▶ fix 2"));
// the running step shows the time since the last event (36s now, last event at 26s)
assert_eq!(find(&d, " edit").live, "▶ 0m10s");
let build = find(&d, "build");
assert_eq!(build.live, "✓ 0m38s ×2");
let test = find(&d, "test");
assert_eq!((test.block, test.live.as_str()), (Block::Fail, "✗ 39/41"));
let hit = find(&d, " catch TestsFailed");
assert_eq!(
(hit.live.as_str(), hit.hit, hit.to.as_str()),
("hit 2×", true, " → code")
);
let next = find(&d, " catch TestsFailed ×3");
assert_eq!(
(next.live.as_str(), next.to.as_str()),
("next", " → escalated")
);
assert_eq!(find(&d, "review · gate").block, Block::Todo);
assert_eq!(find(&d, "merge · exit").live, "");
assert_eq!(find(&d, " end: merged").kind, LineKind::End);
// only_on states come last, marked
assert!(
d.lines
.iter()
.any(|l| l.text == "│ only on TestsFailed ×3, budget")
);
assert!(d.lines.iter().any(|l| l.text == "│ escalated · exit"));
assert!(d.lines.iter().any(|l| l.text == "│ snapshot-worktree"));
// untouched machine order: escalated after merge
let pos = |t: &str| d.lines.iter().position(|l| l.text == t).unwrap();
assert!(pos("merge · exit") < pos("│ escalated · exit"));
}
#[test]
fn path_test_run_now_files_budget() {
let d = detail(&scenario(), "running", "code");
let names: Vec<String> = d
.path
.iter()
.map(|p| format!("{}{}", p.name, if p.failed { " ✗" } else { "" }))
.collect();
assert_eq!(
names,
[
"plan", "code", "build", "test ✗", "code", "build", "test ✗", "code"
]
);
assert!(d.path.last().unwrap().current);
let t = d.test.as_ref().unwrap();
assert_eq!((t.passed, t.failed, t.step.as_str()), (39, 2, "cargo test"));
assert_eq!(t.failures[0].repeats, "failed in the first run too");
assert_eq!(t.failures[1].location, "src/a.rs:1");
assert_eq!(d.now.who, "agent");
assert_eq!(d.now.line, "edit src/auth/token.rs");
assert_eq!(d.now.intent, "rotate the key");
assert_eq!(d.files.len(), 2);
assert_eq!(
(
d.files[0].path.as_str(),
d.files[0].added,
d.files[0].removed
),
("src/auth/token.rs", 10, 2)
);
assert_eq!(d.budget.ctx, Some((142_000, 200_000)));
assert_eq!(d.budget.retries, Some((2, 3)));
assert_eq!(d.budget.wall_secs, 35);
assert!((d.budget.cost - 1.12).abs() < 1e-9);
assert_eq!(
(d.status, d.branch.as_str(), d.pid),
(Status::Fix, "hx/s2-oauth", Some(7))
);
assert_eq!(d.on_budget.as_deref(), Some("escalated"));
}
#[test]
fn third_failure_lists_both_earlier_runs() {
let mut evs = scenario();
evs.push(test_run(30, &["a::one"]));
let d = detail(&evs, "running", "code");
assert_eq!(
d.test.unwrap().failures[0].repeats,
"failed in the first run, fix 1 too"
);
}
#[test]
fn finished_session_has_no_current_state() {
let evs = vec![
state(1, "", "plan"),
step(2, "plan", "read-goal", 100, true),
ev(3, "end", json!({"status": "failed", "reason": "boom"})),
];
let d = detail(&evs, "failed", "plan");
assert_eq!(find(&d, "plan · start").block, Block::Fail);
assert!(d.path[0].failed && !d.path[0].current);
assert_eq!(d.now, Now::default());
assert_eq!(dur(500), "0.5s");
assert_eq!(dur(65_000), "1m05s");
}
}
+253
View File
@@ -0,0 +1,253 @@
//! JUnit XML test reports (`report = "junit"` steps): counts and the failing tests with message and location.
//! Works with `cargo nextest --message-format junit`, `cargo2junit`, pytest, JUnit itself: it only needs
//! `<testcase name classname time file line>` with `<failure>`/`<error>`/`<skipped>` children.
use anyhow::{Result, anyhow};
use quick_xml::Reader;
use quick_xml::escape::resolve_predefined_entity;
use quick_xml::events::{BytesStart, Event};
use serde::Serialize;
#[derive(Serialize, Clone, Debug, PartialEq)]
pub struct Failure {
pub name: String,
/// The assertion text: the `message` attribute, else the first line of the failure body.
pub message: String,
/// `file:line` when the report has it, else the first `path.ext:NN` in the failure body.
pub location: String,
}
#[derive(Serialize, Clone, Debug, Default, PartialEq)]
pub struct Report {
pub passed: u32,
pub failed: u32,
pub skipped: u32,
/// Sum of the test times.
pub secs: f64,
pub failures: Vec<Failure>,
}
fn attr(e: &BytesStart, key: &str) -> String {
e.attributes()
.flatten()
.find(|a| a.key.as_ref() == key)
.and_then(|a| {
a.normalized_value(quick_xml::XmlVersion::Implicit1_0)
.ok()
.map(|v| v.into_owned())
})
.unwrap_or_default()
}
/// First `something/with.ext:123` word of a text.
fn find_location(text: &str) -> String {
text.split(|c: char| c.is_whitespace() || matches!(c, '(' | ')' | ',' | '\'' | '"' | '`'))
.map(|w| w.trim_end_matches(':'))
.find(|w| {
let mut it = w.rsplitn(2, ':');
let (line, file) = (it.next(), it.next());
// rsplitn on `a.rs:12:5` leaves `a.rs:12` as the file part; accept both shapes
let file = file.unwrap_or("").split(':').next().unwrap_or("");
line.is_some_and(|l| !l.is_empty() && l.chars().all(|c| c.is_ascii_digit()))
&& file.contains('.')
&& !file.starts_with('.')
})
.map(|w| {
// keep file:line, drop a trailing :column
let parts: Vec<&str> = w.split(':').collect();
if parts.len() >= 3 {
format!("{}:{}", parts[0], parts[1])
} else {
w.to_string()
}
})
.unwrap_or_default()
}
struct Case {
name: String,
file: String,
line: String,
failure: Option<(String, String)>, // (message attr, body)
skipped: bool,
}
pub fn parse(xml: &str) -> Result<Report> {
let mut r = Reader::from_str(xml);
let mut rep = Report::default();
let mut case: Option<Case> = None;
// inside <failure>/<error>: collecting the body text
let mut in_failure = false;
loop {
let ev = r
.read_event()
.map_err(|e| anyhow!("bad junit xml at byte {}: {e}", r.buffer_position()))?;
match &ev {
Event::Eof => break,
Event::Start(e) | Event::Empty(e) => {
let empty = matches!(ev, Event::Empty(_));
match e.local_name().as_ref() {
"testcase" => {
let (class, name) = (attr(e, "classname"), attr(e, "name"));
let name = if class.is_empty() || name.contains("::") {
name
} else {
format!("{class}::{name}")
};
rep.secs += attr(e, "time").parse::<f64>().unwrap_or(0.0);
let c = Case {
name,
file: attr(e, "file"),
line: attr(e, "line"),
failure: None,
skipped: false,
};
if empty {
rep.passed += 1;
} else {
case = Some(c);
}
}
"failure" | "error" => {
if let Some(c) = &mut case {
c.failure = Some((attr(e, "message"), String::new()));
in_failure = !empty;
}
}
"skipped" => {
if let Some(c) = &mut case {
c.skipped = true;
rep.skipped += 1;
}
}
_ => {}
}
}
Event::Text(t) if in_failure => push_body(&mut case, &t.xml10_content()),
Event::CData(t) if in_failure => push_body(&mut case, &t.xml10_content()),
Event::GeneralRef(g) if in_failure => {
let s = if g.is_char_ref() {
g.resolve_char_ref().ok().flatten().map(String::from)
} else {
resolve_predefined_entity(&g.xml10_content()).map(String::from)
};
push_body(&mut case, &s.unwrap_or_default());
}
Event::End(e) => match e.local_name().as_ref() {
"failure" | "error" => in_failure = false,
"testcase" => {
if let Some(c) = case.take() {
match c.failure {
Some((msg, body)) => {
rep.failed += 1;
let message = if msg.trim().is_empty() {
body.lines()
.map(str::trim)
.find(|l| !l.is_empty())
.unwrap_or("")
.to_string()
} else {
msg
};
let location = if !c.file.is_empty() && !c.line.is_empty() {
format!("{}:{}", c.file, c.line)
} else {
find_location(&format!("{message} {body}"))
};
rep.failures.push(Failure {
name: c.name,
message,
location,
});
}
None if c.skipped => {}
None => rep.passed += 1,
}
}
}
_ => {}
},
_ => {}
}
}
Ok(rep)
}
fn push_body(case: &mut Option<Case>, s: &str) {
if let Some(Case {
failure: Some((_, body)),
..
}) = case
{
body.push_str(s);
}
}
#[cfg(test)]
mod tests {
use super::*;
const XML: &str = r#"<?xml version="1.0"?>
<testsuites>
<testsuite name="auth" tests="5" failures="2" skipped="1">
<testcase classname="auth::token" name="issues_pair" time="0.5"/>
<testcase classname="auth::token" name="skipped_one" time="0"><skipped/></testcase>
<testcase classname="auth::token" name="refresh_rotates_secret" time="1.5">
<failure message="assertion `left != right` failed: key id unchanged after refresh" type="assert">
thread 'main' panicked at src/auth/token.rs:142:9:
assertion failed
</failure>
</testcase>
<testcase classname="x" name="auth::token::expired_token_rejected" time="2.25">
<failure type="assert">expected Err(Expired), got Ok(Claims { sub: &quot;u_17&quot; })
at src/auth/token.rs:188:5</failure>
</testcase>
<testcase classname="auth::token" name="passes_with_body" time="0.25"><system-out><![CDATA[noise]]></system-out></testcase>
</testsuite>
</testsuites>"#;
#[test]
fn counts_failures_and_locations() {
let r = parse(XML).unwrap();
assert_eq!((r.passed, r.failed, r.skipped), (2, 2, 1));
assert!((r.secs - 4.5).abs() < 1e-9);
assert_eq!(
r.failures[0],
Failure {
name: "auth::token::refresh_rotates_secret".into(),
message: "assertion `left != right` failed: key id unchanged after refresh".into(),
location: "src/auth/token.rs:142".into(),
}
);
// message from the body (entities resolved), classname dropped when the name has a path already
assert_eq!(r.failures[1].name, "auth::token::expired_token_rejected");
assert_eq!(
r.failures[1].message,
"expected Err(Expired), got Ok(Claims { sub: \"u_17\" })"
);
assert_eq!(r.failures[1].location, "src/auth/token.rs:188");
}
#[test]
fn file_and_line_attributes_win() {
let r = parse(
r#"<testsuite><testcase name="t" file="a/b.rs" line="7"><error message="boom"/></testcase></testsuite>"#,
)
.unwrap();
assert_eq!(r.failures[0].location, "a/b.rs:7");
assert_eq!((r.passed, r.failed), (0, 1));
}
#[test]
fn empty_and_broken_input() {
assert_eq!(parse("<testsuite/>").unwrap(), Report::default());
assert!(parse("<testsuite><testcase></testsuite>").is_err());
}
#[test]
fn locations() {
assert_eq!(find_location("panicked at src/a.rs:12:5:"), "src/a.rs:12");
assert_eq!(find_location("see lib.rs:3"), "lib.rs:3");
assert_eq!(find_location("no location 12:30 here"), "");
}
}
+12
View File
@@ -183,6 +183,18 @@ impl Machine {
), ),
RunOn::Computer | RunOn::Human => {} RunOn::Computer | RunOn::Human => {}
} }
if let Some(r) = &st.report {
ensure!(
r == "junit",
"state {n:?} step {:?}: unknown report format {r:?} (only junit)",
st.name
);
ensure!(
st.run == RunOn::Computer,
"state {n:?} step {:?}: only computer steps can have a report",
st.name
);
}
if let Some(f) = &st.fail_as { if let Some(f) = &st.fail_as {
ensure!( ensure!(
s.catch.contains_key(f), s.catch.contains_key(f),
+10 -2
View File
@@ -1,5 +1,8 @@
mod acp;
mod adapter; mod adapter;
mod db; mod db;
mod detail;
mod junit;
mod lock; mod lock;
mod machine; mod machine;
mod policy; mod policy;
@@ -70,7 +73,7 @@ enum Cmd {
#[arg(long)] #[arg(long)]
check: bool, check: bool,
}, },
/// Create a state-machine session in REPO and run it to the end (computer steps only for now). /// Create a state-machine session in REPO and run it to the end (human steps are not supported yet).
Session { Session {
#[arg(long)] #[arg(long)]
repo: PathBuf, repo: PathBuf,
@@ -82,6 +85,9 @@ enum Cmd {
/// Value for {{scope}} in machine commands. /// Value for {{scope}} in machine commands.
#[arg(long, default_value = "")] #[arg(long, default_value = "")]
scope: String, scope: String,
/// Profile that says how to start hx for agent steps.
#[arg(long, default_value = "default")]
profile: String,
}, },
/// hx extension that enforces a run's tool allowlist (started by hx, not by hand). /// hx extension that enforces a run's tool allowlist (started by hx, not by hand).
#[command(hide = true)] #[command(hide = true)]
@@ -129,7 +135,9 @@ fn main() -> Result<std::process::ExitCode> {
machine, machine,
name, name,
scope, scope,
profile,
} => { } => {
let profile = profile::Profile::load(&profile)?;
let repo = repo.canonicalize()?; let repo = repo.canonicalize()?;
let m = machine::Machine::find(&machine, &repo)?; let m = machine::Machine::find(&machine, &repo)?;
let db = db::Db::open(&repo.join(".hx/orch.db"))?; let db = db::Db::open(&repo.join(".hx/orch.db"))?;
@@ -137,7 +145,7 @@ fn main() -> Result<std::process::ExitCode> {
let base = repo.file_name().unwrap_or_default(); let base = repo.file_name().unwrap_or_default();
let wts = state_dir().join("worktrees").join(base); let wts = state_dir().join("worktrees").join(base);
let s = runner::create(&db, &wts, &name, "", &machine)?; let s = runner::create(&db, &wts, &name, "", &machine)?;
let status = runner::run_session(&db, &m, &s.id, &repo, &scope)?; let status = runner::run_session(&db, &m, &s.id, &repo, &scope, &profile)?;
println!("{} {} -> {status}", s.id, s.branch); println!("{} {} -> {status}", s.id, s.branch);
Ok(code(status == "merged")) Ok(code(status == "merged"))
} }
+439 -58
View File
@@ -1,18 +1,22 @@
//! Session runner (ORCHESTRATOR.md section 4): walks one session through its machine, writes every step to the //! Session runner (ORCHESTRATOR.md section 4): walks one session through its machine and writes every step to
//! event table. Milestone 2 handles `computer` steps only; `agent` and `human` steps fail the session for now. //! the event table. `computer` steps run as shell commands, `agent` steps go to hx over ACP. `human` steps
//! and `needs_input` results wait for the Needs-you queue (milestone 6) and fail the session for now.
use crate::acp::{Acp, Sink, StepResult};
use crate::db::{Db, Session, Task}; use crate::db::{Db, Session, Task};
use crate::machine::{Kind, Machine, RunOn, State, Step}; use crate::machine::{Kind, Machine, RunOn, State, Step};
use crate::profile::Profile;
use crate::run::{git, tail}; use crate::run::{git, tail};
use anyhow::{Context, Result, bail}; use anyhow::{Context, Result, bail};
use serde_json::json; use serde_json::{Value, json};
use std::path::Path; use std::path::Path;
use std::process::Command; use std::process::Command;
use std::time::Instant; use std::time::Instant;
/// Safety cap against catch loops that have no `retry` limit (e.g. build -> code -> build with a no-op code). /// Safety cap against catch loops that have no `retry` limit (e.g. build -> code -> build with a no-op code).
const MAX_TRANSITIONS: u32 = 500; const MAX_TRANSITIONS: u32 = 500;
const OUTPUT_TAIL: usize = 2000; /// Bytes of step output kept in the event (the `t` key shows it as the full test output).
const OUTPUT_TAIL: usize = 8000;
/// Creates the task and session rows for a new session. The worktree is made by [`run_session`]. /// Creates the task and session rows for a new session. The worktree is made by [`run_session`].
pub fn create( pub fn create(
@@ -76,35 +80,54 @@ fn ensure_worktree(repo: &Path, s: &Session) -> Result<()> {
Ok(()) Ok(())
} }
/// Everything a running session needs; the hx process lives here for the whole session.
struct Ctx<'a> {
db: &'a Db,
s: &'a Session,
task: &'a Task,
profile: &'a Profile,
scope: &'a str,
agent: Option<Acp>,
}
enum Outcome { enum Outcome {
Ok, Ok,
/// A step failed with this catch name. /// A step failed with this catch name.
Caught(String), Caught(String),
} }
fn run_state(db: &Db, s: &Session, st: &State, scope: &str) -> Result<Outcome> { struct StepRes {
ok: bool,
exit: Option<i32>,
/// Command output tail, or the agent's summary.
out: String,
/// Catch named by the step itself (hx `blocked` result); otherwise `fail_as` or the state's first catch.
catch: Option<String>,
}
fn run_state(cx: &mut Ctx, st: &State) -> Result<Outcome> {
for step in &st.steps { for step in &st.steps {
if let Some(label) = &step.sets { if let Some(label) = &step.sets {
db.emit( cx.db.emit(
&s.id, &cx.s.id,
"status", "status",
json!({"state": st.name, "step": step.name, "label": label}), json!({"state": st.name, "step": step.name, "label": label}),
)?; )?;
} }
let t0 = Instant::now(); let t0 = Instant::now();
let (ok, exit, out) = run_step(s, step, scope)?; let r = run_step(cx, st, step)?;
db.emit( cx.db.emit(
&s.id, &cx.s.id,
"step", "step",
json!({ json!({
"state": st.name, "step": step.name, "run": step.run, "ok": ok, "state": st.name, "step": step.name, "run": step.run, "ok": r.ok,
"exit": exit, "ms": t0.elapsed().as_millis() as u64, "output": out, "exit": r.exit, "ms": t0.elapsed().as_millis() as u64, "output": r.out,
}), }),
)?; )?;
if !ok { if !r.ok {
let catch = step let catch = r
.fail_as .catch
.clone() .or_else(|| step.fail_as.clone())
.or_else(|| st.catch.keys().next().cloned()); .or_else(|| st.catch.keys().next().cloned());
let Some(catch) = catch else { let Some(catch) = catch else {
bail!( bail!(
@@ -119,36 +142,216 @@ fn run_state(db: &Db, s: &Session, st: &State, scope: &str) -> Result<Outcome> {
Ok(Outcome::Ok) Ok(Outcome::Ok)
} }
/// (success, exit code, output tail) fn run_step(cx: &mut Ctx, st: &State, step: &Step) -> Result<StepRes> {
fn run_step(s: &Session, step: &Step, scope: &str) -> Result<(bool, Option<i32>, String)> {
match step.run { match step.run {
RunOn::Computer => {} RunOn::Computer => run_command(cx, st, step),
other => bail!( RunOn::Agent => run_agent(cx, st, step),
"step {:?}: {other:?} steps are not supported yet (milestone 4/6)", RunOn::Human => bail!(
"step {:?}: human steps need the Needs-you queue (milestone 6)",
step.name step.name
), ),
} }
}
/// Where a `report = "junit"` step writes its report. Next to the worktree, not in it: it must not dirty git.
fn report_path(s: &Session) -> String {
format!("{}.junit.xml", s.worktree)
}
fn run_command(cx: &Ctx, st: &State, step: &Step) -> Result<StepRes> {
let Some(cmd) = &step.cmd else { let Some(cmd) = &step.cmd else {
return Ok((true, Some(0), String::new())); // marker step (open-diff, mark-merged, ...) // marker step (open-diff, mark-merged, ...)
return Ok(StepRes {
ok: true,
exit: Some(0),
out: String::new(),
catch: None,
});
}; };
let report = report_path(cx.s);
// a stale report from an earlier run must not be read as this run's result
let _ = std::fs::remove_file(&report);
let o = Command::new("sh") let o = Command::new("sh")
.args(["-c", &format!("({}) 2>&1", render(cmd, s, scope))]) .args([
.current_dir(&s.worktree) "-c",
&format!(
"({}) 2>&1",
render(cmd, cx.s, cx.scope).replace("{{report}}", &report)
),
])
.env("ORCH_REPORT", &report)
.current_dir(&cx.s.worktree)
.output()?; .output()?;
Ok(( let mut out = tail(&o.stdout, OUTPUT_TAIL);
o.status.success(), if step.report.as_deref() == Some("junit")
o.status.code(), && let Ok(xml) = std::fs::read_to_string(&report)
tail(&o.stdout, OUTPUT_TAIL), {
)) match crate::junit::parse(&xml) {
Ok(r) => {
cx.db.emit(
&cx.s.id,
"test",
json!({
"state": st.name, "step": step.name, "passed": r.passed, "failed": r.failed,
"skipped": r.skipped, "secs": r.secs, "failures": r.failures,
}),
)?;
}
Err(e) => out.push_str(&format!("\n[orch] junit report unreadable: {e:#}")),
}
}
Ok(StepRes {
ok: o.status.success(),
exit: o.status.code(),
out,
catch: None,
})
}
/// Instruction text for a prompt kind. The kind itself is sent too, so hx can use its own prompts.
fn instruction(kind: &str, goal: Option<&str>, t: &Task) -> String {
let lead = match kind {
"plan" => "Plan the work for this task. Report the plan with hx/plan.",
"implement" => "Implement this task, following the plan.",
_ => "Do this step of the task.",
};
let mut s = format!("{lead}\n\nTask: {}", t.name);
if !t.subtitle.is_empty() {
s.push_str(&format!(" ({})", t.subtitle));
}
if let Some(g) = goal {
s.push_str(&format!("\nGoal: {g}"));
}
s
}
/// The last failed step of this session: what a re-entered `code` state needs to know to fix it.
fn last_failure(db: &Db, id: &str) -> Result<Value> {
Ok(db
.events(Some(id), 0)?
.into_iter()
.rev()
.find(|e| e.kind == "step" && e.payload["ok"] == false)
.map_or(Value::Null, |e| {
json!({
"state": e.payload["state"], "step": e.payload["step"],
"exit": e.payload["exit"], "output": e.payload["output"],
})
}))
}
fn run_agent(cx: &mut Ctx, st: &State, step: &Step) -> Result<StepRes> {
let kind = step.prompt.as_deref().unwrap_or("implement");
if cx.agent.is_none() {
cx.agent = Some(Acp::spawn(cx.profile, Path::new(&cx.s.worktree), &cx.s.id)?);
}
let goal = cx.db.goal()?;
let context = json!({"state": st.name, "last_failure": last_failure(cx.db, &cx.s.id)?});
let mut sink = DbSink {
db: cx.db,
session: &cx.s.id,
};
let agent = cx.agent.as_mut().expect("spawned above");
let r: StepResult = agent.step(
kind,
&instruction(kind, goal.as_deref(), cx.task),
context,
json!({}),
&mut sink,
)?;
match r.status.as_str() {
"done" => Ok(StepRes {
ok: true,
exit: Some(0),
out: r.summary,
catch: None,
}),
"blocked" => Ok(StepRes {
ok: false,
exit: None,
out: r.summary,
catch: r.catch,
}),
"needs_input" => bail!(
"hx asked {:?}; needs_input needs the Needs-you queue (milestone 6)",
r.question.unwrap_or_default()
),
other => bail!("hx sent unknown step status {other:?}"),
}
}
/// Turns what hx reports into events (and decisions) of one session.
struct DbSink<'a> {
db: &'a Db,
session: &'a str,
}
impl Sink for DbSink<'_> {
fn notify(&mut self, method: &str, p: &Value) -> Result<()> {
let (kind, payload) = match method {
"hx/intent" => ("intent", p.clone()),
"hx/edit" => ("edit", p.clone()),
"hx/usage" => ("usage", p.clone()),
"hx/plan" => ("plan", p.clone()),
"hx/decision" => {
let text = p["text"].as_str().unwrap_or_default();
let state = p["state"].as_str().unwrap_or_default();
self.db.add_decision(self.session, text, state)?;
("decision", p.clone())
}
"session/update" if p["update"]["sessionUpdate"] == "tool_call" => (
"tool",
json!({"title": p["update"]["title"], "kind": p["update"]["kind"]}),
),
_ => return Ok(()), // message chunks and the like: not worth a row
};
self.db.emit(self.session, kind, payload)?;
Ok(())
}
/// Until the Needs-you queue exists (milestone 6) every permission request is denied and recorded.
fn permission(&mut self, p: &Value) -> Option<String> {
let deny = p["options"].as_array().and_then(|o| {
o.iter()
.find(|o| o["kind"].as_str().is_some_and(|k| k.starts_with("reject")))
.and_then(|o| o["optionId"].as_str().map(String::from))
});
let _ = self.db.emit(
self.session,
"permission",
json!({"tool": p["toolCall"]["title"], "decision": "denied"}),
);
deny
}
} }
/// Runs the session to the end of its machine and returns the final status (`merged`, `escalated`, `failed`, ...). /// Runs the session to the end of its machine and returns the final status (`merged`, `escalated`, `failed`, ...).
/// Resumes at `current_state` when the session was started before (orchestrator restart). /// Resumes at `current_state` when the session was started before (orchestrator restart).
pub fn run_session(db: &Db, m: &Machine, id: &str, repo: &Path, scope: &str) -> Result<String> { pub fn run_session(
db: &Db,
m: &Machine,
id: &str,
repo: &Path,
scope: &str,
profile: &Profile,
) -> Result<String> {
let s = db let s = db
.session(id)? .session(id)?
.with_context(|| format!("no session {id}"))?; .with_context(|| format!("no session {id}"))?;
let task = db
.tasks()?
.into_iter()
.find(|t| t.id == s.task_id)
.with_context(|| format!("no task {}", s.task_id))?;
ensure_worktree(repo, &s)?; ensure_worktree(repo, &s)?;
let mut cx = Ctx {
db,
s: &s,
task: &task,
profile,
scope,
agent: None,
};
let mut resumed = !s.state.is_empty(); let mut resumed = !s.state.is_empty();
let (mut cur, mut from) = if resumed { let (mut cur, mut from) = if resumed {
db.emit(id, "resume", json!({"state": s.state}))?; db.emit(id, "resume", json!({"state": s.state}))?;
@@ -167,8 +370,7 @@ pub fn run_session(db: &Db, m: &Machine, id: &str, repo: &Path, scope: &str) ->
} }
resumed = false; resumed = false;
db.set_session(id, &cur, "running")?; db.set_session(id, &cur, "running")?;
let result = run_state(db, &s, st, scope); let outcome = match run_state(&mut cx, st) {
let outcome = match result {
Ok(o) => o, Ok(o) => o,
Err(e) => return finish(db, id, &cur, "failed", Some(format!("{e:#}"))), Err(e) => return finish(db, id, &cur, "failed", Some(format!("{e:#}"))),
}; };
@@ -192,8 +394,7 @@ pub fn run_session(db: &Db, m: &Machine, id: &str, repo: &Path, scope: &str) ->
_ => match st.catch.get(&c) { _ => match st.catch.get(&c) {
Some(t) => t.clone(), Some(t) => t.clone(),
None => { None => {
let why = let why = format!("{c:?} is not a catch of state {:?}", st.name);
format!("fail_as {c:?} is not a catch of state {:?}", st.name);
return finish(db, id, &cur, "failed", Some(why)); return finish(db, id, &cur, "failed", Some(why));
} }
}, },
@@ -252,6 +453,24 @@ mod tests {
.collect() .collect()
} }
fn kinds(db: &Db, id: &str) -> Vec<String> {
db.events(Some(id), 0)
.unwrap()
.into_iter()
.map(|e| e.kind)
.collect()
}
fn plain() -> Profile {
Profile::parse("").unwrap()
}
/// Profile whose hx is the Python fake; `vars` are set through `env` (the runner clears its environment).
fn fake(vars: &str) -> Profile {
let script = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fake_acp_hx.py");
Profile::parse(&format!("hx = \"env {vars} python3 {script}\"")).unwrap()
}
const TAIL: &str = r#" const TAIL: &str = r#"
[[state]] [[state]]
name = "done" name = "done"
@@ -283,19 +502,14 @@ next = "done"
.unwrap(); .unwrap();
let s = create(&e.db, &e.dir.join("wt"), "my task", "", "m").unwrap(); let s = create(&e.db, &e.dir.join("wt"), "my task", "", "m").unwrap();
assert_eq!((s.id.as_str(), s.branch.as_str()), ("s1", "hx/s1-my-task")); assert_eq!((s.id.as_str(), s.branch.as_str()), ("s1", "hx/s1-my-task"));
let status = run_session(&e.db, &m, "s1", &e.repo, "").unwrap(); let status = run_session(&e.db, &m, "s1", &e.repo, "", &plain()).unwrap();
assert_eq!(status, "merged"); assert_eq!(status, "merged");
assert_eq!(states(&e.db, "s1"), ["a", "b", "done"]); assert_eq!(states(&e.db, "s1"), ["a", "b", "done"]);
let out = std::fs::read_to_string(e.dir.join("wt/s1/out.txt")).unwrap(); let out = std::fs::read_to_string(e.dir.join("wt/s1/out.txt")).unwrap();
assert_eq!(out.trim(), "s1 hx/s1-my-task"); assert_eq!(out.trim(), "s1 hx/s1-my-task");
let row = e.db.session("s1").unwrap().unwrap(); let row = e.db.session("s1").unwrap().unwrap();
assert_eq!((row.status.as_str(), row.pid), ("merged", None)); assert_eq!((row.status.as_str(), row.pid), ("merged", None));
assert!( assert!(kinds(&e.db, "s1").contains(&"status".to_string()));
e.db.events(Some("s1"), 0)
.unwrap()
.iter()
.any(|v| v.kind == "status")
);
let _ = std::fs::remove_dir_all(&e.dir); let _ = std::fs::remove_dir_all(&e.dir);
} }
@@ -320,7 +534,7 @@ next = "done"
.unwrap(); .unwrap();
create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap();
assert_eq!( assert_eq!(
run_session(&e.db, &m, "s1", &e.repo, "").unwrap(), run_session(&e.db, &m, "s1", &e.repo, "", &plain()).unwrap(),
"escalated" "escalated"
); );
assert_eq!( assert_eq!(
@@ -351,44 +565,211 @@ next = "done"
create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap();
// the orchestrator died while the session was in state b // the orchestrator died while the session was in state b
e.db.set_session("s1", "b", "running").unwrap(); e.db.set_session("s1", "b", "running").unwrap();
assert_eq!(run_session(&e.db, &m, "s1", &e.repo, "").unwrap(), "merged"); assert_eq!(
run_session(&e.db, &m, "s1", &e.repo, "", &plain()).unwrap(),
"merged"
);
assert!( assert!(
!e.dir.join("wt/s1/a.log").exists(), !e.dir.join("wt/s1/a.log").exists(),
"state a must not run again" "state a must not run again"
); );
assert!(e.dir.join("wt/s1/b.log").exists()); assert!(e.dir.join("wt/s1/b.log").exists());
let kinds: Vec<_> = assert_eq!(kinds(&e.db, "s1")[0], "resume");
e.db.events(Some("s1"), 0)
.unwrap()
.into_iter()
.map(|v| v.kind)
.collect();
assert_eq!(kinds[0], "resume");
let _ = std::fs::remove_dir_all(&e.dir); let _ = std::fs::remove_dir_all(&e.dir);
} }
fn one_step(step: &str) -> Machine {
Machine::parse(&format!(
"name = \"m\"\n[[state]]\nname = \"a\"\nkind = \"start\"\nsteps = [{step}]\nnext = \"done\"\n{TAIL}"
))
.unwrap()
}
fn failure_reason(e: &Env) -> String {
let end = e.db.events(Some("s1"), 0).unwrap().pop().unwrap();
end.payload["reason"].as_str().unwrap().to_string()
}
#[test] #[test]
fn agent_step_fails_the_session_cleanly() { fn junit_report_becomes_a_test_event() {
let e = env("agent"); let e = env("junit");
let m = Machine::parse(&format!( let m = Machine::parse(&format!(
r#"name = "m" r#"name = "m"
[[state]] [[state]]
name = "a" name = "test"
kind = "start" kind = "start"
steps = [{{ name = "ag", run = "agent", prompt = "plan" }}] steps = [{{ name = "t", run = "computer", 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 = "stuck" }}
next = "done" next = "done"
{TAIL}"# {TAIL}"#
)) ))
.unwrap(); .unwrap();
create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap();
assert_eq!(run_session(&e.db, &m, "s1", &e.repo, "").unwrap(), "failed"); assert_eq!(
let end = e.db.events(Some("s1"), 0).unwrap().pop().unwrap(); run_session(&e.db, &m, "s1", &e.repo, "", &plain()).unwrap(),
"escalated"
);
let ev = e.db.events(Some("s1"), 0).unwrap();
let t = ev.iter().find(|v| v.kind == "test").expect("test event");
assert_eq!(
(t.payload["passed"].as_u64(), t.payload["failed"].as_u64()),
(Some(1), Some(1))
);
assert_eq!(t.payload["failures"][0]["name"], "a::bad");
assert_eq!(t.payload["failures"][0]["location"], "src/x.rs:9");
let step = ev.iter().find(|v| v.kind == "step").unwrap();
assert!( assert!(
end.payload["reason"] step.payload["output"]
.as_str() .as_str()
.unwrap() .unwrap()
.contains("not supported") .contains("to-stdout")
); );
let _ = std::fs::remove_dir_all(&e.dir); let _ = std::fs::remove_dir_all(&e.dir);
} }
#[test]
fn human_step_fails_the_session_cleanly() {
let e = env("human");
let m = one_step(r#"{ name = "ok", run = "human" }"#);
create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap();
assert_eq!(
run_session(&e.db, &m, "s1", &e.repo, "", &plain()).unwrap(),
"failed"
);
assert!(failure_reason(&e).contains("milestone 6"));
let _ = std::fs::remove_dir_all(&e.dir);
}
#[test]
fn agent_steps_report_through_events() {
let e = env("agent");
let m = Machine::parse(&format!(
r#"name = "m"
[[state]]
name = "plan"
kind = "start"
steps = [{{ name = "draft", run = "agent", sets = "planning", prompt = "plan" }}]
next = "code"
[[state]]
name = "code"
steps = [{{ name = "edit", run = "agent", sets = "coding", prompt = "implement" }}]
next = "done"
{TAIL}"#
))
.unwrap();
e.db.set_goal("rate limit it").unwrap();
create(&e.db, &e.dir.join("wt"), "limiter", "token bucket", "m").unwrap();
let status = run_session(&e.db, &m, "s1", &e.repo, "", &fake("FAKE_MODE=ok")).unwrap();
assert_eq!(status, "merged");
let k = kinds(&e.db, "s1");
for want in [
"intent", "tool", "edit", "usage", "decision", "plan", "step",
] {
assert!(k.contains(&want.to_string()), "no {want} event in {k:?}");
}
let wt = e.dir.join("wt/s1");
assert_eq!(
std::fs::read_to_string(wt.join("steps.txt")).unwrap(),
"plan\nimplement\n"
);
assert!(wt.join("agent_implement.txt").exists());
let usage =
e.db.events(Some("s1"), 0)
.unwrap()
.into_iter()
.find(|v| v.kind == "usage")
.unwrap();
assert_eq!(usage.payload["ctx_used"], 40000);
// one decision per agent step, stored for the goal view's veto list
assert_eq!(e.db.decision_count("s1").unwrap(), 2);
let _ = std::fs::remove_dir_all(&e.dir);
}
#[test]
fn blocked_result_takes_the_named_catch_and_context_carries_the_failure() {
let e = env("blocked");
let log = e.dir.join("fake.log");
let m = Machine::parse(&format!(
r#"name = "m"
[[state]]
name = "code"
kind = "start"
steps = [{{ name = "edit", run = "agent", prompt = "implement" }}]
catch = {{ PlanInvalid = "code" }}
next = "build"
[[state]]
name = "build"
steps = [{{ name = "b", run = "computer", cmd = "echo boom-output; test $(wc -l < steps.txt) -ge 3" }}]
catch = {{ BuildFailed = "code" }}
next = "done"
{TAIL}"#
))
.unwrap();
create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap();
let p = fake(&format!("FAKE_MODE=block_once FAKE_LOG={}", log.display()));
assert_eq!(
run_session(&e.db, &m, "s1", &e.repo, "", &p).unwrap(),
"merged"
);
// code (blocked) -> code (done) -> build (fails: 2 steps) -> code (done, 3 steps) -> build ok
assert_eq!(
states(&e.db, "s1"),
["code", "code", "build", "code", "build", "done"]
);
assert_eq!(e.db.catch_count("s1", "code", "PlanInvalid").unwrap(), 1);
// the third hx/step (re-entering code after the failed build) carries the build output
let steps: Vec<Value> = std::fs::read_to_string(&log)
.unwrap()
.lines()
.map(|l| serde_json::from_str::<Value>(l).unwrap())
.filter(|m| m["method"] == "hx/step")
.collect();
assert_eq!(steps.len(), 3);
let ctx = &steps[2]["params"]["context"]["last_failure"];
assert_eq!(ctx["state"], "build");
assert!(ctx["output"].as_str().unwrap().contains("boom-output"));
let _ = std::fs::remove_dir_all(&e.dir);
}
#[test]
fn permission_requests_are_denied_and_recorded() {
let e = env("perm");
let m = one_step(r#"{ name = "ag", run = "agent", prompt = "implement" }"#);
create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap();
let p = fake("FAKE_MODE=permission");
assert_eq!(
run_session(&e.db, &m, "s1", &e.repo, "", &p).unwrap(),
"merged"
);
let answer = std::fs::read_to_string(e.dir.join("wt/s1/permission.txt")).unwrap();
assert!(answer.contains("\"optionId\": \"deny\""), "{answer}");
let ev = e.db.events(Some("s1"), 0).unwrap();
let perm = ev.iter().find(|v| v.kind == "permission").unwrap();
assert_eq!(perm.payload["tool"], "docker compose up -d redis");
let _ = std::fs::remove_dir_all(&e.dir);
}
#[test]
fn needs_input_and_a_crashing_hx_fail_the_session() {
let e = env("fail");
let m = one_step(r#"{ name = "ag", run = "agent", prompt = "implement" }"#);
create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap();
let p = fake("FAKE_MODE=needs_input");
assert_eq!(
run_session(&e.db, &m, "s1", &e.repo, "", &p).unwrap(),
"failed"
);
assert!(failure_reason(&e).contains("Which provider?"));
let e2 = env("crash");
create(&e2.db, &e2.dir.join("wt"), "t", "", "m").unwrap();
let p = fake("FAKE_MODE=crash");
assert_eq!(
run_session(&e2.db, &m, "s1", &e2.repo, "", &p).unwrap(),
"failed"
);
assert!(failure_reason(&e2).contains("hx closed its output"));
let _ = std::fs::remove_dir_all(&e.dir);
let _ = std::fs::remove_dir_all(&e2.dir);
}
} }
+406 -31
View File
@@ -1,9 +1,11 @@
//! Terminal UI. Everything on screen comes from the event table and the machine files via `view::build`. //! Terminal UI. Everything on screen comes from the event table and the machine files via `view::build`.
mod overview; mod overview;
mod session;
mod theme; mod theme;
use crate::db::{Db, Event}; use crate::db::{Db, Event};
use crate::detail::{self, Detail};
use crate::machine::Machine; use crate::machine::Machine;
use crate::view::{self, Overview}; use crate::view::{self, Overview};
use anyhow::{Result, bail}; use anyhow::{Result, bail};
@@ -24,6 +26,19 @@ pub fn run() -> Result<()> {
res 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 { struct App {
repo: PathBuf, repo: PathBuf,
/// Opened lazily: launching `orch` in a directory without a goal must not create `.hx/orch.db`. /// Opened lazily: launching `orch` in a directory without a goal must not create `.hx/orch.db`.
@@ -33,6 +48,9 @@ struct App {
overview: Overview, overview: Overview,
rev: String, rev: String,
sel: usize, sel: usize,
screen: Screen,
detail: Option<Detail>,
pager: Option<Pager>,
} }
impl App { impl App {
@@ -46,6 +64,9 @@ impl App {
overview: Overview::default(), overview: Overview::default(),
rev, rev,
sel: 0, sel: 0,
screen: Screen::Overview,
detail: None,
pager: None,
} }
} }
@@ -54,16 +75,24 @@ impl App {
if self.db.is_none() && path.exists() { if self.db.is_none() && path.exists() {
self.db = Db::open(&path).ok(); self.db = Db::open(&path).ok();
} }
if let Some(db) = &self.db if let Some(db) = &self.db {
&& let Ok(o) = snapshot( let now = crate::state::now_ms();
db, if let Ok(o) = snapshot(db, &self.repo, &mut self.events, &mut self.machines, now) {
&self.repo, self.overview = o;
&mut self.events, }
&mut self.machines, self.detail = match &self.screen {
crate::state::now_ms(), Screen::Session(id) => session_detail(
) db,
{ &self.repo,
self.overview = o; &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)); 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. /// Everything read from the database for one screen update, plus the loaded machine files.
fn snapshot( 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, db: &Db,
repo: &Path, repo: &Path,
events: &mut Vec<Event>, events: &mut Vec<Event>,
machines: &mut HashMap<String, Machine>, machines: &mut HashMap<String, Machine>,
now_ms: u64, ) -> Result<Loaded> {
) -> Result<Overview> {
let last = events.last().map_or(0, |e| e.id); let last = events.last().map_or(0, |e| e.id);
events.extend(db.events(None, last)?); events.extend(db.events(None, last)?);
let (tasks, sessions) = (db.tasks()?, db.sessions()?); let (tasks, sessions) = (db.tasks()?, db.sessions()?);
@@ -101,17 +136,53 @@ fn snapshot(
machines.insert(t.machine.clone(), m); 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 { Ok(view::build(&view::Input {
goal: goal.as_deref(), goal: l.goal.as_deref(),
tasks: &tasks, tasks: &l.tasks,
sessions: &sessions, sessions: &l.sessions,
events, events,
machines, machines,
now_ms, 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 { fn git_rev(repo: &Path) -> String {
let git = |a: &[&str]| crate::run::git(repo, a).map(|s| s.trim().to_string()); let git = |a: &[&str]| crate::run::git(repo, a).map(|s| s.trim().to_string());
match ( 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<()> { 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(); app.refresh();
loop { loop {
let header = app.header(); 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))? { if !event::poll(Duration::from_millis(250))? {
app.refresh(); app.refresh();
continue; continue;
@@ -136,16 +411,8 @@ fn event_loop(term: &mut ratatui::DefaultTerminal, app: &mut App) -> Result<()>
let Event::Key(k) = event::read()? else { let Event::Key(k) = event::read()? else {
continue; continue;
}; };
if k.kind != KeyEventKind::Press { if k.kind == KeyEventKind::Press && on_key(app, term, k)? {
continue; return Ok(());
}
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),
_ => {}
} }
} }
} }
@@ -353,7 +620,8 @@ mod tests {
db.set_goal("ship the thing").unwrap(); db.set_goal("ship the thing").unwrap();
let s = crate::runner::create(&db, &dir.join("wt"), "demo", "", "m").unwrap(); let s = crate::runner::create(&db, &dir.join("wt"), "demo", "", "m").unwrap();
let m = Machine::find("m", &repo).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 (mut events, mut machines) = (vec![], HashMap::new());
let o = snapshot( let o = snapshot(
@@ -383,4 +651,111 @@ mod tests {
assert_eq!(events.len(), n); assert_eq!(events.len(), n);
let _ = std::fs::remove_dir_all(&dir); 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);
}
} }
+466
View File
@@ -0,0 +1,466 @@
//! 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;
let [test, now, files, budget] = Layout::vertical([
Constraint::Length(test_h),
Constraint::Length(4),
Constraint::Length(files_h),
Constraint::Min(6),
])
.areas(right);
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(), keys);
}
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<Span<'static>>, parts: Vec<Span<'static>>, 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<Line> = 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<Line> = 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))),
])
}
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)),
]),
});
lines.push(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(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() -> Line<'static> {
let mut v = vec![Span::raw(" ")];
for (key, what) in [
("esc", "back"),
("t", "full test output"),
("d", "diff"),
("l", "agent transcript"),
("o", "open worktree in hx"),
] {
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)
}
+14
View File
@@ -344,6 +344,7 @@ fn describe(e: &Event) -> String {
"resume" => "resumed".into(), "resume" => "resumed".into(),
"status" => str_of(p, "label"), "status" => str_of(p, "label"),
"intent" => str_of(p, "text"), "intent" => str_of(p, "text"),
"tool" => str_of(p, "title"),
k => k.to_string(), k => k.to_string(),
} }
} }
@@ -375,6 +376,19 @@ fn line_text(e: &Event) -> String {
"status" => format!("■ {}", str_of(p, "label")), "status" => format!("■ {}", str_of(p, "label")),
"resume" => format!("resumed in {}", str_of(p, "state")), "resume" => format!("resumed in {}", str_of(p, "state")),
"edit" => format!("{} +{} −{}", str_of(p, "path"), p["added"], p["removed"]), "edit" => format!("{} +{} −{}", str_of(p, "path"), p["added"], p["removed"]),
"tool" => str_of(p, "title"),
"permission" => format!(
"permission {}: {}",
str_of(p, "decision"),
str_of(p, "tool")
),
"plan" => {
let steps = p["steps"].as_array().map_or(0, Vec::len);
format!(
"{steps} steps, {} files",
p["files"].as_array().map_or(0, Vec::len)
)
}
_ => p["text"] _ => p["text"]
.as_str() .as_str()
.map_or_else(|| e.kind.clone(), String::from), .map_or_else(|| e.kind.clone(), String::from),
+93
View File
@@ -0,0 +1,93 @@
"""Fake `hx serve --acp --cwd DIR --session ID`: newline-delimited JSON-RPC 2.0 on stdio.
Behaviour per `hx/step`, chosen with FAKE_MODE (orch passes FAKE_* through the profile's `env`):
ok intent, tool call, edit, usage, decision, plan, then step_result done (default)
blocked step_result blocked, catch FAKE_CATCH (default PlanInvalid)
block_once blocked the first time (marker file .fake_blocked in cwd), done afterwards
needs_input step_result needs_input with a question
permission asks session/request_permission first and records the answer in permission.txt
crash exits without a step_result
Every received message is appended to FAKE_LOG when set. Each step also appends its prompt kind to steps.txt.
"""
import json
import os
import sys
args = sys.argv[1:]
cwd = args[args.index("--cwd") + 1] if "--cwd" in args else os.getcwd()
session = args[args.index("--session") + 1] if "--session" in args else "sess-1"
mode = os.environ.get("FAKE_MODE", "ok")
log = os.environ.get("FAKE_LOG")
def send(o):
sys.stdout.write(json.dumps({"jsonrpc": "2.0", **o}) + "\n")
sys.stdout.flush()
def note(method, params):
send({"method": method, "params": params})
def recv():
line = sys.stdin.readline()
if not line:
sys.exit(0)
m = json.loads(line)
if log:
with open(log, "a") as f:
f.write(json.dumps(m) + "\n")
return m
def step(params):
kind = params["prompt"]
with open(os.path.join(cwd, "steps.txt"), "a") as f:
f.write(kind + "\n")
if mode == "crash":
sys.exit(3)
note("hx/intent", {"text": f"working on {kind}"})
note("session/update", {"sessionId": session, "update": {"sessionUpdate": "tool_call", "toolCallId": "t1", "title": "edit src/lib.rs", "kind": "edit", "status": "in_progress"}})
if mode == "permission":
send({"id": 900, "method": "session/request_permission", "params": {
"sessionId": session,
"toolCall": {"toolCallId": "t2", "title": "docker compose up -d redis"},
"options": [{"optionId": "allow", "name": "Allow once", "kind": "allow_once"}, {"optionId": "deny", "name": "Deny", "kind": "reject_once"}]}})
while True:
m = recv()
if m.get("id") == 900:
with open(os.path.join(cwd, "permission.txt"), "w") as f:
f.write(json.dumps(m["result"]))
break
if mode == "needs_input":
note("hx/step_result", {"status": "needs_input", "question": "Which provider?"})
return
blocked = mode == "blocked"
if mode == "block_once" and not os.path.exists(os.path.join(cwd, ".fake_blocked")):
open(os.path.join(cwd, ".fake_blocked"), "w").close()
blocked = True
if blocked:
note("hx/step_result", {"status": "blocked", "catch": os.environ.get("FAKE_CATCH", "PlanInvalid"), "summary": "cannot continue"})
return
with open(os.path.join(cwd, f"agent_{kind}.txt"), "a") as f:
f.write("work\n")
note("hx/edit", {"path": f"agent_{kind}.txt", "added": 4, "removed": 1})
note("hx/usage", {"ctx_used": 40000, "ctx_limit": 200000, "cost": 0.25})
note("hx/decision", {"text": "token bucket over sliding window", "state": kind, "at": 1})
if kind == "plan":
note("hx/plan", {"steps": ["write the limiter", "add tests"], "files": ["src/limiter.rs"]})
note("hx/step_result", {"status": "done", "summary": f"{kind} finished"})
while True:
m = recv()
method, mid = m.get("method"), m.get("id")
if method == "initialize":
send({"id": mid, "result": {"protocolVersion": 1, "agentCapabilities": {}}})
elif method == "session/new":
send({"id": mid, "result": {"sessionId": session}})
elif method == "hx/step":
send({"id": mid, "result": {}}) # ack; the outcome comes as hx/step_result
step(m["params"])
elif mid is not None:
send({"id": mid, "error": {"code": -32601, "message": "unknown method"}})