Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix: preserve native foreground job control (#4400)
Maximilian Rooscd6732e93a44
diff --git a/.claude/skills/writing-user-outputs/SKILL.md b/.claude/skills/writing-user-outputs/SKILL.mdindex 8e2f48d45..41f81e1e6 100644--- a/.claude/skills/writing-user-outputs/SKILL.md+++ b/.claude/skills/writing-user-outputs/SKILL.md@@ -180,12 +180,12 @@ Examples that page: `--help`, `wt config show`, `wt hook show`, `wt step {commitBuild the whole output into a `String` first (don't stream), then:```rust-crate::help_pager::show_help_in_pager(&out, true);+crate::help_pager::show_help_in_pager(&out, true)?;```-The helper is infallible from the caller's perspective — it falls back to-plain stdout itself when no pager is configured, stdout isn't a TTY, or the-pager fails.+The helper falls back to plain stdout when paging is disabled or unavailable,+stdout is not a TTY, or the pager cannot start. Propagate its result so native+signal failures and cancellation reach command cleanup.## Securitydiff --git a/AGENTS.md b/AGENTS.mdindex 501b92156..4c20ad41c 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -76,7 +76,7 @@ Worktrunk touches the network only when the user asks for it. The first Reposito### Signal Handling: Ctrl-C Cancels the Current Command-When a child is interrupted, every foreground loop stops before its next step, including Warn hook pipelines and worktree loops. Use err.interrupt_signal() from ErrorExt and propagate WorktrunkError::Interrupted. Capture mode treats SIGINT and SIGTERM as interrupts; other child signals remain visible failures. See src/shell_exec.rs and src/commands/command_executor.rs for signal normalization and rendering.+Foreground commands share the caller's native job group. A child terminated by SIGINT or SIGTERM stops every foreground loop before its next step, including Warn hook pipelines and worktree loops. A caught Ctrl-C retains the child's normal exit semantics, including an ordinary exit code 130; do not infer cancellation from numeric exit codes. SIGTERM addressed to wt cancels its owned work even if the child catches it. Use err.interrupt_signal() from ErrorExt and propagate WorktrunkError::Interrupted through loops. Capture mode also classifies native SIGINT/SIGTERM exits; other child signals remain visible failures. See src/shell_exec.rs and src/signal_forwarder.rs for the contracts.### Project Commands Run Only After Approvaldiff --git a/Cargo.lock b/Cargo.lockindex dc0d4767c..16ff086e3 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4703,6 +4703,7 @@ dependencies = ["regex","renamore","rstest",+ "rustix","sanitize-filename","schemars","serde",@@ -4714,6 +4715,7 @@ dependencies = ["signal-hook 0.4.4","similar 3.2.0","skim",+ "socket2","strsim","strum","supports-hyperlinks",diff --git a/Cargo.toml b/Cargo.tomlindex f47fc1f0d..484488258 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -244,7 +244,7 @@ ignore = "0.4"reflink-copy = "0.1"# Atomic, no-overwrite rename (renameat2 / renamex_np / MoveFileExW) for# `--clobber` backups — closes the check-then-rename TOCTOU. Keeps the FFI-# (and its `unsafe`) out of this crate, which is `unsafe_code = "forbid"`.+# (and its `unsafe`) out of this crate.renamore = "0.3"dashmap = "6.2.1"fs2 = "0.4.3"@@ -272,6 +272,8 @@ tempfile = "3.27"# picker's pager). Replaced `wait-timeout`, whose SIGCHLD handler aborts the# process when its self-pipe write fails — see "Timed waits" in `shell_exec`.shared_child = "1.1"+# Socket construction separate from connection waits under the spawn guard.+socket2 = "0.6.4"# Interactive picker (`wt switch`) TUI stack, pulled in only by the `cli`# feature's `dep:` entries. These are platform-neutral (skim 4.x is the@@ -322,11 +324,13 @@ arboard = { version = "3.4", optional = true, default-features = false, featuresopen = { version = "5.3", optional = true }[target.'cfg(unix)'.dependencies]-# Unix-only syscall crates: `nix` (process/signal) backs the fsmonitor reap and-# `signal-hook` forwards Ctrl-C to child process groups. Gating keeps both out of-# the Windows dependency graph.-nix = { version = "0.31.3", default-features = false, features = ["process", "signal"] }+# Unix-only syscall crates: `nix` backs process waits and pipe readiness;+# `signal-hook` observes native job interrupts and relays PID-targeted TERM.+# Gating keeps both out of the Windows dependency graph.+nix = { version = "0.31.3", default-features = false, features = ["event", "fs", "poll", "process", "signal"] }signal-hook = "0.4.1"+# Safe FIONREAD snapshots bound cancellation drains even with continuous writers.+rustix = "1.1.4"[build-dependencies]vergen-gitcl = { version = "10.0.0", features = ["build"] }@@ -374,7 +378,9 @@ name = "picker_preview"harness = false[lints.rust]-unsafe_code = "forbid"+unexpected_cfgs = { level = "warn", check-cfg = ["cfg(coverage)"] }+# Native signal inspection and coverage flushing permit scoped runtime calls.+unsafe_code = "deny"# The profile that 'dist' will build with[profile.dist]diff --git a/docs/src/content/docs/shell-integration.md b/docs/src/content/docs/shell-integration.mdindex 0f705a53a..cd65caf8f 100644--- a/docs/src/content/docs/shell-integration.md+++ b/docs/src/content/docs/shell-integration.md@@ -28,7 +28,7 @@ eval "$(wt config shell init zsh)"# fish (~/.config/fish/config.fish):wt config shell init fish | source-# nushell (experimental) — save to vendor autoload directory:+# nushell 0.113+ (experimental) — save to vendor autoload directory:wt config shell init nu | save -f ($nu.vendor-autoload-dirs | last | path join wt.nu)# PowerShell ($PROFILE):@@ -42,7 +42,7 @@ Invoke-Expression (& wt config shell init powershell | Out-String)- **Bash**: adds a line to `~/.bashrc`- **Zsh**: adds a line to `~/.zshrc` (or `$ZDOTDIR/.zshrc`)- **Fish**: creates `~/.config/fish/functions/wt.fish` and `~/.config/fish/completions/wt.fish` (under `$XDG_CONFIG_HOME/fish` when that is set)-- **Nushell** <span class="badge-experimental"></span>: creates `wt.nu` in Nushell's user vendor-autoload directory — the last entry of `$nu.vendor-autoload-dirs`, under `$nu.data-dir` (typically `~/.local/share/nushell/vendor/autoload` on Linux, `~/Library/Application Support/nushell/vendor/autoload` on macOS)+- **Nushell 0.113+** <span class="badge-experimental"></span>: creates `wt.nu` in Nushell's user vendor-autoload directory — the last entry of `$nu.vendor-autoload-dirs`, under `$nu.data-dir` (typically `~/.local/share/nushell/vendor/autoload` on Linux, `~/Library/Application Support/nushell/vendor/autoload` on macOS)- **PowerShell** (Windows): creates both profile files if they don't exist:- `Documents/PowerShell/Microsoft.PowerShell_profile.ps1` (PowerShell 7+)- `Documents/WindowsPowerShell/Microsoft.PowerShell_profile.ps1` (Windows PowerShell 5.1)diff --git a/docs/src/content/docs/step.md b/docs/src/content/docs/step.mdindex 111efccca..ec80370a1 100644--- a/docs/src/content/docs/step.md+++ b/docs/src/content/docs/step.md@@ -675,7 +675,7 @@ Automation:Run command in each worktree. Executes sequentially with real-time output; continues past command failures.-A summary of successes and failures is shown at the end. Context JSON — a flat object of every template variable — is piped to stdin for scripts that need structured data.+A summary of successes and failures is shown at the end. Context JSON — a flat object of every template variable — is provided on stdin for scripts that need structured data.### Argumentsdiff --git a/plugins/worktrunk/skills/worktrunk/reference/shell-integration.md b/plugins/worktrunk/skills/worktrunk/reference/shell-integration.mdindex b4680475d..f259d49e8 100644--- a/plugins/worktrunk/skills/worktrunk/reference/shell-integration.md+++ b/plugins/worktrunk/skills/worktrunk/reference/shell-integration.md@@ -24,7 +24,7 @@ eval "$(wt config shell init zsh)"# fish (~/.config/fish/config.fish):wt config shell init fish | source-# nushell (experimental) — save to vendor autoload directory:+# nushell 0.113+ (experimental) — save to vendor autoload directory:wt config shell init nu | save -f ($nu.vendor-autoload-dirs | last | path join wt.nu)# PowerShell ($PROFILE):@@ -38,7 +38,7 @@ Invoke-Expression (& wt config shell init powershell | Out-String)- **Bash**: adds a line to `~/.bashrc`- **Zsh**: adds a line to `~/.zshrc` (or `$ZDOTDIR/.zshrc`)- **Fish**: creates `~/.config/fish/functions/wt.fish` and `~/.config/fish/completions/wt.fish` (under `$XDG_CONFIG_HOME/fish` when that is set)-- **Nushell** [experimental]: creates `wt.nu` in Nushell's user vendor-autoload directory — the last entry of `$nu.vendor-autoload-dirs`, under `$nu.data-dir` (typically `~/.local/share/nushell/vendor/autoload` on Linux, `~/Library/Application Support/nushell/vendor/autoload` on macOS)+- **Nushell 0.113+** [experimental]: creates `wt.nu` in Nushell's user vendor-autoload directory — the last entry of `$nu.vendor-autoload-dirs`, under `$nu.data-dir` (typically `~/.local/share/nushell/vendor/autoload` on Linux, `~/Library/Application Support/nushell/vendor/autoload` on macOS)- **PowerShell** (Windows): creates both profile files if they don't exist:- `Documents/PowerShell/Microsoft.PowerShell_profile.ps1` (PowerShell 7+)- `Documents/WindowsPowerShell/Microsoft.PowerShell_profile.ps1` (Windows PowerShell 5.1)diff --git a/plugins/worktrunk/skills/worktrunk/reference/step.md b/plugins/worktrunk/skills/worktrunk/reference/step.mdindex bfec94bd5..784db2890 100644--- a/plugins/worktrunk/skills/worktrunk/reference/step.md+++ b/plugins/worktrunk/skills/worktrunk/reference/step.md@@ -663,7 +663,7 @@ Automation:Run command in each worktree. Executes sequentially with real-time output; continues past command failures.-A summary of successes and failures is shown at the end. Context JSON — a flat object of every template variable — is piped to stdin for scripts that need structured data.+A summary of successes and failures is shown at the end. Context JSON — a flat object of every template variable — is provided on stdin for scripts that need structured data.### Argumentsdiff --git a/skills/worktrunk/reference/shell-integration.md b/skills/worktrunk/reference/shell-integration.mdindex b4680475d..f259d49e8 100644--- a/skills/worktrunk/reference/shell-integration.md+++ b/skills/worktrunk/reference/shell-integration.md@@ -24,7 +24,7 @@ eval "$(wt config shell init zsh)"# fish (~/.config/fish/config.fish):wt config shell init fish | source-# nushell (experimental) — save to vendor autoload directory:+# nushell 0.113+ (experimental) — save to vendor autoload directory:wt config shell init nu | save -f ($nu.vendor-autoload-dirs | last | path join wt.nu)# PowerShell ($PROFILE):@@ -38,7 +38,7 @@ Invoke-Expression (& wt config shell init powershell | Out-String)- **Bash**: adds a line to `~/.bashrc`- **Zsh**: adds a line to `~/.zshrc` (or `$ZDOTDIR/.zshrc`)- **Fish**: creates `~/.config/fish/functions/wt.fish` and `~/.config/fish/completions/wt.fish` (under `$XDG_CONFIG_HOME/fish` when that is set)-- **Nushell** [experimental]: creates `wt.nu` in Nushell's user vendor-autoload directory — the last entry of `$nu.vendor-autoload-dirs`, under `$nu.data-dir` (typically `~/.local/share/nushell/vendor/autoload` on Linux, `~/Library/Application Support/nushell/vendor/autoload` on macOS)+- **Nushell 0.113+** [experimental]: creates `wt.nu` in Nushell's user vendor-autoload directory — the last entry of `$nu.vendor-autoload-dirs`, under `$nu.data-dir` (typically `~/.local/share/nushell/vendor/autoload` on Linux, `~/Library/Application Support/nushell/vendor/autoload` on macOS)- **PowerShell** (Windows): creates both profile files if they don't exist:- `Documents/PowerShell/Microsoft.PowerShell_profile.ps1` (PowerShell 7+)- `Documents/WindowsPowerShell/Microsoft.PowerShell_profile.ps1` (Windows PowerShell 5.1)diff --git a/skills/worktrunk/reference/step.md b/skills/worktrunk/reference/step.mdindex bfec94bd5..784db2890 100644--- a/skills/worktrunk/reference/step.md+++ b/skills/worktrunk/reference/step.md@@ -663,7 +663,7 @@ Automation:Run command in each worktree. Executes sequentially with real-time output; continues past command failures.-A summary of successes and failures is shown at the end. Context JSON — a flat object of every template variable — is piped to stdin for scripts that need structured data.+A summary of successes and failures is shown at the end. Context JSON — a flat object of every template variable — is provided on stdin for scripts that need structured data.### Argumentsdiff --git a/src/cli/config.rs b/src/cli/config.rsindex 21b675985..b49e434a0 100644--- a/src/cli/config.rs+++ b/src/cli/config.rs@@ -50,7 +50,7 @@ Zsh (~/.zshrc):eval "$(wt config shell init zsh)"```-Nushell [experimental] — save to vendor autoload directory:+Nushell 0.113+ [experimental] — save to vendor autoload directory:```console$ wt config shell init nu | save -f ($nu.vendor-autoload-dirs | last | path join wt.nu)```"#diff --git a/src/cli/step.rs b/src/cli/step.rsindex e56650d85..822be66aa 100644--- a/src/cli/step.rs+++ b/src/cli/step.rs@@ -508,7 +508,7 @@ feature/auth////// Executes sequentially with real-time output; continues past command failures.#[command(- after_long_help = r#"A summary of successes and failures is shown at the end. Context JSON — a flat object of every template variable — is piped to stdin for scripts that need structured data.+ after_long_help = r#"A summary of successes and failures is shown at the end. Context JSON — a flat object of every template variable — is provided on stdin for scripts that need structured data.## Argumentsdiff --git a/src/commands/config/alias.rs b/src/commands/config/alias.rsindex eef5ed487..27f8afe59 100644--- a/src/commands/config/alias.rs+++ b/src/commands/config/alias.rs@@ -114,7 +114,7 @@ fn list_aliases() -> anyhow::Result<()> {out.push_str(&format_entry(name, cfg, *source, &bodies, None));out.push('\n');}- crate::help_pager::show_help_in_pager(&out, true);+ crate::help_pager::show_help_in_pager(&out, true)?;Ok(())}diff --git a/src/commands/config/approvals.rs b/src/commands/config/approvals.rsindex 540b5bec3..53176ab2d 100644--- a/src/commands/config/approvals.rs+++ b/src/commands/config/approvals.rs@@ -185,7 +185,7 @@ pub fn list_approvals(format: SwitchFormat) -> anyhow::Result<()> {// Human-oriented sectioned output, plausibly more than a screen — page it// like `wt hook show`. The helper TTY-detects, so piping stays plain.- crate::help_pager::show_help_in_pager(&out, true);+ crate::help_pager::show_help_in_pager(&out, true)?;Ok(())}diff --git a/src/commands/config/show.rs b/src/commands/config/show.rsindex 0d3798b8c..f870faa1d 100644--- a/src/commands/config/show.rs+++ b/src/commands/config/show.rs@@ -133,7 +133,7 @@ pub fn handle_config_show(full: bool, format: SwitchFormat) -> anyhow::Result<()render_runtime_info(&mut show_output)?;// Display through pager (config show is always long-form output)- show_help_in_pager(&show_output, true);+ show_help_in_pager(&show_output, true)?;if invalid {return Err(WorktrunkError::AlreadyDisplayed { exit_code: 1 }.into());diff --git a/src/commands/config/state.rs b/src/commands/config/state.rsindex 6e0b92afb..f6dfc9d36 100644--- a/src/commands/config/state.rs+++ b/src/commands/config/state.rs@@ -673,7 +673,7 @@ pub fn handle_logs_list(format: SwitchFormat) -> anyhow::Result<()> {let mut out = String::new();render_all_log_sections(&mut out, &repo)?;- show_help_in_pager(&out, true);+ show_help_in_pager(&out, true)?;Ok(())}@@ -723,7 +723,7 @@ pub fn handle_logs_profile(file: Option<PathBuf>, format: SwitchFormat) -> anyhoif format == SwitchFormat::Json {print_json(&profile)?;} else {- show_help_in_pager(&profile.render_text(&source), true);+ show_help_in_pager(&profile.render_text(&source), true)?;}Ok(())}@@ -1459,7 +1459,7 @@ fn handle_state_show_table(repo: &Repository) -> anyhow::Result<()> {writeln!(out, "{}", rendered.trim_end())?;}- show_help_in_pager(&out, true);+ show_help_in_pager(&out, true)?;Ok(())}@@ -1492,7 +1492,7 @@ fn handle_cache_get_table(repo: &Repository) -> anyhow::Result<()> {writeln!(out)?;render_hints_section(&mut out, repo)?;- show_help_in_pager(&out, true);+ show_help_in_pager(&out, true)?;Ok(())}diff --git a/src/commands/custom.rs b/src/commands/custom.rsindex 580b93587..1d7f30366 100644--- a/src/commands/custom.rs+++ b/src/commands/custom.rs@@ -30,9 +30,12 @@use std::ffi::OsString;use std::path::{Path, PathBuf};use std::process::Command;+use std::sync::Arc;use anyhow::{Context, Result};use worktrunk::git::WorktrunkError;+#[cfg(not(unix))]+use worktrunk::shell_exec::wait_shared_child;use worktrunk::shell_exec::{DIRECTIVE_EXEC_FILE_ENV_VAR, RETIRED_DIRECTIVE_FILE_ENV_VAR};use worktrunk::trace::CommandTrace;@@ -131,7 +134,7 @@ fn unrecognized_subcommand_error(name: &str) -> clap::Error {build_invalid_subcommand_error(&mut cmd, name, suggestions)}-/// Spawn the custom binary, inheriting stdio, and propagate its exit code.+/// Run the custom binary in the native foreground job, preserving handled signals.fn run_custom(path: &Path, args: &[OsString], working_dir: Option<&Path>) -> Result<()> {let mut cmd = Command::new(path);cmd.args(args);@@ -143,17 +146,42 @@ fn run_custom(path: &Path, args: &[OsString], working_dir: Option<&Path>) -> Rescmd.current_dir(dir);}+ #[cfg(unix)]+ let signals = worktrunk::signal_forwarder::ForegroundSignals::install()?;let mut trace = CommandTrace::new(None, &path.display().to_string());- let status = match cmd.status() {- Ok(status) => {- trace.complete(status.success());- status+ #[cfg(unix)]+ let spawned = signals.spawn(&mut cmd);+ #[cfg(not(unix))]+ let spawned = worktrunk::shell_exec::spawn_shared_child(&mut cmd).map_err(anyhow::Error::from);+ let child = match spawned {+ Ok(child) => Arc::new(child),+ Err(error) => {+ trace.fail(&error);+ return Err(error).with_context(|| format!("failed to execute {}", path.display()));}- Err(e) => {- trace.fail(&e);- return Err(e).with_context(|| format!("failed to execute {}", path.display()));+ };+ #[cfg(unix)]+ let waited = signals+ .wait(&child)+ .map(|outcome| (outcome.status, outcome.cancellation));+ #[cfg(not(unix))]+ let waited = wait_shared_child(&child, None).map(|status| (status, None));+ let (status, cancellation) = match waited {+ Ok(outcome) => outcome,+ Err(error) => {+ #[cfg(not(unix))]+ {+ let _ = child.kill();+ let _ = wait_shared_child(&child, None);+ }+ trace.fail(&error);+ return Err(error).with_context(|| format!("failed to execute {}", path.display()));}};+ trace.complete(status.success());+ if let Some(signal) = cancellation {+ return Err(WorktrunkError::Interrupted { signal, hint: None }.into());+ }if status.success() {return Ok(());@@ -161,9 +189,8 @@ fn run_custom(path: &Path, args: &[OsString], working_dir: Option<&Path>) -> Res// Propagate the exact exit status so `wt foo` behaves like running// `wt-foo` directly. A signal kill surfaces as `Interrupted` (exit- // `128 + sig`, rendered per shell convention — a signal-killed child- // usually never got to report anything, and wt's own survival suppresses- // the shell's "Terminated" line). A plain non-zero exit surfaces as+ // `128 + sig`, with native INT/TERM passed on to the parent shell).+ // A plain non-zero exit surfaces as// `AlreadyDisplayed` (not `ChildProcessExited`): the custom command// already reported its own failure, so `wt` just forwards the code// without adding a second error line.diff --git a/src/commands/for_each.rs b/src/commands/for_each.rsindex f5682feb2..1d7da24ff 100644--- a/src/commands/for_each.rs+++ b/src/commands/for_each.rs@@ -47,7 +47,7 @@ use crate::output::print_json;/// real-time. Continues on errors and reports a summary at the end.////// All template variables from hooks are available; values are substituted-/// into argv elements without shell escaping. Context JSON is piped to stdin.+/// into argv elements without shell escaping. Context JSON is provided on stdin.pub fn step_for_each(args: Vec<String>, format: crate::cli::SwitchFormat) -> anyhow::Result<()> {let json_mode = format == crate::cli::SwitchFormat::Json;let repo = Repository::current()?;@@ -202,7 +202,7 @@ pub fn step_for_each(args: Vec<String>, format: crate::cli::SwitchFormat) -> any}/// Run argv directly (no shell) with streaming output, signal forwarding,-/// stdout→stderr redirect, and JSON context piped on stdin.+/// stdout→stderr redirect, and JSON context on stdin.////// Mirrors the bookkeeping in `output::execute_shell_command` (flush, ANSI/// reset, signal forwarding) but builds the command via `Cmd::new` so thediff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rsindex fd1cf8048..2971d230b 100644--- a/src/commands/hook_commands.rs+++ b/src/commands/hook_commands.rs@@ -423,7 +423,7 @@ pub fn handle_hook_show(ctx.as_ref(),)?;- show_help_in_pager(&output, true);+ show_help_in_pager(&output, true)?;Ok(())}diff --git a/src/commands/list/collect/tasks.rs b/src/commands/list/collect/tasks.rsindex d6ba658cf..970452505 100644--- a/src/commands/list/collect/tasks.rs+++ b/src/commands/list/collect/tasks.rs@@ -3,7 +3,7 @@//! Each [`TaskKind`] dispatches here to one private computation over a shared//! [`TaskContext`].-use std::net::{SocketAddr, TcpStream};+use std::net::SocketAddr;use std::time::Duration;use std::sync::Arc;@@ -742,7 +742,9 @@ fn compute_url_status(ctx: &TaskContext) -> anyhow::Result<TaskResult> {parse_port_from_url(url).map(|port| {// Quick TCP connect check with 50ms timeoutlet addr = SocketAddr::from(([127, 0, 0, 1], port));- TcpStream::connect_timeout(&addr, Duration::from_millis(50)).is_ok()+ worktrunk::shell_exec::stream_socket(socket2::Domain::IPV4)+ .and_then(|socket| socket.connect_timeout(&addr.into(), Duration::from_millis(50)))+ .is_ok()})};diff --git a/src/commands/picker/os.rs b/src/commands/picker/os.rsindex 00ac21b16..a719b2e88 100644--- a/src/commands/picker/os.rs+++ b/src/commands/picker/os.rs@@ -7,6 +7,10 @@//! rather than surfacing it — see `PickerCollector`'s copy/open verbs.use anyhow::Context;+use std::io;+use std::process::Stdio;++use worktrunk::trace::CommandTrace;/// Copy `text` to the system clipboard.///@@ -23,8 +27,35 @@ pub(super) fn copy_to_clipboard(text: &str) -> anyhow::Result<()> {}/// Open `url` in the user's default browser via the OS opener (`open` on macOS,-/// `xdg-open` on Linux). Fire-and-forget: the opener detaches, so this returns-/// as soon as it's launched.+/// `xdg-open` on Linux). Wait for the launcher, which normally detaches the+/// browser. Retry another launcher only when spawning or waiting fails.pub(super) fn open_url(url: &str) -> anyhow::Result<()> {- open::that(url).with_context(|| format!("Failed to open {url}"))+ let launch = || {+ let mut last_error = None;+ for mut command in open::commands(url) {+ command+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null());+ let mut trace = CommandTrace::new(None, &format!("{command:?}"));+ match worktrunk::shell_exec::spawn(&mut command).and_then(|mut child| child.wait()) {+ Ok(status) => {+ trace.complete(status.success());+ return if status.success() {+ Ok(())+ } else {+ Err(io::Error::other(format!(+ "Launcher {command:?} failed with {status:?}"+ )))+ };+ }+ Err(error) => {+ trace.fail(&error);+ last_error = Some(error);+ }+ }+ }+ Err(last_error.unwrap_or_else(|| io::Error::other("No browser launcher available")))+ };+ launch().with_context(|| format!("Failed to open {url}"))}diff --git a/src/commands/picker/pager.rs b/src/commands/picker/pager.rsindex b4e521e99..ab63656bb 100644--- a/src/commands/picker/pager.rs+++ b/src/commands/picker/pager.rs@@ -1,18 +1,22 @@//! Pager detection and execution.//!//! Handles detection and use of diff pagers (delta, bat, etc.) for preview windows.+//! Input is prepared in an anonymous file before spawn. On Unix, one deadline+//! bounds both output consumption and the direct child wait,+//! including descendants retaining the pipes. Timeout closes our pipe endpoints+//! and kills/reaps only the owned pager; preview falls back to the original text.use std::io::Read;use std::process::{Command, Stdio};use std::sync::OnceLock;-use std::time::Duration;+use std::time::{Duration, Instant};use shared_child::SharedChild;use worktrunk::config::UserConfig;use worktrunk::shell::extract_filename_from_path;-use crate::pager::{git_config_pager, parse_pager_value};+use crate::pager::git_pager;/// Cached pager command, ready to use. None means no pager.static CACHED_PAGER: OnceLock<Option<String>> = OnceLock::new();@@ -58,11 +62,7 @@ pub(super) fn diff_pager() -> Option<&'static String> {}// GIT_PAGER or core.pager - apply auto-detection for delta/bat- let pager = if let Ok(p) = std::env::var("GIT_PAGER") {- parse_pager_value(&p)- } else {- git_config_pager()- };+ let pager = git_pager(false);pager.map(|p| {if needs_paging_disabled(&p) {@@ -82,35 +82,72 @@ pub(super) fn diff_pager() -> Option<&'static String> {pub(super) fn pipe_through_pager(text: &str, pager_cmd: &str, width: usize) -> String {tracing::debug!(pager_cmd = %pager_cmd, "Piping through pager: {}", pager_cmd);- // Spawn pager with stdin piped+ let mut trace = worktrunk::trace::CommandTrace::new(None, pager_cmd).reads_stdin(true);+ let input = match worktrunk::shell_exec::buffered_stdin(text.as_bytes()) {+ Ok(input) => input,+ Err(error) => {+ trace.fail(&error);+ return text.to_string();+ }+ };let mut cmd = Command::new("sh");cmd.arg("-c").arg(pager_cmd)- .stdin(Stdio::piped())+ .stdin(input).stdout(Stdio::piped()).stderr(Stdio::null()).env("COLUMNS", width.to_string());worktrunk::shell_exec::scrub_directive_env_vars(&mut cmd);- let child = match SharedChild::spawn(&mut cmd) {+ let child = match worktrunk::shell_exec::spawn_shared_child(&mut cmd) {Ok(child) => child,Err(e) => {+ trace.fail(&e);tracing::debug!(error = %e, "Failed to spawn pager: {}", e);return text.to_string();}};- // Write input to stdin in a thread to avoid deadlock.- // Thread will unblock when: (a) write completes, or (b) pipe breaks (pager exits/killed).- let stdin = child.take_stdin();- let input = text.to_string();- let writer_thread = std::thread::spawn(move || {- if let Some(mut stdin) = stdin {- use std::io::Write;- let _ = stdin.write_all(input.as_bytes());+ let deadline = Instant::now() + PAGER_TIMEOUT;+ match pager_output(&child, deadline) {+ Ok(output) => {+ trace.complete(true);+ if let Ok(output) = String::from_utf8(output) {+ return output;+ }}- });+ Err(error) => {+ trace.fail(&error);+ tracing::debug!(%error, "Pager failed; using unpaged text");+ // SharedChild retains ownership even after reaping. Never signal a+ // process group: descendants are not owned by this preview.+ let _ = child.kill();+ let _ = child.wait();+ }+ }+ text.to_string()+}++/// Consume output and wait for the direct pager within the same deadline.+#[cfg(unix)]+fn pager_output(child: &SharedChild, deadline: Instant) -> std::io::Result<Vec<u8>> {+ let stdout = child+ .take_stdout()+ .ok_or_else(|| std::io::Error::other("Pager stdout was not captured"))?;+ let mut reader = worktrunk::shell_exec::pipe::PipeReader::new(stdout, Some(deadline), None)?;+ let mut output = Vec::new();+ reader.read_to_end(&mut output)?;+ let status = worktrunk::shell_exec::wait_shared_child(child, Some(deadline))?;+ if !status.success() {+ return Err(std::io::Error::other(format!(+ "Pager exited with status: {status}"+ )));+ }+ Ok(output)+}- // Read output in a thread to avoid deadlock (can't read stdout after stdin fills)+#[cfg(not(unix))]+fn pager_output(child: &SharedChild, deadline: Instant) -> std::io::Result<Vec<u8>> {+ // Drain output while waiting so a full stdout pipe cannot block the pager.let stdout = child.take_stdout();let reader_thread = std::thread::spawn(move || {stdout.map(|mut stdout| {@@ -121,15 +158,13 @@ pub(super) fn pipe_through_pager(text: &str, pager_cmd: &str, width: usize) -> S});// Wait for pager with timeout- match child.wait_timeout(PAGER_TIMEOUT) {- Ok(Some(status)) => {+ match worktrunk::shell_exec::wait_shared_child(child, Some(deadline)) {+ Ok(status) => {// Pager exited within timeout- let _ = writer_thread.join();if let Ok(Some(output)) = reader_thread.join()&& status.success()- && let Ok(s) = String::from_utf8(output){- return s;+ return Ok(output);}tracing::debug!(status = %status, "Pager exited with status: {}", status);}@@ -143,7 +178,7 @@ pub(super) fn pipe_through_pager(text: &str, pager_cmd: &str, width: usize) -> S}}- text.to_string()+ Err(std::io::Error::other("Pager failed or timed out"))}#[cfg(test)]@@ -195,8 +230,9 @@ mod tests {#[test]fn test_pipe_through_pager_passthrough() {// Use cat as a simple pager that passes through input unchanged- let input = "line 1\nline 2\nline 3";- let result = pipe_through_pager(input, "cat", 80);+ // A large complete input reaches the pager without pipe-capacity limits.+ let input = "line 1\nline 2\nline 3\n".repeat(25_000);+ let result = pipe_through_pager(&input, "cat", 80);assert_eq!(result, input);}@@ -210,11 +246,6 @@ mod tests {/// A pager that never exits must not freeze skim's event loop: it is killed at/// `PAGER_TIMEOUT` and the preview falls back to the unpaged text.- ///- /// Explicit `exec`, because the kill reaches the pager and not its children:- /// a grandchild inherits the stdout pipe, and the reader thread this function- /// joins blocks until *it* exits. `sh -c "sleep 30"` forks here, so without- /// the `exec` the wait runs the full 30 s despite the pager being dead.#[test]#[cfg(unix)]fn test_pipe_through_pager_times_out() {@@ -229,6 +260,53 @@ mod tests {);}+ /// Descendants retaining output must not extend the preview deadline;+ /// retaining only buffered stdin must not delay completion at all.+ /// The release watchdog prevents a broken implementation from hanging the+ /// test. Correctness is the fallback output, not a wall-clock threshold.+ #[test]+ #[cfg(unix)]+ fn test_pipe_through_pager_descendant_pipes_time_out() {+ for redirect in ["", ">/dev/null"] {+ let fixture = tempfile::tempdir().unwrap();+ let release = fixture.path().join("release");+ let done = fixture.path().join("done");+ let quote =+ |path: &std::path::Path| shell_escape::escape(path.to_string_lossy()).into_owned();+ let command = format!(+ "(while [ ! -f {} ]; do sleep 0.02; done; : > {}) <&0 {} & printf transformed; exit 0",+ quote(&release),+ quote(&done),+ redirect,+ );+ let (tx, rx) = std::sync::mpsc::channel();+ let watchdog = std::thread::spawn(move || {+ let _ = rx.recv_timeout(PAGER_TIMEOUT * 3);+ std::fs::write(release, "").unwrap();+ });+ // Closing descendant stdout leaves only its inherited input file.+ // It cannot prolong the completed direct pager's lifetime.+ let input = "input\n".repeat(if redirect.is_empty() { 1 } else { 100_000 });+ let output = pipe_through_pager(&input, &command, 80);+ let _ = tx.send(());+ watchdog.join().unwrap();+ let cleanup_deadline = Instant::now() + PAGER_TIMEOUT * 3;+ while !done.exists() {+ assert!(Instant::now() < cleanup_deadline, "descendant did not exit");+ std::thread::sleep(Duration::from_millis(10));+ }+ assert_eq!(+ output,+ if redirect.is_empty() {+ input.as_str()+ } else {+ "transformed"+ },+ "descendant redirect: {redirect}"+ );+ }+ }+#[test]fn test_pipe_through_pager_invalid_command() {// Invalid pager command should return original text@@ -244,4 +322,10 @@ mod tests {let result = pipe_through_pager(input, "false", 80);assert_eq!(result, input);}++ #[test]+ fn test_pipe_through_pager_invalid_utf8_returns_original() {+ let input = "original text";+ assert_eq!(pipe_through_pager(input, "printf '\\377'", 80), input);+ }}diff --git a/src/commands/process.rs b/src/commands/process.rsindex ba3c6ad5c..f320a8e7b 100644--- a/src/commands/process.rs+++ b/src/commands/process.rs@@ -232,7 +232,8 @@ fn spawn_detached_unix(.process_group(0); // New process group, not in PTY's foreground group// Prevent hooks from writing to the directive fileworktrunk::shell_exec::scrub_directive_env_vars(&mut cmd);- let mut child = cmd.spawn().context("Failed to spawn detached process")?;+ let mut child =+ worktrunk::shell_exec::spawn(&mut cmd).context("Failed to spawn detached process")?;// Wait for sh to exit (immediate, doesn't block on background command)child@@ -258,8 +259,7 @@ fn spawn_detached_windows(let shell = ShellConfig::get()?;- // Git Bash and the PowerShell fallback both run the command as written —- // nothing is piped in, so neither needs a wrapper around it.+ // Git Bash runs the command as written; no stdin wrapper is needed.let mut cmd = shell.command(command);cmd.current_dir(worktree_path)@@ -273,7 +273,7 @@ fn spawn_detached_windows(.creation_flags(CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW);// Prevent hooks from writing to the directive fileworktrunk::shell_exec::scrub_directive_env_vars(&mut cmd);- cmd.spawn().context("Failed to spawn detached process")?;+ worktrunk::shell_exec::spawn(&mut cmd).context("Failed to spawn detached process")?;// Windows: Process is fully detached with a hidden window via CREATE_NO_WINDOW flag,// no need to wait (unlike Unix which waits for the outer shell)@@ -284,11 +284,11 @@ fn spawn_detached_windows(/// Spawn a detached background process by executing a binary directly.////// Unlike [`spawn_detached`] (which wraps a shell command in `sh -c`), this-/// spawns the executable without an intermediate shell. Stdin bytes are written-/// to the child's stdin pipe and then the pipe is closed.+/// spawns the executable without an intermediate shell. Complete input is+/// prepared by [`worktrunk::shell_exec::buffered_stdin`] before spawn.////// Used for structured child processes like `wt hook run-pipeline` where the parent-/// passes data via stdin rather than through a temp file or shell arguments.+/// passes data via stdin rather than through shell arguments.////// When `hook_log` is [`HookLog::Hook`], the spawn is treated as a background/// hook pipeline: the child (and every process it later spawns) receives@@ -366,14 +366,16 @@ fn spawn_detached_exec_unix(low_priority: bool,is_background_hook: bool,) -> anyhow::Result<()> {- use std::io::Write;use std::os::unix::process::CommandExt;// See [`worktrunk::priority`] for the priority-lowering rationale.let mut cmd = worktrunk::priority::command(program, low_priority);cmd.args(args).current_dir(worktree_path)- .stdin(Stdio::piped())+ .stdin(+ worktrunk::shell_exec::buffered_stdin(stdin_bytes)+ .context("Failed to prepare detached input")?,+ ).stdout(Stdio::from(log_file.try_clone()@@ -383,12 +385,7 @@ fn spawn_detached_exec_unix(.process_group(0);worktrunk::shell_exec::scrub_directive_env_vars(&mut cmd);set_background_hook_env(&mut cmd, is_background_hook);- let mut child = cmd.spawn().context("Failed to spawn detached process")?;-- if let Some(mut stdin) = child.stdin.take() {- // Ignore BrokenPipe — child may exit before reading all input.- let _ = stdin.write_all(stdin_bytes);- }+ worktrunk::shell_exec::spawn(&mut cmd).context("Failed to spawn detached process")?;Ok(())}@@ -402,7 +399,6 @@ fn spawn_detached_exec_windows(stdin_bytes: &[u8],is_background_hook: bool,) -> anyhow::Result<()> {- use std::io::Write;use std::os::windows::process::CommandExt;const CREATE_NEW_PROCESS_GROUP: u32 = 0x00000200;@@ -411,7 +407,10 @@ fn spawn_detached_exec_windows(let mut cmd = Command::new(program);cmd.args(args).current_dir(worktree_path)- .stdin(Stdio::piped())+ .stdin(+ worktrunk::shell_exec::buffered_stdin(stdin_bytes)+ .context("Failed to prepare detached input")?,+ ).stdout(Stdio::from(log_file.try_clone()@@ -421,11 +420,7 @@ fn spawn_detached_exec_windows(.creation_flags(CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW);worktrunk::shell_exec::scrub_directive_env_vars(&mut cmd);set_background_hook_env(&mut cmd, is_background_hook);- let mut child = cmd.spawn().context("Failed to spawn detached process")?;-- if let Some(mut stdin) = child.stdin.take() {- let _ = stdin.write_all(stdin_bytes);- }+ worktrunk::shell_exec::spawn(&mut cmd).context("Failed to spawn detached process")?;Ok(())}diff --git a/src/commands/run_pipeline.rs b/src/commands/run_pipeline.rsindex f6c0345fe..863b09751 100644--- a/src/commands/run_pipeline.rs+++ b/src/commands/run_pipeline.rs@@ -2,7 +2,7 @@//!//! The parent `wt` process serializes a [`PipelineSpec`] to JSON and spawns//! `wt hook run-pipeline` as a detached process (via `spawn_detached_exec`, which-//! pipes the JSON to stdin, redirects stdout/stderr to a log file, and puts+//! supplies the JSON on stdin, redirects stdout/stderr to a log file, and puts//! the process in its own process group). This module is that background//! process.//!@@ -175,7 +175,7 @@ fn spawn_shell_command(// worktree cwd, not an inherited GIT_DIR/GIT_WORK_TREE (issue #3373). This// runner only ever executes hook pipelines, so the scrub is unconditional.scrub_git_discovery_env_vars(&mut command);- let child = match command.spawn() {+ let child = match worktrunk::shell_exec::spawn(&mut command) {Ok(child) => child,Err(e) => {trace.fail(&e);@@ -395,7 +395,7 @@ mod tests {assert_eq!(message, expected_msg, "message for {sig}");assert_eq!(err.interrupt_signal(),- Some(sig),+ matches!(sig, 2 | 15).then_some(sig),"interrupt_signal for {sig}");}diff --git a/src/commands/step/prune.rs b/src/commands/step/prune.rsindex ba6e1b6be..530f97208 100644--- a/src/commands/step/prune.rs+++ b/src/commands/step/prune.rs@@ -14,6 +14,8 @@//! reproduces the serial total order the deterministic-output tests pin. The//! first failing removal//! flips an abort flag that drains the remaining queue unexecuted; the+//! command's cancellation latch also stops admission before an interrupted+//! sibling's cleanup completes. The//! current worktree is removed last, after the fan-out, because its removal//! cd's the shell to the primary.@@ -47,6 +49,19 @@ use super::super::repository_ext::{RemoveTarget, RepositoryCliExt};use super::super::worktree::{BranchFate, RemovalPlan};use crate::output::{BackgroundFallbackMode, RemovalExecution, handle_remove_output};+/// Stop queued removals and retain cancellation independently of which error+/// supplies the command's diagnostic. Captures do not publish this themselves.+fn abort_removals(_error: &anyhow::Error, abort: &AtomicBool) {+ #[cfg(unix)]+ {+ use worktrunk::git::ErrorExt as _;+ if let Some(signal) = _error.interrupt_signal() {+ worktrunk::signal_forwarder::cancel_foreground(signal);+ }+ }+ abort.store(true, Ordering::Relaxed);+}+/// A candidate worktree or branch selected for removal.#[derive(Clone)]struct Candidate {@@ -289,10 +304,29 @@ fn try_remove() -> anyhow::Result<Option<BranchFate>> {let _span = Span::new(format!("prune-remove:{}", candidate.label));+ // Cancellation may arrive while this admitted job waits for terminal output.+ // Check after acquiring it, before either stale-entry or planned mutation.+ let needs_write = plan+ .as_ref()+ .is_some_and(|plan| removal_needs_write(candidate.kind, plan, ctx));+ // These guards protect (), so poison cannot corrupt shared data.+ let (_read, _write) = if needs_write {+ (+ None,+ Some(ctx.output_lock.write().unwrap_or_else(|e| e.into_inner())),+ )+ } else {+ (+ Some(ctx.output_lock.read().unwrap_or_else(|e| e.into_inner())),+ None,+ )+ };+ #[cfg(unix)]+ if let Some(signal) = worktrunk::signal_forwarder::operation_interrupt_signal() {+ return Err(worktrunk::git::WorktrunkError::Interrupted { signal, hint: None }.into());+ }+if matches!(candidate.kind, CandidateKind::StaleDetached) {- // Output side: no exclusive output here (no spinner, no hook stream),- // so join the parallel read side of `output_lock`.- let _read = ctx.output_lock.read().unwrap_or_else(|e| e.into_inner());// Name the stale entry rather than sweeping the repository, so a// sibling whose directory is merely absent right now (unmounted// volume, half-finished `mv`) keeps its registration. `gather_check_items`@@ -308,23 +342,6 @@ fn try_remove(}let plan = plan.context("candidate arrived without a removal plan")?;- // Read side for the parallel default, write side for the exclusive cases- // (see `removal_needs_write`). The guards protect `()` — there is no- // shared state to corrupt, so a poisoned lock is meaningless here.- // Recover the guard rather than `.expect()`-ing: a panic elsewhere should- // surface as itself, not as a cascade of secondary poison panics on every- // later removal/reader.- let (_read, _write) = if removal_needs_write(candidate.kind, &plan, ctx) {- (- None,- Some(ctx.output_lock.write().unwrap_or_else(|e| e.into_inner())),- )- } else {- (- Some(ctx.output_lock.read().unwrap_or_else(|e| e.into_inner())),- None,- )- };let mut announcer = HookAnnouncer::new(ctx.repo, true);// `SynchronousForNonCurrent`: a rename-failure fallback completes inline,// so the candidate counts as removed only once the worktree and branch@@ -1238,10 +1255,8 @@ pub fn step_prune(continue;}let result = try_remove(&candidate, *plan, removal_ctx_ref)- .with_context(|| candidate.removal_context());- if result.is_err() {- abort_ref.store(true, Ordering::Relaxed);- }+ .with_context(|| candidate.removal_context())+ .inspect_err(|error| abort_removals(error, abort_ref));if done_tx.send((candidate, result)).is_err() {return;}@@ -1270,7 +1285,7 @@ pub fn step_prune(// (whose results this early return would silently drop).let outcome = outcome.context("checking branch integration")- .inspect_err(|_| abort_ref.store(true, Ordering::Relaxed))?;+ .inspect_err(|error| abort_removals(error, abort_ref))?;let Some(_reason) = outcome.reason else {continue;};diff --git a/src/commands/step/shared.rs b/src/commands/step/shared.rsindex 5acb92c8c..ca529a0de 100644--- a/src/commands/step/shared.rs+++ b/src/commands/step/shared.rs@@ -46,7 +46,7 @@ pub(super) fn print_dry_run(message_block = format_with_gutter(&formatted, None),);- crate::help_pager::show_help_in_pager(&out, true);+ crate::help_pager::show_help_in_pager(&out, true)?;Ok(())}diff --git a/src/commands/step/tether.rs b/src/commands/step/tether.rsindex 0fb8dab10..593d66cde 100644--- a/src/commands/step/tether.rs+++ b/src/commands/step/tether.rs@@ -66,7 +66,7 @@ pub(crate) fn step_tether(command: &[String], working_dir: Option<&Path>) -> Resworktrunk::shell_exec::scrub_directive_env_vars(&mut cmd);set_new_process_group(&mut cmd);let mut trace = CommandTrace::new(None, &command.join(" "));- let mut child = match cmd.spawn() {+ let mut child = match worktrunk::shell_exec::spawn(&mut cmd) {Ok(child) => child,Err(e) => {trace.fail(&e);@@ -122,8 +122,8 @@ fn set_new_process_group(cmd: &mut std::process::Command) {// POSIX `setpgid(0, 0)`: the child's pid is the new group's id, so// `child.id()` is the pgid. Children that do not re-`setpgid` (node,- // Vite, the esbuild sidecar) stay in the group. Same invariant the- // foreground runner relies on (`shell_exec.rs`).+ // Vite, the esbuild sidecar) stay in the group. Timeout-bounded captures+ // use the same ownership (`shell_exec.rs`).cmd.process_group(0);}@@ -144,7 +144,7 @@ fn kill_process_tree(pid: u32) {// `process_group(0)` made the child its own group leader, so the pid is// the pgid. The bounded TERM → KILL escalation reaches every member,// including a child that reparented to PID 1 after the leader exited.- worktrunk::shell_exec::forward_signal_with_escalation(pid as i32, signal_hook::consts::SIGTERM);+ worktrunk::shell_exec::terminate_process_group(pid as i32);}#[cfg(windows)]@@ -152,11 +152,12 @@ fn kill_process_tree(pid: u32) {// No killable process group on Windows; `taskkill /T` terminates the// process and its child tree, `/F` forces. Best-effort: the pid may// already be gone (self-exit) or have left detached children.- let _ = std::process::Command::new("taskkill")+ let mut command = std::process::Command::new("taskkill");+ command.args(["/T", "/F", "/PID", &pid.to_string()]).stdout(std::process::Stdio::null())- .stderr(std::process::Stdio::null())- .status();+ .stderr(std::process::Stdio::null());+ let _ = worktrunk::shell_exec::spawn(&mut command).and_then(|mut child| child.wait());}#[cfg(test)]diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsindex 6342a1966..6d9d101f4 100644--- a/src/commands/worktree/switch.rs+++ b/src/commands/worktree/switch.rs@@ -19,7 +19,7 @@ use worktrunk::config::{};use worktrunk::git::remote_ref::{self, RemoteRefInfo, parse_ref_url};use worktrunk::git::{- ForgeKind, GitError, GitRemoteUrl, RefType, Repository, ResolvedWorktree, Selector,+ ErrorExt, ForgeKind, GitError, GitRemoteUrl, RefType, Repository, ResolvedWorktree, Selector,SwitchSuggestionCtx, WorktreeId, branch_tracks_ref, current_or_recover, resolve_input_path,};use worktrunk::path::format_path_for_display;@@ -872,21 +872,9 @@ fn setup_fork_branch(),).map_err(|e| {- // Same mapping as the `Regular` arm: git stores refs as file paths, so- // a fork PR whose head ref is `feature` cannot create a branch in a- // repo that already has `feature/x`. Name the conflicting branch- // instead of passing on git's raw "cannot lock ref" text.- match detect_branch_namespace_conflict(repo, branch) {- Some(conflicting) => GitError::BranchNamespaceConflict {- branch: branch.to_string(),- conflicting,- },- // No leftover-branch hint on this path: `wt switch pr:N` is the- // re-run, and it adopts or prefixes the branch on its own terms- // (see this function's docstring), so naming the ref would point at- // a recovery that isn't the one to take.- None => worktree_creation_error(&e, branch.to_string(), None, false),- }+ // No leftover-branch hint here: `wt switch pr:N` adopts or prefixes+ // the branch on re-run, so naming the ref would suggest the wrong recovery.+ worktree_creation_error(repo, e, branch.to_string(), None, false)})?;// Configure branch tracking for pull and push@@ -1232,29 +1220,13 @@ fn execute_switch(Repository::SLOW_OPERATION_DELAY_MS,progress_msg,) {- // A new branch whose name is a path prefix of (or sits- // under) an existing branch can't be created: git stores- // refs as file paths, so `release` and `release/2026.4`- // can't coexist. Surface that as a clear, actionable- // error instead of git's raw "cannot lock ref" text.- if *create_branch- && let Some(conflicting) =- detect_branch_namespace_conflict(repo, &branch)- {- return Err(GitError::BranchNamespaceConflict {- branch: branch.clone(),- conflicting,- }- .into());- }- let leftover = *create_branch && failed_add_left_branch(repo, &branch);return Err(worktree_creation_error(- &e,+ repo,+ e,branch.clone(),base_branch.clone(),- leftover,- )- .into());+ *create_branch,+ ));}// `--base pr:N` / `--base mr:N` against a same-repo PR/MR: the@@ -1425,18 +1397,32 @@ fn detect_branch_namespace_conflict(repo: &Repository, branch: &str) -> Option<S.map(String::from)}-/// Build a `GitError::WorktreeCreationFailed` from a failed `git worktree add`,-/// extracting the underlying command output for the error message.+/// Classify a failed `git worktree add` before inspecting any further Git state.+/// Interruptions retain their native error beneath a single-line context.+/// Ordinary failures identify namespace conflicts or render the command output.///-/// `leftover_branch` says whether the failed add left its `-b` branch behind-/// (see [`failed_add_left_branch`]); it only adds a hint naming the branch.+/// Regular branch creation inspects whether the failed add left its `-b` branch+/// behind, adding a recovery hint. Fork creation has its own re-run recovery.fn worktree_creation_error(- err: &anyhow::Error,+ repo: &Repository,+ err: anyhow::Error,branch: String,base_branch: Option<String>,- leftover_branch: bool,-) -> GitError {- let (output, command) = Repository::extract_failed_command(err);+ inspect_leftover: bool,+) -> anyhow::Error {+ if err.interrupt_signal().is_some() {+ return err.context("Worktree creation interrupted");+ }+ // Git stores refs as paths, so `release` and `release/2026.4` cannot coexist.+ if let Some(conflicting) = detect_branch_namespace_conflict(repo, &branch) {+ return GitError::BranchNamespaceConflict {+ branch,+ conflicting,+ }+ .into();+ }+ let leftover_branch = inspect_leftover && failed_add_left_branch(repo, &branch);+ let (output, command) = Repository::extract_failed_command(&err);GitError::WorktreeCreationFailed {branch,base_branch,@@ -1444,6 +1430,7 @@ fn worktree_creation_error(command,leftover_branch,}+ .into()}/// Whether a failed `git worktree add -b <branch>` left the branch behind.diff --git a/src/completion.rs b/src/completion.rsindex ea7357afc..ff91eb57b 100644--- a/src/completion.rs+++ b/src/completion.rs@@ -856,11 +856,9 @@ fn try_forward_completion_to_custom(// candidates. Uses `std::process::Command` rather than `shell_exec::Cmd`// because we only need that captured stdout, not `Cmd`'s tracing/streaming;// stderr is discarded so the child can't write above the user's prompt.- let result = cmd- .stdout(std::process::Stdio::piped())- .stderr(std::process::Stdio::null())- .spawn()?- .wait_with_output()?;+ cmd.stdout(std::process::Stdio::piped())+ .stderr(std::process::Stdio::null());+ let result = worktrunk::shell_exec::spawn(&mut cmd)?.wait_with_output()?;if result.status.success() {Ok(String::from_utf8(result.stdout).ok())} else {diff --git a/src/diagnostic.rs b/src/diagnostic.rsindex 2c1a27106..6927eec21 100644--- a/src/diagnostic.rs+++ b/src/diagnostic.rs@@ -449,9 +449,6 @@ fn environment_vars(repo: &Repository) -> String {.collect();// git's `core.pager` is the pager source `PAGER`/`GIT_PAGER` don't capture.- // Read the raw config value (not `pager::git_config_pager`, which folds an- // explicit `cat`/empty into "unset") so the report shows what git actually- // sees.let core_pager = repo.config_value("core.pager").ok()diff --git a/src/git/error.rs b/src/git/error.rsindex b18859341..dfaf8edc8 100644--- a/src/git/error.rs+++ b/src/git/error.rs@@ -134,7 +134,7 @@ pub trait ErrorExt {/// [`WorktrunkError`] variants that carry an exit code.fn exit_code(&self) -> Option<i32>;- /// If the error is signal-derived, return the terminating signal.+ /// Return SIGINT or SIGTERM for cancellation; other child signals remain failures.////// Implements the Ctrl-C cancellation policy: command loops call this/// on every per-iteration failure and, when it returns `Some(signal)`,@@ -1760,12 +1760,12 @@ impl std::fmt::Display for GitError {/// for cases that need exit code extraction or special handling.#[derive(Debug)]pub enum WorktrunkError {- /// Child process exited with non-zero code (preserves exit code for signals).+ /// Child outcome, retaining its exit code independently of cancellation.///- /// `signal` is `Some(sig)` when the process was terminated by a signal- /// (on Unix), `None` for a normal non-zero exit. Callers that must treat- /// interrupts differently from ordinary failures (e.g., aborting a loop- /// on Ctrl-C) check `signal` rather than inferring from `code`.+ /// `signal` records native signal termination or a cancellation observed by+ /// wt. A child may catch that cancellation and exit normally, even with 0;+ /// `code` still records its real outcome. Loops classify cancellation from+ /// `signal`, never by inferring from `code`.ChildProcessExited {code: i32,message: String,@@ -1782,14 +1782,11 @@ pub enum WorktrunkError {CommandNotApproved,/// Error already displayed, just exit with given code (silent error)AlreadyDisplayed { exit_code: i32 },- /// A signal killed the foreground child and the command aborted.+ /// The operation was cancelled, possibly before any child was admitted.///- /// Exits `128 + signal` and renders once, at exit, following the shell- /// convention for a killed job: nothing for SIGINT (the terminal already- /// echoed `^C`), `Terminated` for SIGTERM. wt traps signals to forward- /// them to children, so the shell never sees wt die and won't print that- /// line itself. `hint` carries an optional recovery line (e.g. a rebase- /// left in progress) rendered under the message.+ /// Exits `128 + signal`; Unix INT/TERM are passed to the parent shell.+ /// Native job messages belong to that shell, while recovery hints belong+ /// to wt. Custom commands may also report other signal-derived exits here.Interrupted { signal: i32, hint: Option<String> },}@@ -1819,6 +1816,27 @@ impl std::fmt::Display for WorktrunkError {}impl WorktrunkError {+ /// Preserve a child's physical status separately from operation cancellation.+ pub fn from_child_status(status: &std::process::ExitStatus, cancellation: Option<i32>) -> Self {+ #[cfg(unix)]+ let signal = std::os::unix::process::ExitStatusExt::signal(status);+ #[cfg(not(unix))]+ let signal: Option<i32> = None;+ let code = status+ .code()+ .or_else(|| signal.map(|signal| 128 + signal))+ .unwrap_or(1);+ let message = match signal {+ Some(signal) => format!("terminated by signal {signal}"),+ None => format!("exit status: {code}"),+ };+ Self::ChildProcessExited {+ code,+ message,+ signal: cancellation.or(signal),+ }+ }+/// Exit code carried by this variant, if any.pub fn exit_code(&self) -> Option<i32> {match self {@@ -1857,12 +1875,11 @@ impl Diagnostic for WorktrunkError {String::new()}WorktrunkError::Interrupted { signal, hint } => {- // Shell convention for a killed job: silent for SIGINT (the- // terminal already echoed ^C), "Terminated" for SIGTERM, the- // signal number otherwise (reachable only from stream mode,- // where any signal classifies as an interrupt).+ // Unix passes INT/TERM to the shell; printing its termination+ // notice here would duplicate the native job message.let message = match *signal {SIGINT => None,+ SIGTERM if cfg!(unix) => None,SIGTERM => Some("Terminated".to_string()),sig => Some(format!("Killed by signal {sig}")),};@@ -1918,21 +1935,25 @@ impl ErrorExt for anyhow::Error {// through them can't demote it.match self.downcast_ref::<WorktrunkError>() {Some(WorktrunkError::ChildProcessExited {- signal: Some(sig), ..+ signal: Some(sig @ (SIGINT | SIGTERM)),+ ..+ }) => return Some(*sig),+ Some(WorktrunkError::Interrupted {+ signal: sig @ (SIGINT | SIGTERM),+ ..}) => return Some(*sig),- Some(WorktrunkError::Interrupted { signal, .. }) => return Some(*signal),_ => {}}- // Capture mode (`Cmd::run`) reports it as a `CommandError` carrying the- // raw `status.signal()`. Walk the chain so `.context(...)` layers (e.g.- // `run_command`'s "Failed to execute: git …") don't hide it. Only- // SIGINT/SIGTERM classify as interrupts here: capture children get no- // signal forwarding or escalation (unlike stream mode, where a- // SIGKILL death can be wt's own escalation of a second Ctrl-C,- // normalized upstream to the originating signal), so any other signal- // means the child fell over on its own — and because its captured- // output was never displayed, a silent interrupt exit would discard- // the evidence. Those fall through to the caller's visible error path.+ #[cfg(unix)]+ if let Some(error) = self.downcast_ref::<crate::shell_exec::StreamCommandError>()+ && let Some(signal @ (SIGINT | SIGTERM)) =+ std::os::unix::process::ExitStatusExt::signal(&error.status)+ {+ return Some(signal);+ }+ // Capture mode carries the same raw status behind context layers.+ // INT/TERM cancel the operation; crashes and other signals stay on+ // the visible error path in every execution mode.if let Some(CommandError {signal: Some(sig @ (SIGINT | SIGTERM)),..@@ -2259,7 +2280,7 @@ mod tests {}#[test]- fn interrupt_signal_capture_mode_narrows_to_sigint_sigterm() {+ fn interrupt_signal_modes_agree_on_cancellation() {// Capture mode has no signal forwarding or escalation, so SIGINT and// SIGTERM are the only signals a user interrupt can deliver; anything// else (a crash, an OOM kill) must stay on the visible error path@@ -2275,7 +2296,14 @@ mod tests {signal: Some(sig),}.into();- assert_eq!(err.interrupt_signal(), expected, "signal {sig}");+ assert_eq!(err.interrupt_signal(), expected, "capture signal {sig}");+ let streamed: anyhow::Error = WorktrunkError::ChildProcessExited {+ code: 128 + sig,+ message: format!("terminated by signal {sig}"),+ signal: Some(sig),+ }+ .into();+ assert_eq!(streamed.interrupt_signal(), expected, "stream signal {sig}");}}@@ -3084,17 +3112,19 @@ mod tests {assert_eq!(sigint.to_string(), "");assert_eq!(sigint.exit_code(), Some(130));- // SIGTERM: the line the shell would print if wt weren't trapping- // the signal.+ // Unix delegates the SIGTERM notice to the parent shell.let sigterm = WorktrunkError::Interrupted {signal: 15,hint: None,};+ #[cfg(unix)]+ assert_eq!(sigterm.render(), "");+ #[cfg(not(unix))]assert_snapshot!(sigterm.render(), @"[31m✗[39m [31mTerminated[39m");assert_eq!(sigterm.to_string(), "Terminated");assert_eq!(sigterm.exit_code(), Some(143));- // Any other signal (stream mode counts all): named by number.+ // Other custom-command signals remain visible failures.let sigkill = WorktrunkError::Interrupted {signal: 9,hint: None,@@ -3109,6 +3139,9 @@ mod tests {signal: 15,hint: Some("Rebase left in progress".to_string()),};+ #[cfg(unix)]+ assert_snapshot!(sigterm_hint.render(), @"[2m↳[22m [2mRebase left in progress[22m");+ #[cfg(not(unix))]assert_snapshot!(sigterm_hint.render(), @"[31m✗[39m [31mTerminated[39m[2m↳[22m [2mRebase left in progress[22mdiff --git a/src/git/mod.rs b/src/git/mod.rsindex 408df12e4..f46739991 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -102,8 +102,8 @@ pub use repository::sha_cache;pub use repository::{Branch, BranchDiffSpec, CommitMessageDetail, InProgressOperation, IntegrationTargets,PreparedDiff, RefSnapshot, Repository, ResolvedWorktree, Selector, StaleWorktreeWork,- TempIndex, WorkingTree, duplicated_branches, is_valid_branch_name, normalize_selector,- resolve_input_path, select_comparison_base, set_base_path,+ TempIndex, WorkingTree, base_path, duplicated_branches, is_valid_branch_name,+ normalize_selector, resolve_input_path, select_comparison_base, set_base_path,};pub use url::parse_owner_repo;pub use url::{GitRemoteUrl, GitRepoInfo, GitRepoProvider};diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex d1db8adb5..581732be5 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -619,8 +619,8 @@ pub fn set_base_path(path: PathBuf) {BASE_PATH.set(path).ok();}-/// Get the base path for repository operations.-fn base_path() -> &'static PathBuf {+/// Directory used for repository discovery, including the command's `-C` base.+pub fn base_path() -> &'static PathBuf {BASE_PATH.get().unwrap_or(&DEFAULT_BASE_PATH)}@@ -1859,7 +1859,7 @@ impl Repository {/// too long for `sun_path`, an unresolvable git dir) falls through to the/// fork, which starts the daemon or reports it running.///- /// Uses `Command::status()` with null stdio instead of `Cmd::run()` to avoid+ /// Spawns with null stdio instead of `Cmd::run()` to avoid/// pipe inheritance: the daemon process (`git fsmonitor--daemon run --detach`)/// inherits pipe file descriptors from its parent, keeping them open/// indefinitely. `read_to_end()` in `Command::output()` then blocks forever@@ -1867,10 +1867,11 @@ impl Repository {pub fn start_fsmonitor_daemon_at(&self, path: &Path) {#[cfg(unix)]if let Ok(git_dir) = self.worktree_at(path).git_dir()- && std::os::unix::net::UnixStream::connect(- git_dir.join(super::fsmonitor::IPC_SOCKET_NAME),- )- .is_ok()+ && socket2::SockAddr::unix(git_dir.join(super::fsmonitor::IPC_SOCKET_NAME))+ .and_then(|address| {+ crate::shell_exec::stream_socket(socket2::Domain::UNIX)?.connect(&address)+ })+ .is_ok(){return;}@@ -1888,10 +1889,10 @@ impl Repository {crate::shell_exec::apply_hermetic_test_env(&mut cmd);crate::shell_exec::scrub_directive_env_vars(&mut cmd);// Trace the daemon launch so it's attributed in the timeline rather than- // appearing as a gap on the switch hot path. Uses `status()` (not- // `Cmd::run`) deliberately — see the doc comment.+ // appearing as a gap on the switch hot path. Wait without captured+ // pipes (unlike `Cmd::run`) — see the daemon rationale above.let mut trace = crate::trace::CommandTrace::new(Some(&context), cmd_str);- let result = cmd.status();+ let result = crate::shell_exec::spawn(&mut cmd).and_then(|mut child| child.wait());match result {Ok(status) => {trace.complete(status.success());@@ -2162,7 +2163,7 @@ impl Repository {e.output.clone(),Some(super::error::FailedCommand {command: e.command.clone(),- exit_info: e.exit_info.clone(),+ exit_info: e.exit_info(),}),);}diff --git a/src/git/repository/tests.rs b/src/git/repository/tests.rsindex 84e7aa00c..753b0fff7 100644--- a/src/git/repository/tests.rs+++ b/src/git/repository/tests.rs@@ -695,11 +695,15 @@ fn worktree_config_enabled_detects_extension() {#[test]fn extract_failed_command_from_stream_error() {use crate::shell_exec::StreamCommandError;+ #[cfg(unix)]+ use std::os::unix::process::ExitStatusExt;+ #[cfg(windows)]+ use std::os::windows::process::ExitStatusExt;let err: anyhow::Error = StreamCommandError {output: "fatal: ref exists".into(),command: "git worktree add /path".into(),- exit_info: "exit code 128".into(),+ status: std::process::ExitStatus::from_raw(if cfg!(unix) { 128 << 8 } else { 128 }),}.into();diff --git a/src/help.rs b/src/help.rsindex 49f905a06..c53426721 100644--- a/src/help.rs+++ b/src/help.rs@@ -283,10 +283,11 @@ pub fn maybe_handle_help_with_pager(worktrunk::styling::terminal_width(),);- // show_help_in_pager checks if stdout or stderr is a TTY.- // If neither is a TTY (e.g., `wt --help &>file`), it skips the pager.+ // Page only when stdout is a TTY; redirected help stays on stdout.// use_pager=false for -h (short help), true for --help (long help)- crate::help_pager::show_help_in_pager(&help, use_pager);+ if let Err(error) = crate::help_pager::show_help_in_pager(&help, use_pager) {+ crate::handle_command_failure(error, 0, &args.join(" "));+ }process::exit(0);}ErrorKind::DisplayVersion => {diff --git a/src/help_pager.rs b/src/help_pager.rsindex cf1d682c6..04a250c6d 100644--- a/src/help_pager.rs+++ b/src/help_pager.rs@@ -1,7 +1,6 @@//! Help text pager integration for CLI help output.//!-//! Provides pager support for `--help` output, following git's pager precedence:-//! GIT_PAGER → core.pager config → PAGER environment variable → "less" default.+//! Provides pager support for `--help` output using Git's pager selection.//!//! # Difference from the diff preview pager//!@@ -11,60 +10,26 @@//! differently://!//! - Help pager: top-level user command, needs a TTY for interactive scrolling-//! - Diff preview pager: pipes the diff over stdin, appends `--paging=never`+//! - Diff preview pager: supplies the diff on stdin, appends `--paging=never`//! for pagers that would otherwise launch their own `less` (delta, bat), and-//! is killed by a `PAGER_TIMEOUT` watchdog if it blocks — it is never given a+//! is bounded by `PAGER_TIMEOUT` — it is never given a//! TTY, so it can't hang the picker's event loop//!//! Both follow git's pager detection but spawn differently based on their usage context.//!//! # Cross-Platform Support//!-//! On Windows, Git Bash (if available) enables standard pagers like `less`.-//! Without Git Bash, we only use a pager if the configured command works under-//! the PowerShell fallback; otherwise we print directly.+//! On Windows, Git Bash enables standard pagers like `less`. If the configured+//! pager cannot execute, help prints directly.-use std::io::{IsTerminal, Write};-use std::process::Stdio;-use worktrunk::shell_exec::ShellConfig;-use worktrunk::styling::print;--use crate::pager::{git_config_pager, parse_pager_value};+use std::io::IsTerminal;-/// Detect pager for help output, following git's pager precedence.-///-/// Checks in order: GIT_PAGER → git config core.pager → PAGER → "less"-///-/// On Windows without Git Bash, returns None if only `less` would be selected-/// (since `less` isn't available without Git for Windows).-fn detect_help_pager() -> Option<String> {- let shell = ShellConfig::get().ok()?;-- // Check environment variables in git's precedence order- let pager = std::env::var("GIT_PAGER")- .ok()- .and_then(|s| parse_pager_value(&s))- .or_else(git_config_pager)- .or_else(|| {- std::env::var("PAGER")- .ok()- .and_then(|s| parse_pager_value(&s))- });-- // If user explicitly configured a pager, use it- if pager.is_some() {- return pager;- }+use anyhow::{Context, Result};+use worktrunk::git::{ErrorExt, WorktrunkError};+use worktrunk::shell_exec::Cmd;+use worktrunk::styling::print;- // Default to "less" only if we have a POSIX shell (Unix or Git Bash on Windows)- // Without Git Bash, less isn't typically available on Windows- if shell.is_posix {- Some("less".to_string())- } else {- tracing::debug!("No POSIX shell available, skipping pager (less not available)");- None- }-}+use crate::pager::git_pager;/// Show help text through a pager with TTY access for interactive scrolling.///@@ -76,61 +41,81 @@ fn detect_help_pager() -> Option<String> {/// while `--help` uses a pager for longer content.////// Even when `use_pager=true`, falls back to direct output if:-/// - No pager configured (prints to stdout)+/// - Paging disabled or unavailable (prints to stdout)/// - stdout is not a TTY (prints to stdout)-/// - Pager spawn fails (prints to stdout)-/// - Pager closes stdin early or wait fails (prints to stdout)+/// - Pager cannot start or I/O fails (prints to stdout)+///+/// A running pager owns its exit status and may close stdin early when the user+/// quits. Neither causes the help text to be printed a second time.+///+/// Native child interruption or controller cancellation propagates to the+/// command's normal cleanup and signal handling instead of printing fallback help.////// Help text goes to stdout — POSIX convention (`wt --help | less` should work/// without redirection), matching `cargo`, `curl`, `python`, `git <cmd> -h`,/// and `--version` (see #2072).-pub(crate) fn show_help_in_pager(help_text: &str, use_pager: bool) {+pub(crate) fn show_help_in_pager(help_text: &str, use_pager: bool) -> Result<()> {// Short help (-h) never uses a pagerif !use_pager {tracing::debug!("Short help (-h) requested, printing directly to stdout");print!("{}", help_text);- return;+ return Ok(());}- let Some(pager_cmd) = detect_help_pager() else {- tracing::debug!("No pager configured, printing help directly to stdout");- print!("{}", help_text);- return;- };-// Only page when our output destination is a terminal.// If stdout is piped/redirected (e.g., `wt --help | grep foo`), print directly.if !std::io::stdout().is_terminal() {tracing::debug!("stdout is not a TTY, skipping pager");print!("{}", help_text);- return;+ return Ok(());}+ let Some(pager_cmd) = git_pager(true) else {+ tracing::debug!("Paging disabled or unavailable, printing help directly to stdout");+ print!("{}", help_text);+ return Ok(());+ };+tracing::debug!(pager_cmd = %pager_cmd, "Invoking pager: {}", pager_cmd);- if let Err(e) = pipe_through_pager(&pager_cmd, help_text) {- tracing::debug!(error = %e, "Pager failed, falling back to stdout: {}", e);+ if !pipe_through_pager(&pager_cmd, help_text)? {print!("{}", help_text);}+ Ok(())}-/// Pipe `help_text` to the given pager command and wait for it to exit.-///-/// Spawn / write / wait failures all surface as `Err` so the caller can fall back-/// to direct stdout. Extracted from `show_help_in_pager` so the failure paths can-/// be exercised by unit tests with stand-in commands (`true`, `cat > /dev/null`)-/// that don't depend on a real TTY.-fn pipe_through_pager(pager_cmd: &str, help_text: &str) -> std::io::Result<()> {+/// Return whether the pager handled help, or false to request stdout fallback.+/// A POSIX shell reserves 126/127 for a command it could not execute; other+/// completed statuses belong to the pager (including less -K quitting with 2).+/// Native signal failures propagate instead of requesting fallback.+fn pipe_through_pager(pager_cmd: &str, help_text: &str) -> Result<bool> {let less_flags = compute_less_flags(std::env::var("LESS").ok().as_deref());- let shell = ShellConfig::get().map_err(std::io::Error::other)?;- tracing::debug!(pager_cmd = %pager_cmd, "$ {} (pager)", pager_cmd);- let mut cmd = shell.command(pager_cmd);- worktrunk::shell_exec::scrub_directive_env_vars(&mut cmd);- let mut child = cmd.stdin(Stdio::piped()).env("LESS", &less_flags).spawn()?;- if let Some(mut stdin) = child.stdin.take() {- stdin.write_all(help_text.as_bytes())?;+ match Cmd::shell(pager_cmd)+ .stdin_bytes(help_text.as_bytes())+ .env("LESS", less_flags)+ .forward_signals()+ .stream()+ {+ Ok(()) => Ok(true),+ Err(error) => {+ if let Some(signal) = error.interrupt_signal() {+ return Err(WorktrunkError::Interrupted { signal, hint: None }.into());+ }+ match error.downcast_ref::<WorktrunkError>() {+ Some(WorktrunkError::ChildProcessExited {+ signal: Some(_), ..+ }) => Err(error).with_context(|| format!("Help pager `{pager_cmd}` failed")),+ Some(WorktrunkError::ChildProcessExited { code, .. })+ if !matches!(*code, 126 | 127) =>+ {+ Ok(true)+ }+ _ => {+ tracing::debug!(error = %error, "Pager failed, falling back to stdout: {}", error);+ Ok(false)+ }+ }+ }}- child.wait()?;- Ok(())}/// Compute LESS flags by appending our required flags to user's existing LESS setting.@@ -153,9 +138,9 @@ fn compute_less_flags(user_less: Option<&str>) -> String {/// terminal wedged (#2968). `-K` routes Ctrl-C through the same clean-exit/// path as quitting with `q`, which restores the terminal correctly.///-/// `-K` is Windows-only on purpose: on Unix the signal forwarder coordinates a-/// clean teardown, and many users rely on Ctrl-C returning `less` to its-/// prompt rather than quitting.+/// `-K` is Windows-only on purpose: on Unix the pager receives the terminal's+/// Ctrl-C directly, and wt waits while a pager that handles it keeps running.+/// Many users rely on Ctrl-C returning `less` to its prompt rather than quitting.fn compute_less_flags_for(user_less: Option<&str>, windows: bool) -> String {let base = user_less.unwrap_or_default();if windows {@@ -167,32 +152,54 @@ fn compute_less_flags_for(user_less: Option<&str>, windows: bool) -> String {#[cfg(test)]mod tests {- use super::{compute_less_flags_for, parse_pager_value};+ use super::compute_less_flags_for;- /// `cat > /dev/null` exercises the full spawn → write → wait path with a- /// stand-in pager that always succeeds. Covers every line of- /// `pipe_through_pager`'s body; the `?` propagations are line-hit even on- /// the Ok branch.#[cfg(unix)]#[test]fn test_pipe_through_pager_pipes_to_real_command() {- super::pipe_through_pager("cat > /dev/null", "help text").expect("cat should succeed");+ assert!(super::pipe_through_pager("cat > /dev/null", "help text").unwrap());}+ #[cfg(unix)]#[test]- fn test_validate_excludes_cat() {- assert_eq!(parse_pager_value("cat"), None);- assert_eq!(parse_pager_value(" cat "), None);- assert_eq!(parse_pager_value(""), None);- assert_eq!(parse_pager_value(" "), None);+ fn successful_pager_can_quit_before_consuming_input() {+ assert!(+ super::pipe_through_pager("head -c 50 > /dev/null", &"help text\n".repeat(100_000))+ .unwrap()+ );}+ #[cfg(unix)]+ #[test]+ fn completed_pager_owns_its_exit_status() {+ assert!(super::pipe_through_pager("cat > /dev/null; exit 1", "help text").unwrap());+ assert!(super::pipe_through_pager("exit 2", &"help text\n".repeat(100_000)).unwrap());+ assert!(super::pipe_through_pager("exit 7", "help text").unwrap());+ assert!(super::pipe_through_pager("exit 137", "help text").unwrap());+ }++ #[cfg(unix)]+ #[test]+ fn pager_signal_remains_a_visible_failure() {+ let error = super::pipe_through_pager("kill -KILL $$", "help text").unwrap_err();+ assert!(matches!(+ error.downcast_ref::<worktrunk::git::WorktrunkError>(),+ Some(worktrunk::git::WorktrunkError::ChildProcessExited {+ signal: Some(9),+ ..+ })+ ));+ }++ #[cfg(unix)]#[test]- fn test_validate_accepts_valid_pagers() {- assert_eq!(parse_pager_value("less"), Some("less".to_string()));- assert_eq!(parse_pager_value(" less "), Some("less".to_string()));- assert_eq!(parse_pager_value("delta"), Some("delta".to_string()));- assert_eq!(parse_pager_value("less -R"), Some("less -R".to_string()));+ fn pager_that_cannot_execute_triggers_fallback() {+ assert!(!super::pipe_through_pager("worktrunk-test-missing-pager", "help text").unwrap());+ let script = tempfile::NamedTempFile::new().unwrap();+ std::fs::write(script.path(), "#!/bin/sh\n").unwrap();+ // NamedTempFile is not executable: the shell returns reserved status 126.+ let command = shell_escape::unix::escape(script.path().to_string_lossy());+ assert!(!super::pipe_through_pager(&command, "help text").unwrap());}#[test]diff --git a/src/main.rs b/src/main.rsindex 411d6527c..ba68d8492 100644--- a/src/main.rs+++ b/src/main.rs@@ -1104,9 +1104,40 @@ fn handle_command_failure(error: anyhow::Error, verbose_level: u8, command_line:print_command_error(&error);print_cwd_removed_hint_if_needed();- // Preserve exit code from child processes (especially for signals like SIGINT)- let code = error.exit_code().unwrap_or(1);+ // Cancellation governs exit independently of the error's diagnostic and+ // recovery hints. A parallel sibling may have failed before cancellation.+ let signal = error.interrupt_signal();+ #[cfg(unix)]+ let signal = worktrunk::signal_forwarder::operation_interrupt_signal().or(signal);+ let code = signal+ .map(|signal| 128 + signal)+ .or_else(|| error.exit_code())+ .unwrap_or(1);finish_command(verbose_level, command_line, Some(&error));+ // Preserve the canonical OS signal through nested wt invocations. Converting+ // it to an ordinary 128+signal exit makes Warn pipelines continue afterward.+ #[cfg(unix)]+ if let Some(signal) = signal {+ match worktrunk::signal_forwarder::should_reraise(signal) {+ Ok(true) => {+ // Native signal death skips LLVM's atexit writer. Dump once+ // before handing control back to the OS, only in coverage builds.+ #[cfg(coverage)]+ #[expect(unsafe_code, reason = "LLVM provides this no-argument profiling API")]+ // SAFETY: cargo-llvm-cov links LLVM's profiling runtime. This+ // no-argument API runs on the main thread, outside signal handlers.+ unsafe {+ unsafe extern "C" {+ fn __llvm_profile_dump() -> std::ffi::c_int;+ }+ let _ = __llvm_profile_dump();+ }+ let _ = signal_hook::low_level::emulate_default_handler(signal);+ }+ Ok(false) => {}+ Err(error) => eprintln!("{}", error_message(error.to_string())),+ }+ }process::exit(code);}@@ -1233,7 +1264,20 @@ fn main() {return;};+ // Cancellation belongs to this command, including work admitted by a+ // parallel worker after another child's interruption was already observed.+ // The guard leaves idle terminal defaults enabled between foreground waits.+ #[cfg(unix)]+ let operation = match worktrunk::signal_forwarder::CommandOperation::start() {+ Ok(operation) => operation,+ Err(error) => handle_command_failure(error.into(), verbose, &command_line),+ };let result = dispatch_command(command, directory, yes);+ #[cfg(unix)]+ let result = result.and_then(|()| match operation.interrupt_signal() {+ Some(signal) => Err(WorktrunkError::Interrupted { signal, hint: None }.into()),+ None => Ok(()),+ });match result {Ok(()) => finish_command(verbose, &command_line, None),diff --git a/src/output/concurrent.rs b/src/output/concurrent.rsindex a657a2473..6892c5a39 100644--- a/src/output/concurrent.rs+++ b/src/output/concurrent.rs@@ -6,47 +6,44 @@//! full scrollback intact for debugging failures and work identically under//! a TTY or pipe (CI logs).//!-//! TODO: upgrade to a docker-compose-v2-style tailing display — each command-//! gets a fixed terminal region showing its last N lines, overwritten in-//! place as output arrives. Better signal-to-noise for long streams like-//! `cargo test`, but substantially more implementation (cursor tracking,-//! resize handling, TTY/non-TTY fallback, scrollback replay on failure).-//! Prefixed lines suffice until live sections are demonstrated to pay for-//! themselves.-//!//! ## Execution model//!-//! For each command:-//! 1. Spawn a shell child with stdout+stderr piped, stdin closed, and (on-//! Unix) its own process group so SIGINT/SIGTERM can be delivered to the-//! whole tree.-//! 2. Launch two reader threads that read lines and send labeled lines on-//! a shared channel. A single consumer writes to stderr — one writer-//! preserves line atomicity so readers never mix bytes mid-line.+//! Children share the caller's foreground process group with closed stdin and+//! piped stdout/stderr. A single Unix poll loop owns all output pipes and renders+//! complete labeled lines. Direct child waits run independently of output EOF.//!-//! The main thread drains the channel. A signal-listener thread blocks-//! on `signal_hook::Signals::forever()` for SIGINT/SIGTERM and forwards-//! the user's signal to every live child's process group; a second user-//! signal escalates every still-live pgroup to SIGKILL. Closing the-//! signal-hook handle on shutdown unblocks the listener.+//! Commands retain EOF semantics, including output from surviving descendants,+//! regardless of ordinary exit status. Cancellation drains queued bytes and+//! releases pipes even when an unowned descendant retains a write end.+//! Once direct waits finish, the signal listener releases its command lease;+//! a newly delivered interrupt cancels any remaining output wait.+//! Ctrl-C reaches the native job through the kernel; a caught key preserves+//! each child's normal status. PID-targeted SIGTERM reaches owned direct children.//!-//! All children always run to completion. Per-child exit status is returned-//! for the caller to fold into a failure, matching alias `thread::scope` and-//! pipeline `run_concurrent_group` semantics.+//! All direct children complete before the caller receives results in input order.-use std::io::{BufRead, BufReader, Read, Write};+use shared_child::SharedChild;+#[cfg(not(unix))]+use std::io::Read;+use std::io::Write;use std::path::Path;-use std::process::{Child, Stdio};-use std::sync::mpsc::{self, Sender};+use std::process::Stdio;+use std::sync::Arc;+use std::sync::mpsc;+#[cfg(not(unix))]+use std::sync::mpsc::Sender;use std::thread;use std::time::Instant;use anyhow::Context;use worktrunk::command_log::log_command;+#[cfg(unix)]+use worktrunk::git::ErrorExt;use worktrunk::git::WorktrunkError;use worktrunk::shell_exec::{ShellConfig, apply_cd_directive_env, scrub_directive_env_vars, scrub_git_discovery_env_vars,+ wait_foreground_child,};#[cfg(unix)]use worktrunk::signal_forwarder::ForegroundSignals;@@ -85,17 +82,17 @@ pub struct ConcurrentCommand<'a> {pub fn run_concurrent_commands(cmds: &[ConcurrentCommand<'_>],) -> anyhow::Result<Vec<anyhow::Result<()>>> {+ if cmds.is_empty() {+ return Ok(Vec::new());+ }let prefix_width = cmds.iter().map(|c| c.label.len()).max().unwrap_or(0);let shell = ShellConfig::get()?;if std::env::var_os("WORKTRUNK_TEST_SERIAL_CONCURRENT").is_some() {- return Ok(run_serial_with_prefix(shell, cmds, prefix_width));+ return run_serial_with_prefix(shell, cmds, prefix_width);}- // Install the SIGINT/SIGTERM latch BEFORE spawning any children so a- // signal that arrives mid-spawn is captured rather than default-killing- // 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).+ // Install before spawn so startup signals remain queued.#[cfg(unix)]let signals = ForegroundSignals::install()?;@@ -105,173 +102,386 @@ pub fn run_concurrent_commands(// their pipes (and `Child::drop` does not kill the process on Unix).let mut children: Vec<SpawnedChild> = Vec::with_capacity(cmds.len());for (i, cmd) in cmds.iter().enumerate() {- match spawn_child(shell, i, cmd) {+ match spawn_child(+ shell,+ i,+ cmd,+ #[cfg(unix)]+ &signals,+ ) {Ok(spawned) => children.push(spawned),Err(e) => {- for mut prior in children {- let _ = prior.child.kill();- let _ = prior.child.wait();- // Spawned but torn down because a sibling failed to spawn —- // record it rather than leaving the trace guard unresolved.- prior.trace.complete(false);+ #[cfg(unix)]+ if e.interrupt_signal().is_some() {+ // Keep admitted children's cleanup and the original+ // startup cancellation through the normal drain path.+ return drain_children(children, cmds, 0, prefix_width, signals);}+ abort_spawned_children(children);return Err(e);}}}- // Print one prefixed line at a time from a single writer. Each reader- // sends complete lines through `line_tx`; the consumer drains them.- let (line_tx, line_rx) = mpsc::channel::<LabeledLine>();+ drain_children(+ children,+ cmds,+ 0,+ prefix_width,+ #[cfg(unix)]+ signals,+ )+}- let mut readers: Vec<thread::JoinHandle<()>> = Vec::new();- for (i, spawned) in children.iter_mut().enumerate() {- let label = cmds[i].label.to_string();- if let Some(stdout) = spawned.child.stdout.take() {- readers.push(spawn_reader(i, label.clone(), stdout, line_tx.clone()));+/// Reap owned children when the group cannot finish spawning. Resolve their+/// traces even though their normal outcome collectors will never run.+fn abort_spawned_children(children: Vec<SpawnedChild>) {+ for mut spawned in children {+ let _ = spawned.child.kill();+ let _ = spawned.child.wait();+ spawned.trace.complete(false);+ }+}++/// Wait independently of output EOF. Cancellation releases remaining pipes+/// after all direct waits; ordinary exits preserve descendant output to EOF.+#[cfg(unix)]+fn drain_children(+ mut children: Vec<SpawnedChild>,+ cmds: &[ConcurrentCommand<'_>],+ offset: usize,+ prefix_width: usize,+ signals: ForegroundSignals,+) -> anyhow::Result<Vec<anyhow::Result<()>>> {+ use nix::poll::{PollFd, PollFlags, PollTimeout, poll};+ use std::io::ErrorKind;+ use std::os::fd::AsFd;++ // One wake pair serves the whole group, regardless of its number of pipes.+ // Allocate it and prepare every pipe before starting any waiter.+ let setup = (|| {+ let (control, wake) = worktrunk::shell_exec::socket_pair()?;+ control.set_nonblocking(true)?;+ wake.set_nonblocking(true)?;+ let mut pipes = Vec::with_capacity(children.len() * 2);+ for (index, child) in children.iter().enumerate() {+ let prefix = render_prefix(index + offset, cmds[index].label, prefix_width);+ if let Some(stdout) = child.child.take_stdout() {+ pipes.push(OutputPipe::new(prefix.clone(), stdout)?);+ }+ if let Some(stderr) = child.child.take_stderr() {+ pipes.push(OutputPipe::new(prefix, stderr)?);+ }}- if let Some(stderr) = spawned.child.stderr.take() {- readers.push(spawn_reader(i, label, stderr, line_tx.clone()));+ Ok::<_, std::io::Error>((control, wake, pipes))+ })();+ let (control, wake, mut pipes) = match setup {+ Ok(prepared) => prepared,+ Err(error) => {+ for child in &mut children {+ let _ = child.child.kill();+ let _ = child.child.wait();+ child.trace.fail(&error);+ }+ return Err(error).context("Failed to prepare concurrent command output");+ }+ };+ let processes: Vec<_> = children.iter().map(|child| child.child.clone()).collect();+ let (tx, rx) = mpsc::channel();+ let notify = WakeSender {+ tx,+ wake: Arc::new(wake),+ };+ let signal_notify = notify.clone();+ let mut signal_thread = signals.forward_to_children(processes.clone(), move || {+ signal_notify.wake();+ });+ let child_count = children.len();+ let mut outcomes = Vec::with_capacity(child_count);+ let mut output_error = None;+ thread::scope(|scope| {+ // Observe every exit independently: a later child's interruption must+ // cancel the operation while an earlier child is still cleaning up.+ for (index, (child, cmd)) in children.into_iter().zip(cmds).enumerate() {+ let notify = notify.clone();+ scope.spawn(move || notify.send(index, collect_outcome(child, cmd)));}+ loop {+ let result = (|| {+ // Consume the wake before the queue: a message racing the queue+ // read must leave a byte to wake the next poll.+ let mut wake_bytes = [0; 256];+ match nix::unistd::read(&control, &mut wake_bytes).map_err(std::io::Error::from) {+ Ok(_) => {}+ Err(error)+ if matches!(+ error.kind(),+ ErrorKind::WouldBlock | ErrorKind::Interrupted+ ) => {}+ Err(error) => return Err(error),+ }+ while let Ok(outcome) = rx.try_recv() {+ outcomes.push(outcome);+ }+ if outcomes.len() == child_count {+ // The execution lease ends here; the provider observes only+ // newly delivered INT while descendants retain output pipes.+ signal_thread.finish_children()?;+ }+ if outcomes.len() == child_count && signal_thread.interrupt_signal().is_some() {+ for pipe in &mut pipes {+ pipe.finish_available()?;+ }+ pipes.clear();+ }+ if outcomes.len() == child_count && pipes.is_empty() {+ return Ok(true);+ }+ let ready = {+ let mut fds = pipes+ .iter()+ .map(|pipe| PollFd::new(pipe.stream.as_fd(), PollFlags::POLLIN))+ .collect::<Vec<_>>();+ fds.push(PollFd::new(control.as_fd(), PollFlags::POLLIN));+ match poll(&mut fds, PollTimeout::NONE) {+ Ok(_) => {}+ Err(nix::errno::Errno::EINTR) => return Ok(false),+ Err(error) => return Err(error.into()),+ }+ fds.into_iter()+ .take(pipes.len())+ .map(|fd| fd.revents().unwrap_or(PollFlags::empty()))+ .collect::<Vec<_>>()+ };+ // Read one chunk per ready pipe so a continuous writer cannot+ // starve completion messages or another child's output.+ for (pipe, ready) in pipes.iter_mut().zip(ready) {+ if !ready.is_empty() && !pipe.read_ready()? {+ pipe.closed = true;+ }+ }+ pipes.retain(|pipe| !pipe.closed);+ Ok::<_, std::io::Error>(false)+ })();+ match result {+ Ok(true) => break,+ Ok(false) => {}+ Err(error) => {+ // Closing pipes releases writers; waiters still reap every+ // owned direct child before we return the I/O failure.+ pipes.clear();+ for child in &processes {+ let _ = child.kill();+ }+ output_error = Some(error);+ break;+ }+ }+ }+ });+ let cancelled = signal_thread+ .stop()+ .context("Failed to stop concurrent signal listener")?;+ if let Some(error) = output_error {+ return Err(error).context("Failed to read concurrent command output");}- // Drop the original sender so the channel closes once every reader exits.- drop(line_tx);+ if let Some(signal) = cancelled {+ return Err(WorktrunkError::Interrupted { signal, hint: None }.into());+ }+ outcomes.sort_unstable_by_key(|(index, _)| *index);+ Ok(outcomes.into_iter().map(|(_, outcome)| outcome).collect())+}- // Start the forwarder thread now that we have the pgid list. The- // `signals` latch was installed up-front, so any signal received during- // the spawn loop was queued and will be delivered on the thread's first- // poll.- #[cfg(unix)]- let signal_thread = signals.forward_to_pgids(- children- .iter()- .map(|c| c.child.id() as i32)- .collect::<Vec<_>>(),- );+#[cfg(unix)]+#[derive(Clone)]+struct WakeSender {+ tx: mpsc::Sender<(usize, anyhow::Result<()>)>,+ wake: Arc<std::os::unix::net::UnixStream>,+}- // Consume labeled lines until every reader drops its sender.- {- let mut stderr = stderr().lock();- for labeled in line_rx {- let prefix = render_prefix(labeled.index, &labeled.label, prefix_width);- writeln!(stderr, "{}{}", prefix, labeled.line).ok();+#[cfg(unix)]+impl WakeSender {+ fn send(&self, index: usize, outcome: anyhow::Result<()>) {+ if self.tx.send((index, outcome)).is_ok() {+ self.wake();}}- for r in readers {- let _ = r.join();+ fn wake(&self) {+ worktrunk::shell_exec::pipe::wake(&*self.wake);}+}++#[cfg(unix)]+struct OutputPipe {+ prefix: String,+ stream: worktrunk::shell_exec::pipe::PipeReader,+ pending: Vec<u8>,+ closed: bool,+}- // After the last output line prints, wait on each child.- let mut outcomes = Vec::with_capacity(children.len());- for (spawned, cmd) in children.into_iter().zip(cmds) {- outcomes.push(collect_outcome(spawned, cmd));+#[cfg(unix)]+impl OutputPipe {+ fn new(prefix: String, stream: impl Into<std::os::fd::OwnedFd>) -> std::io::Result<Self> {+ let stream = worktrunk::shell_exec::pipe::PipeReader::new(stream, None, None)?;+ Ok(Self {+ prefix,+ stream,+ pending: Vec::new(),+ closed: false,+ })}- #[cfg(unix)]- let originating_signal = {- // All children have exited — shut the signal forwarder down. Returns- // the first signal the forwarder observed (None if no signal arrived).- signal_thread.stop()- };- #[cfg(not(unix))]- let originating_signal: Option<i32> = None;-- // If a child died from SIGKILL because the user pressed Ctrl-C twice, the- // user-visible exit code shouldn't be 137 — they only ever sent SIGINT, and- // wt's escalation to SIGKILL on the second press is an implementation- // detail. Override each child's reported signal with the originating signal- // so wt's `exit_code()` and `interrupt_signal()` reflect the user's- // intent (130 from SIGINT, not 137 from SIGKILL).- if let Some(orig) = originating_signal {- for outcome in &mut outcomes {- override_with_originating_signal(outcome, orig);+ fn output(&mut self, bytes: &[u8]) {+ for part in bytes.split_inclusive(|byte| *byte == b'\n') {+ self.pending.extend_from_slice(part);+ if part.ends_with(b"\n") {+ self.flush_line();+ }}}- Ok(outcomes)-}--/// Replace a child's signal-derived `ChildProcessExited` error with one whose-/// `signal` / `code` / `message` reflect the originating signal wt received-/// (rather than the SIGKILL the forwarder may have escalated to on a second-/// user press). No-op if the outcome isn't a signal-derived error.-fn override_with_originating_signal(outcome: &mut anyhow::Result<()>, originating: i32) {- let Err(err) = outcome else { return };- let Some(WorktrunkError::ChildProcessExited {- signal: Some(child_sig),- ..- }) = err.downcast_ref::<WorktrunkError>()- else {- return;- };- if *child_sig == originating {- return;+ fn flush_line(&mut self) {+ let line = worktrunk::shell_exec::output_line(&self.pending);+ writeln!(stderr().lock(), "{}{}", self.prefix, line).ok();+ self.pending.clear();}- *outcome = Err(WorktrunkError::ChildProcessExited {- code: 128 + originating,- message: format!("terminated by signal {originating}"),- signal: Some(originating),++ fn read_ready(&mut self) -> std::io::Result<bool> {+ use std::io::ErrorKind;+ let mut bytes = [0; 8192];+ match self.stream.read_ready(&mut bytes) {+ Ok(0) => {+ if !self.pending.is_empty() {+ self.flush_line();+ }+ Ok(false)+ }+ Ok(count) => {+ self.output(&bytes[..count]);+ Ok(true)+ }+ Err(error)+ if matches!(error.kind(), ErrorKind::WouldBlock | ErrorKind::Interrupted) =>+ {+ Ok(true)+ }+ Err(error) => Err(error),+ }}- .into());-}-/// Serial fallback for `WORKTRUNK_TEST_SERIAL_CONCURRENT`.-///-/// Runs each command to completion before starting the next — same prefix-line-/// output, deterministic interleaving. Outcomes come back in input order.-fn run_serial_with_prefix(- shell: &ShellConfig,- cmds: &[ConcurrentCommand<'_>],- prefix_width: usize,-) -> Vec<anyhow::Result<()>> {- let mut results = Vec::with_capacity(cmds.len());- for (i, cmd) in cmds.iter().enumerate() {- let spawned = match spawn_child(shell, i, cmd) {- Ok(s) => s,- Err(e) => {- results.push(Err(e));- continue;+ /// Snapshot queued bytes once: draining until WouldBlock can run forever+ /// when an unowned descendant continuously writes without newlines.+ fn finish_available(&mut self) -> std::io::Result<()> {+ use std::io::ErrorKind;+ self.stream.cancel()?;+ let mut bytes = [0; 8192];+ loop {+ match self.stream.read_ready(&mut bytes) {+ Ok(0) => break,+ Ok(count) => self.output(&bytes[..count]),+ Err(error) if error.kind() == ErrorKind::Interrupted => continue,+ Err(error) => return Err(error),}- };- let result = drain_and_wait_single(spawned, cmd, i, prefix_width);- results.push(result);+ }+ if !self.pending.is_empty() {+ self.flush_line();+ }+ Ok(())}- results}-/// Spawn readers for one child, drain to stderr with prefixes, then wait.-fn drain_and_wait_single(- mut spawned: SpawnedChild,- cmd: &ConcurrentCommand<'_>,- index: usize,+/// Platforms without Unix poll retain blocking readers and direct-child waits.+#[cfg(not(unix))]+fn drain_children(+ children: Vec<SpawnedChild>,+ cmds: &[ConcurrentCommand<'_>],+ offset: usize,prefix_width: usize,-) -> anyhow::Result<()> {- let (tx, rx) = mpsc::channel::<LabeledLine>();- let mut readers: Vec<thread::JoinHandle<()>> = Vec::new();- let label = cmd.label.to_string();- if let Some(stdout) = spawned.child.stdout.take() {- readers.push(spawn_reader(index, label.clone(), stdout, tx.clone()));- }- if let Some(stderr) = spawned.child.stderr.take() {- readers.push(spawn_reader(index, label, stderr, tx.clone()));+) -> anyhow::Result<Vec<anyhow::Result<()>>> {+ let (tx, rx) = mpsc::channel::<Event>();+ let mut readers = Vec::new();+ for (index, child) in children.iter().enumerate() {+ let label = cmds[index].label.to_string();+ if let Some(stdout) = child.child.take_stdout() {+ readers.push(spawn_reader(+ index + offset,+ label.clone(),+ stdout,+ tx.clone(),+ ));+ }+ if let Some(stderr) = child.child.take_stderr() {+ readers.push(spawn_reader(index + offset, label, stderr, tx.clone()));+ }}drop(tx);- {- let mut out = stderr().lock();- for labeled in rx {- let prefix = render_prefix(labeled.index, &labeled.label, prefix_width);- writeln!(out, "{prefix}{}", labeled.line).ok();+ let mut output_error = None;+ let outcomes = thread::scope(|scope| {+ let waiter = scope.spawn(move || {+ children+ .into_iter()+ .zip(cmds)+ .map(|(child, cmd)| collect_outcome(child, cmd))+ .collect()+ });+ for event in rx {+ match event {+ Event::Line(labeled) => {+ let prefix = render_prefix(labeled.index, &labeled.label, prefix_width);+ writeln!(stderr().lock(), "{}{}", prefix, labeled.line).ok();+ }+ Event::ReaderClosed(Err(error)) => {+ output_error.get_or_insert(error);+ }+ Event::ReaderClosed(Ok(())) => {}+ }}+ waiter+ .join()+ .map_err(|_| anyhow::anyhow!("concurrent child waiter panicked"))+ })?;+ for reader in readers {+ reader+ .join()+ .map_err(|_| anyhow::anyhow!("concurrent output reader panicked"))?;}- for r in readers {- let _ = r.join();+ if let Some(error) = output_error {+ return Err(error).context("Failed to read concurrent command output");}- collect_outcome(spawned, cmd)+ Ok(outcomes)+}++fn run_serial_with_prefix(+ shell: &ShellConfig,+ cmds: &[ConcurrentCommand<'_>],+ prefix_width: usize,+) -> anyhow::Result<Vec<anyhow::Result<()>>> {+ let mut outcomes = Vec::with_capacity(cmds.len());+ for (index, cmd) in cmds.iter().enumerate() {+ #[cfg(unix)]+ let signals = ForegroundSignals::install()?;+ let spawned = spawn_child(+ shell,+ index,+ cmd,+ #[cfg(unix)]+ &signals,+ )?;+ outcomes.extend(drain_children(+ vec![spawned],+ std::slice::from_ref(cmd),+ index,+ prefix_width,+ #[cfg(unix)]+ signals,+ )?);+ }+ Ok(outcomes)}struct SpawnedChild {- child: Child,+ child: Arc<SharedChild>,cmd_str: String,log_label: Option<String>,started_at: Instant,@@ -285,11 +495,10 @@ fn spawn_child(shell: &ShellConfig,index: usize,cmd: &ConcurrentCommand<'_>,+ #[cfg(unix)] signals: &ForegroundSignals,) -> anyhow::Result<SpawnedChild> {- // Each child gets a closed stdin: it can't have the terminal (siblings run- // at the same time and would race for it), and each runs in its own process- // group, where a read from the controlling terminal earns SIGTTIN and stops- // the child rather than returning. A closed stdin reads EOF immediately.+ // Siblings cannot share interactive stdin, but each retains native access+ // to /dev/tty through the shell-established foreground group.let mut command = shell.command(cmd.expanded);command.current_dir(cmd.working_dir)@@ -309,12 +518,6 @@ fn spawn_child(apply_cd_directive_env(&mut command, path);}- #[cfg(unix)]- {- use std::os::unix::process::CommandExt;- command.process_group(0);- }-tracing::debug!(command = %cmd.expanded,shell = %shell.name,@@ -326,8 +529,13 @@ fn spawn_child(// Start the trace just before spawning so its duration brackets the real// spawn → wait span (the child keeps running while we drain its output).let mut trace = CommandTrace::new(None, cmd.expanded);- let child = match command.spawn() {- Ok(child) => child,+ #[cfg(unix)]+ let spawned = signals.spawn(&mut command);+ #[cfg(not(unix))]+ let spawned =+ worktrunk::shell_exec::spawn_shared_child(&mut command).map_err(anyhow::Error::from);+ let child = match spawned {+ Ok(child) => Arc::new(child),Err(e) => {trace.fail(&e);return Err(e)@@ -344,65 +552,51 @@ fn spawn_child(})}+#[cfg(not(unix))]+fn send_line(index: usize, label: &str, bytes: &[u8], tx: &Sender<Event>) {+ let _ = tx.send(Event::Line(LabeledLine {+ index,+ label: label.to_owned(),+ line: worktrunk::shell_exec::output_line(bytes).into_owned(),+ }));+}++#[cfg(not(unix))]fn spawn_reader<R: Read + Send + 'static>(index: usize,label: String,stream: R,- tx: Sender<LabeledLine>,+ tx: Sender<Event>,) -> thread::JoinHandle<()> {+ use std::io::{BufRead, BufReader};thread::spawn(move || {- // Read by bytes, not by `BufRead::lines()` — `lines()` returns- // `InvalidData` on non-UTF-8 bytes and terminates the iterator, which- // would leave the child's pipe un-drained and eventually hang- // `child.wait()` once the pipe buffer fills. Real-world triggers- // include `git diff` of binary files, tools that honor non-UTF-8- // locales, and any raw-byte output. Lossy-decoding preserves the- // stream and keeps the child unblocked.let mut reader = BufReader::new(stream);- let mut buf = Vec::with_capacity(256);- loop {- buf.clear();- match reader.read_until(b'\n', &mut buf) {- Ok(0) => return,- Ok(_) => {- // Strip the trailing newline (and optional \r) before- // forwarding — the writer re-adds a newline per line.- if buf.last() == Some(&b'\n') {- buf.pop();- if buf.last() == Some(&b'\r') {- buf.pop();- }- }- let line = String::from_utf8_lossy(&buf).into_owned();- if tx- .send(LabeledLine {- index,- label: label.clone(),- line,- })- .is_err()- {- return; // consumer dropped- }- }- Err(_) => return, // IO error on the pipe — give up on this stream+ let mut pending = Vec::new();+ let result = (|| {+ while reader.read_until(b'\n', &mut pending)? != 0 {+ send_line(index, &label, &pending, &tx);+ pending.clear();}- }+ Ok(())+ })();+ let _ = tx.send(Event::ReaderClosed(result));})}fn collect_outcome(spawned: SpawnedChild, cmd: &ConcurrentCommand<'_>) -> anyhow::Result<()> {let SpawnedChild {- mut child,+ child,cmd_str,log_label,started_at,mut trace,} = spawned;- let status = match child.wait() {+ let status = match wait_foreground_child(&child) {Ok(status) => status,Err(e) => {+ let _ = child.kill();+ let _ = child.wait();trace.fail(&e);return Err(e).with_context(|| format!("failed to wait for concurrent command '{}'", cmd.label));@@ -411,39 +605,26 @@ fn collect_outcome(spawned: SpawnedChild, cmd: &ConcurrentCommand<'_>) -> anyhowtrace.complete(status.success());let duration = started_at.elapsed();- let exit_code = status.code();-- #[cfg(unix)]- let signal = std::os::unix::process::ExitStatusExt::signal(&status);- #[cfg(not(unix))]- let signal: Option<i32> = None;-- let normalized_code = exit_code.or_else(|| signal.map(|s| 128 + s));+ let outcome = WorktrunkError::from_child_status(&status, None);if let Some(label) = log_label {- log_command(&label, &cmd_str, normalized_code, Some(duration));+ log_command(&label, &cmd_str, outcome.exit_code(), Some(duration));}if status.success() {Ok(())- } else if let Some(sig) = signal {- Err(WorktrunkError::ChildProcessExited {- code: 128 + sig,- message: format!("terminated by signal {sig}"),- signal: Some(sig),- }- .into())} else {- let code = exit_code.unwrap_or(1);- Err(WorktrunkError::ChildProcessExited {- code,- message: format!("exit status: {code}"),- signal: None,- }- .into())+ Err(outcome.into())}}+#[cfg(not(unix))]+enum Event {+ Line(LabeledLine),+ ReaderClosed(std::io::Result<()>),+}++#[cfg(not(unix))]struct LabeledLine {index: usize,label: String,@@ -470,156 +651,11 @@ fn render_prefix(index: usize, label: &str, width: usize) -> String {#[cfg(test)]mod tests {- //! Unit tests that exercise the executor's option-bearing code paths which- //! aren't reachable through the alias integration tests today: every child- //! currently has `log_label=None` (aliases skip per-child logging) and the- //! CD directive env vars are usually unset. Driving these branches- //! with a direct call proves they behave correctly when a future caller- //! (concurrent foreground hooks, once their deprecation completes) uses them.use super::*;- fn run_one_with_directives(- label: &str,- script: &str,- log_label: Option<&str>,- directives: &DirectivePassthrough,- ) -> Vec<anyhow::Result<()>> {- let wd = std::env::temp_dir();- let specs = vec![ConcurrentCommand {- label,- expanded: script,- working_dir: &wd,- log_label,- directives,- scrub_git_discovery: false,- }];- run_concurrent_commands(&specs).expect("spawn failed")- }-- /// A command with a `log_label` exercises the `log_command` branch in- /// `collect_outcome` — only hook-origin children take this path today.- #[test]- fn test_log_label_is_recorded() {- let outcomes = run_one_with_directives(- "job",- "true",- Some("test-label"),- &DirectivePassthrough::default(),- );- assert_eq!(outcomes.len(), 1);- assert!(outcomes[0].is_ok(), "`true` should exit 0");- // The logger is a global OnceCell not initialised in tests, so- // `log_command` is effectively a no-op — what we're testing is that- // passing a log_label doesn't panic and the command still runs.- }-- /// `DirectivePassthrough` with `cd_file` set must propagate it to the child.- ///- /// Unix-only: the script uses POSIX `sh` redirect syntax and relies on- /// native temp paths that don't need escaping. Git Bash on Windows would- /// need the paths converted to `/c/...` form first.- #[test]- #[cfg(unix)]- fn test_directive_env_vars_passed_through() {- use tempfile::NamedTempFile;- let cd = NamedTempFile::new().unwrap();- let directives = DirectivePassthrough {- cd_file: Some(cd.path().to_path_buf()),- };- let script = "printf CD > \"$WORKTRUNK_DIRECTIVE_CD_FILE\"";- let outcomes = run_one_with_directives("job", script, None, &directives);- assert!(outcomes[0].is_ok(), "child should exit 0");- let cd_contents = std::fs::read_to_string(cd.path()).unwrap();- assert_eq!(cd_contents, "CD");- }-- /// An empty `cmds` slice must return an empty outcomes vec without- /// spawning anything or erroring. Integration tests never hit this shape- /// (parser guarantees non-empty Concurrent groups) so we cover it here.#[test]fn test_empty_cmds_returns_empty() {let outcomes = run_concurrent_commands(&[]).expect("no spawn should happen");assert!(outcomes.is_empty());}-- /// `override_with_originating_signal` table-test: covers the four shapes- /// of outcome — `Ok`, non-`WorktrunkError` `Err`, exit-code `Err` (no- /// signal), and signal-derived `Err` matching vs differing from the- /// originating signal. Only the differing-signal case mutates.- #[test]- fn test_override_with_originating_signal() {- let originating = 2; // SIGINT-- // Ok: untouched.- let mut ok: anyhow::Result<()> = Ok(());- override_with_originating_signal(&mut ok, originating);- assert!(ok.is_ok());-- // Err but not WorktrunkError: untouched.- let mut other: anyhow::Result<()> = Err(anyhow::anyhow!("spawn failed"));- override_with_originating_signal(&mut other, originating);- assert_eq!(other.unwrap_err().to_string(), "spawn failed");-- // ChildProcessExited with no signal (plain non-zero exit): untouched.- let mut exit_err: anyhow::Result<()> = Err(WorktrunkError::ChildProcessExited {- code: 1,- message: "exit status: 1".into(),- signal: None,- }- .into());- override_with_originating_signal(&mut exit_err, originating);- let err = exit_err.unwrap_err();- let we = err.downcast_ref::<WorktrunkError>().unwrap();- assert!(matches!(- we,- WorktrunkError::ChildProcessExited {- signal: None,- code: 1,- ..- }- ));-- // ChildProcessExited with same signal as originating: untouched.- let mut same: anyhow::Result<()> = Err(WorktrunkError::ChildProcessExited {- code: 130,- message: "terminated by signal 2".into(),- signal: Some(2),- }- .into());- override_with_originating_signal(&mut same, originating);- let err = same.unwrap_err();- let we = err.downcast_ref::<WorktrunkError>().unwrap();- assert!(matches!(- we,- WorktrunkError::ChildProcessExited {- signal: Some(2),- code: 130,- ..- }- ));-- // ChildProcessExited with different signal (escalation case):- // overridden to the originating signal's code/message/signal.- let mut escalated: anyhow::Result<()> = Err(WorktrunkError::ChildProcessExited {- code: 143,- message: "terminated by signal 15".into(),- signal: Some(15),- }- .into());- override_with_originating_signal(&mut escalated, originating);- let err = escalated.unwrap_err();- let we = err.downcast_ref::<WorktrunkError>().unwrap();- match we {- WorktrunkError::ChildProcessExited {- code,- message,- signal,- } => {- assert_eq!(*code, 130);- assert_eq!(*signal, Some(2));- assert_eq!(message, "terminated by signal 2");- }- _ => panic!("expected ChildProcessExited, got {we:?}"),- }- }}diff --git a/src/output/global.rs b/src/output/global.rsindex dfdc22325..e26ecc9f0 100644--- a/src/output/global.rs+++ b/src/output/global.rs@@ -24,7 +24,7 @@ use anyhow::Context as _;use color_print::cformat;use std::sync::{Mutex, OnceLock};-use worktrunk::git::WorktrunkError;+use worktrunk::git::{ErrorExt, WorktrunkError};use worktrunk::shell_exec::Cmd;use worktrunk::shell_exec::{DIRECTIVE_CD_FILE_ENV_VAR, DIRECTIVE_EXEC_FILE_ENV_VAR, RETIRED_DIRECTIVE_FILE_ENV_VAR,@@ -362,6 +362,9 @@ pub fn execute(argv: Vec<String>, dir: &Path) -> anyhow::Result<()> {/// Preserve a user program's status without printing wt's own error afterward.fn suppress_child_exit_message(result: anyhow::Result<()>) -> anyhow::Result<()> {if let Err(err) = result {+ if let Some(signal) = err.interrupt_signal() {+ return Err(WorktrunkError::Interrupted { signal, hint: None }.into());+ }if let Some(WorktrunkError::ChildProcessExited { code, .. }) =err.downcast_ref::<WorktrunkError>(){diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex 6ef38296f..66ff71386 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -2170,18 +2170,14 @@ fn remove_removed_worktree_silently(/// detached) have their own spawning logic.////// Capabilities: optional stdout→stderr redirect for deterministic ordering,-/// SIGINT/SIGTERM forwarding to child process group, ANSI reset before child+/// native Ctrl-C and direct-child SIGTERM delivery, ANSI reset before child/// runs, `Cmd` tracing/logging, and CD directive control.////// ## Stdin///-/// The child always inherits the parent's stdin, so an interactive body keeps-/// the controlling terminal — a `pre-*` hook can `gum confirm`, an alias body's-/// `wt switch` picker can drive `/dev/tty`. `inherit_stdin()` also keeps the-/// child in wt's process group, which is what makes its `tcsetattr` on-/// `/dev/tty` succeed; see that method's docs for the SIGTTOU rationale, and-/// the "Process groups and signal handling" module docs in-/// [`worktrunk::shell_exec`] for what a shared pgroup costs on teardown.+/// The child inherits the parent's stdin for interactive input. Foreground children+/// share the caller's process group independently of stdin, so a `pre-*` hook+/// can `gum confirm`, and an alias body's `wt switch` picker can drive `/dev/tty`.////// Nothing is ever written to that stdin — a hook reads its context through/// template variables, whatever form it runs in. The two forms that can't bediff --git a/src/pager.rs b/src/pager.rsindex b6d9a80d9..0147f5738 100644--- a/src/pager.rs+++ b/src/pager.rs@@ -1,16 +1,50 @@-use worktrunk::git::Repository;+//! Git owns pager selection, including configuration outside a repository and+//! explicit disabled values. Optional detection failures leave output unpaged.-/// Parse a pager value, treating empty strings and "cat" as "no pager".-pub(crate) fn parse_pager_value(value: &str) -> Option<String> {+use worktrunk::git::base_path;+use worktrunk::shell_exec::Cmd;++/// Normalize Git's pager output, treating `cat` or whitespace as unpaged.+fn parse_pager_value(value: &str) -> Option<String> {let trimmed = value.trim();(!trimmed.is_empty() && trimmed != "cat").then(|| trimmed.to_string())}-/// Read `core.pager` from git config, returning None if unset or invalid.-pub(crate) fn git_config_pager() -> Option<String> {- let repo = Repository::current().ok()?;- repo.config_value("core.pager")+/// Ask Git for its pager. Previews suppress PAGER/default fallback, since an+/// interactive default pager cannot run inside their captured output window.+pub(crate) fn git_pager(allow_fallback: bool) -> Option<String> {+ let mut command = Cmd::new("git")+ .args(["var", "GIT_PAGER"])+ .current_dir(base_path());+ if !allow_fallback {+ command = command.env("PAGER", "cat");+ }+ let output = command+ .run()+ .ok()+ .filter(|output| output.status.success())?;+ std::str::from_utf8(&output.stdout).ok()- .flatten()- .and_then(|output| parse_pager_value(&output))+ .and_then(parse_pager_value)+}++#[cfg(test)]+mod tests {+ use super::parse_pager_value;++ #[test]+ fn parse_pager_output() {+ for (input, expected) in [+ ("cat", None),+ (" cat ", None),+ ("", None),+ (" ", None),+ ("less", Some("less")),+ (" less ", Some("less")),+ ("delta", Some("delta")),+ ("less -R", Some("less -R")),+ ] {+ assert_eq!(parse_pager_value(input).as_deref(), expected, "{input:?}");+ }+ }}diff --git a/src/path.rs b/src/path.rsindex 39456d1bc..49651d949 100644--- a/src/path.rs+++ b/src/path.rs@@ -57,11 +57,6 @@ pub fn to_posix_path(path: &str) -> String {/// relative paths.#[cfg(windows)]fn find_cygpath_from_shell(shell: &crate::shell_exec::ShellConfig) -> Option<PathBuf> {- // Only Git Bash has cygpath- if !shell.is_posix {- return None;- }-let shell_dir = shell.executable.parent()?;// If bash is at usr/bin/bash.exe, cygpath is in the same directorydiff --git a/src/shell/snapshots/worktrunk__shell__tests__init_bash.snap b/src/shell/snapshots/worktrunk__shell__tests__init_bash.snapindex 36cbb09ff..0679cbf4e 100644--- a/src/shell/snapshots/worktrunk__shell__tests__init_bash.snap+++ b/src/shell/snapshots/worktrunk__shell__tests__init_bash.snap@@ -12,11 +12,9 @@ if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; thenwt() {local use_source=falselocal args=()-for arg in "$@"; do- if [[ "$arg" == "--source" ]]; then use_source=true; else args+=("$arg"); fi+ if [[ "$arg" == --source ]]; then use_source=true; else args+=("$arg"); fidone-# Completion mode: call binary directly, no directive files needed.# This check MUST be here (not in the binary) because clap's completion# handler runs before argument parsing.@@ -25,32 +23,85 @@ if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; thenreturnfi- local cd_file exit_code=0- cd_file="$(mktemp)"-- # --source: use cargo run (builds from source)- if [[ "$use_source" == true ]]; then- WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" \- cargo run --bin wt --quiet -- "${args[@]}" || exit_code=$?- else- WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" \- command "${WORKTRUNK_BIN:-wt}" "${args[@]}" || exit_code=$?- fi-- # cd file holds a raw path (no shell escaping needed).+ # Native SIGINT can unwind this body before ordinary cleanup. Capture one+ # cleanup function for both the next prompt and a noninteractive shell exit.+ local cd_file owner cleanup_body exit_trap owns_exit=false prompt_provider prompt_armed=true+ local prompt_value="${PROMPT_COMMAND-}" prompt_present="${PROMPT_COMMAND+x}" prompt_declared=false+ local prompt_declaration prompt_flags+ if builtin declare -p PROMPT_COMMAND >/dev/null 2>&1; then prompt_declared=true; fi+ # Readonly prompts cannot be replaced; allexport would export our callback.+ if [[ $- == *a* ]] || ! (PROMPT_COMMAND="$prompt_value") 2>/dev/null; then prompt_armed=false; fi+ cd_file="$(mktemp)" || return+ owner="_wt_cleanup_${cd_file##*/}"+ owner="${owner//[^a-zA-Z0-9_]/_}"+ exit_trap="$(builtin trap -p EXIT)"+ # trap -p may expose an inherited but inactive EXIT handler in a subshell.+ # Reinstalling it would activate the parent's handler there.+ if [[ ( $BASH_SUBSHELL -eq 0 || -z "$exit_trap" ) && ( $- != *i* || "$prompt_armed" == true ) ]]; then owns_exit=true; fi+ builtin printf -v prompt_provider 'if %s prompt "$?"; then builtin eval %q; else builtin eval %q; fi' "$owner" "$prompt_value" "$prompt_value"+ # %q captures the state after the caller's local variables have unwound.+ builtin printf -v cleanup_body '+ local cd_file=%q owner=%q exit_trap=%q owns_exit=%q+ local prompt_value=%q prompt_present=%q prompt_declared=%q prompt_provider=%q+ ' "$cd_file" "$owner" "$exit_trap" "$owns_exit" "$prompt_value" "$prompt_present" "$prompt_declared" "$prompt_provider"# `builtin cd` bypasses any user `cd` alias or function (e.g. zoxide's- # `alias cd=__zoxide_z`) that would otherwise be substituted into this+ # `alias cd=__zoxide_z`) that would otherwise be substituted into the# function body when it's defined. See #2643.- if [[ -s "$cd_file" ]]; then- builtin cd -- "$(<"$cd_file")"- local cd_exit=$?- if [[ $exit_code -eq 0 ]]; then- exit_code=$cd_exit+ cleanup_body+='+ local event=$1 status=$2 cd_status=0+ if [[ "$owns_exit" == true ]]; then builtin trap - EXIT; fi+ if [[ -s "$cd_file" ]]; then+ builtin cd -- "$(<"$cd_file")" || cd_status=$?fi- fi+ command rm -f "$cd_file"+ if [[ ${PROMPT_COMMAND-} == "$prompt_provider" ]]; then+ if [[ -n "$prompt_present" ]]; then+ PROMPT_COMMAND="$prompt_value"+ else+ local prompt_flags+ prompt_flags="$(builtin declare -p PROMPT_COMMAND 2>/dev/null)" || prompt_flags=+ prompt_flags=${prompt_flags#declare }+ prompt_flags=${prompt_flags%% *}+ if [[ "$prompt_declared" == true ]]; then+ builtin unset "PROMPT_COMMAND[0]"+ else+ builtin unset PROMPT_COMMAND+ fi+ if [[ "$prompt_flags" == *x* ]]; then builtin export PROMPT_COMMAND; fi+ fi+ fi+ if [[ "$owns_exit" == true && -n "$exit_trap" ]]; then builtin eval "$exit_trap"; fi+ builtin unset -f "$owner"+ if [[ "$event" == normal && $status -eq 0 ]]; then+ return "$cd_status"+ else+ return "$status"+ fi+ '+ builtin eval "$owner() { $cleanup_body }"+ if [[ "$prompt_armed" == true ]]; then PROMPT_COMMAND="$prompt_provider"; fi+ # Bash 3.2 only reports an exported, unset variable after assignment.+ prompt_declaration="$(builtin declare -p PROMPT_COMMAND 2>/dev/null)" || prompt_declaration=+ prompt_flags=${prompt_declaration#declare }+ prompt_flags=${prompt_flags%% *}- command rm -f "$cd_file"- return "$exit_code"+ local exit_code=0+ local execution=("${WORKTRUNK_BIN:-wt}" "${args[@]}")+ if [[ "$use_source" == true ]]; then execution=(cargo run --bin wt --quiet -- "${args[@]}"); fi+ if [[ "$owns_exit" == true ]]; then+ local exit_provider="$owner exit \"\$?\""+ if [[ -n "$exit_trap" ]]; then+ local exit_callback=${exit_trap#trap -- }+ exit_callback=${exit_callback% EXIT}+ builtin printf -v exit_provider 'if %s exit "$?"; then builtin eval %s; else builtin eval %s; fi' "$owner" "$exit_callback" "$exit_callback"+ fi+ builtin trap "$exit_provider" EXIT+ fi+ case "$prompt_armed:$prompt_flags" in+ true:*x*) PROMPT_COMMAND="$prompt_value" WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" command "${execution[@]}" || exit_code=$? ;;+ *) WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" command "${execution[@]}" || exit_code=$? ;;+ esac+ if "$owner" normal "$exit_code"; then return 0; else return $?; fi}# Lazy completions - generate on first TAB, then delegate to clap's completerdiff --git a/src/shell/snapshots/worktrunk__shell__tests__init_fish.snap b/src/shell/snapshots/worktrunk__shell__tests__init_fish.snapindex eb8577266..435d9b0e3 100644--- a/src/shell/snapshots/worktrunk__shell__tests__init_fish.snap+++ b/src/shell/snapshots/worktrunk__shell__tests__init_fish.snap@@ -24,31 +24,47 @@ function wtendset -l cd_file (mktemp)+ # Older fish unwinds only the function that directly launched an interrupted+ # child. This boundary lets ordinary cleanup run before its caller continues.+ # Newer fish unwinds the whole input line; postexec owns cleanup in that case.+ set -l cleanup_function _wt_cleanup_(string replace -a / _ -- "$cd_file")+ set -l run_function "$cleanup_function"_run+ function $run_function+ command $argv+ end+ function $cleanup_function --on-event fish_postexec --inherit-variable cd_file --inherit-variable cleanup_function --inherit-variable run_function+ set -l cd_exit 0+ # cd file holds a raw path — read with fish builtin (no cat subprocess,+ # safe even if CWD was removed by worktree removal).+ if test -s "$cd_file"+ set -l target (string trim < "$cd_file")+ # `builtin cd` bypasses any user `cd` override (e.g. the zoxide.fish+ # plugin replaces `cd` with a query function that mishandles the `--`+ # separator). Matches the bash/zsh wrappers. (#3159)+ builtin cd -- "$target"+ set cd_exit $status+ end++ command rm -f "$cd_file"+ functions -e $cleanup_function $run_function+ return $cd_exit+ end+# --source: use cargo run (builds from source)if test $use_source = true- env WORKTRUNK_DIRECTIVE_CD_FILE=$cd_file \+ $run_function env WORKTRUNK_DIRECTIVE_CD_FILE=$cd_file \cargo run --bin wt --quiet -- $argselse- env WORKTRUNK_DIRECTIVE_CD_FILE=$cd_file \+ $run_function env WORKTRUNK_DIRECTIVE_CD_FILE=$cd_file \$WORKTRUNK_BIN $argsendset -l exit_code $status- # cd file holds a raw path — read with fish builtin (no cat subprocess,- # safe even if CWD was removed by worktree removal).- if test -s "$cd_file"- set -l target (string trim < "$cd_file")- # `builtin cd` bypasses any user `cd` override (e.g. the zoxide.fish- # plugin replaces `cd` with a query function that mishandles the `--`- # separator). Matches the bash/zsh wrappers. (#3159)- builtin cd -- "$target"- set -l cd_exit $status- if test $exit_code -eq 0- set exit_code $cd_exit- end+ $cleanup_function+ set -l cd_exit $status+ if test $exit_code -eq 0+ set exit_code $cd_exitend-- command rm -f "$cd_file"return $exit_codeenddiff --git a/src/shell/snapshots/worktrunk__shell__tests__init_nu.snap b/src/shell/snapshots/worktrunk__shell__tests__init_nu.snapindex ed47f3d4b..cf5c555f4 100644--- a/src/shell/snapshots/worktrunk__shell__tests__init_nu.snap+++ b/src/shell/snapshots/worktrunk__shell__tests__init_nu.snap@@ -2,7 +2,7 @@source: src/shell/mod.rsexpression: output----# worktrunk shell integration for nushell+# worktrunk shell integration for nushell 0.113+# Tab completions: calls binary with COMPLETE=nu to get candidates.# Note: nushell's completion engine bypasses custom completers when the current@@ -86,13 +86,17 @@ export def --env --wrapped wt [...args] {($external | get 0.path)}+ # Unquoted wrapped arguments can be glob values. Classify their text+ # while preserving the original arguments for external execution.+ let arg_text = ($args | each {|arg| $arg | into string })+# `list` is the only command that benefits from streaming stdout (progressive# table rendering). It never emits directives, so we skip directive processing# and let the binary be the last expression — stdout flows through pipes.# Note: global flags before `list` (e.g. `wt -C /path list`) miss this check# and fall through to the buffered path. Output is still correct, just not# progressively rendered.- if (not ($args | is-empty)) and ($args | first) == "list" {+ if (not ($arg_text | is-empty)) and ($arg_text | first) == "list" {# Direct passthrough: binary is the last expression of this branch,# which is the last expression of the function. Stdout streams to the# terminal and flows through nushell pipelines.@@ -100,76 +104,57 @@ export def --env --wrapped wt [...args] {} else {let cd_file = (mktemp --tmpdir)let stdout_file = (mktemp --tmpdir)- let wt_args = ($args | take until {|arg| $arg == "--" })- # Before `-x`, `c`, `v`, and `y` are boolean flags clap may cluster with it.- let has_execute = ($wt_args | any {|arg| $arg == "--execute" or ($arg | str starts-with "--execute=") or ($arg =~ '^-[cvy]*x') })+ try {+ let wt_args = ($arg_text | take until {|arg| $arg == "--" })+ # Before `-x`, `c`, `v`, and `y` are boolean flags clap may cluster with it.+ let has_execute = ($wt_args | any {|arg| $arg == "--execute" or ($arg | str starts-with "--execute=") or ($arg =~ '^-[cvy]*x') })- # Capture stdout for pipeline passthrough unless wt will launch an- # interactive child, which must inherit the terminal.- # Nushell 0.98+ throws ShellError on non-zero exit (like bash `set -e`).- # `try` catches it so directive processing and temp file cleanup still run.- let exit_code = (try {- with-env { WORKTRUNK_DIRECTIVE_CD_FILE: $cd_file } {- if $has_execute {- ^$worktrunk_bin ...$args- } else {- ^$worktrunk_bin ...$args o> $stdout_file+ # Capture stdout for pipeline passthrough unless wt will launch an+ # interactive child, which must inherit the terminal.+ # Capture failure status without discarding buffered stdout.+ # The outer `finally` applies directives and cleans up on Ctrl-C too.+ let exit_code = (try {+ with-env { WORKTRUNK_DIRECTIVE_CD_FILE: $cd_file } {+ if $has_execute {+ ^$worktrunk_bin ...$args+ } else {+ ^$worktrunk_bin ...$args o> $stdout_file+ }}- }- 0- } catch {- $env.LAST_EXIT_CODE- })+ 0+ } catch {+ # Nushell reports signal deaths as negative signal numbers. Its+ # `exit` builtin needs the corresponding shell status instead.+ let code = $env.LAST_EXIT_CODE+ if $code < 0 { 128 - $code } else { $code }+ })- # cd file holds a raw path — no shell parsing needed- if ($cd_file | path exists) and (open $cd_file --raw | str trim | is-not-empty) {- let target_dir = open $cd_file --raw | str trim- cd $target_dir- }+ let output = if $has_execute { "" } else { open $stdout_file --raw }- let output = if $has_execute { "" } else { open $stdout_file --raw }-- # Clean up the temp files after their final reads.- #- # A bare `rm` here is shadowable by the user's own `alias rm = ...`:- # nushell resolves aliases at parse time, and `config.nu` runs before the- # vendor autoload dir this file lives in, so the alias is already in scope- # when this `def` is parsed. A `trash`-style alias then leaks the temp- # files, and an alias that exits non-zero raises a ShellError that aborts- # the wrapper before it can return `$output` — swallowing the command's- # stdout entirely.- #- # `^rm` bypasses aliases, but it's external-only, so Windows (where the- # nushell builtin is the only `rm`) keeps the builtin. `try` covers both- # branches so cleanup can never abort the wrapper. `hide rm` is not an- # option: it's a parse-time keyword that leaks out of this function into- # the user's session, silently unbinding their alias.- if $nu.os-info.family == "windows" {- try { rm -f $cd_file $stdout_file }- } else {- try { ^rm -f $cd_file $stdout_file }- }-- # Return stdout or propagate failure as the function's last expression.- # Using a failing external command (not `error make`) so nushell treats it- # identically to the original non-zero exit — minimal display in scripts,- # no verbose source trace.- #- # nushell itself is the external command, not `sh`: `Shell::Nushell` isn't- # platform-gated, so this wrapper is installed on Windows whenever `nu` is- # on PATH, and there `sh` doesn't exist. A missing `sh` turns every failing- # `wt` command into a "Command `sh` not found" trace that prints the- # wrapper's own source and flattens the real exit code to 1 — the opposite- # of what this branch is for. `$nu.current-exe` is always present by- # construction, and using one path on every platform keeps the branch Unix- # CI exercises identical to the one Windows runs. `--no-std-lib` halves- # the startup this costs (~9 ms to ~4.5 ms on nu 0.115); `exit` is a core- # builtin, so propagation is unaffected.- if $exit_code != 0 {- if ($output | is-not-empty) { print -n $output }- ^$nu.current-exe --no-config-file --no-std-lib -c $"exit ($exit_code)"- } else if ($output | is-not-empty) {- $output+ # Return captured stdout or reproduce the external failure without+ # a source trace. Nu itself also works on Windows, where sh is absent.+ if $exit_code != 0 {+ if ($output | is-not-empty) { print -n $output }+ ^$nu.current-exe --no-config-file --no-std-lib -c $"exit ($exit_code)"+ } else if ($output | is-not-empty) {+ $output+ }+ } finally {+ try {+ # cd file holds a raw path — no shell parsing needed+ if ($cd_file | path exists) and (open $cd_file --raw | str trim | is-not-empty) {+ let target_dir = open $cd_file --raw | str trim+ cd $target_dir+ }+ } finally {+ # Bypass user rm aliases on Unix; Windows uses Nushell's builtin.+ # Cleanup cannot replace the command's status.+ if $nu.os-info.family == "windows" {+ try { rm -f $cd_file $stdout_file }+ } else {+ try { ^rm -f $cd_file $stdout_file }+ }+ }}}}diff --git a/src/shell/snapshots/worktrunk__shell__tests__init_zsh.snap b/src/shell/snapshots/worktrunk__shell__tests__init_zsh.snapindex 6f2df7899..455ffef96 100644--- a/src/shell/snapshots/worktrunk__shell__tests__init_zsh.snap+++ b/src/shell/snapshots/worktrunk__shell__tests__init_zsh.snap@@ -31,28 +31,28 @@ if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; thenlocal cd_file exit_code=0cd_file="$(mktemp)"- # --source: use cargo run (builds from source)+ local -a execution=("${WORKTRUNK_BIN:-wt}" "${args[@]}")if [[ "$use_source" == true ]]; then- WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" \- cargo run --bin wt --quiet -- "${args[@]}" || exit_code=$?- else- WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" \- command "${WORKTRUNK_BIN:-wt}" "${args[@]}" || exit_code=$?+ execution=(cargo run --bin wt --quiet -- "${args[@]}")fi-- # cd file holds a raw path (no shell escaping needed).- # `builtin cd` bypasses any user `cd` alias or function (e.g. zoxide's- # `alias cd=__zoxide_z`) that would otherwise be substituted into this- # function body when it's defined. See #2643.- if [[ -s "$cd_file" ]]; then- builtin cd -- "$(<"$cd_file")"- local cd_exit=$?- if [[ $exit_code -eq 0 ]]; then- exit_code=$cd_exit+ {+ WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" command "${execution[@]}"+ } always {+ exit_code=$?+ # cd file holds a raw path (no shell escaping needed).+ # `builtin cd` bypasses any user `cd` alias or function (e.g. zoxide's+ # `alias cd=__zoxide_z`) that would otherwise be substituted into this+ # function body when it's defined. See #2643.+ if [[ -s "$cd_file" ]]; then+ builtin cd -- "$(<"$cd_file")"+ local cd_exit=$?+ if [[ $exit_code -eq 0 ]]; then+ exit_code=$cd_exit+ fifi- fi- command rm -f "$cd_file"+ command rm -f "$cd_file"+ } || :return "$exit_code"}diff --git a/src/shell/snapshots/worktrunk__shell__tests__shell_init_with_custom_prefix.snap b/src/shell/snapshots/worktrunk__shell__tests__shell_init_with_custom_prefix.snapindex 3f5a7dd6b..47ffa27ac 100644--- a/src/shell/snapshots/worktrunk__shell__tests__shell_init_with_custom_prefix.snap+++ b/src/shell/snapshots/worktrunk__shell__tests__shell_init_with_custom_prefix.snap@@ -12,11 +12,9 @@ if command -v custom >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; thencustom() {local use_source=falselocal args=()-for arg in "$@"; do- if [[ "$arg" == "--source" ]]; then use_source=true; else args+=("$arg"); fi+ if [[ "$arg" == --source ]]; then use_source=true; else args+=("$arg"); fidone-# Completion mode: call binary directly, no directive files needed.# This check MUST be here (not in the binary) because clap's completion# handler runs before argument parsing.@@ -25,32 +23,85 @@ if command -v custom >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; thenreturnfi- local cd_file exit_code=0- cd_file="$(mktemp)"-- # --source: use cargo run (builds from source)- if [[ "$use_source" == true ]]; then- WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" \- cargo run --bin custom --quiet -- "${args[@]}" || exit_code=$?- else- WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" \- command "${WORKTRUNK_BIN:-custom}" "${args[@]}" || exit_code=$?- fi-- # cd file holds a raw path (no shell escaping needed).+ # Native SIGINT can unwind this body before ordinary cleanup. Capture one+ # cleanup function for both the next prompt and a noninteractive shell exit.+ local cd_file owner cleanup_body exit_trap owns_exit=false prompt_provider prompt_armed=true+ local prompt_value="${PROMPT_COMMAND-}" prompt_present="${PROMPT_COMMAND+x}" prompt_declared=false+ local prompt_declaration prompt_flags+ if builtin declare -p PROMPT_COMMAND >/dev/null 2>&1; then prompt_declared=true; fi+ # Readonly prompts cannot be replaced; allexport would export our callback.+ if [[ $- == *a* ]] || ! (PROMPT_COMMAND="$prompt_value") 2>/dev/null; then prompt_armed=false; fi+ cd_file="$(mktemp)" || return+ owner="_custom_cleanup_${cd_file##*/}"+ owner="${owner//[^a-zA-Z0-9_]/_}"+ exit_trap="$(builtin trap -p EXIT)"+ # trap -p may expose an inherited but inactive EXIT handler in a subshell.+ # Reinstalling it would activate the parent's handler there.+ if [[ ( $BASH_SUBSHELL -eq 0 || -z "$exit_trap" ) && ( $- != *i* || "$prompt_armed" == true ) ]]; then owns_exit=true; fi+ builtin printf -v prompt_provider 'if %s prompt "$?"; then builtin eval %q; else builtin eval %q; fi' "$owner" "$prompt_value" "$prompt_value"+ # %q captures the state after the caller's local variables have unwound.+ builtin printf -v cleanup_body '+ local cd_file=%q owner=%q exit_trap=%q owns_exit=%q+ local prompt_value=%q prompt_present=%q prompt_declared=%q prompt_provider=%q+ ' "$cd_file" "$owner" "$exit_trap" "$owns_exit" "$prompt_value" "$prompt_present" "$prompt_declared" "$prompt_provider"# `builtin cd` bypasses any user `cd` alias or function (e.g. zoxide's- # `alias cd=__zoxide_z`) that would otherwise be substituted into this+ # `alias cd=__zoxide_z`) that would otherwise be substituted into the# function body when it's defined. See #2643.- if [[ -s "$cd_file" ]]; then- builtin cd -- "$(<"$cd_file")"- local cd_exit=$?- if [[ $exit_code -eq 0 ]]; then- exit_code=$cd_exit+ cleanup_body+='+ local event=$1 status=$2 cd_status=0+ if [[ "$owns_exit" == true ]]; then builtin trap - EXIT; fi+ if [[ -s "$cd_file" ]]; then+ builtin cd -- "$(<"$cd_file")" || cd_status=$?fi- fi+ command rm -f "$cd_file"+ if [[ ${PROMPT_COMMAND-} == "$prompt_provider" ]]; then+ if [[ -n "$prompt_present" ]]; then+ PROMPT_COMMAND="$prompt_value"+ else+ local prompt_flags+ prompt_flags="$(builtin declare -p PROMPT_COMMAND 2>/dev/null)" || prompt_flags=+ prompt_flags=${prompt_flags#declare }+ prompt_flags=${prompt_flags%% *}+ if [[ "$prompt_declared" == true ]]; then+ builtin unset "PROMPT_COMMAND[0]"+ else+ builtin unset PROMPT_COMMAND+ fi+ if [[ "$prompt_flags" == *x* ]]; then builtin export PROMPT_COMMAND; fi+ fi+ fi+ if [[ "$owns_exit" == true && -n "$exit_trap" ]]; then builtin eval "$exit_trap"; fi+ builtin unset -f "$owner"+ if [[ "$event" == normal && $status -eq 0 ]]; then+ return "$cd_status"+ else+ return "$status"+ fi+ '+ builtin eval "$owner() { $cleanup_body }"+ if [[ "$prompt_armed" == true ]]; then PROMPT_COMMAND="$prompt_provider"; fi+ # Bash 3.2 only reports an exported, unset variable after assignment.+ prompt_declaration="$(builtin declare -p PROMPT_COMMAND 2>/dev/null)" || prompt_declaration=+ prompt_flags=${prompt_declaration#declare }+ prompt_flags=${prompt_flags%% *}- command rm -f "$cd_file"- return "$exit_code"+ local exit_code=0+ local execution=("${WORKTRUNK_BIN:-custom}" "${args[@]}")+ if [[ "$use_source" == true ]]; then execution=(cargo run --bin custom --quiet -- "${args[@]}"); fi+ if [[ "$owns_exit" == true ]]; then+ local exit_provider="$owner exit \"\$?\""+ if [[ -n "$exit_trap" ]]; then+ local exit_callback=${exit_trap#trap -- }+ exit_callback=${exit_callback% EXIT}+ builtin printf -v exit_provider 'if %s exit "$?"; then builtin eval %s; else builtin eval %s; fi' "$owner" "$exit_callback" "$exit_callback"+ fi+ builtin trap "$exit_provider" EXIT+ fi+ case "$prompt_armed:$prompt_flags" in+ true:*x*) PROMPT_COMMAND="$prompt_value" WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" command "${execution[@]}" || exit_code=$? ;;+ *) WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" command "${execution[@]}" || exit_code=$? ;;+ esac+ if "$owner" normal "$exit_code"; then return 0; else return $?; fi}# Lazy completions - generate on first TAB, then delegate to clap's completerdiff --git a/src/shell_exec.rs b/src/shell_exec.rsindex 27b8df7da..52c103cef 100644--- a/src/shell_exec.rs+++ b/src/shell_exec.rs@@ -8,42 +8,29 @@//! On Windows, Git for Windows must be installed — this is nearly universal among//! Windows developers since git itself is required.//!-//! ## Process groups and signal handling (Unix, `Cmd::stream`)-//!-//! Foreground children spawned through `Cmd::stream()` fall into one of two-//! shapes, selected by the `forward_signals` / `share_parent_pgroup` pair:+//! ## Spawning children//!-//! - **Isolated** (`forward_signals()` alone): the child gets its own process-//! group via `process_group(0)`. A signal_hook listener catches SIGINT/-//! SIGTERM in wt and `killpg`s the child group with SIGINT→SIGTERM→SIGKILL-//! escalation. Used for children wt runs on its own behalf across worktrees-//! (`wt step for-each`), which may fork further subprocesses — `killpg`-//! reaches the whole subtree, which a shared-pgroup approach cannot.+//! Worktrunk's command spawns use [`spawn`] or [`spawn_shared_child`]. Their+//! shared lock covers descriptor setup and process creation, never child waits:+//! children still execute concurrently. On macOS, the standard library creates+//! pipes and sockets before marking them close-on-exec. Serializing their setup+//! with spawns prevents a child from retaining another command's output or wake.//!-//! - **Shared-tty** (`forward_signals().inherit_stdin()`): the child stays in-//! wt's process group so it can drive `/dev/tty` (raw mode, `tcsetattr`)-//! without the kernel raising SIGTTOU. Tty-initiated signals (Ctrl-C, hangup)-//! reach the child via the kernel's foreground-pgroup broadcast; the listener-//! additionally delivers externally-targeted signals (e.g. `kill -TERM-//! <wt-pid>`) to the child by PID, single-shot. Used for every `Single`-//! foreground step of a hook or alias pipeline, which inherits wt's stdin so-//! the step can prompt, and for the program `wt switch --execute` launches-//! (`execute_command` in `output/global.rs`). Such a child's own subtree is-//! therefore not reachable by `killpg`: an externally-targeted signal-//! reaches the child by PID and stops there, while Ctrl-C still reaches the-//! whole subtree through the kernel's broadcast.+//! ## Process groups and signal handling (Unix, `Cmd::stream`)//!-//! In both cases the listener still records `seen_signal`, so a signal-derived-//! exit surfaces as `WorktrunkError::ChildProcessExited { signal: Some(_) }` —-//! the structured channel that loop callers (`for-each`, hook/alias pipelines)-//! use to abort their loops on Ctrl-C rather than continuing to the next-//! iteration. See `git/interrupt_signal` for the consumer side.+//! Foreground children share the caller's process group, including concurrent+//! hooks with piped output and closed stdin. Group membership is independent+//! of input allocation: programs may still open `/dev/tty` for terminal control.+//! The shell owns the foreground job and the kernel delivers Ctrl-C, Ctrl-Z+//! and hangup to it. No terminal handoff or private foreground group is needed.//!-//! Concurrent foreground children (`output/concurrent.rs`) and detached-//! background children (`commands/process.rs::spawn_detached_*`) have separate-//! spawn paths; both isolate-by-default for the same `killpg` reason. They-//! never share wt's pgroup because they don't drive the tty (concurrent uses-//! piped stdio, detached escapes the PTY entirely).+//! [`Cmd::forward_signals`] observes direct exit while waiting, preserving a+//! child's normal exit when it handles Ctrl-C.+//! SIGTERM addressed only to wt is forwarded+//! to owned direct children and cancels the command. Child signal exits propagate+//! through `WorktrunkError::ChildProcessExited` to stop foreground loops.+//! Detached background commands and timeout-bounded captures have separate+//! ownership: those commands may create a private group for tree cancellation.//!//! ## Cancelling background children//!@@ -54,11 +41,14 @@//!//! ## Timed waits//!-//! Unix has no "wait for this child, but give up after N milliseconds" syscall,-//! so every deadline here (`Cmd::timeout`, `Cmd::delayed_stream`, the picker's-//! pager) goes through [`shared_child::SharedChild`]: `waitid(WNOWAIT)` for the-//! blocking wait, and for the timed one a `SIGCHLD` self-pipe it polls against-//! the deadline. Windows needs none of that — it waits the process handle.+//! [`wait_shared_child`] is the canonical wait for shared child handles. macOS+//! kernel exit events avoid SharedChild's stop-sensitive `waitid` path while+//! retaining its synchronized reaping and PID-safe signal delivery. Other+//! platforms use SharedChild's native waits and deadlines. macOS waits do not+//! change SIGCHLD dispositions or masks, including when a deadline expires.+//! Foreground waits publish native INT/TERM to current foreground scopes.+//! Captures and pagers do not publish cancellation themselves; command consumers+//! decide whether to propagate their typed failures to the foreground operation.//!//! **Why not `wait-timeout`.** wt used it until #3856. Its `SIGCHLD` handler//! pokes an `AF_UNIX` socketpair with `send()` and `panic!`s on any errno but@@ -71,20 +61,15 @@//! deadline is for. It also probes the wake fd and falls back to `write()` on a//! pipe, so the syscall that sandbox denies is not even on the path.//!-//! **When the timed wait itself fails.** Setting a deadline is fallible — each-//! call allocates a pipe and registers a handler — so each site decides what a-//! failed `wait_timeout` means instead of propagating it. Where the deadline-//! bounds wall-clock (`run_with_timeout_impl`, the pager) the site tears the-//! child down, because a wait it cannot observe bounds nothing. Where it only-//! decides when output starts streaming ([`Cmd::delayed_stream`]) the site-//! streams. No site fails the command: a denied syscall in wt's own machinery-//! is not the child's fault, and erroring over one repeats #3856 in a quieter-//! form.+//! **When a timed wait fails.** A wall-clock deadline failure retires the+//! owned child. An advisory output-delay failure switches to streaming and+//! retries the canonical wait; if that wait also fails, it retires the child+//! before joining output readers and returns the underlying error.use std::collections::BTreeSet;use std::ffi::{OsStr, OsString};use std::fs::Metadata;-use std::io::{BufRead, BufReader, ErrorKind, Read, Write};+use std::io::{BufRead, BufReader, ErrorKind, Read, Seek, Write};use std::path::{Path, PathBuf};use std::process::{Command, Stdio};use std::sync::atomic::{AtomicBool, Ordering};@@ -94,11 +79,67 @@ use std::time::{Duration, Instant};use anyhow::Context;use shared_child::SharedChild;-use crate::git::{GitError, WorktrunkError};+use crate::git::{ErrorExt, GitError, WorktrunkError};use crate::styling::eprintln;use crate::sync::Semaphore;use crate::trace::CommandTrace;+#[cfg(unix)]+pub mod pipe;++/// Prepare complete input before spawning, with no producer that can block.+/// The anonymous file is removed when its last handle closes, even on interruption.+/// This is seekable stdin, unlike the pipes connecting live pipeline stages.+pub fn buffered_stdin(bytes: &[u8]) -> std::io::Result<Stdio> {+ let mut file = tempfile::tempfile()?;+ file.write_all(bytes)?;+ file.rewind()?;+ Ok(file.into())+}++// Published Linux/Windows targets use atomic descriptors or std's spawn lock.+#[cfg(target_vendor = "apple")]+static PROCESS_CREATION_LOCK: Mutex<()> = Mutex::new(());++/// Serialize process creation with descriptor creation that sets close-on-exec+/// after its native syscall. Otherwise a concurrent spawn can inherit endpoints+/// between creation and CLOEXEC, keeping unrelated output or wakeups alive.+pub(crate) fn with_process_creation_guard<T>(+ create: impl FnOnce() -> std::io::Result<T>,+) -> std::io::Result<T> {+ #[cfg(target_vendor = "apple")]+ let _guard = PROCESS_CREATION_LOCK+ .lock()+ .unwrap_or_else(|error| error.into_inner());+ create()+}++/// Spawn a child under the shared process-creation guard.+pub fn spawn(command: &mut Command) -> std::io::Result<std::process::Child> {+ with_process_creation_guard(|| command.spawn())+}++/// Spawn a shared child under the same process-creation lock as [`spawn`].+pub fn spawn_shared_child(command: &mut Command) -> std::io::Result<SharedChild> {+ // SharedChild::new calls try_wait and can reap a short-lived child here.+ // Keep SharedChild::spawn's unreaped ownership for process-tree cleanup.+ with_process_creation_guard(|| SharedChild::spawn(command))+}++/// Create wakeup endpoints under the same guard as process creation.+#[cfg(unix)]+pub fn socket_pair() -> std::io::Result<(+ std::os::unix::net::UnixStream,+ std::os::unix::net::UnixStream,+)> {+ with_process_creation_guard(std::os::unix::net::UnixStream::pair)+}++/// Create a stream socket without holding the spawn guard during connection I/O.+pub fn stream_socket(domain: socket2::Domain) -> std::io::Result<socket2::Socket> {+ with_process_creation_guard(|| socket2::Socket::new(domain, socket2::Type::STREAM, None))+}+/// Semaphore to limit concurrent command execution./// Prevents resource exhaustion when spawning many parallel git commands.///@@ -254,7 +295,7 @@ pub fn cancel_background_commands() {/// stranding an `index.lock` in a worktree the user is about to work in.#[cfg(unix)]fn signal_background_pid(pid: u32) {- forward_signal_to_pid(pid as i32, signal_hook::consts::SIGTERM);+ terminate_pid(pid as i32);}/// Windows has no signal to deliver to an unrelated PID, so a command already@@ -405,20 +446,13 @@ fn semaphore() -> &'static Semaphore {/// Cached shell configuration for the current platformstatic SHELL_CONFIG: OnceLock<Result<ShellConfig, String>> = OnceLock::new();-/// Shell configuration for command execution+/// POSIX shell configuration for command execution (sh or Git Bash).#[derive(Debug, Clone)]pub struct ShellConfig {/// Path to the shell executablepub executable: PathBuf,- /// Arguments to pass before the command (e.g., ["-c"] for sh, ["/C"] for cmd)+ /// Arguments to pass before the command (e.g., ["-c"] for sh)pub args: Vec<String>,- /// Whether this shell supports POSIX syntax (bash, sh, zsh, etc.).- ///- /// When true, commands can use POSIX features like:- /// - `{ cmd; } 1>&2` for stdout redirection- /// - `printf '%s' ... | cmd` for stdin piping- /// - `nohup ... &` for background execution- pub is_posix: bool,/// Human-readable name for error messagespub name: String,}@@ -454,7 +488,6 @@ fn detect_shell() -> Result<ShellConfig, String> {Ok(ShellConfig {executable: PathBuf::from("sh"),args: vec!["-c".to_string()],- is_posix: true,name: "sh".to_string(),})}@@ -475,7 +508,6 @@ fn detect_windows_shell() -> Result<ShellConfig, String> {return Ok(ShellConfig {executable: bash_path,args: vec!["-c".to_string()],- is_posix: true,name: "Git Bash".to_string(),});}@@ -931,8 +963,8 @@ fn format_stream_bounded(bytes: &[u8], prefix: &str) -> Vec<String> {////// Spawns reader threads to drain stdout/stderr concurrently (preventing deadlock when/// output exceeds the OS pipe buffer), then waits with timeout. On timeout, tears down-/// the child's whole process tree; scoped threads see EOF and join automatically before-/// the function returns.+/// the still-owned child's process tree; scoped readers share the same deadline,+/// including when an exited child's descendants retain its pipes.////// **The teardown reaches the tree, not just the child, because otherwise the timeout/// doesn't bound anything.** A grandchild inherits the child's stderr pipe, so a@@ -959,17 +991,36 @@ fn run_with_timeout_impl(cmd.process_group(0);}- let child = SharedChild::spawn(- cmd.stdin(Stdio::null())- .stdout(Stdio::piped())- .stderr(Stdio::piped()),- )?;+ let child = spawn_shared_child(cmd)?;let _tracked = cancellable.then(|| track_if_cancellable(child.id())).flatten();- let mut child_stdout = child.take_stdout();- let mut child_stderr = child.take_stderr();+ let deadline = Instant::now() + timeout;+ let child_stdout = child.take_stdout();+ let child_stderr = child.take_stderr();+ #[cfg(unix)]+ let readers = (|| {+ Ok::<_, std::io::Error>((+ child_stdout+ .map(|stream| pipe::PipeReader::new(stream, Some(deadline), None))+ .transpose()?,+ child_stderr+ .map(|stream| pipe::PipeReader::new(stream, Some(deadline), None))+ .transpose()?,+ ))+ })();+ #[cfg(not(unix))]+ let readers = Ok::<_, std::io::Error>((child_stdout, child_stderr));+ let (mut child_stdout, mut child_stderr) = match readers {+ Ok(readers) => readers,+ Err(error) => {+ kill_timed_out_tree(child.id());+ let _ = child.kill();+ let _ = child.wait();+ return Err(error);+ }+ };std::thread::scope(|s| {let stdout_thread = s.spawn(|| {@@ -989,30 +1040,39 @@ fn run_with_timeout_impl(Ok::<_, std::io::Error>(buf)});- match child.wait_timeout(timeout) {- Ok(Some(status)) => {- let stdout = stdout_thread.join().unwrap()?;- let stderr = stderr_thread.join().unwrap()?;- Ok(std::process::Output {- status,- stdout,- stderr,- })+ let collect = || {+ let stdout = output_reader_result(stdout_thread.join());+ let stderr = output_reader_result(stderr_thread.join());+ Ok::<_, std::io::Error>((stdout?, stderr?))+ };+ // Keep the group leader unreaped until bounded EOF. A descendant-held+ // pipe can then time out without surrendering the identity used by cleanup.+ #[cfg(unix)]+ let output = match collect() {+ Ok(output) => output,+ Err(error) => {+ kill_timed_out_tree(child.id());+ let _ = child.kill();+ let _ = child.wait();+ return Err(error);}- // Timed out, or the wait itself failed. A failed wait has to tear the- // tree down too: propagating it instead would leave the child running,- // and the scope's join then blocks on `read_to_end` until the child- // closes its pipes — the caller waits out the full runtime the timeout- // exists to bound, and gets back an error that isn't `TimedOut`.- outcome => {+ };+ let status = match wait_shared_child(&child, Some(deadline)) {+ Ok(status) => status,+ Err(error) => {kill_timed_out_tree(child.id());let _ = child.kill();let _ = child.wait();- Err(outcome.err().unwrap_or_else(|| {- std::io::Error::new(ErrorKind::TimedOut, "command timed out")- }))+ return Err(error);}- }+ };+ #[cfg(not(unix))]+ let output = collect()?;+ Ok(std::process::Output {+ status,+ stdout: output.0,+ stderr: output.1,+ })})}@@ -1024,19 +1084,19 @@ fn run_with_timeout_impl(/// handlers run on TERM, so an interrupted git cleans up after itself.////// Signalling by pid is safe here because the caller still holds an unreaped-/// [`shared_child::SharedChild`]: a timed wait uses `waitid(WNOWAIT)`, so a child-/// that exited on the deadline's other side is a zombie that keeps its pid-/// reserved until the caller's own `wait()`. The pid cannot name a different+/// [`shared_child::SharedChild`]: bounded readers finish before waiting/reaping,+/// and an expired direct wait leaves the child unreaped. An exited child stays+/// a zombie reserving its pid until the caller's own `wait()`. It cannot name a different/// process group by the time the signal lands.////// The same unreaped zombie means the escalation's liveness probe reads the/// group as alive for the entire grace, so its final SIGKILL fires even when/// every member exited on the TERM. Accepted: that sweep is a no-op against a-/// dead group (see [`forward_signal_with_escalation`]), and holding the zombie+/// dead group (see [`terminate_process_group`]), and holding the zombie/// is what pins the pgid.#[cfg(unix)]fn kill_timed_out_tree(pid: u32) {- forward_signal_with_escalation(pid as i32, signal_hook::consts::SIGTERM);+ terminate_process_group(pid as i32);}/// `taskkill /T` walks the child tree Windows has no process group for; `/F`@@ -1044,11 +1104,12 @@ fn kill_timed_out_tree(pid: u32) {/// that detached from it.#[cfg(windows)]fn kill_timed_out_tree(pid: u32) {- let _ = Command::new("taskkill")+ let mut command = Command::new("taskkill");+ command.args(["/T", "/F", "/PID", &pid.to_string()]).stdout(Stdio::null())- .stderr(Stdio::null())- .status();+ .stderr(Stdio::null());+ let _ = spawn(&mut command).and_then(|mut child| child.wait());}// ============================================================================@@ -1110,14 +1171,9 @@ pub struct Cmd {shell_wrap: bool,/// Stdout configuration for stream() (defaults to inherit)stdout_cfg: Option<std::process::Stdio>,- /// Stdin configuration for stream() (defaults to null, or piped if stdin_data is set)+ /// Stdin configuration for stream() (defaults to null, or a file for stdin_data)stdin_cfg: Option<std::process::Stdio>,- /// If true, the child shares the parent's process group instead of being- /// isolated in its own — required when the child reads the controlling- /// terminal (interactive TUI pickers, pagers). Set via `.inherit_stdin()`.- /// See the comment in `stream()` for the SIGTTOU rationale.- share_parent_pgroup: bool,- /// If true, forward signals to child process group (for stream(), Unix only)+ /// Observe terminal signals and forward PID-targeted cancellation during stream().forward_signals: bool,/// If true, treat a SIGPIPE exit as success. This is the default for pager/// producers, where the consumer closing early is expected. Direct user@@ -1217,8 +1273,8 @@ pub struct StreamCommandError {pub output: String,/// The command string, e.g., "git worktree add /path -b fix main".pub command: String,- /// Exit information, e.g., "exit code 255" or "killed by signal".- pub exit_info: String,+ /// Native status, retaining signal identity for cancellation and rendering.+ pub status: std::process::ExitStatus,}impl std::fmt::Display for StreamCommandError {@@ -1230,6 +1286,15 @@ impl std::fmt::Display for StreamCommandError {}}+impl StreamCommandError {+ pub fn exit_info(&self) -> String {+ self.status+ .code()+ .map(|code| format!("exit code {code}"))+ .unwrap_or_else(|| "killed by signal".to_string())+ }+}+impl std::error::Error for StreamCommandError {}/// Shared state between [`Cmd::delayed_stream`] and its two reader threads.@@ -1260,18 +1325,22 @@ fn stream_exit_result(return Ok(());}let lines = &state.lock().unwrap().lines;- let exit_info = status- .code()- .map(|c| format!("exit code {c}"))- .unwrap_or_else(|| "killed by signal".to_string());Err(StreamCommandError {output: lines.join("\n"),command: cmd_str.to_string(),- exit_info,+ status,}.into())}+/// Decode a streamed line, trimming a trailing newline/carriage return and+/// replacing invalid UTF-8 without dropping later command diagnostics.+pub fn output_line(bytes: &[u8]) -> std::borrow::Cow<'_, str> {+ let bytes = bytes.strip_suffix(b"\n").unwrap_or(bytes);+ let bytes = bytes.strip_suffix(b"\r").unwrap_or(bytes);+ String::from_utf8_lossy(bytes)+}+/// Spawn a reader thread for [`Cmd::delayed_stream`]: each line is written to/// stderr live once the switch to streaming has happened, or buffered (for the/// quiet-fast and pre-threshold cases) until then. Both the child's stdout and@@ -1288,20 +1357,45 @@ fn stream_exit_result(fn spawn_delayed_reader<R: Read + Send + 'static>(stream: R,state: Arc<Mutex<DelayedOutput>>,-) -> std::thread::JoinHandle<()> {+) -> std::thread::JoinHandle<std::io::Result<()>> {std::thread::spawn(move || {- let reader = BufReader::new(stream);- for line in reader.lines().map_while(Result::ok) {- let mut state = state.lock().unwrap();+ let mut reader = BufReader::new(stream);+ let mut bytes = Vec::new();+ while reader.read_until(b'\n', &mut bytes)? != 0 {+ let line = output_line(&bytes);+ let mut state = state+ .lock()+ .map_err(|_| std::io::Error::other("Command output state poisoned"))?;if state.streaming {eprintln!("{}", line);} else {- state.lines.push(line);+ state.lines.push(line.into_owned());}+ bytes.clear();}+ Ok(())})}+/// Convert a reader's thread panic or I/O failure into the output error channel.+fn output_reader_result<T>(joined: std::thread::Result<std::io::Result<T>>) -> std::io::Result<T> {+ joined+ .map_err(|_| std::io::Error::other("Command output reader panicked"))+ .and_then(|result| result)+}++/// Join every reader before returning the first I/O or thread failure.+fn join_delayed_readers(+ handles: [std::thread::JoinHandle<std::io::Result<()>>; 2],+) -> std::io::Result<()> {+ let mut result = Ok(());+ for handle in handles {+ let reader_result = output_reader_result(handle.join());+ result = result.and(reader_result);+ }+ result+}+impl Cmd {fn builder(program: impl Into<String>, shell_wrap: bool) -> Self {Self {@@ -1315,7 +1409,6 @@ impl Cmd {shell_wrap,stdout_cfg: None,stdin_cfg: None,- share_parent_pgroup: false,forward_signals: false,ignore_sigpipe: true,external_label: None,@@ -1465,10 +1558,10 @@ impl Cmd {self}- /// Set data to pipe to the command's stdin.+ /// Set complete input bytes, delivered through an anonymous temporary file.///- /// For `.run()`, the data is written to a piped stdin.- /// For `.stream()`, this takes precedence over `.stdin(Stdio)`.+ /// The child reads these bytes followed by EOF, without a pipe writer that+ /// can block on an unread input. This takes precedence over `.stdin(Stdio)`.pub fn stdin_bytes(mut self, data: impl Into<Vec<u8>>) -> Self {self.stdin_data = Some(data.into());self@@ -1565,9 +1658,8 @@ impl Cmd {/// Set stdin configuration for `.stream()`.////// Defaults to `Stdio::null()`. For interactive commands that need the- /// parent's controlling terminal, use [`Cmd::inherit_stdin()`] instead —- /// it also makes `.forward_signals()` keep the child in the parent's- /// process group (required to avoid SIGTTOU stopping the child mid-render).+ /// parent's input, use [`Cmd::inherit_stdin()`] instead. Foreground group+ /// membership and access to `/dev/tty` are independent of stdin.////// Only affects `.stream()`. For `.run()`, stdin defaults to null unless/// data is provided via `.stdin_bytes()`.@@ -1576,42 +1668,18 @@ impl Cmd {self}- /// Inherit the parent's stdin, including the controlling terminal.- ///- /// Required for children that read from a TTY (interactive TUI pickers,- /// pagers, anything that calls `tcsetattr` on `/dev/tty`). When combined- /// with [`Cmd::forward_signals()`], the child is *not* isolated in its- /// own process group — it shares the parent's. A child reading the- /// parent's tty must share the foreground pgroup, or the kernel sends- /// SIGTTOU when the child manipulates terminal settings, suspending it.+ /// Inherit the parent's stdin for interactive input.///- /// In the shared-pgroup case the kernel already delivers tty-initiated- /// signals (SIGINT from Ctrl-C, SIGTSTP from Ctrl-Z, SIGHUP on hangup)- /// to every process in the foreground pgroup. For externally-delivered- /// signals that only reach wt (e.g. `kill -TERM <wt-pid>`), the listener- /// re-delivers to the child by PID so the child also exits — without- /// escalation, since the caller chose the signal and a premature SIGKILL- /// would skip the child's tty restore.+ /// Foreground group membership is independent of this setting.pub fn inherit_stdin(mut self) -> Self {self.stdin_cfg = Some(std::process::Stdio::inherit());- self.share_parent_pgroup = true;self}- /// Forward signals (SIGINT, SIGTERM) to child process group.- ///- /// On Unix, spawns the child in its own process group and forwards signals- /// with escalation (SIGINT → SIGTERM → SIGKILL). This enables clean shutdown- /// of the entire process tree on Ctrl-C.- ///- /// When combined with [`Cmd::inherit_stdin()`], the new-pgroup isolation- /// is skipped (the child shares the parent's pgroup so it can drive the- /// controlling terminal); the listener then forwards by PID single-shot- /// rather than `killpg`-with-escalation, so externally-delivered signals- /// (e.g. `kill -TERM <wt-pid>`) still reach the child. Either way,- /// signal-derived child exits surface as- /// `WorktrunkError::ChildProcessExited { signal: .. }`.+ /// Preserve terminal Ctrl-C delivery and forward SIGTERM to live children.///+ /// The child shares the caller's foreground group. A handled Ctrl-C keeps+ /// its normal status; cancellation and signal exits stop foreground loops./// Only affects `.stream()` on Unix. No-op on Windows.pub fn forward_signals(mut self) -> Self {self.forward_signals = true;@@ -1689,55 +1757,25 @@ impl Cmd {let mut cmd = self.direct_command();self.apply_common_settings(&mut cmd);- // Execute with or without stdin. Every branch produces a single- // `Result<Output>` so spawn/write failures resolve the trace through- // `record_captured` rather than `?`-ing past it (which would leave the- // command unattributed and trip CommandTrace's drop assertion).- let result = if let Some(stdin_data) = self.stdin_data.as_deref() {- // Stdin piping requires spawn/write/wait- // Note: stdin path doesn't support timeout (would need async I/O)- cmd.stdin(Stdio::piped())- .stdout(Stdio::piped())- .stderr(Stdio::piped());-- match cmd.spawn() {- Ok(mut child) => {- let _tracked = self.track_if_cancellable(child.id());- // Write stdin data in an inner scope so the handle DROPS- // (closing the pipe) before `wait_with_output` — otherwise a- // child that reads stdin to EOF (e.g. `git … --stdin`) blocks- // forever. (ignore BrokenPipe - some commands exit early)- let write_result = {- let mut stdin = child.stdin.take().expect("stdin was configured as piped");- stdin.write_all(stdin_data)- };- match write_result {- Err(e) if e.kind() != std::io::ErrorKind::BrokenPipe => Err(e),- _ => child.wait_with_output(),- }- }- Err(e) => Err(e),- }- } else if let Some(timeout_duration) = self.timeout {- // Timeout handling uses the existing impl- run_with_timeout_impl(&mut cmd, timeout_duration, !self.finish_once_started)- } else {- // Simple case: run and capture output. Spawned explicitly rather- // than via `cmd.output()` — which matches these stdio defaults —- // because `output()` hands back only the finished result, never- // the running child, and a background command has to be- // registered as cancellable while it runs (see BACKGROUND_PIDS).- cmd.stdin(Stdio::null())+ // Preparation failures and child outcomes resolve the same trace.+ let result = (|| {+ let stdin = self+ .stdin_data+ .as_deref()+ .map(buffered_stdin)+ .transpose()?+ .unwrap_or_else(Stdio::null);+ cmd.stdin(stdin).stdout(Stdio::piped()).stderr(Stdio::piped());- match cmd.spawn() {- Ok(child) => {- let _tracked = self.track_if_cancellable(child.id());- child.wait_with_output()- }- Err(e) => Err(e),+ if let Some(timeout) = self.timeout {+ run_with_timeout_impl(&mut cmd, timeout, !self.finish_once_started)+ } else {+ let child = spawn(&mut cmd)?;+ let _tracked = self.track_if_cancellable(child.id());+ child.wait_with_output()}- };+ })();record_captured(&mut trace, self.stdin_data.as_deref(), &result);@@ -1807,7 +1845,7 @@ impl Cmd {cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());- match cmd.spawn() {+ match spawn(&mut cmd) {Ok(child) => {let tracked = self.track_if_cancellable(child.id());Ok(CapturedChild {@@ -1903,23 +1941,23 @@ impl Cmd {let source_stdin = self.stdin_data.take();+ let mut first_trace = CommandTrace::new(self.context.as_deref(), &first_cmd_str)+ .reads_stdin(source_stdin.is_some());+ let input = source_stdin+ .as_deref()+ .map(buffered_stdin)+ .transpose()+ .inspect_err(|error| {+ first_trace.fail(error);+ })?+ .unwrap_or_else(Stdio::null);let mut first = self.direct_command();self.apply_common_settings(&mut first);first- .stdin(if source_stdin.is_some() {- Stdio::piped()- } else {- Stdio::null()- })+ .stdin(input).stdout(Stdio::piped()).stderr(Stdio::piped());-- // Trace each command from just before its own spawn so the duration- // brackets the real spawn → wait span. The source reads stdin only when- // fed a buffer; the sink always reads it (the source's piped stdout).- let mut first_trace = CommandTrace::new(self.context.as_deref(), &first_cmd_str)- .reads_stdin(source_stdin.is_some());- let mut first_child = match first.spawn() {+ let mut first_child = match spawn(&mut first) {Ok(child) => child,Err(e) => {first_trace.fail(&e);@@ -1931,16 +1969,6 @@ impl Cmd {.stdout.take().expect("stdout was configured as piped");- // Take the source's stdin pipe, keeping `source_stdin` owned so it can- // also be logged below; a writer thread (in the scope) drains it- // concurrently with the rest of the pipeline.- let source_stdin_pipe = source_stdin.as_ref().map(|_| {- first_child- .stdin- .take()- .expect("stdin was configured as piped")- });-let mut second = next.direct_command();next.apply_common_settings(&mut second);second@@ -1953,7 +1981,7 @@ impl Cmd {// `self`). If the spawn itself fails, clean up `self` before returning.let mut second_trace =CommandTrace::new(next.context.as_deref(), &second_cmd_str).reads_stdin(true);- let second_child = match second.spawn() {+ let second_child = match spawn(&mut second) {Ok(child) => child,Err(e) => {second_trace.fail(&e);@@ -1983,21 +2011,6 @@ impl Cmd {first_stderr_pipe.read_to_end(&mut buf).map(|_| buf)});- // Feed the source's stdin (e.g. a `git rev-list` commit list- // piped into `git diff-tree --stdin`) on a thread, concurrent- // with the drain below — writing it all up front would deadlock- // once the source's stdout pipe fills. A short write (the source- // exited early) surfaces as its non-zero exit status, which- // callers already inspect. The scoped thread only borrows the- // data, so `source_stdin` stays available to log after the- // pipeline reaps the source.- if let (Some(mut stdin), Some(data)) = (source_stdin_pipe, source_stdin.as_deref()) {- s.spawn(move || {- let _ = stdin.write_all(data);- // `stdin` drops here, closing the pipe so the source sees EOF.- });- }-// Drain `next` first (its `wait_with_output` reads its own// stdout/stderr), so `first`'s writes can complete. Its stdin is the// source's stdout (the OS pipe), not its own input, so it is logged@@ -2034,7 +2047,7 @@ impl Cmd {/// - Inherits stderr to preserve TTY behavior (colors, progress bars)/// - Optionally redirects stdout to stderr (via `.stdout(Stdio::from(io::stderr()))`)/// - Optionally inherits stdin for interactive commands (via `.stdin(Stdio::inherit())`)- /// - Optionally forwards signals to child process group (via `.forward_signals()`)+ /// - Optionally observes terminal signals and forwards cancellation (`.forward_signals()`)/// - Does not use concurrency limiting (streaming commands run sequentially by nature)/// - Does not support timeout (interactive commands should not be time-limited)///@@ -2044,7 +2057,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::SIGPIPE, std::os::unix::process::CommandExt};+ use signal_hook::consts::SIGPIPE;// Shell-wrapped commands don't use args (the command string is the full command)assert!(@@ -2092,12 +2105,15 @@ impl Cmd {// Determine stdout handling (default: inherit)let stdout_mode = self.stdout_cfg.unwrap_or_else(std::process::Stdio::inherit);- // Determine stdin handling (stdin_bytes takes precedence, then stdin cfg, then null)- let stdin_mode = if self.stdin_data.is_some() {- std::process::Stdio::piped()- } else {- self.stdin_cfg.unwrap_or_else(std::process::Stdio::null)+ let stdin = match self.stdin_data.as_deref() {+ Some(data) => buffered_stdin(data)+ .inspect_err(|error| {+ CommandTrace::record_failed(self.context.as_deref(), &cmd_str, true, error);+ })+ .context("Failed to prepare command input")?,+ None => self.stdin_cfg.unwrap_or_else(Stdio::null),};+ cmd.stdin(stdin);// Install the SIGINT/SIGTERM handler BEFORE spawn so a signal arriving// mid-spawn is queued, not default-killed.@@ -2108,23 +2124,8 @@ impl Cmd {None};- #[cfg(unix)]- if self.forward_signals && !self.share_parent_pgroup {- // Isolate the child in its own process group so we can signal the whole tree.- //- // Skipped when the caller used `.inherit_stdin()`: a child that- // reads the parent's controlling terminal must share the- // foreground pgroup, otherwise calls like skim's (crossterm)- // `tcsetattr` on `/dev/tty` raise SIGTTOU and stop the child- // mid-render. The kernel already delivers tty-initiated signals- // (Ctrl-C, Ctrl-Z, hangup) to every process in the shared- // pgroup, so explicit forwarding is redundant in that case.- cmd.process_group(0);- }-// Apply environment and spawn- cmd.stdin(stdin_mode)- .stdout(stdout_mode)+ cmd.stdout(stdout_mode).stderr(std::process::Stdio::inherit()) // Preserve TTY for errors// Prevent vergen "overridden" warning in nested cargo builds.env_remove("VERGEN_GIT_DESCRIBE");@@ -2134,8 +2135,19 @@ impl Cmd {// guard unresolved, and the duration brackets the child.let mut trace = CommandTrace::new(self.context.as_deref(), &cmd_str).reads_stdin(self.stdin_data.is_some());- let mut child = match cmd.spawn() {- Ok(child) => child,+ #[cfg(unix)]+ let spawned = match &signals {+ Some(signals) => signals.spawn(&mut cmd),+ None => spawn_shared_child(&mut cmd).map_err(anyhow::Error::from),+ };+ #[cfg(not(unix))]+ let spawned = spawn_shared_child(&mut cmd).map_err(anyhow::Error::from);+ let child = match spawned {+ Ok(child) => Arc::new(child),+ Err(error) if error.interrupt_signal().is_some() => {+ trace.fail(&error);+ return Err(error);+ }Err(e) => {trace.fail(&e);return Err(anyhow::Error::from(GitError::Other {@@ -2144,94 +2156,38 @@ impl Cmd {}};- // Write stdin content if provided (ignore BrokenPipe - child may exit early)- if let Some(ref content) = self.stdin_data- && let Some(mut stdin) = child.stdin.take()- && let Err(e) = stdin.write_all(content)- && e.kind() != std::io::ErrorKind::BrokenPipe- {- trace.fail(&e);- return Err(e.into());- }- // stdin handle is dropped here, closing the pipe-- // 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 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 = forwarder.and_then(|f| f.stop());-- let status = match wait_result {- Ok(status) => status,- Err(e) => {- trace.fail(&e);- return Err(anyhow::Error::from(GitError::Other {- message: format!("Failed to wait for command: {}", e),- }));- }+ let waited = match signals {+ Some(signals) => signals+ .wait(&child)+ .map(|outcome| (outcome.status, outcome.cancellation)),+ None => wait_shared_child(&child, None).map(|status| (status, None)),};-- // Handle signals (Unix only).- //- // `seen_signal` records any signal forwarded by the listener thread,- // covering the case where the child caught the signal and exited with- // a code (no kernel `status.signal()` to read). The clean-exit gate- // closes the wait-vs-handle.close window: if `child.wait()` returned- // success and a signal then landed before `handle.close()` ran, the- // signal arrived too late to have killed anything — the contract on- // `signal: Some(_)` is "this child was killed by the signal" and- // `interrupt_signal` callers in pipeline loops break on it.+ #[cfg(not(unix))]+ let waited = wait_shared_child(&child, None).map(|status| (status, None::<i32>));+ let (status, cancellation) = waited+ .inspect_err(|error| {+ let _ = child.kill();+ let _ = child.wait();+ trace.fail(error);+ })+ .context("Failed to wait for command")?;#[cfg(unix)]- if let Some(sig) = seen_signal- && !status.success()- {- trace.complete(false);- external_log.record(Some(128 + sig));- return Err(WorktrunkError::ChildProcessExited {- code: 128 + sig,- message: format!("terminated by signal {}", sig),- signal: Some(sig),- }- .into());- }+ let child_signal = std::os::unix::process::ExitStatusExt::signal(&status);+ // SIGPIPE is expected when a pager exits before its producer finishes.#[cfg(unix)]- if let Some(sig) = std::os::unix::process::ExitStatusExt::signal(&status) {- // SIGPIPE (13) is expected when a pager (less, bat) exits before the- // child finishes writing — not an error from the user's perspective.- if sig == SIGPIPE && self.ignore_sigpipe {- trace.complete(true);- external_log.record(Some(0));- return Ok(());- }- trace.complete(false);- external_log.record(Some(128 + sig));- return Err(WorktrunkError::ChildProcessExited {- code: 128 + sig,- message: format!("terminated by signal {}", sig),- signal: Some(sig),- }- .into());+ if child_signal == Some(SIGPIPE) && self.ignore_sigpipe && cancellation.is_none() {+ trace.complete(true);+ external_log.record(Some(0));+ return Ok(());}- if !status.success() {- let code = status.code().unwrap_or(1);- trace.complete(false);- external_log.record(status.code());- return Err(WorktrunkError::ChildProcessExited {- code,- message: format!("exit status: {}", code),- signal: None,- }- .into());+ if !status.success() || cancellation.is_some() {+ let error = WorktrunkError::from_child_status(&status, cancellation);+ trace.complete(status.success());+ external_log.record(error.exit_code());+ return Err(error.into());}trace.complete(true);@@ -2305,7 +2261,7 @@ impl Cmd {.stdout(Stdio::piped()).stderr(Stdio::piped());- let child = match SharedChild::spawn(&mut cmd) {+ let child = match spawn_shared_child(&mut cmd) {Ok(child) => child,Err(e) => {trace.fail(&e);@@ -2315,6 +2271,28 @@ impl Cmd {let stdout = child.take_stdout().expect("stdout was piped");let stderr = child.take_stderr().expect("stderr was piped");+ #[cfg(unix)]+ let prepared = (|| {+ let (control, cancel) = socket_pair()?;+ let control = Arc::new(control);+ Ok::<_, std::io::Error>((+ pipe::PipeReader::new(stdout, None, Some(control.clone()))?,+ pipe::PipeReader::new(stderr, None, Some(control))?,+ cancel,+ ))+ })();+ #[cfg(unix)]+ let (stdout, stderr, cancel) = match prepared {+ Ok(prepared) => prepared,+ Err(error) => {+ let _ = child.kill();+ let _ = child.wait();+ trace.fail(&error);+ return Err(error).context("Failed to prepare command output");+ }+ };+ #[cfg(unix)]+ let mut cancel = Some(cancel);// Shared state: readers stream directly once `streaming` is set, and// buffer until then.@@ -2324,41 +2302,26 @@ impl Cmd {let start = Instant::now();- // Phase 1: If the delay threshold is enabled, wait that long for the- // child to exit. If it finishes before the threshold, output stays- // buffered (quiet).- if delay_ms >= 0 {- let delay = Duration::from_millis(delay_ms as u64);- let remaining = delay.saturating_sub(start.elapsed());-- // Zero delay means "stream immediately", not "try a zero-timeout reap".- if !remaining.is_zero() {- match child.wait_timeout(remaining) {- Ok(Some(status)) => {- let _ = stdout_handle.join();- let _ = stderr_handle.join();- trace.complete(status.success());- return stream_exit_result(status, &state, &cmd_str);- }- // No status yet: the threshold passed, or the timed wait- // itself failed. Both fall through to streaming. A failed- // wait means the deadline machinery broke — `sigchld`- // allocates a pipe and registers a handler per call, which- // a sandbox or an fd limit can deny — not that the child- // misbehaved, and Phase 2's `wait()` is a bare `waitid`- // with neither, so it still returns the real status.- // Failing here would turn a denied syscall into a failed- // command, which is the shape of #3856.- outcome => {- tracing::debug!(?outcome, "No exit status yet; switching to streaming");+ let wait_result = 'wait: {+ // Phase 1: wait up to the presentation threshold; an early exit stays quiet.+ if delay_ms >= 0 {+ let delay = Duration::from_millis(delay_ms as u64);+ let remaining = delay.saturating_sub(start.elapsed());++ // Zero delay streams immediately, without a zero-timeout reap.+ if !remaining.is_zero() {+ match wait_shared_child(&child, Some(Instant::now() + remaining)) {+ Ok(status) => break 'wait Ok(status),+ // This deadline controls presentation, not child lifetime.+ // On a timeout or wait-setup error, stream output and retry.+ outcome => {+ tracing::debug!(?outcome, "No exit status yet; switching to streaming");+ }}}- }- // Delay threshold exceeded — switch to streaming. The flip, the- // progress message, and the drain happen under the same lock the- // readers take per line, so no reader can print between them.- {+ // Switch to streaming under the readers' lock so no line can+ // print between the progress message and the buffered output.let mut state = state.lock().unwrap();state.streaming = true;if let Some(ref msg) = progress_message {@@ -2368,12 +2331,25 @@ impl Cmd {eprintln!("{}", line);}}- }- // Phase 2: Block until the child exits (no polling).- let wait_result = child.wait();- let _ = stdout_handle.join();- let _ = stderr_handle.join();+ // Phase 2: block until the child exits.+ wait_shared_child(&child, None)+ };+ #[cfg(unix)]+ if match &wait_result {+ Ok(status) => matches!(+ std::os::unix::process::ExitStatusExt::signal(status),+ Some(signal_hook::consts::SIGINT | signal_hook::consts::SIGTERM)+ ),+ Err(_) => true,+ } {+ cancel.take();+ }+ if wait_result.is_err() {+ let _ = child.kill();+ let _ = child.wait();+ }+ let output_result = join_delayed_readers([stdout_handle, stderr_handle]);let status = match wait_result {Ok(status) => status,Err(e) => {@@ -2381,6 +2357,10 @@ impl Cmd {return Err(e).context("Failed to wait for command");}};+ if let Err(error) = output_result {+ trace.fail(&error);+ return Err(error).context("Failed to read command output");+ }trace.complete(status.success());stream_exit_result(status, &state, &cmd_str)}@@ -2390,12 +2370,114 @@ impl Cmd {// Signal forwarding helpers (Unix only)// ============================================================================-/// One `killpg(pgid, 0)` liveness probe. Only `ESRCH` proves the group empty;-/// everything else counts as alive. That makes the probe conservative in one-/// specific way: an exited-but-unreaped member (a zombie) still registers —-/// Linux answers `Ok`, macOS `EPERM` — so a group whose members all exited-/// keeps reading alive until someone reaps them. See-/// [`forward_signal_with_escalation`] for why that over-report is safe.+/// Wait for a shared child without holding its signaling lock while stopped.+///+/// Darwin can return a stop from SharedChild's waitid(WEXITED) path. Its+/// subsequent blocking Child::wait holds that lock, preventing CONT and kill.+/// On macOS, subscribe to kernel exit events before try_wait so exit cannot+/// be lost between check and sleep. Other platforms use SharedChild directly.+/// A deadline returns TimedOut without reaping a still-running child.+pub fn wait_shared_child(+ child: &SharedChild,+ deadline: Option<Instant>,+) -> std::io::Result<std::process::ExitStatus> {+ #[cfg(target_os = "macos")]+ let status = wait_macos_child(child, deadline)?;+ #[cfg(not(target_os = "macos"))]+ let status = match deadline {+ Some(deadline) => child.wait_deadline(deadline)?,+ None => Some(child.wait()?),+ };+ let status =+ status.ok_or_else(|| std::io::Error::new(ErrorKind::TimedOut, "command timed out"))?;+ Ok(status)+}++/// Wait for a foreground child and publish native cancellation to current scopes.+/// Captures and diff-preview pagers use the neutral wait instead; their command+/// consumers decide whether to propagate typed cancellation.+pub fn wait_foreground_child(child: &SharedChild) -> std::io::Result<std::process::ExitStatus> {+ let status = wait_shared_child(child, None)?;+ #[cfg(unix)]+ if let Some(signal @ (signal_hook::consts::SIGINT | signal_hook::consts::SIGTERM)) =+ std::os::unix::process::ExitStatusExt::signal(&status)+ {+ crate::signal_forwarder::cancel_foreground(signal);+ }+ Ok(status)+}++#[cfg(target_os = "macos")]+fn wait_macos_child(+ child: &SharedChild,+ deadline: Option<Instant>,+) -> std::io::Result<Option<std::process::ExitStatus>> {+ use nix::errno::Errno;+ use nix::sys::event::{EvFlags, EventFilter, FilterFlag, KEvent, Kqueue};+ let queue = Kqueue::new()?;+ let exit = KEvent::new(+ child.id() as usize,+ EventFilter::EVFILT_PROC,+ EvFlags::EV_ADD | EvFlags::EV_ONESHOT,+ FilterFlag::NOTE_EXIT,+ 0,+ 0,+ );+ loop {+ let subscribe = queue.kevent(+ &[exit],+ &mut [],+ Some(nix::libc::timespec {+ tv_sec: 0,+ tv_nsec: 0,+ }),+ );+ // A cached status wins over ESRCH if another waiter reaped the child.+ if let Some(status) = child.try_wait()? {+ return Ok(Some(status));+ }+ match subscribe {+ Err(Errno::EINTR) => continue,+ // Darwin can remove the owned process from kqueue lookup before+ // its exit is waitable. Like NOTE_EXIT below, ESRCH means it can+ // no longer stop; finish synchronized reaping rather than fail.+ Err(Errno::ESRCH) => return child.wait().map(Some),+ Err(error) => return Err(error.into()),+ Ok(_) => break,+ }+ }+ let mut events = [exit];+ loop {+ let timeout = deadline.map(|deadline| {+ let duration = deadline.saturating_duration_since(Instant::now());+ nix::libc::timespec {+ tv_sec: duration.as_secs().min(i64::MAX as u64) as _,+ tv_nsec: duration.subsec_nanos().into(),+ }+ });+ let count = match queue.kevent(&[], &mut events, timeout) {+ Ok(count) => count,+ Err(Errno::EINTR) => continue,+ Err(e) => return Err(e.into()),+ };+ let observed = child.try_wait()?;+ if let Some(status) = observed {+ return Ok(Some(status));+ }+ if count == 0 {+ return Ok(None);+ }+ if events[0].flags().contains(EvFlags::EV_ERROR) {+ return Err(Errno::from_raw(events[0].data() as i32).into());+ }+ // NOTE_EXIT precedes waitable zombie state on Darwin. Once exit has+ // begun, this child cannot stop again; the ordinary synchronized wait+ // is now safe and closes the exit-event vs waitable-status gap.+ return child.wait().map(Some);+ }+}++/// Probe whether an owned background process group still exists.#[cfg(unix)]fn process_group_alive(pgid: i32) -> bool {match nix::sys::signal::killpg(nix::unistd::Pid::from_raw(pgid), None) {@@ -2426,77 +2508,125 @@ fn group_died_within(pgid: i32, grace: Duration) -> bool {}}-/// Single-shot signal delivery to a specific PID. Used in shared-pgroup mode-/// where the child isn't a pgroup leader (so `killpg` would target a non--/// existent group), and where the kernel has already broadcast tty signals-/// to the foreground pgroup — explicit forwarding only matters for-/// externally-delivered signals (e.g. `kill -TERM <wt-pid>`). No escalation:-/// see the call site in `Cmd::stream` for the rationale.+/// Request cancellation of a recorded background worker by PID. Foreground+/// delivery instead uses SharedChild's synchronized signaling ownership.#[cfg(unix)]-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,- _ => return,- };- let _ = nix::sys::signal::kill(nix::unistd::Pid::from_raw(pid), nix_sig);+pub fn terminate_pid(pid: i32) {+ let _ = nix::sys::signal::kill(+ nix::unistd::Pid::from_raw(pid),+ nix::sys::signal::Signal::SIGTERM,+ );}-/// Signal a child process group and sweep stragglers: send `sig` (SIGINT or-/// SIGTERM; anything else is ignored), give the group a 200 ms grace to exit,-/// and SIGKILL whatever still remains. SIGINT inserts a SIGTERM round (with-/// its own grace) before the SIGKILL, so an interrupted git still runs its-/// TERM-time lockfile cleanup before force-kill.-///-/// "Still remains" is `process_group_alive`'s answer, and that probe counts-/// an exited-but-unreaped member as alive — it cannot tell a zombie from live-/// work. The over-report errs in the safe direction on both sides:+/// Terminate an owned timeout or tether group: TERM, 200 ms grace, then KILL.+/// Foreground cancellation uses native job delivery instead of this teardown.///-/// - Every member already exited, the leader just isn't reaped yet: the grace-/// runs to its deadline and the final SIGKILL lands on a dead group, which-/// is a no-op — a signal to a fully-exited process is discarded and cannot-/// change its recorded exit status, so TERM-time cleanup that already ran is-/// not undone. `kill_timed_out_tree` is permanently in this position: its-/// caller holds the group leader unreaped throughout (see its doc), so on-/// that path the sweep always fires, harmlessly.-/// - A member is genuinely alive at the deadline: the probe is accurate and-/// the SIGKILL is the intended escalation. For a SIGSTOP'd member it is the-/// only signal that works — a stopped process runs no TERM handler, so the-/// sweep is what keeps teardown bounded.+/// The group probe counts unreaped exits as alive. Capture timeouts retain+/// their leader, so they always use the full grace; signaling an already dead+/// group cannot change its exit status. Live survivors, including stopped or+/// TERM-ignoring processes, are killed at the deadline.///-/// Callers whose children are reaped concurrently — `Cmd::stream`'s main-/// thread waiting while the signal-forwarder thread runs this, tether's-/// supervisor — get the accurate reading: the poll loop returns at the first-/// probe after the reap, so escalating over a cooperative child costs one-/// poll interval, not the full grace. A reap does unpin the pgid, leaving the-/// microseconds between a probe that read alive and the following `killpg` as-/// the accepted recycling exposure — unchanged from the fixed-sleep-/// predecessor, and shared by every killpg-after-grace design.+/// Tether may have reaped its leader, allowing an early return once the group+/// disappears. Reaping unpins the numeric pgid, leaving the existing recycling+/// exposure between the group probe and the subsequent signal.#[cfg(unix)]-pub fn forward_signal_with_escalation(pgid: i32, sig: i32) {+pub fn terminate_process_group(pgid: i32) {use nix::sys::signal::Signal;let pgid = nix::unistd::Pid::from_raw(pgid);- let chain: &[Signal] = match sig {- signal_hook::consts::SIGINT => &[Signal::SIGINT, Signal::SIGTERM],- signal_hook::consts::SIGTERM => &[Signal::SIGTERM],- _ => return,- };-- let grace = Duration::from_millis(200);- for step in chain {- let _ = nix::sys::signal::killpg(pgid, *step);- if group_died_within(pgid.as_raw(), grace) {- return;- }+ let _ = nix::sys::signal::killpg(pgid, Signal::SIGTERM);+ if !group_died_within(pgid.as_raw(), Duration::from_millis(200)) {+ let _ = nix::sys::signal::killpg(pgid, Signal::SIGKILL);}- let _ = nix::sys::signal::killpg(pgid, Signal::SIGKILL);}#[cfg(test)]mod tests {use super::*;+ /// macOS sets close-on-exec after creating stdio pipes and wakeup sockets.+ /// Concurrent spawns must not inherit these endpoints and delay EOF.+ #[cfg(target_os = "macos")]+ #[test]+ fn test_parallel_commands_do_not_inherit_sibling_descriptors() {+ const SCRIPT: &str = "+import errno, os, stat+counts = [0, 0]+for name in os.listdir('/dev/fd'):+ fd = int(name)+ if fd <= 2:+ continue+ try:+ mode = os.fstat(fd).st_mode+ except OSError as error:+ if error.errno != errno.EBADF:+ raise+ continue+ counts[0] += stat.S_ISFIFO(mode)+ counts[1] += stat.S_ISSOCK(mode)+print(*counts)+";+ let inspect = || Cmd::new("/usr/bin/python3").args(["-c", SCRIPT]).run();+ let descriptor_counts = |output: std::io::Result<std::process::Output>| {+ let output = output.unwrap();+ assert!(output.status.success(), "{output:?}");+ String::from_utf8(output.stdout)+ .unwrap()+ .split_whitespace()+ .map(|count| count.parse::<usize>().unwrap())+ .collect::<Vec<_>>()+ };+ // A test runner may itself have passed inheritable descriptors.+ let inherited = descriptor_counts(inspect());+ let barrier = std::sync::Barrier::new(16);+ let stop = AtomicBool::new(false);+ struct StopCreators<'a>(&'a AtomicBool);+ impl Drop for StopCreators<'_> {+ fn drop(&mut self) {+ self.0.store(true, Ordering::Relaxed);+ }+ }+ let results = std::thread::scope(|scope| {+ // Stop creators before scope joins its threads, including on panic.+ let _stop_creators = StopCreators(&stop);+ for index in 0..8 {+ let stop = &stop;+ scope.spawn(move || {+ while !stop.load(Ordering::Relaxed) {+ match index % 3 {+ 0 => drop(socket_pair().unwrap()),+ 1 => drop(stream_socket(socket2::Domain::UNIX).unwrap()),+ _ => drop(stream_socket(socket2::Domain::IPV4).unwrap()),+ }+ }+ });+ }+ let workers: Vec<_> = (0..16)+ .map(|_| {+ scope.spawn(|| {+ (0..32)+ .map(|_| {+ barrier.wait();+ inspect()+ })+ .collect::<Vec<_>>()+ })+ })+ .collect();+ workers+ .into_iter()+ .flat_map(|worker| worker.join().unwrap())+ .collect::<Vec<_>>()+ });+ for output in results {+ assert_eq!(+ descriptor_counts(output),+ inherited,+ "inherited sibling pipe or wakeup socket"+ );+ }+ }+/// The property the worktree-local scrub sites rest on: `TempIndex` and a/// redirected repository's object store scrub the whole/// [`INHERITED_GIT_PATH_VARS`] list and then set their own value for one of@@ -2728,9 +2858,8 @@ mod tests {#[test]#[cfg(unix)]- fn test_unix_shell_is_posix() {+ fn test_unix_shell_is_sh() {let config = ShellConfig::get().unwrap();- assert!(config.is_posix);assert_eq!(config.name, "sh");}@@ -2772,7 +2901,6 @@ mod tests {fn test_windows_uses_git_bash() {let config = ShellConfig::get().unwrap();assert_eq!(config.name, "Git Bash");- assert!(config.is_posix, "Git Bash should support POSIX syntax");assert!(config.args.contains(&"-c".to_string()),"Git Bash should use -c flag"@@ -2821,7 +2949,6 @@ mod tests {let config = ShellConfig::get().unwrap();let cloned = config.clone();assert_eq!(config.name, cloned.name);- assert_eq!(config.is_posix, cloned.is_posix);assert_eq!(config.args, cloned.args);}@@ -2846,6 +2973,7 @@ mod tests {fn test_cmd_timeout_kills_slow_command() {let result = Cmd::new("sleep").arg("10")+ .stdin_bytes("unconsumed input").timeout(Duration::from_millis(50)).run();assert!(result.is_err());@@ -2930,11 +3058,13 @@ mod tests {#[test]fn test_cmd_with_stdin() {- let result = Cmd::new("cat").stdin_bytes("hello from stdin").run();- assert!(result.is_ok());- let output = result.unwrap();- assert!(output.status.success());- assert!(String::from_utf8_lossy(&output.stdout).contains("hello from stdin"));+ // A complete buffer can exceed both input and output pipe capacity.+ // Empty input must still supply EOF rather than inherit the caller.+ for input in [Vec::new(), b"hello from stdin\n".repeat(100_000)] {+ let output = Cmd::new("cat").stdin_bytes(input.as_slice()).run().unwrap();+ assert!(output.status.success());+ assert_eq!(output.stdout, input);+ }}// ========================================================================@@ -3094,17 +3224,6 @@ mod tests {assert_eq!(err.kind(), ErrorKind::NotFound);}- #[test]- #[cfg(unix)]- fn test_cmd_run_with_stdin_closes_pipe() {- // `cat` reads stdin to EOF; it can only exit once the pipe is closed,- // so this pins the "drop stdin before wait" behavior (a regression here- // hangs forever rather than failing).- let output = Cmd::new("cat").stdin_bytes("piped body").run().unwrap();- assert!(output.status.success());- assert_eq!(String::from_utf8_lossy(&output.stdout), "piped body");- }-#[test]#[cfg(unix)]fn test_cmd_delayed_stream_quiet_success() {@@ -3113,6 +3232,24 @@ mod tests {Cmd::new("true").delayed_stream(5_000, None).unwrap();}+ #[test]+ #[cfg(unix)]+ fn test_cmd_delayed_stream_retains_output_after_invalid_utf8() {+ let error = Cmd::new("python3")+ .args([+ "-c",+ "import sys; sys.stdout.buffer.write(b'\\xffinvalid\\r\\n' + b'x' * 250000 + b'\\nTAIL'); sys.stdout.flush(); sys.exit(17)",+ ])+ .delayed_stream(-1, None)+ .unwrap_err();+ let command = error.downcast_ref::<StreamCommandError>().unwrap();+ assert_eq!(command.status.code(), Some(17), "{error:?}");+ assert_eq!(+ command.output,+ format!("�invalid\n{}\nTAIL", "x".repeat(250000)),+ );+ }+#[test]#[cfg(unix)]fn test_cmd_delayed_stream_crosses_the_threshold() {@@ -3140,7 +3277,7 @@ mod tests {let stream_err = err.downcast_ref::<StreamCommandError>().expect("non-zero delayed_stream exit should be a StreamCommandError");- assert_eq!(stream_err.exit_info, "exit code 3");+ assert_eq!(stream_err.exit_info(), "exit code 3");assert_eq!(stream_err.output, "","output written after the switch must stream, not buffer"@@ -3177,7 +3314,7 @@ mod tests {let stream_err = err.downcast_ref::<StreamCommandError>().expect("non-zero delayed_stream exit should be a StreamCommandError");- assert_eq!(stream_err.exit_info, "exit code 3");+ assert_eq!(stream_err.exit_info(), "exit code 3");assert_eq!(stream_err.output, "","output buffered before the switch must be drained to stderr, not reported"@@ -3197,7 +3334,7 @@ mod tests {let stream_err = err.downcast_ref::<StreamCommandError>().expect("non-zero delayed_stream exit should be a StreamCommandError");- assert_eq!(stream_err.exit_info, "exit code 3");+ assert_eq!(stream_err.exit_info(), "exit code 3");}#[test]@@ -3305,12 +3442,17 @@ mod tests {#[test]fn test_stream_command_error_display_is_the_output() {+ #[cfg(unix)]+ use std::os::unix::process::ExitStatusExt;+ #[cfg(windows)]+ use std::os::windows::process::ExitStatusExt;+// The Display impl exists only for the Error bound; callers read fields// via Repository::extract_failed_command, so nothing else exercises it.let err = StreamCommandError {output: "fatal: ref exists".to_string(),command: "git worktree add /x".to_string(),- exit_info: "exit code 128".to_string(),+ status: std::process::ExitStatus::from_raw(if cfg!(unix) { 128 << 8 } else { 128 }),};assert_eq!(err.to_string(), "fatal: ref exists");}@@ -3394,22 +3536,13 @@ mod tests {assert!(!super::process_group_alive(999_999_999));}- #[test]- #[cfg(unix)]- fn test_forward_signal_with_escalation_unknown_signal() {- // Unknown signal should return early without doing anything- // Use a signal number that's not SIGINT or SIGTERM- super::forward_signal_with_escalation(1, 999);- // No panic = success (function returns early for unknown signals)- }-#[test]#[cfg(unix)]fn test_group_died_within_immediate_for_reaped_group() {// A reaped child leaves an empty group: the first (immediate) probe// reads ESRCH and the grace loop returns without sleeping. This pins// the early exit that keeps escalation cheap for the callers whose- // children are reaped concurrently (signal forwarder, tether).+ // children are reaped concurrently (tether).use std::os::unix::process::CommandExt;let mut cmd = std::process::Command::new("sh");cmd.args(["-c", ":"]).process_group(0);@@ -3463,7 +3596,7 @@ mod tests {child.stdout.take().unwrap().read_to_end(&mut eof).unwrap();let start = Instant::now();- super::forward_signal_with_escalation(pid, signal_hook::consts::SIGTERM);+ super::terminate_process_group(pid);assert!(start.elapsed() >= Duration::from_millis(200),"with the leader unreaped the group must read alive for the whole grace"diff --git a/src/shell_exec/pipe.rs b/src/shell_exec/pipe.rsnew file mode 100644index 000000000..48f5695ba--- /dev/null+++ b/src/shell_exec/pipe.rs@@ -0,0 +1,137 @@+//! Unix pipe waits with a shared deadline and an explicit output cancellation fence.+//!+//! A cancelled reader consumes only the bytes queued when it observes the fence,+//! then closes: a surviving descendant cannot prolong cancellation by writing.+//! Ordinary completion retains EOF semantics. Deadlines cover I/O as well as exit.++use std::io::{self, Read};+use std::os::fd::{AsFd, OwnedFd};+use std::os::unix::net::UnixStream;+use std::sync::Arc;+use std::time::Instant;++use nix::fcntl::{FcntlArg, OFlag, fcntl};+use nix::poll::{PollFd, PollFlags, PollTimeout, poll};++pub fn set_nonblocking(fd: impl AsFd) -> io::Result<()> {+ let flags = OFlag::from_bits_truncate(fcntl(&fd, FcntlArg::F_GETFL)?);+ fcntl(&fd, FcntlArg::F_SETFL(flags | OFlag::O_NONBLOCK))?;+ Ok(())+}++/// Wake a nonblocking poll peer. A full buffer already guarantees readiness;+/// a retired peer needs no wake. Interrupted writes must retry the notification.+pub fn wake(fd: impl AsFd) {+ while let Err(nix::errno::Errno::EINTR) = nix::unistd::write(&fd, &[1]) {}+}++/// Retry interrupted polls against the original deadline, never extending it.+pub fn poll_until_ready(fds: &mut [PollFd<'_>], deadline: Option<Instant>) -> io::Result<()> {+ loop {+ let timeout = match deadline {+ Some(deadline) => {+ let remaining = deadline.saturating_duration_since(Instant::now());+ if remaining.is_zero() {+ return Err(io::Error::new(io::ErrorKind::TimedOut, "command timed out"));+ }+ PollTimeout::try_from(remaining).unwrap_or(PollTimeout::MAX)+ }+ None => PollTimeout::NONE,+ };+ match poll(fds, timeout) {+ Ok(0) => continue,+ Ok(_) => return Ok(()),+ Err(nix::errno::Errno::EINTR) => continue,+ Err(error) => return Err(error.into()),+ }+ }+}++pub struct PipeReader {+ stream: OwnedFd,+ deadline: Option<Instant>,+ cancel: Option<Arc<UnixStream>>,+ remaining: Option<u64>,+}++impl PipeReader {+ pub fn new(+ stream: impl Into<OwnedFd>,+ deadline: Option<Instant>,+ cancel: Option<Arc<UnixStream>>,+ ) -> io::Result<Self> {+ let stream = stream.into();+ set_nonblocking(&stream)?;+ Ok(Self {+ stream,+ deadline,+ cancel,+ remaining: None,+ })+ }++ /// Finish only the bytes already queued; future descendant output is excluded.+ pub fn cancel(&mut self) -> io::Result<()> {+ self.remaining = Some(rustix::io::ioctl_fionread(&self.stream)?);+ self.cancel.take();+ Ok(())+ }++ /// Read one nonblocking chunk for callers that already own the poll loop.+ pub fn read_ready(&mut self, bytes: &mut [u8]) -> io::Result<usize> {+ let limit = self.remaining.map_or(bytes.len(), |remaining| {+ remaining.min(bytes.len() as u64) as usize+ });+ if limit == 0 {+ return Ok(0);+ }+ match nix::unistd::read(&self.stream, &mut bytes[..limit]).map_err(io::Error::from) {+ Ok(count) => {+ if let Some(remaining) = &mut self.remaining {+ *remaining -= count as u64;+ }+ Ok(count)+ }+ Err(error) if error.kind() == io::ErrorKind::WouldBlock && self.remaining.is_some() => {+ Ok(0)+ }+ Err(error) => Err(error),+ }+ }+}++impl AsFd for PipeReader {+ fn as_fd(&self) -> std::os::fd::BorrowedFd<'_> {+ self.stream.as_fd()+ }+}++impl Read for PipeReader {+ fn read(&mut self, bytes: &mut [u8]) -> io::Result<usize> {+ if bytes.is_empty() {+ return Ok(0);+ }+ loop {+ if self.remaining == Some(0) {+ return Ok(0);+ }+ let mut fds = vec![PollFd::new(self.stream.as_fd(), PollFlags::POLLIN)];+ if let Some(cancel) = &self.cancel {+ fds.push(PollFd::new(cancel.as_fd(), PollFlags::POLLIN));+ }+ poll_until_ready(&mut fds, self.deadline)?;+ if fds+ .get(1)+ .is_some_and(|fd| !fd.revents().unwrap_or(PollFlags::empty()).is_empty())+ {+ self.cancel()?;+ }+ match self.read_ready(bytes) {+ Ok(count) => return Ok(count),+ Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,+ Err(error) if error.kind() == io::ErrorKind::WouldBlock => {}+ Err(error) => return Err(error),+ }+ }+ }+}diff --git a/src/signal_forwarder.rs b/src/signal_forwarder.rsindex 1e01180cc..ab4cee181 100644--- a/src/signal_forwarder.rs+++ b/src/signal_forwarder.rs@@ -1,212 +1,570 @@-//! Forwards SIGINT/SIGTERM from `wt` to its foreground children.+//! Foreground commands share the caller's Unix job group, independently of stdin.//!-//! 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>`.-//! Forwards the user's signal once per pgroup; a second user signal-//! SIGKILLs every still-live pgroup. No per-child escalation —-//! cooperative children die from the user's signal so `wt`'s exit code-//! reflects intent (130 on Ctrl-C, not 143 from a SIGTERM landed during-//! a sub-second escalation grace window under CI scheduling latency).-//! Stubborn children require a second Ctrl-C, matching `make` / `cargo`.-//!-//! [`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.+//! The terminal delivers Ctrl-C and Ctrl-Z to the whole job. A handled Ctrl-C+//! therefore leaves each child's own exit status intact. SIGTERM addressed to+//! wt cancels its command and is forwarded to live direct children by PID;+//! SharedChild serializes those deliveries with reaping. No caller group is killed.+//! A group-wide TERM may also reach a child through this PID forwarding;+//! repeated TERM deliveries never trigger escalation here.+//! Spawn return commits admission. Startup cancellation retires an uncommitted+//! child with TERM; its cleanup is best effort, while admitted children finish+//! native-key cleanup. TERM is cooperative, with no escalation.+//! Ignored inherited dispositions stay ignored. Outside active commands, signal+//! handlers retain native default behavior, including between pipeline steps.+//! A confirmed INT/TERM child exit wakes all current foreground scopes, so+//! parallel output waits also stop. Execution leases end with direct waits;+//! output observers remain through EOF and distinguish newly delivered keys+//! using a flag registered at that transition, rather than notification timing.+//! A command-operation guard retains cancellation across gaps between foreground+//! scopes without disabling idle native defaults. New scopes share that operation's+//! latch; dropping the guard makes the next operation independent.-use std::sync::Arc;-use std::sync::atomic::{AtomicI32, Ordering};+use std::sync::atomic::{AtomicBool, AtomicI32, Ordering};+use std::sync::{Arc, Mutex, OnceLock, Weak};use std::thread;-use signal_hook::consts::{SIGINT, SIGTERM};+use shared_child::{SharedChild, unix::SharedChildExt};use signal_hook::iterator::{Handle, Signals};+use signal_hook::{+ SigId,+ consts::{SIGCONT, SIGINT, SIGTERM},+};++struct Activity {+ count: usize,+ idle: Arc<AtomicBool>,+ watched: Vec<i32>,+ scopes: Vec<Weak<Interruption>>,+ operation: Weak<OperationCancellation>,+}++// A typed child interruption cancels the current foreground operation,+// including parallel scopes whose direct children have already finished.+// Weak observers neither retain completed scopes nor carry cancellation into+// a later operation. Callbacks only wake waiters; they never run under Activity.+struct Interruption {+ signal: Arc<AtomicI32>,+ admission: AtomicI32,+ wake: OnceLock<Arc<dyn Fn() + Send + Sync>>,+}++impl Interruption {+ fn signal(&self) -> Option<i32> {+ match self.signal.load(Ordering::SeqCst) {+ 0 => None,+ signal => Some(signal),+ }+ }+}++/// Publish a typed interruption accepted by the foreground command.+/// Capture callers use this when propagating cancellation, so aggregating+/// concurrent errors cannot discard cancellation behind an earlier diagnostic.+pub fn cancel_foreground(signal: i32) {+ let Some(Ok(state)) = ACTIVITY.get() else {+ return;+ };+ let scopes: Vec<_> = {+ let mut activity = state.lock().unwrap_or_else(|error| error.into_inner());+ if let Some(operation) = activity.operation.upgrade() {+ let _ =+ operation+ .signal+ .compare_exchange(0, signal, Ordering::SeqCst, Ordering::SeqCst);+ }+ activity.scopes.retain(|scope| scope.strong_count() != 0);+ let scopes: Vec<_> = activity.scopes.iter().filter_map(Weak::upgrade).collect();+ for scope in &scopes {+ let _ = scope+ .signal+ .compare_exchange(0, signal, Ordering::SeqCst, Ordering::SeqCst);+ }+ scopes+ };+ for scope in scopes {+ if let Some(wake) = scope.wake.get() {+ wake();+ }+ }+}++static ACTIVITY: OnceLock<Result<Mutex<Activity>, String>> = OnceLock::new();++#[derive(Default)]+struct OperationCancellation {+ signal: Arc<AtomicI32>,+ terminated: Arc<AtomicBool>,+}++impl OperationCancellation {+ fn signal(&self) -> Option<i32> {+ if self.terminated.load(Ordering::SeqCst) {+ Some(SIGTERM)+ } else {+ match self.signal.load(Ordering::SeqCst) {+ 0 => None,+ signal => Some(signal),+ }+ }+ }+}-use crate::shell_exec::{forward_signal_to_pid, forward_signal_with_escalation};+/// Own cancellation for one CLI command, including later parallel admissions.+/// This guard holds no execution lease: idle terminal signals keep native defaults.+pub struct CommandOperation {+ state: &'static Mutex<Activity>,+ cancellation: Arc<OperationCancellation>,+ _registration: Registration,+}++impl CommandOperation {+ pub fn start() -> std::io::Result<Self> {+ let state = Lease::state()?;+ let mut activity = state.lock().unwrap_or_else(|error| error.into_inner());+ if activity.operation.upgrade().is_some() {+ return Err(std::io::Error::other(+ "a command operation is already active",+ ));+ }+ let cancellation = Arc::new(OperationCancellation::default());+ let mut registration = Registration(Vec::new());+ if activity.watched.contains(&SIGTERM) {+ registration.0.push(signal_hook::flag::register(+ SIGTERM,+ cancellation.terminated.clone(),+ )?);+ }+ activity.operation = Arc::downgrade(&cancellation);+ Ok(Self {+ state,+ cancellation,+ _registration: registration,+ })+ }++ pub fn interrupt_signal(&self) -> Option<i32> {+ self.cancellation.signal()+ }+}++impl Drop for CommandOperation {+ fn drop(&mut self) {+ self.state+ .lock()+ .unwrap_or_else(|error| error.into_inner())+ .operation = Weak::new();+ }+}++/// Cancellation of the command whose work is currently being admitted.+pub fn operation_interrupt_signal() -> Option<i32> {+ let state = ACTIVITY.get()?.as_ref().ok()?;+ let operation = state+ .lock()+ .unwrap_or_else(|error| error.into_inner())+ .operation+ .upgrade()?;+ operation.signal()+}++struct Lease(&'static Mutex<Activity>);++impl Lease {+ fn state() -> std::io::Result<&'static Mutex<Activity>> {+ ACTIVITY+ .get_or_init(|| {+ let idle = Arc::new(AtomicBool::new(true));+ let watched = [SIGINT, SIGTERM]+ .into_iter()+ .filter_map(|signal| match ignored(signal) {+ Ok(false) => Some(Ok(signal)),+ Ok(true) => None,+ Err(error) => Some(Err(error)),+ })+ .collect::<std::io::Result<Vec<_>>>()+ .map_err(|error| error.to_string())?;+ for &signal in &watched {+ signal_hook::flag::register_conditional_default(signal, idle.clone())+ .map_err(|error| error.to_string())?;+ }+ Ok(Mutex::new(Activity {+ count: 0,+ idle,+ watched,+ scopes: Vec::new(),+ operation: Weak::new(),+ }))+ })+ .as_ref()+ .map_err(|error| std::io::Error::other(error.clone()))+ }+}++impl Drop for Lease {+ fn drop(&mut self) {+ // Cleanup must restore defaults even if another owner panicked.+ let mut activity = self.0.lock().unwrap_or_else(|error| error.into_inner());+ activity.count -= 1;+ if activity.count == 0 {+ activity.idle.store(true, Ordering::SeqCst);+ }+ }+}++/// Query an inherited disposition without replacing its handler.+#[allow(unsafe_code)]+fn ignored(signal: i32) -> std::io::Result<bool> {+ let mut action = std::mem::MaybeUninit::<nix::libc::sigaction>::uninit();+ // SAFETY: null new-action is a read-only query; action is valid output storage.+ if unsafe { nix::libc::sigaction(signal, std::ptr::null(), action.as_mut_ptr()) } == -1 {+ return Err(std::io::Error::last_os_error());+ }+ // SAFETY: successful sigaction initialized the returned disposition.+ Ok(unsafe { action.assume_init() }.sa_sigaction == nix::libc::SIG_IGN)+}++struct Registration(Vec<SigId>);++impl Drop for Registration {+ fn drop(&mut self) {+ for id in self.0.drain(..) {+ signal_hook::low_level::unregister(id);+ }+ }+}-/// 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,+ terminated: Arc<AtomicBool>,+ interrupted: Arc<AtomicBool>,+ scope: Arc<Interruption>,+ lease: Lease,+ registration: Registration,+}++/// Physical child status and independent foreground cancellation.+pub struct ForegroundOutcome {+ pub status: std::process::ExitStatus,+ pub cancellation: Option<i32>,}impl ForegroundSignals {- /// Register `wt`'s SIGINT/SIGTERM handler. Errors only if the- /// `signal_hook` registration itself fails (extremely rare).+ /// Install before spawning so startup signals remain queued.pub fn install() -> std::io::Result<Self> {+ let state = Lease::state()?;+ // Fallible setup precedes admission, so an unwinding setup leaves+ // existing leases intact. Recover as the other Activity owners do.+ let mut activity = state.lock().unwrap_or_else(|error| error.into_inner());+ let operation = activity.operation.upgrade();+ let scope = Arc::new(Interruption {+ signal: operation+ .as_ref()+ .map(|operation| operation.signal.clone())+ .unwrap_or_default(),+ admission: AtomicI32::new(0),+ wake: OnceLock::new(),+ });+ let watched = &activity.watched;+ let terminated = operation+ .as_ref()+ .map(|operation| operation.terminated.clone())+ .unwrap_or_default();+ let interrupted = Arc::new(AtomicBool::new(false));+ let mut registration = Registration(Vec::new());+ for &signal in watched {+ if signal == SIGTERM && operation.is_some() {+ // CommandOperation already registered this shared TERM flag.+ continue;+ }+ let flag = if signal == SIGTERM {+ terminated.clone()+ } else {+ interrupted.clone()+ };+ registration+ .0+ .push(signal_hook::flag::register(signal, flag)?);+ }+ // signal-hook creates its wake socket pair internally, with the same+ // macOS close-on-exec window as our own output sockets.+ let signals = crate::shell_exec::with_process_creation_guard(|| {+ Signals::new(watched.iter().copied())+ })?;+ // Admit only after handlers are ready. Before this point an idle job+ // keeps its native default, and an overlapping job latches startup keys.+ activity.scopes.retain(|scope| scope.strong_count() != 0);+ activity.scopes.push(Arc::downgrade(&scope));+ activity.count += 1;+ activity.idle.store(false, Ordering::SeqCst);+ drop(activity);Ok(Self {- signals: Signals::new([SIGINT, SIGTERM])?,+ signals,+ terminated,+ interrupted,+ scope,+ registration,+ lease: Lease(state),})}- /// 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);+ /// Synchronously latched startup cancellation, before a listener exists.+ pub fn interrupt_signal(&self) -> Option<i32> {+ if self.terminated.load(Ordering::SeqCst) {+ Some(SIGTERM)+ } else {+ self.scope+ .signal()+ .or_else(|| self.interrupted.load(Ordering::SeqCst).then_some(SIGINT))+ }+ }++ /// Admission commits when spawn returns. A cancelled in-flight child may+ /// have missed the native key; retire only that uncommitted child with TERM.+ /// Earlier admitted children finish native-key cleanup. Publish the admission+ /// origin before its teardown can report a different physical child signal.+ pub fn spawn(&self, command: &mut std::process::Command) -> anyhow::Result<SharedChild> {+ if let Some(signal) = self.interrupt_signal() {+ self.cancel_admission(signal);+ return Err(crate::git::WorktrunkError::Interrupted { signal, hint: None }.into());+ }+ match crate::shell_exec::spawn_shared_child(command) {+ Ok(child) => {+ if let Some(signal) = self.interrupt_signal() {+ self.cancel_admission(signal);+ let _ = child.send_signal(SIGTERM);+ let _ = child.send_signal(SIGCONT);+ } else if tracing::enabled!(target: crate::trace::WT_TRACE_TARGET, tracing::Level::DEBUG)+ {+ crate::trace::instant(&format!("Foreground admitted:{}", child.id()));}+ Ok(child)}- })+ Err(error) => {+ if let Some(signal) = self.interrupt_signal() {+ self.cancel_admission(signal);+ return Err(+ crate::git::WorktrunkError::Interrupted { signal, hint: None }.into(),+ );+ }+ Err(error.into())+ }+ }}- /// Begin forwarding to N children's PGIDs. Forwards the same signal- /// once on the first press; a second user signal SIGKILLs every- /// still-live PGID immediately.- ///- /// No per-child escalation: cooperative children die from the user's- /// signal, so `child.wait()` reports a cause of death that matches- /// intent (e.g. `wt step <alias>` exits 130 on Ctrl-C, not 143 from a- /// SIGTERM that landed during a 200 ms escalation grace window under- /// CI scheduling latency). Stubborn children that ignore SIGINT- /// require a second Ctrl-C — matching `make` / `cargo` behavior.- 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);- let signal_to_send = pgid_broadcast_signal(sig, seen_once);- seen_once = true;- for &pgid in &child_pgids {- let _ = nix::sys::signal::killpg(nix::unistd::Pid::from_raw(pgid), signal_to_send);- }+ fn cancel_admission(&self, signal: i32) {+ let _ =+ self.scope+ .admission+ .compare_exchange(0, signal, Ordering::SeqCst, Ordering::SeqCst);+ cancel_foreground(signal);+ }++ /// Wait for the owned direct child and stop its signal listener on every path.+ pub fn wait(self, child: &Arc<SharedChild>) -> std::io::Result<ForegroundOutcome> {+ let forwarder = self.forward_to_children(vec![child.clone()], || {});+ let waited = crate::shell_exec::wait_foreground_child(child);+ if waited.is_err() {+ let _ = child.kill();+ let _ = child.wait();+ }+ let admission = forwarder.admission_interrupt_signal();+ let stopped = forwarder.stop();+ Ok(ForegroundOutcome {+ status: waited?,+ cancellation: stopped?.or(admission),})}- /// 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(+ pub fn forward_to_children(self,- mut body: impl FnMut(i32, &AtomicI32) + Send + 'static,+ children: Vec<Arc<SharedChild>>,+ wake: impl Fn() + Send + Sync + '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);+ let Self {+ mut signals,+ terminated,+ interrupted: _,+ scope,+ registration,+ lease,+ } = self;+ let wake = scope.wake.get_or_init(|| Arc::new(wake)).clone();+ if scope.signal().is_some() {+ wake();+ }+ let listener = thread::spawn(move || {+ for signal in signals.forever() {+ if signal == SIGTERM {+ cancel_foreground(signal);+ for child in &children {+ let _ = child.send_signal(signal);+ let _ = child.send_signal(SIGCONT);+ }}- })- };+ // Wake output drains; a caught terminal INT still keeps the+ // child's normal exit status, including a successful exit.+ wake();+ }+ });ActiveForwarder {handle,- listener,- originating,+ listener: Some(listener),+ terminated,+ output_interrupted: None,+ scope,+ _registration: registration,+ _lease: Some(lease),}}}-/// 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()+pub struct ActiveForwarder {+ handle: Handle,+ listener: Option<thread::JoinHandle<()>>,+ terminated: Arc<AtomicBool>,+ output_interrupted: Option<Arc<AtomicBool>>,+ scope: Arc<Interruption>,+ _lease: Option<Lease>,+ _registration: Registration,}-/// The signal to broadcast to every still-live pgroup on a user signal. The-/// first press forwards the user's own signal so cooperative children die with-/// the cause the user intended; any later press escalates to SIGKILL. The-/// listener registers only SIGINT and SIGTERM, so a non-SIGTERM press is-/// necessarily SIGINT.-fn pgid_broadcast_signal(sig: i32, already_signaled: bool) -> nix::sys::signal::Signal {- use nix::sys::signal::Signal;- if already_signaled {- Signal::SIGKILL- } else if sig == SIGTERM {- Signal::SIGTERM- } else {- Signal::SIGINT+impl ActiveForwarder {+ /// The semantic startup cancellation, before any owned teardown signal.+ pub fn admission_interrupt_signal(&self) -> Option<i32> {+ match self.scope.admission.load(Ordering::SeqCst) {+ 0 => None,+ signal => Some(signal),+ }}-}-/// 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>,+ /// Release direct execution while continuing to observe output cancellation.+ /// Registering a fresh flag here excludes older, already handled Ctrl-C+ /// deliveries, even when their iterator notifications are still queued.+ pub fn finish_children(&mut self) -> std::io::Result<()> {+ if let Some(lease) = &self._lease {+ let watched = lease+ .0+ .lock()+ .unwrap_or_else(|error| error.into_inner())+ .watched+ .contains(&SIGINT);+ if watched {+ let flag = Arc::new(AtomicBool::new(false));+ self._registration+ .0+ .push(signal_hook::flag::register(SIGINT, flag.clone())?);+ self.output_interrupted = Some(flag);+ }+ self._lease.take();+ }+ Ok(())+ }++ pub fn interrupt_signal(&self) -> Option<i32> {+ if self.terminated.load(Ordering::SeqCst) {+ Some(SIGTERM)+ } else {+ self.scope.signal().or_else(|| {+ if self+ .output_interrupted+ .as_ref()+ .is_some_and(|flag| flag.load(Ordering::SeqCst))+ {+ cancel_foreground(SIGINT);+ Some(SIGINT)+ } else {+ None+ }+ })+ }+ }++ pub fn stop(mut self) -> std::io::Result<Option<i32>> {+ self.handle.close();+ if let Some(listener) = self.listener.take() {+ listener+ .join()+ .map_err(|_| std::io::Error::other("foreground signal listener panicked"))?;+ }+ self._lease.take();+ Ok(self.interrupt_signal())+ }}-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.+impl Drop for ActiveForwarder {+ fn drop(&mut self) {self.handle.close();- let _ = self.listener.join();- match self.originating.load(Ordering::SeqCst) {- 0 => None,- sig => Some(sig),+ if let Some(listener) = self.listener.take() {+ let _ = listener.join();}}}+/// Whether native re-raising is compatible with the inherited disposition.+pub fn should_reraise(signal: i32) -> std::io::Result<bool> {+ let activity = Lease::state()?+ .lock()+ .unwrap_or_else(|error| error.into_inner());+ Ok(activity.watched.contains(&signal))+}+#[cfg(test)]mod tests {use super::*;- use nix::sys::signal::Signal;+ use crate::git::ErrorExt;+ use crate::shell_exec::Cmd;#[test]- fn first_press_forwards_the_user_signal() {- assert_eq!(pgid_broadcast_signal(SIGINT, false), Signal::SIGINT);- assert_eq!(pgid_broadcast_signal(SIGTERM, false), Signal::SIGTERM);- }+ fn operation_cancellation_survives_scope_retirement_and_resets() {+ const CHILD_ENV: &str = "WORKTRUNK_OPERATION_LIFETIME_TEST_CHILD";+ if std::env::var_os(CHILD_ENV).is_none() {+ // Operation ownership is process-wide. Keep this real lifecycle+ // isolated even when cargo test runs other library tests in parallel.+ let mut command = std::process::Command::new(std::env::current_exe().unwrap());+ command.args([+ "--exact",+ "signal_forwarder::tests::operation_cancellation_survives_scope_retirement_and_resets",+ ]).env(CHILD_ENV, "1");+ assert!(+ crate::shell_exec::spawn(&mut command)+ .unwrap()+ .wait()+ .unwrap()+ .success()+ );+ return;+ }- #[test]- fn later_press_escalates_to_sigkill() {- assert_eq!(pgid_broadcast_signal(SIGINT, true), Signal::SIGKILL);- assert_eq!(pgid_broadcast_signal(SIGTERM, true), Signal::SIGKILL);+ let temp = tempfile::tempdir().unwrap();+ let marker = temp.path().join("late-command-ran");+ let operation = CommandOperation::start().unwrap();+ let error = Cmd::new("python3")+ .args(["-c", "import os,signal; signal.signal(signal.SIGINT,signal.SIG_DFL); os.kill(os.getpid(),signal.SIGINT)"])+ .forward_signals()+ .stream()+ .unwrap_err();+ assert_eq!(error.interrupt_signal(), Some(SIGINT));+ assert_eq!(operation.interrupt_signal(), Some(SIGINT));++ // The first command and its signal scope have finished. A new scope+ // must still refuse work from the same cancelled operation.+ let error = Cmd::new("sh")+ .args(["-c", "touch \"$1\"", "sh", marker.to_str().unwrap()])+ .forward_signals()+ .stream()+ .unwrap_err();+ assert_eq!(error.interrupt_signal(), Some(SIGINT));+ assert!(!marker.exists());+ drop(operation);++ let next = CommandOperation::start().unwrap();+ Cmd::new("sh")+ .args(["-c", "touch \"$1\"", "sh", marker.to_str().unwrap()])+ .forward_signals()+ .stream()+ .unwrap();+ assert!(marker.exists());+ assert_eq!(next.interrupt_signal(), None);}}diff --git a/templates/bash.sh b/templates/bash.shindex 9f4958ef7..9b98cf419 100644--- a/templates/bash.sh+++ b/templates/bash.sh@@ -8,11 +8,9 @@ if command -v {{ cmd }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then{{ cmd }}() {local use_source=falselocal args=()-for arg in "$@"; do- if [[ "$arg" == "--source" ]]; then use_source=true; else args+=("$arg"); fi+ if [[ "$arg" == --source ]]; then use_source=true; else args+=("$arg"); fidone-# Completion mode: call binary directly, no directive files needed.# This check MUST be here (not in the binary) because clap's completion# handler runs before argument parsing.@@ -21,32 +19,85 @@ if command -v {{ cmd }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; thenreturnfi- local cd_file exit_code=0- cd_file="$(mktemp)"-- # --source: use cargo run (builds from source)- if [[ "$use_source" == true ]]; then- WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" \- cargo run --bin {{ cmd }} --quiet -- "${args[@]}" || exit_code=$?- else- WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" \- command "${WORKTRUNK_BIN:-{{ cmd }}}" "${args[@]}" || exit_code=$?- fi-- # cd file holds a raw path (no shell escaping needed).+ # Native SIGINT can unwind this body before ordinary cleanup. Capture one+ # cleanup function for both the next prompt and a noninteractive shell exit.+ local cd_file owner cleanup_body exit_trap owns_exit=false prompt_provider prompt_armed=true+ local prompt_value="${PROMPT_COMMAND-}" prompt_present="${PROMPT_COMMAND+x}" prompt_declared=false+ local prompt_declaration prompt_flags+ if builtin declare -p PROMPT_COMMAND >/dev/null 2>&1; then prompt_declared=true; fi+ # Readonly prompts cannot be replaced; allexport would export our callback.+ if [[ $- == *a* ]] || ! (PROMPT_COMMAND="$prompt_value") 2>/dev/null; then prompt_armed=false; fi+ cd_file="$(mktemp)" || return+ owner="_{{ cmd_ident }}_cleanup_${cd_file##*/}"+ owner="${owner//[^a-zA-Z0-9_]/_}"+ exit_trap="$(builtin trap -p EXIT)"+ # trap -p may expose an inherited but inactive EXIT handler in a subshell.+ # Reinstalling it would activate the parent's handler there.+ if [[ ( $BASH_SUBSHELL -eq 0 || -z "$exit_trap" ) && ( $- != *i* || "$prompt_armed" == true ) ]]; then owns_exit=true; fi+ builtin printf -v prompt_provider 'if %s prompt "$?"; then builtin eval %q; else builtin eval %q; fi' "$owner" "$prompt_value" "$prompt_value"+ # %q captures the state after the caller's local variables have unwound.+ builtin printf -v cleanup_body '+ local cd_file=%q owner=%q exit_trap=%q owns_exit=%q+ local prompt_value=%q prompt_present=%q prompt_declared=%q prompt_provider=%q+ ' "$cd_file" "$owner" "$exit_trap" "$owns_exit" "$prompt_value" "$prompt_present" "$prompt_declared" "$prompt_provider"# `builtin cd` bypasses any user `cd` alias or function (e.g. zoxide's- # `alias cd=__zoxide_z`) that would otherwise be substituted into this+ # `alias cd=__zoxide_z`) that would otherwise be substituted into the# function body when it's defined. See #2643.- if [[ -s "$cd_file" ]]; then- builtin cd -- "$(<"$cd_file")"- local cd_exit=$?- if [[ $exit_code -eq 0 ]]; then- exit_code=$cd_exit+ cleanup_body+='+ local event=$1 status=$2 cd_status=0+ if [[ "$owns_exit" == true ]]; then builtin trap - EXIT; fi+ if [[ -s "$cd_file" ]]; then+ builtin cd -- "$(<"$cd_file")" || cd_status=$?fi- fi+ command rm -f "$cd_file"+ if [[ ${PROMPT_COMMAND-} == "$prompt_provider" ]]; then+ if [[ -n "$prompt_present" ]]; then+ PROMPT_COMMAND="$prompt_value"+ else+ local prompt_flags+ prompt_flags="$(builtin declare -p PROMPT_COMMAND 2>/dev/null)" || prompt_flags=+ prompt_flags=${prompt_flags#declare }+ prompt_flags=${prompt_flags%% *}+ if [[ "$prompt_declared" == true ]]; then+ builtin unset "PROMPT_COMMAND[0]"+ else+ builtin unset PROMPT_COMMAND+ fi+ if [[ "$prompt_flags" == *x* ]]; then builtin export PROMPT_COMMAND; fi+ fi+ fi+ if [[ "$owns_exit" == true && -n "$exit_trap" ]]; then builtin eval "$exit_trap"; fi+ builtin unset -f "$owner"+ if [[ "$event" == normal && $status -eq 0 ]]; then+ return "$cd_status"+ else+ return "$status"+ fi+ '+ builtin eval "$owner() { $cleanup_body }"+ if [[ "$prompt_armed" == true ]]; then PROMPT_COMMAND="$prompt_provider"; fi+ # Bash 3.2 only reports an exported, unset variable after assignment.+ prompt_declaration="$(builtin declare -p PROMPT_COMMAND 2>/dev/null)" || prompt_declaration=+ prompt_flags=${prompt_declaration#declare }+ prompt_flags=${prompt_flags%% *}- command rm -f "$cd_file"- return "$exit_code"+ local exit_code=0+ local execution=("${WORKTRUNK_BIN:-{{ cmd }}}" "${args[@]}")+ if [[ "$use_source" == true ]]; then execution=(cargo run --bin {{ cmd }} --quiet -- "${args[@]}"); fi+ if [[ "$owns_exit" == true ]]; then+ local exit_provider="$owner exit \"\$?\""+ if [[ -n "$exit_trap" ]]; then+ local exit_callback=${exit_trap#trap -- }+ exit_callback=${exit_callback% EXIT}+ builtin printf -v exit_provider 'if %s exit "$?"; then builtin eval %s; else builtin eval %s; fi' "$owner" "$exit_callback" "$exit_callback"+ fi+ builtin trap "$exit_provider" EXIT+ fi+ case "$prompt_armed:$prompt_flags" in+ true:*x*) PROMPT_COMMAND="$prompt_value" WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" command "${execution[@]}" || exit_code=$? ;;+ *) WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" command "${execution[@]}" || exit_code=$? ;;+ esac+ if "$owner" normal "$exit_code"; then return 0; else return $?; fi}# Lazy completions - generate on first TAB, then delegate to clap's completerdiff --git a/templates/fish.fish b/templates/fish.fishindex 011dd158e..0148ee5ed 100644--- a/templates/fish.fish+++ b/templates/fish.fish@@ -20,31 +20,47 @@ function {{ cmd }}endset -l cd_file (mktemp)+ # Older fish unwinds only the function that directly launched an interrupted+ # child. This boundary lets ordinary cleanup run before its caller continues.+ # Newer fish unwinds the whole input line; postexec owns cleanup in that case.+ set -l cleanup_function _{{ cmd }}_cleanup_(string replace -a / _ -- "$cd_file")+ set -l run_function "$cleanup_function"_run+ function $run_function+ command $argv+ end+ function $cleanup_function --on-event fish_postexec --inherit-variable cd_file --inherit-variable cleanup_function --inherit-variable run_function+ set -l cd_exit 0+ # cd file holds a raw path — read with fish builtin (no cat subprocess,+ # safe even if CWD was removed by worktree removal).+ if test -s "$cd_file"+ set -l target (string trim < "$cd_file")+ # `builtin cd` bypasses any user `cd` override (e.g. the zoxide.fish+ # plugin replaces `cd` with a query function that mishandles the `--`+ # separator). Matches the bash/zsh wrappers. (#3159)+ builtin cd -- "$target"+ set cd_exit $status+ end++ command rm -f "$cd_file"+ functions -e $cleanup_function $run_function+ return $cd_exit+ end+# --source: use cargo run (builds from source)if test $use_source = true- env WORKTRUNK_DIRECTIVE_CD_FILE=$cd_file \+ $run_function env WORKTRUNK_DIRECTIVE_CD_FILE=$cd_file \cargo run --bin {{ cmd }} --quiet -- $argselse- env WORKTRUNK_DIRECTIVE_CD_FILE=$cd_file \+ $run_function env WORKTRUNK_DIRECTIVE_CD_FILE=$cd_file \$WORKTRUNK_BIN $argsendset -l exit_code $status- # cd file holds a raw path — read with fish builtin (no cat subprocess,- # safe even if CWD was removed by worktree removal).- if test -s "$cd_file"- set -l target (string trim < "$cd_file")- # `builtin cd` bypasses any user `cd` override (e.g. the zoxide.fish- # plugin replaces `cd` with a query function that mishandles the `--`- # separator). Matches the bash/zsh wrappers. (#3159)- builtin cd -- "$target"- set -l cd_exit $status- if test $exit_code -eq 0- set exit_code $cd_exit- end+ $cleanup_function+ set -l cd_exit $status+ if test $exit_code -eq 0+ set exit_code $cd_exitend-- command rm -f "$cd_file"return $exit_codeenddiff --git a/templates/nushell.nu b/templates/nushell.nuindex bb7daf6eb..c0a70e916 100644--- a/templates/nushell.nu+++ b/templates/nushell.nu@@ -1,4 +1,4 @@-# worktrunk shell integration for nushell+# worktrunk shell integration for nushell 0.113+# Tab completions: calls binary with COMPLETE=nu to get candidates.# Note: nushell's completion engine bypasses custom completers when the current@@ -82,13 +82,17 @@ export def --env --wrapped {{ cmd }} [...args] {($external | get 0.path)}+ # Unquoted wrapped arguments can be glob values. Classify their text+ # while preserving the original arguments for external execution.+ let arg_text = ($args | each {|arg| $arg | into string })+# `list` is the only command that benefits from streaming stdout (progressive# table rendering). It never emits directives, so we skip directive processing# and let the binary be the last expression — stdout flows through pipes.# Note: global flags before `list` (e.g. `wt -C /path list`) miss this check# and fall through to the buffered path. Output is still correct, just not# progressively rendered.- if (not ($args | is-empty)) and ($args | first) == "list" {+ if (not ($arg_text | is-empty)) and ($arg_text | first) == "list" {# Direct passthrough: binary is the last expression of this branch,# which is the last expression of the function. Stdout streams to the# terminal and flows through nushell pipelines.@@ -96,76 +100,57 @@ export def --env --wrapped {{ cmd }} [...args] {} else {let cd_file = (mktemp --tmpdir)let stdout_file = (mktemp --tmpdir)- let wt_args = ($args | take until {|arg| $arg == "--" })- # Before `-x`, `c`, `v`, and `y` are boolean flags clap may cluster with it.- let has_execute = ($wt_args | any {|arg| $arg == "--execute" or ($arg | str starts-with "--execute=") or ($arg =~ '^-[cvy]*x') })+ try {+ let wt_args = ($arg_text | take until {|arg| $arg == "--" })+ # Before `-x`, `c`, `v`, and `y` are boolean flags clap may cluster with it.+ let has_execute = ($wt_args | any {|arg| $arg == "--execute" or ($arg | str starts-with "--execute=") or ($arg =~ '^-[cvy]*x') })- # Capture stdout for pipeline passthrough unless wt will launch an- # interactive child, which must inherit the terminal.- # Nushell 0.98+ throws ShellError on non-zero exit (like bash `set -e`).- # `try` catches it so directive processing and temp file cleanup still run.- let exit_code = (try {- with-env { WORKTRUNK_DIRECTIVE_CD_FILE: $cd_file } {- if $has_execute {- ^$worktrunk_bin ...$args- } else {- ^$worktrunk_bin ...$args o> $stdout_file+ # Capture stdout for pipeline passthrough unless wt will launch an+ # interactive child, which must inherit the terminal.+ # Capture failure status without discarding buffered stdout.+ # The outer `finally` applies directives and cleans up on Ctrl-C too.+ let exit_code = (try {+ with-env { WORKTRUNK_DIRECTIVE_CD_FILE: $cd_file } {+ if $has_execute {+ ^$worktrunk_bin ...$args+ } else {+ ^$worktrunk_bin ...$args o> $stdout_file+ }}- }- 0- } catch {- $env.LAST_EXIT_CODE- })+ 0+ } catch {+ # Nushell reports signal deaths as negative signal numbers. Its+ # `exit` builtin needs the corresponding shell status instead.+ let code = $env.LAST_EXIT_CODE+ if $code < 0 { 128 - $code } else { $code }+ })- # cd file holds a raw path — no shell parsing needed- if ($cd_file | path exists) and (open $cd_file --raw | str trim | is-not-empty) {- let target_dir = open $cd_file --raw | str trim- cd $target_dir- }+ let output = if $has_execute { "" } else { open $stdout_file --raw }- let output = if $has_execute { "" } else { open $stdout_file --raw }-- # Clean up the temp files after their final reads.- #- # A bare `rm` here is shadowable by the user's own `alias rm = ...`:- # nushell resolves aliases at parse time, and `config.nu` runs before the- # vendor autoload dir this file lives in, so the alias is already in scope- # when this `def` is parsed. A `trash`-style alias then leaks the temp- # files, and an alias that exits non-zero raises a ShellError that aborts- # the wrapper before it can return `$output` — swallowing the command's- # stdout entirely.- #- # `^rm` bypasses aliases, but it's external-only, so Windows (where the- # nushell builtin is the only `rm`) keeps the builtin. `try` covers both- # branches so cleanup can never abort the wrapper. `hide rm` is not an- # option: it's a parse-time keyword that leaks out of this function into- # the user's session, silently unbinding their alias.- if $nu.os-info.family == "windows" {- try { rm -f $cd_file $stdout_file }- } else {- try { ^rm -f $cd_file $stdout_file }- }-- # Return stdout or propagate failure as the function's last expression.- # Using a failing external command (not `error make`) so nushell treats it- # identically to the original non-zero exit — minimal display in scripts,- # no verbose source trace.- #- # nushell itself is the external command, not `sh`: `Shell::Nushell` isn't- # platform-gated, so this wrapper is installed on Windows whenever `nu` is- # on PATH, and there `sh` doesn't exist. A missing `sh` turns every failing- # `wt` command into a "Command `sh` not found" trace that prints the- # wrapper's own source and flattens the real exit code to 1 — the opposite- # of what this branch is for. `$nu.current-exe` is always present by- # construction, and using one path on every platform keeps the branch Unix- # CI exercises identical to the one Windows runs. `--no-std-lib` halves- # the startup this costs (~9 ms to ~4.5 ms on nu 0.115); `exit` is a core- # builtin, so propagation is unaffected.- if $exit_code != 0 {- if ($output | is-not-empty) { print -n $output }- ^$nu.current-exe --no-config-file --no-std-lib -c $"exit ($exit_code)"- } else if ($output | is-not-empty) {- $output+ # Return captured stdout or reproduce the external failure without+ # a source trace. Nu itself also works on Windows, where sh is absent.+ if $exit_code != 0 {+ if ($output | is-not-empty) { print -n $output }+ ^$nu.current-exe --no-config-file --no-std-lib -c $"exit ($exit_code)"+ } else if ($output | is-not-empty) {+ $output+ }+ } finally {+ try {+ # cd file holds a raw path — no shell parsing needed+ if ($cd_file | path exists) and (open $cd_file --raw | str trim | is-not-empty) {+ let target_dir = open $cd_file --raw | str trim+ cd $target_dir+ }+ } finally {+ # Bypass user rm aliases on Unix; Windows uses Nushell's builtin.+ # Cleanup cannot replace the command's status.+ if $nu.os-info.family == "windows" {+ try { rm -f $cd_file $stdout_file }+ } else {+ try { ^rm -f $cd_file $stdout_file }+ }+ }}}}diff --git a/templates/zsh.zsh b/templates/zsh.zshindex e1d5716ce..7e6cef20b 100644--- a/templates/zsh.zsh+++ b/templates/zsh.zsh@@ -27,28 +27,28 @@ if command -v {{ cmd }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; thenlocal cd_file exit_code=0cd_file="$(mktemp)"- # --source: use cargo run (builds from source)+ local -a execution=("${WORKTRUNK_BIN:-{{ cmd }}}" "${args[@]}")if [[ "$use_source" == true ]]; then- WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" \- cargo run --bin {{ cmd }} --quiet -- "${args[@]}" || exit_code=$?- else- WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" \- command "${WORKTRUNK_BIN:-{{ cmd }}}" "${args[@]}" || exit_code=$?+ execution=(cargo run --bin {{ cmd }} --quiet -- "${args[@]}")fi-- # cd file holds a raw path (no shell escaping needed).- # `builtin cd` bypasses any user `cd` alias or function (e.g. zoxide's- # `alias cd=__zoxide_z`) that would otherwise be substituted into this- # function body when it's defined. See #2643.- if [[ -s "$cd_file" ]]; then- builtin cd -- "$(<"$cd_file")"- local cd_exit=$?- if [[ $exit_code -eq 0 ]]; then- exit_code=$cd_exit+ {+ WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" command "${execution[@]}"+ } always {+ exit_code=$?+ # cd file holds a raw path (no shell escaping needed).+ # `builtin cd` bypasses any user `cd` alias or function (e.g. zoxide's+ # `alias cd=__zoxide_z`) that would otherwise be substituted into this+ # function body when it's defined. See #2643.+ if [[ -s "$cd_file" ]]; then+ builtin cd -- "$(<"$cd_file")"+ local cd_exit=$?+ if [[ $exit_code -eq 0 ]]; then+ exit_code=$cd_exit+ fifi- fi- command rm -f "$cd_file"+ command rm -f "$cd_file"+ } || :return "$exit_code"}diff --git a/tests/common/mod.rs b/tests/common/mod.rsindex 16cd9c6d6..efcee6652 100644--- a/tests/common/mod.rs+++ b/tests/common/mod.rs@@ -28,6 +28,30 @@ use worktrunk::path::to_posix_path;// Signal handling (for PTY tests)// =============================================================================+#[cfg(unix)]+pub const FOREGROUND_TRACE_FILTER: &str = "worktrunk::wt_trace=debug,worktrunk::trace::emit=debug";++/// Child readiness may precede the parent's spawn return. Caught-signal tests+/// wait for wt to commit admission before delivering ordinary terminal input.+#[cfg(unix)]+pub fn wait_for_foreground_admission(repo: &TestRepo, children: &[i32]) {+ let trace = resolve_git_common_dir(repo.root_path()).join("wt/logs/trace.jsonl");+ let admissions: Vec<_> = children+ .iter()+ .map(|pid| format!("Foreground admitted:{pid}"))+ .collect();+ wait_for("foreground child admission", || {+ std::fs::read_to_string(&trace).is_ok_and(|records| {+ let events = worktrunk::trace::parse_lines(&records);+ admissions.iter().all(|admission| {+ events.iter().any(|entry| {+ matches!(&entry.kind, worktrunk::trace::TraceEntryKind::Instant { name } if name == admission)+ })+ })+ })+ });+}+/// Block SIGTTIN and SIGTTOU signals to prevent test processes from being/// stopped when PTY operations interact with terminal control in background/// process groups.@@ -1380,6 +1404,19 @@ pub fn add_pty_binary_path_filters(settings: &mut insta::Settings) {);}+/// Shell-visible exit status, including a CLI terminated by its native signal.+pub fn shell_exit_code(status: &std::process::ExitStatus) -> Option<i32> {+ #[cfg(unix)]+ {+ use std::os::unix::process::ExitStatusExt;+ status+ .code()+ .or_else(|| status.signal().map(|signal| 128 + signal))+ }+ #[cfg(not(unix))]+ status.code()+}+// =============================================================================// Tests// =============================================================================diff --git a/tests/common/pty.rs b/tests/common/pty.rsindex 224178791..4d15a910f 100644--- a/tests/common/pty.rs+++ b/tests/common/pty.rs@@ -230,8 +230,8 @@ fn find_cursor_request(data: &[u8]) -> Option<usize> {pub type SharedPtyWriter = Arc<Mutex<Box<dyn Write + Send>>>;/// Spawn a thread that drains the PTY master `reader` into the returned channel-/// and answers the cursor-position report query (`ESC[6n`) skim emits while-/// initializing the picker.+/// and answers the cursor-position report query (`ESC[6n`) used by skim during+/// picker initialization and Nushell's interactive prompt.////// skim 4.x runs the picker in partial-height mode, whose setup calls skim's/// `cursor_pos_from_tty()`: it writes `ESC[6n` to `/dev/tty` and blocks in@@ -240,8 +240,9 @@ pub type SharedPtyWriter = Arc<Mutex<Box<dyn Write + Send>>>;/// without this reply skim fails init with "Cursor position detection timed out"/// and the picker never renders. The reply (`1;1`) is a safe constant — skim only/// uses it to place its inline viewport, which the TUI snapshot tests don't assert-/// on. Sharing `writer` with the caller lets keystrokes and query replies both-/// reach the master. The query is matched within a single read chunk; skim emits+/// on. Nushell also waits for a reply before reading prompt input. Sharing+/// `writer` keeps keystrokes and query replies from interleaving. The query is+/// matched within a single read chunk; skim emits/// the 4-byte DSR as one small write, so it never spans chunks.pub fn spawn_pty_reader_answering_queries(reader: Box<dyn Read + Send>,diff --git a/tests/integration_tests/for_each.rs b/tests/integration_tests/for_each.rsindex 44c247179..246ded9a6 100644--- a/tests/integration_tests/for_each.rs+++ b/tests/integration_tests/for_each.rs@@ -218,13 +218,8 @@ fn test_for_each_json_spawn_failure(repo: TestRepo) {}}-/// Signal-derived exit (Ctrl-C, SIGTERM) in a child must abort the loop-/// rather than continuing into the remaining worktrees. Simulated here with-/// a command that self-signals via SIGTERM — this drives the same-/// `ChildProcessExited { signal: Some(_), .. }` path as a real Ctrl-C against-/// the wt process. Sending SIGINT to the parent wt process from an integration-/// test is impractical (it would kill the test harness), so we cover the-/// signal-detection branch via an equivalent in-child signal.+/// A child terminated by a signal aborts the loop before the next worktree.+/// Self-signalling TERM exercises native child status without a terminal.#[rstest]#[cfg(unix)]fn test_for_each_aborts_on_signal_exit(repo: TestRepo) {@@ -248,7 +243,7 @@ fn test_for_each_aborts_on_signal_exit(repo: TestRepo) {// Exit code: 128 + SIGTERM (15) = 143assert_eq!(- output.status.code(),+ crate::common::shell_exit_code(&output.status),Some(143),"expected exit 143 (SIGTERM), got {:?}\nstderr: {}",output.status.code(),@@ -278,8 +273,7 @@ fn test_for_each_aborts_on_signal_exit(repo: TestRepo) {/// An interrupted `--format=json` run still owes its consumer the results it/// collected before the signal: the machine-readable answer is emitted on the-/// abort path too, not just on the completing one. Same in-child SIGTERM as-/// the test above, for the same reason.+/// abort path too, not just on the completing one.#[rstest]#[cfg(unix)]fn test_for_each_json_emitted_on_signal_abort(repo: TestRepo) {@@ -299,7 +293,7 @@ fn test_for_each_json_emitted_on_signal_abort(repo: TestRepo) {let stderr = String::from_utf8_lossy(&output.stderr);assert_eq!(- output.status.code(),+ crate::common::shell_exit_code(&output.status),Some(143),"expected exit 143 (SIGTERM), got {:?}\nstderr: {stderr}",output.status.code(),@@ -316,6 +310,122 @@ fn test_for_each_json_emitted_on_signal_abort(repo: TestRepo) {);}+/// Controller cancellation stops iteration even when the child handles TERM,+/// while JSON retains the child's actual exit rather than reporting spawn failure.+#[rstest]+#[case::caught_success(0)]+#[case::caught_failure(3)]+#[cfg(unix)]+fn test_for_each_json_preserves_caught_exit_on_controller_term(+ repo: TestRepo,+ #[case] exit_code: i32,+) {+ use nix::sys::signal::{Signal, kill, killpg};+ use nix::unistd::Pid;+ use std::os::unix::process::CommandExt;+ use std::process::{Child, Command, Stdio};++ struct OwnedJob {+ keeper: Child,+ child: Option<Child>,+ }+ impl Drop for OwnedJob {+ fn drop(&mut self) {+ // The keeper is never reaped before this signal: its PID reserves+ // the group even if wt has already exited and been collected.+ let _ = killpg(Pid::from_raw(self.keeper.id() as i32), Signal::SIGKILL);+ if let Some(child) = &mut self.child {+ let _ = child.wait();+ }+ let _ = self.keeper.wait();+ }+ }++ let markers = tempfile::tempdir().unwrap();+ let ready = markers.path().join("ready");+ std::fs::create_dir(&ready).unwrap();+ let worker = r#"import json, os, pathlib, signal, sys+signal.signal(signal.SIGTERM, lambda *_: os._exit(int(sys.argv[2])))+directory = pathlib.Path(sys.argv[1])+temporary = directory.parent / f'{os.getpid()}.tmp'+temporary.write_text(json.dumps({'pid': os.getpid(), 'parent': os.getppid()}))+temporary.rename(directory / str(os.getpid()))+while True:+ signal.pause()+"#;++ let mut job = OwnedJob {+ keeper: Command::new("sleep")+ .arg("300")+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .process_group(0)+ .spawn()+ .unwrap(),+ child: None,+ };+ job.child = Some(+ repo.wt_command()+ .args([+ "-vv",+ "step",+ "for-each",+ "--format=json",+ "--",+ "python3",+ "-c",+ ])+ .arg(worker)+ .arg(&ready)+ .arg(exit_code.to_string())+ .env("RUST_LOG", crate::common::FOREGROUND_TRACE_FILTER)+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .process_group(job.keeper.id() as i32)+ .spawn()+ .unwrap(),+ );++ crate::common::wait_for("for-each command readiness", || {+ assert!(+ job.child.as_mut().unwrap().try_wait().unwrap().is_none(),+ "wt exited before its command became ready"+ );+ std::fs::read_dir(&ready).unwrap().next().is_some()+ });+ let entry = std::fs::read_dir(&ready).unwrap().next().unwrap().unwrap();+ let metadata: serde_json::Value =+ serde_json::from_slice(&std::fs::read(entry.path()).unwrap()).unwrap();+ let controller = job.child.as_ref().unwrap().id() as i32;+ assert_eq!(metadata["parent"], controller);+ crate::common::wait_for_foreground_admission(+ &repo,+ &[metadata["pid"].as_i64().unwrap() as i32],+ );+ assert_eq!(+ nix::unistd::getpgid(Some(+ Pid::from_raw(metadata["pid"].as_i64().unwrap() as i32)+ ))+ .unwrap(),+ Pid::from_raw(job.keeper.id() as i32),+ );+ kill(Pid::from_raw(controller), Signal::SIGTERM).unwrap();++ crate::common::wait_for("cancelled for-each completion", || {+ job.child.as_mut().unwrap().try_wait().unwrap().is_some()+ });+ let output = job.child.take().unwrap().wait_with_output().unwrap();+ assert_eq!(crate::common::shell_exit_code(&output.status), Some(143));+ let json: serde_json::Value = serde_json::from_slice(&output.stdout)+ .unwrap_or_else(|e| panic!("cancelled run must emit JSON: {e}\n{output:?}"));+ let items = json.as_array().unwrap();+ assert_eq!(items.len(), 1, "{json}");+ assert_eq!(items[0]["exit_code"], exit_code, "{json}");+ assert_eq!(std::fs::read_dir(&ready).unwrap().count(), 1);+}+/// for-each relocates the user's command into each worktree, so inherited/// git-discovery vars (`GIT_DIR`/`GIT_WORK_TREE`) must be scrubbed — git/// resolves them before walking up from the cwd, so a forwarded value woulddiff --git a/tests/integration_tests/foreground_jobs.rs b/tests/integration_tests/foreground_jobs.rsnew file mode 100644index 000000000..66bb2f1f9--- /dev/null+++ b/tests/integration_tests/foreground_jobs.rs@@ -0,0 +1,1850 @@+//! Foreground CLI children use the shell-established native Unix job group.+//! The shared shell fixture also exercises help-pager selection and completion+//! through the actual TTY entrypoint.+#![cfg(all(unix, feature = "shell-integration-tests"))]++use crate::common::{TestRepo, configure_pty_command, open_pty, repo, wt_bin};+use portable_pty::{Child, CommandBuilder, MasterPty};+use rstest::rstest;+use std::io::Write;+use std::sync::{Arc, Mutex, mpsc};+use std::time::{Duration, Instant};++struct Shell {+ master: Box<dyn MasterPty + Send>,+ writer: crate::common::pty::SharedPtyWriter,+ child: Box<dyn Child + Send + Sync>,+ output: String,+ chunks: mpsc::Receiver<Vec<u8>>,+ members: Vec<nix::unistd::Pid>,+}+impl Shell {+ fn start(repo: &TestRepo) -> Self {+ let mut command = CommandBuilder::new("bash");+ command.args(["--noprofile", "--norc", "-i"]);+ let mut shell = Self::spawn(repo, command);+ shell.wait_for("job-test> ");+ shell+ }+ fn spawn(repo: &TestRepo, mut command: CommandBuilder) -> Self {+ configure_pty_command(&mut command);+ command.cwd(repo.root_path());+ command.env("PS1", "job-test> ");+ command.env("TERM", "dumb");+ command.env("WT_JOB_TEST_BINARY", wt_bin());+ command.env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());+ let pair = open_pty();+ let child = pair.slave.spawn_command(command).unwrap();+ drop(pair.slave);+ let reader = pair.master.try_clone_reader().unwrap();+ let writer = Arc::new(Mutex::new(pair.master.take_writer().unwrap()));+ let chunks =+ crate::common::pty::spawn_pty_reader_answering_queries(reader, Arc::clone(&writer));+ Self {+ master: pair.master,+ writer,+ child,+ output: String::new(),+ chunks,+ members: Vec::new(),+ }+ }+ fn send(&mut self, text: &str) {+ self.output.clear();+ let mut writer = self.writer.lock().unwrap();+ writer.write_all(text.as_bytes()).unwrap();+ writer.flush().unwrap();+ }+ fn wait_for(&mut self, marker: &str) {+ let deadline = Instant::now() + Duration::from_secs(20);+ while !self.output.contains(marker) {+ let remaining = deadline.saturating_duration_since(Instant::now());+ let chunk = self.chunks.recv_timeout(remaining).unwrap_or_else(|_| {+ let members: Vec<_> = self+ .members+ .iter()+ .map(|pid| (*pid, nix::unistd::getpgid(Some(*pid))))+ .collect();+ panic!(+ "missing {marker:?}; shell={:?}, foreground={:?}, members={members:?}, termios={:?}; terminal output:\n{}",+ self.child.process_id(),+ self.master.process_group_leader(),+ self.master.get_termios(),+ self.output+ )+ });+ self.output.push_str(&String::from_utf8_lossy(&chunk));+ }+ }+ fn foreground(&self) -> i32 {+ self.master.process_group_leader().unwrap()+ }+ fn remember(&mut self, pid: i32) {+ let pid = nix::unistd::Pid::from_raw(pid);+ assert_eq!(+ nix::unistd::getsid(Some(pid)).unwrap().as_raw(),+ self.child.process_id().unwrap() as i32+ );+ self.members.push(pid);+ }+}+impl Drop for Shell {+ fn drop(&mut self) {+ // Shell never waits/reaps its leader before Drop. Its reserved PID+ // keeps the session identity valid even if the leader already exited.+ let session = self.child.process_id().unwrap() as i32;+ for member in &self.members {+ if nix::unistd::getsid(Some(*member)).is_ok_and(|owner| owner.as_raw() == session)+ && let Ok(group) = nix::unistd::getpgid(Some(*member))+ {+ let _ = nix::sys::signal::killpg(group, nix::sys::signal::Signal::SIGKILL);+ }+ }+ if let Some(group) = self.master.process_group_leader() {+ let group = nix::unistd::Pid::from_raw(group);+ if nix::unistd::getsid(Some(group)).is_ok_and(|owner| owner.as_raw() == session) {+ let _ = nix::sys::signal::killpg(group, nix::sys::signal::Signal::SIGKILL);+ }+ }+ let _ = nix::sys::signal::kill(+ nix::unistd::Pid::from_raw(session),+ nix::sys::signal::Signal::SIGKILL,+ );+ let _ = self.child.wait();+ }+}++fn native_pipeline(concurrent: bool) -> String {+ let first = if concurrent {+ "{ one = 'exec python3 worker.py', two = 'true' }"+ } else {+ "'exec python3 worker.py'"+ };+ format!("post-start = [{first}, 'printf NEXT > next']")+}++fn native_info(repo: &TestRepo, file: &str) -> Vec<i32> {+ let path = repo.root_path().join(file);+ crate::common::wait_for_file_content(&path);+ std::fs::read_to_string(path)+ .unwrap()+ .split_whitespace()+ .map(|n| n.parse().unwrap())+ .collect()+}++const WAITING_NATIVE_WORKER: &str = r#"import os, time+from pathlib import Path+Path('worker-info').write_text(f'{os.getpid()} {os.getpgrp()} {os.getppid()}')+while not Path('release').exists():+ time.sleep(.01)+"#;++/// An inherited ignored TERM must not become foreground cancellation.+#[rstest]+fn inherited_ignored_term_remains_ignored(repo: TestRepo) {+ use nix::sys::signal::{Signal, kill};+ use nix::unistd::Pid;++ repo.write_project_config(&native_pipeline(false));+ std::fs::write(+ repo.root_path().join("worker.py"),+ format!(+ "import signal\nsignal.signal(signal.SIGTERM, signal.SIG_DFL)\n{WAITING_NATIVE_WORKER}"+ ),+ )+ .unwrap();+ let mut shell = Shell::start(&repo);+ shell.send(&format!(+ "RUST_LOG={} python3 -c 'import os,signal,sys; signal.signal(signal.SIGTERM,signal.SIG_IGN); os.execv(sys.argv[1],sys.argv[1:])' \"$WT_JOB_TEST_BINARY\" -vv hook post-start --yes --foreground; printf 'RESULT_%s\\n' \"$?\"\n",+ crate::common::FOREGROUND_TRACE_FILTER+ ));+ let info = native_info(&repo, "worker-info");+ shell.remember(info[0]);+ shell.remember(info[2]);+ crate::common::wait_for_foreground_admission(&repo, &[info[0]]);+ kill(Pid::from_raw(info[2]), Signal::SIGTERM).unwrap();+ std::thread::sleep(crate::common::SLEEP_FOR_ABSENCE_CHECK);+ assert_eq!(shell.foreground(), info[1]);+ assert!(nix::unistd::getpgid(Some(Pid::from_raw(info[0]))).is_ok());+ assert!(!repo.root_path().join("next").exists());+ std::fs::write(repo.root_path().join("release"), "").unwrap();+ shell.wait_for("RESULT_0");+ assert!(repo.root_path().join("next").exists());+}++/// An explicit disabled pager ends precedence instead of selecting a lower+/// source or the interactive default. Exercise the actual TTY help entrypoint.+#[rstest]+#[case::git_cat("git", "cat")]+#[case::git_empty("git", "")]+#[case::core_cat("core", "cat")]+#[case::core_empty("core", "")]+#[case::pager_cat("pager", "cat")]+#[case::pager_empty("pager", "")]+fn explicit_disabled_pager_stops_selection(+ repo: TestRepo,+ #[case] source: &str,+ #[case] value: &str,+) {+ let lower = repo.root_path().join("lower-pager.sh");+ std::fs::write(&lower, "printf 'LOWER_PAGER_USED\\n'\ncat > /dev/null\n").unwrap();+ let lower = format!("sh {}", shell_escape::unix::escape(lower.to_string_lossy()));+ if source != "pager" {+ repo.run_git(&[+ "config",+ "core.pager",+ if source == "core" { value } else { &lower },+ ]);+ }+ let assignments = match source {+ "git" => format!(+ "GIT_PAGER={} PAGER={}",+ shell_escape::unix::escape(value.into()),+ shell_escape::unix::escape(lower.into())+ ),+ "core" => format!("PAGER={}", shell_escape::unix::escape(lower.into())),+ "pager" => format!("PAGER={}", shell_escape::unix::escape(value.into())),+ _ => unreachable!(),+ };+ let mut shell = Shell::start(&repo);+ shell.send(&format!(+ "unset GIT_PAGER PAGER; {assignments} \"$WT_JOB_TEST_BINARY\" --help\n"+ ));+ shell.wait_for("job-test> ");+ assert!(shell.output.contains("Usage:"), "{}", shell.output);+ assert!(+ !shell.output.contains("LOWER_PAGER_USED"),+ "{}",+ shell.output+ );+}++/// Global Git pager configuration applies even when help runs outside a repo.+#[rstest]+#[case::cat(Some("cat"))]+#[case::empty(Some(""))]+#[case::command(None)]+fn help_pager_uses_global_config_outside_repository(+ repo: TestRepo,+ #[case] disabled: Option<&str>,+) {+ let outside = repo.home_path().join("outside");+ std::fs::create_dir(&outside).unwrap();+ let lower = repo.root_path().join("lower-pager.sh");+ let global = repo.root_path().join("global-pager.sh");+ std::fs::write(&lower, "printf 'LOWER_PAGER_USED\\n'\ncat > /dev/null\n").unwrap();+ std::fs::write(&global, "printf 'GLOBAL_PAGER_USED\\n'\ncat > /dev/null\n").unwrap();+ let quote =+ |path: &std::path::Path| shell_escape::unix::escape(path.to_string_lossy()).into_owned();+ let global_command = format!("sh {}", quote(&global));+ let config = repo.home_path().join("pager.gitconfig");+ repo.run_git(&[+ "config",+ "--file",+ config.to_str().unwrap(),+ "core.pager",+ disabled.unwrap_or(&global_command),+ ]);+ let mut shell = Shell::start(&repo);+ shell.send(&format!(+ "cd {}; unset GIT_PAGER PAGER; GIT_CONFIG_GLOBAL={} PAGER={} \"$WT_JOB_TEST_BINARY\" --help\n",+ quote(&outside), quote(&config), shell_escape::unix::escape(format!("sh {}", quote(&lower)).into()),+ ));+ shell.wait_for("job-test> ");+ assert_eq!(+ shell.output.contains("Usage:"),+ disabled.is_some(),+ "{}",+ shell.output+ );+ assert_eq!(+ shell.output.contains("GLOBAL_PAGER_USED"),+ disabled.is_none(),+ "{}",+ shell.output+ );+ assert!(+ !shell.output.contains("LOWER_PAGER_USED"),+ "{}",+ shell.output+ );+}++/// Paging is optional: unavailable Git or malformed configuration must leave+/// help readable, without selecting an unverified lower-priority command.+#[rstest]+#[case::missing_git(true)]+#[case::invalid_config(false)]+fn help_remains_available_when_pager_lookup_fails(repo: TestRepo, #[case] missing_git: bool) {+ let config = repo.home_path().join("invalid.gitconfig");+ std::fs::write(&config, "[invalid\n").unwrap();+ let lower = repo.root_path().join("lower-pager.sh");+ std::fs::write(&lower, "printf 'LOWER_PAGER_USED\\n'\ncat > /dev/null\n").unwrap();+ let environment = if missing_git {+ "PATH=/worktrunk-test-no-programs".to_string()+ } else {+ format!(+ "GIT_CONFIG_GLOBAL={}",+ shell_escape::unix::escape(config.to_string_lossy())+ )+ };+ let mut shell = Shell::start(&repo);+ shell.send(&format!(+ "unset GIT_PAGER PAGER; {environment} PAGER={} \"$WT_JOB_TEST_BINARY\" --help\n",+ shell_escape::unix::escape(+ format!("sh {}", shell_escape::unix::escape(lower.to_string_lossy())).into()+ ),+ ));+ shell.wait_for("job-test> ");+ assert!(shell.output.contains("Usage:"), "{}", shell.output);+ assert!(+ !shell.output.contains("LOWER_PAGER_USED"),+ "{}",+ shell.output+ );+}++/// From outside the target repository, `-C` selects its local pager over global.+#[rstest]+fn help_pager_honors_c_base_path(repo: TestRepo) {+ let local = repo.root_path().join("local-pager.sh");+ let global = repo.root_path().join("global-pager.sh");+ std::fs::write(&local, "printf 'LOCAL_PAGER_USED\\n'\ncat > /dev/null\n").unwrap();+ std::fs::write(&global, "printf 'GLOBAL_PAGER_USED\\n'\ncat > /dev/null\n").unwrap();+ let quote =+ |path: &std::path::Path| shell_escape::unix::escape(path.to_string_lossy()).into_owned();+ let config = repo.home_path().join("pager.gitconfig");+ repo.run_git(&[+ "config",+ "--file",+ config.to_str().unwrap(),+ "core.pager",+ &format!("sh {}", quote(&global)),+ ]);+ repo.run_git(&["config", "core.pager", &format!("sh {}", quote(&local))]);+ let mut shell = Shell::start(&repo);+ shell.send(&format!(+ "cd {}; unset GIT_PAGER PAGER; GIT_CONFIG_GLOBAL={} \"$WT_JOB_TEST_BINARY\" -C {} --help\n",+ quote(repo.home_path()),+ quote(&config),+ quote(repo.root_path()),+ ));+ shell.wait_for("job-test> ");+ assert!(+ shell.output.contains("LOCAL_PAGER_USED"),+ "{}",+ shell.output+ );+ assert!(+ !shell.output.contains("GLOBAL_PAGER_USED"),+ "{}",+ shell.output+ );+}++/// Lossy decoding could turn an invalid command into executable shell text.+#[rstest]+fn invalid_utf8_pager_is_not_executed(repo: TestRepo) {+ let config = repo.home_path().join("pager.gitconfig");+ std::fs::write(+ &config,+ b"[core]\n\tpager = \"printf INVALID_PAGER_EXECUTED; cat # \xff\"\n",+ )+ .unwrap();+ let mut shell = Shell::start(&repo);+ shell.send(&format!(+ "unset GIT_PAGER PAGER; GIT_CONFIG_GLOBAL={} \"$WT_JOB_TEST_BINARY\" --help\n",+ shell_escape::unix::escape(config.to_string_lossy()),+ ));+ shell.wait_for("job-test> ");+ assert!(shell.output.contains("Usage:"), "{}", shell.output);+ assert!(+ !shell.output.contains("INVALID_PAGER_EXECUTED"),+ "{}",+ shell.output+ );+}++/// Custom commands and help pagers keep the native execution lease until the+/// child finishes. A caught key remains input; targeted TERM cancels wt.+#[rstest]+#[case::custom_caught_success(false, "caught-key", 0, 0)]+#[case::custom_caught_130(false, "caught-key", 130, 130)]+#[case::custom_raw_int(false, "raw-key", 0, 130)]+#[case::custom_caught_term(false, "caught-term", 0, 143)]+#[case::pager_caught_success(true, "caught-key", 0, 0)]+#[case::pager_caught_130(true, "caught-key", 130, 0)]+#[case::pager_raw_int(true, "raw-key", 0, 130)]+#[case::pager_raw_term(true, "raw-term", 0, 143)]+#[case::help_raw_term(true, "help-term", 0, 143)]+#[case::pager_caught_term(true, "caught-term", 0, 143)]+fn custom_commands_and_help_pagers_preserve_native_signals(+ repo: TestRepo,+ #[case] pager: bool,+ #[case] mode: &str,+ #[case] child_exit: i32,+ #[case] expected: i32,+) {+ use nix::sys::signal::{Signal, kill};+ use nix::unistd::{Pid, getpgid};+ use std::os::unix::fs::PermissionsExt;++ let bin = repo.home_path().join("native-bin");+ std::fs::create_dir(&bin).unwrap();+ let worker = bin.join("wt-nativecancel");+ std::fs::write(+ &worker,+ format!(+ r#"#!{}+import os, signal, sys, time+from pathlib import Path+pager, mode, code = sys.argv[1], sys.argv[2], int(sys.argv[3])+def caught(*_):+ Path('ack').write_text('caught')+ if mode == 'caught-term':+ sys.exit(0)+signal.signal(signal.SIGINT, caught if mode == 'caught-key' else signal.SIG_DFL)+signal.signal(signal.SIGTERM, caught if mode == 'caught-term' else signal.SIG_DFL)+if pager == 'pager':+ sys.stdin.buffer.read()+Path('worker-info').write_text(f'{{os.getpid()}} {{os.getpgrp()}} {{os.getppid()}}')+while not Path('release').exists():+ time.sleep(.01)+sys.exit(code)+"#,+ which::which("python3").unwrap().display()+ ),+ )+ .unwrap();+ std::fs::set_permissions(&worker, std::fs::Permissions::from_mode(0o755)).unwrap();+ let quote =+ |path: &std::path::Path| shell_escape::unix::escape(path.to_string_lossy()).into_owned();+ let command = if pager {+ format!(+ "GIT_PAGER={} \"$WT_JOB_TEST_BINARY\" {}",+ shell_escape::unix::escape(+ format!("exec {} pager {mode} {child_exit}", quote(&worker)).into()+ ),+ if mode == "help-term" {+ "--help"+ } else {+ "-vv config show"+ }+ )+ } else {+ format!(+ "PATH={}:$PATH \"$WT_JOB_TEST_BINARY\" -vv nativecancel custom {mode} {child_exit}",+ quote(&bin)+ )+ };+ let mut shell = Shell::start(&repo);+ shell.send(&format!(+ "RUST_LOG={} {command}\n",+ crate::common::FOREGROUND_TRACE_FILTER+ ));+ let info = native_info(&repo, "worker-info");+ shell.remember(info[0]);+ shell.remember(info[2]);+ assert_eq!(info[1], shell.foreground());+ assert_eq!(+ getpgid(Some(Pid::from_raw(info[2]))).unwrap().as_raw(),+ info[1]+ );+ if mode.ends_with("key") {+ crate::common::wait_for_foreground_admission(&repo, &[info[0]]);+ shell.send("\x03");+ } else {+ let target = if matches!(mode, "raw-term" | "help-term") {+ info[0]+ } else {+ info[2]+ };+ kill(Pid::from_raw(target), Signal::SIGTERM).unwrap();+ }+ if mode == "caught-term" {+ // Controller status alone could hide an unforwarded TERM and a live+ // orphan. Establish that the child actually handled the forwarded signal.+ crate::common::wait_for_file_content(&repo.root_path().join("ack"));+ }+ if mode == "caught-key" {+ crate::common::wait_for_file_content(&repo.root_path().join("ack"));+ assert_eq!(+ shell.foreground(),+ info[1],+ "wt must await the caught key's cleanup"+ );+ assert_eq!(+ getpgid(Some(Pid::from_raw(info[2]))).unwrap().as_raw(),+ info[1]+ );+ std::fs::write(repo.root_path().join("release"), "").unwrap();+ }+ shell.wait_for("job-test> ");+ if pager {+ // Verbose trace records retain the physical child status. A separate+ // user-facing failure for cancellation would be misleading.+ assert!(+ !shell.output.contains("✗ terminated by signal")+ && !shell.output.contains("✗ exit status:"),+ "{}",+ shell.output+ );+ assert!(+ !shell.output.contains("Usage:"),+ "help must not bypass its pager: {}",+ shell.output+ );+ }+ // Bash aborts a compound command after a child's raw SIGINT. Read its+ // native status from fresh input after the completed foreground job.+ shell.send("printf 'RESULT_%s\\n' \"$?\"\n");+ shell.wait_for(&format!("RESULT_{expected}"));+}++#[rstest]+#[case::single(false, false)]+#[case::concurrent(true, false)]+#[case::single_pipeline(false, true)]+#[case::concurrent_pipeline(true, true)]+fn children_inherit_foreground_group_and_pipeline_terminal(+ repo: TestRepo,+ #[case] concurrent: bool,+ #[case] pipeline: bool,+) {+ repo.write_project_config(&native_pipeline(concurrent));+ std::fs::write(repo.root_path().join("worker.py"), WAITING_NATIVE_WORKER).unwrap();+ std::fs::write(+ repo.root_path().join("sibling.py"),+ r#"import os, subprocess, sys, time+from pathlib import Path+Path('sibling-info').write_text(f'{os.getpid()} {os.getpgrp()}')+while not Path('worker-info').exists():+ time.sleep(.01)+with open('/dev/tty', 'rb') as tty:+ subprocess.run(['stty', '-ixon'], stdin=tty, check=True)+Path('tty-access').write_text('success')+for line in sys.stdin:+ pass+"#,+ )+ .unwrap();+ let mut shell = Shell::start(&repo);+ shell.send(if pipeline {+ "\"$WT_JOB_TEST_BINARY\" hook post-start --yes --foreground | python3 sibling.py; printf 'RESULT_%s\\n' \"$?\"\n"+ } else {+ "\"$WT_JOB_TEST_BINARY\" hook post-start --yes --foreground; printf 'RESULT_%s\\n' \"$?\"\n"+ });+ let info = native_info(&repo, "worker-info");+ shell.remember(info[0]);+ shell.remember(info[2]);+ let group = nix::unistd::Pid::from_raw(info[1]);+ assert_eq!(shell.foreground(), group.as_raw());+ assert_eq!(+ nix::unistd::getpgid(Some(nix::unistd::Pid::from_raw(info[2]))).unwrap(),+ group,+ "wt and its worker must remain in the same native group"+ );+ if pipeline {+ let sibling = native_info(&repo, "sibling-info");+ shell.remember(sibling[0]);+ assert_eq!(sibling[1], group.as_raw());+ crate::common::wait_for_file_content(&repo.root_path().join("tty-access"));+ }+ std::fs::write(repo.root_path().join("release"), "release").unwrap();+ shell.wait_for("RESULT_0");+ assert_eq!(+ std::fs::read_to_string(repo.root_path().join("next")).unwrap(),+ "NEXT"+ );+}++#[rstest]+#[case::single_one(false, 1)]+#[case::single_two(false, 2)]+#[case::concurrent_one(true, 1)]+#[case::concurrent_two(true, 2)]+fn caught_keyboard_interrupt_preserves_success_and_following_step(+ repo: TestRepo,+ #[case] concurrent: bool,+ #[case] keys: usize,+) {+ repo.write_project_config(if concurrent {+ "post-start = [{ one = 'exec python3 worker.py', two = 'exec python3 companion.py' }, 'printf NEXT > next']"+ } else {+ "post-start = ['exec python3 worker.py', 'printf NEXT > next']"+ });+ std::fs::write(+ repo.root_path().join("companion.py"),+ format!(+ r#"import os, signal, time+from pathlib import Path+signal.signal(signal.SIGINT, signal.SIG_IGN)+Path('companion-info').write_text(f'{{os.getpid()}} {{os.getpgrp()}}')+while not Path('count').exists() or Path('count').read_text() != '{keys}':+ time.sleep(.01)+"#+ ),+ )+ .unwrap();+ std::fs::write(+ repo.root_path().join("worker.py"),+ format!(+ r#"import os, signal, time+from pathlib import Path+count = 0+def interrupted(*_):+ global count+ count += 1+ Path('count').write_text(str(count))+signal.signal(signal.SIGINT, interrupted)+Path('worker-info').write_text(f'{{os.getpid()}} {{os.getpgrp()}}')+while count < {keys}:+ time.sleep(.01)+"#+ ),+ )+ .unwrap();+ let mut shell = Shell::start(&repo);+ shell.send(&format!(+ "RUST_LOG={} \"$WT_JOB_TEST_BINARY\" -vv hook post-start --yes --foreground; printf 'RESULT_%s\\n' \"$?\"\n",+ crate::common::FOREGROUND_TRACE_FILTER+ ));+ let info = native_info(&repo, "worker-info");+ shell.remember(info[0]);+ assert_eq!(info[1], shell.foreground());+ if concurrent {+ let companion = native_info(&repo, "companion-info");+ shell.remember(companion[0]);+ assert_eq!(companion[1], info[1]);+ crate::common::wait_for_foreground_admission(&repo, &[companion[0]]);+ }+ crate::common::wait_for_foreground_admission(&repo, &[info[0]]);+ for key in 1..=keys {+ shell.send("\x03");+ let expected = key.to_string();+ let deadline = Instant::now() + Duration::from_secs(20);+ while std::fs::read_to_string(repo.root_path().join("count"))+ .ok()+ .as_deref()+ != Some(expected.as_str())+ {+ assert!(Instant::now() < deadline, "child did not handle key {key}");+ std::thread::sleep(Duration::from_millis(10));+ }+ }+ shell.wait_for("RESULT_0");+ assert_eq!(+ std::fs::read_to_string(repo.root_path().join("count")).unwrap(),+ keys.to_string()+ );+ assert!(repo.root_path().join("next").exists());+}++#[rstest]+fn startup_interrupt_preserves_already_started_child_cleanup(repo: TestRepo) {+ let mut commands = vec![+ "a000 = 'exec python3 worker.py'".to_string(),+ "a001 = 'while [ ! -f worker-info ]; do :; done; kill -STOP \"$PPID\"; printf ready > paused-admitted; while :; do :; done'".to_string(),+ ];+ commands.extend((2..120).map(|index| {+ format!("a{index:03} = 'printf ready > admitted-{index:03}; while :; do :; done'")+ }));+ repo.write_project_config(&format!(+ "post-start = [{{ {} }}, 'printf NEXT > next']",+ commands.join(", ")+ ));+ std::fs::write(+ repo.root_path().join("worker.py"),+ r#"import os, signal, time+from pathlib import Path+interrupted = False+def on_int(*_):+ global interrupted+ interrupted = True+ Path('ack').write_text('handled')+signal.signal(signal.SIGINT, on_int)+Path('worker-info').write_text(f'{os.getpid()} {os.getpgrp()} {os.getppid()}')+while not interrupted:+ time.sleep(.01)+print('CLEANUP_ENTERED', flush=True)+while not Path('release-cleanup').exists():+ time.sleep(.01)+Path('cleanup').write_text('finished')+print('CLEANUP_FINISHED', flush=True)+"#,+ )+ .unwrap();+ // A waiting caller keeps the job foreground while only wt is stopped;+ // an interactive shell would take the terminal back on its child's stop.+ let mut command = CommandBuilder::new("python3");+ command.args(["-c", r#"import os, signal, subprocess+for number in [signal.SIGINT, signal.SIGTERM]:+ signal.signal(number, lambda *_: None)+owner = subprocess.Popen([os.environ['WT_JOB_TEST_BINARY'], 'hook', 'post-start', '--yes', '--foreground'])+code = owner.wait()+print('RESULT_' + str(128 - code if code < 0 else code), flush=True)+input()+"#]);+ let mut shell = Shell::spawn(&repo, command);+ let info = native_info(&repo, "worker-info");+ shell.remember(info[0]);+ shell.remember(info[2]);+ assert_eq!(info[1], shell.foreground());++ // Starting the second command proves that the first was admitted before+ // only the controller stops. Establish that startup boundary before the key.+ crate::common::wait_for_file_content(&repo.root_path().join("paused-admitted"));+ let owner = info[2].to_string();+ let state = std::process::Command::new("ps")+ .args(["-o", "stat=", "-p", &owner])+ .output()+ .unwrap();+ assert!(state.status.success());+ assert!(+ String::from_utf8_lossy(&state.stdout)+ .trim()+ .starts_with('T')+ );+ let processes = std::process::Command::new("ps")+ .args(["-Ao", "pid=,ppid="])+ .output()+ .unwrap();+ assert!(processes.status.success());+ let started = String::from_utf8_lossy(&processes.stdout)+ .lines()+ .filter(|line| {+ line.split_whitespace()+ .nth(1)+ .is_some_and(|parent| parent == owner)+ })+ .count();+ assert!(+ (2..120).contains(&started),+ "startup already completed: {started}"+ );++ shell.send("\x03");+ crate::common::wait_for_file_content(&repo.root_path().join("ack"));+ nix::sys::signal::kill(+ nix::unistd::Pid::from_raw(info[2]),+ nix::sys::signal::Signal::SIGCONT,+ )+ .unwrap();+ // This line can reach the terminal only through wt's output drain. Keep+ // cleanup blocked until that proves startup cancellation is waiting for it.+ shell.wait_for("CLEANUP_ENTERED");+ std::fs::write(repo.root_path().join("release-cleanup"), "release").unwrap();+ shell.wait_for("RESULT_130");+ assert_eq!(+ std::fs::read_to_string(repo.root_path().join("cleanup")).unwrap(),+ "finished"+ );+ assert!(shell.output.contains("CLEANUP_FINISHED"));+ assert!(!repo.root_path().join("next").exists());+}++#[rstest]+fn keyboard_suspend_and_shell_fg_resume_the_native_job(repo: TestRepo) {+ repo.write_project_config(&native_pipeline(true));+ std::fs::write(repo.root_path().join("worker.py"), WAITING_NATIVE_WORKER).unwrap();+ let mut shell = Shell::start(&repo);+ let caller = shell.foreground();+ shell.send("\"$WT_JOB_TEST_BINARY\" hook post-start --yes --foreground\n");+ let info = native_info(&repo, "worker-info");+ shell.remember(info[0]);+ shell.remember(info[2]);+ shell.send("\x1a");+ shell.wait_for("job-test> ");+ assert_eq!(shell.foreground(), caller);+ let deadline = Instant::now() + Duration::from_secs(20);+ loop {+ let stopped = std::process::Command::new("ps")+ .args(["-o", "stat=", "-p", &info[0].to_string()])+ .output()+ .unwrap();+ assert!(stopped.status.success());+ if String::from_utf8_lossy(&stopped.stdout)+ .trim()+ .starts_with('T')+ {+ break;+ }+ assert!(Instant::now() < deadline, "worker did not stop");+ std::thread::sleep(Duration::from_millis(10));+ }+ shell.send("fg; printf 'RESUMED_%s\\n' \"$?\"\n");+ let deadline = Instant::now() + Duration::from_secs(20);+ while shell.foreground() != info[1] {+ assert!(+ Instant::now() < deadline,+ "shell did not foreground the job"+ );+ std::thread::sleep(Duration::from_millis(10));+ }+ std::fs::write(repo.root_path().join("release"), "release").unwrap();+ shell.wait_for("RESUMED_0");+ assert!(repo.root_path().join("next").exists());+}++#[rstest]+fn cancelled_concurrent_drain_preserves_final_partial_diagnostic(repo: TestRepo) {+ repo.write_project_config(&native_pipeline(true));+ std::fs::write(+ repo.root_path().join("worker.py"),+ r#"import os, signal, subprocess, time+from pathlib import Path+descendant = subprocess.Popen(['sleep', '60'])+def terminated(*_):+ os.write(2, b'FINAL_PARTIAL_DIAGNOSTIC')+ signal.signal(signal.SIGTERM, signal.SIG_DFL)+ os.kill(os.getpid(), signal.SIGTERM)+signal.signal(signal.SIGTERM, terminated)+Path('worker-info').write_text(f'{os.getpid()} {os.getpgrp()} {descendant.pid}')+while True:+ time.sleep(60)+"#,+ )+ .unwrap();+ let mut command = CommandBuilder::new("python3");+ command.args(["-c", r#"import os, signal, subprocess+from pathlib import Path+for number in [signal.SIGINT, signal.SIGTERM]:+ signal.signal(number, lambda *_: None)+owner = subprocess.Popen([os.environ['WT_JOB_TEST_BINARY'], 'hook', 'post-start', '--yes', '--foreground'])+Path('owner').write_text(str(owner.pid))+code = owner.wait()+print('RESULT_' + str(128 - code if code < 0 else code), flush=True)+input()+"#]);+ let mut shell = Shell::spawn(&repo, command);+ let info = native_info(&repo, "worker-info");+ let owner = native_info(&repo, "owner")[0];+ shell.remember(info[0]);+ shell.remember(info[2]);+ shell.remember(owner);+ let session = shell.child.process_id().unwrap() as i32;+ assert_eq!(info[1], session);+ assert_eq!(shell.foreground(), session);+ nix::sys::signal::kill(+ nix::unistd::Pid::from_raw(owner),+ nix::sys::signal::Signal::SIGTERM,+ )+ .unwrap();+ shell.wait_for("RESULT_143");+ assert!(shell.output.contains("FINAL_PARTIAL_DIAGNOSTIC"));+ assert!(!repo.root_path().join("next").exists());+ // The successful waiting caller still pins this foreground group. Dropping+ // Shell kills only that owned session group, including the pipe holder.+}++#[rstest]+fn interrupt_cancels_completed_drain_while_another_prune_hook_is_active(mut repo: TestRepo) {+ std::fs::write(+ repo.root_path().join("prune-worker.py"),+ r#"import os, signal, sys, time+from pathlib import Path+base = Path(__file__).resolve().parent+if sys.argv[1] == 'draining':+ direct = os.getpid()+ if os.fork():+ while not (base / 'draining-info').exists():+ time.sleep(.01)+ os._exit(0)+ signal.signal(signal.SIGINT, signal.SIG_IGN)+ signal.signal(signal.SIGTERM, signal.SIG_IGN)+ (base / 'draining-info').write_text(f'{os.getpid()} {os.getpgrp()} {direct}')+else:+ signal.signal(signal.SIGINT, signal.SIG_DFL)+ (base / 'active-info').write_text(f'{os.getpid()} {os.getpgrp()}')+while True:+ time.sleep(60)+"#,+ )+ .unwrap();+ let worker = format!(+ "exec python3 {} {{{{ branch }}}}",+ shell_escape::unix::escape(repo.root_path().join("prune-worker.py").to_string_lossy())+ );+ repo.write_project_config(&format!(+ "pre-remove = {{ one = {}, two = 'true' }}",+ serde_json::to_string(&worker).unwrap()+ ));+ repo.commit("Add overlapping prune hooks");+ repo.add_worktree("draining");+ repo.add_worktree("active");++ let mut command = CommandBuilder::new("python3");+ command.args(["-c", r#"import os, signal, subprocess+from pathlib import Path+for number in [signal.SIGINT, signal.SIGTERM]:+ signal.signal(number, lambda *_: None)+owner = subprocess.Popen([os.environ['WT_JOB_TEST_BINARY'], 'step', 'prune', '--yes', '--min-age=0s'], env=dict(os.environ, RAYON_NUM_THREADS='2'))+Path('owner').write_text(str(owner.pid))+code = owner.wait()+print('RESULT_' + str(128 - code if code < 0 else code), flush=True)+input()+"#]);+ let mut shell = Shell::spawn(&repo, command);+ let draining = native_info(&repo, "draining-info");+ let active = native_info(&repo, "active-info");+ let owner = native_info(&repo, "owner")[0];+ shell.remember(draining[0]);+ shell.remember(active[0]);+ shell.remember(owner);+ assert_eq!(draining[1], shell.foreground());+ assert_eq!(active[1], draining[1]);++ // A's direct command has completed, but its ignored-INT descendant still+ // holds the pipes. B keeps the process-wide foreground signal observer live.+ let deadline = Instant::now() + Duration::from_secs(20);+ loop {+ match nix::unistd::getpgid(Some(nix::unistd::Pid::from_raw(draining[2]))) {+ Err(nix::errno::Errno::ESRCH) => break,+ Ok(_) => {}+ result => panic!("querying completed command: {result:?}"),+ }+ assert!(Instant::now() < deadline, "direct command did not finish");+ std::thread::sleep(Duration::from_millis(10));+ }+ shell.send("\x03");+ shell.wait_for("RESULT_130");+ // The waiting caller pins the owned session until Shell's Drop cleans up+ // the descendant. Completion must not depend on releasing its output pipes.+}++/// A best-effort timed capture can consume its own child's TERM failure.+/// It must not turn an independent healthy foreground stream into cancellation.+#[cfg(unix)]+#[test]+fn captured_child_signal_does_not_cancel_foreground_stream() {+ use std::os::unix::process::ExitStatusExt;+ use std::time::{Duration, Instant};+ use worktrunk::shell_exec::Cmd;++ let dir = tempfile::tempdir().unwrap();+ let ready = dir.path().join("ready");+ let release = dir.path().join("release");+ let body = format!(+ "printf ready > {}; while [ ! -f {} ]; do :; done",+ shell_escape::escape(ready.to_string_lossy()),+ shell_escape::escape(release.to_string_lossy()),+ );++ // Release before thread::scope joins, including assertion unwinding.+ struct ReleaseOnDrop(std::path::PathBuf);+ impl Drop for ReleaseOnDrop {+ fn drop(&mut self) {+ let _ = std::fs::write(&self.0, "release");+ }+ }++ std::thread::scope(|scope| {+ let worker = scope.spawn(|| {+ Cmd::new("sh")+ .args(["-c", &body])+ .forward_signals()+ .stream()+ });+ let release_guard = ReleaseOnDrop(release);+ let deadline = Instant::now() + Duration::from_secs(10);+ while !ready.exists() && Instant::now() < deadline {+ std::thread::sleep(Duration::from_millis(5));+ }+ assert!(ready.exists(), "foreground child did not become ready");++ let captured = Cmd::new("sh")+ .args(["-c", "kill -TERM $$"])+ .timeout(Duration::from_secs(1))+ .run()+ .unwrap();+ assert_eq!(captured.status.signal(), Some(15));+ std::fs::write(&release_guard.0, "release").unwrap();+ worker+ .join()+ .unwrap()+ .expect("a consumed capture failure cancelled a healthy foreground stream");+ });++ Cmd::new("true")+ .forward_signals()+ .stream()+ .expect("interruption leaked into the subsequent foreground operation");+}++/// Deadlines and native interruption cover output EOF, including descendants.+#[test]+fn captured_deadline_and_delayed_interrupt_bound_descendant_output() {+ use worktrunk::git::ErrorExt;+ use worktrunk::shell_exec::Cmd;++ // Capture deadline, fully buffered interruption, and a quiet pre-threshold exit.+ for delay in [None, Some(-1), Some(30_000)] {+ let dir = tempfile::tempdir().unwrap();+ let release = dir.path().join("release");+ let finished = dir.path().join("finished");+ let body = format!(+ "(finish() {{ printf finished > {}; }}; trap 'finish; exit 0' TERM; while [ ! -f {} ]; do sleep .01; done; finish) & printf prior; {}",+ shell_escape::escape(finished.to_string_lossy()),+ shell_escape::escape(release.to_string_lossy()),+ if delay.is_none() {+ "exit 0"+ } else {+ "kill -TERM $$"+ },+ );+ // A safety watchdog releases the pipe holder if the wait regresses.+ let (release_tx, release_rx) = mpsc::channel();+ std::thread::scope(|scope| {+ let watchdog = scope.spawn(move || {+ let fallback = release_rx.recv_timeout(Duration::from_secs(10)).is_err();+ std::fs::write(&release, "release").unwrap();+ let deadline = Instant::now() + Duration::from_secs(10);+ while !finished.exists() && Instant::now() < deadline {+ std::thread::sleep(Duration::from_millis(5));+ }+ assert!(finished.exists(), "descendant did not finish after release");+ fallback+ });+ if let Some(delay) = delay {+ let error = Cmd::new("sh")+ .args(["-c", &body])+ .delayed_stream(delay, None)+ .unwrap_err();+ assert_eq!(error.interrupt_signal(), Some(15));+ let failure = error+ .downcast_ref::<worktrunk::shell_exec::StreamCommandError>()+ .unwrap();+ assert_eq!(failure.output, "prior");+ } else {+ let error = Cmd::new("sh")+ .args(["-c", &body])+ .timeout(Duration::from_millis(200))+ .run()+ .expect_err("a retained output pipe must respect the capture deadline");+ assert_eq!(error.kind(), std::io::ErrorKind::TimedOut);+ }+ release_tx.send(()).unwrap();+ assert!(+ !watchdog.join().unwrap(),+ "output wait required watchdog release"+ );+ });+ }+}++fn wrapper_prompt(shell: &mut Shell, marker: &str) {+ shell.wait_for(marker);+ // The setup line itself names the prompt, and a preceding command may+ // leave its prompt queued. Consume the prompt after this actual marker.+ let end = shell.output.rfind(marker).unwrap() + marker.len();+ shell.output.drain(..end);+ shell.wait_for("wrapper-prompt> ");+}++// Record the producer's actual path: BSD mktemp need not use TMPDIR.+fn recording_wrapper_binary(repo: &TestRepo, binary: &std::path::Path) -> std::path::PathBuf {+ use std::os::unix::fs::PermissionsExt;+ let quote = |path: &std::path::Path| {+ shell_escape::escape(path.to_string_lossy().into_owned().into()).into_owned()+ };+ let launcher = repo.root_path().join("wrapper-recording-binary");+ std::fs::write(+ &launcher,+ format!(+ "#!/bin/sh\nprintf '%s\\n' \"$WORKTRUNK_DIRECTIVE_CD_FILE\" >> {}\nexec {} \"$@\"\n",+ quote(&repo.root_path().join("wrapper-directive-files")),+ quote(binary)+ ),+ )+ .unwrap();+ std::fs::set_permissions(&launcher, std::fs::Permissions::from_mode(0o755)).unwrap();+ launcher+}++fn assert_wrapper_directives_removed(repo: &TestRepo) {+ let paths = std::fs::read_to_string(repo.root_path().join("wrapper-directive-files")).unwrap();+ assert!(!paths.is_empty(), "the wrapper never ran its binary");+ for path in paths.lines() {+ assert!(+ !std::path::Path::new(path).exists(),+ "directive file leaked: {path}"+ );+ }+}++fn wrapper_shell(repo: &TestRepo, name: &str, binary: &std::path::Path) -> Shell {+ let dialect = if name == "/bin/bash" { "bash" } else { name };+ let temporary = repo.root_path().join("wrapper-temporary");+ std::fs::create_dir(&temporary).unwrap();+ let wrapper = std::process::Command::new(wt_bin())+ .args(["config", "shell", "init", dialect])+ .env("WORKTRUNK_CONFIG_PATH", repo.test_config_path())+ .current_dir(repo.root_path())+ .output()+ .unwrap();+ assert!(wrapper.status.success());+ std::fs::write(repo.root_path().join("wrapper-init"), wrapper.stdout).unwrap();+ let mut command = CommandBuilder::new(crate::common::shell::shell_binary(name));+ match dialect {+ "bash" => command.args(["--noprofile", "--norc", "-i"]),+ "zsh" => command.args(["-f", "-i"]),+ "fish" => command.args(["--no-config", "-i"]),+ _ => unreachable!(),+ }+ let mut shell = Shell::spawn(repo, command);+ let temporary = shell_escape::escape(temporary.to_string_lossy().into_owned().into());+ let binary = recording_wrapper_binary(repo, binary);+ let binary = shell_escape::escape(binary.to_string_lossy().into_owned().into());+ let target = shell_escape::escape(repo.root_path().to_string_lossy().into_owned().into());+ let setup = if name == "fish" {+ format!(+ "function fish_prompt; printf 'wrapper-prompt> '; end; set -gx WORKTRUNK_BIN {binary}; set -gx WT_WRAPPER_TEST_TARGET {target}; set -gx TMPDIR {temporary}; source wrapper-init"+ )+ } else {+ format!(+ "export WORKTRUNK_BIN={binary} WT_WRAPPER_TEST_TARGET={target} TMPDIR={temporary}; source wrapper-init; PS1='wrapper-prompt> '"+ )+ };+ shell.send(&format!("{setup}; printf 'WRAPPER_%s\\n' READY\n"));+ wrapper_prompt(&mut shell, "WRAPPER_READY");+ shell+}++/// Nushell must apply the directive and release its temp files even when a+/// real terminal Ctrl-C unwinds a noninteractive script.+#[rstest]+#[case(false, false)]+#[case(false, true)]+#[case(true, false)]+#[case(true, true)]+fn nushell_interrupt_runs_wrapper_cleanup(+ mut repo: TestRepo,+ #[case] interactive: bool,+ #[case] caught: bool,+) {+ let feature = repo.add_worktree("feature");+ let temporary = repo.root_path().join("wrapper-temporary");+ std::fs::create_dir(&temporary).unwrap();+ let wrapper = repo+ .wt_command()+ .args(["config", "shell", "init", "nu"])+ .output()+ .unwrap();+ assert!(wrapper.status.success());+ std::fs::write(repo.root_path().join("wrapper-init"), wrapper.stdout).unwrap();+ std::fs::write(+ repo.root_path().join("worker.py"),+ format!("import signal, sys\nsignal.signal(signal.SIGINT, {})\nsignal.pthread_sigmask(signal.SIG_UNBLOCK, {{signal.SIGINT}})\n{WAITING_NATIVE_WORKER}", if caught { "lambda *_: sys.exit(0)" } else { "signal.SIG_DFL" }),+ )+ .unwrap();+ let quote = |path: &std::path::Path| serde_json::to_string(&path.to_string_lossy()).unwrap();+ let binary = recording_wrapper_binary(&repo, &wt_bin());+ let script = format!(+ "$env.WORKTRUNK_BIN = {}; $env.TMPDIR = {}; $env.RUST_LOG = '{}'; source wrapper-init; cd {}; try {{ wt -vv switch main --yes --execute python3 -- {} }} finally {{ $env.PWD | save {} }}",+ quote(&binary),+ quote(&temporary),+ crate::common::FOREGROUND_TRACE_FILTER,+ quote(&feature),+ quote(&repo.root_path().join("worker.py")),+ quote(&repo.root_path().join("wrapper-cwd")),+ );+ let mut command = CommandBuilder::new("nu");+ command.arg("--no-config-file");+ if interactive {+ command.arg("-i");+ } else {+ command.args(["-c", &script]);+ }+ let mut shell = Shell::spawn(&repo, command);+ if interactive {+ shell.send(&format!("{script}\n"));+ }+ let info = native_info(&repo, "worker-info");+ shell.remember(info[0]);+ shell.remember(info[2]);+ assert_eq!(info[1], shell.foreground());+ crate::common::wait_for_foreground_admission(&repo, &[info[0]]);+ shell.send("\u{3}");+ crate::common::wait_for_file_content(&repo.root_path().join("wrapper-cwd"));+ assert_eq!(+ std::fs::read_to_string(repo.root_path().join("wrapper-cwd"))+ .unwrap()+ .trim(),+ repo.root_path().to_str().unwrap()+ );+ assert_wrapper_directives_removed(&repo);+ // Nushell's mktemp --tmpdir also puts its captured stdout file here.+ assert_eq!(std::fs::read_dir(temporary).unwrap().count(), 0);+}++#[rstest]+#[case("bash", "default")]+#[case("bash", "custom")]+#[case("bash", "ignored")]+#[case("zsh", "default")]+#[case("zsh", "custom")]+#[case("zsh", "ignored")]+#[case("fish", "default")]+#[case("fish", "custom")]+#[case("fish", "ignored")]+fn interrupted_shell_wrapper_applies_directive_and_cleans_up(+ mut repo: TestRepo,+ #[case] name: &str,+ #[case] disposition: &str,+) {+ let feature = repo.add_worktree("feature");+ std::fs::write(+ repo.root_path().join("wrapper-worker.py"),+ r#"import os, signal, sys, time+from pathlib import Path+if len(sys.argv) > 1:+ signal.signal(signal.SIGINT, signal.SIG_DFL)+ signal.pthread_sigmask(signal.SIG_UNBLOCK, {signal.SIGINT})+ os.kill(os.getpid(), signal.SIGINT)+seen = False+def on_int(*_):+ global seen+ seen = True+signal.signal(signal.SIGINT, on_int)+signal.pthread_sigmask(signal.SIG_UNBLOCK, {signal.SIGINT})+Path('wrapper-info').write_text(f'{os.getpid()} {os.getpgrp()} {os.getppid()}')+while not seen:+ time.sleep(.01)+"#,+ )+ .unwrap();+ let mut shell = wrapper_shell(&repo, name, &wt_bin());+ let quote = |path: &std::path::Path| {+ shell_escape::escape(path.to_string_lossy().into_owned().into()).into_owned()+ };+ let trap = match disposition {+ "custom" => "trap 'printf called > wrapper-trap-called' INT",+ "ignored" => "trap '' INT",+ _ => ":",+ };+ shell.send(&format!(+ "{trap}; trap > wrapper-traps-before; printf 'WRAPPER_%s\\n' READY\n"+ ));+ wrapper_prompt(&mut shell, "WRAPPER_READY");++ shell.send(&format!(+ "cd {}; wt switch main --yes --execute python3 -- {} self\n",+ quote(&feature),+ quote(&repo.root_path().join("wrapper-worker.py"))+ ));+ shell.wait_for("wrapper-prompt> ");+ // A signal can cancel the remainder of the interactive input line. Read+ // its status on the next command, after the shell's cleanup fence ran.+ let status = if name == "fish" { "$status" } else { "$?" };+ shell.send(&format!(+ "printf '%s' {status} > {}; pwd > {}; trap > {}; printf 'WRAPPER_%s\\n' CHECKED\n",+ quote(&repo.root_path().join("wrapper-status")),+ quote(&repo.root_path().join("wrapper-cwd")),+ quote(&repo.root_path().join("wrapper-traps-after"))+ ));+ wrapper_prompt(&mut shell, "WRAPPER_CHECKED");+ assert_eq!(+ std::fs::read_to_string(repo.root_path().join("wrapper-status")).unwrap(),+ "130"+ );+ assert_eq!(+ std::fs::read_to_string(repo.root_path().join("wrapper-cwd"))+ .unwrap()+ .trim(),+ repo.root_path().to_str().unwrap()+ );+ assert_wrapper_directives_removed(&repo);+ assert_eq!(+ std::fs::read(repo.root_path().join("wrapper-traps-before")).unwrap(),+ std::fs::read(repo.root_path().join("wrapper-traps-after")).unwrap()+ );++ let logging = if name == "fish" {+ format!(+ "set -gx RUST_LOG {}",+ crate::common::FOREGROUND_TRACE_FILTER+ )+ } else {+ format!("export RUST_LOG={}", crate::common::FOREGROUND_TRACE_FILTER)+ };+ shell.send(&format!(+ "{logging}; cd {}; wt -vv switch main --yes --execute python3 -- {}; printf '%s' {status} > {}; printf 'WRAPPER_%s\\n' CAUGHT\n",+ quote(&feature),+ quote(&repo.root_path().join("wrapper-worker.py")),+ quote(&repo.root_path().join("wrapper-caught-status"))+ ));+ let info = native_info(&repo, "wrapper-info");+ shell.remember(info[0]);+ shell.remember(info[2]);+ assert_eq!(info[1], shell.foreground());+ crate::common::wait_for_foreground_admission(&repo, &[info[0]]);+ shell.send("\u{3}");+ shell.wait_for("WRAPPER_CAUGHT");+ assert_eq!(+ std::fs::read_to_string(repo.root_path().join("wrapper-caught-status")).unwrap(),+ "0"+ );+ assert_wrapper_directives_removed(&repo);+}++#[rstest]+#[case("bash", false)]+#[case("/bin/bash", false)]+#[case("zsh", false)]+#[case("fish", false)]+#[case("bash", true)]+#[case("/bin/bash", true)]+fn shell_wrapper_preserves_native_compound_interrupts(+ mut repo: TestRepo,+ #[case] name: &str,+ #[case] exported_prompt: bool,+) {+ use std::os::unix::fs::PermissionsExt;+ let feature = repo.add_worktree("feature");+ // Exercise the generated wrapper's documented binary/directive boundary+ // with real raw-SIGINT and ordinary-130 exits. Numeric 130 must not be used+ // to infer that the shell should abort its compound command or loop.+ let executable = repo.root_path().join("native-wrapper-command");+ std::fs::write(+ &executable,+ r#"#!/usr/bin/env python3+import os, signal, sys+from pathlib import Path+Path(os.environ['WORKTRUNK_DIRECTIVE_CD_FILE']).write_text(os.environ['WT_WRAPPER_TEST_TARGET'])+if sys.argv[1] == 'raw':+ signal.signal(signal.SIGINT, signal.SIG_DFL)+ signal.pthread_sigmask(signal.SIG_UNBLOCK, {signal.SIGINT})+ os.kill(os.getpid(), signal.SIGINT)+sys.exit({'zero': 0, 'three': 3}.get(sys.argv[1], 130))+"#,+ )+ .unwrap();+ std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755)).unwrap();+ let mut shell = wrapper_shell(&repo, name, &executable);+ let quote = |path: &std::path::Path| {+ shell_escape::escape(path.to_string_lossy().into_owned().into()).into_owned()+ };+ let bash = matches!(name, "bash" | "/bin/bash");+ if bash {+ let export = if exported_prompt { "export " } else { "" };+ shell.send(&format!(+ "{export}PROMPT_COMMAND='status=$?'; printf 'WRAPPER_%s\\n' PROMPT\n"+ ));+ wrapper_prompt(&mut shell, "WRAPPER_PROMPT");+ }+ let feature = quote(&feature);+ let next = quote(&repo.root_path().join("wrapper-next"));+ let status = if name == "fish" { "$status" } else { "$?" };+ let raw_status_path = quote(&repo.root_path().join("wrapper-raw-status"));+ let continuation_cwd = repo.root_path().join("wrapper-continuation-cwd");+ let assert_continuation_cwd = || {+ assert_eq!(+ std::fs::read_to_string(&continuation_cwd).unwrap().trim(),+ repo.root_path().to_str().unwrap()+ );+ };+ // Compare the same function and compound context as the wrapper. Fish+ // 3.x continues after a signal-killed child inside a function, while 4.x+ // aborts the input line; a bare external command is not the same boundary.+ let reference_cd = quote(&repo.root_path().join("wrapper-reference-cd"));+ let reference_command = format!(+ "env WORKTRUNK_DIRECTIVE_CD_FILE={reference_cd} {} raw",+ quote(&executable)+ );+ let reference_function = if name == "fish" {+ format!("function native_reference; {reference_command}; end")+ } else {+ format!("native_reference() {{ {reference_command}; }}")+ };+ shell.send(&format!("{reference_function}\n"));+ shell.wait_for("wrapper-prompt> ");+ let compound = |command: &str, raw_status: &str, next: &str, looping: bool| {+ let body = format!(+ "{command}; printf '%s' {status} > {raw_status}; pwd > {}; printf next >> {next}",+ quote(&continuation_cwd)+ );+ if looping && name == "fish" {+ format!("for iteration in first second; {body}; end")+ } else if looping {+ format!("for iteration in first second; do {body}; done")+ } else {+ body+ }+ };+ let mut native_expectations = Vec::new();+ for looping in [false, true] {+ let reference = repo+ .root_path()+ .join(format!("wrapper-reference-{looping}"));+ let reference_raw_status = repo.root_path().join("wrapper-reference-raw-status");+ let reference_native_status = repo.root_path().join("wrapper-reference-native-status");+ let native = compound(+ "native_reference",+ "e(&reference_raw_status),+ "e(&reference),+ looping,+ );+ shell.send(&format!("cd {feature}; {native}\n"));+ shell.wait_for("wrapper-prompt> ");+ let reference_prompt_status = repo.root_path().join("wrapper-reference-prompt-status");+ let record_prompt = if bash {+ format!(+ "printf '%s' \"$status\" > {}; ",+ quote(&reference_prompt_status)+ )+ } else {+ String::new()+ };+ shell.send(&format!(+ "printf '%s' {status} > {}; {record_prompt}printf 'WRAPPER_%s\\n' REFERENCE\n",+ quote(&reference_native_status)+ ));+ wrapper_prompt(&mut shell, "WRAPPER_REFERENCE");+ let native_continues = reference.exists();+ let native_status = std::fs::read_to_string(if native_continues {+ &reference_raw_status+ } else {+ &reference_native_status+ })+ .unwrap();+ let next_path = repo.root_path().join(format!("wrapper-next-{looping}"));+ let interrupted = compound("wt raw", &raw_status_path, "e(&next_path), looping);+ let reset_prompt_status = if bash { "status=seed; " } else { "" };+ shell.send(&format!(+ "{reset_prompt_status}cd {feature}; {interrupted}\n"+ ));+ shell.wait_for("wrapper-prompt> ");+ let raw_output = shell.output.clone();+ let wrapper_prompt_status = repo.root_path().join("wrapper-prompt-status");+ let record_prompt = if bash {+ format!(+ "printf '%s' \"$status\" > {}; ",+ quote(&wrapper_prompt_status)+ )+ } else {+ String::new()+ };+ shell.send(&format!(+ "printf '%s' {status} > {}; {record_prompt}pwd > {}; printf 'WRAPPER_%s\\n' ABORTED\n",+ quote(&repo.root_path().join("wrapper-native-status")),+ quote(&repo.root_path().join("wrapper-native-cwd"))+ ));+ wrapper_prompt(&mut shell, "WRAPPER_ABORTED");+ if bash {+ assert_eq!(+ std::fs::read_to_string(wrapper_prompt_status).unwrap(),+ std::fs::read_to_string(reference_prompt_status).unwrap(),+ "the prompt callback must run in its caller's variable scope"+ );+ }+ let raw_status = if native_continues {+ "wrapper-raw-status"+ } else {+ "wrapper-native-status"+ };+ assert_eq!(+ std::fs::read_to_string(repo.root_path().join(raw_status)).unwrap_or_else(|error| {+ panic!("missing {raw_status}, shell={name}, looping={looping}, native_continues={native_continues}: {error}; terminal output:\n{raw_output}")+ }),+ native_status,+ "shell={name}, looping={looping}, native_continues={native_continues}; terminal output:\n{raw_output}"+ );+ assert_eq!(+ std::fs::read_to_string(repo.root_path().join("wrapper-native-cwd"))+ .unwrap()+ .trim(),+ repo.root_path().to_str().unwrap()+ );+ assert_eq!(next_path.exists(), native_continues);+ if native_continues {+ assert_continuation_cwd();+ }+ assert_wrapper_directives_removed(&repo);+ native_expectations.push((native_continues, native_status));+ }+ shell.send(&format!(+ "cd {feature}; wt ordinary; printf '%s' {status} > {}; printf next > {next}; printf 'WRAPPER_%s\\n' CONTINUED\n",+ quote(&repo.root_path().join("wrapper-native-status"))+ ));+ wrapper_prompt(&mut shell, "WRAPPER_CONTINUED");+ assert_eq!(+ std::fs::read_to_string(repo.root_path().join("wrapper-native-status")).unwrap(),+ "130"+ );+ assert!(repo.root_path().join("wrapper-next").exists());+ assert_wrapper_directives_removed(&repo);++ let missing = quote(&repo.root_path().join("missing-wrapper-target"));+ let target = if name == "fish" {+ format!("set -gx WT_WRAPPER_TEST_TARGET {missing}")+ } else {+ format!("export WT_WRAPPER_TEST_TARGET={missing}")+ };+ for (mode, expected) in [("zero", "1"), ("three", "3")] {+ shell.send(&format!("{target}; cd {feature}; wt {mode}; printf '%s' {status} > {}; printf 'WRAPPER_%s\\n' CD_FAILED\n", quote(&repo.root_path().join("wrapper-native-status"))));+ wrapper_prompt(&mut shell, "WRAPPER_CD_FAILED");+ assert_eq!(+ std::fs::read_to_string(repo.root_path().join("wrapper-native-status")).unwrap(),+ expected+ );+ assert_wrapper_directives_removed(&repo);+ }+ // A foreground hook uses an exec leaf, so actual wt propagates a real+ // SIGINT rather than a shell intermediary's ordinary exit code 130.+ repo.write_project_config("post-start = 'exec python3 -c \"import os,signal; signal.signal(2,signal.SIG_DFL); signal.pthread_sigmask(signal.SIG_UNBLOCK,{2}); os.kill(os.getpid(),2)\"'");+ let binary = quote(&recording_wrapper_binary(&repo, &wt_bin()));+ let binary = if name == "fish" {+ format!("set -gx WORKTRUNK_BIN {binary}")+ } else {+ format!("export WORKTRUNK_BIN={binary}")+ };+ shell.send(&format!("{binary}; printf 'WRAPPER_%s\\n' ACTUAL\n"));+ wrapper_prompt(&mut shell, "WRAPPER_ACTUAL");+ for (looping, (native_continues, native_status)) in+ [false, true].into_iter().zip(native_expectations)+ {+ let actual_next = repo+ .root_path()+ .join(format!("wrapper-actual-next-{looping}"));+ let command = compound(+ &format!("cd {feature}; wt switch main --yes; wt hook post-start --yes --foreground"),+ &raw_status_path,+ "e(&actual_next),+ looping,+ );+ shell.send(&format!("{command}\n"));+ shell.wait_for("wrapper-prompt> ");+ let raw_output = shell.output.clone();+ shell.send(&format!(+ "printf '%s' {status} > {}; printf 'WRAPPER_%s\\n' ACTUAL_ABORTED\n",+ quote(&repo.root_path().join("wrapper-native-status"))+ ));+ wrapper_prompt(&mut shell, "WRAPPER_ACTUAL_ABORTED");+ assert_eq!(+ std::fs::read_to_string(repo.root_path().join(if native_continues {+ "wrapper-raw-status"+ } else {+ "wrapper-native-status"+ }))+ .unwrap(),+ native_status,+ "shell={name}, looping={looping}, native_continues={native_continues}; terminal output:\n{raw_output}"+ );+ assert_eq!(actual_next.exists(), native_continues);+ if native_continues {+ assert_continuation_cwd();+ }+ assert_wrapper_directives_removed(&repo);+ }+}++/// A terminal key can exit a noninteractive Bash before RETURN runs. Cleanup+/// must precede the caller's existing EXIT handler and preserve its native status.+#[rstest]+#[case("bash")]+#[case("/bin/bash")]+fn bash_script_interrupt_cleans_before_exit_handler(mut repo: TestRepo, #[case] name: &str) {+ use std::os::unix::fs::PermissionsExt;+ let feature = repo.add_worktree("feature");+ let executable = repo.root_path().join("native-wrapper-command");+ std::fs::write(+ &executable,+ r#"#!/usr/bin/env python3+import os, signal, sys, time+from pathlib import Path+root = Path(os.environ['WT_WRAPPER_TEST_TARGET'])+Path(os.environ['WORKTRUNK_DIRECTIVE_CD_FILE']).write_text(str(root))+signal.signal(signal.SIGINT, signal.SIG_DFL)+signal.pthread_sigmask(signal.SIG_UNBLOCK, {signal.SIGINT})+(root / ('script-info-' + sys.argv[1])).write_text(f'{os.getpid()} {os.getpgrp()} {os.getppid()}')+while True:+ time.sleep(.01)+"#,+ )+ .unwrap();+ std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755)).unwrap();+ let init = repo+ .wt_command()+ .args(["config", "shell", "init", "bash"])+ .output()+ .unwrap();+ assert!(init.status.success());+ let init_path = repo.root_path().join("wrapper-init");+ std::fs::write(&init_path, init.stdout).unwrap();+ let binary = recording_wrapper_binary(&repo, &executable);+ let quote = |path: &std::path::Path| {+ shell_escape::escape(path.to_string_lossy().into_owned().into()).into_owned()+ };+ let mut expectations = None;+ for mode in ["reference", "wrapper"] {+ let status_path = repo.root_path().join(format!("script-status-{mode}"));+ let cwd_path = repo.root_path().join(format!("script-cwd-{mode}"));+ let global_path = repo.root_path().join(format!("script-global-{mode}"));+ let next_path = repo.root_path().join(format!("script-next-{mode}"));+ let after_path = repo.root_path().join(format!("script-after-{mode}"));+ let command = if mode == "reference" {+ "native_reference"+ } else {+ "wt wrapper"+ };+ let script = format!(+ "export WORKTRUNK_BIN={} WT_WRAPPER_TEST_TARGET={}; source {}; status=seed; native_reference() {{ env WORKTRUNK_DIRECTIVE_CD_FILE={} {} reference; }}; trap 'printf \"%s\\n\" \"$?\" >> {}; printf \"%s\" \"$status\" > {}; pwd > {}' EXIT; cd {}; for iteration in only; do {command}; printf next > {}; done; printf after > {}",+ quote(&binary),+ quote(repo.root_path()),+ quote(&init_path),+ quote(&repo.root_path().join("script-reference-cd")),+ quote(&executable),+ quote(&status_path),+ quote(&global_path),+ quote(&cwd_path),+ quote(&feature),+ quote(&next_path),+ quote(&after_path)+ );+ let mut command = CommandBuilder::new(name);+ command.args(["--noprofile", "--norc", "-c", &script]);+ let mut shell = Shell::spawn(&repo, command);+ let info = native_info(&repo, &format!("script-info-{mode}"));+ shell.remember(info[0]);+ assert_eq!(info[1], shell.foreground());+ shell.send("\u{3}");+ crate::common::wait_for_file_content(&cwd_path);+ let status = std::fs::read_to_string(&status_path).unwrap();+ assert_eq!(std::fs::read_to_string(global_path).unwrap(), "seed");+ assert_eq!(+ status.lines().count(),+ 1,+ "EXIT ran more than once: {status}"+ );+ let observed = (status, next_path.exists(), after_path.exists());+ if mode == "reference" {+ expectations = Some(observed);+ } else {+ assert_eq!(&observed, expectations.as_ref().unwrap());+ assert_wrapper_directives_removed(&repo);+ assert_eq!(+ std::fs::read_to_string(cwd_path).unwrap().trim(),+ repo.root_path().to_str().unwrap()+ );+ }+ }+}++/// A subshell can report its parent's inactive EXIT trap. A wrapper must not+/// activate that handler, or replace a subshell's own handler.+#[rstest]+#[case("bash")]+#[case("/bin/bash")]+fn bash_wrapper_preserves_subshell_exit_ownership(repo: TestRepo, #[case] name: &str) {+ use std::os::unix::fs::PermissionsExt;+ let executable = repo.root_path().join("native-wrapper-command");+ std::fs::write(+ &executable,+ "#!/bin/sh\nprintf '%s' \"$WORKTRUNK_TEST_WRAPPER_TARGET\" > \"$WORKTRUNK_DIRECTIVE_CD_FILE\"\nexit 3\n",+ )+ .unwrap();+ std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755)).unwrap();+ let init = repo+ .wt_command()+ .args(["config", "shell", "init", "bash"])+ .output()+ .unwrap();+ assert!(init.status.success());+ let init = String::from_utf8(init.stdout).unwrap();+ let binary = recording_wrapper_binary(&repo, &executable);+ for (body, expected) in [+ (+ "value=$(wt; printf INNER); printf 'VALUE_%s\\n' \"$value\"",+ "VALUE_INNER\nPARENT_0\n",+ ),+ ("wt | cat; printf AFTER", "AFTERPARENT_0\n"),+ ("(wt; printf INNER); printf AFTER", "INNERAFTERPARENT_0\n"),+ (+ "(trap 'printf \"SUB_%s\\n\" \"$?\"' EXIT; wt; exit 17); printf AFTER",+ "SUB_17\nAFTERPARENT_0\n",+ ),+ ] {+ let script = format!("{init}\ntrap 'printf \"PARENT_%s\\n\" \"$?\"' EXIT; {body}");+ let mut command = std::process::Command::new(name);+ repo.configure_wt_cmd(&mut command);+ let output = command+ .args(["--noprofile", "--norc", "-c", &script])+ .current_dir(repo.root_path())+ .env("WORKTRUNK_BIN", &binary)+ .env("WORKTRUNK_TEST_WRAPPER_TARGET", repo.root_path())+ .output()+ .unwrap();+ assert!(output.status.success(), "{name}, {body}: {output:?}");+ assert_eq!(+ String::from_utf8(output.stdout).unwrap(),+ expected,+ "{name}, {body}"+ );+ assert_wrapper_directives_removed(&repo);+ }+}++/// Prompt hooks with caller-owned attributes must not prevent ordinary commands,+/// lose those attributes, or export the wrapper's temporary callback to children.+#[rstest]+#[case("bash", "readonly PROMPT_COMMAND=:")]+#[case("/bin/bash", "readonly PROMPT_COMMAND=:")]+#[case("bash", "export PROMPT_COMMAND=:")]+#[case("/bin/bash", "export PROMPT_COMMAND=:")]+#[case("bash", "unset PROMPT_COMMAND; export PROMPT_COMMAND")]+#[case("/bin/bash", "unset PROMPT_COMMAND; export PROMPT_COMMAND")]+#[case("bash", "readonly PROMPT_COMMAND=:; export PROMPT_COMMAND")]+#[case("/bin/bash", "readonly PROMPT_COMMAND=:; export PROMPT_COMMAND")]+#[case("bash", "PROMPT_COMMAND=:; set -a")]+#[case("/bin/bash", "PROMPT_COMMAND=:; set -a")]+#[case("bash", "unset PROMPT_COMMAND; set -a")]+#[case("/bin/bash", "unset PROMPT_COMMAND; set -a")]+#[case("bash", "unset PROMPT_COMMAND; readonly PROMPT_COMMAND")]+#[case("/bin/bash", "unset PROMPT_COMMAND; readonly PROMPT_COMMAND")]+#[case("bash", "unset PROMPT_COMMAND")]+#[case("/bin/bash", "unset PROMPT_COMMAND")]+fn bash_wrapper_preserves_protected_prompt(+ repo: TestRepo,+ #[case] name: &str,+ #[case] setup: &str,+) {+ use std::os::unix::fs::PermissionsExt;+ let executable = repo.root_path().join("native-wrapper-command");+ std::fs::write(+ &executable,+ "#!/bin/sh\nprintf '%s' \"$WT_WRAPPER_TEST_TARGET\" > \"$WORKTRUNK_DIRECTIVE_CD_FILE\"\nprintf '%s' \"${PROMPT_COMMAND-}\" > \"$WT_WRAPPER_TEST_TARGET/prompt-child\"\nexit \"$1\"\n",+ )+ .unwrap();+ std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755)).unwrap();+ // A literal x makes flag parsing failures deterministic rather than+ // depending on the allocator's random suffix appearing in the callback.+ let quote = |path: &std::path::Path| {+ shell_escape::escape(path.to_string_lossy().into_owned().into()).into_owned()+ };+ let tools = repo.root_path().join("wrapper-tools");+ std::fs::create_dir(&tools).unwrap();+ let mktemp = tools.join("mktemp");+ std::fs::write(+ &mktemp,+ format!(+ "#!/bin/sh\nexec {} {}\n",+ quote(&which::which("mktemp").unwrap()),+ quote(&repo.root_path().join("directive-x.XXXXXX"))+ ),+ )+ .unwrap();+ std::fs::set_permissions(&mktemp, std::fs::Permissions::from_mode(0o755)).unwrap();+ let mut shell = wrapper_shell(&repo, name, &executable);+ shell.send(&format!(+ "PATH={}:$PATH; {setup}; declare -p PROMPT_COMMAND > prompt-before; export -p > prompt-exports-before; printf 'WRAPPER_%s\\n' PROTECTED\n", quote(&tools)+ ));+ wrapper_prompt(&mut shell, "WRAPPER_PROTECTED");+ for status in [0, 130] {+ shell.send(&format!("wt {status}\n"));+ shell.wait_for("wrapper-prompt> ");+ shell.send("printf '%s' $? > prompt-status; declare -p PROMPT_COMMAND > prompt-after; export -p > prompt-exports-after; printf 'WRAPPER_%s\\n' CHECKED\n");+ wrapper_prompt(&mut shell, "WRAPPER_CHECKED");+ assert_eq!(+ std::fs::read_to_string(repo.root_path().join("prompt-status")).unwrap(),+ status.to_string(),+ "{name}, {setup}"+ );+ assert_eq!(+ std::fs::read(repo.root_path().join("prompt-before")).unwrap(),+ std::fs::read(repo.root_path().join("prompt-after")).unwrap(),+ "{name}, {setup}"+ );+ let exported_prompt = |file: &str| {+ std::fs::read_to_string(repo.root_path().join(file))+ .unwrap()+ .lines()+ .find(|line| line.starts_with("declare -x PROMPT_COMMAND"))+ .map(str::to_owned)+ };+ assert_eq!(+ exported_prompt("prompt-exports-before"),+ exported_prompt("prompt-exports-after"),+ "{name}, {setup}"+ );+ assert!(+ !std::fs::read_to_string(repo.root_path().join("prompt-child"))+ .unwrap()+ .contains("_wt_cleanup_"),+ "{name}, {setup}"+ );+ assert_wrapper_directives_removed(&repo);+ }+}++#[rstest]+#[case("bash")]+#[case("/bin/bash")]+fn bash_wrapper_preserves_exported_prompt_in_interactive_child(repo: TestRepo, #[case] name: &str) {+ use std::os::unix::fs::PermissionsExt;+ let executable = repo.root_path().join("native-wrapper-command");+ std::fs::write(&executable, "#!/bin/sh\nexec \"$@\"\n").unwrap();+ std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755)).unwrap();+ let mut shell = wrapper_shell(&repo, name, &executable);+ let events = repo.root_path().join("child-prompt-events");+ let events_quoted = shell_escape::escape(events.to_string_lossy().into_owned().into());+ let callback =+ shell_escape::escape(format!("printf 'CHILD_PROMPT\\n' >> {events_quoted}").into());+ shell.send(&format!(+ "export PROMPT_COMMAND={callback}; wt {name} --noprofile --norc -i\n"+ ));+ crate::common::wait_for_file_content(&events);+ assert_eq!(std::fs::read_to_string(&events).unwrap(), "CHILD_PROMPT\n");+ shell.send("exit\n");+ shell.wait_for("wrapper-prompt> ");+ shell.send("printf 'WRAPPER_%s\\n' CHILD_RETURNED\n");+ shell.wait_for("WRAPPER_CHILD_RETURNED");+ assert!(+ !shell.output.contains("command not found"),+ "{}",+ shell.output+ );+ assert!(+ !shell.output.contains("maximum evaluation"),+ "{}",+ shell.output+ );+ wrapper_prompt(&mut shell, "WRAPPER_CHILD_RETURNED");+ assert_wrapper_directives_removed(&repo);+}++#[rstest]+#[case("bash")]+#[case("/bin/bash")]+fn bash_wrapper_preserves_functrace_return_handler(mut repo: TestRepo, #[case] name: &str) {+ let feature = repo.add_worktree("feature");+ let mut shell = wrapper_shell(&repo, name, &wt_bin());+ let quote = |path: &std::path::Path| {+ shell_escape::escape(path.to_string_lossy().into_owned().into()).into_owned()+ };+ shell.send("set -T; trap 'printf \"%s\\n\" \"${FUNCNAME[0]}\" >> wrapper-return-events' RETURN; trap -p RETURN > wrapper-return-before; printf 'WRAPPER_%s\\n' TRACED\n");+ wrapper_prompt(&mut shell, "WRAPPER_TRACED");+ shell.send(&format!(+ "cd {}; wt switch main --yes --execute sh -- -c 'exit 130'\n",+ quote(&feature)+ ));+ shell.wait_for("wrapper-prompt> ");+ shell.send(&format!(+ "printf '%s' $? > {}; trap -p RETURN > {}; printf 'WRAPPER_%s\\n' RETURNED\n",+ quote(&repo.root_path().join("wrapper-return-status")),+ quote(&repo.root_path().join("wrapper-return-after"))+ ));+ wrapper_prompt(&mut shell, "WRAPPER_RETURNED");+ assert_eq!(+ std::fs::read_to_string(repo.root_path().join("wrapper-return-status")).unwrap(),+ "130"+ );+ assert_eq!(+ std::fs::read(repo.root_path().join("wrapper-return-before")).unwrap(),+ std::fs::read(repo.root_path().join("wrapper-return-after")).unwrap()+ );+ // The prior handler receives wt's return as it did before the fence.+ let events = std::fs::read_to_string(repo.root_path().join("wrapper-return-events")).unwrap();+ assert_eq!(events.lines().filter(|name| *name == "wt").count(), 1);+ assert_wrapper_directives_removed(&repo);+}diff --git a/tests/integration_tests/mod.rs b/tests/integration_tests/mod.rsindex eb93c35dc..d7a379897 100644--- a/tests/integration_tests/mod.rs+++ b/tests/integration_tests/mod.rs@@ -29,6 +29,7 @@ pub mod e2e_shell;pub mod e2e_shell_post_start;pub mod eval;pub mod for_each;+pub mod foreground_jobs;pub mod git_error_display;pub mod help;pub mod hook_show;diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rsindex 6a5e00777..c3c31398f 100644--- a/tests/integration_tests/remove.rs+++ b/tests/integration_tests/remove.rs@@ -1159,7 +1159,7 @@ fn test_remove_interrupt_stops_batch(.output().unwrap();assert_eq!(- output.status.code(),+ crate::common::shell_exit_code(&output.status),Some(exit_code),"stderr:\n{}",String::from_utf8_lossy(&output.stderr)@@ -1254,7 +1254,11 @@ exec {real_git} "$@"if boundary == "status" {assert!(interrupted.exists(), "the clean check precedes removal");}- assert_eq!(output.status.code(), Some(exit_code), "stderr:\n{stderr}");+ assert_eq!(+ crate::common::shell_exit_code(&output.status),+ Some(exit_code),+ "stderr:\n{stderr}"+ );assert!(output.stdout.is_empty(),"a canceled batch must not publish success JSON"diff --git a/tests/integration_tests/shell_wrapper.rs b/tests/integration_tests/shell_wrapper.rsindex 4f624505f..d1189006d 100644--- a/tests/integration_tests/shell_wrapper.rs+++ b/tests/integration_tests/shell_wrapper.rs@@ -776,6 +776,49 @@ mod unix_tests {use crate::common::repo;use rstest::rstest;+ /// Errexit must wait for cleanup, and a failed CD must retain child failure.+ #[rstest]+ #[case("bash", "/bin/bash")]+ #[case("bash", "bash")]+ #[case("zsh", "zsh")]+ fn wrapper_errexit_preserves_status_and_cleanup(+ repo: TestRepo,+ #[case] shell: &str,+ #[case] executable: &str,+ ) {+ use std::os::unix::fs::PermissionsExt;++ let temporary = repo.root_path().join("wrapper-temps");+ fs::create_dir(&temporary).unwrap();+ let child = repo.root_path().join("failing-child");+ fs::write(+ &child,+ "#!/bin/sh\nprintf '%s' \"$WORKTRUNK_TEST_WRAPPER_MISSING\" > \"$WORKTRUNK_DIRECTIVE_CD_FILE\"\nexit 3\n",+ )+ .unwrap();+ fs::set_permissions(&child, fs::Permissions::from_mode(0o755)).unwrap();+ // An explicit template keeps mktemp inside the fixture on every OS.+ let script = format!(+ "{}\nmktemp() {{ command mktemp \"$WORKTRUNK_TEST_WRAPPER_TEMP/XXXXXX\"; }}\nset -e\nwt\nprintf UNREACHABLE\n",+ generate_wrapper(&repo, shell)+ );+ let mut command = Command::new(executable);+ repo.configure_wt_cmd(&mut command);+ let output = command+ .args(["-c", &script])+ .env("WORKTRUNK_BIN", &child)+ .env("WORKTRUNK_TEST_WRAPPER_TEMP", &temporary)+ .env(+ "WORKTRUNK_TEST_WRAPPER_MISSING",+ repo.root_path().join("missing"),+ )+ .output()+ .unwrap();+ assert_eq!(output.status.code(), Some(3), "{output:?}");+ assert!(!String::from_utf8_lossy(&output.stdout).contains("UNREACHABLE"));+ assert_eq!(fs::read_dir(temporary).unwrap().count(), 0);+ }+// ========================================================================// Cross-Shell Error Handling Tests// ========================================================================@@ -1043,8 +1086,11 @@ mod unix_tests {fn test_nu_wrapper_ignores_execute_flags_after_argument_boundary(repo: TestRepo) {let mut script = String::new();append_wrapper_setup(&mut script, "nu", &repo);+ // Nu 0.113 passes unquoted wrapped words as glob values. Keep that+ // native argument type explicit on newer Nu versions too.script.push_str(- "let out = (wt step for-each --format=json -- printf -- -x)\n\+ "let subcommand = (\"step\" | into glob)\n\+ let out = (wt $subcommand for-each --format=json -- printf -- -x)\n\print $\"PIPELINE_CAPTURED:(not ($out | is-empty))\"\n",);@@ -1227,6 +1273,82 @@ mod unix_tests {);}+ /// A failed directive must still release both wrapper temp files.+ #[rstest]+ fn test_nu_wrapper_cd_failure_runs_cleanup(repo: TestRepo) {+ use std::os::unix::fs::PermissionsExt;+ let tmp = tempfile::tempdir().unwrap();+ let executable = repo.root_path().join("invalid-directive");+ fs::write(+ &executable,+ "#!/bin/sh\nprintf '%s' \"$PWD/missing-directory\" > \"$WORKTRUNK_DIRECTIVE_CD_FILE\"\n",+ )+ .unwrap();+ fs::set_permissions(&executable, fs::Permissions::from_mode(0o755)).unwrap();+ let mut script = String::new();+ append_wrapper_setup(&mut script, "nu", &repo);+ script.push_str(&format!(+ "$env.WORKTRUNK_BIN = {}\nwt config show\n",+ nushell_quote(&executable.to_string_lossy()),+ ));+ let config_path = repo.test_config_path().to_string_lossy().to_string();+ let approvals_path = repo.test_approvals_path().to_string_lossy().to_string();+ let tmp_path = tmp.path().to_string_lossy().to_string();+ let mut env_vars = build_test_env_vars(&config_path, &approvals_path);+ env_vars.push(("TMPDIR", &tmp_path));+ let (combined, exit_code) =+ exec_in_pty_interactive("nu", &script, repo.root_path(), &env_vars, &[]);+ assert_ne!(exit_code, 0, "invalid directive should fail: {combined}");+ assert!(combined.contains("missing-directory"), "{combined}");+ assert_eq!(fs::read_dir(tmp.path()).unwrap().count(), 0, "{combined}");+ }++ /// Native signal deaths must cross Nushell's negative-status boundary+ /// before the wrapper propagates the status, after applying CD and cleanup.+ #[rstest]+ fn test_nu_wrapper_signal_status_runs_cleanup(mut repo: TestRepo) {+ repo.add_worktree("nu-signal");+ let target = canonicalize(repo.worktree_path("nu-signal")).unwrap();+ let tmp = tempfile::tempdir().unwrap();+ let tmp_path = tmp.path().to_string_lossy().to_string();+ let mut script = String::new();+ append_wrapper_setup(&mut script, "nu", &repo);+ for (body, expected) in [+ ("kill -INT $$", 130),+ ("kill -TERM $$", 143),+ ("exit 130", 130),+ ("exit 143", 143),+ ] {+ script.push_str(&format!(+ "let code = (try {{ wt switch nu-signal --yes --execute sh -- -c {}; 0 }} catch {{ $env.LAST_EXIT_CODE }})\nprint $\"WT_EXIT:($code)\"\nprint $\"WT_CD:($env.PWD == {})\"\n",+ nushell_quote(body),+ nushell_quote(&target.to_string_lossy()),+ ));+ // Each iteration starts outside the destination, so every call+ // must apply the directive before propagating its failure.+ script.push_str(&format!(+ "cd {}\n",+ nushell_quote(&repo.root_path().to_string_lossy())+ ));+ script.push_str(&format!(+ "if $code != {expected} {{ error make {{ msg: $\"unexpected wrapper status: ($code)\" }} }}\n"+ ));+ }++ let config_path = repo.test_config_path().to_string_lossy().to_string();+ let approvals_path = repo.test_approvals_path().to_string_lossy().to_string();+ let mut env_vars = build_test_env_vars(&config_path, &approvals_path);+ env_vars.push(("TMPDIR", &tmp_path));+ let (combined, exit_code) =+ exec_in_pty_interactive("nu", &script, repo.root_path(), &env_vars, &[]);++ assert_eq!(exit_code, 0, "Output:\n{combined}");+ assert_eq!(combined.matches("WT_CD:true").count(), 4, "{combined}");+ assert_eq!(combined.matches("WT_EXIT:130").count(), 2, "{combined}");+ assert_eq!(combined.matches("WT_EXIT:143").count(), 2, "{combined}");+ assert_eq!(fs::read_dir(tmp.path()).unwrap().count(), 0, "{combined}");+ }+/// Test switch --create with pre-start (blocking) and post-start (background)/// Note: bash and fish disabled due to flaky PTY buffering race conditions///diff --git a/tests/integration_tests/step_alias.rs b/tests/integration_tests/step_alias.rsindex 812dc990a..20bc30cae 100644--- a/tests/integration_tests/step_alias.rs+++ b/tests/integration_tests/step_alias.rs@@ -1179,396 +1179,343 @@ fail = "exit 1");}-/// Aliases must run their child in wt's process group when stdin is inherited,-/// not isolate it in a new pgroup. Interactive children (`wt switch`'s picker,-/// pagers, anything that calls `tcsetattr` on `/dev/tty`) only work when they-/// share the foreground tty pgroup — otherwise the kernel sends SIGTTOU and-/// stops the child mid-render. We check the invariant directly: the alias body-/// records its shell pgid, and we assert it matches wt's pid (== wt's pgid-/// because the test spawns wt as its own pgroup leader).-#[rstest]+// Signal fixtures synchronize through files and avoid background descendants.+// An owned, unreaped keeper reserves the native group for scoped cleanup.#[cfg(unix)]-fn test_alias_child_shares_parent_pgroup(repo: TestRepo) {- use std::os::unix::process::CommandExt;- use std::process::Stdio;+struct AliasSignalJob {+ child: Option<std::process::Child>,+ keeper: std::process::Child,+ release: std::path::PathBuf,+}- repo.write_test_config(- r#"-[aliases]-record-pgid = "ps -o pgid= -p $$ | tr -d ' \n' > alias_pgid.txt"-"#,- );- repo.commit("initial");+#[cfg(unix)]+impl AliasSignalJob {+ fn spawn(repo: &TestRepo) -> Self {+ Self::spawn_with_stderr(repo, Stdio::null())+ }- let mut cmd = repo.wt_command();- cmd.args(["step", "record-pgid"]);- cmd.current_dir(repo.root_path());- cmd.stdout(Stdio::null());- cmd.stderr(Stdio::null());- // wt becomes its own pgroup leader: wt.pid == wt.pgid. The alias child- // (a `sh -c '...'` shell) should inherit that pgid rather than being- // moved into a new group.- cmd.process_group(0);- let mut child = cmd.spawn().expect("failed to spawn wt step record-pgid");- let wt_pid = child.id() as i32;- let status = child.wait().expect("failed to wait for wt");- assert!(status.success(), "alias should succeed, got: {status:?}");-- let marker = repo.root_path().join("alias_pgid.txt");- let recorded = std::fs::read_to_string(&marker)- .unwrap_or_else(|e| panic!("missing pgid marker {marker:?}: {e}"));- let alias_pgid: i32 = recorded- .trim()- .parse()- .unwrap_or_else(|e| panic!("could not parse pgid {recorded:?}: {e}"));- assert_eq!(- alias_pgid, wt_pid,- "alias child shell must share wt's pgroup (wt pid={wt_pid}); \- got child pgid {alias_pgid}, indicating a new pgroup was created"- );+ fn spawn_with_stderr(repo: &TestRepo, stderr: Stdio) -> Self {+ Self::spawn_command(repo, &["step", "signal-test"], stderr)+ }++ fn spawn_traced(repo: &TestRepo, stderr: Stdio) -> Self {+ Self::spawn_command(repo, &["-vv", "step", "signal-test"], stderr)+ }++ fn spawn_command(repo: &TestRepo, args: &[&str], stderr: Stdio) -> Self {+ use std::os::unix::process::CommandExt;+ // This owned, unreaped child reserves the caller group's numeric ID+ // even after wt finishes or a group interrupt kills the keeper.+ let keeper = std::process::Command::new("sleep")+ .arg("300")+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .process_group(0)+ .spawn()+ .unwrap();+ let mut job = Self {+ child: None,+ keeper,+ release: repo.root_path().join("release"),+ };+ let mut command = repo.wt_command();+ command.args(args);+ command+ .current_dir(repo.root_path())+ .env("RUST_LOG", crate::common::FOREGROUND_TRACE_FILTER)+ .stdout(Stdio::null())+ .stderr(stderr)+ .process_group(job.group().as_raw());+ job.child = Some(command.spawn().unwrap());+ job+ }++ fn pid(&self) -> nix::unistd::Pid {+ nix::unistd::Pid::from_raw(self.child.as_ref().unwrap().id() as i32)+ }++ fn group(&self) -> nix::unistd::Pid {+ nix::unistd::Pid::from_raw(self.keeper.id() as i32)+ }++ fn running(&mut self) -> bool {+ self.child.as_mut().unwrap().try_wait().unwrap().is_none()+ }++ fn release(&self) {+ std::fs::write(&self.release, "release").unwrap();+ }++ fn wait(&mut self) -> std::process::ExitStatus {+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);+ loop {+ if let Some(status) = self.child.as_mut().unwrap().try_wait().unwrap() {+ return status;+ }+ assert!(std::time::Instant::now() < deadline, "alias did not finish");+ std::thread::sleep(std::time::Duration::from_millis(10));+ }+ }}-/// Externally-delivered SIGTERM to wt (e.g. `kill -TERM <wt-pid>`) must still-/// reach the alias child in the shared-pgroup case. The kernel only delivers-/// PID-targeted signals to the named process, not the foreground pgroup, so-/// the listener in `Cmd::stream` must re-deliver to the child by PID.-/// Without that, wt would latch the signal but the child would keep running-/// indefinitely.-#[rstest]#[cfg(unix)]-fn test_alias_external_sigterm_reaches_child(repo: TestRepo) {- use crate::common::wait_for_file_content;- use nix::sys::signal::{Signal, kill};- use nix::unistd::Pid;- use std::os::unix::process::CommandExt;- use std::process::Stdio;-- // The trap installs in wt's wrapper sh (no inner `sh -c`), so SIGTERM- // delivered to wt's child by PID hits the same shell that has the- // handler. The body uses `sleep 30 & wait $!` rather than a plain- // `sleep 30` because POSIX shells defer trap execution until the- // current foreground command returns; `wait` (a builtin) is the- // canonical interruptible idiom.- repo.write_test_config(- r#"-[aliases]-trapped = "trap 'echo got-term >> trap.log; exit 143' TERM; echo started >> start.log; sleep 30 & wait $!"-"#,- );- repo.commit("initial");+impl Drop for AliasSignalJob {+ fn drop(&mut self) {+ let _ = std::fs::write(&self.release, "release");+ // No wait for the keeper precedes this signal. Its reserved PID pins+ // the group's identity, independently of wt's cached wait status.+ let _ = nix::sys::signal::killpg(self.group(), nix::sys::signal::Signal::SIGKILL);+ if let Some(child) = &mut self.child {+ let _ = child.wait();+ }+ let _ = self.keeper.wait();+ }+}- let mut cmd = repo.wt_command();- cmd.args(["step", "trapped"]);- cmd.current_dir(repo.root_path());- cmd.stdout(Stdio::null());- cmd.stderr(Stdio::null());- // wt becomes its own pgroup leader so a PID-targeted `kill -TERM` against- // wt does NOT incidentally hit the test harness's pgroup, and only reaches- // wt itself (not the alias child via kernel broadcast).- cmd.process_group(0);- let mut child = cmd.spawn().expect("failed to spawn wt step trapped");-- // Wait until the alias shell has installed its trap and entered `sleep`.- let start_marker = repo.root_path().join("start.log");- wait_for_file_content(&start_marker);-- // Target wt's PID specifically (not its pgroup) — simulates an external- // `kill -TERM <wt-pid>`.- let wt_pid = Pid::from_raw(child.id() as i32);- kill(wt_pid, Signal::SIGTERM).expect("failed to send SIGTERM to wt");-- let status = child.wait().expect("failed to wait for wt");-- // wt forwarded SIGTERM to the wrapper sh by PID (the contract this test- // pins), so the trap's `exit` orphaned the backgrounded `sleep 30` in wt's- // process group. wt led that group (`process_group(0)` above) and is now- // reaped, so SIGKILL the whole group (negative pgid) to reap the sleep- // before returning — otherwise it lingers ~30s as a stray process.- let _ = kill(Pid::from_raw(-wt_pid.as_raw()), Signal::SIGKILL);-- // The trap marker proves the alias shell received SIGTERM. Without the- // PID-targeted forwarding, this file would never appear and wt would- // block on the 30s sleep.- let trap_marker = repo.root_path().join("trap.log");- let recorded = std::fs::read_to_string(&trap_marker).unwrap_or_else(|e| {- panic!(- "missing trap marker {trap_marker:?}: {e} — \- alias child did not receive SIGTERM (forwarding regressed?)"+#[cfg(unix)]+fn signal_alias(repo: &TestRepo, concurrent: bool, caught_int: Option<bool>) -> Vec<&'static str> {+ let labels = if concurrent {+ vec!["one", "two"]+ } else {+ vec!["one"]+ };+ let commands: Vec<_> = labels.iter().map(|label| {+ let int_trap = match caught_int {+ Some(true) => format!("trap 'echo got-int >> int-{label}' INT; "),+ Some(false) => "trap '' INT; ".to_owned(),+ None => String::new(),+ };+ let body = format!("{int_trap}trap 'echo got-term > term-{label}; exit 0' TERM; echo $$ > pid-{label}; echo ready > start-{label}; while test ! -f release; do :; done");+ (*label, serde_json::to_string(&body).unwrap())+ }).collect();+ let first = if concurrent {+ format!(+ "{{ {} }}",+ commands+ .iter()+ .map(|(label, command)| format!("{label} = {command}"))+ .collect::<Vec<_>>()+ .join(", "))- });- assert!(- recorded.contains("got-term"),- "trap marker missing expected content: {recorded:?}"- );-- // wt itself exits with the signal-derived code (128 + 15 = 143).- use std::os::unix::process::ExitStatusExt;- assert!(- status.signal() == Some(15) || status.code() == Some(143),- "wt should exit from SIGTERM (signal 15) or with code 143, got: {status:?}"- );+ } else {+ commands[0].1.clone()+ };+ repo.write_test_config(&format!(+ "[aliases]\nsignal-test = [{first}, 'echo next > next']\n"+ ));+ labels}-/// SIGINT counterpart of `test_alias_external_sigterm_reaches_child`. A-/// PID-targeted `kill -INT <wt-pid>` (not pgroup-broadcast) must traverse the-/// SIGINT arm of `forward_signal_to_pid` — kernel pgroup delivery is bypassed-/// when the signal is aimed at a single PID, so the child only sees SIGINT if-/// wt re-delivers it.-#[rstest]#[cfg(unix)]-fn test_alias_external_sigint_reaches_child(repo: TestRepo) {- use crate::common::wait_for_file_content;- use nix::sys::signal::{Signal, kill};- use nix::unistd::Pid;- use std::os::unix::process::CommandExt;- use std::process::Stdio;-- repo.write_test_config(- r#"-[aliases]-trapped = "trap 'echo got-int >> trap.log; exit 130' INT; echo started >> start.log; sleep 30 & wait $!"+fn ready_alias_children(repo: &TestRepo, labels: &[&str], group: nix::unistd::Pid) -> Vec<i32> {+ labels+ .iter()+ .map(|label| {+ crate::common::wait_for_file_content(&repo.root_path().join(format!("start-{label}")));+ let pid =+ std::fs::read_to_string(repo.root_path().join(format!("pid-{label}"))).unwrap();+ let pid = nix::unistd::Pid::from_raw(pid.trim().parse().unwrap());+ assert_eq!(+ nix::unistd::getpgid(Some(pid)).unwrap(),+ group,+ "{label} left wt's native group"+ );+ pid.as_raw()+ })+ .collect()+}++/// A child that crashes in its TERM handler must not let a Warn hook pipeline+/// continue after controller cancellation. The same crash alone stays ordinary.+#[rstest]+#[case::ordinary_child_death(false)]+#[case::controller_cancellation(true)]+#[cfg(unix)]+fn test_controller_cancellation_survives_child_term_handler_crash(+ repo: TestRepo,+ #[case] controller_cancel: bool,+) {+ repo.write_project_config(r#"post-start = ["exec python3 worker.py", "printf NEXT > next"]"#);+ std::fs::write(+ repo.root_path().join("worker.py"),+ r#"import os, signal, time+from pathlib import Path+def on_term(*_):+ Path('term-handled').write_text('handled')+ os.kill(os.getpid(), signal.SIGKILL)+signal.signal(signal.SIGTERM, on_term)+Path('pid-one').write_text(str(os.getpid()))+Path('start-one').write_text('ready')+while not Path('release').exists():+ time.sleep(.001)+os.kill(os.getpid(), signal.SIGKILL)"#,+ )+ .unwrap();+ let stderr_path = repo.root_path().join("stderr");+ let mut job = AliasSignalJob::spawn_command(+ &repo,+ &["hook", "post-start", "--yes", "--foreground"],+ Stdio::from(std::fs::File::create(&stderr_path).unwrap()),+ );+ ready_alias_children(&repo, &["one"], job.group());+ if controller_cancel {+ nix::sys::signal::kill(job.pid(), nix::sys::signal::Signal::SIGTERM).unwrap();+ crate::common::wait_for_file_content(&repo.root_path().join("term-handled"));+ } else {+ job.release();+ }+ let status = job.wait();+ let stderr = std::fs::read_to_string(stderr_path).unwrap();+ assert_eq!(+ crate::common::shell_exit_code(&status),+ Some(if controller_cancel { 143 } else { 0 }),+ "{status:?}\n{stderr}",);- repo.commit("initial");-- let mut cmd = repo.wt_command();- cmd.args(["step", "trapped"]);- cmd.current_dir(repo.root_path());- cmd.stdout(Stdio::null());- cmd.stderr(Stdio::null());- cmd.process_group(0);- let mut child = cmd.spawn().expect("failed to spawn wt step trapped");-- let start_marker = repo.root_path().join("start.log");- wait_for_file_content(&start_marker);-- // Target wt's PID specifically (not its pgroup). Kernel won't broadcast to- // the alias child; the only way the child sees SIGINT is via wt's PID-- // forwarding path.- let wt_pid = Pid::from_raw(child.id() as i32);- kill(wt_pid, Signal::SIGINT).expect("failed to send SIGINT to wt");-- let status = child.wait().expect("failed to wait for wt");-- // wt forwarded SIGINT to the wrapper sh by PID (the contract this test- // pins), so the trap's `exit` orphaned the backgrounded `sleep 30` in wt's- // process group. wt led that group (`process_group(0)` above) and is now- // reaped, so SIGKILL the whole group (negative pgid) to reap the sleep- // before returning — otherwise it lingers ~30s as a stray process.- let _ = kill(Pid::from_raw(-wt_pid.as_raw()), Signal::SIGKILL);-- let trap_marker = repo.root_path().join("trap.log");- let recorded = std::fs::read_to_string(&trap_marker).unwrap_or_else(|e| {- panic!(- "missing trap marker {trap_marker:?}: {e} — \- alias child did not receive SIGINT (forwarding regressed?)"- )- });- assert!(- recorded.contains("got-int"),- "trap marker missing expected content: {recorded:?}"- );-- use std::os::unix::process::ExitStatusExt;- assert!(- status.signal() == Some(2) || status.code() == Some(130),- "wt should exit from SIGINT (signal 2) or with code 130, got: {status:?}"+ assert_eq!(+ repo.root_path().join("next").exists(),+ !controller_cancel,+ "{stderr}",);}-/// SIGINT sent to `wt step <alias>` while a concurrent group is mid-flight-/// must reach every child's process group and tear them all down — otherwise-/// Ctrl-C on a long-running concurrent alias would leave orphans behind.-///-/// We spawn the alias in its own process group, wait until BOTH children have-/// written their "start" marker (proving they're actually running concurrently),-/// send SIGINT to the group, then verify that the subsequent "done" markers-/// never appear — every child was interrupted.+/// Native policy: TERM aimed at wt cancels owned work even when its+/// child handles TERM successfully; PID-only INT is observed without delivery.#[rstest]+#[case::single_term(false, true)]+#[case::concurrent_term(true, true)]+#[case::single_int(false, false)]+#[case::concurrent_int(true, false)]#[cfg(unix)]-fn test_alias_concurrent_receives_sigint(repo: TestRepo) {- use crate::common::wait_for_file_content;+fn test_alias_pid_signal_policy(repo: TestRepo, #[case] concurrent: bool, #[case] terminate: bool) {use nix::sys::signal::{Signal, kill};- use nix::unistd::Pid;- use std::os::unix::process::CommandExt;- use std::process::Stdio;-- repo.write_test_config(- r#"-[aliases.slow]-one = "sh -c 'echo start-one >> slow_one.log; sleep 30; echo done-one >> slow_one.log'"-two = "sh -c 'echo start-two >> slow_two.log; sleep 30; echo done-two >> slow_two.log'"-"#,- );- repo.commit("initial");-- let mut cmd = repo.wt_command();- cmd.args(["step", "slow"]);- cmd.current_dir(repo.root_path());- 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 step slow");-- // Wait until BOTH children write their start marker — proves the group- // is running concurrently before we send the signal.- let one_log = repo.root_path().join("slow_one.log");- let two_log = repo.root_path().join("slow_two.log");- wait_for_file_content(&one_log);- wait_for_file_content(&two_log);-- // SIGINT the wt process group (wt == leader). The concurrent executor's- // signal forwarder must propagate it to every child's process group.- let wt_pgid = Pid::from_raw(child.id() as i32);- kill(Pid::from_raw(-wt_pgid.as_raw()), Signal::SIGINT)- .expect("failed to send SIGINT to wt's process group");-- let status = child.wait().expect("failed to wait for wt");-- use std::os::unix::process::ExitStatusExt;- assert!(- status.signal() == Some(2) || status.code() == Some(130),- "wt should exit from SIGINT (signal 2) or with code 130, got: {status:?}"- );-- // Grace period — the killed children must NOT reach their "done" write.- std::thread::sleep(SLEEP_FOR_ABSENCE_CHECK);- for log in [&one_log, &two_log] {- let contents = std::fs::read_to_string(log).unwrap_or_default();+ let labels = signal_alias(&repo, concurrent, Some(true));+ let stderr_path = repo.root_path().join("stderr");+ let stderr = std::fs::File::create(&stderr_path).unwrap();+ let mut job = AliasSignalJob::spawn_traced(&repo, stderr.into());+ let children = ready_alias_children(&repo, &labels, job.group());+ // A child can announce readiness before wt returns from spawn. This test+ // sends its signal to an admitted command, not during startup cancellation.+ crate::common::wait_for_foreground_admission(&repo, &children);+ kill(+ job.pid(),+ if terminate {+ Signal::SIGTERM+ } else {+ Signal::SIGINT+ },+ )+ .unwrap();+ if terminate {+ for label in &labels {+ crate::common::wait_for_file_content(&repo.root_path().join(format!("term-{label}")));+ }+ use std::os::unix::process::ExitStatusExt;+ let status = job.wait();+ assert!(+ status.code() == Some(143) || status.signal() == Some(15),+ "forwarded TERM must cancel after caught success: {status:?}\n{}",+ std::fs::read_to_string(stderr_path).unwrap()+ );+ assert!(!repo.root_path().join("next").exists());+ } else {+ std::thread::sleep(SLEEP_FOR_ABSENCE_CHECK);+ assert!(job.running(), "PID-only INT stopped the waiting caller");+ for label in &labels {+ assert!(+ !repo.root_path().join(format!("int-{label}")).exists(),+ "PID-only INT reached {label}"+ );+ }+ job.release();+ let status = job.wait();assert!(- !contents.contains("done"),- "sibling child reached 'done' after SIGINT, log: {contents:?}"+ status.success(),+ "PID-only INT changed an admitted command's status: {status:?}\n{}",+ std::fs::read_to_string(stderr_path).unwrap());+ assert!(repo.root_path().join("next").exists());}}-/// Children that trap SIGINT survive a single Ctrl-C — wt forwards the-/// user's signal once and waits. Matches `make` / `cargo` behavior:-/// stubborn children need a second Ctrl-C (see-/// `test_alias_concurrent_second_sigint_kills`) to escalate to SIGKILL.-///-/// Counterpart to `test_alias_concurrent_receives_sigint` (cooperative-/// children, single press is sufficient). Together they pin the-/// no-per-child-escalation contract: the previous design escalated-/// SIGINT → SIGTERM → SIGKILL inside one press, which under CI scheduling-/// latency could land SIGTERM on a cooperative-but-slow child and make-/// `wt step <alias>` exit 143 instead of 130 on Ctrl-C.+/// Kernel group delivery reaches both children; actual interrupted status+/// stops the following alias step.#[rstest]#[cfg(unix)]-fn test_alias_concurrent_sigint_trapped_survives_first_press(repo: TestRepo) {- use crate::common::wait_for_file_content;- use nix::sys::signal::{Signal, kill};- use nix::unistd::Pid;- use std::os::unix::process::CommandExt;- use std::process::Stdio;-- // Children trap SIGINT (ignore it). With the new no-escalation- // contract, a single SIGINT should NOT kill them.- repo.write_test_config(- r#"-[aliases.intignored]-one = "sh -c 'trap \"\" INT; echo start-one >> ignored_one.log; sleep 30'"-two = "sh -c 'trap \"\" INT; echo start-two >> ignored_two.log; sleep 30'"-"#,+fn test_alias_concurrent_receives_sigint(repo: TestRepo) {+ let labels = signal_alias(&repo, true, None);+ let mut job = AliasSignalJob::spawn(&repo);+ ready_alias_children(&repo, &labels, job.group());+ nix::sys::signal::killpg(job.group(), nix::sys::signal::Signal::SIGINT).unwrap();+ use std::os::unix::process::ExitStatusExt;+ let status = job.wait();+ assert!(+ status.code() == Some(130) || status.signal() == Some(2),+ "group INT should exit 130: {status:?}");- repo.commit("initial");-- let mut cmd = repo.wt_command();- cmd.args(["step", "intignored"]);- cmd.current_dir(repo.root_path());- cmd.stdout(Stdio::null());- cmd.stderr(Stdio::null());- cmd.process_group(0);- let mut child = cmd.spawn().expect("failed to spawn wt step intignored");-- wait_for_file_content(&repo.root_path().join("ignored_one.log"));- wait_for_file_content(&repo.root_path().join("ignored_two.log"));-- let wt_pgid = Pid::from_raw(child.id() as i32);- kill(Pid::from_raw(-wt_pgid.as_raw()), Signal::SIGINT)- .expect("failed to send SIGINT to wt's process group");-- // Give the signal a moment to traverse the forwarder. With escalation- // (the old design), within ~400 ms SIGTERM would have killed both- // children and wt would be in the process of exiting. With the new- // contract, both children keep sleeping and wt is still running.- std::thread::sleep(SLEEP_FOR_ABSENCE_CHECK);-- match child.try_wait().expect("try_wait failed") {- None => {- // Expected: wt is still running, blocked on its sleeping- // children. Clean up with a second SIGINT (impatient- // SIGKILL path).- kill(Pid::from_raw(-wt_pgid.as_raw()), Signal::SIGINT)- .expect("failed to send second SIGINT");- let _ = child.wait();- }- Some(status) => panic!(- "wt exited after a single SIGINT against SIGINT-trapping children — \- per-child escalation appears to have crept back in. status: {status:?}"- ),- }+ assert!(!repo.root_path().join("next").exists());}-/// A second SIGINT (user mashing Ctrl-C) must escalate to SIGKILL on every-/// child immediately — otherwise a child that traps SIGINT keeps the group-/// alive for up to N × 400ms of per-pgid escalation, with subsequent-/// presses silently discarded.+/// Repeated group interrupts retain the child's disposition and status. One+/// contrast per handler/key/cardinality covers both stream execution paths.#[rstest]+#[case::single_caught_once(false, true, 1)]+#[case::concurrent_caught_twice(true, true, 2)]+#[case::single_ignored_twice(false, false, 2)]+#[case::concurrent_ignored_once(true, false, 1)]#[cfg(unix)]-fn test_alias_concurrent_second_sigint_kills(repo: TestRepo) {- use crate::common::wait_for_file_content;- use nix::sys::signal::{Signal, kill};- use nix::unistd::Pid;- use std::os::unix::process::CommandExt;- use std::process::Stdio;-- // Both children trap SIGINT and sleep; first SIGINT does nothing- // (graceful escalation to SIGTERM is also trapped), a second SIGINT- // must SIGKILL the pgids and exit wt promptly.- repo.write_test_config(- r#"-[aliases.stubborn]-one = "sh -c 'trap \"\" INT TERM; echo start-one >> stubborn_one.log; sleep 30'"-two = "sh -c 'trap \"\" INT TERM; echo start-two >> stubborn_two.log; sleep 30'"-"#,- );- repo.commit("initial");-- let mut cmd = repo.wt_command();- cmd.args(["step", "stubborn"]);- cmd.current_dir(repo.root_path());- cmd.stdout(Stdio::null());- cmd.stderr(Stdio::null());- cmd.process_group(0);- let mut child = cmd.spawn().expect("failed to spawn wt step stubborn");-- wait_for_file_content(&repo.root_path().join("stubborn_one.log"));- wait_for_file_content(&repo.root_path().join("stubborn_two.log"));-- let wt_pgid = Pid::from_raw(child.id() as i32);- // First SIGINT — trapped by children; graceful path chews through- // escalation serially.- kill(Pid::from_raw(-wt_pgid.as_raw()), Signal::SIGINT).expect("failed to send first SIGINT");-- std::thread::sleep(std::time::Duration::from_millis(100));-- // Second SIGINT — impatient path should SIGKILL the whole tree now.- kill(Pid::from_raw(-wt_pgid.as_raw()), Signal::SIGINT).expect("failed to send second SIGINT");-- let start = std::time::Instant::now();- let _status = child.wait().expect("failed to wait for wt");- let elapsed = start.elapsed();-- // With only graceful escalation (200ms × 2 grace windows × 2 pgids),- // worst case would be ~800ms. The impatient SIGKILL should be faster- // still. Give 3s headroom for slow CI without being so loose that a- // regression (no SIGKILL on 2nd press) would slip through — that- // regression would leave wt waiting ~60s for the sleeps to finish.+fn test_alias_group_sigint_does_not_escalate(+ repo: TestRepo,+ #[case] concurrent: bool,+ #[case] caught: bool,+ #[case] presses: usize,+) {+ let labels = signal_alias(&repo, concurrent, Some(caught));+ let mut job = AliasSignalJob::spawn_traced(&repo, Stdio::null());+ let children = ready_alias_children(&repo, &labels, job.group());+ crate::common::wait_for_foreground_admission(&repo, &children);+ for press in 1..=presses {+ nix::sys::signal::killpg(job.group(), nix::sys::signal::Signal::SIGINT).unwrap();+ if caught {+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);+ for label in &labels {+ let marker = repo.root_path().join(format!("int-{label}"));+ while std::fs::read_to_string(&marker)+ .unwrap_or_default()+ .lines()+ .count()+ != press+ {+ assert!(+ std::time::Instant::now() < deadline,+ "{label} did not handle interrupt {press} exactly once"+ );+ std::thread::sleep(std::time::Duration::from_millis(10));+ }+ }+ }+ std::thread::sleep(SLEEP_FOR_ABSENCE_CHECK);+ assert!(job.running(), "interrupt {press} killed wt before release");+ ready_alias_children(&repo, &labels, job.group());+ }+ job.release();assert!(- elapsed < std::time::Duration::from_secs(3),- "wt took too long to die after 2nd SIGINT; impatient path may not be firing: {elapsed:?}"- );+ job.wait().success(),+ "caught/ignored interrupts must preserve child success"+ );+ assert!(repo.root_path().join("next").exists());+ if caught {+ for label in &labels {+ assert_eq!(+ std::fs::read_to_string(repo.root_path().join(format!("int-{label}")))+ .unwrap()+ .lines()+ .count(),+ presses+ );+ }+ }}/// Non-UTF-8 bytes and CRLF line endings in child output must not stall the@@ -1677,6 +1624,134 @@ second = "yes 'SECOND-PAYLOAD-BBBBB' | head -n 50000");}+/// Ordinary success and failure both retain EOF semantics, including delayed+/// diagnostics from the failed command and output from healthy siblings.+#[rstest]+#[cfg(unix)]+fn test_alias_failure_preserves_descendant_output(repo: TestRepo) {+ repo.write_test_config(+ r#"[aliases.signal-test]+bad = "(sleep .6; printf 'FAILED_%s' TAIL) & exit 17"+good = "(sleep .6; printf 'LATE_%s' TAIL) & printf EARLY_"+"#,+ );+ let output_path = repo.root_path().join("output");+ let stderr = std::fs::File::create(&output_path).unwrap();+ let mut job = AliasSignalJob::spawn_with_stderr(&repo, stderr.into());+ assert_eq!(job.wait().code(), Some(17));+ let output = std::fs::read_to_string(output_path).unwrap();+ assert!(+ output.contains("EARLY_LATE_TAIL"),+ "healthy output lost: {output}"+ );+ assert!(+ output.contains("FAILED_TAIL"),+ "failure diagnostics lost: {output}"+ );+}++/// Ctrl-C handled successfully by a direct child must not truncate its later+/// descendant output or change the child's successful result.+#[rstest]+#[cfg(unix)]+fn test_alias_caught_sigint_preserves_successful_descendant_output(repo: TestRepo) {+ repo.write_test_config(+ r#"[aliases.signal-test]+one = "trap 'printf handled > caught' INT; echo $$ > worker-pid; printf ready > first-ready; while test ! -f caught; do :; done; (sleep .6; printf 'LATE_%s' TAIL) & printf EARLY_"+two = "echo $$ > second-pid; printf ready > second-ready"+"#,+ );+ let output_path = repo.root_path().join("output");+ let stderr = std::fs::File::create(&output_path).unwrap();+ let mut job = AliasSignalJob::spawn_traced(&repo, stderr.into());+ for marker in ["first-ready", "second-ready"] {+ crate::common::wait_for_file_content(&repo.root_path().join(marker));+ }+ let worker = std::fs::read_to_string(repo.root_path().join("worker-pid")).unwrap();+ let worker = nix::unistd::Pid::from_raw(worker.trim().parse().unwrap());+ assert_eq!(nix::unistd::getpgid(Some(worker)).unwrap(), job.group());+ let second = std::fs::read_to_string(repo.root_path().join("second-pid")).unwrap();+ crate::common::wait_for_foreground_admission(+ &repo,+ &[worker.as_raw(), second.trim().parse().unwrap()],+ );+ nix::sys::signal::killpg(job.group(), nix::sys::signal::Signal::SIGINT).unwrap();+ assert!(job.wait().success());+ let output = std::fs::read_to_string(output_path).unwrap();+ assert!(+ output.contains("EARLY_LATE_TAIL"),+ "caught key truncated output: {output}"+ );+}++/// Cancellation must finish even when an unowned descendant continuously+/// refills an output pipe, retaining buffered bytes and the final diagnostic.+#[rstest]+#[cfg(all(unix, feature = "shell-integration-tests"))]+fn test_alias_cancelled_continuous_writer_flushes_partial_output(repo: TestRepo) {+ std::fs::write(+ repo.root_path().join("writer.py"),+ r#"import os, signal, time+from pathlib import Path+signal.signal(signal.SIGTERM, lambda *_: os._exit(0))+if os.fork():+ while True:+ time.sleep(60)+os.write(1, b'BUFFERED_STDOUT')+os.write(2, b'FINAL_PARTIAL_DIAGNOSTIC')+Path('descendant-ready').write_text('ready')+try:+ while not Path('release').exists():+ os.write(1, b'x' * 8192)+except BrokenPipeError:+ pass+os._exit(0)+"#,+ )+ .unwrap();+ repo.write_test_config(+ r#"[aliases.signal-test]+bad = "exec python3 writer.py"+good = "true"+"#,+ );+ let output_path = repo.root_path().join("output");+ let stderr = std::fs::File::create(&output_path).unwrap();+ let mut job = AliasSignalJob::spawn_with_stderr(&repo, stderr.into());+ crate::common::wait_for_file_content(&repo.root_path().join("descendant-ready"));+ nix::sys::signal::kill(job.pid(), nix::sys::signal::Signal::SIGTERM).unwrap();+ let release = job.release.clone();+ let (stop, done) = std::sync::mpsc::channel::<()>();+ let (status, watchdog_fired) = std::thread::scope(|scope| {+ let watchdog = scope.spawn(move || {+ if matches!(+ done.recv_timeout(std::time::Duration::from_secs(5)),+ Err(std::sync::mpsc::RecvTimeoutError::Timeout)+ ) {+ std::fs::write(release, "release").unwrap();+ true+ } else {+ false+ }+ });+ let status = job.wait();+ let _ = stop.send(());+ (status, watchdog.join().unwrap())+ });+ assert!(+ !watchdog_fired,+ "cancelled reader needed producer release to finish"+ );+ use std::os::unix::process::ExitStatusExt;+ assert!(+ status.signal() == Some(15) || status.code() == Some(143),+ "{status:?}"+ );+ let output = std::fs::read_to_string(output_path).unwrap();+ assert!(output.contains("BUFFERED_STDOUT"));+ assert!(output.contains("FINAL_PARTIAL_DIAGNOSTIC"));+}+/// Pipeline-form aliases (list of steps) run sequentially. A later step/// referencing `{{ vars.X }}` must see vars set by an earlier step —/// `expand_shell_template` reads `vars.*` fresh from git config on each call.diff --git a/tests/integration_tests/step_prune.rs b/tests/integration_tests/step_prune.rsindex d0b591cf9..e3f62fb4f 100644--- a/tests/integration_tests/step_prune.rs+++ b/tests/integration_tests/step_prune.rs@@ -2147,7 +2147,11 @@ fn test_removal_runs_post_remove_after_cleanup_spawn_failure(.into_owned();assert!(!output.status.success(), "{stderr}");if interrupt {- assert_eq!(output.status.code(), Some(130), "{stderr}");+ assert_eq!(+ crate::common::shell_exit_code(&output.status),+ Some(130),+ "{stderr}"+ );assert_eq!(repo.git_output(&["rev-parse", "cleanup-error"]),repo.git_output(&["rev-parse", "main"])@@ -2367,6 +2371,402 @@ touch {0}/completed-{{{{ branch }}}}}}+#[cfg(unix)]+struct PruneSignalJob {+ keeper: std::process::Child,+ child: Option<std::process::Child>,+ release: std::path::PathBuf,+}++#[cfg(unix)]+impl PruneSignalJob {+ fn spawn(mut cmd: std::process::Command, release: std::path::PathBuf) -> Self {+ use std::os::unix::process::CommandExt;+ use std::process::{Command, Stdio};++ let mut job = Self {+ keeper: Command::new("sleep")+ .arg("300")+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .process_group(0)+ .spawn()+ .unwrap(),+ child: None,+ release,+ };+ job.child = Some(+ cmd.stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .process_group(job.keeper.id() as i32)+ .spawn()+ .unwrap(),+ );+ job+ }++ fn output(mut self) -> std::process::Output {+ crate::common::wait_for("parallel prune completion", || {+ self.child.as_mut().unwrap().try_wait().unwrap().is_some()+ });+ self.child.take().unwrap().wait_with_output().unwrap()+ }+}++#[cfg(unix)]+impl Drop for PruneSignalJob {+ fn drop(&mut self) {+ use nix::sys::signal::{Signal, killpg};+ use nix::unistd::Pid;++ // Captured Git commands own separate groups. Release their fixture+ // barriers even when an assertion prevents the normal path.+ let _ = std::fs::write(&self.release, "");+ // The unreaped keeper reserves the group even if wt was collected.+ let _ = killpg(Pid::from_raw(self.keeper.id() as i32), Signal::SIGKILL);+ if let Some(child) = &mut self.child {+ let _ = child.wait();+ }+ let _ = self.keeper.wait();+ }+}++/// A signaled hook cancels the operation before its healthy sibling finishes.+/// Release a later worktree's scan after an owned child actually dies, while+/// its earlier or later sibling remains alive. Input order cannot delay cancellation.+#[cfg(unix)]+#[rstest]+#[case::first("one")]+#[case::later("two")]+fn test_prune_interrupt_stops_later_parallel_removal(mut repo: TestRepo, #[case] dying_role: &str) {+ use std::os::unix::process::ExitStatusExt;+ use worktrunk::trace::{TraceEntryKind, TraceResult, parse_lines};++ repo.commit("initial");+ repo.add_worktree("a");+ let later = repo.add_worktree("c");+ let barriers = repo.home_path().join("barriers");+ std::fs::create_dir(&barriers).unwrap();+ let worker = repo.home_path().join("worker.py");+ std::fs::write(+ &worker,+ r#"import os, pathlib, signal, sys, time+branch, role, directory = sys.argv[1], sys.argv[2], pathlib.Path(sys.argv[3])+def wait(name):+ deadline = time.monotonic() + 15+ while not (directory / name).exists():+ if time.monotonic() > deadline:+ raise RuntimeError(name)+ time.sleep(.01)+if role == 'scan':+ (directory / 'c-scan-blocked').touch()+ wait('release-c')+elif branch == 'a' and role == sys.argv[4]:+ wait('c-scan-blocked')+ wait('a-held-ready')+ (directory / 'dying-info').write_text(f'{os.getpid()} {os.getppid()} {os.getpgrp()}')+ wait('interrupt-child')+ signal.signal(signal.SIGINT, signal.SIG_DFL)+ os.kill(os.getpid(), signal.SIGINT)+elif branch == 'a':+ (directory / 'a-held-ready').touch()+ wait('c-scan-completed')+ # Release the rendezvous even when cancellation correctly prevents c's+ # hook. This is a watchdog, not an assertion about execution speed.+ deadline = time.monotonic() + 2+ while not (directory / 'c-started').exists() and time.monotonic() < deadline:+ time.sleep(.01)+ (directory / 'a-held-finished').touch()+else:+ (directory / 'c-started').touch()+"#,+ )+ .unwrap();+ let worker = shell_escape::unix::escape(worker.to_string_lossy());+ let barriers_arg = shell_escape::unix::escape(barriers.to_string_lossy());+ repo.write_test_config(&format!(+ r#"pre-remove = {{ one = """exec python3 {worker} {{{{ branch }}}} one {barriers_arg} {dying_role}""", two = """exec python3 {worker} {{{{ branch }}}} two {barriers_arg} {dying_role}""" }}"#+ ));+ let wrapper = repo.home_path().join("git-wrapper");+ std::fs::create_dir(&wrapper).unwrap();+ write_prune_git_wrapper(+ &wrapper,+ &which::which("git").unwrap(),+ &format!(+ r#"+case "$PWD:$1:$2" in+ *.c:status:* | *.c:--no-optional-locks:status)+ python3 {worker} c scan {barriers_arg} || exit 2+ run_git "$@"+ status=$?+ touch {barriers_arg}/c-scan-completed+ exit "$status"+ ;;+esac+"#+ ),+ );+ let mut cmd = repo.wt_command();+ prepend_path(&mut cmd, &wrapper);+ cmd.args(["-vv", "step", "prune", "--yes", "--min-age=0s"])+ .env("RAYON_NUM_THREADS", "2")+ .env("RUST_LOG", "worktrunk::wt_trace=debug");+ let job = PruneSignalJob::spawn(cmd, barriers.join("release-c"));+ crate::common::wait_for_file_content(&barriers.join("dying-info"));+ let info: Vec<i32> = std::fs::read_to_string(barriers.join("dying-info"))+ .unwrap()+ .split_whitespace()+ .map(|number| number.parse().unwrap())+ .collect();+ assert_eq!(info[1], job.child.as_ref().unwrap().id() as i32);+ assert_eq!(info[2], job.keeper.id() as i32);+ std::fs::write(barriers.join("interrupt-child"), "").unwrap();+ if dying_role == "one" {+ let trace = repo.root_path().join(".git/wt/logs/trace.jsonl");+ crate::common::wait_for("prune's observed child interruption", || {+ std::fs::read_to_string(&trace).is_ok_and(|records| {+ parse_lines(&records).into_iter().any(|entry| {+ matches!(entry.kind, TraceEntryKind::Command {+ command, result: TraceResult::Completed { success: false }, ..+ } if command.contains(" a one "))+ })+ })+ });+ } else {+ // Waiting for cmd_completed would mask serial input-order waits.+ // A zombie or reaped PID establishes actual death independently.+ let pid = info[0].to_string();+ crate::common::wait_for("later input child's native death", || {+ let state = std::process::Command::new("ps")+ .args(["-o", "stat=", "-p", &pid])+ .output()+ .unwrap();+ let state = String::from_utf8_lossy(&state.stdout);+ state.trim().is_empty() || state.trim().starts_with('Z')+ });+ }+ assert!(barriers.join("c-scan-blocked").exists());+ assert!(barriers.join("a-held-ready").exists());+ assert!(!barriers.join("a-held-finished").exists());+ std::fs::write(barriers.join("release-c"), "").unwrap();+ let output = job.output();+ assert_eq!(+ output.status.signal(),+ Some(nix::libc::SIGINT),+ "{output:?}"+ );+ assert!(barriers.join("c-scan-completed").exists());+ assert!(!barriers.join("c-started").exists(), "{output:?}");+ assert!(+ later.exists(),+ "cancelled prune must retain the later worktree"+ );+ assert!(+ repo.git_output(&["branch", "--format=%(refname:short)"])+ .lines()+ .any(|branch| branch == "c")+ );+}++/// Rendering retains an earlier ordinary failure even when an already-running+/// sibling later interrupts the operation and determines the native exit status.+#[cfg(unix)]+#[rstest]+#[case::ordinary(false)]+#[case::later_interrupt(true)]+fn test_prune_preserves_failure_diagnostic_after_sibling_interrupt(+ mut repo: TestRepo,+ #[case] interrupt: bool,+) {+ use std::os::unix::process::ExitStatusExt;+ use worktrunk::trace::{TraceEntryKind, parse_lines};++ repo.commit("initial");+ let failed = repo.add_worktree("a");+ repo.add_worktree("b");+ let barriers = repo.home_path().join("barriers");+ std::fs::create_dir(&barriers).unwrap();+ let worker = repo.home_path().join("worker.py");+ std::fs::write(+ &worker,+ r#"import os, pathlib, signal, sys, time+branch, role, directory = sys.argv[1], sys.argv[2], pathlib.Path(sys.argv[3])+def wait(name):+ deadline = time.monotonic() + 15+ while not (directory / name).exists():+ if time.monotonic() > deadline:+ raise RuntimeError(name)+ time.sleep(.01)+if branch == 'a' and role == 'one':+ wait('b-one-ready')+ wait('b-two-ready')+ print('a: important refusal', file=sys.stderr)+ sys.exit(3)+elif branch == 'b' and role == 'two':+ (directory / 'b-two-ready').touch()+elif branch == 'b':+ (directory / 'b-one-ready').touch()+ wait('release-b')+ if sys.argv[4] == 'interrupt':+ signal.signal(signal.SIGINT, signal.SIG_DFL)+ os.kill(os.getpid(), signal.SIGINT)+"#,+ )+ .unwrap();+ let worker = shell_escape::unix::escape(worker.to_string_lossy());+ let barriers_arg = shell_escape::unix::escape(barriers.to_string_lossy());+ let mode = if interrupt { "interrupt" } else { "success" };+ repo.write_test_config(&format!(+ r#"pre-remove = {{ one = """exec python3 {worker} {{{{ branch }}}} one {barriers_arg} {mode}""", two = """exec python3 {worker} {{{{ branch }}}} two {barriers_arg} {mode}""" }}"#+ ));+ let mut cmd = repo.wt_command();+ cmd.args(["-vv", "step", "prune", "--yes", "--min-age=0s"])+ .env("RAYON_NUM_THREADS", "2")+ .env(+ "RUST_LOG",+ "worktrunk::wt_trace=debug,worktrunk::trace::emit=debug",+ );+ let job = PruneSignalJob::spawn(cmd, barriers.join("release-b"));+ let trace = repo.root_path().join(".git/wt/logs/trace.jsonl");+ crate::common::wait_for("first prune removal's complete failure", || {+ std::fs::read_to_string(&trace).is_ok_and(|records| {+ parse_lines(&records).into_iter().any(|entry| {+ matches!(entry.kind, TraceEntryKind::Span { name, .. } if name == "prune-remove:a")+ })+ })+ });+ assert!(barriers.join("b-one-ready").exists());+ assert!(barriers.join("b-two-ready").exists());+ std::fs::write(barriers.join("release-b"), "").unwrap();+ let output = job.output();+ if interrupt {+ assert_eq!(+ output.status.signal(),+ Some(nix::libc::SIGINT),+ "{output:?}"+ );+ } else {+ assert_eq!(output.status.code(), Some(3), "{output:?}");+ }+ let stderr = String::from_utf8_lossy(&output.stderr)+ .ansi_strip()+ .into_owned();+ assert!(stderr.contains("a: important refusal"), "{stderr}");+ assert!(+ stderr.contains("pre-remove command failed: one: exit status: 3"),+ "{stderr}"+ );+ assert!(+ stderr.contains("To skip pre-remove hooks, re-run with --no-hooks"),+ "{stderr}"+ );+ assert!(failed.exists());+}++/// An accepted captured Git interrupt cancels the operation even when an+/// earlier hook failure owns its diagnostic. Ordinary Git failures do not.+#[cfg(unix)]+#[rstest]+#[case::ordinary(false)]+#[case::native_interrupt(true)]+fn test_prune_preserves_prior_failure_after_captured_git_error(+ mut repo: TestRepo,+ #[case] interrupt: bool,+) {+ use std::os::unix::process::ExitStatusExt;+ use worktrunk::trace::{TraceEntryKind, parse_lines};++ repo.commit("initial");+ let failed = repo.add_worktree("a");+ repo.add_worktree("b");+ let original = repo.git_output(&["rev-parse", "b"]);+ let barriers = repo.home_path().join("barriers");+ std::fs::create_dir(&barriers).unwrap();+ let worker = repo.home_path().join("worker.py");+ std::fs::write(+ &worker,+ r#"import os, pathlib, signal, sys, time+branch, role, directory = sys.argv[1], sys.argv[2], pathlib.Path(sys.argv[3])+def wait(name):+ deadline = time.monotonic() + 15+ while not (directory / name).exists():+ if time.monotonic() > deadline:+ raise RuntimeError(name)+ time.sleep(.01)+if role == 'delete':+ (directory / 'b-at-delete').touch()+ wait('release-b')+ if sys.argv[4] == 'interrupt':+ signal.signal(signal.SIGINT, signal.SIG_DFL)+ os.kill(os.getpid(), signal.SIGINT)+ sys.exit(7)+elif branch == 'a':+ wait('b-at-delete')+ print('a: important refusal', file=sys.stderr)+ sys.exit(3)+"#,+ )+ .unwrap();+ let worker = shell_escape::unix::escape(worker.to_string_lossy());+ let barriers_arg = shell_escape::unix::escape(barriers.to_string_lossy());+ let mode = if interrupt { "interrupt" } else { "ordinary" };+ repo.write_test_config(&format!(+ r#"pre-remove = """exec python3 {worker} {{{{ branch }}}} hook {barriers_arg}""""#+ ));+ let wrapper = repo.home_path().join("git-wrapper");+ std::fs::create_dir(&wrapper).unwrap();+ write_prune_git_wrapper(+ &wrapper,+ &which::which("git").unwrap(),+ &format!("if has_delete b; then exec python3 {worker} b delete {barriers_arg} {mode}; fi"),+ );+ let mut cmd = repo.wt_command();+ prepend_path(&mut cmd, &wrapper);+ cmd.args(["-vv", "step", "prune", "--yes", "--min-age=0s"])+ .env("RAYON_NUM_THREADS", "2")+ .env(+ "RUST_LOG",+ "worktrunk::wt_trace=debug,worktrunk::trace::emit=debug",+ );+ let job = PruneSignalJob::spawn(cmd, barriers.join("release-b"));+ let trace = repo.root_path().join(".git/wt/logs/trace.jsonl");+ crate::common::wait_for("ordinary failure before captured Git error", || {+ std::fs::read_to_string(&trace).is_ok_and(|records| {+ parse_lines(&records).into_iter().any(|entry| {+ matches!(entry.kind, TraceEntryKind::Span { name, .. } if name == "prune-remove:a")+ })+ })+ });+ assert!(barriers.join("b-at-delete").exists());+ std::fs::write(barriers.join("release-b"), "").unwrap();+ let output = job.output();+ if interrupt {+ assert_eq!(+ output.status.signal(),+ Some(nix::libc::SIGINT),+ "{output:?}"+ );+ } else {+ assert_eq!(output.status.code(), Some(3), "{output:?}");+ }+ let stderr = String::from_utf8_lossy(&output.stderr)+ .ansi_strip()+ .into_owned();+ assert!(stderr.contains("a: important refusal"), "{stderr}");+ assert!(+ stderr.contains("pre-remove command failed: exit status: 3"),+ "{stderr}"+ );+ assert!(+ stderr.contains("To skip pre-remove hooks, re-run with --no-hooks"),+ "{stderr}"+ );+ assert!(failed.exists());+ assert_eq!(repo.git_output(&["rev-parse", "b"]), original);+}+#[cfg(unix)]#[derive(Clone, Copy, PartialEq)]enum SerializedDeleteFailure {@@ -2587,7 +2987,11 @@ fi}}if interrupted {- assert_eq!(output.status.code(), Some(130), "{stderr}");+ assert_eq!(+ crate::common::shell_exit_code(&output.status),+ Some(130),+ "{stderr}"+ );assert!(barriers.join(mode).exists());} else if failure == SerializedDeleteFailure::Moved {assert!(stderr.contains("moved during deletion"), "{stderr}");diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rsindex 6a26438dc..797fef49c 100644--- a/tests/integration_tests/switch.rs+++ b/tests/integration_tests/switch.rs@@ -1286,6 +1286,56 @@ fn test_switch_execute_failure(repo: TestRepo) {);}+/// Suppressing wt's own failure message must preserve a program's native+/// termination signal, distinct from an ordinary exit with the same shell code.+#[rstest]+#[case::interrupt(Some(nix::libc::SIGINT))]+#[case::terminate(Some(nix::libc::SIGTERM))]+#[case::ordinary_exit(None)]+#[cfg(unix)]+fn test_switch_execute_preserves_native_signal(repo: TestRepo, #[case] signal: Option<i32>) {+ use std::os::unix::process::ExitStatusExt;++ let program = r#"import os, signal, sys+number = int(sys.argv[1])+print('child output', flush=True)+if number:+ signal.signal(number, signal.SIG_DFL)+ os.kill(os.getpid(), number)+else:+ os._exit(130)+"#;+ let output = repo+ .wt_command()+ .args([+ "switch",+ "main",+ "--no-cd",+ "--execute",+ "python3",+ "--",+ "-c",+ program,+ ])+ .arg(signal.unwrap_or(0).to_string())+ .output()+ .unwrap();++ assert_eq!(output.status.signal(), signal, "{output:?}");+ assert_eq!(+ output.status.code(),+ signal.is_none().then_some(130),+ "{output:?}"+ );+ assert_eq!(output.stdout, b"child output\n");+ let raw_stderr = String::from_utf8_lossy(&output.stderr);+ let stderr = raw_stderr.ansi_strip();+ assert!(+ !stderr.contains('✗'),+ "unexpected wt failure message: {stderr}"+ );+}+// Execute template expansion tests#[rstest]fn test_switch_execute_template_branch(repo: TestRepo) {diff --git a/tests/integration_tests/switch_picker.rs b/tests/integration_tests/switch_picker.rsindex 87162ee47..657ed58c1 100644--- a/tests/integration_tests/switch_picker.rs+++ b/tests/integration_tests/switch_picker.rs@@ -1067,6 +1067,58 @@ fn test_switch_picker_preview_navigation_and_log_panel(mut repo: TestRepo) {});}+/// The completed diff proves pager selection has finished before checking that+/// an interactive fallback was not launched. All cases run from outside -C.+#[cfg(unix)]+#[rstest]+#[case::fallback("fallback", false)]+#[case::git("git", true)]+#[case::core("core", true)]+fn preview_pager_priority_honors_c(+ mut repo: TestRepo,+ #[case] source: &str,+ #[case] selected: bool,+) {+ repo.run_git(&["remote", "remove", "origin"]);+ let feature = repo.add_worktree("feature");+ std::fs::write(feature.join("pager-test.txt"), "pager test\n").unwrap();+ repo.run_git_in(&feature, &["add", "pager-test.txt"]);+ repo.run_git_in(&feature, &["commit", "-m", "Pager preview"]);+ let pager = repo.home_path().join("selected-pager.sh");+ let fallback = repo.home_path().join("fallback-pager.sh");+ std::fs::write(&pager, "printf 'SELECTED_PAGER\\n'\ncat\n").unwrap();+ std::fs::write(&fallback, "printf 'FALLBACK_PAGER\\n'\ncat\n").unwrap();+ let command =+ |path: &Path| format!("sh {}", shell_escape::unix::escape(path.to_string_lossy()));+ if source == "core" {+ repo.run_git(&["config", "core.pager", &command(&pager)]);+ }+ let mut env_vars = repo.test_env_vars();+ env_vars.retain(|(key, _)| key != "GIT_PAGER" && key != "PAGER");+ env_vars.push(("PAGER".into(), command(&fallback)));+ if source == "git" {+ env_vars.push(("GIT_PAGER".into(), command(&pager)));+ }+ let PickerSession {+ child,+ _master,+ writer,+ rx,+ mut parser,+ } = boot_picker_pty(+ wt_bin().to_str().unwrap(),+ &["-C", repo.root_path().to_str().unwrap(), "switch"],+ repo.home_path(),+ &env_vars,+ );+ send_input_awaiting_content(&writer, &rx, &mut parser, "\x1b[B", Some("feature"));+ wait_for_stable_with_content(&rx, &mut parser, Some("diff --git"));+ let preview = preview_pane_text(parser.screen());+ assert_valid_abort_exit_code(abort_and_exit_code(child, writer, rx));+ assert_eq!(preview.contains("SELECTED_PAGER"), selected, "{preview}");+ assert!(!preview.contains("FALLBACK_PAGER"), "{preview}");+}+/// Seed a fresh CI-status cache entry for `branch` so the picker primes the/// row's `pr_status` at skeleton time (`populate_from_cache`) — making the `pr`/// and `comments` tabs resolve deterministically with no dependence on the live@@ -1126,6 +1178,117 @@ impl Drop for MockReleaseGate {}}+/// Browser launchers must receive the selected URL without writing into skim's+/// terminal. A launcher that starts and fails must not open a second browser.+/// Linux launchers resolve through PATH; macOS uses absolute /usr/bin/open.+#[rstest]+#[case::success(0)]+#[case::failed_launcher(17)]+#[cfg(target_os = "linux")]+fn test_switch_picker_open_url_keeps_launcher_output_out_of_terminal(+ repo: TestRepo,+ #[case] launcher_exit: i32,+) {+ use worktrunk::trace::{TraceEntryKind, TraceResult};++ const URL: &str = "https://github.com/owner/test-repo/pull/42";+ // WSL uses PowerShell's environment transport rather than Unix launcher argv.+ if open::commands(URL)[0].get_program() != "xdg-open" {+ return;+ }+ const STDOUT: &str = "BROWSER_LAUNCHER_STDOUT";+ const STDERR: &str = "BROWSER_LAUNCHER_STDERR";+ repo.run_git(&[+ "remote",+ "set-url",+ "origin",+ "https://github.com/owner/test-repo.git",+ ]);+ let mock_bin = repo.root_path().join("mock-bin");+ std::fs::create_dir_all(&mock_bin).unwrap();+ let pr_json = format!(+ r#"[{{"number":42,"title":"Open this PR","headRefName":"url","author":{{"login":"octocat"}},"isDraft":false,"url":"{URL}","body":"body"}}]"#,+ );+ MockConfig::new("gh")+ .version("gh version 1.0.0 (mock)")+ .command("pr list --state", MockResponse::output(&pr_json))+ .command("pr list --head", MockResponse::output("[]"))+ .command("_default", MockResponse::exit(1))+ .write(&mock_bin);+ for launcher in ["xdg-open", "gio", "gnome-open", "kde-open"] {+ MockConfig::new(launcher)+ .command(+ "_default",+ MockResponse::output(STDOUT)+ .with_stderr(STDERR)+ .with_exit_code(launcher_exit),+ )+ .write(&mock_bin);+ }+ let call_log = tempfile::tempdir().unwrap();+ let mut env_vars = forge_mock_env_vars(&repo, &mock_bin);+ env_vars.push((+ "WORKTRUNK_TEST_MOCK_CALL_LOG_DIR".into(),+ call_log.path().display().to_string(),+ ));+ let PickerSession {+ child,+ _master,+ writer,+ rx,+ mut parser,+ } = boot_picker_pty(+ wt_bin().to_str().unwrap(),+ &["-vv", "switch", "--prs"],+ repo.root_path(),+ &env_vars,+ );+ send_input_awaiting_content(&writer, &rx, &mut parser, ARROW_DOWN, Some("url"));+ {+ let mut writer = writer.lock().unwrap();+ writer.write_all(b"\x1bo").unwrap();+ writer.flush().unwrap();+ }++ // The trace establishes launcher completion before the absence window.+ // Inspect every PTY byte: a later redraw could hide leaked launcher output.+ let trace = repo.root_path().join(".git/wt/logs/trace.jsonl");+ let mut terminal_output = Vec::new();+ let mut completed_at = None;+ crate::common::wait_for(+ "browser launcher completion without terminal output",+ || {+ while let Ok(chunk) = rx.try_recv() {+ terminal_output.extend_from_slice(&chunk);+ parser.process(&chunk);+ }+ if completed_at.is_none() && {+ let records =+ std::fs::read_to_string(&trace).expect("read -vv trace after picker startup");+ worktrunk::trace::parse_lines(&records).iter().any(|entry| {+ matches!(&entry.kind,+ TraceEntryKind::Command {+ command,+ result: TraceResult::Completed { success },+ ..+ } if command.contains("xdg-open") && *success == (launcher_exit == 0))+ })+ } {+ completed_at = Some(Instant::now());+ }+ completed_at.is_some_and(|at| at.elapsed() >= crate::common::SLEEP_FOR_ABSENCE_CHECK)+ },+ );+ assert_valid_abort_exit_code(abort_and_exit_code(child, writer, rx));+ assert_eq!(mock_calls(call_log.path(), "xdg-open"), [URL]);+ for fallback in ["gio", "gnome-open", "kde-open"] {+ assert!(mock_calls(call_log.path(), fallback).is_empty());+ }+ let terminal_output = String::from_utf8_lossy(&terminal_output);+ assert!(!terminal_output.contains(STDOUT), "{terminal_output}");+ assert!(!terminal_output.contains(STDERR), "{terminal_output}");+}+/// Removing a worktree row with alt-x in `--prs` mode must keep the streamed/// PR/MR rows on screen — only the removed worktree row leaves the list, no/// alt-r refresh needed.diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rsindex 126d9621b..8f69ca71e 100644--- a/tests/integration_tests/user_hooks.rs+++ b/tests/integration_tests/user_hooks.rs@@ -19,6 +19,79 @@ use std::fs;use std::thread;use std::time::Duration;+#[rstest]+#[cfg(unix)]+fn test_concurrent_hooks_log_labels_and_pass_cd_directive(repo: TestRepo) {+ repo.write_project_config(+ r#"[pre-start]+first = 'printf CD > "$WORKTRUNK_DIRECTIVE_CD_FILE"'+second = 'true'+"#,+ );+ let cd_file = repo.home_path().join("cd-directive");+ let output = repo+ .wt_command()+ .args(["hook", "pre-start", "--yes"])+ .env("WORKTRUNK_DIRECTIVE_CD_FILE", &cd_file)+ .output()+ .unwrap();+ assert!(output.status.success(), "{output:?}");+ assert_eq!(fs::read_to_string(cd_file).unwrap(), "CD");+ let log = fs::read_to_string(repo.root_path().join(".git/wt/logs/commands.jsonl")).unwrap();+ let mut labels: Vec<String> = log+ .lines()+ .map(|line| {+ let entry: serde_json::Value = serde_json::from_str(line).unwrap();+ assert_eq!(entry["exit"], 0);+ entry["label"].as_str().unwrap().to_owned()+ })+ .collect();+ labels.sort();+ assert_eq!(+ labels,+ ["pre-start project:first", "pre-start project:second"]+ );+}++/// A Git checkout hook interrupts its owned Git parent during worktree creation.+/// The creation error's presentation must retain the command's native status.+#[rstest]+#[case::interrupt("INT", 130)]+#[case::terminate("TERM", 143)]+#[cfg(unix)]+fn test_worktree_creation_preserves_git_hook_interrupt(+ repo: TestRepo,+ #[case] signal: &str,+ #[case] expected: i32,+) {+ use std::os::unix::fs::PermissionsExt;++ let hook = resolve_git_common_dir(repo.root_path()).join("hooks/post-checkout");+ let marker = repo.root_path().join("git-hook-ran");+ fs::create_dir_all(hook.parent().unwrap()).unwrap();+ fs::write(+ &hook,+ format!(+ "#!/bin/sh\nprintf called > {}\nkill -{signal} \"$PPID\"\n",+ shell_escape::escape(marker.to_string_lossy()),+ ),+ )+ .unwrap();+ fs::set_permissions(&hook, fs::Permissions::from_mode(0o755)).unwrap();++ let output = repo+ .wt_command()+ .args(["switch", "--create", "interrupted", "--yes"])+ .output()+ .unwrap();+ assert_eq!(fs::read_to_string(marker).unwrap(), "called");+ assert_eq!(+ crate::common::shell_exit_code(&output.status),+ Some(expected),+ "{output:?}",+ );+}+// ============================================================================// User Post-Create Hook Tests// ============================================================================@@ -518,7 +591,7 @@ fn test_pre_merge_pipeline_aborts_on_signal_exit(repo: TestRepo) {// 128 + SIGTERM (15) = 143assert_eq!(- output.status.code(),+ crate::common::shell_exit_code(&output.status),Some(143),"expected exit 143 (SIGTERM); got {:?}\nstderr: {}",output.status.code(),@@ -2105,10 +2178,7 @@ fn test_standalone_hook_post_start_foreground_inherits_stdin(repo: TestRepo) {);}-/// A foreground hook runs in wt's process group, like an alias (see-/// `test_alias_child_shares_parent_pgroup`). In its own pgroup it isn't the-/// terminal's foreground group, so a tool that touches the tty (turbo,-/// `gum confirm`) gets SIGTTOU and stops — `wt switch` then hangs.+/// Foreground children share the caller's native job group.#[rstest]#[cfg(unix)]fn test_pre_start_hook_shares_parent_pgroup(repo: TestRepo) {@@ -2139,8 +2209,7 @@ fn test_pre_start_hook_shares_parent_pgroup(repo: TestRepo) {.unwrap_or_else(|e| panic!("could not parse pgid {recorded:?}: {e}"));assert_eq!(hook_pgid, wt_pid,- "foreground hook shell must share wt's pgroup (wt pid={wt_pid}); \- got child pgid {hook_pgid}, indicating a new pgroup was created"+ "foreground hook must share its caller group");}@@ -4698,3 +4767,105 @@ fn test_concurrent_hook_does_not_inherit_git_discovery_vars(repo: TestRepo) {assert!(marker.exists(), "concurrent hook did not run");assert_git_env_scrubbed(&marker);}++/// Sibling count must not change access to /dev/tty. Exercise the reported+/// terminal-settings failure, input allocation, and restoration after the job.+#[rstest]+#[cfg(all(unix, feature = "shell-integration-tests"))]+#[case::single(false)]+#[case::concurrent(true)]+fn test_foreground_hook_terminal_job(repo: TestRepo, #[case] concurrent: bool) {+ use crate::common::{configure_pty_command, open_pty, wt_bin};+ use portable_pty::CommandBuilder;+ use std::io::Read;+ use std::sync::mpsc;+ use std::time::{Duration, Instant};++ let probe = "stty -echo < /dev/tty; ps -o pgid= -p $$ > job.txt; ps -o tpgid= -p $$ >> job.txt; stty \"$WT_TEST_TERMINAL_MODES\" < /dev/tty";+ let input = if concurrent {+ "test ! -t 0"+ } else {+ "test -t 0"+ };+ let config = if concurrent {+ format!(+ "[pre-start]\none = '{probe}; {input}'\ntwo = 'stty -echo < /dev/tty; test ! -t 0; ps -o pgid= -p $$ > sibling.txt; stty \"$WT_TEST_TERMINAL_MODES\" < /dev/tty'\n"+ )+ } else {+ format!("pre-start = '{probe}; {input}'\n")+ };+ repo.write_project_config(&config);+ let mut command = CommandBuilder::new("bash");+ command.args([+ "--noprofile",+ "--norc",+ "-c",+ r#"+before=$(stty -g)+export WT_TEST_TERMINAL_MODES="$before"+"$WT_JOB_TEST_BINARY" hook pre-start --yes+result=$?+after=$(stty -g)+[ "$before" = "$after" ] || exit 99+printf 'TERMINAL-RESTORED\n'+exit "$result"+"#,+ ]);+ configure_pty_command(&mut command);+ command.cwd(repo.root_path());+ command.env("WT_JOB_TEST_BINARY", wt_bin());+ command.env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());+ let pair = open_pty();+ let mut child = pair.slave.spawn_command(command).unwrap();+ drop(pair.slave);+ let mut reader = pair.master.try_clone_reader().unwrap();+ let (tx, rx) = mpsc::channel();+ let reading = std::thread::spawn(move || {+ let mut output = Vec::new();+ let _ = reader.read_to_end(&mut output);+ let _ = tx.send(String::from_utf8_lossy(&output).into_owned());+ });+ let deadline = Instant::now() + Duration::from_secs(20);+ let status = loop {+ if let Some(status) = child.try_wait().unwrap() {+ break status;+ }+ if Instant::now() >= deadline {+ if let Some(group) = pair.master.process_group_leader() {+ let _ = nix::sys::signal::killpg(+ nix::unistd::Pid::from_raw(group),+ nix::sys::signal::Signal::SIGKILL,+ );+ }+ let _ = child.kill();+ panic!("foreground hook stopped or hung (concurrent={concurrent})");+ }+ std::thread::sleep(Duration::from_millis(10));+ };+ drop(pair.master);+ let output = rx.recv_timeout(Duration::from_secs(5)).unwrap();+ reading.join().unwrap();+ assert_eq!(status.exit_code(), 0, "{output}");+ assert!(output.contains("TERMINAL-RESTORED"), "{output}");+ let groups: Vec<i32> = fs::read_to_string(repo.root_path().join("job.txt"))+ .unwrap()+ .split_whitespace()+ .map(|group| group.parse().unwrap())+ .collect();+ assert_eq!(groups.len(), 2);+ assert_eq!(+ groups[0], groups[1],+ "child must own the terminal's foreground group"+ );+ if concurrent {+ let sibling: i32 = fs::read_to_string(repo.root_path().join("sibling.txt"))+ .unwrap()+ .trim()+ .parse()+ .unwrap();+ assert_eq!(+ sibling, groups[0],+ "siblings must share one foreground job group"+ );+ }+}diff --git a/tests/snapshots/integration__integration_tests__init__init_bash.snap b/tests/snapshots/integration__integration_tests__init__init_bash.snapindex a913b9e69..0c5b4b41c 100644--- a/tests/snapshots/integration__integration_tests__init__init_bash.snap+++ b/tests/snapshots/integration__integration_tests__init__init_bash.snap@@ -69,11 +69,9 @@ if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; thenwt() {local use_source=falselocal args=()-for arg in "$@"; do- if [[ "$arg" == "--source" ]]; then use_source=true; else args+=("$arg"); fi+ if [[ "$arg" == --source ]]; then use_source=true; else args+=("$arg"); fidone-# Completion mode: call binary directly, no directive files needed.# This check MUST be here (not in the binary) because clap's completion# handler runs before argument parsing.@@ -82,32 +80,85 @@ if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; thenreturnfi- local cd_file exit_code=0- cd_file="$(mktemp)"-- # --source: use cargo run (builds from source)- if [[ "$use_source" == true ]]; then- WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" \- cargo run --bin wt --quiet -- "${args[@]}" || exit_code=$?- else- WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" \- command "${WORKTRUNK_BIN:-wt}" "${args[@]}" || exit_code=$?- fi-- # cd file holds a raw path (no shell escaping needed).+ # Native SIGINT can unwind this body before ordinary cleanup. Capture one+ # cleanup function for both the next prompt and a noninteractive shell exit.+ local cd_file owner cleanup_body exit_trap owns_exit=false prompt_provider prompt_armed=true+ local prompt_value="${PROMPT_COMMAND-}" prompt_present="${PROMPT_COMMAND+x}" prompt_declared=false+ local prompt_declaration prompt_flags+ if builtin declare -p PROMPT_COMMAND >/dev/null 2>&1; then prompt_declared=true; fi+ # Readonly prompts cannot be replaced; allexport would export our callback.+ if [[ $- == *a* ]] || ! (PROMPT_COMMAND="$prompt_value") 2>/dev/null; then prompt_armed=false; fi+ cd_file="$(mktemp)" || return+ owner="_wt_cleanup_${cd_file##*/}"+ owner="${owner//[^a-zA-Z0-9_]/_}"+ exit_trap="$(builtin trap -p EXIT)"+ # trap -p may expose an inherited but inactive EXIT handler in a subshell.+ # Reinstalling it would activate the parent's handler there.+ if [[ ( $BASH_SUBSHELL -eq 0 || -z "$exit_trap" ) && ( $- != *i* || "$prompt_armed" == true ) ]]; then owns_exit=true; fi+ builtin printf -v prompt_provider 'if %s prompt "$?"; then builtin eval %q; else builtin eval %q; fi' "$owner" "$prompt_value" "$prompt_value"+ # %q captures the state after the caller's local variables have unwound.+ builtin printf -v cleanup_body '+ local cd_file=%q owner=%q exit_trap=%q owns_exit=%q+ local prompt_value=%q prompt_present=%q prompt_declared=%q prompt_provider=%q+ ' "$cd_file" "$owner" "$exit_trap" "$owns_exit" "$prompt_value" "$prompt_present" "$prompt_declared" "$prompt_provider"# `builtin cd` bypasses any user `cd` alias or function (e.g. zoxide's- # `alias cd=__zoxide_z`) that would otherwise be substituted into this+ # `alias cd=__zoxide_z`) that would otherwise be substituted into the# function body when it's defined. See #2643.- if [[ -s "$cd_file" ]]; then- builtin cd -- "$(<"$cd_file")"- local cd_exit=$?- if [[ $exit_code -eq 0 ]]; then- exit_code=$cd_exit+ cleanup_body+='+ local event=$1 status=$2 cd_status=0+ if [[ "$owns_exit" == true ]]; then builtin trap - EXIT; fi+ if [[ -s "$cd_file" ]]; then+ builtin cd -- "$(<"$cd_file")" || cd_status=$?fi- fi+ command rm -f "$cd_file"+ if [[ ${PROMPT_COMMAND-} == "$prompt_provider" ]]; then+ if [[ -n "$prompt_present" ]]; then+ PROMPT_COMMAND="$prompt_value"+ else+ local prompt_flags+ prompt_flags="$(builtin declare -p PROMPT_COMMAND 2>/dev/null)" || prompt_flags=+ prompt_flags=${prompt_flags#declare }+ prompt_flags=${prompt_flags%% *}+ if [[ "$prompt_declared" == true ]]; then+ builtin unset "PROMPT_COMMAND[0]"+ else+ builtin unset PROMPT_COMMAND+ fi+ if [[ "$prompt_flags" == *x* ]]; then builtin export PROMPT_COMMAND; fi+ fi+ fi+ if [[ "$owns_exit" == true && -n "$exit_trap" ]]; then builtin eval "$exit_trap"; fi+ builtin unset -f "$owner"+ if [[ "$event" == normal && $status -eq 0 ]]; then+ return "$cd_status"+ else+ return "$status"+ fi+ '+ builtin eval "$owner() { $cleanup_body }"+ if [[ "$prompt_armed" == true ]]; then PROMPT_COMMAND="$prompt_provider"; fi+ # Bash 3.2 only reports an exported, unset variable after assignment.+ prompt_declaration="$(builtin declare -p PROMPT_COMMAND 2>/dev/null)" || prompt_declaration=+ prompt_flags=${prompt_declaration#declare }+ prompt_flags=${prompt_flags%% *}- command rm -f "$cd_file"- return "$exit_code"+ local exit_code=0+ local execution=("${WORKTRUNK_BIN:-wt}" "${args[@]}")+ if [[ "$use_source" == true ]]; then execution=(cargo run --bin wt --quiet -- "${args[@]}"); fi+ if [[ "$owns_exit" == true ]]; then+ local exit_provider="$owner exit \"\$?\""+ if [[ -n "$exit_trap" ]]; then+ local exit_callback=${exit_trap#trap -- }+ exit_callback=${exit_callback% EXIT}+ builtin printf -v exit_provider 'if %s exit "$?"; then builtin eval %s; else builtin eval %s; fi' "$owner" "$exit_callback" "$exit_callback"+ fi+ builtin trap "$exit_provider" EXIT+ fi+ case "$prompt_armed:$prompt_flags" in+ true:*x*) PROMPT_COMMAND="$prompt_value" WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" command "${execution[@]}" || exit_code=$? ;;+ *) WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" command "${execution[@]}" || exit_code=$? ;;+ esac+ if "$owner" normal "$exit_code"; then return 0; else return $?; fi}# Lazy completions - generate on first TAB, then delegate to clap's completerdiff --git a/tests/snapshots/integration__integration_tests__init__init_fish.snap b/tests/snapshots/integration__integration_tests__init__init_fish.snapindex ec0125a34..6c7bad1a8 100644--- a/tests/snapshots/integration__integration_tests__init__init_fish.snap+++ b/tests/snapshots/integration__integration_tests__init__init_fish.snap@@ -81,31 +81,47 @@ function wtendset -l cd_file (mktemp)+ # Older fish unwinds only the function that directly launched an interrupted+ # child. This boundary lets ordinary cleanup run before its caller continues.+ # Newer fish unwinds the whole input line; postexec owns cleanup in that case.+ set -l cleanup_function _wt_cleanup_(string replace -a / _ -- "$cd_file")+ set -l run_function "$cleanup_function"_run+ function $run_function+ command $argv+ end+ function $cleanup_function --on-event fish_postexec --inherit-variable cd_file --inherit-variable cleanup_function --inherit-variable run_function+ set -l cd_exit 0+ # cd file holds a raw path — read with fish builtin (no cat subprocess,+ # safe even if CWD was removed by worktree removal).+ if test -s "$cd_file"+ set -l target (string trim < "$cd_file")+ # `builtin cd` bypasses any user `cd` override (e.g. the zoxide.fish+ # plugin replaces `cd` with a query function that mishandles the `--`+ # separator). Matches the bash/zsh wrappers. (#3159)+ builtin cd -- "$target"+ set cd_exit $status+ end++ command rm -f "$cd_file"+ functions -e $cleanup_function $run_function+ return $cd_exit+ end+# --source: use cargo run (builds from source)if test $use_source = true- env WORKTRUNK_DIRECTIVE_CD_FILE=$cd_file \+ $run_function env WORKTRUNK_DIRECTIVE_CD_FILE=$cd_file \cargo run --bin wt --quiet -- $argselse- env WORKTRUNK_DIRECTIVE_CD_FILE=$cd_file \+ $run_function env WORKTRUNK_DIRECTIVE_CD_FILE=$cd_file \$WORKTRUNK_BIN $argsendset -l exit_code $status- # cd file holds a raw path — read with fish builtin (no cat subprocess,- # safe even if CWD was removed by worktree removal).- if test -s "$cd_file"- set -l target (string trim < "$cd_file")- # `builtin cd` bypasses any user `cd` override (e.g. the zoxide.fish- # plugin replaces `cd` with a query function that mishandles the `--`- # separator). Matches the bash/zsh wrappers. (#3159)- builtin cd -- "$target"- set -l cd_exit $status- if test $exit_code -eq 0- set exit_code $cd_exit- end+ $cleanup_function+ set -l cd_exit $status+ if test $exit_code -eq 0+ set exit_code $cd_exitend-- command rm -f "$cd_file"return $exit_codeenddiff --git a/tests/snapshots/integration__integration_tests__init__init_zsh.snap b/tests/snapshots/integration__integration_tests__init__init_zsh.snapindex 780afff72..acb13b7ec 100644--- a/tests/snapshots/integration__integration_tests__init__init_zsh.snap+++ b/tests/snapshots/integration__integration_tests__init__init_zsh.snap@@ -88,28 +88,28 @@ if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; thenlocal cd_file exit_code=0cd_file="$(mktemp)"- # --source: use cargo run (builds from source)+ local -a execution=("${WORKTRUNK_BIN:-wt}" "${args[@]}")if [[ "$use_source" == true ]]; then- WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" \- cargo run --bin wt --quiet -- "${args[@]}" || exit_code=$?- else- WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" \- command "${WORKTRUNK_BIN:-wt}" "${args[@]}" || exit_code=$?+ execution=(cargo run --bin wt --quiet -- "${args[@]}")fi-- # cd file holds a raw path (no shell escaping needed).- # `builtin cd` bypasses any user `cd` alias or function (e.g. zoxide's- # `alias cd=__zoxide_z`) that would otherwise be substituted into this- # function body when it's defined. See #2643.- if [[ -s "$cd_file" ]]; then- builtin cd -- "$(<"$cd_file")"- local cd_exit=$?- if [[ $exit_code -eq 0 ]]; then- exit_code=$cd_exit+ {+ WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" command "${execution[@]}"+ } always {+ exit_code=$?+ # cd file holds a raw path (no shell escaping needed).+ # `builtin cd` bypasses any user `cd` alias or function (e.g. zoxide's+ # `alias cd=__zoxide_z`) that would otherwise be substituted into this+ # function body when it's defined. See #2643.+ if [[ -s "$cd_file" ]]; then+ builtin cd -- "$(<"$cd_file")"+ local cd_exit=$?+ if [[ $exit_code -eq 0 ]]; then+ exit_code=$cd_exit+ fifi- fi- command rm -f "$cd_file"+ command rm -f "$cd_file"+ } || :return "$exit_code"}