Skip to content

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

Fix stream interleaving between stdout and stderr prompts

Maximilian Roos3c877dd613bb
diff --git a/src/commands/command_approval.rs b/src/commands/command_approval.rs
index 652f0f434..ee8dee7a0 100644
--- a/src/commands/command_approval.rs
+++ b/src/commands/command_approval.rs
@@ -83,6 +83,11 @@ fn prompt_for_batch_approval(commands: &[&Command], project_id: &str) -> std::io
let count = commands.len();
let plural = if count == 1 { "" } else { "s" };
+ // CRITICAL: Flush stdout before writing to stderr to prevent stream interleaving
+ // In directive mode, emits NUL to flush shell wrapper's read buffer
+ // In interactive mode, just flushes normally
+ crate::output::flush_for_stderr_prompt()?;
+
eprintln!();
eprintln!(
"{WARNING_EMOJI} {WARNING}{WARNING_BOLD}{project_name}{WARNING_BOLD:#}{WARNING} wants to execute {WARNING_BOLD}{count}{WARNING_BOLD:#}{WARNING} command{plural}:{WARNING:#}"
diff --git a/src/commands/configure_shell.rs b/src/commands/configure_shell.rs
index 953f82a6e..535e8dd92 100644
--- a/src/commands/configure_shell.rs
+++ b/src/commands/configure_shell.rs
@@ -345,8 +345,14 @@ fn configure_fish_file(
fn prompt_for_confirmation(results: &[ConfigureResult]) -> Result<bool, String> {
use anstyle::Style;
+ use std::io::Write;
use worktrunk::styling::{HINT_EMOJI, eprint, eprintln};
+ // CRITICAL: Flush stdout before writing to stderr to prevent stream interleaving
+ // In directive mode, emits NUL to flush shell wrapper's read buffer
+ // In interactive mode, just flushes normally
+ crate::output::flush_for_stderr_prompt().map_err(|e| e.to_string())?;
+
// Interactive prompts go to stderr so they appear even when stdout is redirected
eprintln!();
eprintln!("{HINT_EMOJI} {CYAN_BOLD}Configuration changes:{CYAN_BOLD:#}");
diff --git a/src/output/directive.rs b/src/output/directive.rs
index ffefc0cdf..fef393c00 100644
--- a/src/output/directive.rs
+++ b/src/output/directive.rs
@@ -101,6 +101,13 @@ impl DirectiveOutput {
io::stdout().flush()
}
+ pub fn flush_for_stderr_prompt(&mut self) -> io::Result<()> {
+ // In directive mode, emit NUL to flush buffered stdout through shell's read loop
+ // The shell wrapper uses `while read -d '' chunk` which buffers until NUL arrives
+ write!(io::stdout(), "\0")?;
+ io::stdout().flush()
+ }
+
pub fn terminate_output(&mut self) -> io::Result<()> {
// Write NUL terminator to separate command output from subsequent directives
write!(io::stdout(), "\0")?;
diff --git a/src/output/global.rs b/src/output/global.rs
index d5463830f..8d0c650cf 100644
--- a/src/output/global.rs
+++ b/src/output/global.rs
@@ -177,6 +177,23 @@ pub fn flush() -> io::Result<()> {
})
}
+/// Flush stdout before showing stderr prompt
+///
+/// This is a special-purpose function for approval prompts that write to stderr.
+/// In directive mode, emits a NUL terminator to flush buffered stdout through the
+/// shell wrapper's `read -d ''` loop. In interactive mode, just flushes normally.
+///
+/// Context: The shell wrapper (templates/bash.sh) uses `while read -d '' chunk` to parse
+/// stdout. This buffers stdout until a NUL byte arrives. Without this NUL, previous
+/// stdout messages (like success) stay buffered while stderr (prompts) passes through,
+/// causing incorrect ordering.
+pub fn flush_for_stderr_prompt() -> io::Result<()> {
+ OUTPUT_CONTEXT.with(|ctx| match &mut *ctx.borrow_mut() {
+ OutputHandler::Interactive(i) => i.flush_for_stderr_prompt(),
+ OutputHandler::Directive(d) => d.flush_for_stderr_prompt(),
+ })
+}
+
/// Terminate command output
///
/// In directive mode, writes a NUL terminator to separate command output from
diff --git a/src/output/interactive.rs b/src/output/interactive.rs
index a1e38c4fd..458ad538e 100644
--- a/src/output/interactive.rs
+++ b/src/output/interactive.rs
@@ -105,6 +105,11 @@ impl InteractiveOutput {
Ok(())
}
+ pub fn flush_for_stderr_prompt(&mut self) -> io::Result<()> {
+ // In interactive mode, just flush normally - no NUL needed
+ stdout().flush()
+ }
+
pub fn terminate_output(&mut self) -> io::Result<()> {
// No-op in interactive mode - no NUL terminators needed
Ok(())
diff --git a/src/output/mod.rs b/src/output/mod.rs
index 738461d19..414c1ae5a 100644
--- a/src/output/mod.rs
+++ b/src/output/mod.rs
@@ -63,8 +63,8 @@ pub mod interactive;
// Re-export the public API
pub use global::{
- OutputMode, change_directory, execute, flush, gutter, hint, info, initialize, progress,
- success, terminate_output, warning,
+ OutputMode, change_directory, execute, flush, flush_for_stderr_prompt, gutter, hint, info,
+ initialize, progress, success, terminate_output, warning,
};
// blank_line is only used by select command which is Unix-only
diff --git a/templates/posix_directives.sh b/templates/posix_directives.sh
index 57a7104ac..e400bfc36 100644
--- a/templates/posix_directives.sh
+++ b/templates/posix_directives.sh
@@ -32,7 +32,8 @@ _wt_exec() {
elif [[ "$chunk" == __WORKTRUNK_EXEC__* ]]; then
exec_cmd="${chunk#__WORKTRUNK_EXEC__}"
else
- printf '%s\n' "$chunk"
+ # Regular output - print it with newline (ignore empty chunks)
+ [[ -n "$chunk" ]] && printf '%s\n' "$chunk"
fi
done <"$fifo_path"
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_mixed_stdout_stderr_bash.snap b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_mixed_stdout_stderr_bash.snap
index 83da391ca..2f7008a56 100644
--- a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_mixed_stdout_stderr_bash.snap
+++ b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_mixed_stdout_stderr_bash.snap
@@ -13,7 +13,6 @@ expression: output.normalized()
[check1] stderr line 3
[check1] stdout complete
[check1] stderr complete
-
πŸ”„ Running pre-merge check2:
  [WORKSPACE]/tests/fixtures/mixed-output.sh check2 3
@@ -25,7 +24,6 @@ expression: output.normalized()
[check2] stderr line 3
[check2] stdout complete
[check2] stderr complete
-
πŸ”„ Merging 1 commit to main @ [HASH] (no commit/squash/rebase needed)
  * [HASH] (HEAD -> feature) Add feature
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_mixed_stdout_stderr_zsh.snap b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_mixed_stdout_stderr_zsh.snap
index 83da391ca..2f7008a56 100644
--- a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_mixed_stdout_stderr_zsh.snap
+++ b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_mixed_stdout_stderr_zsh.snap
@@ -13,7 +13,6 @@ expression: output.normalized()
[check1] stderr line 3
[check1] stdout complete
[check1] stderr complete
-
πŸ”„ Running pre-merge check2:
  [WORKSPACE]/tests/fixtures/mixed-output.sh check2 3
@@ -25,7 +24,6 @@ expression: output.normalized()
[check2] stderr line 3
[check2] stdout complete
[check2] stderr complete
-
πŸ”„ Merging 1 commit to main @ [HASH] (no commit/squash/rebase needed)
  * [HASH] (HEAD -> feature) Add feature
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_pre_merge_failure_bash.snap b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_pre_merge_failure_bash.snap
index 218fd4dae..e948f19d8 100644
--- a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_pre_merge_failure_bash.snap
+++ b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_pre_merge_failure_bash.snap
@@ -6,7 +6,6 @@ expression: output.normalized()
  echo 'βœ“ Code formatting check passed'
βœ“ Code formatting check passed
-
πŸ”„ Running pre-merge test:
  echo 'βœ— Test suite failed: 3 tests failing' && exit 1
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_pre_merge_failure_zsh.snap b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_pre_merge_failure_zsh.snap
index 218fd4dae..e948f19d8 100644
--- a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_pre_merge_failure_zsh.snap
+++ b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_pre_merge_failure_zsh.snap
@@ -6,7 +6,6 @@ expression: output.normalized()
  echo 'βœ“ Code formatting check passed'
βœ“ Code formatting check passed
-
πŸ”„ Running pre-merge test:
  echo 'βœ— Test suite failed: 3 tests failing' && exit 1
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_pre_merge_success_bash.snap b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_pre_merge_success_bash.snap
index 238fc6b08..ead65e4d7 100644
--- a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_pre_merge_success_bash.snap
+++ b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_pre_merge_success_bash.snap
@@ -6,17 +6,14 @@ expression: output.normalized()
  echo 'βœ“ Code formatting check passed'
βœ“ Code formatting check passed
-
πŸ”„ Running pre-merge lint:
  echo 'βœ“ Linting passed - no warnings'
βœ“ Linting passed - no warnings
-
πŸ”„ Running pre-merge test:
  echo 'βœ“ All 47 tests passed in 2.3s'
βœ“ All 47 tests passed in 2.3s
-
πŸ”„ Merging 1 commit to main @ [HASH] (no commit/squash/rebase needed)
  * [HASH] (HEAD -> feature) Add feature
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_pre_merge_success_zsh.snap b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_pre_merge_success_zsh.snap
index 238fc6b08..ead65e4d7 100644
--- a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_pre_merge_success_zsh.snap
+++ b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_pre_merge_success_zsh.snap
@@ -6,17 +6,14 @@ expression: output.normalized()
  echo 'βœ“ Code formatting check passed'
βœ“ Code formatting check passed
-
πŸ”„ Running pre-merge lint:
  echo 'βœ“ Linting passed - no warnings'
βœ“ Linting passed - no warnings
-
πŸ”„ Running pre-merge test:
  echo 'βœ“ All 47 tests passed in 2.3s'
βœ“ All 47 tests passed in 2.3s
-
πŸ”„ Merging 1 commit to main @ [HASH] (no commit/squash/rebase needed)
  * [HASH] (HEAD -> feature) Add feature
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__switch_with_hooks_zsh.snap b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__switch_with_hooks_zsh.snap
index 8be679a0d..856830a18 100644
--- a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__switch_with_hooks_zsh.snap
+++ b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__switch_with_hooks_zsh.snap
@@ -6,12 +6,10 @@ expression: output.normalized()
  echo 'Installing dependencies...'
Installing dependencies...
-
πŸ”„ Running post-create:
  echo 'Building project...'
Building project...
-
βœ… Created new worktree for feature-hooks from main at [TMPDIR]/test-repo.feature-hooks
πŸ”„ Running post-start server:
  echo 'Starting dev server on port 3000'
diff --git a/tests/snapshots/integration__integration_tests__init__init_bash.snap b/tests/snapshots/integration__integration_tests__init__init_bash.snap
index bd51bf447..e3353e395 100644
--- a/tests/snapshots/integration__integration_tests__init__init_bash.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_bash.snap
@@ -16,7 +16,7 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpiqC07O/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpGSj2lQ/test-config.toml
---
success: true
exit_code: 0
@@ -63,7 +63,8 @@ _wt_exec() {
elif [[ "$chunk" == __WORKTRUNK_EXEC__* ]]; then
exec_cmd="${chunk#__WORKTRUNK_EXEC__}"
else
- printf '%s\n' "$chunk"
+ # Regular output - print it with newline (ignore empty chunks)
+ [[ -n "$chunk" ]] && printf '%s\n' "$chunk"
fi
done <"$fifo_path"
diff --git a/tests/snapshots/integration__integration_tests__init__init_zsh.snap b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
index 4e8c8b8a6..f2e1e04ec 100644
--- a/tests/snapshots/integration__integration_tests__init__init_zsh.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
@@ -16,7 +16,7 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpPLmErG/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpdnJurE/test-config.toml
---
success: true
exit_code: 0
@@ -63,7 +63,8 @@ _wt_exec() {
elif [[ "$chunk" == __WORKTRUNK_EXEC__* ]]; then
exec_cmd="${chunk#__WORKTRUNK_EXEC__}"
else
- printf '%s\n' "$chunk"
+ # Regular output - print it with newline (ignore empty chunks)
+ [[ -n "$chunk" ]] && printf '%s\n' "$chunk"
fi
done <"$fifo_path"