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

+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();
}
}