1968 lines
69 KiB
Rust
1968 lines
69 KiB
Rust
//! Terminal UI. Everything on screen comes from the event table and the machine files via `view::build`.
|
||
|
||
mod goal;
|
||
mod host;
|
||
mod newform;
|
||
mod overview;
|
||
mod session;
|
||
mod theme;
|
||
|
||
use crate::db::{Db, Event};
|
||
use crate::detail::{self, Detail};
|
||
use crate::machine::Machine;
|
||
use crate::view::{self, Overview};
|
||
use anyhow::{Result, bail};
|
||
use overview::Header;
|
||
use std::collections::HashMap;
|
||
use std::io::IsTerminal;
|
||
use std::path::{Path, PathBuf};
|
||
use std::time::Duration;
|
||
|
||
pub fn run() -> Result<()> {
|
||
if !std::io::stdout().is_terminal() {
|
||
bail!("orch needs a terminal; use a subcommand (orch --help) in scripts");
|
||
}
|
||
let mut app = App::new(std::env::current_dir()?);
|
||
let mut term = ratatui::init();
|
||
let res = event_loop(&mut term, &mut app);
|
||
ratatui::restore();
|
||
res
|
||
}
|
||
|
||
enum Screen {
|
||
Overview,
|
||
/// Session detail for this session id.
|
||
Session(String),
|
||
/// Goal, task graph, decisions, acceptance checks.
|
||
Goal,
|
||
}
|
||
|
||
/// What a key does to the focused Needs-you item.
|
||
#[derive(Debug, PartialEq)]
|
||
enum NeedKey {
|
||
/// Write this answer to the queue.
|
||
Answer(String),
|
||
/// Show the session's diff.
|
||
Diff,
|
||
/// Ask for an allow rule (prefilled with a guess) and save it to the profile.
|
||
AllowRule,
|
||
/// Allow once every pending permission request that asks for the same thing as the focused one.
|
||
AllIdentical,
|
||
/// Ask for a line of text first; the answer is `prefix` + text.
|
||
Prompt {
|
||
label: &'static str,
|
||
prefix: &'static str,
|
||
},
|
||
Nothing,
|
||
}
|
||
|
||
fn need_key(n: &view::Need, c: char) -> NeedKey {
|
||
use view::NeedKind::*;
|
||
let a = |s: &str| NeedKey::Answer(s.into());
|
||
match (n.kind, c) {
|
||
(Review, 'a') => a("approve"),
|
||
(Review, 'd') => NeedKey::Diff,
|
||
(Review, 'c') => NeedKey::Prompt {
|
||
label: "comment",
|
||
prefix: "changes: ",
|
||
},
|
||
(Permission, 'y') => a("allow_once"),
|
||
(Permission, 'Y') => a("allow_always"),
|
||
(Permission, 'A') => NeedKey::AllIdentical,
|
||
(Permission, 'P') => NeedKey::AllowRule,
|
||
(Permission, 'n') => a("deny"),
|
||
(Input, 'r') => NeedKey::Prompt {
|
||
label: "reply",
|
||
prefix: "reply: ",
|
||
},
|
||
_ => NeedKey::Nothing,
|
||
}
|
||
}
|
||
|
||
/// The profile `P` and the host use; the TUI has no profile choice yet.
|
||
const PROFILE: &str = "default";
|
||
|
||
/// A first guess for the allow rule of a permission request ("wants to run TOOL"): hx sends a free-text title, so
|
||
/// a known tool name (first word) becomes that tool, anything else is taken as a bash command.
|
||
fn suggest_rule(detail: &str) -> String {
|
||
const TOOLS: [&str; 11] = [
|
||
"read",
|
||
"write",
|
||
"edit",
|
||
"bash",
|
||
"lsp",
|
||
"grep",
|
||
"glob",
|
||
"ls",
|
||
"readonly",
|
||
"webfetch",
|
||
"websearch",
|
||
];
|
||
let title = detail
|
||
.strip_prefix("wants to run ")
|
||
.unwrap_or(detail)
|
||
.trim();
|
||
let first = title.split_whitespace().next().unwrap_or_default();
|
||
match TOOLS.iter().find(|t| t.eq_ignore_ascii_case(first)) {
|
||
Some(t) => (*t).to_string(),
|
||
None => format!("bash:{title}"),
|
||
}
|
||
}
|
||
|
||
/// What a finished input line is for.
|
||
#[derive(Clone, PartialEq, Debug)]
|
||
enum Target {
|
||
/// Answer to this Needs-you item.
|
||
Need(i64),
|
||
/// New goal sentence.
|
||
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),
|
||
/// The allow rule for this permission request; saved to the profile, then the request is allowed.
|
||
AllowRule(i64),
|
||
/// Quit and suspend the hosted sessions, but only when the text is `yes`.
|
||
Quit,
|
||
}
|
||
|
||
/// A one-line text entry shown at the bottom while the user writes a comment, reply, goal or check.
|
||
struct InputLine {
|
||
label: &'static str,
|
||
prefix: &'static str,
|
||
target: Target,
|
||
text: String,
|
||
}
|
||
|
||
/// `name | command | owner` -> (name, command, owner)
|
||
fn parse_check(s: &str) -> Option<(String, String, Option<String>)> {
|
||
let mut p = s.split('|').map(str::trim);
|
||
let (name, cmd) = (p.next()?, p.next()?);
|
||
let owner = p.next().filter(|o| !o.is_empty()).map(String::from);
|
||
(!name.is_empty() && !cmd.is_empty()).then(|| (name.into(), cmd.into(), owner))
|
||
}
|
||
|
||
/// A scrollable text overlay: full test output, diff, agent transcript.
|
||
struct Pager {
|
||
title: String,
|
||
lines: Vec<String>,
|
||
scroll: usize,
|
||
}
|
||
|
||
struct App {
|
||
repo: PathBuf,
|
||
/// Opened lazily: launching `orch` in a directory without a goal must not create `.hx/orch.db`.
|
||
db: Option<Db>,
|
||
events: Vec<Event>,
|
||
machines: HashMap<String, Machine>,
|
||
overview: Overview,
|
||
rev: String,
|
||
sel: usize,
|
||
screen: Screen,
|
||
detail: Option<Detail>,
|
||
pager: Option<Pager>,
|
||
/// Focused item of the Needs-you box.
|
||
need_sel: usize,
|
||
input: Option<InputLine>,
|
||
goal_view: Option<crate::goal::GoalView>,
|
||
/// Selected decision on the goal screen.
|
||
dec_sel: usize,
|
||
/// True while a background `run all checks` is going.
|
||
checks_running: std::sync::Arc<std::sync::atomic::AtomicBool>,
|
||
/// Runs the sessions started from this TUI; created with the first one.
|
||
host: Option<host::Host>,
|
||
/// Set by a confirmed quit; the event loop leaves when it sees it.
|
||
quit: bool,
|
||
/// The new-session form while it is open.
|
||
form: Option<newform::Form>,
|
||
}
|
||
|
||
impl App {
|
||
fn ensure_host(&mut self) -> Result<&mut host::Host> {
|
||
if self.host.is_none() {
|
||
let profile = crate::profile::Profile::load(PROFILE)?;
|
||
self.host = Some(host::Host::new(self.repo.clone(), profile));
|
||
}
|
||
Ok(self.host.as_mut().expect("just created"))
|
||
}
|
||
|
||
/// `u`: hands every resumable session to the host. Returns how many; the error is a broken profile.
|
||
fn resume_all(&mut self) -> Result<usize> {
|
||
let Some(db) = &self.db else { return Ok(0) };
|
||
let ids = host::resumable(db);
|
||
let host = self.ensure_host()?;
|
||
let ids: Vec<String> = ids.into_iter().filter(|id| !host.hosts(id)).collect();
|
||
for id in &ids {
|
||
host.submit(id);
|
||
}
|
||
self.refresh();
|
||
Ok(ids.len())
|
||
}
|
||
|
||
/// Creates a session row from the form and hands it to the host, which runs it as soon as a slot is free.
|
||
/// Any problem (no machine, broken machine file, worktree in use) comes back as the error to show in the form.
|
||
fn start_session(&mut self, f: &newform::Form) -> Result<String> {
|
||
let name = f.name.trim();
|
||
if name.is_empty() {
|
||
bail!("give the session a name");
|
||
}
|
||
let Some(machine) = f.machine() else {
|
||
bail!("no machine to run");
|
||
};
|
||
Machine::find(machine, &self.repo)?;
|
||
let after: Vec<String> = f
|
||
.after
|
||
.split([',', ' '])
|
||
.filter(|s| !s.is_empty())
|
||
.map(String::from)
|
||
.collect();
|
||
let place = crate::place::resolve(&self.repo, &f.place)?;
|
||
self.ensure_host()?;
|
||
self.db_or_create();
|
||
let db = self.db.as_ref().expect("db_or_create opened it");
|
||
let base = self.repo.file_name().unwrap_or_default();
|
||
let wts = crate::state_dir().join("worktrees").join(base);
|
||
let s = crate::runner::create_in(db, &wts, name, machine, &after, &place, f.no_merge)?;
|
||
if let Some(h) = &mut self.host {
|
||
h.submit(&s.id);
|
||
}
|
||
self.refresh();
|
||
Ok(s.id)
|
||
}
|
||
|
||
/// `q` and ctrl-c: quits at once, or asks first while this TUI hosts sessions.
|
||
fn request_quit(&mut self) {
|
||
if self.host.as_ref().is_none_or(|h| h.busy() == 0) {
|
||
self.quit = true;
|
||
} else {
|
||
self.input = Some(InputLine {
|
||
label: "quit suspends this TUI's sessions (continue with u); type yes",
|
||
prefix: "",
|
||
target: Target::Quit,
|
||
text: String::new(),
|
||
});
|
||
}
|
||
}
|
||
|
||
/// Runs every check on main in the background; the goal view shows `running…` meanwhile.
|
||
fn run_all_checks(&mut self) {
|
||
use std::sync::atomic::Ordering;
|
||
if self.checks_running.swap(true, Ordering::SeqCst) {
|
||
return; // already running
|
||
}
|
||
let (repo, flag) = (self.repo.clone(), self.checks_running.clone());
|
||
std::thread::spawn(move || {
|
||
if let Ok(db) = Db::open(&repo.join(".hx/orch.db")) {
|
||
let _ = crate::checks::run_on_main(&db, &repo);
|
||
}
|
||
flag.store(false, Ordering::SeqCst);
|
||
});
|
||
}
|
||
|
||
/// The goal database, created on first use by actions that only make sense with one (edit goal, add check).
|
||
fn db_or_create(&mut self) -> Option<&Db> {
|
||
if self.db.is_none() {
|
||
self.db = Db::open(&self.repo.join(".hx/orch.db")).ok();
|
||
}
|
||
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::AllowRule(id) => {
|
||
let msg = match crate::profile::Profile::add_allow(PROFILE, &text) {
|
||
Ok(added) => {
|
||
self.answer(id, "allow_always");
|
||
format!(
|
||
"{} `{text}` in profile {PROFILE}; it counts for sessions started from now on.",
|
||
if added { "added" } else { "already allowed:" }
|
||
)
|
||
}
|
||
Err(e) => format!("not saved, the request stays open: {e:#}"),
|
||
};
|
||
self.pager = Some(Pager {
|
||
title: "allow rule".into(),
|
||
lines: vec![msg],
|
||
scroll: 0,
|
||
});
|
||
return;
|
||
}
|
||
Target::Quit => {
|
||
self.quit = text == "yes";
|
||
return;
|
||
}
|
||
Target::Goal if !text.is_empty() => {
|
||
if let Some(db) = self.db_or_create() {
|
||
let _ = db.set_goal(&text);
|
||
}
|
||
}
|
||
Target::Check => {
|
||
if let Some((name, cmd, owner)) = parse_check(&text)
|
||
&& let Some(db) = self.db_or_create()
|
||
{
|
||
let _ = db.add_check(&name, &cmd, owner.as_deref());
|
||
}
|
||
}
|
||
Target::Goal => {}
|
||
}
|
||
self.refresh();
|
||
}
|
||
|
||
/// Allows once every pending permission request that asks for the same thing as `n`, in any session.
|
||
fn answer_identical(&mut self, n: &view::Need) {
|
||
let same: Vec<i64> = self
|
||
.overview
|
||
.needs
|
||
.iter()
|
||
.filter(|o| o.kind == n.kind && o.what == n.what && o.detail == n.detail)
|
||
.map(|o| o.id)
|
||
.collect();
|
||
for id in same {
|
||
self.answer(id, "allow_once");
|
||
}
|
||
}
|
||
|
||
/// Writes the user's answer to the queue; the waiting runner picks it up.
|
||
fn answer(&mut self, need: i64, answer: &str) {
|
||
if let Some(db) = &self.db {
|
||
let _ = db.answer_need(need, answer);
|
||
}
|
||
self.refresh();
|
||
}
|
||
|
||
fn new(repo: PathBuf) -> Self {
|
||
let rev = git_rev(&repo);
|
||
Self {
|
||
repo,
|
||
db: None,
|
||
events: vec![],
|
||
machines: HashMap::new(),
|
||
overview: Overview::default(),
|
||
rev,
|
||
sel: 0,
|
||
screen: Screen::Overview,
|
||
detail: None,
|
||
pager: None,
|
||
need_sel: 0,
|
||
input: None,
|
||
goal_view: None,
|
||
dec_sel: 0,
|
||
checks_running: Default::default(),
|
||
host: None,
|
||
quit: false,
|
||
form: None,
|
||
}
|
||
}
|
||
|
||
fn refresh(&mut self) {
|
||
let path = self.repo.join(".hx/orch.db");
|
||
if self.db.is_none() && path.exists() {
|
||
self.db = Db::open(&path).ok();
|
||
}
|
||
if let (Some(h), Some(db)) = (&mut self.host, &self.db) {
|
||
h.tick(db);
|
||
}
|
||
if let Some(db) = &self.db {
|
||
let now = crate::state::now_ms();
|
||
if let Ok(mut o) = snapshot(db, &self.repo, &mut self.events, &mut self.machines, now) {
|
||
let h = self.host.as_ref();
|
||
o.resumable = host::resumable(db)
|
||
.iter()
|
||
.filter(|id| !h.is_some_and(|h| h.hosts(id)))
|
||
.count();
|
||
self.overview = o;
|
||
}
|
||
self.detail = match &self.screen {
|
||
Screen::Session(id) => session_detail(
|
||
db,
|
||
&self.repo,
|
||
&mut self.events,
|
||
&mut self.machines,
|
||
id,
|
||
now,
|
||
)
|
||
.ok()
|
||
.flatten(),
|
||
_ => None,
|
||
};
|
||
self.goal_view = match self.screen {
|
||
Screen::Goal => {
|
||
goal_snapshot(db, &self.repo, &mut self.events, &mut self.machines, now).ok()
|
||
}
|
||
_ => None,
|
||
};
|
||
}
|
||
self.sel = self.sel.min(self.overview.rows.len().saturating_sub(1));
|
||
self.need_sel = self
|
||
.need_sel
|
||
.min(self.overview.needs.len().saturating_sub(1));
|
||
}
|
||
|
||
fn header(&self) -> Header {
|
||
let home = std::env::var("HOME").unwrap_or_default();
|
||
let repo = self.repo.to_string_lossy().into_owned();
|
||
let repo = match repo.strip_prefix(&home) {
|
||
Some(rest) if !home.is_empty() => format!("~{rest}"),
|
||
_ => repo,
|
||
};
|
||
Header {
|
||
repo,
|
||
rev: self.rev.clone(),
|
||
now_ms: crate::state::now_ms(),
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Everything read from the database for one screen update, plus the loaded machine files.
|
||
struct Loaded {
|
||
tasks: Vec<crate::db::Task>,
|
||
sessions: Vec<crate::db::Session>,
|
||
needs: Vec<crate::db::NeedRow>,
|
||
checks: Vec<crate::db::CheckRow>,
|
||
decisions: Vec<crate::db::DecisionRow>,
|
||
goal: Option<String>,
|
||
}
|
||
|
||
/// Reads what is new in the database since the last call and loads missing machine files.
|
||
fn load(
|
||
db: &Db,
|
||
repo: &Path,
|
||
events: &mut Vec<Event>,
|
||
machines: &mut HashMap<String, Machine>,
|
||
) -> Result<Loaded> {
|
||
let last = events.last().map_or(0, |e| e.id);
|
||
events.extend(db.events(None, last)?);
|
||
let (tasks, sessions) = (db.tasks()?, db.sessions()?);
|
||
for t in &tasks {
|
||
if !machines.contains_key(&t.machine)
|
||
&& let Ok(m) = Machine::find(&t.machine, repo)
|
||
{
|
||
machines.insert(t.machine.clone(), m);
|
||
}
|
||
}
|
||
Ok(Loaded {
|
||
tasks,
|
||
sessions,
|
||
needs: db.pending_needs()?,
|
||
checks: db.checks()?,
|
||
decisions: db.decisions()?,
|
||
goal: db.goal()?,
|
||
})
|
||
}
|
||
|
||
fn snapshot(
|
||
db: &Db,
|
||
repo: &Path,
|
||
events: &mut Vec<Event>,
|
||
machines: &mut HashMap<String, Machine>,
|
||
now_ms: u64,
|
||
) -> Result<Overview> {
|
||
let l = load(db, repo, events, machines)?;
|
||
Ok(view::build(&view::Input {
|
||
goal: l.goal.as_deref(),
|
||
tasks: &l.tasks,
|
||
sessions: &l.sessions,
|
||
events,
|
||
machines,
|
||
needs: &l.needs,
|
||
checks: &l.checks,
|
||
decisions: &l.decisions,
|
||
now_ms,
|
||
}))
|
||
}
|
||
|
||
fn goal_snapshot(
|
||
db: &Db,
|
||
repo: &Path,
|
||
events: &mut Vec<Event>,
|
||
machines: &mut HashMap<String, Machine>,
|
||
now_ms: u64,
|
||
) -> Result<crate::goal::GoalView> {
|
||
let l = load(db, repo, events, machines)?;
|
||
Ok(crate::goal::build(&view::Input {
|
||
goal: l.goal.as_deref(),
|
||
tasks: &l.tasks,
|
||
sessions: &l.sessions,
|
||
events,
|
||
machines,
|
||
needs: &l.needs,
|
||
checks: &l.checks,
|
||
decisions: &l.decisions,
|
||
now_ms,
|
||
}))
|
||
}
|
||
|
||
fn session_detail(
|
||
db: &Db,
|
||
repo: &Path,
|
||
events: &mut Vec<Event>,
|
||
machines: &mut HashMap<String, Machine>,
|
||
id: &str,
|
||
now_ms: u64,
|
||
) -> Result<Option<Detail>> {
|
||
let l = load(db, repo, events, machines)?;
|
||
Ok(detail::build(
|
||
&view::Input {
|
||
goal: l.goal.as_deref(),
|
||
tasks: &l.tasks,
|
||
sessions: &l.sessions,
|
||
events,
|
||
machines,
|
||
needs: &l.needs,
|
||
checks: &l.checks,
|
||
decisions: &l.decisions,
|
||
now_ms,
|
||
},
|
||
id,
|
||
))
|
||
}
|
||
|
||
fn git_rev(repo: &Path) -> String {
|
||
let git = |a: &[&str]| crate::run::git(repo, a).map(|s| s.trim().to_string());
|
||
match (
|
||
git(&["rev-parse", "--abbrev-ref", "HEAD"]),
|
||
git(&["rev-parse", "--short", "HEAD"]),
|
||
) {
|
||
(Ok(b), Ok(s)) => format!("{b}@{s}"),
|
||
_ => "no git".into(),
|
||
}
|
||
}
|
||
|
||
fn draw(f: &mut ratatui::Frame, app: &App, header: &Header) {
|
||
match (&app.screen, &app.detail) {
|
||
(Screen::Session(_), Some(d)) => session::draw(f, d, header),
|
||
(Screen::Goal, _) => {
|
||
let empty;
|
||
let g = match &app.goal_view {
|
||
Some(g) => g,
|
||
None => {
|
||
empty = crate::goal::GoalView::default();
|
||
&empty
|
||
}
|
||
};
|
||
let running = app.checks_running.load(std::sync::atomic::Ordering::SeqCst);
|
||
goal::draw(f, g, header, running, app.dec_sel);
|
||
}
|
||
_ => overview::draw(f, &app.overview, header, app.sel, app.need_sel),
|
||
}
|
||
if let Some(p) = &app.pager {
|
||
draw_pager(f, p);
|
||
}
|
||
if let Some(form) = &app.form {
|
||
newform::draw(f, form);
|
||
}
|
||
if let Some(i) = &app.input {
|
||
draw_input(f, i);
|
||
}
|
||
}
|
||
|
||
/// One bordered line at the bottom: ` comment › text▏`.
|
||
fn draw_input(f: &mut ratatui::Frame, i: &InputLine) {
|
||
use ratatui::text::{Line, Span};
|
||
use ratatui::widgets::{Block, Clear, Paragraph};
|
||
let a = f.area();
|
||
let area = ratatui::layout::Rect::new(
|
||
a.x + 2,
|
||
a.bottom().saturating_sub(4),
|
||
a.width.saturating_sub(4),
|
||
3,
|
||
);
|
||
f.render_widget(Clear, area);
|
||
let block = Block::bordered()
|
||
.border_style(theme::fg(theme::WAIT))
|
||
.title(Span::styled(
|
||
" enter send · esc cancel ",
|
||
theme::fg(theme::DIM),
|
||
));
|
||
let inner = block.inner(area);
|
||
f.render_widget(block, area);
|
||
f.render_widget(
|
||
Paragraph::new(Line::from(vec![
|
||
Span::styled(format!(" {} › ", i.label), theme::fg(theme::WAIT)),
|
||
Span::raw(i.text.clone()),
|
||
Span::styled("▏", theme::fg(theme::RUN)),
|
||
])),
|
||
inner,
|
||
);
|
||
}
|
||
|
||
fn draw_pager(f: &mut ratatui::Frame, p: &Pager) {
|
||
use ratatui::style::Style;
|
||
use ratatui::text::{Line, Span};
|
||
use ratatui::widgets::{Block, Clear, Paragraph};
|
||
let area = f.area().inner(ratatui::layout::Margin::new(2, 1));
|
||
f.render_widget(Clear, area);
|
||
let hint = format!(
|
||
" {} · {}/{} · j/k scroll · esc close ",
|
||
p.title,
|
||
(p.scroll + 1).min(p.lines.len().max(1)),
|
||
p.lines.len().max(1)
|
||
);
|
||
let block = Block::bordered()
|
||
.border_style(theme::fg(theme::RUN))
|
||
.title(Span::styled(hint, theme::bold(theme::TEXT)))
|
||
.style(Style::new().bg(theme::BG));
|
||
let inner = block.inner(area);
|
||
f.render_widget(block, area);
|
||
let lines: Vec<Line> = p
|
||
.lines
|
||
.iter()
|
||
.skip(p.scroll)
|
||
.take(inner.height as usize)
|
||
.map(|l| {
|
||
let color = if l.starts_with("+++") || l.starts_with("---") || l.starts_with("diff ") {
|
||
theme::DIM
|
||
} else if l.starts_with('+') {
|
||
theme::OK
|
||
} else if l.starts_with('-') {
|
||
theme::ERR
|
||
} else if l.starts_with("@@") {
|
||
theme::RUN
|
||
} else {
|
||
theme::TEXT
|
||
};
|
||
Line::from(Span::styled(l.clone(), theme::fg(color)))
|
||
})
|
||
.collect();
|
||
f.render_widget(Paragraph::new(lines), inner);
|
||
}
|
||
|
||
fn lines_of(text: &str) -> Vec<String> {
|
||
text.lines().map(|l| l.replace('\t', " ")).collect()
|
||
}
|
||
|
||
/// Output of the last test step (the whole tail kept in the event), else of the last failed step.
|
||
fn test_output(app: &App, id: &str) -> Pager {
|
||
let mine = || app.events.iter().rev().filter(|e| e.session == id);
|
||
let step_name = mine()
|
||
.find(|e| e.kind == "test")
|
||
.and_then(|e| e.payload["step"].as_str());
|
||
let found = mine().find(|e| {
|
||
e.kind == "step"
|
||
&& match step_name {
|
||
Some(n) => e.payload["step"] == n,
|
||
None => e.payload["ok"] == false,
|
||
}
|
||
});
|
||
let (title, text) = match found {
|
||
Some(e) => (
|
||
format!("output of {}", e.payload["step"].as_str().unwrap_or("step")),
|
||
e.payload["output"].as_str().unwrap_or_default().to_string(),
|
||
),
|
||
None => ("test output".into(), "no test or failed step yet".into()),
|
||
};
|
||
Pager {
|
||
title,
|
||
lines: lines_of(&text),
|
||
scroll: 0,
|
||
}
|
||
}
|
||
|
||
fn diff_of(worktree: &str) -> Pager {
|
||
let git = |a: &[&str]| crate::run::git(Path::new(worktree), a);
|
||
let mut text = String::new();
|
||
match git(&["status", "--short"]) {
|
||
Ok(s) if !s.trim().is_empty() => text.push_str(&format!("{s}\n")),
|
||
Ok(_) => {}
|
||
Err(e) => text.push_str(&format!("{e:#}\n")),
|
||
}
|
||
match git(&["diff", "HEAD"]) {
|
||
Ok(s) if s.trim().is_empty() && text.is_empty() => text.push_str("no changes yet"),
|
||
Ok(s) => text.push_str(&s),
|
||
Err(e) => text.push_str(&format!("{e:#}")),
|
||
}
|
||
Pager {
|
||
title: "diff".into(),
|
||
lines: lines_of(&text),
|
||
scroll: 0,
|
||
}
|
||
}
|
||
|
||
fn transcript(app: &App, id: &str) -> Pager {
|
||
let lines = app
|
||
.overview
|
||
.events
|
||
.iter()
|
||
.filter(|e| e.session == id)
|
||
.map(|e| format!("{} {:<10} {}", view::hms(e.at_ms), e.kind, e.text))
|
||
.collect();
|
||
Pager {
|
||
title: format!("{id} events"),
|
||
lines,
|
||
scroll: 0,
|
||
}
|
||
}
|
||
|
||
/// Opens hx on the session's conversation in the worktree: the TUI steps aside for the time hx runs.
|
||
fn open_in_hx(
|
||
term: &mut ratatui::DefaultTerminal,
|
||
worktree: &str,
|
||
session: &str,
|
||
) -> Option<String> {
|
||
let hx = crate::profile::Profile::load("default").map_or_else(|_| "hx".into(), |p| p.hx);
|
||
let mut parts = hx.split_whitespace();
|
||
let mut cmd = std::process::Command::new(parts.next()?);
|
||
cmd.args(parts)
|
||
.args(["--session", session])
|
||
.current_dir(worktree);
|
||
ratatui::restore();
|
||
let res = cmd.status();
|
||
*term = ratatui::init();
|
||
res.err().map(|e| format!("could not start {hx}: {e}"))
|
||
}
|
||
|
||
/// Handles one key; returns true to quit.
|
||
fn on_key(
|
||
app: &mut App,
|
||
term: &mut ratatui::DefaultTerminal,
|
||
k: crossterm::event::KeyEvent,
|
||
) -> Result<bool> {
|
||
use crossterm::event::{KeyCode, KeyModifiers};
|
||
if k.code == KeyCode::Char('c') && k.modifiers.contains(KeyModifiers::CONTROL) {
|
||
app.request_quit();
|
||
return Ok(app.quit);
|
||
}
|
||
if let Some(mut form) = app.form.take() {
|
||
match form.key(k) {
|
||
newform::Outcome::Open => app.form = Some(form),
|
||
newform::Outcome::Cancel => {}
|
||
newform::Outcome::Submit => match app.start_session(&form) {
|
||
Ok(id) => {
|
||
if let Some(i) = app.overview.rows.iter().position(|r| r.id == id) {
|
||
app.sel = i;
|
||
}
|
||
}
|
||
Err(e) => {
|
||
form.error = Some(format!("{e:#}"));
|
||
app.form = Some(form);
|
||
}
|
||
},
|
||
}
|
||
return Ok(false);
|
||
}
|
||
if let Some(i) = &mut app.input {
|
||
match k.code {
|
||
KeyCode::Esc => app.input = None,
|
||
KeyCode::Backspace => {
|
||
i.text.pop();
|
||
}
|
||
KeyCode::Char(c) => i.text.push(c),
|
||
KeyCode::Enter => {
|
||
if let Some(done) = app.input.take() {
|
||
app.submit(done);
|
||
}
|
||
}
|
||
_ => {}
|
||
}
|
||
return Ok(false);
|
||
}
|
||
if let Some(p) = &mut app.pager {
|
||
let max = p.lines.len().saturating_sub(1);
|
||
match k.code {
|
||
KeyCode::Esc | KeyCode::Char('q') => p.scroll = usize::MAX, // closed below
|
||
KeyCode::Char('j') | KeyCode::Down => p.scroll = (p.scroll + 1).min(max),
|
||
KeyCode::Char('k') | KeyCode::Up => p.scroll = p.scroll.saturating_sub(1),
|
||
KeyCode::PageDown | KeyCode::Char(' ') => p.scroll = (p.scroll + 20).min(max),
|
||
KeyCode::PageUp => p.scroll = p.scroll.saturating_sub(20),
|
||
KeyCode::Char('g') | KeyCode::Home => p.scroll = 0,
|
||
KeyCode::Char('G') | KeyCode::End => p.scroll = max,
|
||
_ => {}
|
||
}
|
||
if p.scroll == usize::MAX {
|
||
app.pager = None;
|
||
}
|
||
return Ok(false);
|
||
}
|
||
match &app.screen {
|
||
Screen::Overview => {
|
||
let last = app.overview.rows.len().saturating_sub(1);
|
||
match k.code {
|
||
KeyCode::Char('q') => {
|
||
app.request_quit();
|
||
return Ok(app.quit);
|
||
}
|
||
KeyCode::Char('j') | KeyCode::Down => app.sel = (app.sel + 1).min(last),
|
||
KeyCode::Char('k') | KeyCode::Up => app.sel = app.sel.saturating_sub(1),
|
||
KeyCode::Enter => {
|
||
if let Some(r) = app.overview.rows.get(app.sel) {
|
||
app.screen = Screen::Session(r.id.clone());
|
||
app.refresh();
|
||
}
|
||
}
|
||
KeyCode::Tab => {
|
||
let n = app.overview.needs.len().max(1);
|
||
app.need_sel = (app.need_sel + 1) % n;
|
||
}
|
||
KeyCode::Char('g') => {
|
||
app.screen = Screen::Goal;
|
||
app.refresh();
|
||
}
|
||
KeyCode::Char('N') => app.form = Some(newform::Form::new(&app.repo)),
|
||
KeyCode::Char('u') if app.overview.resumable > 0 => {
|
||
if let Err(e) = app.resume_all() {
|
||
app.pager = Some(Pager {
|
||
title: "resume".into(),
|
||
lines: vec![format!("{e:#}")],
|
||
scroll: 0,
|
||
});
|
||
}
|
||
}
|
||
// every other letter acts on the focused Needs-you item
|
||
KeyCode::Char(c) => {
|
||
if let Some(n) = app.overview.needs.get(app.need_sel).cloned() {
|
||
match need_key(&n, c) {
|
||
NeedKey::Answer(a) => app.answer(n.id, &a),
|
||
NeedKey::AllIdentical => app.answer_identical(&n),
|
||
NeedKey::AllowRule => {
|
||
app.input = Some(InputLine {
|
||
label: "allow rule",
|
||
prefix: "",
|
||
target: Target::AllowRule(n.id),
|
||
text: suggest_rule(&n.detail),
|
||
});
|
||
}
|
||
NeedKey::Diff => {
|
||
let wt = app
|
||
.db
|
||
.as_ref()
|
||
.and_then(|db| db.session(&n.session).ok().flatten());
|
||
if let Some(s) = wt {
|
||
app.pager = Some(diff_of(&s.worktree));
|
||
}
|
||
}
|
||
NeedKey::Prompt { label, prefix } => {
|
||
app.input = Some(InputLine {
|
||
label,
|
||
prefix,
|
||
target: Target::Need(n.id),
|
||
text: String::new(),
|
||
});
|
||
}
|
||
NeedKey::Nothing => {}
|
||
}
|
||
}
|
||
}
|
||
_ => {}
|
||
}
|
||
}
|
||
Screen::Goal => match k.code {
|
||
KeyCode::Esc | KeyCode::Char('q') => {
|
||
app.screen = Screen::Overview;
|
||
app.goal_view = None;
|
||
}
|
||
KeyCode::Char('e') => {
|
||
let current = app.db.as_ref().and_then(|d| d.goal().ok().flatten());
|
||
app.input = Some(InputLine {
|
||
label: "goal",
|
||
prefix: "",
|
||
target: Target::Goal,
|
||
text: current.unwrap_or_default(),
|
||
});
|
||
}
|
||
KeyCode::Char('+') => {
|
||
app.input = Some(InputLine {
|
||
label: "check: name | command | owner (optional)",
|
||
prefix: "",
|
||
target: Target::Check,
|
||
text: String::new(),
|
||
});
|
||
}
|
||
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) => {
|
||
let id = id.clone();
|
||
match k.code {
|
||
KeyCode::Esc | KeyCode::Char('q') => {
|
||
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') => {
|
||
if let Some(d) = &app.detail {
|
||
app.pager = Some(diff_of(&d.worktree));
|
||
}
|
||
}
|
||
KeyCode::Char('o') => {
|
||
if let Some(d) = &app.detail
|
||
&& let Some(err) = open_in_hx(term, &d.worktree.clone(), &d.id.clone())
|
||
{
|
||
app.pager = Some(Pager {
|
||
title: "open worktree".into(),
|
||
lines: vec![err],
|
||
scroll: 0,
|
||
});
|
||
}
|
||
}
|
||
_ => {}
|
||
}
|
||
}
|
||
}
|
||
Ok(false)
|
||
}
|
||
|
||
fn event_loop(term: &mut ratatui::DefaultTerminal, app: &mut App) -> Result<()> {
|
||
use crossterm::event::{self, Event, KeyEventKind};
|
||
app.refresh();
|
||
loop {
|
||
let header = app.header();
|
||
term.draw(|f| draw(f, app, &header))?;
|
||
if !event::poll(Duration::from_millis(250))? {
|
||
app.refresh();
|
||
continue;
|
||
}
|
||
let Event::Key(k) = event::read()? else {
|
||
continue;
|
||
};
|
||
let quit = k.kind == KeyEventKind::Press && on_key(app, term, k)?;
|
||
if quit || app.quit {
|
||
if let (Some(h), Some(db)) = (&mut app.host, &app.db) {
|
||
h.shutdown(db, Duration::from_secs(10));
|
||
}
|
||
return Ok(());
|
||
}
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
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();
|
||
let h = Header {
|
||
repo: "~/code/api".into(),
|
||
rev: "main@4f2a91c".into(),
|
||
now_ms: 0,
|
||
};
|
||
t.draw(|f| overview::draw(f, o, &h, sel, 1)).unwrap();
|
||
let b = t.backend().buffer();
|
||
let w = b.area.width as usize;
|
||
b.content()
|
||
.chunks(w)
|
||
.map(|r| {
|
||
r.iter()
|
||
.map(|c| c.symbol())
|
||
.collect::<String>()
|
||
.trim_end()
|
||
.to_string()
|
||
})
|
||
.collect::<Vec<_>>()
|
||
.join("\n")
|
||
}
|
||
|
||
fn chips(spec: &str) -> Vec<Chip> {
|
||
let names = ["plan", "code", "build", "test", "review", "merge"];
|
||
spec.chars()
|
||
.zip(names)
|
||
.map(|(c, n)| Chip {
|
||
name: n.into(),
|
||
mark: match c {
|
||
'd' => Mark::Done,
|
||
'a' => Mark::Active,
|
||
'f' => Mark::Failed,
|
||
'w' => Mark::Waiting,
|
||
_ => Mark::Todo,
|
||
},
|
||
})
|
||
.collect()
|
||
}
|
||
|
||
/// Sample data of `Main.dc.html`.
|
||
fn mockup() -> Overview {
|
||
let row = |id: &str,
|
||
status,
|
||
task: &str,
|
||
sub: &str,
|
||
spec: &str,
|
||
retry: &str,
|
||
tests: &str,
|
||
ok,
|
||
last: &str| Row {
|
||
id: id.into(),
|
||
status,
|
||
task: task.into(),
|
||
sub: sub.into(),
|
||
machine: "task.toml".into(),
|
||
chips: chips(spec),
|
||
retry: retry.into(),
|
||
looping: false,
|
||
tests: tests.into(),
|
||
tests_ok: ok,
|
||
added: 164,
|
||
removed: 51,
|
||
ctx: Some(71),
|
||
last: last.into(),
|
||
};
|
||
Overview {
|
||
resumable: 0,
|
||
goal: "Move login to OAuth2 and add per-user rate limiting".into(),
|
||
rows: vec![
|
||
row(
|
||
"s1",
|
||
Status::Done,
|
||
"schema-migrate",
|
||
"users → oauth_identities",
|
||
"dddddd",
|
||
"",
|
||
"18/18 ✓",
|
||
Some(true),
|
||
"merged to main · 12m ago",
|
||
),
|
||
row(
|
||
"s2",
|
||
Status::Fix,
|
||
"oauth-provider",
|
||
"GitHub + Google login",
|
||
"dadftt",
|
||
"↻ fix 2/3",
|
||
"39/41 ✗2",
|
||
Some(false),
|
||
"editing src/auth/token.rs",
|
||
),
|
||
row(
|
||
"s3",
|
||
Status::Wait,
|
||
"auth-middleware",
|
||
"session → bearer tokens",
|
||
"ddddwt",
|
||
"",
|
||
"52/52 ✓",
|
||
Some(true),
|
||
"review ready · 4m",
|
||
),
|
||
row(
|
||
"s5",
|
||
Status::Blocked,
|
||
"docs-update",
|
||
"AUTH.md, migration notes",
|
||
"tttttt",
|
||
"",
|
||
"—",
|
||
None,
|
||
"waits on s2 oauth-provider",
|
||
),
|
||
],
|
||
needs: vec![
|
||
Need {
|
||
id: 1,
|
||
kind: NeedKind::Review,
|
||
session: "s3".into(),
|
||
task: "auth-middleware".into(),
|
||
what: "review ready".into(),
|
||
detail: "6 files, +318 −97, 52/52 tests pass".into(),
|
||
age_secs: 240,
|
||
},
|
||
Need {
|
||
id: 2,
|
||
kind: NeedKind::Permission,
|
||
session: "s4".into(),
|
||
task: "rate-limiter".into(),
|
||
what: "permission".into(),
|
||
detail: "wants to run docker compose up -d redis".into(),
|
||
age_secs: 60,
|
||
},
|
||
],
|
||
events: vec![EventLine {
|
||
id: 1,
|
||
at_ms: 0,
|
||
session: "s2".into(),
|
||
kind: "test".into(),
|
||
text: "cargo test auth:: → 39 passed, 2 failed".into(),
|
||
}],
|
||
merged: 1,
|
||
total: 6,
|
||
checks: Some((9, 14)),
|
||
running: 4,
|
||
waiting: 1,
|
||
blocked: 1,
|
||
cost: 3.41,
|
||
elapsed_secs: 42 * 60,
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn overview_matches_the_mockup_at_160x45() {
|
||
let s = screen(&mockup(), 1);
|
||
for want in [
|
||
"hx·orch",
|
||
"Move login to OAuth2 and add per-user rate limiting",
|
||
"main@4f2a91c",
|
||
"1/6 merged",
|
||
"9/14 checks",
|
||
"4 running · 1 waiting on you · 1 blocked",
|
||
"spent $3.41 · 42m elapsed",
|
||
"Sessions 4",
|
||
"▶ s2",
|
||
"oauth-provider",
|
||
"✓plan › ●code › ✓build › ✗test › ·review › ·merge",
|
||
"↻ fix 2/3",
|
||
"39/41 ✗2",
|
||
"+164 −51",
|
||
"▰▰▰▰▰▰▰▱▱▱",
|
||
"waits on s2 oauth-provider",
|
||
"BLOCKED",
|
||
"◆ Needs you 2",
|
||
"s3 auth-middleware · review ready · 4m",
|
||
"6 files, +318 −97, 52/52 tests pass",
|
||
"[a] approve [d] open diff [c] comment back",
|
||
"▶s4 rate-limiter · permission · 1m", // focus is on the second item
|
||
"wants to run docker compose up -d redis",
|
||
"[y] allow once [Y] always for s4 [A] all same [n] deny",
|
||
"Events all sessions",
|
||
] {
|
||
assert!(s.contains(want), "missing {want:?} in:\n{s}");
|
||
}
|
||
// chips of s2 use the spec's glyphs; the cursor row has the selected background
|
||
assert!(!s.contains("✗build"));
|
||
}
|
||
|
||
#[test]
|
||
fn empty_overview_explains_how_to_start() {
|
||
let s = screen(&Overview::default(), 0);
|
||
assert!(s.contains("no sessions yet"), "{s}");
|
||
assert!(s.contains("Sessions 0"));
|
||
assert!(s.contains("nothing waits on you"));
|
||
}
|
||
|
||
#[test]
|
||
fn live_session_flows_from_runner_through_events_to_screen() {
|
||
let dir = std::env::temp_dir().join(format!("orch-tui-{}", std::process::id()));
|
||
let _ = std::fs::remove_dir_all(&dir);
|
||
let repo = dir.join("repo");
|
||
std::fs::create_dir_all(repo.join(".hx/machines")).unwrap();
|
||
crate::run::git(&repo, &["init", "-q", "-b", "main"]).unwrap();
|
||
// a small machine of local steps is enough to drive the screen
|
||
std::fs::write(
|
||
repo.join(".hx/machines/m.toml"),
|
||
"name = \"m\"\n[[state]]\nname = \"plan\"\nkind = \"start\"\nnext = \"build\"\n\
|
||
[[state]]\nname = \"build\"\nsteps = [{ name = \"b\", run = \"computer\", cmd = \"true\" }]\nnext = \"merge\"\n\
|
||
[[state]]\nname = \"merge\"\nkind = \"exit\"\nend = \"merged\"\n",
|
||
)
|
||
.unwrap();
|
||
crate::run::git(&repo, &["add", "-A"]).unwrap();
|
||
crate::run::git(&repo, &["commit", "-qm", "init"]).unwrap();
|
||
let db = Db::open(&repo.join(".hx/orch.db")).unwrap();
|
||
db.set_goal("ship the thing").unwrap();
|
||
let s = crate::runner::create(&db, &dir.join("wt"), "demo", "", "m").unwrap();
|
||
let m = Machine::find("m", &repo).unwrap();
|
||
let profile = crate::profile::Profile::parse("").unwrap();
|
||
crate::runner::run_session(&db, &m, &s.id, &repo, "", &profile).unwrap();
|
||
|
||
let (mut events, mut machines) = (vec![], HashMap::new());
|
||
let o = snapshot(
|
||
&db,
|
||
&repo,
|
||
&mut events,
|
||
&mut machines,
|
||
crate::state::now_ms(),
|
||
)
|
||
.unwrap();
|
||
assert_eq!(o.rows.len(), 1);
|
||
assert_eq!(o.rows[0].status, Status::Done);
|
||
let text = screen(&o, 0);
|
||
for want in [
|
||
"ship the thing",
|
||
"demo",
|
||
"✓plan › ✓build › ✓merge",
|
||
"1/1 merged",
|
||
"ended: merged",
|
||
"m.toml",
|
||
] {
|
||
assert!(text.contains(want), "missing {want:?} in:\n{text}");
|
||
}
|
||
// incremental: a second snapshot adds no events twice
|
||
let n = events.len();
|
||
snapshot(&db, &repo, &mut events, &mut machines, 0).unwrap();
|
||
assert_eq!(events.len(), n);
|
||
let _ = std::fs::remove_dir_all(&dir);
|
||
}
|
||
|
||
#[test]
|
||
fn failing_tests_flow_from_junit_report_to_session_screen_and_pagers() {
|
||
let dir = std::env::temp_dir().join(format!("orch-tui-detail-{}", std::process::id()));
|
||
let _ = std::fs::remove_dir_all(&dir);
|
||
let repo = dir.join("repo");
|
||
std::fs::create_dir_all(repo.join(".hx/machines")).unwrap();
|
||
crate::run::git(&repo, &["init", "-q", "-b", "main"]).unwrap();
|
||
std::fs::write(
|
||
repo.join(".hx/machines/m.toml"),
|
||
r#"name = "m"
|
||
[[state]]
|
||
name = "code"
|
||
kind = "start"
|
||
steps = [{ name = "edit", run = "computer", cmd = "echo x >> n" }]
|
||
next = "test"
|
||
[[state]]
|
||
name = "test"
|
||
steps = [{ name = "cargo test", run = "computer", sets = "testing", report = "junit", cmd = "printf '<testsuite><testcase name=\"a::ok\"/><testcase name=\"a::bad\"><failure message=\"nope\">at src/x.rs:9:1</failure></testcase></testsuite>' > {{report}}; echo to-stdout; exit 1" }]
|
||
catch = { TestsFailed = "code" }
|
||
retry = { TestsFailed = { max = 3, then = "stuck" } }
|
||
next = "merge"
|
||
[[state]]
|
||
name = "merge"
|
||
kind = "exit"
|
||
end = "merged"
|
||
[[state]]
|
||
name = "stuck"
|
||
kind = "exit"
|
||
only_on = ["TestsFailed x3"]
|
||
end = "escalated"
|
||
"#,
|
||
)
|
||
.unwrap();
|
||
crate::run::git(&repo, &["add", "-A"]).unwrap();
|
||
crate::run::git(&repo, &["commit", "-qm", "init"]).unwrap();
|
||
let db = Db::open(&repo.join(".hx/orch.db")).unwrap();
|
||
let s = crate::runner::create(&db, &dir.join("wt"), "demo", "", "m").unwrap();
|
||
let m = Machine::find("m", &repo).unwrap();
|
||
let profile = crate::profile::Profile::parse("").unwrap();
|
||
let status = crate::runner::run_session(&db, &m, &s.id, &repo, "", &profile).unwrap();
|
||
assert_eq!(status, "escalated");
|
||
|
||
let mut app = App::new(repo.clone());
|
||
app.screen = Screen::Session("s1".into());
|
||
app.refresh();
|
||
let d = app.detail.as_ref().expect("detail loads").clone();
|
||
let mut t = Terminal::new(TestBackend::new(160, 45)).unwrap();
|
||
let h = Header {
|
||
repo: "~/r".into(),
|
||
rev: "main@abc".into(),
|
||
now_ms: 0,
|
||
};
|
||
t.draw(|f| session::draw(f, &d, &h)).unwrap();
|
||
let b = t.backend().buffer();
|
||
let text = b
|
||
.content()
|
||
.chunks(b.area.width as usize)
|
||
.map(|r| {
|
||
r.iter()
|
||
.map(|c| c.symbol())
|
||
.collect::<String>()
|
||
.trim_end()
|
||
.to_string()
|
||
})
|
||
.collect::<Vec<_>>()
|
||
.join("\n");
|
||
if std::env::var_os("ORCH_DUMP").is_some() {
|
||
println!("{text}"); // `ORCH_DUMP=1 cargo test -- --nocapture` shows the screen
|
||
}
|
||
for want in [
|
||
"s1 demo",
|
||
"m.toml",
|
||
"state / step",
|
||
"code · start",
|
||
"catch TestsFailed",
|
||
"hit 3×",
|
||
"catch TestsFailed ×3",
|
||
"│ only on TestsFailed ×3",
|
||
"Last test run",
|
||
"1 passed",
|
||
"1 failed",
|
||
"✗ a::bad",
|
||
"src/x.rs:9",
|
||
"failed in the first run, fix 1 too",
|
||
"retries",
|
||
"3 / 3",
|
||
"path",
|
||
"code → test ✗ → code → test ✗ → code → test ✗ → stuck",
|
||
"full test output",
|
||
] {
|
||
assert!(text.contains(want), "missing {want:?} in:\n{text}");
|
||
}
|
||
|
||
let out = test_output(&app, "s1");
|
||
assert_eq!(out.title, "output of cargo test");
|
||
assert!(
|
||
out.lines.iter().any(|l| l == "to-stdout"),
|
||
"{:?}",
|
||
out.lines
|
||
);
|
||
let tr = transcript(&app, "s1");
|
||
assert!(tr.lines.last().unwrap().contains("ended: escalated"));
|
||
// the agent's (here: the shell's) untracked file shows up in the diff view
|
||
assert!(diff_of(&d.worktree).lines.iter().any(|l| l == "?? n"));
|
||
let _ = std::fs::remove_dir_all(&dir);
|
||
}
|
||
|
||
fn need(kind: NeedKind) -> Need {
|
||
Need {
|
||
id: 7,
|
||
kind,
|
||
session: "s4".into(),
|
||
task: "t".into(),
|
||
what: "w".into(),
|
||
detail: String::new(),
|
||
age_secs: 0,
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn keys_map_to_answers_per_item_kind() {
|
||
let a = |s: &str| NeedKey::Answer(s.into());
|
||
let r = need(NeedKind::Review);
|
||
assert_eq!(need_key(&r, 'a'), a("approve"));
|
||
assert_eq!(need_key(&r, 'd'), NeedKey::Diff);
|
||
assert!(matches!(
|
||
need_key(&r, 'c'),
|
||
NeedKey::Prompt {
|
||
prefix: "changes: ",
|
||
..
|
||
}
|
||
));
|
||
assert_eq!(
|
||
need_key(&r, 'y'),
|
||
NeedKey::Nothing,
|
||
"permission keys do nothing on a review"
|
||
);
|
||
let p = need(NeedKind::Permission);
|
||
assert_eq!(
|
||
[need_key(&p, 'y'), need_key(&p, 'Y'), need_key(&p, 'n')],
|
||
[a("allow_once"), a("allow_always"), a("deny")]
|
||
);
|
||
assert_eq!(need_key(&p, 'a'), NeedKey::Nothing);
|
||
assert!(matches!(
|
||
need_key(&need(NeedKind::Input), 'r'),
|
||
NeedKey::Prompt {
|
||
prefix: "reply: ",
|
||
..
|
||
}
|
||
));
|
||
assert_eq!(need_key(&need(NeedKind::Escalated), 'a'), NeedKey::Nothing);
|
||
}
|
||
|
||
#[test]
|
||
fn answering_in_the_tui_unblocks_the_waiting_runner() {
|
||
let dir = std::env::temp_dir().join(format!("orch-tui-needs-{}", std::process::id()));
|
||
let _ = std::fs::remove_dir_all(&dir);
|
||
let repo = dir.join("repo");
|
||
std::fs::create_dir_all(repo.join(".hx/machines")).unwrap();
|
||
crate::run::git(&repo, &["init", "-q", "-b", "main"]).unwrap();
|
||
std::fs::write(
|
||
repo.join(".hx/machines/m.toml"),
|
||
r#"name = "m"
|
||
[[state]]
|
||
name = "code"
|
||
kind = "start"
|
||
steps = [{ name = "edit", run = "computer", cmd = "true" }]
|
||
next = "review"
|
||
[[state]]
|
||
name = "review"
|
||
kind = "gate"
|
||
steps = [{ name = "wait-approval", run = "human" }]
|
||
catch = { ChangesRequested = "code" }
|
||
next = "merge"
|
||
[[state]]
|
||
name = "merge"
|
||
kind = "exit"
|
||
end = "merged"
|
||
"#,
|
||
)
|
||
.unwrap();
|
||
crate::run::git(&repo, &["add", "-A"]).unwrap();
|
||
crate::run::git(&repo, &["commit", "-qm", "init"]).unwrap();
|
||
let db = Db::open(&repo.join(".hx/orch.db")).unwrap();
|
||
let s = crate::runner::create(&db, &dir.join("wt"), "demo", "", "m").unwrap();
|
||
|
||
// the runner is a separate connection (could be another process): it blocks in the review gate
|
||
let (r2, id) = (repo.clone(), s.id.clone());
|
||
let runner = std::thread::spawn(move || {
|
||
let db = Db::open(&r2.join(".hx/orch.db")).unwrap();
|
||
let m = Machine::find("m", &r2).unwrap();
|
||
let p = crate::profile::Profile::parse("").unwrap();
|
||
crate::runner::run_session(&db, &m, &id, &r2, "", &p).unwrap()
|
||
});
|
||
|
||
let mut app = App::new(repo.clone());
|
||
let deadline = std::time::Instant::now() + Duration::from_secs(20);
|
||
while app.overview.needs.is_empty() && std::time::Instant::now() < deadline {
|
||
std::thread::sleep(Duration::from_millis(30));
|
||
app.refresh();
|
||
}
|
||
let n = app
|
||
.overview
|
||
.needs
|
||
.first()
|
||
.expect("review item appears in the queue")
|
||
.clone();
|
||
assert_eq!(
|
||
(n.kind, n.what.as_str()),
|
||
(NeedKind::Review, "review ready")
|
||
);
|
||
assert_eq!(
|
||
app.overview.rows[0].status,
|
||
Status::Wait,
|
||
"the session waits on the user"
|
||
);
|
||
let text = screen(&app.overview, 0);
|
||
assert!(
|
||
text.contains("review ready") && text.contains("[a] approve"),
|
||
"{text}"
|
||
);
|
||
|
||
let NeedKey::Answer(a) = need_key(&n, 'a') else {
|
||
panic!("a approves")
|
||
};
|
||
app.answer(n.id, &a);
|
||
assert_eq!(runner.join().unwrap(), "merged");
|
||
app.refresh();
|
||
assert!(app.overview.needs.is_empty());
|
||
assert_eq!(app.overview.rows[0].status, Status::Done);
|
||
let _ = std::fs::remove_dir_all(&dir);
|
||
}
|
||
|
||
fn goal_text(g: &crate::goal::GoalView, running: bool) -> String {
|
||
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| goal::draw(f, g, &h, running, 0)).unwrap();
|
||
let b = t.backend().buffer();
|
||
b.content()
|
||
.chunks(b.area.width as usize)
|
||
.map(|r| {
|
||
r.iter()
|
||
.map(|c| c.symbol())
|
||
.collect::<String>()
|
||
.trim_end()
|
||
.to_string()
|
||
})
|
||
.collect::<Vec<_>>()
|
||
.join("\n")
|
||
}
|
||
|
||
fn add(db: &Db, id: &str, name: &str, after: &[&str], state: &str, status: &str) {
|
||
db.add_task(&crate::db::Task {
|
||
id: id.into(),
|
||
name: name.into(),
|
||
subtitle: String::new(),
|
||
machine: "task".into(),
|
||
depends_on: after.iter().map(|a| a.to_string()).collect(),
|
||
})
|
||
.unwrap();
|
||
db.add_session(&crate::db::Session {
|
||
id: id.into(),
|
||
task_id: id.into(),
|
||
branch: format!("hx/{id}"),
|
||
worktree: "/w".into(),
|
||
pid: None,
|
||
state: state.into(),
|
||
status: status.into(),
|
||
})
|
||
.unwrap();
|
||
}
|
||
|
||
#[test]
|
||
fn goal_screen_shows_graph_critical_path_decisions_and_acceptance() {
|
||
let dir = std::env::temp_dir().join(format!("orch-tui-goal-{}", std::process::id()));
|
||
let _ = std::fs::remove_dir_all(&dir);
|
||
std::fs::create_dir_all(&dir).unwrap();
|
||
let db = Db::open(&dir.join(".hx/orch.db")).unwrap();
|
||
db.set_goal("Move login to OAuth2").unwrap();
|
||
add(&db, "s1", "schema-migrate", &[], "merge", "merged");
|
||
add(&db, "s2", "oauth-provider", &["s1"], "test", "running");
|
||
add(&db, "s3", "auth-middleware", &["s1"], "review", "waiting");
|
||
add(&db, "s5", "docs-update", &["s2", "s3"], "", "queued");
|
||
let build = db.add_check("cargo build", "true", None).unwrap();
|
||
let unit = db
|
||
.add_check("unit: auth::token", "false", Some("s2"))
|
||
.unwrap();
|
||
db.add_check("e2e: login", "true", Some("s6")).unwrap();
|
||
db.set_check_result(build, true).unwrap();
|
||
db.set_check_result(unit, false).unwrap();
|
||
db.add_decision("s2", "refresh tokens stored as argon2 hashes", "code")
|
||
.unwrap();
|
||
|
||
let mut app = App::new(dir.clone());
|
||
app.screen = Screen::Goal;
|
||
app.refresh();
|
||
let g = app.goal_view.as_ref().expect("goal view loads");
|
||
let text = goal_text(g, false);
|
||
if std::env::var_os("ORCH_DUMP").is_some() {
|
||
println!("{text}");
|
||
}
|
||
for want in [
|
||
"‹ sessions / goal",
|
||
"Move login to OAuth2",
|
||
"Done = all 3 acceptance checks green on main",
|
||
"Task graph",
|
||
"level 0",
|
||
"level 2",
|
||
"after: —",
|
||
"after: s2, s3",
|
||
"DONE · merged",
|
||
"WAIT · review",
|
||
"BLOCKED · queued",
|
||
"critical path",
|
||
"s2 oauth-provider → s5 docs-update",
|
||
"Decisions agents made",
|
||
"refresh tokens stored as argon2 hashes",
|
||
"Acceptance 1/3",
|
||
"✓ cargo build",
|
||
"✗ unit: auth::token",
|
||
"· e2e: login",
|
||
"esc back",
|
||
"R run all checks",
|
||
] {
|
||
assert!(text.contains(want), "missing {want:?} in:\n{text}");
|
||
}
|
||
assert!(goal_text(g, true).contains("running…"));
|
||
// the overview's acceptance bar reads the same checks
|
||
let o = screen(&app.overview, 0);
|
||
assert!(o.contains("1/3 checks"), "{o}");
|
||
let _ = std::fs::remove_dir_all(&dir);
|
||
}
|
||
|
||
#[test]
|
||
fn editing_the_goal_and_adding_checks_from_the_tui() {
|
||
let dir = std::env::temp_dir().join(format!("orch-tui-edit-{}", std::process::id()));
|
||
let _ = std::fs::remove_dir_all(&dir);
|
||
std::fs::create_dir_all(&dir).unwrap();
|
||
let mut app = App::new(dir.clone()); // no database yet: the first action creates it
|
||
let line = |target, text: &str| InputLine {
|
||
label: "x",
|
||
prefix: "",
|
||
target,
|
||
text: text.into(),
|
||
};
|
||
app.submit(line(Target::Goal, " ship it "));
|
||
app.submit(line(Target::Check, "build | cargo build | s1"));
|
||
app.submit(line(Target::Check, "no owner|true"));
|
||
app.submit(line(Target::Check, "broken, no pipe"));
|
||
app.submit(line(Target::Goal, " ")); // empty goal is ignored
|
||
let db = Db::open(&dir.join(".hx/orch.db")).unwrap();
|
||
assert_eq!(db.goal().unwrap().as_deref(), Some("ship it"));
|
||
let c = db.checks().unwrap();
|
||
assert_eq!(c.len(), 2);
|
||
assert_eq!(
|
||
(c[0].name.as_str(), c[0].cmd.as_str(), c[0].owner.as_deref()),
|
||
("build", "cargo build", Some("s1"))
|
||
);
|
||
assert_eq!(c[1].owner, None);
|
||
assert_eq!(
|
||
parse_check("a | b | "),
|
||
Some(("a".into(), "b".into(), None))
|
||
);
|
||
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::<String>()
|
||
.trim_end()
|
||
.to_string()
|
||
})
|
||
.collect::<Vec<_>>()
|
||
.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::<Vec<_>>(),
|
||
[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);
|
||
}
|
||
#[test]
|
||
fn the_new_session_form_creates_a_session_for_the_host_and_reports_problems() {
|
||
use crossterm::event::{KeyCode, KeyEvent};
|
||
let dir = std::env::temp_dir().join(format!("orch-tui-form-{}", 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/zz-form.toml"), "name = \"zz-form\"\n[[state]]\nname = \"a\"\nkind = \"start\"\nsteps = [{ name = \"x\", run = \"computer\", cmd = \"true\" }]\nnext = \"done\"\n[[state]]\nname = \"done\"\nkind = \"exit\"\nend = \"merged\"\n").unwrap();
|
||
let mut app = App::new(dir.clone());
|
||
// a session to wait for keeps the new one from starting work (and from touching the state dir)
|
||
let db = app.db_or_create().unwrap();
|
||
crate::runner::create(db, &dir.join("wt"), "blocker", "", "zz-form").unwrap();
|
||
|
||
let mut form = newform::Form::new(&dir);
|
||
while form.machine() != Some("zz-form") {
|
||
form.key(KeyEvent::from(KeyCode::Right));
|
||
}
|
||
let err = app.start_session(&form).unwrap_err().to_string();
|
||
assert!(err.contains("name"), "{err}");
|
||
form.name = "ticket work".into();
|
||
form.after = "s1, s9".into();
|
||
let err = app.start_session(&form).unwrap_err().to_string();
|
||
assert!(err.contains("no session s9"), "{err}");
|
||
form.after = "s1".into();
|
||
form.place = "bad name".into();
|
||
assert!(app.start_session(&form).is_err(), "bad branch name");
|
||
form.place = "PROJ-7".into();
|
||
form.no_merge = true;
|
||
assert_eq!(app.start_session(&form).unwrap(), "s2");
|
||
assert_eq!(app.host.as_ref().unwrap().busy(), 1);
|
||
let db = app.db.as_ref().unwrap();
|
||
let s = db.session("s2").unwrap().unwrap();
|
||
assert_eq!(s.branch, "PROJ-7");
|
||
assert!(
|
||
db.events(Some("s2"), 0)
|
||
.unwrap()
|
||
.iter()
|
||
.any(|e| e.kind == "options" && e.payload["no_merge"] == true)
|
||
);
|
||
app.host
|
||
.as_mut()
|
||
.unwrap()
|
||
.shutdown(app.db.as_ref().unwrap(), Duration::from_secs(10));
|
||
assert_eq!(
|
||
app.db
|
||
.as_ref()
|
||
.unwrap()
|
||
.session("s2")
|
||
.unwrap()
|
||
.unwrap()
|
||
.status,
|
||
"suspended"
|
||
);
|
||
let _ = std::fs::remove_dir_all(&dir);
|
||
}
|
||
|
||
#[test]
|
||
fn a_allows_every_identical_permission_request_and_nothing_else() {
|
||
let dir = std::env::temp_dir().join(format!("orch-tui-ident-{}", std::process::id()));
|
||
let _ = std::fs::remove_dir_all(&dir);
|
||
std::fs::create_dir_all(&dir).unwrap();
|
||
let mut app = App::new(dir.clone());
|
||
let db = app.db_or_create().unwrap();
|
||
for _ in 0..4 {
|
||
crate::runner::create(db, &dir.join("wt"), "t", "", "m").unwrap();
|
||
}
|
||
let ask = |s: &str, kind: &str, detail: &str| {
|
||
db.add_need(
|
||
s,
|
||
kind,
|
||
&json!({"key": "", "title": "permission", "detail": detail}),
|
||
)
|
||
.unwrap()
|
||
};
|
||
let a = ask("s1", "permission", "wants to run docker compose up");
|
||
let b = ask("s2", "permission", "wants to run docker compose up");
|
||
let other = ask("s3", "permission", "wants to run rm -rf target");
|
||
let review = ask("s4", "review", "wants to run docker compose up");
|
||
app.refresh();
|
||
let first = app
|
||
.overview
|
||
.needs
|
||
.iter()
|
||
.find(|n| n.id == a)
|
||
.cloned()
|
||
.unwrap();
|
||
app.answer_identical(&first);
|
||
let db = app.db.as_ref().unwrap();
|
||
let answer = |id| db.need_answer(id).unwrap();
|
||
assert_eq!(answer(a).as_deref(), Some("allow_once"));
|
||
assert_eq!(answer(b).as_deref(), Some("allow_once"));
|
||
assert_eq!(answer(other), None, "a different request stays");
|
||
assert_eq!(answer(review), None, "a different kind stays");
|
||
let _ = std::fs::remove_dir_all(&dir);
|
||
}
|
||
|
||
#[test]
|
||
fn the_allow_rule_guess_is_a_tool_or_a_bash_command() {
|
||
assert_eq!(suggest_rule("wants to run edit src/lib.rs"), "edit");
|
||
assert_eq!(suggest_rule("wants to run Bash"), "bash");
|
||
assert_eq!(
|
||
suggest_rule("wants to run docker compose up -d redis"),
|
||
"bash:docker compose up -d redis"
|
||
);
|
||
for g in ["edit", "bash:cargo test *"] {
|
||
assert!(crate::policy::check_entry(g).is_ok());
|
||
}
|
||
let p = need(NeedKind::Permission);
|
||
assert_eq!(need_key(&p, 'P'), NeedKey::AllowRule);
|
||
assert_eq!(need_key(&need(NeedKind::Review), 'P'), NeedKey::Nothing);
|
||
}
|
||
}
|