TUI hosts sessions: new-session form, named worktrees, resume, faster permissions

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

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

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
johannesandClaude Sonnet 5.5 committed 2026-11-14 18:04:41 +01:00
1 parent 5a80bc9fe1
commit cfb735cdb3
22 files changed
+1623 -115

No files matched your search

+325 -5
View File
@@ -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<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;
@@ -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<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 {
@@ -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<bool> {
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);
}
}