From bf609c2e0e5084647f4b723e32528b6f58fe3b89 Mon Sep 17 00:00:00 2001 From: Johannes Kresner Date: Sat, 14 Nov 2026 12:55:28 +0100 Subject: [PATCH] Add loop detector, budgets, and live session control MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Milestone 8: the loop detector alerts when test failures repeat, budget caps limit context/cost/wall-time per session with compaction support, and live control lets you interrupt, message, or kill a running session from the TUI. Decisions can now be vetoed, which sends hx/message and rewinds the session to code. All 82 tests pass. - src/budget.rs: pure functions for active time, budgets and loop detect - src/runner.rs: Ctl control object polls for commands ~100ms, handles interrupt/message/abort/stop at every blocking point, re-runs on hints, and compacts when context is high - src/db.rs: commands table for TUI→runner control - src/detail.rs, src/goal.rs, src/tui/: loop detector box, budget caps, session keys (i/m/s/k/r), goal keys (v for veto), state forcing - tests/fake_acp_hx.py: slow mode and hx/message, hx/compact log - examples/machines/task.toml: [budget] with wall_secs, cost, compact_at Co-Authored-By: Claude Haiku 4.5 --- README.md | 14 + examples/machines/task.toml | 5 + src/acp.rs | 50 ++- src/budget.rs | 292 ++++++++++++++ src/db.rs | 63 +++ src/detail.rs | 43 +- src/goal.rs | 3 + src/machine.rs | 37 ++ src/main.rs | 1 + src/runner.rs | 763 ++++++++++++++++++++++++++++++++++-- src/tui/goal.rs | 26 +- src/tui/mod.rs | 312 ++++++++++++++- src/tui/overview.rs | 3 + src/tui/session.rs | 108 ++++- src/view.rs | 7 + tests/fake_acp_hx.py | 22 ++ 16 files changed, 1694 insertions(+), 55 deletions(-) create mode 100644 src/budget.rs diff --git a/README.md b/README.md index 3f5ca5c..eca8f84 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,20 @@ Machines are TOML files in `.hx/machines/` or `~/.hx/machines/` (examples in `ex 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. +A running session can be steered from the session screen, also when `orch session` runs in another terminal: `i` +interrupt (the agent stops, you reply with a hint), `m` message to the agent, `s` force a state, `k` kill (type +`yes`; goes to `on_abort`), and `r` re-plan from the start state while the loop detector box shows (the last test +runs failed on the same tests). On the goal screen `j/k` selects a decision and `v` vetoes it: the agent is told and +the session goes back to `code`. The commands go through the database (`commands` table) and the runner picks them +up within a fraction of a second, even in the middle of a shell command. A machine can set limits: + + [budget] + wall_secs = 5400 # time spent working, waiting for you does not count + cost = 5.0 # US dollars + compact_at = 85 # percent of the context window; hx gets `hx/compact` + +Passing wall time or cost sends the session to `on_budget` (or fails it when the machine has none). + The goal lives in the same database: `orch goal "sentence"`, `orch check NAME CMD [--owner sN]` (an acceptance check: pass = exit 0), `orch checks [--owner sN | --main]`. `g` in the TUI opens the goal view (task graph, critical path, decisions, checks; `e` edit goal, `+` add check, `R` run all checks on main). `orch session --after s1,s2` makes diff --git a/examples/machines/task.toml b/examples/machines/task.toml index fae300c..d5b6762 100644 --- a/examples/machines/task.toml +++ b/examples/machines/task.toml @@ -2,6 +2,11 @@ name = "task" on_abort = "aborted" on_budget = "escalated" +[budget] +wall_secs = 5400 # 90 min of work, not counting time spent waiting for you +cost = 5.0 # US dollars +compact_at = 85 # percent of the context window + [[state]] name = "plan" kind = "start" diff --git a/src/acp.rs b/src/acp.rs index b52cec4..7a27365 100644 --- a/src/acp.rs +++ b/src/acp.rs @@ -12,6 +12,7 @@ use std::os::unix::process::CommandExt; use std::path::Path; use std::process::{Child, ChildStdin, Command, Stdio}; use std::sync::mpsc; +use std::time::{Duration, Instant}; /// Receives what hx reports while a step runs. pub trait Sink { @@ -19,8 +20,25 @@ pub trait Sink { 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; + /// Called about every 100 ms while a step runs: what the user or the budgets want hx to be told. + fn poll(&mut self) -> Poll { + Poll::default() + } } +/// What to send to a running step. +#[derive(Default, Debug, PartialEq)] +pub struct Poll { + /// User hints, sent as `hx/message`. + pub messages: Vec, + /// `hx/interrupt`: finish the current tool call, then stop (the step result still arrives). + pub interrupt: bool, + /// `hx/compact`: compact the context now. + pub compact: bool, +} + +const POLL_EVERY: Duration = Duration::from_millis(100); + #[derive(Debug, PartialEq)] pub struct StepResult { /// done | blocked | needs_input @@ -175,8 +193,34 @@ impl Acp { "context": context, "limits": limits, }}), )?; + let mut last_poll = Instant::now(); + let mut interrupted = false; loop { - let m = self.recv()?; + // poll on a timer, also while hx streams without a pause (a recv timeout alone would starve it) + if last_poll.elapsed() >= POLL_EVERY { + last_poll = Instant::now(); + let p = sink.poll(); + for text in p.messages { + self.notify( + "hx/message", + json!({"sessionId": self.session, "text": text}), + )?; + } + if p.interrupt && !interrupted { + interrupted = true; + self.notify("hx/interrupt", json!({"sessionId": self.session}))?; + } + if p.compact { + self.notify("hx/compact", json!({"sessionId": self.session}))?; + } + } + let m = match self.rx.recv_timeout(POLL_EVERY) { + Ok(m) => m, + Err(mpsc::RecvTimeoutError::Timeout) => continue, + Err(mpsc::RecvTimeoutError::Disconnected) => { + bail!("hx closed its output (exited or crashed)") + } + }; if m.get("method").is_none() && m["id"] == json!(id) { if let Some(e) = m.get("error") { bail!( @@ -191,6 +235,10 @@ impl Acp { } } } + + fn notify(&mut self, method: &str, params: Value) -> Result<()> { + self.send(json!({"jsonrpc": "2.0", "method": method, "params": params})) + } } impl Drop for Acp { diff --git a/src/budget.rs b/src/budget.rs new file mode 100644 index 0000000..bed76ee --- /dev/null +++ b/src/budget.rs @@ -0,0 +1,292 @@ +//! Budgets and the loop detector (ORCHESTRATOR.md section 4), as pure functions over a session's events. +//! The runner uses them to stop a session; the session screen uses them to show how close it is. + +use crate::db::Event; +use crate::machine::BudgetCfg; +use std::collections::{BTreeSet, HashMap}; + +/// Seconds the session spent working: from its first event to its end (or now), minus the time it sat in the +/// Needs-you queue. Waiting for you must not eat the wall-time budget. +pub fn active_secs(evs: &[&Event], now_ms: u64) -> u64 { + // work starts with the first state; time blocked on dependencies before that is not work + let Some(first) = evs.iter().find(|e| e.kind == "state") else { + return 0; + }; + let end = match evs.last() { + Some(e) if e.kind == "end" => e.at, + _ => now_ms, + }; + let mut open: HashMap = HashMap::new(); // need id -> when it was put in the queue + let mut waited = 0; + for e in evs { + let id = e.payload["id"].as_i64().unwrap_or(-1); + match e.kind.as_str() { + "need" => { + open.insert(id, e.at); + } + "answer" => { + if let Some(at) = open.remove(&id) { + waited += e.at.saturating_sub(at); + } + } + _ => {} + } + } + waited += open.values().map(|at| end.saturating_sub(*at)).sum::(); + end.saturating_sub(first.at).saturating_sub(waited) / 1000 +} + +/// Cost so far: the last `usage` event carries the running total. +pub fn cost(evs: &[&Event]) -> f64 { + evs.iter() + .rev() + .find(|e| e.kind == "usage") + .and_then(|e| e.payload["cost"].as_f64()) + .unwrap_or(0.0) +} + +/// Context window use in percent, from the last `usage` event. +pub fn ctx_pct(evs: &[&Event]) -> Option { + let e = evs.iter().rev().find(|e| e.kind == "usage")?; + let (used, limit) = ( + e.payload["ctx_used"].as_u64()?, + e.payload["ctx_limit"].as_u64()?, + ); + Some((used * 100).checked_div(limit)?.min(100) as u8) +} + +#[derive(Debug, PartialEq)] +pub struct Exceeded { + pub what: &'static str, + pub used: String, + pub limit: String, +} + +pub fn exceeded(evs: &[&Event], cfg: &BudgetCfg, now_ms: u64) -> Option { + if let Some(limit) = cfg.wall_secs { + let used = active_secs(evs, now_ms); + if used > limit { + return Some(Exceeded { + what: "wall time", + used: format!("{}m", used / 60), + limit: format!("{}m", limit / 60), + }); + } + } + if let Some(limit) = cfg.cost { + let used = cost(evs); + if used > limit { + return Some(Exceeded { + what: "cost", + used: format!("${used:.2}"), + limit: format!("${limit:.2}"), + }); + } + } + None +} + +#[derive(Debug, PartialEq)] +pub struct LoopInfo { + /// Test runs in a row that failed on exactly the same tests. + pub runs: usize, + /// How many tests that is. + pub tests: usize, + /// The file the agent edited most since the loop began. + pub file: Option, +} + +fn failing(e: &Event) -> BTreeSet { + e.payload["failures"] + .as_array() + .into_iter() + .flatten() + .filter_map(|f| f["name"].as_str().map(String::from)) + .collect() +} + +/// After a failed test run: do the last runs fail on the same set of tests? Two in a row is a loop (the agent +/// tried a fix and got the same failures), a run that passes or fails differently ends it. +pub fn looping(evs: &[&Event]) -> Option { + let runs: Vec<&&Event> = evs.iter().filter(|e| e.kind == "test").collect(); + let last = failing(runs.last()?); + if last.is_empty() { + return None; + } + let n = runs.iter().rev().take_while(|r| failing(r) == last).count(); + if n < 2 { + return None; + } + let since = runs[runs.len() - n].id; + let mut edits: HashMap<&str, u64> = HashMap::new(); + for e in evs.iter().filter(|e| e.kind == "edit" && e.id > since) { + let touched = + e.payload["added"].as_u64().unwrap_or(0) + e.payload["removed"].as_u64().unwrap_or(0); + *edits + .entry(e.payload["path"].as_str().unwrap_or_default()) + .or_default() += touched.max(1); + } + let file = edits + .into_iter() + .max_by(|a, b| a.1.cmp(&b.1).then(b.0.cmp(a.0))) + .map(|(p, _)| p.to_string()); + Some(LoopInfo { + runs: n, + tests: last.len(), + file, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn ev(id: i64, at: u64, kind: &str, payload: serde_json::Value) -> Event { + Event { + id, + session: "s1".into(), + at, + kind: kind.into(), + payload, + } + } + + fn refs(v: &[Event]) -> Vec<&Event> { + v.iter().collect() + } + + fn test_run(id: i64, names: &[&str]) -> Event { + let f: Vec<_> = names.iter().map(|n| json!({"name": n})).collect(); + ev( + id, + id as u64 * 1000, + "test", + json!({"passed": 3, "failed": names.len(), "failures": f}), + ) + } + + #[test] + fn time_in_the_queue_does_not_count_as_work() { + let evs = [ + ev(1, 0, "state", json!({})), + ev(2, 60_000, "need", json!({"id": 5})), + ev(3, 660_000, "answer", json!({"id": 5})), // waited ten minutes + ev(4, 720_000, "step", json!({})), + ]; + assert_eq!(active_secs(&refs(&evs), 720_000), 120); + // still waiting: the open item counts as waiting until now + assert_eq!(active_secs(&refs(&evs[..2]), 3_600_000), 60); + // a finished session stops at its end, not at now + let done = [ + ev(1, 0, "state", json!({})), + ev(2, 30_000, "end", json!({})), + ]; + assert_eq!(active_secs(&refs(&done), 9_999_999), 30); + assert_eq!(active_secs(&[], 5), 0); + } + + #[test] + fn limits_trip_on_time_and_cost() { + let evs = [ + ev(1, 0, "state", json!({})), + ev( + 2, + 10_000, + "usage", + json!({"cost": 5.25, "ctx_used": 142, "ctx_limit": 200}), + ), + ]; + let r = refs(&evs); + assert_eq!(cost(&r), 5.25); + assert_eq!(ctx_pct(&r), Some(71)); + let none = BudgetCfg::default(); + assert_eq!( + exceeded(&r, &none, 999_999_999), + None, + "no limits, no budget stop" + ); + let cost_cap = BudgetCfg { + cost: Some(5.0), + ..none.clone() + }; + assert_eq!( + exceeded(&r, &cost_cap, 0), + Some(Exceeded { + what: "cost", + used: "$5.25".into(), + limit: "$5.00".into() + }) + ); + let wall = BudgetCfg { + wall_secs: Some(60), + ..none + }; + assert_eq!(exceeded(&r, &wall, 30_000), None); + let e = exceeded(&r, &wall, 600_000).unwrap(); + assert_eq!( + (e.what, e.used.as_str(), e.limit.as_str()), + ("wall time", "10m", "1m") + ); + } + + #[test] + fn same_failing_tests_twice_is_a_loop() { + let evs = [ + ev( + 0, + 0, + "edit", + json!({"path": "src/old.rs", "added": 50, "removed": 0}), + ), // before the first of the identical runs: not part of the loop + test_run(1, &["a::x", "a::y"]), + test_run(3, &["a::y", "a::x"]), + ev( + 4, + 4000, + "edit", + json!({"path": "src/token.rs", "added": 6, "removed": 2}), + ), + ev( + 5, + 5000, + "edit", + json!({"path": "src/token.rs", "added": 1, "removed": 1}), + ), + ev( + 6, + 6000, + "edit", + json!({"path": "src/mod.rs", "added": 1, "removed": 0}), + ), + test_run(7, &["a::x", "a::y"]), + ]; + let l = looping(&refs(&evs)).expect("loop"); + assert_eq!((l.runs, l.tests), (3, 2)); + assert_eq!( + l.file.as_deref(), + Some("src/token.rs"), + "edits before the loop do not count" + ); + } + + #[test] + fn different_or_fixed_failures_are_no_loop() { + // fix 1 changed which tests fail: progress, not a loop + let evs = [test_run(1, &["a::x", "a::y"]), test_run(2, &["a::x"])]; + assert_eq!(looping(&refs(&evs)), None); + // the last run passed + let evs = [ + test_run(1, &["a::x"]), + test_run(2, &["a::x"]), + test_run(3, &[]), + ]; + assert_eq!(looping(&refs(&evs)), None); + // only one run so far + assert_eq!(looping(&refs(&[test_run(1, &["a::x"])])), None); + assert_eq!(looping(&[]), None); + // a loop without edits has no file to blame + let evs = [test_run(1, &["a::x"]), test_run(2, &["a::x"])]; + assert_eq!(looping(&refs(&evs)).unwrap().file, None); + } +} diff --git a/src/db.rs b/src/db.rs index c4b2d2d..639eac7 100644 --- a/src/db.rs +++ b/src/db.rs @@ -26,6 +26,9 @@ create index if not exists events_session on events(session_id, id); create table if not exists decisions( session_id text not null, text text not null, state text not null, at integer not null, vetoed integer not null default 0); +create table if not exists commands( + id integer primary key autoincrement, session_id text not null, kind text not null, + payload text not null default '{}', at integer not null, done integer not null default 0); create table if not exists merge_queue( ticket integer primary key autoincrement, session_id text not null unique); create table if not exists needs( @@ -223,6 +226,48 @@ impl Db { Ok(()) } + /// A command for a running session (`message`, `interrupt`, `goto`, `abort`, `veto`). The runner, which may be + /// another process, picks it up the next time it polls. + pub fn add_command(&self, session: &str, kind: &str, payload: &Value) -> Result { + self.conn.execute( + "insert into commands(session_id, kind, payload, at) values (?1, ?2, ?3, ?4)", + params![ + session, + kind, + payload.to_string(), + crate::state::now_ms() as i64 + ], + )?; + Ok(self.conn.last_insert_rowid()) + } + + /// Takes the session's unprocessed commands, oldest first, and marks them processed. + pub fn take_commands(&self, session: &str) -> Result> { + let mut q = self.conn.prepare( + "select id, kind, payload from commands where session_id = ?1 and done = 0 order by id", + )?; + let rows: Vec<(i64, String, String)> = q + .query_map([session], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))? + .collect::>()?; + for (id, ..) in &rows { + self.conn + .execute("update commands set done = 1 where id = ?1", [id])?; + } + Ok(rows + .into_iter() + .map(|(_, k, p)| (k, serde_json::from_str(&p).unwrap_or(Value::Null))) + .collect()) + } + + /// Marks a decision as vetoed; false if it does not exist or was already vetoed. + pub fn veto_decision(&self, id: i64) -> Result { + let n = self.conn.execute( + "update decisions set vetoed = 1 where rowid = ?1 and vetoed = 0", + [id], + )?; + Ok(n == 1) + } + pub fn set_goal(&self, text: &str) -> Result<()> { self.conn.execute("delete from goal", [])?; self.conn.execute( @@ -540,6 +585,24 @@ mod tests { db.queue_leave("s1").unwrap(); assert_eq!(db.queue_head().unwrap().as_deref(), Some("s2")); db.queue_leave("s2").unwrap(); + // commands: taken once, in order, per session + db.add_command("s1", "message", &json!({"text": "hi"})) + .unwrap(); + db.add_command("s1", "interrupt", &json!({})).unwrap(); + db.add_command("s2", "abort", &json!({})).unwrap(); + let cmds = db.take_commands("s1").unwrap(); + assert_eq!( + cmds.iter().map(|c| c.0.as_str()).collect::>(), + ["message", "interrupt"] + ); + assert_eq!(cmds[0].1["text"], "hi"); + assert!(db.take_commands("s1").unwrap().is_empty()); + assert_eq!(db.take_commands("s2").unwrap().len(), 1); + // a decision can be vetoed once + let d = db.decisions().unwrap()[0].id; + assert!(db.veto_decision(d).unwrap()); + assert!(!db.veto_decision(d).unwrap()); + assert!(db.decisions().unwrap()[0].vetoed); // needs queue: pending until answered, the first answer wins, finished items disappear let n = db .add_need("s1", "review", &json!({"key": "review/ok", "title": "t"})) diff --git a/src/detail.rs b/src/detail.rs index ffef640..287a3ca 100644 --- a/src/detail.rs +++ b/src/detail.rs @@ -2,6 +2,7 @@ //! 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::budget; use crate::db::Event; use crate::machine::{Kind, RunOn}; use crate::view::{Input, Status}; @@ -88,8 +89,22 @@ pub struct Budget { pub ctx: Option<(u64, u64)>, /// (fix count, max) of the busiest retry loop. pub retries: Option<(u32, u32)>, + /// Time spent working, not counting time waiting for the user. pub wall_secs: u64, pub cost: f64, + /// Limits from the machine's `[budget]`; None = no cap. + pub wall_cap: Option, + pub cost_cap: Option, + pub compact_at: Option, +} + +/// The loop detector fired: the last test runs failed on the same tests. +#[derive(Clone, PartialEq, Debug)] +pub struct LoopView { + pub runs: usize, + pub tests: usize, + /// The file the agent keeps editing. + pub file: Option, } #[derive(Clone, PartialEq, Debug)] @@ -109,6 +124,11 @@ pub struct Detail { pub now: Now, pub files: Vec, pub budget: Budget, + pub looping: Option, + /// Every state of the machine, for the force-state key. + pub states: Vec, + /// The start state, where `re-plan` goes. + pub start: String, } /// `6.2s`, `0m59s`, `4m10s`. @@ -181,7 +201,6 @@ pub fn build(i: &Input, id: &str) -> Option { 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| { @@ -462,10 +481,21 @@ pub fn build(i: &Input, id: &str) -> Option { ) }), 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), + wall_secs: budget::active_secs(&evs, i.now_ms), + cost: budget::cost(&evs), + wall_cap: machine.budget.wall_secs, + cost_cap: machine.budget.cost, + compact_at: machine.budget.compact_at, + }; + // a loop only matters while the session still runs + let looping = if active { + budget::looping(&evs).map(|l| LoopView { + runs: l.runs, + tests: l.tests, + file: l.file, + }) + } else { + None }; Some(Detail { @@ -484,6 +514,9 @@ pub fn build(i: &Input, id: &str) -> Option { now, files, budget, + looping, + states: machine.states.iter().map(|s| s.name.clone()).collect(), + start: machine.start().name.clone(), }) } diff --git a/src/goal.rs b/src/goal.rs index 3c7169f..cad6694 100644 --- a/src/goal.rs +++ b/src/goal.rs @@ -25,6 +25,8 @@ pub struct DecisionView { pub id: i64, pub session: String, pub text: String, + /// The state the decision was made in. + pub state: String, /// `plan · 13:22` pub whence: String, pub vetoed: bool, @@ -156,6 +158,7 @@ pub fn build(i: &Input) -> GoalView { id: d.id, session: d.session.clone(), text: d.text.clone(), + state: d.state.clone(), whence: format!("{} · {}", d.state, &hms(d.at)[..5]), vetoed: d.vetoed, }) diff --git a/src/machine.rs b/src/machine.rs index 5f588ea..65b0259 100644 --- a/src/machine.rs +++ b/src/machine.rs @@ -70,12 +70,26 @@ pub struct State { pub only_on: Vec, } +/// Per-session limits. Exceeding `wall_secs` (time spent working, not waiting for the user) or `cost` emits a +/// `budget` event and sends the session to `on_budget`. Past `compact_at` percent of the context window hx is +/// told to compact. The retry limit is the `retry` table of the state that loops. +#[derive(Deserialize, Clone, Debug, Default, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct BudgetCfg { + pub wall_secs: Option, + /// US dollars. + pub cost: Option, + pub compact_at: Option, +} + #[derive(Deserialize, Clone, Debug)] #[serde(deny_unknown_fields)] pub struct Machine { pub name: String, pub on_abort: Option, pub on_budget: Option, + #[serde(default)] + pub budget: BudgetCfg, #[serde(rename = "state")] pub states: Vec, } @@ -138,6 +152,12 @@ impl Machine { ); Ok(()) }; + if let Some(c) = self.budget.compact_at { + ensure!( + (1..=100).contains(&c), + "budget.compact_at is a percent, 1 to 100" + ); + } for (what, to) in [("on_abort", &self.on_abort), ("on_budget", &self.on_budget)] { if let Some(to) = to { target("", what, to)?; @@ -262,6 +282,15 @@ mod tests { fn task_machine_details() { let m = example("task"); assert_eq!(m.start().name, "plan"); + assert_eq!( + m.budget, + BudgetCfg { + wall_secs: Some(5400), + cost: Some(5.0), + compact_at: Some(85) + } + ); + assert_eq!(example("docs").budget, BudgetCfg::default()); let t = m.state("test").unwrap(); assert_eq!(t.catch.keys().next().unwrap(), "TestsFailed"); assert_eq!(t.retry["TestsFailed"].max, 3); @@ -293,6 +322,14 @@ end = "done" #[test] fn rejects_bad_machines() { + assert!( + err(&OK.replace("name = \"m\"", "name = \"m\"\n[budget]\ncompact_at = 0")) + .contains("percent") + ); + assert!( + err(&OK.replace("name = \"m\"", "name = \"m\"\n[budget]\nbogus = 1")) + .contains("unknown field") + ); assert!(err(&OK.replace("kind = \"start\"", "")).contains("exactly one start")); assert!( err(&OK.replace("kind = \"exit\"", "kind = \"start\"")).contains("exactly one start") diff --git a/src/main.rs b/src/main.rs index cd409fb..8e44e96 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,6 @@ mod acp; mod adapter; +mod budget; mod checks; mod db; mod detail; diff --git a/src/runner.rs b/src/runner.rs index 887a262..6e76e40 100644 --- a/src/runner.rs +++ b/src/runner.rs @@ -4,15 +4,19 @@ //! turn in the merge queue before it enters the state that ends in `merged`; after the merge all acceptance //! checks run again on main. -use crate::acp::{Acp, Sink, StepResult}; -use crate::db::{Db, Session, Task}; -use crate::machine::{Kind, Machine, RunOn, State, Step}; +use crate::acp::{Acp, Poll, Sink, StepResult}; +use crate::budget; +use crate::db::{Db, Event, Session, Task}; +use crate::machine::{BudgetCfg, Kind, Machine, RunOn, State, Step}; use crate::profile::Profile; use crate::run::{git, tail}; use anyhow::{Context, Result, bail}; use serde_json::{Value, json}; +use std::cell::{Cell, RefCell}; +use std::io::Read; +use std::os::unix::process::CommandExt; use std::path::Path; -use std::process::Command; +use std::process::{Command, Stdio}; use std::time::{Duration, Instant}; /// Safety cap against catch loops that have no `retry` limit (e.g. build -> code -> build with a no-op code). @@ -99,6 +103,222 @@ fn ensure_worktree(repo: &Path, s: &Session) -> Result<()> { Ok(()) } +/// Why the runner leaves what it is doing (a command from the user, or a budget). +#[derive(Clone, Debug, PartialEq)] +enum Stop { + /// Abandon the current step and continue in this state. + Goto { state: String, why: String }, + /// End the session. + End { + status: &'static str, + reason: String, + }, +} + +/// Error that unwinds a blocked wait (command, agent step, Needs-you item, queue) because a [`Stop`] is pending. +#[derive(Debug)] +struct Stopped; + +impl std::fmt::Display for Stopped { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("stopped") + } +} + +impl std::error::Error for Stopped {} + +/// Live control of a running session. Everything that blocks calls [`Ctl::poll`] while it waits, so a command +/// written to the database by the TUI (another process) takes effect within a fraction of a second. +struct Ctl<'a> { + db: &'a Db, + id: String, + cfg: BudgetCfg, + on_abort: Option, + on_budget: Option, + states: Vec, + start: String, + stop: RefCell>, + /// The user pressed interrupt (without asking to go anywhere). + interrupted: Cell, + /// In the state that handles a budget stop or an abort: budgets no longer apply there. + exempt: Cell, + last_budget: Cell, + last_compact: Cell, + compacted: Cell, +} + +impl<'a> Ctl<'a> { + fn new(db: &'a Db, id: &str, m: &Machine) -> Self { + let long_ago = Instant::now() - Duration::from_secs(60); + Self { + db, + id: id.to_string(), + cfg: m.budget.clone(), + on_abort: m.on_abort.clone(), + on_budget: m.on_budget.clone(), + states: m.states.iter().map(|s| s.name.clone()).collect(), + start: m.start().name.clone(), + stop: RefCell::new(None), + interrupted: Cell::new(false), + exempt: Cell::new(false), + last_budget: Cell::new(long_ago), + last_compact: Cell::new(long_ago), + compacted: Cell::new(false), + } + } + + fn enter_state(&self, name: &str) { + let n = Some(name); + self.exempt + .set(n == self.on_abort.as_deref() || n == self.on_budget.as_deref()); + } + + fn has_state(&self, s: &str) -> bool { + self.states.iter().any(|x| x == s) + } + + fn set_stop(&self, s: Stop) { + let mut st = self.stop.borrow_mut(); + if st.is_none() { + *st = Some(s); // the first one wins + } + } + + fn stopped(&self) -> bool { + self.stop.borrow().is_some() + } + + fn take_stop(&self) -> Option { + self.stop.borrow_mut().take() + } + + fn take_interrupt(&self) -> bool { + self.interrupted.replace(false) + } + + /// Reads new commands and checks the budgets. Messages become `hint` events (the next agent step gets them + /// as context) and are returned so a running step can be told right away. + fn poll(&self) -> Result { + let mut p = Poll::default(); + for (kind, pl) in self.db.take_commands(&self.id)? { + let text = pl["text"].as_str().unwrap_or_default().to_string(); + let target = pl["state"].as_str().unwrap_or_default(); + let fail = |what: String| { + self.db.emit( + &self.id, + "command_failed", + json!({"kind": kind, "error": what}), + ) + }; + match kind.as_str() { + "message" => { + self.db.emit(&self.id, "hint", json!({"text": text}))?; + p.messages.push(text); + } + "interrupt" => { + self.interrupted.set(true); + p.interrupt = true; + } + "goto" if self.has_state(target) => { + let why = pl["why"].as_str().unwrap_or("forced").to_string(); + self.set_stop(Stop::Goto { + state: target.into(), + why, + }); + p.interrupt = true; + } + "goto" => { + fail(format!("no state {target:?}"))?; + } + "abort" => { + self.set_stop(match &self.on_abort { + Some(s) => Stop::Goto { + state: s.clone(), + why: "abort".into(), + }, + None => Stop::End { + status: "aborted", + reason: "aborted by the user".into(), + }, + }); + p.interrupt = true; + } + "veto" => { + // the agent hears why, and the session goes back to `code` (spec 7.3) + let msg = format!( + "The user vetoed this decision: {text}. Choose a different approach." + ); + self.db.emit(&self.id, "hint", json!({"text": msg}))?; + p.messages.push(msg); + let back = ["code", target].into_iter().find(|s| self.has_state(s)); + self.set_stop(Stop::Goto { + state: back.unwrap_or(&self.start).to_string(), + why: "veto".into(), + }); + p.interrupt = true; + } + other => { + fail(format!("unknown command {other:?}"))?; + } + } + } + if !self.exempt.get() + && !self.stopped() + && self.last_budget.get().elapsed() >= Duration::from_secs(1) + { + self.last_budget.set(Instant::now()); + let evs = self.db.events(Some(&self.id), 0)?; + let refs: Vec<&Event> = evs.iter().collect(); + if let Some(x) = budget::exceeded(&refs, &self.cfg, crate::state::now_ms()) { + self.db.emit( + &self.id, + "budget", + json!({"what": x.what, "used": x.used, "limit": x.limit}), + )?; + self.set_stop(match &self.on_budget { + Some(s) => Stop::Goto { + state: s.clone(), + why: "budget".into(), + }, + None => Stop::End { + status: "failed", + reason: format!("budget: {} {} > {}", x.what, x.used, x.limit), + }, + }); + p.interrupt = true; + } + } + Ok(p) + } + + /// True once when the context window passes `compact_at` percent; hx is told to compact. + fn compaction_due(&self) -> bool { + let Some(limit) = self.cfg.compact_at else { + return false; + }; + if self.last_compact.get().elapsed() < Duration::from_secs(1) { + return false; + } + self.last_compact.set(Instant::now()); + let Ok(evs) = self.db.events(Some(&self.id), 0) else { + return false; + }; + let refs: Vec<&Event> = evs.iter().collect(); + match budget::ctx_pct(&refs) { + Some(p) if p >= limit && !self.compacted.get() => { + self.compacted.set(true); + let _ = self.db.emit(&self.id, "compact", json!({"pct": p})); + true + } + Some(p) if p < limit => { + self.compacted.set(false); // it worked: arm again for the next time + false + } + _ => false, + } + } +} + /// Everything a running session needs; the hx process lives here for the whole session. struct Ctx<'a> { db: &'a Db, @@ -107,6 +327,7 @@ struct Ctx<'a> { profile: &'a Profile, scope: &'a str, repo: &'a Path, + ctl: Ctl<'a>, agent: Option, } @@ -114,6 +335,8 @@ enum Outcome { Ok, /// A step failed with this catch name. Caught(String), + /// A command or a budget ended the state early. + Stop(Stop), } struct StepRes { @@ -134,6 +357,11 @@ fn run_state(cx: &mut Ctx, st: &State) -> Result { json!({"state": st.name, "step": step.name, "label": label}), )?; } + // a command or budget stop is pending: do not start the next step + cx.ctl.poll()?; + if cx.ctl.stopped() { + return Err(Stopped.into()); + } let t0 = Instant::now(); let r = run_step(cx, st, step)?; cx.db.emit( @@ -144,6 +372,9 @@ fn run_state(cx: &mut Ctx, st: &State) -> Result { "exit": r.exit, "ms": t0.elapsed().as_millis() as u64, "output": r.out, }), )?; + if cx.ctl.stopped() { + return Err(Stopped.into()); // it arrived while the step ran (the step was cut short) + } if !r.ok { let catch = r .catch @@ -173,13 +404,14 @@ fn run_step(cx: &mut Ctx, st: &State, step: &Step) -> Result { /// Puts an item into the Needs-you queue and blocks until somebody answers it in the database. /// `reuse`: take over an unfinished item with the same key (orchestrator restarted while it was pending). fn ask( - db: &Db, + ctl: &Ctl, session: &str, state: &str, kind: &str, payload: Value, reuse: bool, ) -> Result { + let db = ctl.db; let key = payload["key"].as_str().unwrap_or_default().to_string(); let existing = if reuse { db.open_need(session, kind, &key)? @@ -204,6 +436,17 @@ fn ask( if let Some(a) = db.need_answer(id)? { break a; } + ctl.poll()?; + if ctl.stopped() { + // abort, force state or budget while the item is open: it is moot now + db.finish_need(id)?; + db.emit( + session, + "answer", + json!({"id": id, "kind": kind, "answer": "(cancelled)"}), + )?; + return Err(Stopped.into()); + } std::thread::sleep(Duration::from_millis(50)); }; db.finish_need(id)?; @@ -255,7 +498,7 @@ fn run_human(cx: &Ctx, st: &State, step: &Step) -> Result { "state": st.name, "step": step.name, "title": title, "detail": review_summary(cx.db, &cx.s.id)?, }); - let answer = ask(cx.db, &cx.s.id, &st.name, "review", payload, true)?; + let answer = ask(&cx.ctl, &cx.s.id, &st.name, "review", payload, true)?; if answer == "approve" { return Ok(StepRes { ok: true, @@ -279,16 +522,18 @@ fn run_human(cx: &Ctx, st: &State, step: &Step) -> Result { }) } -/// A comment from a reviewer that no agent step has seen yet. +/// Reviewer comments and user hints (messages, vetoes) that no agent step has seen yet, oldest first. fn pending_comment(db: &Db, id: &str) -> Result> { + let mut texts = vec![]; for e in db.events(Some(id), 0)?.into_iter().rev() { match e.kind.as_str() { - "comment" => return Ok(e.payload["text"].as_str().map(String::from)), - "step" if e.payload["run"] == "agent" => return Ok(None), + "comment" | "hint" => texts.extend(e.payload["text"].as_str().map(String::from)), + "step" if e.payload["run"] == "agent" => break, _ => {} } } - Ok(None) + texts.reverse(); + Ok((!texts.is_empty()).then(|| texts.join("\n"))) } /// Where a `report = "junit"` step writes its report. Next to the worktree, not in it: it must not dirty git. @@ -309,7 +554,7 @@ fn run_command(cx: &Ctx, st: &State, step: &Step) -> Result { 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 mut child = Command::new("sh") .args([ "-c", &format!( @@ -323,8 +568,31 @@ fn run_command(cx: &Ctx, st: &State, step: &Step) -> Result { .env("ORCH_REPO", cx.repo) .env("ORCH_SESSION", &cx.s.id) .current_dir(&cx.s.worktree) - .output()?; - let mut out = tail(&o.stdout, OUTPUT_TAIL); + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .process_group(0) // own group: an abort kills the command and what it started + .spawn()?; + let mut pipe = child.stdout.take().expect("piped"); + let reader = std::thread::spawn(move || { + let mut buf = Vec::new(); + let _ = pipe.read_to_end(&mut buf); + buf + }); + // wait in small steps so an abort, a forced state or a budget stop can cut the command short + let status = loop { + if let Some(s) = child.try_wait()? { + break s; + } + cx.ctl.poll()?; + if cx.ctl.stopped() { + crate::state::kill_group(child.id()); + let _ = child.wait(); + return Err(Stopped.into()); + } + std::thread::sleep(Duration::from_millis(30)); + }; + let stdout = reader.join().unwrap_or_default(); + let mut out = tail(&stdout, OUTPUT_TAIL); if step.report.as_deref() == Some("junit") && let Ok(xml) = std::fs::read_to_string(&report) { @@ -343,8 +611,8 @@ fn run_command(cx: &Ctx, st: &State, step: &Step) -> Result { } } Ok(StepRes { - ok: o.status.success(), - exit: o.status.code(), + ok: status.success(), + exit: status.code(), out, catch: None, }) @@ -398,7 +666,9 @@ fn run_agent(cx: &mut Ctx, st: &State, step: &Step) -> Result { db: cx.db, session: &cx.s.id, state: &st.name, + ctl: &cx.ctl, }; + cx.ctl.take_interrupt(); // an interrupt pressed during an earlier computer step is stale let agent = cx.agent.as_mut().expect("spawned above"); let r: StepResult = agent.step( kind, @@ -407,6 +677,21 @@ fn run_agent(cx: &mut Ctx, st: &State, step: &Step) -> Result { json!({}), &mut sink, )?; + if cx.ctl.stopped() { + return Err(Stopped.into()); // abort, forced state, veto or budget: hx was interrupted + } + if cx.ctl.take_interrupt() { + // the user interrupted: hx stopped after its tool call. Ask what it should do now. + let payload = json!({ + "key": format!("{}/{}/interrupted", st.name, step.name), + "state": st.name, "step": step.name, "title": "interrupted", + "detail": "the agent stopped; reply with a hint to go on (empty = go on as before)", + }); + let answer = ask(&cx.ctl, &cx.s.id, &st.name, "input", payload, true)?; + let reply = answer.strip_prefix("reply:").unwrap_or(&answer).trim(); + hint = (!reply.is_empty()).then(|| reply.to_string()); + continue; + } return match r.status.as_str() { "done" => Ok(StepRes { ok: true, @@ -426,7 +711,7 @@ fn run_agent(cx: &mut Ctx, st: &State, step: &Step) -> Result { "key": format!("{}/{}/input", st.name, step.name), "state": st.name, "step": step.name, "title": "question", "detail": question, }); - let answer = ask(cx.db, &cx.s.id, &st.name, "input", payload, true)?; + let answer = ask(&cx.ctl, &cx.s.id, &st.name, "input", payload, true)?; hint = Some( answer .strip_prefix("reply:") @@ -446,6 +731,7 @@ struct DbSink<'a> { db: &'a Db, session: &'a str, state: &'a str, + ctl: &'a Ctl<'a>, } /// The `optionId` of the first option whose kind is one of `kinds`. @@ -492,6 +778,12 @@ impl Sink for DbSink<'_> { Ok(()) } + fn poll(&mut self) -> Poll { + let mut p = self.ctl.poll().unwrap_or_default(); + p.compact = self.ctl.compaction_due(); + p + } + /// Goes to the Needs-you queue and blocks hx (which waits for our reply) until the user decides. /// An error while waiting cancels the request. fn permission(&mut self, p: &Value) -> Option { @@ -505,7 +797,7 @@ impl Sink for DbSink<'_> { "detail": format!("wants to run {tool}"), "options": opts, }); ask( - self.db, + self.ctl, self.session, self.state, "permission", @@ -545,8 +837,16 @@ pub fn run_session( .into_iter() .find(|t| t.id == s.task_id) .with_context(|| format!("no task {}", s.task_id))?; + let ctl = Ctl::new(db, id, m); if s.state.is_empty() { - wait_for_dependencies(db, &s, &task)?; + match wait_for_dependencies(&ctl, &s, &task) { + Ok(()) => {} + Err(e) if e.is::() => { + let why = "stopped while blocked on its dependencies".to_string(); + return finish(db, id, "", "aborted", Some(why)); + } + Err(e) => return Err(e), + } } ensure_worktree(repo, &s)?; let mut cx = Ctx { @@ -556,6 +856,7 @@ pub fn run_session( profile, scope, repo, + ctl, agent: None, }; let mut resumed = !s.state.is_empty(); @@ -576,12 +877,15 @@ pub fn run_session( } resumed = false; db.set_session(id, &cur, "running")?; + cx.ctl.enter_state(&cur); // the state that ends the session as `merged` is the merge: one session at a time, first come first served let merging = st.end.as_deref() == Some("merged"); - if merging { - enter_merge_queue(db, id)?; - } - let result = run_state(&mut cx, st); + let result = (|| { + if merging { + enter_merge_queue(&cx.ctl, id)?; + } + run_state(&mut cx, st) + })(); if merging { // all acceptance checks again on main, while this session still holds the merge slot if matches!(result, Ok(Outcome::Ok)) @@ -593,10 +897,25 @@ pub fn run_session( } let outcome = match result { Ok(o) => o, + // a wait was cut short by a command or a budget: what was asked decides where we go + Err(e) if e.is::() => Outcome::Stop(cx.ctl.take_stop().unwrap_or(Stop::End { + status: "failed", + reason: "stopped".into(), + })), Err(e) => return finish(db, id, &cur, "failed", Some(format!("{e:#}"))), }; from = cur.clone(); match outcome { + Outcome::Stop(Stop::End { status, reason }) => { + return finish(db, id, &cur, status, Some(reason)); + } + Outcome::Stop(Stop::Goto { state, why }) => { + db.emit(id, "goto", json!({"from": cur, "to": state, "why": why}))?; + if matches!(why.as_str(), "abort" | "budget") { + cx.agent = None; // stop hx for good; a forced state or a veto keeps its conversation + } + cur = state; + } Outcome::Ok => { if matches!(st.kind, Kind::Exit | Kind::Abort) || st.next.is_none() { let end = st.end.clone().unwrap_or_else(|| "done".into()); @@ -635,9 +954,14 @@ pub fn run_session( const POLL: Duration = Duration::from_millis(100); /// A task whose dependencies have not merged stays `queued` (BLOCKED on screen) and nothing of it starts. -fn wait_for_dependencies(db: &Db, s: &Session, t: &Task) -> Result<()> { +fn wait_for_dependencies(ctl: &Ctl, s: &Session, t: &Task) -> Result<()> { + let db = ctl.db; let mut announced = false; loop { + ctl.poll()?; + if ctl.stopped() { + return Err(Stopped.into()); + } let unmet: Vec<&String> = t .depends_on .iter() @@ -671,13 +995,19 @@ fn alive(db: &Db, session: &str) -> bool { } /// Joins the merge queue and blocks until this session is at the head. -fn enter_merge_queue(db: &Db, id: &str) -> Result<()> { +fn enter_merge_queue(ctl: &Ctl, id: &str) -> Result<()> { + let db = ctl.db; db.queue_join(id)?; let pos = db.queue_position(id)?; if pos > 1 { db.emit(id, "queue", json!({"position": pos}))?; } loop { + ctl.poll()?; + if ctl.stopped() { + db.queue_leave(id)?; // an aborted session must not keep its place + return Err(Stopped.into()); + } match db.queue_head()? { Some(h) if h == id => return Ok(()), Some(h) if !alive(db, &h) => db.queue_leave(&h)?, @@ -1357,4 +1687,389 @@ end = "merged" assert_eq!(e.db.events(Some(crate::checks::GOAL), 0).unwrap().len(), 2); let _ = std::fs::remove_dir_all(&e.dir); } + + // ---- live control: commands from another connection, budgets ---- + + const CTL_TAIL: &str = r#" +[[state]] +name = "done" +kind = "exit" +end = "merged" +[[state]] +name = "stuck" +kind = "exit" +only_on = ["budget"] +end = "escalated" +[[state]] +name = "aborted" +kind = "abort" +only_on = ["abort"] +end = "aborted" +"#; + + fn ctl_machine(top_and_states: &str) -> Machine { + Machine::parse(&[top_and_states, CTL_TAIL].concat()).unwrap() + } + + /// Polls `f` until it is true or `secs` passed. + fn wait_until(secs: u64, mut f: impl FnMut() -> bool) -> bool { + let end = Instant::now() + Duration::from_secs(secs); + while Instant::now() < end { + if f() { + return true; + } + std::thread::sleep(Duration::from_millis(20)); + } + false + } + + /// The user in another process: waits until `ready` holds on the session's events, then runs `act`. + fn user( + e: &Env, + ready: impl Fn(&[crate::db::Event]) -> bool + Send + 'static, + act: impl FnOnce(&Db) + Send + 'static, + ) -> std::thread::JoinHandle<()> { + let path = e.dir.join("orch.db"); + std::thread::spawn(move || { + let db = Db::open(&path).unwrap(); + assert!( + wait_until(20, || ready(&db.events(Some("s1"), 0).unwrap())), + "the session never got there" + ); + act(&db); + }) + } + + fn has(evs: &[crate::db::Event], kind: &str) -> bool { + evs.iter().any(|e| e.kind == kind) + } + + const ABORTABLE: &str = r#"name = "m" +on_abort = "aborted" +on_budget = "stuck" +[[state]] +name = "a" +kind = "start" +steps = [{ name = "long", run = "computer", cmd = "sleep 30" }] +next = "done" +"#; + + #[test] + fn abort_kills_a_running_command_and_goes_to_on_abort() { + let e = env("abort"); + let m = ctl_machine(ABORTABLE); + create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); + let u = user( + &e, + |ev| has(ev, "state"), + |db| { + db.add_command("s1", "abort", &json!({})).unwrap(); + }, + ); + let t0 = Instant::now(); + assert_eq!( + run_session(&e.db, &m, "s1", &e.repo, "", &plain()).unwrap(), + "aborted" + ); + u.join().unwrap(); + assert!( + t0.elapsed() < Duration::from_secs(10), + "the sleep 30 was killed, not waited for" + ); + let ev = e.db.events(Some("s1"), 0).unwrap(); + let g = ev.iter().find(|v| v.kind == "goto").unwrap(); + assert_eq!( + (g.payload["to"].as_str(), g.payload["why"].as_str()), + (Some("aborted"), Some("abort")) + ); + assert_eq!(states(&e.db, "s1"), ["a", "aborted"]); + let _ = std::fs::remove_dir_all(&e.dir); + } + + #[test] + fn force_state_jumps_and_an_unknown_state_is_refused() { + let e = env("force"); + let m = ctl_machine(ABORTABLE); + create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); + let u = user( + &e, + |ev| has(ev, "state"), + |db| { + db.add_command("s1", "goto", &json!({"state": "nowhere"})) + .unwrap(); + std::thread::sleep(Duration::from_millis(400)); // the bad one is taken and refused first + db.add_command("s1", "goto", &json!({"state": "done", "why": "forced"})) + .unwrap(); + }, + ); + assert_eq!( + run_session(&e.db, &m, "s1", &e.repo, "", &plain()).unwrap(), + "merged" + ); + u.join().unwrap(); + let ev = e.db.events(Some("s1"), 0).unwrap(); + let bad = ev + .iter() + .find(|v| v.kind == "command_failed") + .expect("refused"); + assert!(bad.payload["error"].as_str().unwrap().contains("nowhere")); + assert_eq!(states(&e.db, "s1"), ["a", "done"]); + let _ = std::fs::remove_dir_all(&e.dir); + } + + #[test] + fn abort_cancels_an_open_needs_you_item() { + let e = env("abort-need"); + let m = ctl_machine( + r#"name = "m" +on_abort = "aborted" +[[state]] +name = "review" +kind = "start" +steps = [{ name = "wait", run = "human" }] +next = "done" +"#, + ); + create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); + let u = user( + &e, + |ev| has(ev, "need"), + |db| { + db.add_command("s1", "abort", &json!({})).unwrap(); + }, + ); + assert_eq!( + run_session(&e.db, &m, "s1", &e.repo, "", &plain()).unwrap(), + "aborted" + ); + u.join().unwrap(); + assert!( + e.db.pending_needs().unwrap().is_empty(), + "the moot item left the queue" + ); + let _ = std::fs::remove_dir_all(&e.dir); + } + + #[test] + fn budget_stop_interrupts_hx_and_goes_to_on_budget() { + let e = env("budget"); + let m = ctl_machine( + r#"name = "m" +on_abort = "aborted" +on_budget = "stuck" +[budget] +cost = 1.0 +[[state]] +name = "a" +kind = "start" +steps = [{ name = "ag", run = "agent", prompt = "implement" }] +next = "done" +"#, + ); + create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); + // hx reports $2.50 spent and keeps working until it is interrupted + let p = fake("FAKE_MODE=slow FAKE_USAGE=1000,100000,2.5"); + assert_eq!( + run_session(&e.db, &m, "s1", &e.repo, "", &p).unwrap(), + "escalated" + ); + let ev = e.db.events(Some("s1"), 0).unwrap(); + let b = ev + .iter() + .find(|v| v.kind == "budget") + .expect("budget event"); + assert_eq!(b.payload["what"], "cost"); + assert_eq!( + (b.payload["used"].as_str(), b.payload["limit"].as_str()), + (Some("$2.50"), Some("$1.00")) + ); + let g = ev.iter().find(|v| v.kind == "goto").unwrap(); + assert_eq!( + (g.payload["to"].as_str(), g.payload["why"].as_str()), + (Some("stuck"), Some("budget")) + ); + assert_eq!( + ev.iter().filter(|v| v.kind == "budget").count(), + 1, + "stops once, not on every poll" + ); + let _ = std::fs::remove_dir_all(&e.dir); + } + + #[test] + fn a_budget_without_on_budget_fails_the_session() { + let e = env("budget-fail"); + let m = ctl_machine( + r#"name = "m" +[budget] +cost = 1.0 +[[state]] +name = "a" +kind = "start" +steps = [{ name = "ag", run = "agent", prompt = "implement" }] +next = "done" +"#, + ); + create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); + let p = fake("FAKE_MODE=slow FAKE_USAGE=1000,100000,2.5"); + assert_eq!( + run_session(&e.db, &m, "s1", &e.repo, "", &p).unwrap(), + "failed" + ); + assert!( + failure_reason(&e).contains("budget: cost $2.50 > $1.00"), + "{}", + failure_reason(&e) + ); + let _ = std::fs::remove_dir_all(&e.dir); + } + + const SLOW_AGENT: &str = r#"name = "m" +on_abort = "aborted" +[[state]] +name = "a" +kind = "start" +steps = [{ name = "ag", run = "agent", prompt = "implement" }] +next = "done" +"#; + + #[test] + fn interrupt_asks_what_now_and_the_reply_goes_to_hx() { + let e = env("interrupt"); + let log = e.dir.join("fake.log"); + let m = ctl_machine(SLOW_AGENT); + create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); + let u = user( + &e, + |ev| has(ev, "intent"), + |db| { + db.add_command("s1", "interrupt", &json!({})).unwrap(); + }, + ); + let answerer = answerer(e.dir.join("orch.db"), &["reply: try tokens"]); + let p = fake(&format!("FAKE_MODE=slow FAKE_LOG={}", log.display())); + assert_eq!( + run_session(&e.db, &m, "s1", &e.repo, "", &p).unwrap(), + "merged" + ); + u.join().unwrap(); + let seen = answerer.join().unwrap(); + assert_eq!( + (seen[0].0.as_str(), seen[0].1["title"].as_str()), + ("input", Some("interrupted")) + ); + let steps: Vec = std::fs::read_to_string(&log) + .unwrap() + .lines() + .map(|l| serde_json::from_str::(l).unwrap()) + .filter(|m| m["method"] == "hx/step") + .collect(); + assert_eq!(steps.len(), 2, "the step ran again after the reply"); + assert_eq!(steps[1]["params"]["context"]["hint"], "try tokens"); + let _ = std::fs::remove_dir_all(&e.dir); + } + + #[test] + fn messages_reach_a_running_step_and_veto_goes_back_to_code() { + let e = env("veto"); + let m = ctl_machine( + r#"name = "m" +on_abort = "aborted" +[[state]] +name = "plan" +kind = "start" +steps = [{ name = "draft", run = "agent", prompt = "plan" }] +next = "code" +[[state]] +name = "code" +steps = [{ name = "edit", run = "computer", cmd = "true" }] +next = "done" +"#, + ); + create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); + let wt = e.dir.join("wt/s1"); + let messages = wt.join("messages.txt"); + let u = user( + &e, + |ev| has(ev, "intent"), + move |db| { + db.add_command("s1", "message", &json!({"text": "prefer a bucket"})) + .unwrap(); + // let the message arrive before the veto interrupts hx + assert!(wait_until(10, || std::fs::read_to_string(&messages) + .is_ok_and(|m| m.contains("prefer a bucket")))); + db.add_command( + "s1", + "veto", + &json!({"text": "sliding window", "state": "plan"}), + ) + .unwrap(); + }, + ); + let p = fake("FAKE_MODE=slow"); + assert_eq!( + run_session(&e.db, &m, "s1", &e.repo, "", &p).unwrap(), + "merged" + ); + u.join().unwrap(); + let said = std::fs::read_to_string(wt.join("messages.txt")).unwrap(); + assert!(said.contains("prefer a bucket")); + assert!( + said.contains("vetoed this decision: sliding window"), + "{said}" + ); + assert_eq!( + states(&e.db, "s1"), + ["plan", "code", "done"], + "veto goes back to code" + ); + let g = + e.db.events(Some("s1"), 0) + .unwrap() + .into_iter() + .find(|v| v.kind == "goto") + .unwrap(); + assert_eq!(g.payload["why"], "veto"); + let _ = std::fs::remove_dir_all(&e.dir); + } + + #[test] + fn hx_is_told_to_compact_once_the_context_passes_the_threshold() { + let e = env("compact"); + let m = ctl_machine( + r#"name = "m" +on_abort = "aborted" +[budget] +compact_at = 85 +[[state]] +name = "a" +kind = "start" +steps = [{ name = "ag", run = "agent", prompt = "implement" }] +next = "done" +"#, + ); + create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); + let marker = e.dir.join("wt/s1/compact.txt"); + let u = user( + &e, + |ev| has(ev, "intent"), + move |db| { + assert!(wait_until(15, || marker.exists()), "hx got hx/compact"); + db.add_command("s1", "abort", &json!({})).unwrap(); + }, + ); + let p = fake("FAKE_MODE=slow FAKE_USAGE=90000,100000,0.1"); // 90% of the window + assert_eq!( + run_session(&e.db, &m, "s1", &e.repo, "", &p).unwrap(), + "aborted" + ); + u.join().unwrap(); + let ev = e.db.events(Some("s1"), 0).unwrap(); + assert_eq!( + ev.iter().filter(|v| v.kind == "compact").count(), + 1, + "asked once, not every second" + ); + let _ = std::fs::remove_dir_all(&e.dir); + } } diff --git a/src/tui/goal.rs b/src/tui/goal.rs index bbf951e..22b6a03 100644 --- a/src/tui/goal.rs +++ b/src/tui/goal.rs @@ -15,7 +15,7 @@ const BOX_W: u16 = 26; const GAP_W: u16 = 5; const BOX_H: u16 = 5; -pub fn draw(f: &mut Frame, g: &GoalView, h: &Header, checks_running: bool) { +pub fn draw(f: &mut Frame, g: &GoalView, h: &Header, checks_running: bool, dec_sel: usize) { let area = f.area(); f.render_widget( Block::new().style(Style::new().bg(theme::BG).fg(theme::TEXT)), @@ -32,7 +32,7 @@ pub fn draw(f: &mut Frame, g: &GoalView, h: &Header, checks_running: bool) { goal_box(f, goal, g); let [left, right] = Layout::horizontal([Constraint::Fill(1), Constraint::Length(56)]).areas(body); - left_box(f, left, g); + left_box(f, left, g, dec_sel); acceptance_box(f, right, g, checks_running); f.render_widget(key_bar(), keys); } @@ -134,7 +134,7 @@ fn task_box(f: &mut Frame, area: Rect, t: &TaskBox) { ); } -fn left_box(f: &mut Frame, area: Rect, g: &GoalView) { +fn left_box(f: &mut Frame, area: Rect, g: &GoalView, dec_sel: usize) { let title = vec![ Span::styled("Task graph", bold(theme::TEXT)), Span::styled(" left to right = dependency order", fg(theme::DIM)), @@ -199,20 +199,32 @@ fn left_box(f: &mut Frame, area: Rect, g: &GoalView) { let di = db.inner(decisions); f.render_widget(db, decisions); let w = di.width as usize; + // scroll so the selected decision stays in view + let skip = dec_sel.saturating_sub((di.height as usize).saturating_sub(1)); let lines: Vec = g .decisions .iter() + .enumerate() + .skip(skip) .take(di.height as usize) - .map(|d| { + .map(|(i, d)| { let text_style = if d.vetoed { fg(theme::DIM).add_modifier(Modifier::CROSSED_OUT) } else { Style::new() }; + let cursor = if i == dec_sel { + Span::styled("▶", fg(theme::RUN)) + } else { + Span::raw(" ") + }; + let tag = if d.vetoed { " vetoed" } else { "" }; Line::from(vec![ - Span::styled(format!(" {:<4}", d.session), fg(theme::RUN)), - Span::styled(fit(&d.text, w.saturating_sub(22)), text_style), + cursor, + Span::styled(format!("{:<4}", d.session), fg(theme::RUN)), + Span::styled(fit(&d.text, w.saturating_sub(30)), text_style), Span::styled(format!(" {:<14}", d.whence), fg(theme::DIM)), + Span::styled(tag, fg(theme::ERR)), ]) }) .collect(); @@ -283,6 +295,8 @@ fn key_bar() -> Line<'static> { ("e", "edit goal"), ("+", "add check"), ("R", "run all checks"), + ("j/k", "select decision"), + ("v", "veto decision"), ] { v.push(Span::styled( format!(" {k} "), diff --git a/src/tui/mod.rs b/src/tui/mod.rs index 8376acf..8ae4e22 100644 --- a/src/tui/mod.rs +++ b/src/tui/mod.rs @@ -72,7 +72,7 @@ fn need_key(n: &view::Need, c: char) -> NeedKey { } /// What a finished input line is for. -#[derive(Clone, Copy, PartialEq, Debug)] +#[derive(Clone, PartialEq, Debug)] enum Target { /// Answer to this Needs-you item. Need(i64), @@ -80,6 +80,12 @@ enum Target { Goal, /// `name | command | owner` of a new acceptance check; the owner is optional. Check, + /// A hint for the agent of this session. + Message(String), + /// Force this session into the state named in the text. + Goto(String), + /// Kill this session, but only when the text is `yes`. + Abort(String), } /// A one-line text entry shown at the bottom while the user writes a comment, reply, goal or check. @@ -121,6 +127,8 @@ struct App { need_sel: usize, input: Option, goal_view: Option, + /// Selected decision on the goal screen. + dec_sel: usize, /// True while a background `run all checks` is going. checks_running: std::sync::Arc, } @@ -149,11 +157,79 @@ impl App { self.db.as_ref() } + /// Sends a command to a running session; its runner (maybe another process) picks it up within a moment. + fn command(&mut self, session: &str, kind: &str, payload: serde_json::Value) { + if let Some(db) = &self.db { + let _ = db.add_command(session, kind, &payload); + } + } + + /// Vetoes the selected decision: the agent is told, and the session goes back to `code`. + fn veto_selected(&mut self) { + let Some(d) = self + .goal_view + .as_ref() + .and_then(|g| g.decisions.get(self.dec_sel)) + .filter(|d| !d.vetoed) + .cloned() + else { + return; + }; + if self + .db + .as_ref() + .is_some_and(|db| db.veto_decision(d.id).unwrap_or(false)) + { + self.command( + &d.session, + "veto", + serde_json::json!({"text": d.text, "state": d.state}), + ); + } + self.refresh(); + } + /// A finished input line: an answer for the queue, a new goal, or a new check. fn submit(&mut self, i: InputLine) { let text = i.text.trim().to_string(); match i.target { Target::Need(id) => return self.answer(id, &format!("{}{text}", i.prefix)), + Target::Message(sid) => { + if !text.is_empty() { + self.command(&sid, "message", serde_json::json!({"text": text})); + } + return; + } + Target::Goto(sid) => { + let states = self + .detail + .as_ref() + .map(|d| d.states.clone()) + .unwrap_or_default(); + if states.contains(&text) { + self.command( + &sid, + "goto", + serde_json::json!({"state": text, "why": "forced"}), + ); + } else { + self.pager = Some(Pager { + title: "force state".into(), + lines: vec![ + format!("no state {text:?}"), + format!("states: {}", states.join(", ")), + ], + scroll: 0, + }); + } + return; + } + Target::Abort(sid) => { + if text == "yes" { + self.command(&sid, "abort", serde_json::json!({})); + } + return; + } Target::Goal if !text.is_empty() => { if let Some(db) = self.db_or_create() { let _ = db.set_goal(&text); @@ -195,6 +271,7 @@ impl App { need_sel: 0, input: None, goal_view: None, + dec_sel: 0, checks_running: Default::default(), } } @@ -378,7 +455,7 @@ fn draw(f: &mut ratatui::Frame, app: &App, header: &Header) { } }; let running = app.checks_running.load(std::sync::atomic::Ordering::SeqCst); - goal::draw(f, g, header, running); + goal::draw(f, g, header, running, app.dec_sel); } _ => overview::draw(f, &app.overview, header, app.sel, app.need_sel), } @@ -655,6 +732,15 @@ fn on_key( }); } KeyCode::Char('R') => app.run_all_checks(), + KeyCode::Char('j') | KeyCode::Down => { + let last = app + .goal_view + .as_ref() + .map_or(0, |g| g.decisions.len().saturating_sub(1)); + app.dec_sel = (app.dec_sel + 1).min(last); + } + KeyCode::Char('k') | KeyCode::Up => app.dec_sel = app.dec_sel.saturating_sub(1), + KeyCode::Char('v') => app.veto_selected(), _ => {} }, Screen::Session(id) => { @@ -664,6 +750,44 @@ fn on_key( app.screen = Screen::Overview; app.detail = None; } + KeyCode::Char('i') => app.command(&id, "interrupt", serde_json::json!({})), + KeyCode::Char('m') => { + app.input = Some(InputLine { + label: "message to the agent", + prefix: "", + target: Target::Message(id), + text: String::new(), + }); + } + KeyCode::Char('s') => { + app.input = Some(InputLine { + label: "force state", + prefix: "", + target: Target::Goto(id), + text: String::new(), + }); + } + KeyCode::Char('k') => { + app.input = Some(InputLine { + label: "type yes to kill this session (hx stops, it goes to on abort)", + prefix: "", + target: Target::Abort(id), + text: String::new(), + }); + } + // re-plan from the start state; only offered while the loop detector shows + KeyCode::Char('r') if app.detail.as_ref().is_some_and(|d| d.looping.is_some()) => { + let start = app + .detail + .as_ref() + .map(|d| d.start.clone()) + .unwrap_or_default(); + app.command( + &id, + "goto", + serde_json::json!({"state": start, "why": "replan"}), + ); + } KeyCode::Char('t') => app.pager = Some(test_output(app, &id)), KeyCode::Char('l') => app.pager = Some(transcript(app, &id)), KeyCode::Char('d') => { @@ -713,6 +837,7 @@ mod tests { use super::*; use crate::view::{Chip, EventLine, Mark, Need, NeedKind, Row, Status}; use ratatui::{Terminal, backend::TestBackend}; + use serde_json::json; fn screen(o: &Overview, sel: usize) -> String { let mut t = Terminal::new(TestBackend::new(160, 45)).unwrap(); @@ -772,6 +897,7 @@ mod tests { machine: "task.toml".into(), chips: chips(spec), retry: retry.into(), + looping: false, tests: tests.into(), tests_ok: ok, added: 164, @@ -1202,7 +1328,7 @@ end = "merged" rev: "main@abc".into(), now_ms: 0, }; - t.draw(|f| goal::draw(f, g, &h, running)).unwrap(); + t.draw(|f| goal::draw(f, g, &h, running, 0)).unwrap(); let b = t.backend().buffer(); b.content() .chunks(b.area.width as usize) @@ -1332,4 +1458,184 @@ end = "merged" assert_eq!(parse_check("| b"), None); let _ = std::fs::remove_dir_all(&dir); } + + /// A repo with `task.toml` and a running session s2 whose last two test runs failed on the same two tests. + fn looping_repo(tag: &str) -> (PathBuf, Db) { + let dir = std::env::temp_dir().join(format!("orch-tui-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join(".hx/machines")).unwrap(); + std::fs::write( + dir.join(".hx/machines/task.toml"), + include_str!("../../examples/machines/task.toml"), + ) + .unwrap(); + let db = Db::open(&dir.join(".hx/orch.db")).unwrap(); + add(&db, "s2", "oauth-provider", &[], "code", "running"); + let run = |names: &[&str]| { + let f: Vec<_> = names + .iter() + .map(|n| json!({"name": n, "message": "left != right", "location": "src/token.rs:142"})) + .collect(); + db.emit("s2", "test", json!({"state": "test", "step": "cargo test", "passed": 39, "failed": names.len(), "skipped": 0, "secs": 6.2, "failures": f})).unwrap(); + }; + let go = |from: &str, to: &str| { + db.emit("s2", "state", json!({"from": from, "to": to})) + .unwrap(); + }; + go("", "plan"); + go("plan", "code"); + go("code", "build"); + go("build", "test"); + run(&["auth::token::refresh", "auth::token::expired"]); + db.emit( + "s2", + "catch", + json!({"state": "test", "catch": "TestsFailed"}), + ) + .unwrap(); + go("test", "code"); + db.emit( + "s2", + "edit", + json!({"path": "src/token.rs", "added": 6, "removed": 2}), + ) + .unwrap(); + go("code", "build"); + go("build", "test"); + run(&["auth::token::expired", "auth::token::refresh"]); + db.emit( + "s2", + "catch", + json!({"state": "test", "catch": "TestsFailed"}), + ) + .unwrap(); + go("test", "code"); + db.emit( + "s2", + "usage", + json!({"ctx_used": 142_000, "ctx_limit": 200_000, "cost": 1.12}), + ) + .unwrap(); + (dir, db) + } + + #[test] + fn the_session_screen_shows_the_loop_detector_and_budget_caps() { + let (dir, db) = looping_repo("loop"); + let mut app = App::new(dir.clone()); + app.screen = Screen::Session("s2".into()); + app.refresh(); + let d = app.detail.as_ref().expect("detail").clone(); + assert_eq!(d.looping.as_ref().map(|l| (l.runs, l.tests)), Some((2, 2))); + 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::() + .trim_end() + .to_string() + }) + .collect::>() + .join("\n"); + if std::env::var_os("ORCH_DUMP").is_some() { + println!("{text}"); + } + for want in [ + "◆ Loop detector", + "The last 2 test runs failed on the same 2 tests.", + "editing src/token.rs.", + "[r] re-plan from PLAN [m] send hint to agent", + "[k] kill and hand over", + "142k / 200k compact at 85%", + "$1.12 / $5.00", + "/ 1h cap", + " r re-plan", + " i interrupt", + " k kill", + ] { + assert!(text.contains(want), "missing {want:?} in:\n{text}"); + } + // the overview marks the row too + let o = screen(&app.overview, 0); + assert!(o.contains("· looping"), "{o}"); + drop(db); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn session_keys_become_commands_and_bad_input_is_refused() { + let (dir, _db) = looping_repo("cmds"); + let mut app = App::new(dir.clone()); + app.screen = Screen::Session("s2".into()); + app.refresh(); + let line = |target, text: &str| InputLine { + label: "x", + prefix: "", + target, + text: text.into(), + }; + app.submit(line(Target::Message("s2".into()), " use a bucket ")); + app.submit(line(Target::Message("s2".into()), " ")); // empty: nothing sent + app.submit(line(Target::Goto("s2".into()), "review")); + app.submit(line(Target::Goto("s2".into()), "nowhere")); + assert!(app.pager.as_ref().unwrap().lines[1].contains("states: plan, code")); + app.submit(line(Target::Abort("s2".into()), "no")); + app.submit(line(Target::Abort("s2".into()), "yes")); + app.command("s2", "interrupt", json!({})); + let db = Db::open(&dir.join(".hx/orch.db")).unwrap(); + let cmds = db.take_commands("s2").unwrap(); + let kinds: Vec<_> = cmds.iter().map(|c| c.0.as_str()).collect(); + assert_eq!(kinds, ["message", "goto", "abort", "interrupt"]); + assert_eq!(cmds[0].1["text"], "use a bucket"); + assert_eq!( + (cmds[1].1["state"].as_str(), cmds[1].1["why"].as_str()), + (Some("review"), Some("forced")) + ); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn vetoing_a_decision_marks_it_and_tells_the_session() { + let (dir, db) = looping_repo("veto"); + db.add_decision("s2", "token bucket in Redis", "plan") + .unwrap(); + db.add_decision("s2", "limit keyed by user id", "code") + .unwrap(); + let mut app = App::new(dir.clone()); + app.screen = Screen::Goal; + app.refresh(); + app.dec_sel = 1; + app.veto_selected(); + app.veto_selected(); // already vetoed: no second command + let ds = db.decisions().unwrap(); + assert_eq!( + ds.iter().map(|d| d.vetoed).collect::>(), + [false, true] + ); + let cmds = db.take_commands("s2").unwrap(); + assert_eq!(cmds.len(), 1); + assert_eq!(cmds[0].0, "veto"); + assert_eq!( + (cmds[0].1["text"].as_str(), cmds[0].1["state"].as_str()), + (Some("limit keyed by user id"), Some("code")) + ); + // the goal screen shows it struck out and tagged + let text = goal_text(app.goal_view.as_ref().unwrap(), false); + assert!( + text.contains("limit keyed by user id") && text.contains("vetoed"), + "{text}" + ); + assert!(text.contains("v veto decision")); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/src/tui/overview.rs b/src/tui/overview.rs index 5eac0cd..7a3a6fd 100644 --- a/src/tui/overview.rs +++ b/src/tui/overview.rs @@ -283,6 +283,9 @@ fn sessions_box(f: &mut Frame, area: Rect, o: &Overview, sel: usize) { if !r.retry.is_empty() { m2.push(Span::styled(format!(" {}", r.retry), fg(theme::ERR))); } + if r.looping { + m2.push(Span::styled(" · looping", bold(theme::WAIT))); + } cell(&mut l2, m2, w_machine); let bg = if on { Style::new().bg(theme::SEL) diff --git a/src/tui/session.rs b/src/tui/session.rs index 7b32159..05f07e1 100644 --- a/src/tui/session.rs +++ b/src/tui/session.rs @@ -38,18 +38,54 @@ pub fn draw(f: &mut Frame, d: &Detail, h: &Header) { None => 3, }; let files_h = (d.files.len().clamp(1, 6) + 2) as u16; - let [test, now, files, budget] = Layout::vertical([ + // the loop detector box only exists while the session loops + let loop_h = if d.looping.is_some() { 7 } else { 0 }; + let [loop_area, test, now, files, budget] = Layout::vertical([ + Constraint::Length(loop_h), Constraint::Length(test_h), Constraint::Length(4), Constraint::Length(files_h), Constraint::Min(6), ]) .areas(right); + if let Some(l) = &d.looping { + loop_box(f, loop_area, d, l); + } test_box(f, test, d.test.as_ref()); now_box(f, now, d); files_box(f, files, d); budget_box(f, budget, d); - f.render_widget(key_bar(), keys); + f.render_widget(key_bar(d.looping.is_some()), keys); +} + +fn loop_box(f: &mut Frame, area: Rect, d: &Detail, l: &crate::detail::LoopView) { + let b = Block::bordered().border_style(fg(theme::WAIT)); + let inner = b.inner(area); + f.render_widget(b, area); + let mut what = format!( + "The last {} test runs failed on the same {} tests.", + l.runs, l.tests + ); + if let Some(file) = &l.file { + what.push_str(&format!(" The agent keeps editing {file}.")); + } + // the sentence wraps (two lines fit); the keys get a line each so none is cut + f.render_widget( + Paragraph::new(vec![ + Line::from(Span::styled(" ◆ Loop detector", bold(theme::WAIT))), + Line::from(Span::raw(format!(" {what}"))), + Line::from(Span::styled( + format!( + " [r] re-plan from {} [m] send hint to agent", + d.start.to_uppercase() + ), + fg(theme::DIM), + )), + Line::from(Span::styled(" [k] kill and hand over", fg(theme::DIM))), + ]) + .wrap(ratatui::widgets::Wrap { trim: false }), + inner, + ); } fn status_color(s: Status) -> Color { @@ -416,6 +452,12 @@ fn budget_box(f: &mut Frame, area: Rect, d: &Detail) { label("context"), bar(u as usize, l as usize, 10, c), Span::raw(format!(" {} / {}", k(u), k(l))), + Span::styled( + d.budget + .compact_at + .map_or(String::new(), |c| format!(" compact at {c}%")), + fg(theme::DIM), + ), ]) } None => Line::from(vec![label("context"), Span::styled("—", fg(theme::DIM))]), @@ -431,28 +473,62 @@ fn budget_box(f: &mut Frame, area: Rect, d: &Detail) { 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)), - ])); + // a cap turns the plain number into a bar; red once it is passed + let over = |used: f64, cap: f64| if used > cap { theme::ERR } else { theme::RUN }; + lines.push(match d.budget.wall_cap { + Some(cap) => { + let c = over(d.budget.wall_secs as f64, cap as f64); + Line::from(vec![ + label("wall time"), + bar(d.budget.wall_secs as usize, cap as usize, 10, c), + Span::raw(format!(" {} / {} cap", ago(d.budget.wall_secs), ago(cap))), + ]) + } + None => Line::from(vec![ + label("wall time"), + Span::styled(ago(d.budget.wall_secs), fg(theme::RUN)), + Span::styled(" no cap set", fg(theme::DIM)), + ]), + }); + lines.push(match d.budget.cost_cap { + Some(cap) => { + let c = over(d.budget.cost, cap); + Line::from(vec![ + label("cost"), + bar( + (d.budget.cost * 100.0) as usize, + (cap * 100.0) as usize, + 10, + c, + ), + Span::raw(format!(" ${:.2} / ${cap:.2}", d.budget.cost)), + ]) + } + None => Line::from(vec![ + label("cost"), + Span::styled(format!("${:.2}", d.budget.cost), fg(theme::RUN)), + Span::styled(" no cap set", fg(theme::DIM)), + ]), + }); f.render_widget(Paragraph::new(lines), inner); } -fn key_bar() -> Line<'static> { +fn key_bar(looping: bool) -> Line<'static> { let mut v = vec![Span::raw(" ")]; for (key, what) in [ ("esc", "back"), ("t", "full test output"), ("d", "diff"), - ("l", "agent transcript"), - ("o", "open worktree in hx"), - ] { + ("l", "transcript"), + ("i", "interrupt"), + ("m", "message"), + ("s", "state"), + ("k", "kill"), + ("o", "open in hx"), + ] + .into_iter() + .chain(looping.then_some(("r", "re-plan"))) + { v.push(Span::styled( format!(" {key} "), Style::new() diff --git a/src/view.rs b/src/view.rs index 82a0834..69e0ff1 100644 --- a/src/view.rs +++ b/src/view.rs @@ -54,6 +54,8 @@ pub struct Row { pub chips: Vec, /// `↻ fix 2/3` while the session recovers from a catch, else empty. pub retry: String, + /// The loop detector fired: the last test runs failed on the same tests. + pub looping: bool, /// `39/41 ✗2`, `18/18 ✓` or `—`. pub tests: String, pub tests_ok: Option, @@ -248,6 +250,7 @@ pub fn build(i: &Input) -> Overview { machine: machine.map_or_else(|| task.machine.clone(), |m| format!("{}.toml", m.name)), chips: scan.chips, retry: scan.retry, + looping: scan.looping, tests: scan.tests.0, tests_ok: scan.tests.1, added: scan.added, @@ -286,6 +289,7 @@ pub fn build(i: &Input) -> Overview { struct Scan { chips: Vec, retry: String, + looping: bool, tests: (String, Option), added: u32, removed: u32, @@ -304,6 +308,7 @@ fn scan(evs: &[&Event], s: &Session, machine: Option<&Machine>) -> Scan { let mut sc = Scan { chips: vec![], retry: String::new(), + looping: false, tests: ("—".into(), None), added: 0, removed: 0, @@ -394,6 +399,8 @@ fn scan(evs: &[&Event], s: &Session, machine: Option<&Machine>) -> Scan { }; } } + sc.looping = + matches!(s.status.as_str(), "running" | "waiting") && crate::budget::looping(evs).is_some(); sc } diff --git a/tests/fake_acp_hx.py b/tests/fake_acp_hx.py index 7f8728c..09df6c5 100644 --- a/tests/fake_acp_hx.py +++ b/tests/fake_acp_hx.py @@ -6,7 +6,10 @@ Behaviour per `hx/step`, chosen with FAKE_MODE (orch passes FAKE_* through the p block_once blocked the first time (marker file .fake_blocked in cwd), done afterwards needs_input step_result needs_input with a question; finishes when the retried step has a context.hint permission asks session/request_permission first and records the answer in permission.txt + slow works until hx/interrupt (records hx/message and hx/compact in messages.txt / compact.txt), then + answers done; a retried step with context.hint finishes at once crash exits without a step_result +FAKE_USAGE="ctx_used,ctx_limit,cost" makes every step report that usage first. Every received message is appended to FAKE_LOG when set. Each step also appends its prompt kind to steps.txt. """ import json @@ -47,6 +50,10 @@ def step(params): if mode == "crash": sys.exit(3) note("hx/intent", {"text": f"working on {kind}"}) + usage = os.environ.get("FAKE_USAGE") # "ctx_used,ctx_limit,cost" + if usage: + used, limit, cost = usage.split(",") + note("hx/usage", {"ctx_used": int(used), "ctx_limit": int(limit), "cost": float(cost)}) 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": { @@ -59,6 +66,21 @@ def step(params): with open(os.path.join(cwd, "permission.txt"), "w") as f: f.write(json.dumps(m["result"])) break + # slow keeps working until the orchestrator interrupts it; it records what it is told meanwhile. + # A retried step (context.hint set, e.g. the user's reply after an interrupt) finishes at once. + if mode == "slow" and not params.get("context", {}).get("hint"): + while True: + m = recv() + md = m.get("method") + if md == "hx/message": + with open(os.path.join(cwd, "messages.txt"), "a") as f: + f.write(m["params"]["text"] + "\n") + elif md == "hx/compact": + with open(os.path.join(cwd, "compact.txt"), "a") as f: + f.write("compact\n") + elif md == "hx/interrupt": + note("hx/step_result", {"status": "done", "summary": "interrupted"}) + return # needs_input asks once; with the user's answer in context.hint the same step finishes if mode == "needs_input" and not params.get("context", {}).get("hint"): note("hx/step_result", {"status": "needs_input", "question": "Which provider?"})