Skip to content

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

fix(output): don't panic when a consumer stops reading stdout (#3766)

Maximilian Roos5576eec1a49d
diff --git a/src/commands/CLAUDE.md b/src/commands/CLAUDE.md
index 1c40bb664..f2922cf94 100644
--- a/src/commands/CLAUDE.md
+++ b/src/commands/CLAUDE.md
@@ -85,7 +85,7 @@ wt --source -C /path/to/repo switch
3. Add an `after_long_help` attribute — it is the source of truth for `docs/content/{command}.md`.
4. Run `cargo test --test integration test_docs_are_in_sync`. Editing help text also changes the rendered `--help` snapshots, which that test leaves untouched — regenerate them with `cargo insta test --accept --test integration -- test_help` (or run the pre-merge hook, which does both).
-A `--format=json` mode prints its answer to stdout through anstream's `println!`, which drops a `BrokenPipe` write error where std's panics. `crate::output::print_json` is that printer for every surface but `wt switch --format=json`, which emits its single result as one compact line.
+A `--format=json` mode prints its answer to stdout through anstream's `println!`, which drops a `BrokenPipe` write error where std's panics. `crate::output::print_json` is that printer for every surface but `wt switch --format=json`, which emits its single result as one compact line. Anything else a person reads goes through anstream too (`worktrunk::styling::println`), which strips color when stdout isn't a terminal and honors `CLICOLOR_FORCE` as `wt --help` documents. `NO_COLOR` reaches the `wt list` table wherever `print_buffered_table` runs — piped, where color is off regardless, and `--no-progressive` on a terminal, where it now genuinely strips. It does not reach the default terminal rendering: `RenderTarget::detect` hands every tty that didn't ask otherwise to `ProgressiveTable`, which writes to a raw `std::io::stdout()` with each row's escapes already baked in. `crate::output::println_verbatim!` is for the two surfaces whose pipe is a courier rather than the destination, so their escapes are data: the statusline a shell prompt or Claude Code renders, and the `--help-page` document whose escapes the docs pipeline turns into HTML. Neither consumer is ever a tty, so anstream would strip them every time — and no test would catch it, since the suite forces color with `CLICOLOR_FORCE=1`. std's `print!`/`println!` write the command's answer nowhere: they panic on a closed pipe, so `wt … | head -3` dies with exit 101.
## Branch Argument Conventions
diff --git a/src/commands/config/update.rs b/src/commands/config/update.rs
index 046e15f3e..a2a0b9a5a 100644
--- a/src/commands/config/update.rs
+++ b/src/commands/config/update.rs
@@ -15,7 +15,7 @@ use worktrunk::config::{
};
use worktrunk::git::Repository;
use worktrunk::styling::{
- eprintln, format_bash_with_gutter, hint_message, info_message, success_message,
+ eprintln, format_bash_with_gutter, hint_message, info_message, print, println, success_message,
suggest_command_in_dir,
};
diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rs
index 5d2530f70..a58c45b3b 100644
--- a/src/commands/list/collect/mod.rs
+++ b/src/commands/list/collect/mod.rs
@@ -322,6 +322,7 @@ use worktrunk::styling::{
};
use crate::commands::is_worktree_at_expected_path;
+use worktrunk::styling::println;
use super::model::{CommitDetails, ItemKind, ListItem, StatusSymbols, WorktreeData};
use super::progressive::RenderTarget;
@@ -390,7 +391,7 @@ impl TableRenderPlan {
// for `WORKTRUNK_FIRST_OUTPUT` whenever progressive rendering is on
// (`show_progress || progressive_handler.is_some()`), so this render
// path runs only in buffered mode.
- print_first_buffered_line(&self.header)?;
+ println!("{}", self.header);
return Ok(true);
}
@@ -403,15 +404,6 @@ impl TableRenderPlan {
}
}
-fn print_first_buffered_line(header: &str) -> anyhow::Result<()> {
- use std::io::Write as _;
-
- let mut stdout = std::io::stdout();
- writeln!(stdout, "{header}")?;
- stdout.flush()?;
- Ok(())
-}
-
fn print_buffered_table(header: &str, rows: &[String], summary: &str) {
println!("{header}");
for row in rows {
diff --git a/src/commands/statusline.rs b/src/commands/statusline.rs
index ecc32d4ed..1a5e48f01 100644
--- a/src/commands/statusline.rs
+++ b/src/commands/statusline.rs
@@ -31,7 +31,7 @@ use worktrunk::styling::{
use super::list::{self, CollectOptions, StatuslineSegment, json_output};
use crate::cli::StatuslineFormat;
-use crate::output::print_json;
+use crate::output::{print_json, println_verbatim};
/// Claude Code context parsed from stdin JSON
struct ClaudeCodeContext {
@@ -723,8 +723,9 @@ fn format_context_gauge(percentage: f64) -> String {
/// Run the statusline command.
///
-/// Output uses `println!` for raw stdout (bypasses anstream color detection).
-/// Shell prompts (PS1) and Claude Code always expect ANSI codes.
+/// Output goes through `println_verbatim!`, which bypasses anstream's color
+/// detection: shell prompts (PS1) and Claude Code always expect ANSI codes,
+/// and neither is a tty from this process's point of view.
pub fn run(format: StatuslineFormat) -> Result<()> {
// Statusline runs on every prompt redraw — deprecation warnings on stderr
// would appear above each prompt.
@@ -845,7 +846,7 @@ pub fn run(format: StatuslineFormat) -> Result<()> {
let output = fix_dim_after_color_reset(&output);
let output = truncate_visible(&format!("{reset} {output}"), max_width);
- println!("{}", output);
+ println_verbatim!("{}", output);
Ok(())
}
diff --git a/src/help.rs b/src/help.rs
index e05393c03..b13e9a260 100644
--- a/src/help.rs
+++ b/src/help.rs
@@ -55,9 +55,10 @@ use worktrunk::docs::{
BADGE_EXPERIMENTAL_HTML, DEMO_MARKER_PREFIX, MARKER_CLOSE, MARKER_OPEN_PREFIX,
SUBDOC_MARKER_PREFIX, convert_dollar_console_to_terminal,
};
-use worktrunk::styling::eprintln;
+use worktrunk::styling::{eprintln, print};
use crate::cli;
+use crate::output::println_verbatim;
/// Output format for a `--help-page`. Web pages keep Zola shortcodes, HTML
/// spans, and demo GIF figures for the docs site; plain pages strip those for
@@ -122,19 +123,19 @@ impl PageMode {
/// uses it as a region marker), or an H1 title for plain skill pages.
fn emit_header(self, subcommand: &str) {
match self {
- Self::Web => std::println!(
+ Self::Web => println_verbatim!(
"{MARKER_OPEN_PREFIX}`wt {subcommand} --help-page` — edit src/cli/mod.rs to update -->"
),
- Self::Plain => std::println!("# wt {subcommand}"),
+ Self::Plain => println_verbatim!("# wt {subcommand}"),
}
- std::println!();
+ println_verbatim!();
}
/// Emit the closing END marker (web only).
fn emit_footer(self) {
if matches!(self, Self::Web) {
- std::println!();
- std::println!("{MARKER_CLOSE}");
+ println_verbatim!();
+ println_verbatim!("{MARKER_CLOSE}");
}
}
}
@@ -521,18 +522,19 @@ Commands with pages: merge, switch, remove, list"
let main_help = mode.process_body(main_content);
let reference_block = help_reference_with_color(&[subcommand], Some(100), mode.color());
- // Use std::println! to preserve ANSI codes in output (the styling::println strips them)
+ // println_verbatim! preserves the ANSI the web mode's reference block
+ // carries — the docs pipeline converts those escapes into HTML spans, and
+ // anstream's println! would strip them off a piped stdout.
mode.emit_header(subcommand);
- std::println!("{}", main_help.trim());
- std::println!();
+ println_verbatim!("{}", main_help.trim());
+ println_verbatim!();
// Main command reference immediately after its content
- std::println!("## Command reference");
- std::println!();
- std::println!("```");
- std::print!("{}", reference_block.trim());
- std::println!();
- std::println!("```");
+ println_verbatim!("## Command reference");
+ println_verbatim!();
+ println_verbatim!("```");
+ println_verbatim!("{}", reference_block.trim());
+ println_verbatim!("```");
// Subdocs follow, each with their own command reference at the end.
if let Some(subdocs) = subdoc_content {
@@ -541,10 +543,10 @@ Commands with pages: merge, switch, remove, list"
// inside format_subcommand_section, so re-running would double-convert.
let subdocs = mode.process_subdoc_trailing(subdocs);
let subdocs_expanded = expand_subdoc_placeholders(&subdocs, sub, &parent_name, mode);
- std::println!();
- std::println!("# Subcommands");
- std::println!();
- std::println!("{}", subdocs_expanded.trim());
+ println_verbatim!();
+ println_verbatim!("# Subcommands");
+ println_verbatim!();
+ println_verbatim!("{}", subdocs_expanded.trim());
}
mode.emit_footer();
diff --git a/src/output/mod.rs b/src/output/mod.rs
index 41617b974..50db613f8 100644
--- a/src/output/mod.rs
+++ b/src/output/mod.rs
@@ -3,7 +3,8 @@
//! # Architecture
//!
//! For regular output, use `eprintln!`/`println!` directly (from `worktrunk::styling`
-//! for color support); [`print_json`] serializes a `--format=json` answer to stdout.
+//! for color support); [`print_json`] serializes a `--format=json` answer to stdout,
+//! and [`println_verbatim`] writes a line whose color is already resolved.
//! This module handles shell integration directives (cd, exec) that need to be
//! communicated to the parent shell.
//!
@@ -36,6 +37,7 @@ pub(crate) mod handlers;
mod json;
pub(crate) mod prompt;
pub(crate) mod shell_integration;
+mod verbatim;
// Re-export the public API
pub(crate) use global::{
@@ -59,3 +61,5 @@ pub(crate) use shell_integration::{
pub(crate) use commit_generation::prompt_commit_generation;
// Re-export the JSON answer printer
pub(crate) use json::print_json;
+// Re-export the verbatim (already-colored) line printer
+pub(crate) use verbatim::println_verbatim;
diff --git a/src/output/verbatim.rs b/src/output/verbatim.rs
new file mode 100644
index 000000000..2ed6f37e6
--- /dev/null
+++ b/src/output/verbatim.rs
@@ -0,0 +1,40 @@
+//! Stdout for output whose ANSI is already decided.
+
+/// Print a line to stdout byte-for-byte, exiting cleanly when the consumer
+/// stops reading.
+///
+/// The companion to [`print_json`](super::print_json) for the output whose
+/// pipe is a courier rather than the destination, so the escapes in it are
+/// data: the statusline, which a shell prompt or Claude Code captures and
+/// renders, and the `--help-page` document, whose escapes the docs pipeline
+/// converts into HTML spans. Neither consumer is ever a tty, so anstream's
+/// `println!` would strip both every time — and no test would notice, since
+/// the suite sets `CLICOLOR_FORCE=1`. std's macros keep the bytes but panic
+/// when a consumer closes the pipe, which is how `wt list statusline | head -1`
+/// came to exit 101 on the surface a prompt redraws on.
+///
+/// Output a person reads is not this: `wt list` and the rest go through
+/// anstream, which strips color when stdout isn't a terminal unless
+/// `CLICOLOR_FORCE` says otherwise, and strips it on a terminal too under
+/// `NO_COLOR`. The `wt list` table's default terminal rendering is the one
+/// path that never reaches anstream — `RenderTarget::detect` hands every tty
+/// that didn't pass `--no-progressive` to `ProgressiveTable`, which writes to
+/// a raw `std::io::stdout()` with each row's escapes already baked in.
+///
+/// A `BrokenPipe` is dropped and any other write error still panics — the
+/// same policy anstream's macros apply, so both printers fail the same way on
+/// a full disk.
+macro_rules! println_verbatim {
+ ($($arg:tt)*) => {{
+ use ::std::io::Write as _;
+ let mut stdout = ::std::io::stdout().lock();
+ match ::std::writeln!(stdout, $($arg)*) {
+ Err(e) if e.kind() != ::std::io::ErrorKind::BrokenPipe => {
+ ::std::panic!("failed printing to stdout: {e}");
+ }
+ Err(_) | Ok(_) => {}
+ }
+ }};
+}
+
+pub(crate) use println_verbatim;
diff --git a/tests/integration_tests/output_system_guard.rs b/tests/integration_tests/output_system_guard.rs
index 5547338e9..ef720de1a 100644
--- a/tests/integration_tests/output_system_guard.rs
+++ b/tests/integration_tests/output_system_guard.rs
@@ -14,21 +14,28 @@
//! - `println!` / `print!` in files listed in `STDOUT_ALLOWED_PATHS`
//!
//! When adding stdout output:
-//! - Use `worktrunk::styling::println` for color-aware output
+//! - Use `worktrunk::styling::println` for color-aware output, or
+//! `crate::output::println_verbatim` where the consumer renders the escapes
+//! and is never a tty (the statusline, `--help-page`)
//! - Add the file path to `STDOUT_ALLOWED_PATHS` with a comment explaining why
+//!
+//! Neither printer panics when the consumer closes the pipe, which
+//! [`test_stdout_surfaces_survive_a_closed_consumer`] checks from the outside.
use std::fs;
use std::path::Path;
+use std::process::Stdio;
use path_slash::PathExt as _;
+use rstest::rstest;
+
+use crate::common::{TestRepo, repo};
/// Paths (relative to src/commands/) that are allowed to use println!/print! for stdout.
/// These intentionally output data to stdout for scripting/piping.
const STDOUT_ALLOWED_PATHS: &[&str] = &[
// Shell integration code for: eval "$(wt config shell init bash)"
"init.rs",
- // Status line text for shell prompts (PS1)
- "statusline.rs",
// Table and summary output for wt list
"list/collect/mod.rs",
// State data output (branch names, previous worktree, etc.)
@@ -177,3 +184,59 @@ fn check_file(path: &Path, tokens: &[&str], violations: &mut Vec<String>, comman
}
}
}
+
+/// Every stdout surface exits cleanly when its consumer stops reading.
+///
+/// std's `print!`/`println!` panic on a `BrokenPipe`, so a command whose
+/// answer went out through them died with exit 101 and a Rust panic message
+/// the moment the reader left — `wt list | head -3`, and `wt list statusline`
+/// on the surface a shell prompt runs on every redraw. anstream's macros and
+/// `println_verbatim!` drop that error instead, and one of the two now carries
+/// every answer this binary writes to stdout.
+///
+/// Which of the two a surface uses is about color, not about this, so the
+/// cases below span both.
+///
+/// The child's stdout pipe is closed before it is waited on, so its first
+/// write has no reader. `--version` writes a few dozen bytes and still trips
+/// it: `EPIPE` is about whether a reader is attached, not about filling the
+/// pipe buffer.
+#[rstest]
+fn test_stdout_surfaces_survive_a_closed_consumer(repo: TestRepo) {
+ for args in [
+ &["--version"][..],
+ &["merge", "--help-page"][..],
+ &["merge", "--help-description"][..],
+ &["merge", "--help-md"][..],
+ &["list"][..],
+ &["list", "--full"][..],
+ &["list", "statusline"][..],
+ &["list", "--format=json"][..],
+ &["config", "update", "--print"][..],
+ ] {
+ let mut command = repo.wt_command();
+ let mut child = command
+ .args(args)
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
+ .unwrap_or_else(|e| panic!("failed to spawn wt {args:?}: {e}"));
+
+ drop(child.stdout.take().expect("stdout was piped"));
+
+ let output = child
+ .wait_with_output()
+ .unwrap_or_else(|e| panic!("failed to wait for wt {args:?}: {e}"));
+ let stderr = String::from_utf8_lossy(&output.stderr);
+
+ assert!(
+ output.status.success(),
+ "wt {args:?} exited {:?} with its consumer gone; stderr: {stderr}",
+ output.status.code()
+ );
+ assert!(
+ !stderr.contains("panicked"),
+ "wt {args:?} panicked with its consumer gone; stderr: {stderr}"
+ );
+ }
+}
diff --git a/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_commands_from_bare_directory.snap b/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_commands_from_bare_directory.snap
index 54cbe56f7..4c8c45784 100644
--- a/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_commands_from_bare_directory.snap
+++ b/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_commands_from_bare_directory.snap
@@ -46,8 +46,8 @@ info:
success: true
exit_code: 0
----- stdout -----
- Branch Status HEAD± main↕ main…± Remote⇅ Path Commit Age Message
-^ main ^ . b834638 1d Initial commit
+ Branch Status HEAD± main↕ main…± Remote⇅ Path Commit Age Message
+^ main ^ . b834638 1d Initial commit
----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_identifies_primary_correctly.snap b/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_identifies_primary_correctly.snap
index 7571df014..36ba5bca4 100644
--- a/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_identifies_primary_correctly.snap
+++ b/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_identifies_primary_correctly.snap
@@ -46,10 +46,10 @@ info:
success: true
exit_code: 0
----- stdout -----
- Branch Status HEAD± main↕ main…± Remote⇅ Path Commit Age Message
-@ main ^ . b37a293 1d Main commit
-+ feature1 _ ../feature1 b37a293 1d Main commit
-+ feature2 _ ../feature2 b37a293 1d Main commit
+ Branch Status HEAD± main↕ main…± Remote⇅ Path Commit Age Message
+@ main ^ . b37a293 1d Main commit
++ feature1 _ ../feature1 b37a293 1d Main commit
++ feature2 _ ../feature2 b37a293 1d Main commit
----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_list_shows_no_bare_entry.snap b/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_list_shows_no_bare_entry.snap
index feaffa965..84f255c42 100644
--- a/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_list_shows_no_bare_entry.snap
+++ b/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_list_shows_no_bare_entry.snap
@@ -46,8 +46,8 @@ info:
success: true
exit_code: 0
----- stdout -----
- Branch Status HEAD± main↕ main…± Remote⇅ Path Commit Age Message
-@ main ^ . b834638 1d Initial commit
+ Branch Status HEAD± main↕ main…± Remote⇅ Path Commit Age Message
+@ main ^ . b834638 1d Initial commit
----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_list_worktrees.snap b/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_list_worktrees.snap
index 8b2f38944..0780f58e1 100644
--- a/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_list_worktrees.snap
+++ b/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_list_worktrees.snap
@@ -46,9 +46,9 @@ info:
success: true
exit_code: 0
----- stdout -----
- Branch Status HEAD± main↕ main…± Remote⇅ Path Commit Age Message
-@ main ^ . 6c3da84 1d Initial commit on main
-+ feature ↑ ↑1 +1 -1 ../feature 72413a3 1d Work on feature
+ Branch Status HEAD± main↕ main…± Remote⇅ Path Commit Age Message
+@ main ^ . 6c3da84 1d Initial commit on main
++ feature ↑ ↑1 +1 -1 ../feature 72413a3 1d Work on feature
----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__bare_repository__nested_bare_repo_list_snapshot.snap b/tests/snapshots/integration__integration_tests__bare_repository__nested_bare_repo_list_snapshot.snap
index 97d8d157b..d56dc3da9 100644
--- a/tests/snapshots/integration__integration_tests__bare_repository__nested_bare_repo_list_snapshot.snap
+++ b/tests/snapshots/integration__integration_tests__bare_repository__nested_bare_repo_list_snapshot.snap
@@ -46,9 +46,9 @@ info:
success: true
exit_code: 0
----- stdout -----
- Branch Status HEAD± main↕ main…± Remote⇅ Path Commit Age Message
-@ main ^ . a6c13b1 1d Initial
-+ feature _ ../feature a6c13b1 1d Initial
+ Branch Status HEAD± main↕ main…± Remote⇅ Path Commit Age Message
+@ main ^ . a6c13b1 1d Initial
++ feature _ ../feature a6c13b1 1d Initial
----- stderr -----