diff --git a/crates/maestro-daemon/src/proc.rs b/crates/maestro-daemon/src/proc.rs index c534bf3..09b366a 100644 --- a/crates/maestro-daemon/src/proc.rs +++ b/crates/maestro-daemon/src/proc.rs @@ -16,43 +16,87 @@ //! Every step degrades to `false` on a read failure, so a non-Linux host or a //! denied `/proc` read falls back to `Idle`. -/// Whether the process on `tty` (e.g. `/dev/pts/3`) looks blocked on terminal -/// input — the signal for `AwaitingInput`. +/// Whether the session on `tty` (e.g. `/dev/pts/3`) is blocked waiting on the +/// user — the signal for `AwaitingInput`. pub fn awaiting_input(pane_pid: i32, tty: &str) -> bool { - let Some(fg) = foreground_pid(pane_pid) else { + let Some(pgid) = foreground_pgid(pane_pid) else { return false; }; + foreground_members(pane_pid, pgid) + .into_iter() + .any(|pid| parked_on_tty(pid, tty)) +} + +/// The process group the terminal considers foreground. +/// +/// `tpgid` is the kernel's own answer, which is why this replaced walking +/// `children` to the deepest descendant: that guessed the newest child was the +/// foreground one, so an agent with a background helper looked idle. +fn foreground_pgid(pane_pid: i32) -> Option { + let tpgid = read_stat(pane_pid)?.tpgid; + // -1 when the process has no controlling terminal. + (tpgid > 0).then_some(tpgid) +} + +/// Cap on processes examined per pass. A session's tree is a shell plus a +/// handful of children; this only bounds a pathological one. +const MAX_TREE_NODES: usize = 256; + +/// Live members of process group `pgid`, searched within the pane's subtree. +/// +/// `pgid` names a *group*, not a process. Its leader can exit while another +/// member still holds the terminal — a foreground pipeline whose first stage +/// finished — and then `/proc/` does not exist. Members stay in this +/// subtree because their parent shell is still alive, so they never reparent. +fn foreground_members(pane_pid: i32, pgid: i32) -> Vec { + let mut found = Vec::new(); + let mut queue = vec![pane_pid]; + let mut visited = 0usize; + while let Some(pid) = queue.pop() { + visited += 1; + if visited > MAX_TREE_NODES { + break; + } + if read_stat(pid).is_some_and(|s| s.pgrp == pgid) { + found.push(pid); + } + queue.extend(children(pid)); + } + found +} + +/// Direct children of `pid`, via `/proc//task//children`. +fn children(pid: i32) -> Vec { + std::fs::read_to_string(format!("/proc/{pid}/task/{pid}/children")) + .map(|s| { + s.split_whitespace() + .filter_map(|x| x.parse().ok()) + .collect() + }) + .unwrap_or_default() +} + +/// Whether `pid` is parked on `tty` rather than busy or sleeping on a timer. +fn parked_on_tty(pid: i32, tty: &str) -> bool { // Interruptible sleep is where a blocking read parks; anything else // (running, uninterruptible) is busy, not waiting on us. - if read_stat(fg).map(|s| s.state) != Some('S') { + if read_stat(pid).map(|s| s.state) != Some('S') { return false; } // A pure timer sleep (`sleep`, `usleep`) also sits in 'S' with the terminal // inherited — exclude it so it reads as Idle, not AwaitingInput. - if is_timer_sleep(fg) { + if is_timer_sleep(pid) { return false; } - fd_points_at_tty(fg, tty) -} - -/// The process the terminal considers foreground. -/// -/// `tpgid` is the kernel's own answer — the foreground process *group* of the -/// controlling terminal — and the group leader's pid equals the group id. This -/// replaced walking `children` to the deepest descendant, which picked whatever -/// was spawned last: an agent that starts a background helper and then blocks -/// on `read` was reported as not awaiting input, because the walk landed on the -/// helper. -fn foreground_pid(pane_pid: i32) -> Option { - let tpgid = read_stat(pane_pid)?.tpgid; - // -1 when the process has no controlling terminal. - (tpgid > 0).then_some(tpgid) + fd_points_at_tty(pid, tty) } /// The fields of `/proc//stat` this module needs. #[derive(Debug, Clone, Copy, PartialEq, Eq)] struct Stat { state: char, + /// The process group this process belongs to. + pgrp: i32, /// Foreground process group of the controlling terminal. tpgid: i32, } @@ -70,9 +114,12 @@ fn parse_stat(stat: &str) -> Option { let close = stat.rfind(')')?; let mut rest = stat[close + 1..].split_whitespace(); let state = rest.next()?.chars().next()?; - // ppid, pgrp, session, tty_nr then tpgid. - let tpgid = rest.nth(4)?.parse().ok()?; - Some(Stat { state, tpgid }) + let _ppid = rest.next()?; + let pgrp = rest.next()?.parse().ok()?; + let _session = rest.next()?; + let _tty_nr = rest.next()?; + let tpgid = rest.next()?.parse().ok()?; + Some(Stat { state, pgrp, tpgid }) } /// Whether `pid`'s `wchan` (the kernel symbol it's blocked in) is a timer @@ -104,17 +151,23 @@ mod tests { /// `pid (comm) state ppid pgrp session tty_nr tpgid …` fn stat_line(comm: &str, state: char, tpgid: i32) -> String { - format!("1234 ({comm}) {state} 1000 1234 1234 34816 {tpgid} 4194304 …") + stat_line_pgrp(comm, state, 1234, tpgid) + } + + fn stat_line_pgrp(comm: &str, state: char, pgrp: i32, tpgid: i32) -> String { + format!("1234 ({comm}) {state} 1000 {pgrp} 1234 34816 {tpgid} 4194304 …") } #[test] - fn parse_stat_reads_state_and_tpgid() { - let s = parse_stat(&stat_line("bash", 'S', 4321)).unwrap(); + fn parse_stat_reads_state_pgrp_and_tpgid() { + let s = parse_stat(&stat_line_pgrp("bash", 'S', 500, 4321)).unwrap(); assert_eq!(s.state, 'S'); + assert_eq!(s.pgrp, 500); assert_eq!(s.tpgid, 4321); - let r = parse_stat(&stat_line("cat", 'R', 99)).unwrap(); + let r = parse_stat(&stat_line_pgrp("cat", 'R', 7, 99)).unwrap(); assert_eq!(r.state, 'R'); + assert_eq!(r.pgrp, 7); assert_eq!(r.tpgid, 99); } @@ -123,8 +176,9 @@ mod tests { /// every later field at the wrong index. #[test] fn parse_stat_indexes_from_the_final_paren() { - let s = parse_stat(&stat_line("weird (name) with spaces", 'D', 777)).unwrap(); + let s = parse_stat(&stat_line_pgrp("weird (name) with spaces", 'D', 42, 777)).unwrap(); assert_eq!(s.state, 'D'); + assert_eq!(s.pgrp, 42); assert_eq!(s.tpgid, 777); } diff --git a/crates/maestro-daemon/tests/activity.rs b/crates/maestro-daemon/tests/activity.rs index 0ac8f19..b3f0994 100644 --- a/crates/maestro-daemon/tests/activity.rs +++ b/crates/maestro-daemon/tests/activity.rs @@ -91,3 +91,63 @@ fn a_foreground_sleep_is_not_awaiting_input() { wait_for_awaiting(&fx, id, false, "a timer sleep is not user input"); } + +/// Read `pgrp` and `tpgid` for a pid straight from `/proc`, so the test can +/// wait for the exact condition it means to exercise rather than a proxy. +fn pgrp_and_tpgid(pid: i32) -> Option<(i32, i32)> { + let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?; + let close = stat.rfind(')')?; + let f: Vec<&str> = stat[close + 1..].split_whitespace().collect(); + Some((f.get(2)?.parse().ok()?, f.get(5)?.parse().ok()?)) +} + +/// `tpgid` names a process *group*, and its leader can exit while another +/// member still holds the terminal — a foreground pipeline whose first stage +/// finished. Reading `/proc/` directly then finds nothing and reports +/// idle, so the group has to be searched for a live member. +/// +/// Needs an interactive shell: job control is what puts a pipeline in its own +/// process group, and that is how the daemon spawns commands +/// (`$SHELL -lic ''`). +#[test] +fn a_foreground_pipeline_whose_leader_exited_is_still_awaiting_input() { + let fx = TmuxFixture::new(); + let cwd = TempDir::new().unwrap(); + let id = Uuid::new_v4(); + fx.tmux + .new_session(id, cwd.path(), "bash --noprofile --norc -i") + .expect("new_session"); + wait_for_awaiting(&fx, id, true, "the shell must settle first"); + + // `true` leads the group and exits immediately; the right-hand stage + // survives, blocked reading the terminal. + fx.tmux + .send_keys(id, b"true | { read -r line < /dev/tty; }\n") + .expect("send_keys"); + + // Wait for the state this test exists for: the foreground group is no + // longer the shell's own, and its leader is gone. Asserting before that + // would pass against a leader-only lookup, because the shell is still + // foreground and alive. + let pane = fx.tmux.pane_info(id).expect("pane_info").expect("pane"); + let deadline = std::time::Instant::now() + Duration::from_secs(5); + let mut reached = false; + while std::time::Instant::now() < deadline { + if let Some((pgrp, tpgid)) = pgrp_and_tpgid(pane.pane_pid) { + if tpgid > 0 && tpgid != pgrp && pgrp_and_tpgid(tpgid).is_none() { + reached = true; + break; + } + } + std::thread::sleep(Duration::from_millis(20)); + } + assert!( + reached, + "never observed a foreground group whose leader had exited" + ); + + assert!( + awaiting_input(pane.pane_pid, &pane.tty), + "a surviving pipeline member still holds the tty" + ); +}