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.rsindex 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::iolet 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.rsindex 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 redirectedeprintln!();eprintln!("{HINT_EMOJI} {CYAN_BOLD}Configuration changes:{CYAN_BOLD:#}");diff --git a/src/output/directive.rs b/src/output/directive.rsindex 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 directiveswrite!(io::stdout(), "\0")?;diff --git a/src/output/global.rs b/src/output/global.rsindex 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 fromdiff --git a/src/output/interactive.rs b/src/output/interactive.rsindex 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 neededOk(())diff --git a/src/output/mod.rs b/src/output/mod.rsindex 738461d19..414c1ae5a 100644--- a/src/output/mod.rs+++ b/src/output/mod.rs@@ -63,8 +63,8 @@ pub mod interactive;// Re-export the public APIpub 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-onlydiff --git a/templates/posix_directives.sh b/templates/posix_directives.shindex 57a7104ac..e400bfc36 100644--- a/templates/posix_directives.sh+++ b/templates/posix_directives.sh@@ -32,7 +32,8 @@ _wt_exec() {elif [[ "$chunk" == __WORKTRUNK_EXEC__* ]]; thenexec_cmd="${chunk#__WORKTRUNK_EXEC__}"else- printf '%s\n' "$chunk"+ # Regular output - print it with newline (ignore empty chunks)+ [[ -n "$chunk" ]] && printf '%s\n' "$chunk"fidone <"$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.snapindex 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-π [36mRunning pre-merge [1mcheck2[0m:[0m[40m [0m [1m[34m[WORKSPACE]/tests/fixtures/mixed-output.sh[0m check2 3[0m@@ -25,7 +24,6 @@ expression: output.normalized()[check2] stderr line 3[check2] stdout complete[check2] stderr complete-π [36mMerging 1 commit to [1m[36mmain[0m[36m @ [2m[36m[HASH][0m[0m (no commit/squash/rebase needed)[40m [0m * [33m[HASH][m[33m ([m[1;36mHEAD[m[33m -> [m[1;32mfeature[m[33m)[m Add featurediff --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.snapindex 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-π [36mRunning pre-merge [1mcheck2[0m:[0m[40m [0m [1m[34m[WORKSPACE]/tests/fixtures/mixed-output.sh[0m check2 3[0m@@ -25,7 +24,6 @@ expression: output.normalized()[check2] stderr line 3[check2] stdout complete[check2] stderr complete-π [36mMerging 1 commit to [1m[36mmain[0m[36m @ [2m[36m[HASH][0m[0m (no commit/squash/rebase needed)[40m [0m * [33m[HASH][m[33m ([m[1;36mHEAD[m[33m -> [m[1;32mfeature[m[33m)[m Add featurediff --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.snapindex 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()[40m [0m [1m[34mecho[0m [32m'β Code formatting check passed'[0m[0mβ Code formatting check passed-π [36mRunning pre-merge [1mtest[0m:[0m[40m [0m [1m[34mecho[0m [32m'β Test suite failed: 3 tests failing'[0m [36m&&[0m [1m[34mexit[0m 1[0mdiff --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.snapindex 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()[40m [0m [1m[34mecho[0m [32m'β Code formatting check passed'[0m[0mβ Code formatting check passed-π [36mRunning pre-merge [1mtest[0m:[0m[40m [0m [1m[34mecho[0m [32m'β Test suite failed: 3 tests failing'[0m [36m&&[0m [1m[34mexit[0m 1[0mdiff --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.snapindex 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()[40m [0m [1m[34mecho[0m [32m'β Code formatting check passed'[0m[0mβ Code formatting check passed-π [36mRunning pre-merge [1mlint[0m:[0m[40m [0m [1m[34mecho[0m [32m'β Linting passed - no warnings'[0m[0mβ Linting passed - no warnings-π [36mRunning pre-merge [1mtest[0m:[0m[40m [0m [1m[34mecho[0m [32m'β All 47 tests passed in 2.3s'[0m[0mβ All 47 tests passed in 2.3s-π [36mMerging 1 commit to [1m[36mmain[0m[36m @ [2m[36m[HASH][0m[0m (no commit/squash/rebase needed)[40m [0m * [33m[HASH][m[33m ([m[1;36mHEAD[m[33m -> [m[1;32mfeature[m[33m)[m Add featurediff --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.snapindex 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()[40m [0m [1m[34mecho[0m [32m'β Code formatting check passed'[0m[0mβ Code formatting check passed-π [36mRunning pre-merge [1mlint[0m:[0m[40m [0m [1m[34mecho[0m [32m'β Linting passed - no warnings'[0m[0mβ Linting passed - no warnings-π [36mRunning pre-merge [1mtest[0m:[0m[40m [0m [1m[34mecho[0m [32m'β All 47 tests passed in 2.3s'[0m[0mβ All 47 tests passed in 2.3s-π [36mMerging 1 commit to [1m[36mmain[0m[36m @ [2m[36m[HASH][0m[0m (no commit/squash/rebase needed)[40m [0m * [33m[HASH][m[33m ([m[1;36mHEAD[m[33m -> [m[1;32mfeature[m[33m)[m Add featurediff --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.snapindex 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()[40m [0m [1m[34mecho[0m [32m'Installing dependencies...'[0m[0mInstalling dependencies...-π [36mRunning post-create:[0m[40m [0m [1m[34mecho[0m [32m'Building project...'[0m[0mBuilding project...-β [32mCreated new worktree for [1m[32mfeature-hooks[0m[32m from [1m[32mmain[0m[32m at [1m[32m[TMPDIR]/test-repo.feature-hooks[0m[0mπ [36mRunning post-start [1mserver[0m:[0m[40m [0m [1m[34mecho[0m [32m'Starting dev server on port 3000'[0m[0mdiff --git a/tests/snapshots/integration__integration_tests__init__init_bash.snap b/tests/snapshots/integration__integration_tests__init__init_bash.snapindex 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: CLC_ALL: CSOURCE_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: trueexit_code: 0@@ -63,7 +63,8 @@ _wt_exec() {elif [[ "$chunk" == __WORKTRUNK_EXEC__* ]]; thenexec_cmd="${chunk#__WORKTRUNK_EXEC__}"else- printf '%s\n' "$chunk"+ # Regular output - print it with newline (ignore empty chunks)+ [[ -n "$chunk" ]] && printf '%s\n' "$chunk"fidone <"$fifo_path"diff --git a/tests/snapshots/integration__integration_tests__init__init_zsh.snap b/tests/snapshots/integration__integration_tests__init__init_zsh.snapindex 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: CLC_ALL: CSOURCE_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: trueexit_code: 0@@ -63,7 +63,8 @@ _wt_exec() {elif [[ "$chunk" == __WORKTRUNK_EXEC__* ]]; thenexec_cmd="${chunk#__WORKTRUNK_EXEC__}"else- printf '%s\n' "$chunk"+ # Regular output - print it with newline (ignore empty chunks)+ [[ -n "$chunk" ]] && printf '%s\n' "$chunk"fidone <"$fifo_path"