Files
orch/src/view.rs
T
johannesandClaude Sonnet 5.5 cfb735cdb3 TUI hosts sessions: new-session form, named worktrees, resume, faster permissions
- Use the terminal's own colors and background; the key bar and the Needs-you
  panel wrap, fixed-width panels shrink on narrow terminals.
- Sessions run on threads of the TUI (tui/host.rs), capped by the profile's
  `workers`; quitting asks for `yes` and suspends them. New `suspend` command
  keeps the state so a session can be resumed.
- `N` opens a new-session form: machine, name, --after, a named branch or
  worktree (place.rs; never deleted by orch), and a "keep for a PR" option.
- `u` resumes suspended sessions and ones whose process died.
- `A` allows identical permission requests across sessions, `P` saves an allow
  rule to the profile with toml_edit (comments kept).
- Fix clippy lint in report.rs so tests/all.sh passes; add GLOSSARY.md.

Includes the already staged `orch init` work (init.rs, example profile).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 18:04:41 +01:00

721 lines
22 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Pure view models: sessions, tasks, events and machine files in, what a screen shows out (ORCHESTRATOR.md
//! principle 3: no panel computes state on its own). No terminal and no database in here, so it is easy to test.
use crate::db::{Event, Session, Task};
use crate::machine::Machine;
use std::collections::HashMap;
/// Overview status column. `Fail` is not in the spec's list; a failed or aborted session needs some label.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Status {
Run,
Fix,
Wait,
Blocked,
Done,
Fail,
}
impl Status {
pub fn label(self) -> &'static str {
match self {
Status::Run => "RUN",
Status::Fix => "FIX",
Status::Wait => "WAIT",
Status::Blocked => "BLOCKED",
Status::Done => "DONE",
Status::Fail => "FAIL",
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Mark {
Done,
Active,
Failed,
Waiting,
Todo,
}
#[derive(Clone, PartialEq, Debug)]
pub struct Chip {
pub name: String,
pub mark: Mark,
}
#[derive(Clone, PartialEq, Debug)]
pub struct Row {
pub id: String,
pub status: Status,
pub task: String,
pub sub: String,
pub machine: String,
pub chips: Vec<Chip>,
/// `↻ 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<bool>,
pub added: u32,
pub removed: u32,
/// Context used, percent.
pub ctx: Option<u8>,
pub last: String,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum NeedKind {
/// A `human` step (review gate): approve or send back with a comment.
Review,
/// hx asks to run a tool: allow once, always, or deny.
Permission,
/// hx asks a question: reply with text.
Input,
/// The session ended in `escalated`. Derived from the session, nothing to answer in the queue.
Escalated,
}
/// One item of the Needs-you box.
#[derive(Clone, PartialEq, Debug)]
pub struct Need {
/// Row id in the `needs` table; 0 for derived items.
pub id: i64,
pub kind: NeedKind,
pub session: String,
pub task: String,
/// `review ready`, `permission`, `question`, `escalated`.
pub what: String,
pub detail: String,
pub age_secs: u64,
}
impl Need {
/// The key line under the item, like `[y] allow once [Y] always for s4 [A] all same [n] deny`.
pub fn keys(&self) -> String {
match self.kind {
NeedKind::Review => "[a] approve [d] open diff [c] comment back".into(),
NeedKind::Permission => format!(
"[y] allow once [Y] always for {} [A] all same [n] deny",
self.session
),
NeedKind::Input => "[r] reply".into(),
NeedKind::Escalated => String::new(),
}
}
}
#[derive(Clone, PartialEq, Debug)]
pub struct EventLine {
pub id: i64,
pub at_ms: u64,
pub session: String,
pub kind: String,
pub text: String,
}
#[derive(Clone, Default, PartialEq, Debug)]
pub struct Overview {
pub goal: String,
/// Unfinished sessions nobody runs (suspended, or their process died): `u` resumes them.
pub resumable: usize,
pub rows: Vec<Row>,
pub needs: Vec<Need>,
pub events: Vec<EventLine>,
pub merged: usize,
pub total: usize,
/// (passing, total) acceptance checks; None until checks exist (milestone 7).
pub checks: Option<(usize, usize)>,
pub running: usize,
pub waiting: usize,
pub blocked: usize,
pub cost: f64,
pub elapsed_secs: u64,
}
pub struct Input<'a> {
pub goal: Option<&'a str>,
pub tasks: &'a [Task],
pub sessions: &'a [Session],
/// All events, oldest first.
pub events: &'a [Event],
/// Loaded machine files by name; a missing one only costs the strip.
pub machines: &'a HashMap<String, Machine>,
/// Unanswered items of the Needs-you queue, oldest first.
pub needs: &'a [crate::db::NeedRow],
/// Acceptance checks with their last result on main.
pub checks: &'a [crate::db::CheckRow],
pub decisions: &'a [crate::db::DecisionRow],
pub now_ms: u64,
}
pub fn build(i: &Input) -> Overview {
let mut by_session: HashMap<&str, Vec<&Event>> = HashMap::new();
for e in i.events {
by_session.entry(e.session.as_str()).or_default().push(e);
}
let none = vec![];
let mut o = Overview {
goal: i.goal.unwrap_or_default().to_string(),
total: i.tasks.len(),
..Default::default()
};
let name_of = |sid: &str| {
i.tasks
.iter()
.find(|t| t.id == sid)
.map_or_else(String::new, |t| t.name.clone())
};
let mut escalated = vec![];
for n in i.needs {
let Some(task) = i
.sessions
.iter()
.find(|s| s.id == n.session)
.and_then(|s| i.tasks.iter().find(|t| t.id == s.task_id))
else {
continue;
};
let text = |k: &str| n.payload[k].as_str().unwrap_or_default().to_string();
o.needs.push(Need {
id: n.id,
kind: match n.kind.as_str() {
"permission" => NeedKind::Permission,
"input" => NeedKind::Input,
_ => NeedKind::Review,
},
session: n.session.clone(),
task: task.name.clone(),
what: text("title"),
detail: text("detail"),
age_secs: i.now_ms.saturating_sub(n.at) / 1000,
});
}
for s in i.sessions {
let Some(task) = i.tasks.iter().find(|t| t.id == s.task_id) else {
continue;
};
let evs = by_session.get(s.id.as_str()).unwrap_or(&none);
let machine = i.machines.get(&task.machine);
let scan = scan(evs, s, machine);
let unmet = task.depends_on.iter().find(|d| {
i.sessions
.iter()
.find(|x| &x.id == *d)
.is_none_or(|x| x.status != "merged")
});
let status = match s.status.as_str() {
"merged" | "done" => Status::Done,
"failed" | "aborted" => Status::Fail,
"waiting" | "escalated" | "suspended" => Status::Wait,
"queued" if unmet.is_some() => Status::Blocked,
_ if !scan.retry.is_empty() => Status::Fix,
_ => Status::Run,
};
let last = match (status, unmet) {
(Status::Blocked, Some(d)) => format!("waits on {d} {}", name_of(d)),
(Status::Done, _) => {
let at = evs.last().map_or(0, |e| e.at);
format!(
"{} · {} ago",
s.status,
ago(i.now_ms.saturating_sub(at) / 1000)
)
}
_ => evs.last().map_or_else(String::new, |e| describe(e)),
};
if s.status == "escalated" {
let end = evs.iter().rev().find(|e| e.kind == "end");
escalated.push(Need {
id: 0,
kind: NeedKind::Escalated,
session: s.id.clone(),
task: task.name.clone(),
what: "escalated".into(),
detail: end
.and_then(|e| e.payload["reason"].as_str().map(String::from))
.unwrap_or_default(),
age_secs: end.map_or(0, |e| i.now_ms.saturating_sub(e.at) / 1000),
});
}
match status {
Status::Run | Status::Fix => o.running += 1,
Status::Wait => o.waiting += 1,
Status::Blocked => o.blocked += 1,
Status::Done => o.merged += 1,
Status::Fail => {}
}
o.cost += scan.cost;
o.rows.push(Row {
id: s.id.clone(),
status,
task: task.name.clone(),
sub: task.subtitle.clone(),
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,
removed: scan.removed,
ctx: scan.ctx,
last,
});
}
o.needs.extend(escalated);
if !i.checks.is_empty() {
let green = i
.checks
.iter()
.filter(|c| c.last_status.as_deref() == Some("pass"))
.count();
o.checks = Some((green, i.checks.len()));
}
o.events = i
.events
.iter()
.map(|e| EventLine {
id: e.id,
at_ms: e.at,
session: e.session.clone(),
kind: e.kind.clone(),
text: line_text(e),
})
.collect();
o.elapsed_secs = i
.events
.first()
.map_or(0, |e| i.now_ms.saturating_sub(e.at) / 1000);
o
}
struct Scan {
chips: Vec<Chip>,
retry: String,
looping: bool,
tests: (String, Option<bool>),
added: u32,
removed: u32,
ctx: Option<u8>,
cost: f64,
}
/// One pass over a session's events. Strip marks: a state that was left through a catch is failed, one left
/// normally is done, the state the session is in is active.
fn scan(evs: &[&Event], s: &Session, machine: Option<&Machine>) -> Scan {
let mut marks: HashMap<String, Mark> = HashMap::new();
let mut cur = String::new();
let mut pending_fail: Option<String> = None;
// (state, catch) the session is recovering from; cleared once that state passes again
let mut recovering: Option<(String, String)> = None;
let mut sc = Scan {
chips: vec![],
retry: String::new(),
looping: false,
tests: ("—".into(), None),
added: 0,
removed: 0,
ctx: None,
cost: 0.0,
};
for e in evs {
let p = &e.payload;
match e.kind.as_str() {
"catch" => {
let (st, c) = (str_of(p, "state"), str_of(p, "catch"));
pending_fail = Some(st.clone());
recovering = Some((st, c));
}
"state" => {
let (from, to) = (str_of(p, "from"), str_of(p, "to"));
if !from.is_empty() {
let failed = pending_fail.as_deref() == Some(from.as_str());
marks.insert(from.clone(), if failed { Mark::Failed } else { Mark::Done });
if !failed && recovering.as_ref().is_some_and(|(r, _)| *r == from) {
recovering = None;
}
}
pending_fail = None;
marks.insert(to.clone(), Mark::Active);
cur = to;
}
"end" => {
let ok = p["status"].as_str().is_some_and(|x| x != "failed");
marks.insert(cur.clone(), if ok { Mark::Done } else { Mark::Failed });
}
"test" => {
let (pass, fail) = (
p["passed"].as_u64().unwrap_or(0),
p["failed"].as_u64().unwrap_or(0),
);
let total = pass + fail;
sc.tests = if fail > 0 {
(format!("{pass}/{total} ✗{fail}"), Some(false))
} else {
(format!("{pass}/{total} ✓"), Some(true))
};
}
"edit" => {
sc.added += p["added"].as_u64().unwrap_or(0) as u32;
sc.removed += p["removed"].as_u64().unwrap_or(0) as u32;
}
"usage" => {
let (used, limit) = (
p["ctx_used"].as_u64().unwrap_or(0),
p["ctx_limit"].as_u64().unwrap_or(0),
);
if let Some(pct) = (used * 100).checked_div(limit) {
sc.ctx = Some(pct.min(100) as u8);
}
sc.cost = p["cost"].as_f64().unwrap_or(sc.cost);
}
_ => {}
}
}
if s.status == "waiting"
&& let Some(m) = marks.get_mut(&cur)
{
*m = Mark::Waiting;
}
if let Some(m) = machine {
sc.chips = m
.strip()
.map(|st| Chip {
name: st.name.clone(),
mark: marks.get(&st.name).copied().unwrap_or(Mark::Todo),
})
.collect();
if s.status == "running"
&& let Some((st, c)) = &recovering
{
let n = evs
.iter()
.filter(|e| {
e.kind == "catch"
&& str_of(&e.payload, "state") == *st
&& str_of(&e.payload, "catch") == *c
})
.count();
sc.retry = match m.state(st).and_then(|x| x.retry.get(c)) {
Some(r) => format!("↻ fix {n}/{}", r.max),
None => format!("↻ fix {n}"),
};
}
}
sc.looping =
matches!(s.status.as_str(), "running" | "waiting") && crate::budget::looping(evs).is_some();
sc
}
fn str_of(p: &serde_json::Value, k: &str) -> String {
p[k].as_str().unwrap_or_default().to_string()
}
/// Short text for the "last activity" column.
fn describe(e: &Event) -> String {
let p = &e.payload;
match e.kind.as_str() {
"state" => format!("entered {}", str_of(p, "to")),
"step" if p["ok"] == true => format!(
"{} · {}",
str_of(p, "step"),
secs(p["ms"].as_u64().unwrap_or(0))
),
"step" => format!("{} failed", str_of(p, "step")),
"catch" => format!("{} ✗ {}", str_of(p, "state"), str_of(p, "catch")),
"end" => format!("ended: {}", str_of(p, "status")),
"resume" => "resumed".into(),
"status" => str_of(p, "label"),
"intent" => str_of(p, "text"),
"tool" => str_of(p, "title"),
k => k.to_string(),
}
}
/// Text of one line in the events box.
fn line_text(e: &Event) -> String {
let p = &e.payload;
match e.kind.as_str() {
"state" if str_of(p, "from").is_empty() => format!("start {}", str_of(p, "to")),
"state" => format!("{} → {}", str_of(p, "from"), str_of(p, "to")),
"step" => {
let res = if p["ok"] == true {
"ok".to_string()
} else {
format!("exit {}", p["exit"])
};
format!(
"{}/{} → {res} ({})",
str_of(p, "state"),
str_of(p, "step"),
secs(p["ms"].as_u64().unwrap_or(0))
)
}
"catch" => format!("{} ✗ {}", str_of(p, "state"), str_of(p, "catch")),
"end" => match p["reason"].as_str() {
Some(r) => format!("ended: {} ({r})", str_of(p, "status")),
None => format!("ended: {}", str_of(p, "status")),
},
"status" => format!("■ {}", str_of(p, "label")),
"resume" => format!("resumed in {}", str_of(p, "state")),
"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"]
.as_str()
.map_or_else(|| e.kind.clone(), String::from),
}
}
fn secs(ms: u64) -> String {
if ms < 10_000 {
format!("{:.1}s", ms as f64 / 1000.0)
} else {
format!("{}s", ms / 1000)
}
}
pub fn ago(secs: u64) -> String {
match secs {
0..60 => format!("{secs}s"),
60..3600 => format!("{}m", secs / 60),
_ => format!("{}h", secs / 3600),
}
}
/// Local wall-clock time `HH:MM:SS` of a millisecond timestamp.
pub fn hms(ms: u64) -> String {
let t = (ms / 1000) as libc::time_t;
// SAFETY: localtime_r writes into our zeroed tm and reads t; no shared state.
let tm = unsafe {
let mut tm: libc::tm = std::mem::zeroed();
libc::localtime_r(&t, &mut tm);
tm
};
format!("{:02}:{:02}:{:02}", tm.tm_hour, tm.tm_min, tm.tm_sec)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn session(id: &str, task: &str, state: &str, status: &str) -> Session {
Session {
id: id.into(),
task_id: task.into(),
branch: "b".into(),
worktree: "/w".into(),
pid: None,
state: state.into(),
status: status.into(),
}
}
fn task(id: &str, name: &str, deps: &[&str]) -> Task {
Task {
id: id.into(),
name: name.into(),
subtitle: "sub".into(),
machine: "task".into(),
depends_on: deps.iter().map(|d| d.to_string()).collect(),
}
}
fn ev(id: i64, s: &str, kind: &str, payload: serde_json::Value) -> Event {
Event {
id,
session: s.into(),
at: 1_000 * id as u64,
kind: kind.into(),
payload,
}
}
fn machines() -> HashMap<String, Machine> {
let text = include_str!("../examples/machines/task.toml");
HashMap::from([("task".into(), Machine::parse(text).unwrap())])
}
fn marks(r: &Row) -> String {
r.chips
.iter()
.map(|c| match c.mark {
Mark::Done => 'd',
Mark::Active => 'a',
Mark::Failed => 'f',
Mark::Waiting => 'w',
Mark::Todo => 't',
})
.collect()
}
fn st(id: i64, from: &str, to: &str) -> Event {
ev(id, "s2", "state", json!({"from": from, "to": to}))
}
#[test]
fn fix_loop_marks_and_label() {
// plan -> code -> build -> test fails -> code (fix 1 of 3)
let events = vec![
st(1, "", "plan"),
st(2, "plan", "code"),
st(3, "code", "build"),
st(4, "build", "test"),
ev(5, "s2", "test", json!({"passed": 39, "failed": 2})),
ev(
6,
"s2",
"catch",
json!({"state": "test", "catch": "TestsFailed"}),
),
st(7, "test", "code"),
ev(
8,
"s2",
"edit",
json!({"path": "a.rs", "added": 6, "removed": 2}),
),
ev(
9,
"s2",
"usage",
json!({"ctx_used": 71, "ctx_limit": 100, "cost": 1.5}),
),
];
let m = machines();
let (tasks, sessions) = (
[task("s2", "oauth", &[])],
[session("s2", "s2", "code", "running")],
);
let o = build(&Input {
goal: Some("g"),
tasks: &tasks,
sessions: &sessions,
events: &events,
machines: &m,
needs: &[],
checks: &[],
decisions: &[],
now_ms: 20_000,
});
let r = &o.rows[0];
// plan done, code active again, build done, test failed, review and merge not reached
assert_eq!(marks(r), "dadftt");
assert_eq!(r.status, Status::Fix);
assert_eq!(r.retry, "↻ fix 1/3");
assert_eq!((r.tests.as_str(), r.tests_ok), ("39/41 ✗2", Some(false)));
assert_eq!((r.added, r.removed, r.ctx), (6, 2, Some(71)));
assert_eq!(o.running, 1);
assert!((o.cost - 1.5).abs() < 1e-9);
assert_eq!(o.elapsed_secs, 19);
assert_eq!(o.events.len(), 9);
assert_eq!(o.events[5].text, "test ✗ TestsFailed");
}
#[test]
fn retry_label_clears_when_the_state_passes() {
let events = vec![
st(1, "", "test"),
ev(
2,
"s2",
"catch",
json!({"state": "test", "catch": "TestsFailed"}),
),
st(3, "test", "code"),
st(4, "code", "build"),
st(5, "build", "test"),
st(6, "test", "review"),
];
let m = machines();
let (tasks, sessions) = (
[task("s2", "t", &[])],
[session("s2", "s2", "review", "running")],
);
let o = build(&Input {
goal: None,
tasks: &tasks,
sessions: &sessions,
events: &events,
machines: &m,
needs: &[],
checks: &[],
decisions: &[],
now_ms: 0,
});
assert_eq!(o.rows[0].retry, "");
assert_eq!(o.rows[0].status, Status::Run);
assert_eq!(marks(&o.rows[0]), "tdddat");
}
#[test]
fn blocked_done_and_wait() {
let events = vec![
ev(1, "s1", "end", json!({"status": "merged", "reason": null})),
ev(
2,
"s3",
"end",
json!({"status": "escalated", "reason": "budget"}),
),
];
let m = machines();
let tasks = [
task("s1", "one", &[]),
task("s2", "two", &["s1", "s3"]),
task("s3", "three", &[]),
];
let sessions = [
session("s1", "s1", "merge", "merged"),
session("s2", "s2", "", "queued"),
session("s3", "s3", "escalated", "escalated"),
];
let o = build(&Input {
goal: None,
tasks: &tasks,
sessions: &sessions,
events: &events,
machines: &m,
needs: &[],
checks: &[],
decisions: &[],
now_ms: 61_000,
});
let s: Vec<_> = o.rows.iter().map(|r| r.status).collect();
assert_eq!(s, [Status::Done, Status::Blocked, Status::Wait]);
assert_eq!(o.rows[1].last, "waits on s3 three");
assert_eq!(o.rows[0].last, "merged · 1m ago");
assert_eq!((o.merged, o.total, o.blocked, o.waiting), (1, 3, 1, 1));
assert_eq!(o.needs.len(), 1);
assert_eq!(
(o.needs[0].session.as_str(), o.needs[0].detail.as_str()),
("s3", "budget")
);
}
#[test]
fn helpers() {
assert_eq!(ago(5), "5s");
assert_eq!(ago(130), "2m");
assert_eq!(ago(7300), "2h");
assert_eq!(secs(1500), "1.5s");
assert_eq!(secs(38_000), "38s");
assert_eq!(hms(0).len(), 8);
}
}