From cfb735cdb300fec5f1124dbe6c80952f3fcc91eb Mon Sep 17 00:00:00 2001 From: Johannes Kresner Date: Sat, 14 Nov 2026 18:04:41 +0100 Subject: [PATCH] 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 --- .gitignore | 3 + Cargo.lock | 1 + Cargo.toml | 1 + GLOSSARY.md | 29 +++ README.md | 16 ++ examples/profiles/example.toml | 23 +++ src/db.rs | 9 + src/init.rs | 54 ++++++ src/machine.rs | 31 +++- src/main.rs | 20 ++ src/place.rs | 244 ++++++++++++++++++++++++ src/profile.rs | 78 ++++++++ src/report.rs | 2 +- src/runner.rs | 162 +++++++++++++++- src/tui/goal.rs | 42 ++--- src/tui/host.rs | 257 +++++++++++++++++++++++++ src/tui/mod.rs | 330 ++++++++++++++++++++++++++++++++- src/tui/newform.rs | 246 ++++++++++++++++++++++++ src/tui/overview.rs | 60 +++--- src/tui/session.rs | 35 ++-- src/tui/theme.rs | 79 +++++--- src/view.rs | 16 +- 22 files changed, 1623 insertions(+), 115 deletions(-) create mode 100644 GLOSSARY.md create mode 100644 examples/profiles/example.toml create mode 100644 src/init.rs create mode 100644 src/place.rs create mode 100644 src/tui/host.rs create mode 100644 src/tui/newform.rs diff --git a/.gitignore b/.gitignore index a93c69d..95c847d 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,6 @@ devenv.local.yaml # pre-commit .pre-commit-config.yaml + +# hx +.hx diff --git a/Cargo.lock b/Cargo.lock index e508ff4..e6f4d0e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -910,6 +910,7 @@ dependencies = [ "serde", "serde_json", "toml", + "toml_edit", "unicode-width", ] diff --git a/Cargo.toml b/Cargo.toml index 5a12b14..9319c0f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,4 +16,5 @@ rusqlite = { version = "0.42.0", features = ["bundled"] } serde = { version = "1", features = ["derive"] } serde_json = "1" toml = { version = "0.8", features = ["preserve_order"] } +toml_edit = "0.22" unicode-width = "0.2" diff --git a/GLOSSARY.md b/GLOSSARY.md new file mode 100644 index 0000000..22e08e7 --- /dev/null +++ b/GLOSSARY.md @@ -0,0 +1,29 @@ +# orch + +Runs many hx coding agents in parallel on one repository, each in its own git worktree, and gives one human a single place to steer them. + +## Language + +**Session**: +One agent run through a machine, on one branch in one worktree. Hosted by the TUI, or by a separate `orch session` process. +_Avoid_: Job, run (a "run" is the older single-task `orch run`) + +**Machine**: +A TOML definition of the states a session passes through and the steps in each. +_Avoid_: Workflow, pipeline + +**Need**: +A point where a session waits on the human: a permission request, a review, a question, or an escalation. +_Avoid_: Prompt, interrupt (an interrupt is something the human sends) + +**Named worktree**: +A worktree or branch the human picks for a session, such as a ticket branch, instead of the default `hx/sN-slug`. orch never deletes one it did not create. +_Avoid_: Custom branch, existing worktree + +**Host**: +The process whose threads run a session. A session has one host; other processes can only steer it through the database. +_Avoid_: Daemon, worker (a worker is a slot in `orch pull`) + +**Allow rule**: +An entry in a profile's `allow` list that lets the agent use a tool without asking. +_Avoid_: Permission, whitelist diff --git a/README.md b/README.md index 15bce31..d5d531b 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,22 @@ from its saved state; `--machine`, `--name` and `--after` are not allowed with i with `report = "junit"` writes its JUnit XML to `$ORCH_REPORT` (also available as `{{report}}` in `cmd`); orch parses it into counts and failing tests. +`N` on the overview opens the new-session form: machine (`←→`), name, sessions to wait for, and where to work. +"Work in" takes a branch or the name or path of a worktree of the repo (`←→` picks a listed one); a branch that +exists is checked out, a new one is created from `HEAD`, and left empty you get `hx/sN-name` as before. orch never +deletes a worktree it did not create. The merge toggle ends the session at `done` where the machine would merge, so +the branch stays for a pull request. Sessions started this way run on threads of the TUI, at most `workers` of the +`default` profile at a time (the rest wait as `queued`; sessions waiting for `--after` take no slot). `q` while they +run asks for `yes` and suspends them; `u` on the overview resumes every suspended session and every one whose process died (it shows in the key bar +with a count); `orch session --resume sN` does the same for one session from a shell. + +On a permission request in the Needs-you box: `y` allow once, `Y` always for that session, `n` deny, `A` allow +once every pending request that asks for the same thing (any session), and `P` save an allow rule to the profile +`default`. `P` opens a line with a guess (`edit`, or `bash:`) you can change; it is checked like a profile +entry and appended to `allow` with the rest of the file left alone, and the request is allowed. It refuses when the +profile has no file or no `allow` list (that means everything is allowed already). Running sessions keep the +policy they started with; the rule counts for sessions started afterwards. + 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 diff --git a/examples/profiles/example.toml b/examples/profiles/example.toml new file mode 100644 index 0000000..3c2e939 --- /dev/null +++ b/examples/profiles/example.toml @@ -0,0 +1,23 @@ +# Example profile. Copy to /profiles/NAME.toml and use it with --profile NAME. +# Every key is optional; a missing "default" profile behaves like an empty file. + +hx = "hx" +# home = "/home/me/.hx-work" # own HOME, so the profile keeps its own ~/.hx/auth.json +# provider = "anthropic" +sandbox = false +# yolo = true # only together with sandbox = true + +# Shell command run in the worktree after hx; exit 0 = pass. +# gate = "cargo test" +max_retries = 2 + +# Tool allowlist; absent = every tool allowed. +# allow = ["readonly"] +# on_deny = "stop" # or "continue" + +workers = 1 + +[budget] +wall_secs = 1800 +# max_turns = 40 +# max_tokens = 500000 diff --git a/src/db.rs b/src/db.rs index 639eac7..1c7fad3 100644 --- a/src/db.rs +++ b/src/db.rs @@ -333,6 +333,15 @@ impl Db { Ok(()) } + /// Points a session at a branch and worktree chosen by the user instead of the generated ones. + pub fn set_location(&self, id: &str, branch: &str, worktree: &str) -> Result<()> { + self.conn.execute( + "update sessions set branch = ?2, worktree = ?3 where id = ?1", + params![id, branch, worktree], + )?; + Ok(()) + } + pub fn session(&self, id: &str) -> Result> { Ok(self .conn diff --git a/src/init.rs b/src/init.rs new file mode 100644 index 0000000..dfe807c --- /dev/null +++ b/src/init.rs @@ -0,0 +1,54 @@ +//! `orch init`: write the example machines and profile so there is something to copy from. + +use anyhow::{Context, Result}; +use std::path::Path; + +const MACHINES: [(&str, &str); 4] = [ + ("docs.toml", include_str!("../examples/machines/docs.toml")), + ("e2e.toml", include_str!("../examples/machines/e2e.toml")), + ( + "migration.toml", + include_str!("../examples/machines/migration.toml"), + ), + ("task.toml", include_str!("../examples/machines/task.toml")), +]; +const PROFILE: &str = include_str!("../examples/profiles/example.toml"); + +/// Writes `/.hx/machines/*.toml` and `/profiles/example.toml`; existing files stay +/// unless `force`. Returns the paths written. +pub fn run(repo: &Path, config: &Path, force: bool) -> Result> { + let mut files: Vec<_> = MACHINES + .iter() + .map(|(n, s)| (repo.join(".hx/machines").join(n), *s)) + .collect(); + files.push((config.join("profiles/example.toml"), PROFILE)); + let mut written = vec![]; + for (path, text) in files { + if path.exists() && !force { + continue; + } + std::fs::create_dir_all(path.parent().unwrap())?; + std::fs::write(&path, text).with_context(|| path.display().to_string())?; + written.push(path); + } + Ok(written) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn writes_once_and_examples_parse() { + let d = std::env::temp_dir().join(format!("orch-init-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + assert_eq!(run(&d.join("r"), &d.join("c"), false).unwrap().len(), 5); + assert!(run(&d.join("r"), &d.join("c"), false).unwrap().is_empty()); + assert_eq!(run(&d.join("r"), &d.join("c"), true).unwrap().len(), 5); + crate::profile::Profile::parse(PROFILE).unwrap(); + for (_, s) in MACHINES { + crate::machine::Machine::parse(s).unwrap(); + } + std::fs::remove_dir_all(&d).unwrap(); + } +} diff --git a/src/machine.rs b/src/machine.rs index 65b0259..d35e19a 100644 --- a/src/machine.rs +++ b/src/machine.rs @@ -106,13 +106,38 @@ impl Machine { Self::parse(&text).with_context(|| format!("machine {}", path.display())) } - /// `.toml` in `/.hx/machines/`, then `~/.hx/machines/`. - pub fn find(name: &str, repo: &Path) -> Result { - let file = format!("{name}.toml"); + fn dirs(repo: &Path) -> Vec { let mut dirs = vec![repo.join(".hx/machines")]; if let Some(h) = std::env::var_os("HOME") { dirs.push(PathBuf::from(h).join(".hx/machines")); } + dirs + } + + /// Names of the machine files in `/.hx/machines/` and `~/.hx/machines/`, sorted, without duplicates. + pub fn names(repo: &Path) -> Vec { + let mut v: Vec = Self::dirs(repo) + .iter() + .filter_map(|d| std::fs::read_dir(d).ok()) + .flatten() + .flatten() + .filter_map(|e| { + let p = e.path(); + if p.extension()? != "toml" { + return None; + } + p.file_stem()?.to_str().map(String::from) + }) + .collect(); + v.sort(); + v.dedup(); + v + } + + /// `.toml` in `/.hx/machines/`, then `~/.hx/machines/`. + pub fn find(name: &str, repo: &Path) -> Result { + let file = format!("{name}.toml"); + let dirs = Self::dirs(repo); for d in &dirs { if d.join(&file).is_file() { return Self::load(&d.join(&file)); diff --git a/src/main.rs b/src/main.rs index e74552e..cfb736b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,9 +5,11 @@ mod checks; mod db; mod detail; mod goal; +mod init; mod junit; mod lock; mod machine; +mod place; mod policy; mod profile; mod report; @@ -36,6 +38,14 @@ struct Cli { #[derive(Subcommand)] enum Cmd { + /// Write example machines to REPO/.hx/machines and an example profile to the config dir. + Init { + #[arg(long, default_value = ".")] + repo: PathBuf, + /// Overwrite files that already exist. + #[arg(long)] + force: bool, + }, /// Run one task (Markdown file) in a fresh git worktree of REPO. Run { task: PathBuf, @@ -184,6 +194,16 @@ fn main() -> Result { return Ok(code(true)); }; match cmd { + Cmd::Init { repo, force } => { + let written = init::run(&repo, &config_dir(), force)?; + for p in &written { + println!("wrote {}", p.display()); + } + if written.is_empty() { + println!("nothing to do (use --force to overwrite)"); + } + Ok(code(true)) + } Cmd::Goal { text, export, repo } => { let db = open_db(repo.as_deref())?; if let Some(t) = text { diff --git a/src/place.rs b/src/place.rs new file mode 100644 index 0000000..8675b37 --- /dev/null +++ b/src/place.rs @@ -0,0 +1,244 @@ +//! Where a new session works: a fresh branch and worktree (the default), or one the user names, such as a ticket +//! branch. orch never removes a worktree it did not create, so nothing here has a cleanup side. + +use crate::db::Db; +use crate::run::git; +use anyhow::{Result, bail, ensure}; +use std::path::{Path, PathBuf}; + +#[derive(Clone, Debug, PartialEq)] +pub enum Place { + /// `hx/sN-slug` in a worktree under the state dir. + Fresh, + /// A branch without a worktree: orch checks it out (or creates it from HEAD) under the state dir. + Branch(String), + /// A worktree that exists, with the branch checked out in it. + Worktree { path: PathBuf, branch: String }, +} + +/// A linked worktree of the repo (the main checkout is not listed). +#[derive(Clone, Debug, PartialEq)] +pub struct Wt { + pub path: PathBuf, + pub branch: Option, + pub dirty: bool, +} + +pub fn worktrees(repo: &Path) -> Vec { + let Ok(out) = git(repo, &["worktree", "list", "--porcelain"]) else { + return vec![]; + }; + let mut v: Vec = vec![]; + for line in out.lines() { + if let Some(p) = line.strip_prefix("worktree ") { + v.push(Wt { + path: p.into(), + branch: None, + dirty: false, + }); + } else if let Some(b) = line.strip_prefix("branch refs/heads/") + && let Some(w) = v.last_mut() + { + w.branch = Some(b.to_string()); + } + } + if !v.is_empty() { + v.remove(0); // the main checkout + } + for w in &mut v { + w.dirty = git(&w.path, &["status", "--porcelain"]).is_ok_and(|s| !s.trim().is_empty()); + } + v +} + +/// Reads what the user typed: empty = fresh, a path or a branch that has a worktree = that worktree, otherwise a +/// branch name. +pub fn resolve(repo: &Path, input: &str) -> Result { + let input = input.trim(); + if input.is_empty() { + return Ok(Place::Fresh); + } + let wts = worktrees(repo); + let as_path = Path::new(input); + let hit = wts.iter().find(|w| { + w.path == as_path + || w.path.file_name().is_some_and(|n| n == input) + || w.branch.as_deref() == Some(input) + }); + if let Some(w) = hit { + let Some(branch) = &w.branch else { + bail!("{} has no branch checked out", w.path.display()); + }; + return Ok(Place::Worktree { + path: w.path.clone(), + branch: branch.clone(), + }); + } + ensure!( + !as_path.is_absolute(), + "{input} is not a worktree of this repo" + ); + ensure!( + git(repo, &["check-ref-format", "--branch", input]).is_ok(), + "{input:?} is not a valid branch name" + ); + Ok(Place::Branch(input.to_string())) +} + +/// Refuses a place another live session already works in. +pub fn ensure_free(db: &Db, place: &Place) -> Result<()> { + let (branch, path) = match place { + Place::Fresh => return Ok(()), + Place::Branch(b) => (Some(b.as_str()), None), + Place::Worktree { path, branch } => (Some(branch.as_str()), Some(path)), + }; + for s in db.sessions()? { + let live = matches!(s.status.as_str(), "queued" | "running" | "waiting") + && s.pid + .is_none_or(|p| Path::new(&format!("/proc/{p}")).exists()); + let same = Some(s.branch.as_str()) == branch + || path.is_some_and(|p| Path::new(&s.worktree) == p.as_path()); + ensure!(!(live && same), "session {} already works there", s.id); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::machine::Machine; + use crate::profile::Profile; + use crate::runner; + + const M: &str = r#"name = "m" +[[state]] +name = "a" +kind = "start" +steps = [{ name = "w", run = "computer", cmd = "echo hi > out.txt" }] +next = "merge" +[[state]] +name = "merge" +kind = "exit" +steps = [{ name = "never", run = "computer", cmd = "touch merged-it" }] +end = "merged" +"#; + + fn setup(tag: &str) -> (PathBuf, PathBuf, Db) { + let dir = std::env::temp_dir().join(format!("orch-place-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let repo = dir.join("repo"); + std::fs::create_dir_all(&repo).unwrap(); + git(&repo, &["init", "-q", "-b", "main"]).unwrap(); + std::fs::write(repo.join("f"), "x").unwrap(); + git(&repo, &["add", "-A"]).unwrap(); + git( + &repo, + &[ + "-c", + "user.name=t", + "-c", + "user.email=t@t", + "commit", + "-qm", + "i", + ], + ) + .unwrap(); + let db = Db::open(&dir.join("orch.db")).unwrap(); + (dir, repo, db) + } + + #[test] + fn resolve_reads_empty_branch_and_worktree() { + let (dir, repo, _db) = setup("resolve"); + assert_eq!(resolve(&repo, " ").unwrap(), Place::Fresh); + assert_eq!( + resolve(&repo, "PROJ-7").unwrap(), + Place::Branch("PROJ-7".into()) + ); + assert!(resolve(&repo, "bad name").is_err()); + assert!(resolve(&repo, "/nowhere/else").is_err()); + let wt = dir.join("ticket"); + git( + &repo, + &["worktree", "add", "-b", "PROJ-9", &wt.to_string_lossy()], + ) + .unwrap(); + std::fs::write(wt.join("dirty"), "x").unwrap(); + let listed = worktrees(&repo); + assert_eq!(listed.len(), 1, "the main checkout is not listed"); + assert!(listed[0].dirty); + let want = Place::Worktree { + path: listed[0].path.clone(), + branch: "PROJ-9".into(), + }; + assert_eq!(resolve(&repo, "PROJ-9").unwrap(), want, "by branch"); + assert_eq!(resolve(&repo, "ticket").unwrap(), want, "by directory name"); + assert_eq!( + resolve(&repo, &listed[0].path.to_string_lossy()).unwrap(), + want, + "by path" + ); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn named_worktree_is_used_kept_and_not_merged_on_request() { + let (dir, repo, db) = setup("named"); + let wt = dir.join("ticket"); + git( + &repo, + &["worktree", "add", "-b", "PROJ-9", &wt.to_string_lossy()], + ) + .unwrap(); + let place = resolve(&repo, "PROJ-9").unwrap(); + let s = runner::create_in(&db, &dir.join("wts"), "t", "m", &[], &place, true).unwrap(); + assert_eq!(s.branch, "PROJ-9"); + assert_eq!(db.session(&s.id).unwrap().unwrap().worktree, s.worktree); + // a second session may not take the same worktree while the first is live + assert!(runner::create_in(&db, &dir.join("wts"), "u", "m", &[], &place, false).is_err()); + let m = Machine::parse(M).unwrap(); + let status = + runner::run_session(&db, &m, &s.id, &repo, "", &Profile::parse("").unwrap()).unwrap(); + assert_eq!( + status, "done", + "no_merge stops where the machine would merge" + ); + assert!(wt.join("out.txt").exists(), "worked in the named worktree"); + assert!(!wt.join("merged-it").exists()); + assert!(wt.exists(), "a worktree orch did not create stays"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_named_branch_without_worktree_is_created_or_checked_out() { + let (dir, repo, db) = setup("branch"); + git(&repo, &["branch", "existing"]).unwrap(); + for b in ["existing", "brand-new"] { + let s = runner::create_in( + &db, + &dir.join("wts"), + b, + "m", + &[], + &Place::Branch(b.into()), + false, + ) + .unwrap(); + let m = Machine::parse(M).unwrap(); + let p = Profile::parse("").unwrap(); + // the merge step only touches a file here, so the session ends merged + assert_eq!( + runner::run_session(&db, &m, &s.id, &repo, "", &p).unwrap(), + "merged" + ); + assert_eq!( + git(Path::new(&s.worktree), &["branch", "--show-current"]) + .unwrap() + .trim(), + b + ); + } + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/src/profile.rs b/src/profile.rs index 8507b06..ff7327a 100644 --- a/src/profile.rs +++ b/src/profile.rs @@ -4,6 +4,35 @@ use anyhow::{Context, Result, bail}; use serde::Deserialize; use std::path::PathBuf; +/// [`Profile::add_allow`] on a file. +fn add_allow_at(path: &std::path::Path, entry: &str) -> Result { + crate::policy::check_entry(entry)?; + let text = std::fs::read_to_string(path).map_err(|e| { + if e.kind() == std::io::ErrorKind::NotFound { + anyhow::anyhow!( + "{} does not exist: the implicit default profile has no allowlist to extend", + path.display() + ) + } else { + anyhow::anyhow!("{}: {e}", path.display()) + } + })?; + let mut doc: toml_edit::DocumentMut = + text.parse().with_context(|| path.display().to_string())?; + let Some(list) = doc.get_mut("allow").and_then(|a| a.as_array_mut()) else { + bail!( + "{} has no `allow` list: without one every tool is already allowed", + path.display() + ); + }; + if list.iter().any(|v| v.as_str() == Some(entry)) { + return Ok(false); + } + list.push(entry); + std::fs::write(path, doc.to_string()).with_context(|| path.display().to_string())?; + Ok(true) +} + #[derive(Deserialize, Debug, Default, Clone)] #[serde(deny_unknown_fields)] pub struct Budget { @@ -117,6 +146,19 @@ impl Profile { Self::parse(&s).with_context(|| path.display().to_string()) } + /// Appends `entry` to the `allow` list of profile `name`, keeping the rest of the file (comments, order) as it + /// is. Returns false when the entry was there already. Refuses a profile without a file or without `allow`: + /// no list means "everything allowed", and one entry would silently turn that into "almost nothing". + pub fn add_allow(name: &str, entry: &str) -> Result { + if name.is_empty() || name.contains(['/', '.']) { + bail!("bad profile name {name:?}"); + } + let path = crate::config_dir() + .join("profiles") + .join(format!("{name}.toml")); + add_allow_at(&path, entry) + } + pub fn account<'a>(&'a self, profile: &'a str) -> &'a str { self.account.as_deref().unwrap_or(profile) } @@ -180,4 +222,40 @@ mod tests { fn rejects_path_like_names() { assert!(Profile::load("../x").is_err()); } + + #[test] + fn add_allow_keeps_the_file_and_refuses_what_would_change_its_meaning() { + let dir = std::env::temp_dir().join(format!("orch-addallow-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let f = dir.join("p.toml"); + std::fs::write( + &f, + "# mine\nhx = \"hx\"\nallow = [\"read\", \"edit\"] # tools\n[budget]\nmax_turns = 3\n", + ) + .unwrap(); + assert!(add_allow_at(&f, "bash:cargo *").unwrap()); + assert!(!add_allow_at(&f, "bash:cargo *").unwrap(), "already there"); + let text = std::fs::read_to_string(&f).unwrap(); + assert!( + text.contains("# mine") && text.contains("# tools") && text.contains("max_turns = 3"), + "{text}" + ); + let p = Profile::parse(&text).unwrap(); + assert_eq!(p.allow.unwrap(), ["read", "edit", "bash:cargo *"]); + assert!(add_allow_at(&f, "bad entry").is_err()); + assert!( + add_allow_at(&f, "edit:x").is_err(), + "only bash takes a pattern" + ); + std::fs::write(&f, "hx = \"hx\"\n").unwrap(); + assert!( + add_allow_at(&f, "read") + .unwrap_err() + .to_string() + .contains("no `allow` list") + ); + assert!(add_allow_at(&dir.join("none.toml"), "read").is_err()); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/src/report.rs b/src/report.rs index bee0e62..738932f 100644 --- a/src/report.rs +++ b/src/report.rs @@ -232,7 +232,7 @@ impl Agg { } /// Share of input served from the prompt cache. pub fn cache_pct(&self) -> Option { - (self.input_all > 0).then(|| self.cache_read as f64 * 100.0 / self.input_all as f64) + (self.input_all > 0).then_some(self.cache_read as f64 * 100.0 / self.input_all as f64) } pub fn tok_per_run(&self) -> Option { (self.finished() > 0).then(|| self.tokens / self.finished()) diff --git a/src/runner.rs b/src/runner.rs index bb5213e..a311c8b 100644 --- a/src/runner.rs +++ b/src/runner.rs @@ -80,6 +80,37 @@ pub fn create_after( Ok(s) } +/// Like [`create_after`], working in a branch or worktree the user named. With `no_merge` the session stops at +/// `done` where its machine would run the state that ends as `merged`, and leaves the branch for a pull request. +pub fn create_in( + db: &Db, + worktrees: &Path, + name: &str, + machine: &str, + after: &[String], + place: &crate::place::Place, + no_merge: bool, +) -> Result { + use crate::place::Place; + crate::place::ensure_free(db, place)?; + let mut s = create_after(db, worktrees, name, "", machine, after)?; + match place { + Place::Fresh => {} + Place::Branch(b) => s.branch = b.clone(), + Place::Worktree { path, branch } => { + s.branch = branch.clone(); + s.worktree = path.to_string_lossy().into_owned(); + } + } + if *place != Place::Fresh { + db.set_location(&s.id, &s.branch, &s.worktree)?; + } + if no_merge { + db.emit(&s.id, "options", json!({"no_merge": true}))?; + } + Ok(s) +} + fn render(cmd: &str, s: &Session, scope: &str, repo: &Path) -> String { cmd.replace("{{session}}", &s.id) .replace("{{scope}}", scope) @@ -96,10 +127,25 @@ fn ensure_worktree(repo: &Path, s: &Session) -> Result<()> { std::fs::create_dir_all(wt.parent().context("worktree has no parent")?)?; // git races on its own locks when worktrees are added in parallel let _l = crate::lock::lock(&repo.join(".git/orch-worktree.lock"))?; - git( + // a branch the user named may exist already (a ticket branch): check it out instead of creating it + let exists = git( repo, - &["worktree", "add", "-b", &s.branch, &s.worktree, "HEAD"], - )?; + &[ + "rev-parse", + "--verify", + "--quiet", + &format!("refs/heads/{}", s.branch), + ], + ) + .is_ok(); + if exists { + git(repo, &["worktree", "add", &s.worktree, &s.branch])?; + } else { + git( + repo, + &["worktree", "add", "-b", &s.branch, &s.worktree, "HEAD"], + )?; + } Ok(()) } @@ -108,6 +154,8 @@ fn ensure_worktree(repo: &Path, s: &Session) -> Result<()> { enum Stop { /// Abandon the current step and continue in this state. Goto { state: String, why: String }, + /// Stop working but keep the state, so `--resume` continues here (the TUI host is closing). + Suspend, /// End the session. End { status: &'static str, @@ -244,6 +292,10 @@ impl<'a> Ctl<'a> { "goto" => { fail(format!("no state {target:?}"))?; } + "suspend" => { + self.set_stop(Stop::Suspend); + p.interrupt = true; + } "abort" => { self.set_stop(match &self.on_abort { Some(s) => Stop::Goto { @@ -858,6 +910,9 @@ pub fn run_session( match wait_for_dependencies(&ctl, &s, &task) { Ok(()) => {} Err(e) if e.is::() => { + if matches!(ctl.take_stop(), Some(Stop::Suspend)) { + return suspend(db, id, ""); + } let why = "stopped while blocked on its dependencies".to_string(); return finish(db, id, "", "aborted", Some(why)); } @@ -883,6 +938,10 @@ pub fn run_session( (m.start().name.clone(), String::new()) }; db.set_pid(id, Some(std::process::id()))?; + let no_merge = db + .events(Some(id), 0)? + .iter() + .any(|e| e.kind == "options" && e.payload["no_merge"] == true); for _ in 0..MAX_TRANSITIONS { let st = m .state(&cur) @@ -892,6 +951,15 @@ pub fn run_session( db.emit(id, "state", json!({"from": from, "to": cur}))?; } resumed = false; + if no_merge && st.end.as_deref() == Some("merged") { + return finish( + db, + id, + &cur, + "done", + Some("not merged: kept for a pull request".into()), + ); + } 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 @@ -922,6 +990,7 @@ pub fn run_session( }; from = cur.clone(); match outcome { + Outcome::Stop(Stop::Suspend) => return suspend(db, id, &cur), Outcome::Stop(Stop::End { status, reason }) => { return finish(db, id, &cur, status, Some(reason)); } @@ -1035,6 +1104,14 @@ fn enter_merge_queue(ctl: &Ctl, id: &str) -> Result<()> { } } +/// Leaves the session unfinished in `state`: no `end` event, no pid, so `--resume` picks it up. +fn suspend(db: &Db, id: &str, state: &str) -> Result { + db.set_session(id, state, "suspended")?; + db.set_pid(id, None)?; + db.emit(id, "suspend", json!({"state": state}))?; + Ok("suspended".into()) +} + fn finish(db: &Db, id: &str, state: &str, status: &str, reason: Option) -> Result { db.set_session(id, state, status)?; db.set_pid(id, None)?; @@ -1275,6 +1352,43 @@ next = "done" }) } + #[test] + fn suspending_a_session_that_waits_on_a_need_closes_the_need_and_resume_asks_again() { + let e = env("suspend-need"); + let m = Machine::parse(&format!( + r#"name = "m" +[[state]] +name = "review" +kind = "start" +steps = [{{ name = "wait-approval", run = "human", sets = "waiting" }}] +next = "done" +{TAIL}"# + )) + .unwrap(); + create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); + let path = e.dir.join("orch.db"); + let user = std::thread::spawn(move || { + let db = Db::open(&path).unwrap(); + assert!(wait_until(10, || !db.pending_needs().unwrap().is_empty())); + db.add_command("s1", "suspend", &json!({})).unwrap(); + assert!(wait_until(10, || db.pending_needs().unwrap().is_empty())); + }); + assert_eq!( + run_session(&e.db, &m, "s1", &e.repo, "", &plain()).unwrap(), + "suspended" + ); + user.join().unwrap(); + assert!(e.db.pending_needs().unwrap().is_empty(), "no stale item"); + // resumed: the review is asked again, and an answer finishes the session + let user = answerer(e.dir.join("orch.db"), &["approve"]); + assert_eq!( + run_session(&e.db, &m, "s1", &e.repo, "", &plain()).unwrap(), + "merged" + ); + assert_eq!(user.join().unwrap().len(), 1); + let _ = std::fs::remove_dir_all(&e.dir); + } + #[test] fn human_review_waits_in_the_queue_and_changes_requested_loops_back() { let e = env("human"); @@ -1806,6 +1920,48 @@ next = "done" let _ = std::fs::remove_dir_all(&e.dir); } + #[test] + fn suspend_keeps_the_state_and_resume_continues_it() { + let e = env("suspend"); + 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", "suspend", &json!({})).unwrap(); + }, + ); + assert_eq!( + run_session(&e.db, &m, "s1", &e.repo, "", &plain()).unwrap(), + "suspended" + ); + u.join().unwrap(); + let s = e.db.session("s1").unwrap().unwrap(); + assert_eq!( + (s.status.as_str(), s.state.as_str(), s.pid), + ("suspended", "a", None) + ); + assert!( + !kinds(&e.db, "s1").contains(&"end".to_string()), + "not ended, so it can be resumed" + ); + // resumed in state a; the sleep is cut short by a second suspend + let u = user( + &e, + |ev| has(ev, "resume"), + |db| { + db.add_command("s1", "suspend", &json!({})).unwrap(); + }, + ); + assert_eq!( + run_session(&e.db, &m, "s1", &e.repo, "", &plain()).unwrap(), + "suspended" + ); + u.join().unwrap(); + let _ = std::fs::remove_dir_all(&e.dir); + } + #[test] fn force_state_jumps_and_an_unknown_state_is_refused() { let e = env("force"); diff --git a/src/tui/goal.rs b/src/tui/goal.rs index 22b6a03..aaa7676 100644 --- a/src/tui/goal.rs +++ b/src/tui/goal.rs @@ -17,24 +17,24 @@ const BOX_H: u16 = 5; 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)), - area, - ); + let key_lines = theme::key_lines(&KEYS, area.width); let [head, goal, body, keys] = Layout::vertical([ Constraint::Length(1), Constraint::Length(4), Constraint::Fill(1), - Constraint::Length(1), + Constraint::Length(key_lines.len() as u16), ]) .areas(area); f.render_widget(header(h, head.width as usize), head); goal_box(f, goal, g); - let [left, right] = - Layout::horizontal([Constraint::Fill(1), Constraint::Length(56)]).areas(body); + let [left, right] = Layout::horizontal([ + Constraint::Fill(1), + Constraint::Length(theme::capped(body, 56, 45)), + ]) + .areas(body); left_box(f, left, g, dec_sel); acceptance_box(f, right, g, checks_running); - f.render_widget(key_bar(), keys); + f.render_widget(Paragraph::new(key_lines), keys); } fn header(h: &Header, width: usize) -> Line<'static> { @@ -288,21 +288,11 @@ fn acceptance_box(f: &mut Frame, area: Rect, g: &GoalView, running: bool) { f.render_widget(Paragraph::new(lines), inner); } -fn key_bar() -> Line<'static> { - let mut v = vec![Span::raw(" ")]; - for (k, what) in [ - ("esc", "back"), - ("e", "edit goal"), - ("+", "add check"), - ("R", "run all checks"), - ("j/k", "select decision"), - ("v", "veto decision"), - ] { - v.push(Span::styled( - format!(" {k} "), - Style::new().fg(theme::BG).bg(theme::DIM), - )); - v.push(Span::styled(format!(" {what} "), fg(theme::DIM))); - } - Line::from(v) -} +const KEYS: [(&str, &str); 6] = [ + ("esc", "back"), + ("e", "edit goal"), + ("+", "add check"), + ("R", "run all checks"), + ("j/k", "select decision"), + ("v", "veto decision"), +]; diff --git a/src/tui/host.rs b/src/tui/host.rs new file mode 100644 index 0000000..46ad818 --- /dev/null +++ b/src/tui/host.rs @@ -0,0 +1,257 @@ +//! Runs sessions on threads of the TUI process. A session started here lives and dies with the TUI: quitting +//! suspends them (state kept), and `orch session --resume` or the TUI's resume key continues them. + +use crate::db::Db; +use crate::machine::Machine; +use crate::profile::Profile; +use crate::runner; +use anyhow::{Context, Result}; +use std::collections::VecDeque; +use std::path::PathBuf; +use std::thread::JoinHandle; +use std::time::{Duration, Instant}; + +pub struct Host { + repo: PathBuf, + profile: Profile, + /// Sessions that wait for a free slot, oldest first. + pending: VecDeque, + running: Vec<(String, JoinHandle<()>)>, +} + +impl Host { + pub fn new(repo: PathBuf, profile: Profile) -> Self { + Self { + repo, + profile, + pending: VecDeque::new(), + running: vec![], + } + } + + /// Queues a session that already has its rows in the database. + pub fn submit(&mut self, id: &str) { + if !self.hosts(id) { + self.pending.push_back(id.to_string()); + } + } + + pub fn hosts(&self, id: &str) -> bool { + self.pending.iter().any(|p| p == id) || self.running.iter().any(|(r, _)| r == id) + } + + /// Sessions this host still owns (running or waiting for a slot). + pub fn busy(&self) -> usize { + self.pending.len() + self.running.len() + } + + /// Drops finished threads and starts queued sessions while slots are free. A session that waits for + /// `--after` dependencies holds a thread but no slot. + pub fn tick(&mut self, db: &Db) { + self.running.retain(|(_, h)| !h.is_finished()); + let slots = self.profile.workers as usize; + while !self.pending.is_empty() { + let active = self + .running + .iter() + .filter(|(id, _)| !blocked(db, id)) + .count(); + if active >= slots { + break; + } + let id = self.pending.pop_front().expect("not empty"); + match self.start(&id) { + Ok(h) => self.running.push((id, h)), + Err(e) => { + let _ = db.set_session(&id, "", "failed"); + let _ = db.emit( + &id, + "end", + serde_json::json!({"status": "failed", "reason": format!("{e:#}")}), + ); + } + } + } + } + + fn start(&self, id: &str) -> Result> { + let (repo, profile, id) = (self.repo.clone(), self.profile.clone(), id.to_string()); + // fail here, on the caller's thread, when the session or its machine is missing + let db = Db::open(&repo.join(".hx/orch.db"))?; + let s = db + .session(&id)? + .with_context(|| format!("no session {id}"))?; + let task = db + .tasks()? + .into_iter() + .find(|t| t.id == s.task_id) + .with_context(|| format!("no task {}", s.task_id))?; + let m = Machine::find(&task.machine, &repo)?; + Ok(std::thread::spawn(move || { + if let Err(e) = runner::run_session(&db, &m, &id, &repo, "", &profile) { + let _ = db.set_session(&id, "", "failed"); + let _ = db.set_pid(&id, None); + let _ = db.emit( + &id, + "end", + serde_json::json!({"status": "failed", "reason": format!("{e:#}")}), + ); + } + })) + } + + /// Suspends every running session and waits (at most `wait`) for the threads. Sessions that never got a + /// slot stay `queued` in the database. + pub fn shutdown(&mut self, db: &Db, wait: Duration) { + self.pending.clear(); + for (id, _) in &self.running { + let _ = db.add_command(id, "suspend", &serde_json::json!({})); + } + let deadline = Instant::now() + wait; + while Instant::now() < deadline && self.running.iter().any(|(_, h)| !h.is_finished()) { + std::thread::sleep(Duration::from_millis(50)); + } + self.running.retain(|(_, h)| !h.is_finished()); + } +} + +/// Unfinished sessions with no live process: suspended ones, and running or waiting ones whose pid is gone +/// (a crash or a closed terminal). A `queued` session is not listed: another process may still be waiting on its +/// dependencies without a pid. +pub fn resumable(db: &Db) -> Vec { + let Ok(sessions) = db.sessions() else { + return vec![]; + }; + sessions + .into_iter() + .filter(|s| match s.status.as_str() { + "suspended" => true, + "running" | "waiting" => s + .pid + .is_none_or(|p| !std::path::Path::new(&format!("/proc/{p}")).exists()), + _ => false, + }) + .map(|s| s.id) + .collect() +} + +/// Queued and waiting for sessions that have not merged: does not use a slot. +fn blocked(db: &Db, id: &str) -> bool { + let Ok(Some(s)) = db.session(id) else { + return false; + }; + if s.status != "queued" { + return false; + } + let (Ok(tasks), Ok(sessions)) = (db.tasks(), db.sessions()) else { + return false; + }; + tasks.iter().find(|t| t.id == s.task_id).is_some_and(|t| { + t.depends_on.iter().any(|d| { + sessions + .iter() + .find(|x| &x.id == d) + .is_none_or(|x| x.status != "merged") + }) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + const SLEEPER: &str = r#"name = "sleeper" +[[state]] +name = "a" +kind = "start" +steps = [{ name = "long", run = "computer", cmd = "sleep 30" }] +next = "done" +[[state]] +name = "done" +kind = "exit" +end = "merged" +"#; + + fn git(repo: &std::path::Path, args: &[&str]) { + assert!( + std::process::Command::new("git") + .arg("-C") + .arg(repo) + .args(args) + .status() + .unwrap() + .success() + ); + } + + #[test] + fn workers_cap_the_running_sessions_and_shutdown_suspends_them() { + let dir = std::env::temp_dir().join(format!("orch-host-{}", 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(); + std::fs::write(repo.join(".hx/machines/sleeper.toml"), SLEEPER).unwrap(); + git(&repo, &["init", "-q", "-b", "main"]); + std::fs::write(repo.join("f"), "x").unwrap(); + git(&repo, &["add", "-A"]); + git( + &repo, + &[ + "-c", + "user.name=t", + "-c", + "user.email=t@t", + "commit", + "-qm", + "i", + ], + ); + let db = Db::open(&repo.join(".hx/orch.db")).unwrap(); + for n in ["one", "two"] { + runner::create_after(&db, &dir.join("wt"), n, "", "sleeper", &[]).unwrap(); + } + let mut host = Host::new(repo.clone(), Profile::parse("workers = 1").unwrap()); + host.submit("s1"); + host.submit("s2"); + host.submit("s2"); // twice is once + assert_eq!(host.busy(), 2); + host.tick(&db); + assert_eq!( + (host.running.len(), host.pending.len()), + (1, 1), + "one slot, one session" + ); + // wait until s1 is really running, then stop everything + let end = Instant::now() + Duration::from_secs(10); + while db.session("s1").unwrap().unwrap().status != "running" && Instant::now() < end { + std::thread::sleep(Duration::from_millis(20)); + } + host.shutdown(&db, Duration::from_secs(10)); + assert_eq!(host.busy(), 0); + assert_eq!(db.session("s1").unwrap().unwrap().status, "suspended"); + assert_eq!( + db.session("s2").unwrap().unwrap().status, + "queued", + "never got a slot" + ); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] + fn resumable_are_suspended_or_dead_but_not_live_queued_or_finished() { + let dir = std::env::temp_dir().join(format!("orch-resumable-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let db = Db::open(&dir.join("orch.db")).unwrap(); + for _ in 0..6 { + runner::create(&db, &dir.join("wt"), "t", "", "m").unwrap(); + } + db.set_session("s1", "code", "suspended").unwrap(); + db.set_session("s2", "code", "running").unwrap(); + db.set_pid("s2", Some(4_000_000)).unwrap(); // no such process + db.set_session("s3", "code", "running").unwrap(); + db.set_pid("s3", Some(std::process::id())).unwrap(); // this one lives + db.set_session("s5", "merge", "merged").unwrap(); + db.set_session("s6", "code", "waiting").unwrap(); // no pid recorded: nobody runs it + assert_eq!(resumable(&db), ["s1", "s2", "s6"]); // s4 stays queued + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/src/tui/mod.rs b/src/tui/mod.rs index 8ae4e22..58ea7d5 100644 --- a/src/tui/mod.rs +++ b/src/tui/mod.rs @@ -1,6 +1,8 @@ //! 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; @@ -42,6 +44,10 @@ enum NeedKey { 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, @@ -62,6 +68,8 @@ fn need_key(n: &view::Need, c: char) -> NeedKey { }, (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", @@ -71,6 +79,36 @@ fn need_key(n: &view::Need, c: char) -> NeedKey { } } +/// 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 { @@ -86,6 +124,10 @@ enum Target { 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. @@ -131,9 +173,81 @@ struct App { dec_sel: usize, /// True while a background `run all checks` is going. checks_running: std::sync::Arc, + /// Runs the sessions started from this TUI; created with the first one. + host: Option, + /// 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, } 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 { + let Some(db) = &self.db else { return Ok(0) }; + let ids = host::resumable(db); + let host = self.ensure_host()?; + let ids: Vec = 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 { + 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 = 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; @@ -230,6 +344,28 @@ impl App { } 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); @@ -247,6 +383,20 @@ impl App { 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 = 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 { @@ -273,6 +423,9 @@ impl App { goal_view: None, dec_sel: 0, checks_running: Default::default(), + host: None, + quit: false, + form: None, } } @@ -281,9 +434,17 @@ impl App { 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(o) = snapshot(db, &self.repo, &mut self.events, &mut self.machines, now) { + 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 { @@ -462,6 +623,9 @@ fn draw(f: &mut ratatui::Frame, app: &App, header: &Header) { 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); } @@ -624,7 +788,26 @@ fn on_key( ) -> Result { use crossterm::event::{KeyCode, KeyModifiers}; if k.code == KeyCode::Char('c') && k.modifiers.contains(KeyModifiers::CONTROL) { - return Ok(true); + 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 { @@ -663,7 +846,10 @@ fn on_key( Screen::Overview => { let last = app.overview.rows.len().saturating_sub(1); match k.code { - KeyCode::Char('q') => return Ok(true), + 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 => { @@ -680,11 +866,30 @@ fn on_key( 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 @@ -826,7 +1031,11 @@ fn event_loop(term: &mut ratatui::DefaultTerminal, app: &mut App) -> Result<()> let Event::Key(k) = event::read()? else { continue; }; - if k.kind == KeyEventKind::Press && on_key(app, term, k)? { + 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(()); } } @@ -906,6 +1115,7 @@ mod tests { last: last.into(), }; Overview { + resumable: 0, goal: "Move login to OAuth2 and add per-user rate limiting".into(), rows: vec![ row( @@ -1018,7 +1228,7 @@ mod tests { "[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 [n] deny", + "[y] allow once [Y] always for s4 [A] all same [n] deny", "Events all sessions", ] { assert!(s.contains(want), "missing {want:?} in:\n{s}"); @@ -1638,4 +1848,114 @@ end = "merged" 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); + } } diff --git a/src/tui/newform.rs b/src/tui/newform.rs new file mode 100644 index 0000000..d55aadc --- /dev/null +++ b/src/tui/newform.rs @@ -0,0 +1,246 @@ +//! The new-session form (`N` on the overview): machine, name, sessions to wait for, where to work, merge or not. + +use super::theme::{self, bold, fg}; +use crate::place::{self, Wt}; +use crossterm::event::{KeyCode, KeyEvent}; +use ratatui::Frame; +use ratatui::layout::Rect; +use ratatui::text::{Line, Span}; +use ratatui::widgets::{Block, Clear, Paragraph, Wrap}; +use std::path::Path; + +const FIELDS: usize = 5; +const MACHINE: usize = 0; +const NAME: usize = 1; +const AFTER: usize = 2; +const WHERE: usize = 3; +const NO_MERGE: usize = 4; + +pub struct Form { + machines: Vec, + machine: usize, + pub name: String, + pub after: String, + pub place: String, + pub no_merge: bool, + field: usize, + worktrees: Vec, + pub error: Option, +} + +pub enum Outcome { + Open, + Cancel, + Submit, +} + +impl Form { + pub fn new(repo: &Path) -> Self { + Self { + machines: crate::machine::Machine::names(repo), + machine: 0, + name: String::new(), + after: String::new(), + place: String::new(), + no_merge: false, + field: NAME, + worktrees: place::worktrees(repo), + error: None, + } + } + + pub fn machine(&self) -> Option<&str> { + self.machines.get(self.machine).map(String::as_str) + } + + pub fn key(&mut self, k: KeyEvent) -> Outcome { + self.error = None; + match k.code { + KeyCode::Esc => return Outcome::Cancel, + KeyCode::Enter => return Outcome::Submit, + KeyCode::Tab | KeyCode::Down => self.field = (self.field + 1) % FIELDS, + KeyCode::BackTab | KeyCode::Up => self.field = (self.field + FIELDS - 1) % FIELDS, + KeyCode::Left | KeyCode::Right => self.step(k.code == KeyCode::Right), + KeyCode::Char(' ') if self.field == NO_MERGE => self.no_merge = !self.no_merge, + KeyCode::Backspace => { + if let Some(t) = self.text() { + t.pop(); + } + } + KeyCode::Char(c) => { + if let Some(t) = self.text() { + t.push(c); + } + } + _ => {} + } + Outcome::Open + } + + /// The text field in focus, if the focus is on one. + fn text(&mut self) -> Option<&mut String> { + match self.field { + NAME => Some(&mut self.name), + AFTER => Some(&mut self.after), + WHERE => Some(&mut self.place), + _ => None, + } + } + + /// ← → on the machine (cycle), the toggle, and the place field (fill in a listed worktree). + fn step(&mut self, forward: bool) { + match self.field { + MACHINE if !self.machines.is_empty() => { + let n = self.machines.len(); + self.machine = (self.machine + if forward { 1 } else { n - 1 }) % n; + } + NO_MERGE => self.no_merge = !self.no_merge, + WHERE if !self.worktrees.is_empty() => { + let n = self.worktrees.len(); + let i = match self.place_index() { + Some(i) => (i + if forward { 1 } else { n - 1 }) % n, + None => 0, + }; + let w = &self.worktrees[i]; + self.place = w + .branch + .clone() + .unwrap_or_else(|| w.path.to_string_lossy().into_owned()); + } + _ => {} + } + } + + /// The listed worktree the place field currently names, if any. + fn place_index(&self) -> Option { + self.worktrees.iter().position(|w| { + w.branch.as_deref() == Some(self.place.as_str()) + || w.path.to_string_lossy() == self.place.as_str() + }) + } +} + +pub fn draw(f: &mut Frame, form: &Form) { + let a = f.area(); + let w = a.width.saturating_sub(4).min(76); + let rows = 9 + form.worktrees.len().min(4) as u16 + u16::from(form.error.is_some()); + let h = (rows + 2).min(a.height); + let area = Rect::new( + a.x + (a.width.saturating_sub(w)) / 2, + a.y + 1.min(a.height), + w, + h, + ); + f.render_widget(Clear, area); + let block = Block::bordered() + .border_style(fg(theme::WAIT)) + .title(Span::styled(" new session ", bold(theme::TEXT))) + .title_bottom(Span::styled( + " tab next · ←→ choose · enter start · esc cancel ", + fg(theme::DIM), + )); + let inner = block.inner(area); + f.render_widget(block, area); + + let label = |i: usize, s: &str| { + let style = if form.field == i { + bold(theme::WAIT) + } else { + fg(theme::DIM) + }; + Span::styled(format!(" {s:<10}"), style) + }; + let text = |i: usize, s: &str, hint: &str| -> Vec> { + let mut v = vec![label(i, ["", "name", "waits for", "work in", ""][i])]; + if s.is_empty() && form.field != i { + v.push(Span::styled(hint.to_string(), fg(theme::DIM))); + } else { + v.push(Span::raw(s.to_string())); + } + if form.field == i { + v.push(Span::styled("▏", fg(theme::RUN))); + } + v + }; + let machine = match form.machine() { + Some(m) => Span::styled( + format!("‹ {m} › {}/{}", form.machine + 1, form.machines.len()), + bold(theme::TEXT), + ), + None => Span::styled( + "no machine files in .hx/machines or ~/.hx/machines (orch init)", + fg(theme::ERR), + ), + }; + let mut lines = vec![ + Line::from(vec![label(MACHINE, "machine"), machine]), + Line::from(text(NAME, &form.name, "what the session works on")), + Line::from(text(AFTER, &form.after, "s1, s2 (optional)")), + Line::from(text(WHERE, &form.place, "new branch hx/sN-name")), + Line::from(vec![ + label(NO_MERGE, "merge"), + Span::raw(if form.no_merge { + "[x] keep the branch for a pull request, do not merge" + } else { + "[ ] merge when done, as the machine says" + }), + ]), + Line::raw(""), + ]; + if !form.worktrees.is_empty() { + lines.push(Line::from(Span::styled( + " worktrees (← → in “work in” picks one)", + fg(theme::DIM), + ))); + } + for (i, wt) in form.worktrees.iter().enumerate().take(4) { + let on = form.place_index() == Some(i); + let name = wt + .path + .file_name() + .map_or_else(String::new, |n| n.to_string_lossy().into_owned()); + let mut v = vec![ + Span::raw(if on { " ▶ " } else { " " }), + Span::styled(name, bold(theme::TEXT)), + Span::styled( + format!(" {}", wt.branch.as_deref().unwrap_or("detached")), + fg(theme::RUN), + ), + ]; + if wt.dirty { + v.push(Span::styled(" uncommitted changes", fg(theme::WAIT))); + } + lines.push(Line::from(v)); + } + if let Some(e) = &form.error { + lines.push(Line::from(Span::styled(format!(" {e}"), fg(theme::ERR)))); + } + f.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }), inner); +} + +#[cfg(test)] +mod tests { + use super::*; + use ratatui::{Terminal, backend::TestBackend}; + + #[test] + fn the_form_draws_on_wide_and_tiny_terminals() { + let dir = std::env::temp_dir(); + let mut form = Form::new(&dir); + form.error = Some("no session s9 to wait for".into()); + for (w, h) in [(100, 30), (40, 12), (10, 3), (1, 1)] { + let mut t = Terminal::new(TestBackend::new(w, h)).unwrap(); + t.draw(|f| draw(f, &form)).unwrap(); + } + let mut t = Terminal::new(TestBackend::new(100, 30)).unwrap(); + t.draw(|f| draw(f, &form)).unwrap(); + let text: String = t + .backend() + .buffer() + .content() + .iter() + .map(|c| c.symbol()) + .collect(); + assert!(text.contains("new session") && text.contains("merge when done")); + } +} diff --git a/src/tui/overview.rs b/src/tui/overview.rs index 7a3a6fd..6e9ead2 100644 --- a/src/tui/overview.rs +++ b/src/tui/overview.rs @@ -25,10 +25,12 @@ const W_CTX: usize = 10; pub fn draw(f: &mut Frame, o: &Overview, h: &Header, sel: usize, need_sel: usize) { let area = f.area(); - f.render_widget( - Block::new().style(Style::new().bg(theme::BG).fg(theme::TEXT)), - area, - ); + let resume = format!("resume {}", o.resumable); + let mut keys = KEYS.to_vec(); + if o.resumable > 0 { + keys.insert(3, ("u", resume.as_str())); + } + let key_lines = theme::key_lines(&keys, area.width); let rows_h = (o.rows.len().max(1) * 2 + 3) as u16; let sessions_h = rows_h.clamp(5, area.height.saturating_sub(14).max(5)); let [head, stats, sessions, lower, keys] = Layout::vertical([ @@ -36,17 +38,20 @@ pub fn draw(f: &mut Frame, o: &Overview, h: &Header, sel: usize, need_sel: usize Constraint::Length(1), Constraint::Length(sessions_h), Constraint::Fill(1), - Constraint::Length(1), + Constraint::Length(key_lines.len() as u16), ]) .areas(area); - let [needs, events] = - Layout::horizontal([Constraint::Length(62), Constraint::Fill(1)]).areas(lower); + let [needs, events] = Layout::horizontal([ + Constraint::Length(theme::capped(lower, 62, 50)), + Constraint::Fill(1), + ]) + .areas(lower); f.render_widget(header_line(o, h, head.width as usize), head); f.render_widget(stats_line(o), stats); sessions_box(f, sessions, o, sel); needs_box(f, needs, &o.needs, need_sel); events_box(f, events, &o.events); - f.render_widget(key_bar(), keys); + f.render_widget(Paragraph::new(key_lines), keys); } /// Cuts `s` to `w` display columns, ending in `…` when it was too long. @@ -327,14 +332,19 @@ fn needs_box(f: &mut Frame, area: Rect, needs: &[Need], focus: usize) { Span::styled(n.task.clone(), bold(theme::TEXT)), Span::styled(format!(" · {}{age}", n.what), fg(theme::DIM)), ])); - let w = (inner.width as usize).saturating_sub(1); if !n.detail.is_empty() { - lines.push(Line::from(Span::raw(format!(" {}", fit(&n.detail, w))))); + lines.push(Line::from(Span::raw(format!(" {}", n.detail)))); } let keys = n.keys(); if !keys.is_empty() { lines.push(Line::from(Span::styled(format!(" {keys}"), fg(theme::DIM)))); } + if n.kind == crate::view::NeedKind::Permission { + lines.push(Line::from(Span::styled( + " [P] save an allow rule to the profile", + fg(theme::DIM), + ))); + } lines.push(Line::raw("")); } if needs.is_empty() { @@ -343,7 +353,10 @@ fn needs_box(f: &mut Frame, area: Rect, needs: &[Need], focus: usize) { fg(theme::DIM), ))); } - f.render_widget(Paragraph::new(lines), inner); + f.render_widget( + Paragraph::new(lines).wrap(ratatui::widgets::Wrap { trim: false }), + inner, + ); } fn kind_color(kind: &str) -> Color { @@ -381,20 +394,11 @@ fn events_box(f: &mut Frame, area: Rect, events: &[EventLine]) { f.render_widget(Paragraph::new(lines), inner); } -fn key_bar() -> Line<'static> { - let mut v = vec![Span::raw(" ")]; - for (k, what) in [ - ("j/k", "move"), - ("enter", "open"), - ("g", "goal"), - ("tab", "next item"), - ("q", "quit"), - ] { - v.push(Span::styled( - format!(" {k} "), - Style::new().fg(theme::BG).bg(theme::DIM), - )); - v.push(Span::styled(format!(" {what} "), fg(theme::DIM))); - } - Line::from(v) -} +const KEYS: [(&str, &str); 6] = [ + ("j/k", "move"), + ("enter", "open"), + ("N", "new session"), + ("g", "goal"), + ("tab", "next item"), + ("q", "quit"), +]; diff --git a/src/tui/session.rs b/src/tui/session.rs index 05f07e1..498b542 100644 --- a/src/tui/session.rs +++ b/src/tui/session.rs @@ -7,7 +7,7 @@ use crate::machine::RunOn; use crate::view::{Status, ago, hms}; use ratatui::Frame; use ratatui::layout::{Constraint, Layout, Rect}; -use ratatui::style::{Color, Modifier, Style}; +use ratatui::style::{Color, Style}; use ratatui::text::{Line, Span}; use ratatui::widgets::{Block, Paragraph}; use unicode_width::UnicodeWidthStr; @@ -18,18 +18,18 @@ const W_SETS: usize = 14; pub fn draw(f: &mut Frame, d: &Detail, h: &Header) { let area = f.area(); - f.render_widget( - Block::new().style(Style::new().bg(theme::BG).fg(theme::TEXT)), - area, - ); + let key_lines = theme::key_lines(&keys_for(d.looping.is_some()), area.width); let [head, body, keys] = Layout::vertical([ Constraint::Length(1), Constraint::Fill(1), - Constraint::Length(1), + Constraint::Length(key_lines.len() as u16), ]) .areas(area); - let [left, right] = - Layout::horizontal([Constraint::Length(90), Constraint::Fill(1)]).areas(body); + let [left, right] = Layout::horizontal([ + Constraint::Length(theme::capped(body, 90, 60)), + Constraint::Fill(1), + ]) + .areas(body); f.render_widget(header(d, h, head.width as usize), head); machine_box(f, left, d); @@ -55,7 +55,7 @@ pub fn draw(f: &mut Frame, d: &Detail, h: &Header) { now_box(f, now, d); files_box(f, files, d); budget_box(f, budget, d); - f.render_widget(key_bar(d.looping.is_some()), keys); + f.render_widget(Paragraph::new(key_lines), keys); } fn loop_box(f: &mut Frame, area: Rect, d: &Detail, l: &crate::detail::LoopView) { @@ -513,9 +513,8 @@ fn budget_box(f: &mut Frame, area: Rect, d: &Detail) { f.render_widget(Paragraph::new(lines), inner); } -fn key_bar(looping: bool) -> Line<'static> { - let mut v = vec![Span::raw(" ")]; - for (key, what) in [ +fn keys_for(looping: bool) -> Vec<(&'static str, &'static str)> { + [ ("esc", "back"), ("t", "full test output"), ("d", "diff"), @@ -528,15 +527,5 @@ fn key_bar(looping: bool) -> Line<'static> { ] .into_iter() .chain(looping.then_some(("r", "re-plan"))) - { - v.push(Span::styled( - format!(" {key} "), - Style::new() - .fg(theme::BG) - .bg(theme::DIM) - .add_modifier(Modifier::empty()), - )); - v.push(Span::styled(format!(" {what} "), fg(theme::DIM))); - } - Line::from(v) + .collect() } diff --git a/src/tui/theme.rs b/src/tui/theme.rs index 7a5e696..88e667b 100644 --- a/src/tui/theme.rs +++ b/src/tui/theme.rs @@ -1,25 +1,24 @@ -//! Colors from ORCHESTRATOR.md section 8. Truecolor; ratatui maps to the nearest color on 256-color terminals -//! only through the terminal itself, so `COLORTERM` without truecolor looks approximate. -// shortcut: no explicit 256-color table; add one if a target terminal needs it. +//! Colors use the terminal's own palette (ANSI names and the default fg/bg), so the UI follows the user's +//! terminal theme and never paints a background of its own. +use ratatui::layout::Rect; use ratatui::style::{Color, Modifier, Style}; +use ratatui::text::{Line, Span}; +use unicode_width::UnicodeWidthStr; -const fn rgb(hex: u32) -> Color { - Color::Rgb((hex >> 16) as u8, (hex >> 8) as u8, hex as u8) -} - -pub const BG: Color = rgb(0x0b0e14); -pub const TEXT: Color = rgb(0xc9d1d9); -pub const DIM: Color = rgb(0x8b949e); -pub const TODO: Color = rgb(0x7d8590); -pub const BORDER: Color = rgb(0x30363d); -pub const SEL: Color = rgb(0x161b22); -pub const SEP: Color = rgb(0x484f58); -pub const RUN: Color = rgb(0x79c0ff); -pub const OK: Color = rgb(0x7ee787); -pub const ERR: Color = rgb(0xff7b72); -pub const WAIT: Color = rgb(0xe3b341); -pub const AGENT: Color = rgb(0xd2a8ff); +/// Terminal default background and foreground. +pub const BG: Color = Color::Reset; +pub const TEXT: Color = Color::Reset; +pub const DIM: Color = Color::DarkGray; +pub const TODO: Color = Color::DarkGray; +pub const BORDER: Color = Color::DarkGray; +pub const SEL: Color = Color::DarkGray; +pub const SEP: Color = Color::DarkGray; +pub const RUN: Color = Color::Cyan; +pub const OK: Color = Color::Green; +pub const ERR: Color = Color::Red; +pub const WAIT: Color = Color::Yellow; +pub const AGENT: Color = Color::Magenta; pub fn fg(c: Color) -> Style { Style::new().fg(c) @@ -29,7 +28,45 @@ pub fn bold(c: Color) -> Style { Style::new().fg(c).add_modifier(Modifier::BOLD) } -/// Inverted block: dark text on a colored ground (active and waiting marks, key caps). +/// Inverted block: dark text on a colored ground (active and waiting marks). pub fn inverted(c: Color) -> Style { - Style::new().fg(BG).bg(c).add_modifier(Modifier::BOLD) + Style::new() + .fg(Color::Black) + .bg(c) + .add_modifier(Modifier::BOLD) +} + +/// Key cap: the terminal's own colors swapped. +pub fn keycap() -> Style { + Style::new().add_modifier(Modifier::REVERSED) +} + +/// Packs `(key, label)` hints into as many lines as `width` needs; a hint is never split. +pub fn key_lines(items: &[(&str, &str)], width: u16) -> Vec> { + let width = width.max(1) as usize; + let mut lines = Vec::new(); + let mut cur = vec![Span::raw(" ")]; + let mut used = 1; + for (k, what) in items { + let cap = format!(" {k} "); + let label = format!(" {what} "); + let w = cap.width() + label.width(); + if used + w > width && used > 1 { + lines.push(Line::from(std::mem::replace( + &mut cur, + vec![Span::raw(" ")], + ))); + used = 1; + } + cur.push(Span::styled(cap, keycap())); + cur.push(Span::styled(label, fg(DIM))); + used += w; + } + lines.push(Line::from(cur)); + lines +} + +/// Left part of the area, at most `max` wide and at most `pct` percent of it. +pub fn capped(area: Rect, max: u16, pct: u16) -> u16 { + max.min((area.width as u32 * pct as u32 / 100) as u16) } diff --git a/src/view.rs b/src/view.rs index 69e0ff1..356f629 100644 --- a/src/view.rs +++ b/src/view.rs @@ -93,12 +93,12 @@ pub struct Need { } impl Need { - /// The key line under the item, like `[y] allow once [Y] always for s4 [n] deny`. + /// 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 {} [n] deny", + "[y] allow once [Y] always for {} [A] all same [n] deny", self.session ), NeedKind::Input => "[r] reply".into(), @@ -119,6 +119,8 @@ pub struct EventLine { #[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, pub needs: Vec, pub events: Vec, @@ -205,9 +207,9 @@ pub fn build(i: &Input) -> Overview { .is_none_or(|x| x.status != "merged") }); let status = match s.status.as_str() { - "merged" => Status::Done, + "merged" | "done" => Status::Done, "failed" | "aborted" => Status::Fail, - "waiting" | "escalated" => Status::Wait, + "waiting" | "escalated" | "suspended" => Status::Wait, "queued" if unmet.is_some() => Status::Blocked, _ if !scan.retry.is_empty() => Status::Fix, _ => Status::Run, @@ -216,7 +218,11 @@ pub fn build(i: &Input) -> Overview { (Status::Blocked, Some(d)) => format!("waits on {d} {}", name_of(d)), (Status::Done, _) => { let at = evs.last().map_or(0, |e| e.at); - format!("merged · {} ago", ago(i.now_ms.saturating_sub(at) / 1000)) + format!( + "{} · {} ago", + s.status, + ago(i.now_ms.saturating_sub(at) / 1000) + ) } _ => evs.last().map_or_else(String::new, |e| describe(e)), };