Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Add signal forwarding for hook process groups (#279)
Maximilian Roosa8b9c59e3cb8
diff --git a/Cargo.lock b/Cargo.lockindex 679a0c678..52bba8f45 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3094,6 +3094,7 @@ dependencies = ["shell-escape","shellexpand","shlex",+ "signal-hook","skim","strum","synoptic",diff --git a/Cargo.toml b/Cargo.tomlindex 00833efe1..8ea259c6e 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -107,10 +107,8 @@ termimad = "0.34.1"[target.'cfg(unix)'.dependencies]skim = "0.20"--[target.'cfg(unix)'.dev-dependencies]-# Match version used by portable-pty to avoid compiling multiple nix versionsnix = { version = "0.30", default-features = false, features = ["process", "signal"] }+signal-hook = "0.3"[build-dependencies]vergen-gitcl = { version = "1.0.8", features = ["build"] }diff --git a/src/output/global.rs b/src/output/global.rsindex ee9fc27b9..544c07405 100644--- a/src/output/global.rs+++ b/src/output/global.rs@@ -271,7 +271,7 @@ fn execute_command(command: String, target_dir: Option<&Path>) -> anyhow::Result// On non-Unix platforms, fall back to spawn-and-wait.// This uses the shell abstraction (Git Bash if available).let exec_dir = target_dir.unwrap_or_else(|| Path::new("."));- if let Err(err) = execute_streaming(&command, exec_dir, false, None, true) {+ if let Err(err) = execute_streaming(&command, exec_dir, false, None, true, false) {// If the command failed with an exit code, just exit with that code.// This matches Unix behavior where exec() replaces the process and// the shell's exit code becomes the process exit code (no error message).diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex d61fca6d7..a02542ce6 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -788,6 +788,51 @@ fn handle_removed_worktree_output(}}+#[cfg(unix)]+fn process_group_alive(pgid: i32) -> bool {+ match nix::sys::signal::killpg(nix::unistd::Pid::from_raw(pgid), None) {+ Ok(_) => true,+ Err(nix::errno::Errno::ESRCH) => false,+ Err(_) => true,+ }+}++#[cfg(unix)]+fn wait_for_exit(pgid: i32, grace: std::time::Duration) -> bool {+ std::thread::sleep(grace);+ !process_group_alive(pgid)+}++#[cfg(unix)]+fn forward_signal_with_escalation(pgid: i32, sig: i32) {+ let pgid = nix::unistd::Pid::from_raw(pgid);+ let initial_signal = match sig {+ signal_hook::consts::SIGINT => nix::sys::signal::Signal::SIGINT,+ signal_hook::consts::SIGTERM => nix::sys::signal::Signal::SIGTERM,+ _ => return,+ };++ let _ = nix::sys::signal::killpg(pgid, initial_signal);++ let grace = std::time::Duration::from_millis(200);+ match sig {+ signal_hook::consts::SIGINT => {+ if !wait_for_exit(pgid.as_raw(), grace) {+ let _ = nix::sys::signal::killpg(pgid, nix::sys::signal::Signal::SIGTERM);+ if !wait_for_exit(pgid.as_raw(), grace) {+ let _ = nix::sys::signal::killpg(pgid, nix::sys::signal::Signal::SIGKILL);+ }+ }+ }+ signal_hook::consts::SIGTERM => {+ if !wait_for_exit(pgid.as_raw(), grace) {+ let _ = nix::sys::signal::killpg(pgid, nix::sys::signal::Signal::SIGKILL);+ }+ }+ _ => {}+ }+}+/// Execute a command with streaming output////// Uses Stdio::inherit for stderr to preserve TTY behavior - this ensures commands like cargo@@ -814,23 +859,32 @@ fn handle_removed_worktree_output(////// ## Signal Handling (Unix)///-/// SIGINT (Ctrl-C) is handled by checking the child's exit status:-/// - If the child was killed by a signal, we return exit code 128 + signal number-/// - This follows Unix conventions (e.g., exit code 130 for SIGINT)-///-/// The child process receives SIGINT directly from the terminal (via Stdio::inherit for stderr).+/// When `forward_signals` is true, the child is spawned in its own process group and+/// SIGINT/SIGTERM received by the parent are forwarded to that group so we can abort+/// the entire command tree without shell-wrapping. If the process group does not exit+/// promptly, we escalate to SIGTERM/SIGKILL (SIGINT path) or SIGKILL (SIGTERM path).+/// We still return exit code 128 + signal number (e.g., 130 for SIGINT) to match Unix conventions.pub(crate) fn execute_streaming(command: &str,working_dir: &std::path::Path,redirect_stdout_to_stderr: bool,stdin_content: Option<&str>,inherit_stdin: bool,+ forward_signals: bool,) -> anyhow::Result<()> {use std::io::Write;use worktrunk::git::WorktrunkError;use worktrunk::shell_exec::ShellConfig;+ #[cfg(unix)]+ use {+ signal_hook::consts::{SIGINT, SIGTERM},+ signal_hook::iterator::Signals,+ std::os::unix::process::CommandExt,+ };let shell = ShellConfig::get();+ #[cfg(not(unix))]+ let _ = forward_signals;// Determine stdout handling based on redirect flag// When redirecting, use Stdio::from(stderr) to redirect child stdout to our stderr at OS level.@@ -851,7 +905,19 @@ pub(crate) fn execute_streaming(std::process::Stdio::null()};+ #[cfg(unix)]+ let mut signals = if forward_signals {+ Some(Signals::new([SIGINT, SIGTERM])?)+ } else {+ None+ };+let mut cmd = shell.command(command);+ #[cfg(unix)]+ if forward_signals {+ // Isolate the child in its own process group so we can signal the whole tree.+ cmd.process_group(0);+ }let mut child = cmd.current_dir(working_dir).stdin(stdin_mode)@@ -882,13 +948,53 @@ pub(crate) fn execute_streaming(// stdin is dropped here, closing the pipe}- // Wait for command to complete+ #[cfg(unix)]+ let (status, seen_signal) = if forward_signals {+ let child_pgid = child.id() as i32;+ let mut seen_signal: Option<i32> = None;+ loop {+ if let Some(status) = child.try_wait().map_err(|e| {+ anyhow::Error::from(worktrunk::git::GitError::Other {+ message: format!("Failed to wait for command: {}", e),+ })+ })? {+ break (status, seen_signal);+ }+ if let Some(signals) = signals.as_mut() {+ for sig in signals.pending() {+ if seen_signal.is_none() {+ seen_signal = Some(sig);+ forward_signal_with_escalation(child_pgid, sig);+ }+ }+ }+ std::thread::sleep(std::time::Duration::from_millis(10));+ }+ } else {+ let status = child.wait().map_err(|e| {+ anyhow::Error::from(worktrunk::git::GitError::Other {+ message: format!("Failed to wait for command: {}", e),+ })+ })?;+ (status, None)+ };++ #[cfg(not(unix))]let status = child.wait().map_err(|e| {anyhow::Error::from(worktrunk::git::GitError::Other {message: format!("Failed to wait for command: {}", e),})})?;+ #[cfg(unix)]+ if let Some(sig) = seen_signal {+ return Err(WorktrunkError::ChildProcessExited {+ code: 128 + sig,+ message: format!("terminated by signal {}", sig),+ }+ .into());+ }+// Check if child was killed by a signal (Unix only)// This handles Ctrl-C: when SIGINT is sent, the child receives it and terminates,// and we propagate the signal exit code (128 + signal number, e.g., 130 for SIGINT)@@ -957,7 +1063,7 @@ pub fn execute_command_in_worktree(// Execute with stdout→stderr redirect for deterministic ordering// Hooks don't need stdin inheritance (inherit_stdin=false)- execute_streaming(command, worktree_path, true, stdin_content, false)?;+ execute_streaming(command, worktree_path, true, stdin_content, false, true)?;// Flush to ensure all output appears before we continuesuper::flush()?;diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rsindex 55a715777..735ea803f 100644--- a/tests/integration_tests/user_hooks.rs+++ b/tests/integration_tests/user_hooks.rs@@ -396,6 +396,67 @@ long = "sh -c 'echo start >> hook.log; sleep 30; echo done >> hook.log'");}+/// Test that hooks receive SIGTERM and do not continue after termination.+#[rstest]+#[cfg(unix)]+fn test_pre_merge_hook_receives_sigterm(repo: TestRepo) {+ use nix::sys::signal::{Signal, kill};+ use nix::unistd::Pid;+ use std::io::Read;+ use std::os::unix::process::CommandExt;+ use std::process::Stdio;++ repo.commit("Initial commit");++ // Project pre-merge hook: write start, then sleep, then write done (if not interrupted)+ repo.write_project_config(+ r#"[pre-merge]+long = "sh -c 'echo start >> hook.log; sleep 30; echo done >> hook.log'"+"#,+ );+ repo.commit("Add pre-merge hook");++ // Spawn wt in its own process group (so SIGTERM to that group doesn't kill the test)+ let mut cmd = crate::common::wt_command();+ cmd.current_dir(repo.root_path());+ cmd.args(["hook", "pre-merge", "--force"]);+ cmd.stdout(Stdio::null());+ cmd.stderr(Stdio::null());+ cmd.process_group(0); // wt becomes leader of its own process group+ let mut child = cmd.spawn().expect("failed to spawn wt hook pre-merge");++ // Wait until hook writes "start" to hook.log (verifies the hook is running)+ let hook_log = repo.root_path().join("hook.log");+ wait_for_file_content(&hook_log, Duration::from_secs(5));++ // Send SIGTERM to wt's process group (wt's PID == its PGID since it's the leader)+ let wt_pgid = Pid::from_raw(child.id() as i32);+ kill(Pid::from_raw(-wt_pgid.as_raw()), Signal::SIGTERM)+ .expect("failed to send SIGTERM to pgrp");++ let status = child.wait().expect("failed to wait for wt");++ // wt was killed by signal, so code() returns None and we check the signal+ use std::os::unix::process::ExitStatusExt;+ assert!(+ status.signal() == Some(15) || status.code() == Some(143),+ "wt should be killed by SIGTERM (signal 15) or exit 143, got: {status:?}"+ );++ // Give the (killed) hook a moment; it must not append "done"+ thread::sleep(Duration::from_millis(500));++ let mut contents = String::new();+ std::fs::File::open(&hook_log)+ .unwrap()+ .read_to_string(&mut contents)+ .unwrap();+ assert!(+ contents.trim() == "start",+ "hook should not have reached 'done'; got: {contents:?}"+ );+}+// ============================================================================// User Post-Merge Hook Tests// ============================================================================