Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor(signal): unify foreground signal forwarding into one module (#2734)
Maximilian Roos89d684f17d15
diff --git a/src/lib.rs b/src/lib.rsindex 8466ce677..bf7a852cc 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -19,6 +19,8 @@ pub mod progress;pub mod remove_dir;pub mod shell;pub mod shell_exec;+#[cfg(unix)]+pub mod signal_forwarder;pub mod styling;pub mod sync;pub mod trace;diff --git a/src/output/concurrent.rs b/src/output/concurrent.rsindex 50db133ce..67736d391 100644--- a/src/output/concurrent.rs+++ b/src/output/concurrent.rs@@ -36,10 +36,6 @@use std::io::{BufRead, BufReader, Read, Write};use std::path::Path;use std::process::{Child, Stdio};-#[cfg(unix)]-use std::sync::Arc;-#[cfg(unix)]-use std::sync::atomic::{AtomicI32, Ordering};use std::sync::mpsc::{self, Sender};use std::thread;use std::time::Instant;@@ -52,6 +48,8 @@ use worktrunk::shell_exec::{DIRECTIVE_CD_FILE_ENV_VAR, DIRECTIVE_EXEC_FILE_ENV_VAR, DIRECTIVE_FILE_ENV_VAR, ShellConfig,scrub_directive_env_vars,};+#[cfg(unix)]+use worktrunk::signal_forwarder::ForegroundSignals;use worktrunk::styling::stderr;use super::handlers::DirectivePassthrough;@@ -96,10 +94,7 @@ pub fn run_concurrent_commands(// wt (which would orphan already-spawned children, since each runs in// its own process group and wouldn't see the tty's Ctrl-C broadcast).#[cfg(unix)]- let signals = {- use signal_hook::consts::{SIGINT, SIGTERM};- signal_hook::iterator::Signals::new([SIGINT, SIGTERM])?- };+ let signals = ForegroundSignals::install()?;// Spawn each child and record its start time for commands.jsonl. If any// spawn fails partway, kill and reap every child we already spawned —@@ -141,8 +136,7 @@ pub fn run_concurrent_commands(// the spawn loop was queued and will be delivered on the thread's first// poll.#[cfg(unix)]- let signal_thread = spawn_signal_forwarder(- signals,+ let signal_thread = signals.forward_to_pgids(children.iter().map(|c| c.child.id() as i32)@@ -448,74 +442,6 @@ fn render_prefix(index: usize, label: &str, width: usize) -> String {format!("{style}{label:<width$}{style:#} │ ")}-#[cfg(unix)]-struct SignalForwarder {- handle: signal_hook::iterator::Handle,- listener: thread::JoinHandle<()>,- /// First signal the forwarder observed, or 0 if none arrived. Lets the- /// caller report the user's originating signal (e.g., SIGINT) as wt's- /// exit code even when escalation ultimately killed the child with a- /// later signal (e.g., SIGTERM/SIGKILL).- originating_signal: Arc<AtomicI32>,-}--#[cfg(unix)]-impl SignalForwarder {- fn stop(self) -> Option<i32> {- // Closing the signal-hook handle unblocks `Signals::forever()` so- // the listener thread returns; join it to avoid a leak.- self.handle.close();- let _ = self.listener.join();- match self.originating_signal.load(Ordering::SeqCst) {- 0 => None,- sig => Some(sig),- }- }-}--#[cfg(unix)]-fn spawn_signal_forwarder(- mut signals: signal_hook::iterator::Signals,- pgids: Vec<i32>,-) -> SignalForwarder {- let handle = signals.handle();- let originating_signal = Arc::new(AtomicI32::new(0));- let originating = Arc::clone(&originating_signal);- let listener = thread::spawn(move || {- let mut seen_once = false;- for sig in signals.forever() {- // Record the user's first signal so the caller can report it as- // wt's exit code regardless of any internal escalation. Only the- // first wins — later signals here are either the user impatiently- // re-pressing Ctrl-C or wt's own escalation chain firing.- let _ = originating.compare_exchange(0, sig, Ordering::SeqCst, Ordering::SeqCst);- if !seen_once {- // First signal: graceful escalation per child- // (SIGINT → SIGTERM → SIGKILL with grace windows).- seen_once = true;- for &pgid in &pgids {- worktrunk::shell_exec::forward_signal_with_escalation(pgid, sig);- }- } else {- // Subsequent signals: user is impatient — SIGKILL every- // still-live process group without waiting.- for &pgid in &pgids {- let _ = nix::sys::signal::killpg(- nix::unistd::Pid::from_raw(pgid),- nix::sys::signal::Signal::SIGKILL,- );- }- }- }- });-- SignalForwarder {- handle,- listener,- originating_signal,- }-}-#[cfg(test)]mod tests {//! Unit tests that exercise the executor's option-bearing code paths whichdiff --git a/src/shell_exec.rs b/src/shell_exec.rsindex 55f65c3a1..004723caf 100644--- a/src/shell_exec.rs+++ b/src/shell_exec.rs@@ -1192,11 +1192,7 @@ impl Cmd {/// Returns error if command exits with non-zero status.pub fn stream(mut self) -> anyhow::Result<()> {#[cfg(unix)]- use {- signal_hook::consts::{SIGINT, SIGPIPE, SIGTERM},- signal_hook::iterator::Signals,- std::os::unix::process::CommandExt,- };+ use {signal_hook::consts::SIGPIPE, std::os::unix::process::CommandExt};// Shell-wrapped commands don't use args (the command string is the full command)assert!(@@ -1246,9 +1242,11 @@ impl Cmd {self.stdin_cfg.unwrap_or_else(std::process::Stdio::null)};+ // Install the SIGINT/SIGTERM handler BEFORE spawn so a signal arriving+ // mid-spawn is queued, not default-killed.#[cfg(unix)]let signals = if self.forward_signals {- Some(Signals::new([SIGINT, SIGTERM])?)+ Some(crate::signal_forwarder::ForegroundSignals::install()?)} else {None};@@ -1297,68 +1295,19 @@ impl Cmd {}// stdin handle is dropped here, closing the pipe- // Wait for child. With signal forwarding, a listener thread blocks- // on `Signals::forever()` and forwards SIGINT/SIGTERM to the child;- // the main thread blocks on `child.wait()`. After wait returns we- // close the signal handle (which unblocks `forever()`) and join- // the listener.+ // Start the listener now that the child PID is known. The handler+ // installed pre-spawn has been queueing signals; the listener+ // processes any queued signal on its first poll.#[cfg(unix)]- let listener_state = signals.map(|mut signals| {- let child_pid = child.id() as i32;- let share_parent_pgroup = self.share_parent_pgroup;- let handle = signals.handle();- // Sentinel 0 = no signal yet (POSIX signals are >= 1). First- // signal wins via compare_exchange; subsequent signals are- // dropped, matching the prior loop's first-signal-only semantics.- // Re-press escalation lives inside `forward_signal_with_escalation`- // (SIGINT → SIGTERM → SIGKILL with grace windows).- let seen = std::sync::Arc::new(std::sync::atomic::AtomicI32::new(0));- let listener = {- let seen = std::sync::Arc::clone(&seen);- std::thread::spawn(move || {- for sig in signals.forever() {- if seen- .compare_exchange(- 0,- sig,- std::sync::atomic::Ordering::Relaxed,- std::sync::atomic::Ordering::Relaxed,- )- .is_ok()- {- if share_parent_pgroup {- // Shared-pgroup mode: tty-initiated signals- // (Ctrl-C, hangup) already hit the child via- // kernel fg-pgroup delivery. Forward by PID- // anyway so externally-delivered signals- // (e.g. `kill -TERM <wt-pid>`) also reach the- // child — they otherwise stop at wt. Single- // shot, no escalation: if the user chose- // SIGTERM, an unsolicited SIGKILL would skip- // the child's tty restore (raw-mode reset,- // cursor-show) and leave the terminal wedged.- forward_signal_to_pid(child_pid, sig);- } else {- forward_signal_with_escalation(child_pid, sig);- }- }- }- })- };- (handle, listener, seen)- });+ let forwarder =+ signals.map(|s| s.forward_to_pid(child.id() as i32, self.share_parent_pgroup));let wait_result = child.wait();// Always tear down the listener, even on wait error, so the// signal-hook handle is released and the thread doesn't leak.#[cfg(unix)]- let seen_signal = listener_state.and_then(|(handle, listener, seen)| {- handle.close();- let _ = listener.join();- let sig = seen.load(std::sync::atomic::Ordering::Relaxed);- (sig != 0).then_some(sig)- });+ let seen_signal = forwarder.and_then(|f| f.stop());let status = match wait_result {Ok(status) => status,@@ -1458,7 +1407,7 @@ fn wait_for_exit(pgid: i32, grace: std::time::Duration) -> bool {/// externally-delivered signals (e.g. `kill -TERM <wt-pid>`). No escalation:/// see the call site in `Cmd::stream` for the rationale.#[cfg(unix)]-fn forward_signal_to_pid(pid: i32, sig: i32) {+pub fn forward_signal_to_pid(pid: i32, sig: i32) {let nix_sig = match sig {signal_hook::consts::SIGINT => nix::sys::signal::Signal::SIGINT,signal_hook::consts::SIGTERM => nix::sys::signal::Signal::SIGTERM,diff --git a/src/signal_forwarder.rs b/src/signal_forwarder.rsnew file mode 100644index 000000000..724c4efa0--- /dev/null+++ b/src/signal_forwarder.rs@@ -0,0 +1,177 @@+//! Forwards SIGINT/SIGTERM from `wt` to its foreground children.+//!+//! Unix-only — the whole module is `#[cfg(unix)]` at the `pub mod`+//! declaration in `lib.rs`. Windows has no process groups or POSIX+//! signals; `Cmd::stream` and the concurrent executor simply don't+//! forward there.+//!+//! `wt` runs many child processes. When the kernel delivers a tty-initiated+//! signal (Ctrl-C, hangup) to wt's foreground process group, every process+//! in that pgroup receives it directly — but `wt` isolates some children in+//! their own pgroups for clean teardown, and externally-delivered signals+//! (`kill -TERM <wt-pid>`) only reach `wt`. In both cases `wt` must+//! explicitly forward the signal to each child (or child-group) so the+//! whole tree shuts down.+//!+//! ## Two-phase setup+//!+//! Signal handlers must be installed *before* spawning children — otherwise+//! a SIGINT arriving mid-spawn would default-kill `wt` and orphan any+//! already-spawned children. But the listener can't start until the child+//! PIDs/PGIDs are known. So callers do:+//!+//! 1. [`ForegroundSignals::install`] — call before spawning. Queues any+//! signal that arrives during spawn.+//! 2. [`ForegroundSignals::forward_to_pid`] / [`forward_to_pgids`] — call+//! after spawn. Starts the listener; processes any queued signal+//! immediately.+//! 3. [`ActiveForwarder::stop`] — call after waits return. Returns the+//! user's *originating* signal (the first SIGINT/SIGTERM observed),+//! which is what `wt`'s exit code should reflect even when the+//! escalation chain ultimately killed each child with a later signal.+//!+//! [`forward_to_pgids`]: ForegroundSignals::forward_to_pgids+//!+//! ## Modes+//!+//! - **Single PID** ([`forward_to_pid`]) — `wt step <single-cmd>` and the+//! `Cmd::stream` path. With `share_parent_pgroup=true`, the kernel+//! already broadcasts tty signals to the child, so we deliver only as a+//! single shot covering externally-delivered signals (no escalation,+//! to avoid wedging an interactive child mid-tty-restore). With+//! `share_parent_pgroup=false`, the child is in its own pgroup and we+//! escalate SIGINT → SIGTERM → SIGKILL with grace windows.+//! - **Multi PGID** ([`forward_to_pgids`]) — `wt step <concurrent-alias>`.+//! Always escalates per-pgroup. A second user signal SIGKILLs every+//! still-live pgroup immediately to short-circuit the otherwise+//! serialized N × 400 ms escalation walk.+//!+//! [`forward_to_pid`]: ForegroundSignals::forward_to_pid+//!+//! Both modes record the first observed signal so `wt`'s exit code matches+//! what the user pressed, not whichever signal escalation ended up using.++use std::sync::Arc;+use std::sync::atomic::{AtomicI32, Ordering};+use std::thread;++use signal_hook::consts::{SIGINT, SIGTERM};+use signal_hook::iterator::{Handle, Signals};++use crate::shell_exec::{forward_signal_to_pid, forward_signal_with_escalation};++/// Pre-spawn signal handler. Install before spawning any child so signals+/// arriving mid-spawn are queued rather than default-killing `wt`.+pub struct ForegroundSignals {+ signals: Signals,+}++impl ForegroundSignals {+ /// Register `wt`'s SIGINT/SIGTERM handler. Errors only if the+ /// `signal_hook` registration itself fails (extremely rare).+ pub fn install() -> std::io::Result<Self> {+ Ok(Self {+ signals: Signals::new([SIGINT, SIGTERM])?,+ })+ }++ /// Begin forwarding to a single child PID. See module docs for the+ /// `share_parent_pgroup` semantics.+ pub fn forward_to_pid(self, child_pid: i32, share_parent_pgroup: bool) -> ActiveForwarder {+ // First-write wins. Subsequent signals are ignored: single-child+ // escalation already walks SIGINT → SIGTERM → SIGKILL inside one+ // call, so re-pressing Ctrl-C wouldn't add anything actionable.+ self.run_listener(move |sig, originating| {+ if record_originating(originating, sig) {+ if share_parent_pgroup {+ forward_signal_to_pid(child_pid, sig);+ } else {+ forward_signal_with_escalation(child_pid, sig);+ }+ }+ })+ }++ /// Begin forwarding to N children's PGIDs with per-PGID escalation.+ /// A second user signal SIGKILLs every still-live PGID immediately —+ /// per-PGID escalation is serialized, so without the impatient path a+ /// user mashing Ctrl-C might wait `N × 400 ms` for the chain to walk.+ pub fn forward_to_pgids(self, child_pgids: Vec<i32>) -> ActiveForwarder {+ let mut seen_once = false;+ self.run_listener(move |sig, originating| {+ record_originating(originating, sig);+ if !seen_once {+ seen_once = true;+ for &pgid in &child_pgids {+ forward_signal_with_escalation(pgid, sig);+ }+ } else {+ for &pgid in &child_pgids {+ let _ = nix::sys::signal::killpg(+ nix::unistd::Pid::from_raw(pgid),+ nix::sys::signal::Signal::SIGKILL,+ );+ }+ }+ })+ }++ /// Common scaffolding: take ownership of the signal handle, spawn a+ /// listener thread that calls `body` on each received signal, and+ /// package the pieces into an [`ActiveForwarder`].+ fn run_listener(+ self,+ mut body: impl FnMut(i32, &AtomicI32) + Send + 'static,+ ) -> ActiveForwarder {+ let handle = self.signals.handle();+ let originating = Arc::new(AtomicI32::new(0));+ let listener = {+ let originating = Arc::clone(&originating);+ let mut signals = self.signals;+ thread::spawn(move || {+ for sig in signals.forever() {+ body(sig, &originating);+ }+ })+ };+ ActiveForwarder {+ handle,+ listener,+ originating,+ }+ }+}++/// Record `sig` as the originating signal if nothing has been recorded yet.+/// Returns `true` when this call won the race (i.e., `sig` is the first+/// signal observed). The 0 sentinel is safe — POSIX signals are >= 1.+fn record_originating(slot: &AtomicI32, sig: i32) -> bool {+ slot.compare_exchange(0, sig, Ordering::SeqCst, Ordering::SeqCst)+ .is_ok()+}++/// Running signal-forwarder. Returned from+/// [`ForegroundSignals::forward_to_pid`] / [`ForegroundSignals::forward_to_pgids`].+/// Call [`stop`] after every child has been waited on.+///+/// [`stop`]: ActiveForwarder::stop+pub struct ActiveForwarder {+ handle: Handle,+ listener: thread::JoinHandle<()>,+ originating: Arc<AtomicI32>,+}++impl ActiveForwarder {+ /// Tear the listener down and return the user's originating signal,+ /// or `None` if no SIGINT/SIGTERM was received.+ pub fn stop(self) -> Option<i32> {+ // Closing the signal-hook handle unblocks `Signals::forever()`+ // so the listener thread returns; join it to avoid a leak.+ self.handle.close();+ let _ = self.listener.join();+ match self.originating.load(Ordering::SeqCst) {+ 0 => None,+ sig => Some(sig),+ }+ }+}