Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

fix(tether): stop supervised processes on Ctrl-C (#4623)

Worktrunk Bote82f74e5df02
diff --git a/src/commands/step/tether.rs b/src/commands/step/tether.rs
index 593d66cde..3afa6a801 100644
--- a/src/commands/step/tether.rs
+++ b/src/commands/step/tether.rs
@@ -27,6 +27,7 @@
//! outlive it — Windows neither reparents to a single init nor offers a pgid.
use std::path::Path;
+use std::sync::Arc;
use std::time::Duration;
use anyhow::{Context, Result};
@@ -65,23 +66,33 @@ pub(crate) fn step_tether(command: &[String], working_dir: Option<&Path>) -> Res
// shell's directory.
worktrunk::shell_exec::scrub_directive_env_vars(&mut cmd);
set_new_process_group(&mut cmd);
+ // The supervised command is in a different process group, so terminal
+ // Ctrl-C reaches this supervisor alone. Hold a foreground signal lease
+ // while it runs; the reaper observes cancellation and sweeps its group.
+ #[cfg(unix)]
+ let signals = worktrunk::signal_forwarder::ForegroundSignals::install(
+ worktrunk::shell_exec::TerminalInterrupt::Cancels,
+ )?;
let mut trace = CommandTrace::new(None, &command.join(" "));
- let mut child = match worktrunk::shell_exec::spawn(&mut cmd) {
+ #[cfg(unix)]
+ let spawned = signals.spawn(&mut cmd);
+ #[cfg(windows)]
+ let spawned = worktrunk::shell_exec::spawn_shared_child(&mut cmd).map_err(anyhow::Error::from);
+ let child = match spawned {
Ok(child) => child,
Err(e) => {
- trace.fail(&e);
+ trace.fail(e.as_ref());
return Err(e).with_context(|| format!("spawn tethered command: {}", command[0]));
}
};
+ let child = Arc::new(child);
let id = child.id();
- // Reaper: polls until the worktree is gone, then kills the tree so the
- // supervised child exits and `wait` returns. Only spawned when there is a
- // worktree to watch; otherwise teardown relies solely on the command's
- // own exit.
- if let Some(dir) = worktree {
+ // Reaper: polls for worktree removal or command interruption, then kills
+ // the tree so the supervised child exits and `wait` returns.
+ if worktree.is_some() || cfg!(unix) {
std::thread::spawn(move || {
- while !worktree_gone(&dir) {
+ while !worktree.as_deref().is_some_and(worktree_gone) && !interrupted() {
std::thread::sleep(POLL_INTERVAL);
}
kill_process_tree(id);
@@ -89,7 +100,11 @@ pub(crate) fn step_tether(command: &[String], working_dir: Option<&Path>) -> Res
}
// Block until the child exits — killed by the reaper, or on its own.
- match child.wait() {
+ #[cfg(unix)]
+ let waited = signals.wait(&child).map(|outcome| outcome.status);
+ #[cfg(windows)]
+ let waited = child.wait();
+ match waited {
Ok(status) => trace.complete(status.success()),
Err(e) => trace.fail(&e),
}
@@ -104,6 +119,16 @@ pub(crate) fn step_tether(command: &[String], working_dir: Option<&Path>) -> Res
Ok(())
}
+#[cfg(unix)]
+fn interrupted() -> bool {
+ worktrunk::signal_forwarder::operation_interrupt_signal().is_some()
+}
+
+#[cfg(windows)]
+fn interrupted() -> bool {
+ false
+}
+
/// The worktree path no longer resolves. Only `NotFound` counts as gone; a
/// transient stat error (`EACCES`, `EIO`) is not a removal, so the reaper
/// keeps waiting rather than tearing down a live server.
diff --git a/tests/integration_tests/step_tether.rs b/tests/integration_tests/step_tether.rs
index 5e2c95f85..8c75d345a 100644
--- a/tests/integration_tests/step_tether.rs
+++ b/tests/integration_tests/step_tether.rs
@@ -133,6 +133,56 @@ fn test_tether_kills_process_group_when_command_exits(repo: TestRepo) {
);
}
+/// A terminal Ctrl-C reaches the supervisor's foreground group, while the
+/// supervised command is in a separate group. The supervisor must still reap
+/// that command before it exits.
+#[rstest]
+fn test_tether_kills_process_group_when_interrupted(repo: TestRepo) {
+ use std::os::unix::process::CommandExt;
+
+ let pidfile = repo.home_path().join("tether-interrupted.pgid");
+ let snippet = format!(
+ "printf %s \"$$\" > \"{}\"; exec sleep 600",
+ pidfile.display()
+ );
+ let mut command = repo.wt_command();
+ command
+ .args(["step", "tether", "--", "sh", "-c", &snippet])
+ .current_dir(repo.path())
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .process_group(0);
+ let mut supervisor = command.spawn().expect("spawn wt step tether");
+ wait_for_file_content(&pidfile);
+ let pgid: i32 = std::fs::read_to_string(&pidfile)
+ .unwrap()
+ .trim()
+ .parse()
+ .expect("supervised command PID");
+ assert_ne!(supervisor.id() as i32, pgid);
+ assert!(
+ group_alive(pgid),
+ "supervised group should be alive before Ctrl-C"
+ );
+
+ kill(
+ Pid::from_raw(-(supervisor.id() as i32)),
+ nix::sys::signal::Signal::SIGINT,
+ )
+ .expect("signal the supervisor's foreground group");
+ let supervisor_exited = wait_until(|| supervisor.try_wait().unwrap().is_some());
+ let group_gone = wait_until(|| !group_alive(pgid));
+
+ // Clean up before asserting so a failure cannot leak the sleep.
+ let _ = kill(Pid::from_raw(-pgid), nix::sys::signal::Signal::SIGKILL);
+ let _ = supervisor.kill();
+ let _ = supervisor.wait();
+
+ assert!(supervisor_exited, "the supervisor should exit after Ctrl-C");
+ assert!(group_gone, "Ctrl-C must kill the supervised process group");
+}
+
/// The global `-C <dir>` flag runs the tethered command in that directory —
/// the canonical way to start a server from a subdirectory (Astro in `docs/`,
/// a dev server in `frontend/`) given the command runs directly with no shell