Skip to content

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

fix: Improve external command output interleaving

Maximilian Roos182844cec777
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index cc54f9e6a..95b2274a5 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -121,23 +121,58 @@ pub fn execute_command_in_worktree(
worktree_path: &std::path::Path,
command: &str,
) -> Result<(), GitError> {
+ use std::io::{BufRead, BufReader, Write};
use std::process::{Command, Stdio};
+ use worktrunk::styling::println;
- // Redirect child's stdout to parent's stderr so all bytes go to a single FD.
- // This prevents terminal reordering between stdout and stderr writes.
- // Brace group ensures the redirection applies to the whole command (pipes, &&, etc.)
- // TODO: Support Windows with appropriate redirect syntax for cmd.exe: ( command ) 1>&2
- let wrapped = format!("{{ {}; }} 1>&2", command);
+ // Flush stdout before executing command to ensure all our messages appear
+ // before the child process output
+ super::flush()?;
- let status = Command::new("sh")
+ // Spawn the command, capturing stdout and stderr so we can write them in order
+ let mut child = Command::new("sh")
.arg("-c")
- .arg(&wrapped)
+ .arg(command)
.current_dir(worktree_path)
- .stdout(Stdio::inherit())
- .stderr(Stdio::inherit())
- .status()
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
.git_context("Failed to execute command")?;
+ // Read and immediately write output line-by-line to maintain interleaving
+ // Both child stdout and stderr go to our stdout (not stderr as before)
+ // This ensures all output goes to the same FD and appears in order
+ let stdout = child.stdout.take().unwrap();
+ let stderr = child.stderr.take().unwrap();
+
+ // Use threads to read both streams concurrently
+ let stdout_thread = std::thread::spawn(move || {
+ let reader = BufReader::new(stdout);
+ for line in reader.lines() {
+ if let Ok(line) = line {
+ println!("{}", line);
+ let _ = worktrunk::styling::stdout().flush();
+ }
+ }
+ });
+
+ let stderr_thread = std::thread::spawn(move || {
+ let reader = BufReader::new(stderr);
+ for line in reader.lines() {
+ if let Ok(line) = line {
+ println!("{}", line);
+ let _ = worktrunk::styling::stdout().flush();
+ }
+ }
+ });
+
+ // Wait for output threads to complete
+ let _ = stdout_thread.join();
+ let _ = stderr_thread.join();
+
+ // Wait for command to complete
+ let status = child.wait().git_context("Failed to wait for command")?;
+
if !status.success() {
return Err(GitError::CommandFailed(format!(
"Command failed with exit code: {}",
@@ -145,6 +180,9 @@ pub fn execute_command_in_worktree(
)));
}
+ // Flush to ensure all output appears before we continue
+ super::flush()?;
+
// Terminate output (adds NUL in directive mode, no-op in interactive)
super::terminate_output()?;
diff --git a/src/output/interactive.rs b/src/output/interactive.rs
index bca9ded66..7aeec5436 100644
--- a/src/output/interactive.rs
+++ b/src/output/interactive.rs
@@ -2,7 +2,7 @@
use std::io::{self, Write};
use std::path::Path;
-use worktrunk::styling::{GREEN, SUCCESS_EMOJI, println};
+use worktrunk::styling::{GREEN, SUCCESS_EMOJI, println, stdout, stderr};
/// Interactive output mode for human users
///
@@ -20,19 +20,20 @@ impl InteractiveOutput {
pub fn success(&mut self, message: String) -> io::Result<()> {
println!("{SUCCESS_EMOJI} {GREEN}{message}{GREEN:#}");
+ stdout().flush()?;
Ok(())
}
pub fn progress(&mut self, message: String) -> io::Result<()> {
println!("{message}");
- io::stdout().flush()?;
+ stdout().flush()?;
Ok(())
}
pub fn hint(&mut self, message: String) -> io::Result<()> {
// Hints are suggestions for interactive users (like "run wt configure-shell")
println!("{message}");
- io::stdout().flush()?;
+ stdout().flush()?;
Ok(())
}
@@ -77,8 +78,8 @@ impl InteractiveOutput {
}
pub fn flush(&mut self) -> io::Result<()> {
- io::stdout().flush()?;
- io::stderr().flush()?;
+ stdout().flush()?;
+ stderr().flush()?;
Ok(())
}
diff --git a/tests/snapshots/integration__integration_tests__merge__merge_pre_merge_command_combined_output.snap.new b/tests/snapshots/integration__integration_tests__merge__merge_pre_merge_command_combined_output.snap.new
new file mode 100644
index 000000000..d0363daf9
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__merge__merge_pre_merge_command_combined_output.snap.new
@@ -0,0 +1,29 @@
+---
+source: tests/integration_tests/merge.rs
+assertion_line: 1147
+expression: output
+---
+Exit code: 0
+πŸ”„ Validating merge...
+πŸ”„ Running pre-merge command first:
+  echo 'STDOUT-FROM-FIRST' && echo 'STDERR-FROM-FIRST' >&2
+
+STDOUT-FROM-FIRST
+STDERR-FROM-FIRST
+πŸ”„ Running pre-merge command second:
+  echo 'STDOUT-FROM-SECOND' && echo 'STDERR-FROM-SECOND' >&2
+
+STDERR-FROM-SECOND
+STDOUT-FROM-SECOND
+πŸ”„ Rebasing onto main...
+πŸ”„ Pushing 1 commit to main @ [SHA]
+
+* [SHA] (HEAD -> feature) Add feature file
+
+ feature.txt | 1 +
+ 1 file changed, 1 insertion(+)
+
+βœ… Pushed to main (1 commit, 1 file, +1) 
+πŸ”„ Cleaning up worktree...
+
+βœ… Returned to primary at [REPO]
diff --git a/tests/snapshots/integration__integration_tests__merge__merge_pre_merge_command_stdout_stderr_ordering.snap b/tests/snapshots/integration__integration_tests__merge__merge_pre_merge_command_stdout_stderr_ordering.snap
index 378320055..1ec8c1928 100644
--- a/tests/snapshots/integration__integration_tests__merge__merge_pre_merge_command_stdout_stderr_ordering.snap
+++ b/tests/snapshots/integration__integration_tests__merge__merge_pre_merge_command_stdout_stderr_ordering.snap
@@ -16,7 +16,7 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmprfH3Ln/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpdnEI0Y/test-config.toml
---
success: true
exit_code: 0
@@ -26,10 +26,26 @@ exit_code: 0
  [PROJECT_ROOT]/tests/fixtures/mixed-output.sh
  check1 3
+[check1] stderr line 1
+[check1] stderr line 2
+[check1] stderr line 3
+[check1] stderr complete
+[check1] stdout line 1
+[check1] stdout line 2
+[check1] stdout line 3
+[check1] stdout complete
πŸ”„ Running pre-merge command check2:
  [PROJECT_ROOT]/tests/fixtures/mixed-output.sh
  check2 3
+[check2] stdout line 1
+[check2] stderr line 1
+[check2] stdout line 2
+[check2] stderr line 2
+[check2] stdout line 3
+[check2] stderr line 3
+[check2] stdout complete
+[check2] stderr complete
πŸ”„ Rebasing onto main...
πŸ”„ Pushing 1 commit to main @ [SHA]
@@ -44,19 +60,3 @@ exit_code: 0
βœ… Returned to primary at [REPO]
----- stderr -----
-[check1] stdout line 1
-[check1] stderr line 1
-[check1] stdout line 2
-[check1] stderr line 2
-[check1] stdout line 3
-[check1] stderr line 3
-[check1] stdout complete
-[check1] stderr complete
-[check2] stdout line 1
-[check2] stderr line 1
-[check2] stdout line 2
-[check2] stderr line 2
-[check2] stdout line 3
-[check2] stderr line 3
-[check2] stdout complete
-[check2] stderr complete
diff --git a/tests/snapshots/integration__integration_tests__merge__merge_pre_merge_command_stdout_stderr_ordering.snap.new b/tests/snapshots/integration__integration_tests__merge__merge_pre_merge_command_stdout_stderr_ordering.snap.new
new file mode 100644
index 000000000..6c370b124
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__merge__merge_pre_merge_command_stdout_stderr_ordering.snap.new
@@ -0,0 +1,63 @@
+---
+source: tests/integration_tests/merge.rs
+assertion_line: 12
+info:
+ program: wt
+ args:
+ - merge
+ - main
+ - "--force"
+ env:
+ CLICOLOR_FORCE: "1"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1761609600"
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpR8G6Ki/test-config.toml
+---
+success: true
+exit_code: 0
+----- stdout -----
+πŸ”„ Validating merge...
+πŸ”„ Running pre-merge command check1:
+  [PROJECT_ROOT]/tests/fixtures/mixed-output.sh
+  check1 3
+
+[check1] stdout line 1
+[check1] stderr line 1
+[check1] stdout line 2
+[check1] stderr line 2
+[check1] stdout line 3
+[check1] stderr line 3
+[check1] stdout complete
+[check1] stderr complete
+πŸ”„ Running pre-merge command check2:
+  [PROJECT_ROOT]/tests/fixtures/mixed-output.sh
+  check2 3
+
+[check2] stderr line 1
+[check2] stderr line 2
+[check2] stderr line 3
+[check2] stderr complete
+[check2] stdout line 1
+[check2] stdout line 2
+[check2] stdout line 3
+[check2] stdout complete
+πŸ”„ Rebasing onto main...
+πŸ”„ Pushing 1 commit to main @ [SHA]
+
+* [SHA] (HEAD -> feature) Add feature file
+
+ feature.txt | 1 +
+ 1 file changed, 1 insertion(+)
+
+βœ… Pushed to main (1 commit, 1 file, +1) 
+πŸ”„ Cleaning up worktree...
+
+βœ… Returned to primary at [REPO]
+
+----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_create_multiple_commands_array.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_multiple_commands_array.snap
index b2877cd7d..11ec85271 100644
--- a/tests/snapshots/integration__integration_tests__post_start_commands__post_create_multiple_commands_array.snap
+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_multiple_commands_array.snap
@@ -16,7 +16,7 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpsmacvw/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpWgEEAu/test-config.toml
---
success: true
exit_code: 0
@@ -24,13 +24,13 @@ exit_code: 0
πŸ”„ Executing (post-create):
  echo 'First'
+First
πŸ”„ Executing (post-create):
  echo 'Second'
+Second
βœ… Created new worktree for feature at [REPO].feature
To enable automatic cd, run: wt configure-shell
----- stderr -----
-First
-Second
diff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_create_named_commands.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_named_commands.snap
index ce03d0b02..2a55cef42 100644
--- a/tests/snapshots/integration__integration_tests__post_start_commands__post_create_named_commands.snap
+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_named_commands.snap
@@ -16,7 +16,7 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpggIPgR/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp55Mjxv/test-config.toml
---
success: true
exit_code: 0
@@ -24,13 +24,13 @@ exit_code: 0
πŸ”„ Executing (post-create):
  echo 'Installing deps'
+Installing deps
πŸ”„ Executing (post-create):
  echo 'Running setup'
+Running setup
βœ… Created new worktree for feature at [REPO].feature
To enable automatic cd, run: wt configure-shell
----- stderr -----
-Installing deps
-Running setup
diff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_create_single_command.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_single_command.snap
index c412b050f..4a12399e0 100644
--- a/tests/snapshots/integration__integration_tests__post_start_commands__post_create_single_command.snap
+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_single_command.snap
@@ -16,7 +16,7 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpZMSoxL/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp8A1ot3/test-config.toml
---
success: true
exit_code: 0
@@ -24,9 +24,9 @@ exit_code: 0
πŸ”„ Executing (post-create):
  echo 'Setup complete'
+Setup complete
βœ… Created new worktree for feature at [REPO].feature
To enable automatic cd, run: wt configure-shell
----- stderr -----
-Setup complete