Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Give stdin to the foreground pipeline that owns it (#4451)
Maximilian Roos6cbabac59e1c
diff --git a/src/commands/alias.rs b/src/commands/alias.rsindex 75617a322..e8bc5ddb0 100644--- a/src/commands/alias.rs+++ b/src/commands/alias.rs@@ -38,6 +38,8 @@//! applies `DirectivePassthrough`: the CD directive file is passed through so//! inner `wt` invocations can redirect the parent shell's cwd.+use crate::commands::command_executor::ForegroundStdin;+use std::collections::{BTreeMap, BTreeSet};use std::sync::LazyLock;@@ -744,7 +746,11 @@ fn run_alias(sourced_steps.push(SourcedStep { step, source });}}- sourced_steps_to_foreground(sourced_steps, &PipelineKind::Alias { name: alias_name })+ sourced_steps_to_foreground(+ sourced_steps,+ &PipelineKind::Alias { name: alias_name },+ ForegroundStdin::Inherit,+ )};execute_pipeline_foreground(&foreground_steps, repo, &wt_path, FailureStrategy::FailFast)diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rsindex b6c83388a..ad1ca568a 100644--- a/src/commands/command_executor.rs+++ b/src/commands/command_executor.rs@@ -126,9 +126,21 @@ impl PipelineKind {}}+/// Whether a foreground pipeline owns the caller's input.+///+/// An exclusive pipeline inherits stdin for interactive input. A pipeline+/// running alongside another input consumer must read EOF instead. Foreground+/// process-group membership is independent of this input allocation.+#[derive(Clone, Copy, Debug)]+pub enum ForegroundStdin {+ Inherit,+ Closed,+}+/// A pipeline step ready for foreground execution, with rendering / error policy.pub struct ForegroundStep {pub step: PreparedStep,+ pub stdin: ForegroundStdin,/// Which pipeline this step belongs to. Drives how each command is/// announced before execution: hooks render a per-command "Running …"/// line plus the bash gutter; aliases stay silent (the caller emits one@@ -178,6 +190,7 @@ pub struct CommandContext<'a> {pub branch: Option<&'a str>,pub worktree_path: &'a Path,pub yes: bool,+ pub stdin: ForegroundStdin,}impl<'a> CommandContext<'a> {@@ -194,9 +207,16 @@ impl<'a> CommandContext<'a> {branch,worktree_path,yes,+ stdin: ForegroundStdin::Inherit,}}+ /// Set input ownership when the caller runs this pipeline concurrently.+ pub fn with_stdin(mut self, stdin: ForegroundStdin) -> Self {+ self.stdin = stdin;+ self+ }+/// Get the project identifier for per-project config lookup.////// Uses the remote URL if available, otherwise the canonical repository path.@@ -574,17 +594,13 @@ fn run_one_command(};announce_command(cmd, &fg_step.announce, fg_step.source, &command_str);- // Foreground steps inherit the parent's stdin so an interactive child keeps- // its controlling terminal — a `pre-*` hook can prompt (e.g. `gum confirm`- // before `mise trust`), and an alias body's `wt switch` picker keeps the- // tty. Nothing is ever piped in: template variables are how a hook reads- // its context, whatever form it runs in.let log_label = fg_step.announce.log_label(cmd);let result = execute_shell_command(wt_path,&command_str,log_label.as_deref(),directives.clone(),+ fg_step.stdin,fg_step.redirect_stdout_to_stderr,fg_step.announce.is_hook(),);diff --git a/src/commands/hook_plan.rs b/src/commands/hook_plan.rsindex d176febbb..7723d6697 100644--- a/src/commands/hook_plan.rs+++ b/src/commands/hook_plan.rs@@ -390,7 +390,7 @@ pub fn execute_planned_hook(hook_type,display_path: display_path.map(Path::to_path_buf),};- let foreground = sourced_steps_to_foreground(sourced, &kind);+ let foreground = sourced_steps_to_foreground(sourced, &kind, ctx.stdin);execute_pipeline_foreground(&foreground, ctx.repo, ctx.worktree_path, failure_strategy).map_err(add_hook_skip_hint)}diff --git a/src/commands/hooks.rs b/src/commands/hooks.rsindex df51fe3a2..47f7db773 100644--- a/src/commands/hooks.rs+++ b/src/commands/hooks.rs@@ -66,6 +66,8 @@//! (test isolation); user config (`~/.config/worktrunk/config.toml`) is global//! and unaffected.+use crate::commands::command_executor::ForegroundStdin;+use std::path::{Path, PathBuf};use anyhow::Context;@@ -652,15 +654,14 @@ fn spawn_hook_pipeline_quiet(repo: &Repository, pipeline: PendingPipeline) -> an/// Every step gets the same `DirectivePassthrough::inherit_from_env()`; the/// EXEC passthrough the `source` field used to select is gone (#3977).///-/// Foreground steps — hook and alias alike — inherit the parent's stdin so an-/// interactive child keeps the controlling terminal (a `pre-*` hook can prompt;-/// an alias body's `wt switch` picker works). The forms that can't be-/// interactive get a closed stdin rather than a substitute payload: concurrent-/// children (they'd race for the terminal) and detached (`post-*`) hooks (there-/// is none). Template variables carry the context in every form.+/// The caller supplies input ownership: exclusive pipelines inherit stdin,+/// while pipelines running alongside other input consumers read EOF.+/// Concurrent groups always close stdin, whatever the outer pipeline's policy.+/// Template variables carry the context in every form.pub(crate) fn sourced_steps_to_foreground(sourced_steps: Vec<SourcedStep>,kind: &PipelineKind,+ stdin: ForegroundStdin,) -> Vec<ForegroundStep> {sourced_steps.into_iter()@@ -674,6 +675,7 @@ pub(crate) fn sourced_steps_to_foreground(};ForegroundStep {step: sourced.step,+ stdin,announce: kind.clone(),source: sourced.source,redirect_stdout_to_stderr,@@ -724,7 +726,7 @@ pub(crate) fn run_hooks_foreground(display_path: crate::output::pre_hook_display_path(ctx.worktree_path).map(Path::to_path_buf),};- let foreground_steps = sourced_steps_to_foreground(sourced_steps, &kind);+ let foreground_steps = sourced_steps_to_foreground(sourced_steps, &kind, ctx.stdin);execute_pipeline_foreground(&foreground_steps,diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex 60fb898fe..7e0a4ee4e 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -103,6 +103,8 @@ mod progressive_handler;mod prs;mod summary;+use crate::commands::command_executor::ForegroundStdin;+use std::cell::RefCell;use std::io::IsTerminal;use std::path::{Path, PathBuf};@@ -387,6 +389,7 @@ impl AltXRemover {handle_remove_output(result,RemovalExecution::Silent,+ ForegroundStdin::Closed,&plan,/* quiet */ true,&mut announcer,diff --git a/src/commands/remove.rs b/src/commands/remove.rsindex ed597db7a..9a2a495ab 100644--- a/src/commands/remove.rs+++ b/src/commands/remove.rs@@ -4,6 +4,8 @@//! Target failures are reported independently; later targets still run and//! the batch exits unsuccessfully. An interrupt cancels the batch immediately.+use crate::commands::command_executor::ForegroundStdin;+use std::collections::HashSet;use std::path::Path;@@ -483,6 +485,7 @@ pub fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()>let fate = handle_remove_output(&result,removal_execution(args.foreground),+ ForegroundStdin::Inherit,&plan,false,&mut announcer,@@ -545,6 +548,7 @@ pub fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()>let fate = handle_remove_output(result,removal_execution(args.foreground),+ ForegroundStdin::Inherit,&plan,false,&mut announcer,diff --git a/src/commands/step/prune.rs b/src/commands/step/prune.rsindex 11c8dbbcd..5ec818bd9 100644--- a/src/commands/step/prune.rs+++ b/src/commands/step/prune.rs@@ -19,6 +19,8 @@//! current worktree is removed last, after the fan-out, because its removal//! cd's the shell to the primary.+use crate::commands::command_executor::ForegroundStdin;+use std::collections::{HashMap, HashSet};use std::fs;use std::path::{Path, PathBuf};@@ -351,7 +353,12 @@ fn try_remove(} else {RemovalExecution::Background(BackgroundFallbackMode::SynchronousForNonCurrent)};- let fate = handle_remove_output(&plan, execution, ctx.hook_plan, true, &mut announcer)?;+ let stdin = if needs_write {+ ForegroundStdin::Inherit+ } else {+ ForegroundStdin::Closed+ };+ let fate = handle_remove_output(&plan, execution, stdin, ctx.hook_plan, true, &mut announcer)?;announcer.flush()?;let branch_deleted = fate.deleted();// A branch-only candidate that kept its branch removed nothing at all —diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex 1754a2487..84706f2e7 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -12,7 +12,7 @@ use worktrunk::shell_exec::{Cmd, shell_cwd};use worktrunk::styling::{eprint, format_bash_with_gutter, stderr};use crate::commands::command_executor::CommandContext;-use crate::commands::command_executor::FailureStrategy;+use crate::commands::command_executor::{FailureStrategy, ForegroundStdin};use crate::commands::hook_plan::{ApprovedHookPlan, execute_planned_hook, register_planned};use crate::commands::hooks::HookAnnouncer;use crate::commands::process::{@@ -1222,11 +1222,12 @@ pub fn execute_user_command(pub fn handle_remove_output(plan: &RemovalPlan,execution: RemovalExecution,+ stdin: ForegroundStdin,hook_plan: &ApprovedHookPlan,quiet: bool,announcer: &mut HookAnnouncer<'_>,) -> anyhow::Result<BranchFate> {- handle_remove_output_inner(plan, execution, hook_plan, quiet, false, announcer)+ handle_remove_output_inner(plan, execution, stdin, hook_plan, quiet, false, announcer)}/// Merge may select a source containing another checkout, including the@@ -1242,6 +1243,7 @@ pub fn handle_merge_remove_output(handle_remove_output_inner(plan,RemovalExecution::Background(BackgroundFallbackMode::Detached),+ ForegroundStdin::Inherit,hook_plan,false,true,@@ -1252,6 +1254,7 @@ pub fn handle_merge_remove_output(fn handle_remove_output_inner(plan: &RemovalPlan,execution: RemovalExecution,+ stdin: ForegroundStdin,hook_plan: &ApprovedHookPlan,quiet: bool,protect_nested_worktrees: bool,@@ -1283,6 +1286,7 @@ fn handle_remove_output_inner(branch_checked_out_at: branch_checked_out_at.as_ref(),hook_plan,execution,+ stdin,protect_nested_worktrees,},announcer,@@ -1813,6 +1817,7 @@ struct WorktreeRemovalContext<'a> {/// no `ProjectConfig` snapshot to thread.hook_plan: &'a ApprovedHookPlan,execution: RemovalExecution,+ stdin: ForegroundStdin,protect_nested_worktrees: bool,}@@ -1846,7 +1851,8 @@ fn execute_pre_remove_hooks_if_needed(ctx.branch_name,ctx.worktree_path,false, // yes=false for CommandContext (not approval-related)- );+ )+ .with_stdin(ctx.stdin);let display_path = if ctx.changed_directory {None} else {@@ -2202,15 +2208,10 @@ fn remove_removed_worktree_silently(////// ## Stdin///-/// 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 be-/// interactive close stdin instead, in their own spawn paths: concurrent groups-/// in `output/concurrent.rs`, detached `post-*` pipelines in-/// `commands/run_pipeline.rs`.+/// Exclusive pipelines inherit stdin. Picker removals and parallel prune hooks+/// close it so they cannot consume another input owner's bytes. Process-group+/// membership and signal forwarding are independent of this input policy.+/// Hook context comes from template variables.////// ## Directive files///@@ -2256,6 +2257,7 @@ pub fn execute_shell_command(command: &str,command_log_label: Option<&str>,directives: DirectivePassthrough,+ stdin: ForegroundStdin,redirect_stdout_to_stderr: bool,scrub_git_discovery: bool,) -> anyhow::Result<()> {@@ -2287,10 +2289,10 @@ pub fn execute_shell_command(cmd = cmd.external(label);}- // Inherit the parent's stdin so interactive children (e.g. TUI pickers,- // a `gum confirm` in a hook body) keep their controlling terminal — see- // the "Stdin" section of this function's docs.- cmd = cmd.inherit_stdin();+ cmd = match stdin {+ ForegroundStdin::Inherit => cmd.inherit_stdin(),+ ForegroundStdin::Closed => cmd.stdin(Stdio::null()),+ };if let Some(path) = directives.cd_file {cmd = cmd.directive_cd_file(path);diff --git a/tests/integration_tests/step_prune.rs b/tests/integration_tests/step_prune.rsindex 24add5e5c..6fa5756e6 100644--- a/tests/integration_tests/step_prune.rs+++ b/tests/integration_tests/step_prune.rs@@ -2364,6 +2364,8 @@ fn test_prune_stages_concurrently_without_packed_ref_contention(#[rstest]fn test_prune_pre_remove_hooks_run_concurrently(mut repo: TestRepo) {use path_slash::PathExt as _;+ use std::io::Write;+ use std::process::Stdio;repo.commit("initial");let worktrees: Vec<_> = ["parallel-a", "parallel-b"]@@ -2384,22 +2386,38 @@ while [ ! -f {0}/started-parallel-a ] || [ ! -f {0}/started-parallel-b ]; dofisleep 0.05done+cat > {0}/stdin-{{{{ branch }}}}[ -e .git ] || exit 1touch {0}/completed-{{{{ branch }}}}""""#,barriers.to_slash_lossy()));- let output = repo+ let mut child = repo.wt_command().env("RAYON_NUM_THREADS", "2").args(["step", "prune", "--yes", "--min-age=0s"])- .output()+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()+ .unwrap();+ child+ .stdin+ .take()+ .unwrap()+ .write_all(b"parent input must stay unread\n").unwrap();+ let output = child.wait_with_output().unwrap();let stderr = String::from_utf8_lossy(&output.stderr);assert!(output.status.success(), "{stderr}");let branches = repo.git_output(&["branch", "--format=%(refname:short)"]);for (name, path) in worktrees {assert!(barriers.join(format!("completed-{name}")).exists());+ assert_eq!(+ std::fs::read_to_string(barriers.join(format!("stdin-{name}"))).unwrap(),+ "",+ "parallel removals must not compete for parent stdin"+ );assert!(!path.exists());assert!(!branches.lines().any(|branch| branch == name));}@@ -3420,3 +3438,55 @@ fn test_prune_retains_branch_checked_out_in_another_worktree(mut repo: TestRepo)"summary must count the pruned entry, not the retained branch:\n{stderr}",);}++/// Exclusive removals own input: foreground cleanup serializes with the other+/// candidates, and the current worktree is deferred until the fan-out finishes.+#[rstest]+#[case::foreground(true)]+#[case::current_worktree(false)]+fn test_prune_exclusive_pre_remove_hooks_inherit_stdin(+ mut repo: TestRepo,+ #[case] foreground: bool,+) {+ use path_slash::PathExt as _;+ use std::io::Write;+ use std::process::Stdio;++ repo.commit("initial");+ let worktree = repo.add_worktree("exclusive");+ let input_marker = repo.home_path().join("hook-input.txt");+ repo.write_test_config(&format!(+ "pre-remove = 'cat > {}'",+ input_marker.to_slash_lossy()+ ));+ let mut command = repo.wt_command();+ command.args(["step", "prune", "--yes", "--min-age=0s"]);+ if foreground {+ command.arg("--foreground");+ } else {+ command.current_dir(&worktree);+ }+ let mut child = command+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()+ .unwrap();+ child+ .stdin+ .take()+ .unwrap()+ .write_all(b"exclusive hook input\n")+ .unwrap();+ let output = child.wait_with_output().unwrap();+ assert!(+ output.status.success(),+ "{}",+ String::from_utf8_lossy(&output.stderr)+ );+ assert_eq!(+ std::fs::read_to_string(input_marker).unwrap(),+ "exclusive hook input\n"+ );+ crate::common::assert_worktree_removed(&worktree);+}