Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor(output): resolve color in one place via anstream's global ColorChoice (#3777)
Maximilian Roosc37d07d87a14
diff --git a/.claude/skills/writing-user-outputs/SKILL.md b/.claude/skills/writing-user-outputs/SKILL.mdindex 89f02ec3d..1bae7f498 100644--- a/.claude/skills/writing-user-outputs/SKILL.md+++ b/.claude/skills/writing-user-outputs/SKILL.md@@ -60,15 +60,17 @@ panics on the `BrokenPipe` write error, anstream's drops it. `wt … | head`closes the pipe, so command code imports the `worktrunk::styling` one and no`std::println!` is left in `src/`.-**Output whose ANSI is already decided** goes through-`crate::output::println_verbatim!` instead — the statusline a shell prompt or+**Output whose ANSI is already decided** declares that once at the top of the+command with `worktrunk::styling::ColorChoice::Always.write_global()` and then+prints through the same anstream macros — the statusline a shell prompt orClaude 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 their color every time, and the test suite would not catch it because it-forces color with `CLICOLOR_FORCE=1`. `println_verbatim!` writes the bytes-through unchanged and drops a `BrokenPipe` the same way anstream does. Reach-for it only when the pipe is a courier rather than the destination; anything a-person reads directly stays on anstream, which is what strips color on a pipe+pipeline turns into HTML (`--plain` and `--help-md` declare `Never` the same+way). Neither consumer is ever a tty, so without the declaration anstream+would strip their color every time — and the test suite would not catch it,+because it forces color with `CLICOLOR_FORCE=1`;+`test_color_follows_the_consumer` pins the unforced behavior. Declare `Always`+only when the pipe is a courier rather than the destination; anything a person+reads directly stays on plain anstream, which is what strips color on a pipeand honors `NO_COLOR`.**`--format=json` answers** go through `crate::output::print_json`, never adiff --git a/src/commands/CLAUDE.md b/src/commands/CLAUDE.mdindex ae7eff317..8de19f6d7 100644--- a/src/commands/CLAUDE.md+++ b/src/commands/CLAUDE.md@@ -85,7 +85,11 @@ wt --source -C /path/to/repo switch3. 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. 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.+All stdout goes through anstream: `worktrunk::styling::println` for anything a person reads, and `crate::output::print_json` for a `--format=json` answer — every surface but `wt switch --format=json`, which emits its single result as one compact line. anstream's macros drop a `BrokenPipe` write error where std's panic, so `wt … | head -3` never exits 101.++Color resolves in exactly one place, anstream's `AutoStream::choice`: the process-global `ColorChoice` first, then the tty check with `NO_COLOR` / `CLICOLOR_FORCE`. A command whose stdout is a renderer's payload says so once at the top of its `run` with `ColorChoice::Always.write_global()`, then prints normally — the statusline, which a shell prompt or Claude Code captures and re-renders, and `--help-page`, whose escapes the docs pipeline turns into HTML spans (`--plain` writes `Never`, for portable markdown). Neither consumer is ever a tty, so without the global their escapes would be stripped every time.++`wt list`'s progressive table applies that choice itself rather than writing through an anstream stream, because a strip would eat its cursor-control CSI along with the color; it reads the resolved choice from `AutoStream::choice`, so the single resolution point still holds. The test suite forces `CLICOLOR_FORCE=1`, so `test_color_follows_the_consumer` in `tests/integration_tests/output_system_guard.rs` pins the unforced behavior.## Branch Argument Conventionsdiff --git a/src/commands/config/alias.rs b/src/commands/config/alias.rsindex 1e18fa532..eef5ed487 100644--- a/src/commands/config/alias.rs+++ b/src/commands/config/alias.rs@@ -21,7 +21,6 @@//! natural home alongside `show`.use std::collections::BTreeSet;-use std::io::Write;use anyhow::Context;use color_print::cformat;@@ -29,7 +28,7 @@ use worktrunk::config::{ALIAS_ARGS_KEY, CommandConfig, ProjectConfig, UserConfig, VarScope, referenced_vars_for_config,};use worktrunk::git::{Repository, WorktrunkError};-use worktrunk::styling::{format_bash_with_gutter, info_message, println};+use worktrunk::styling::{eprint, format_bash_with_gutter, info_message, println};use crate::commands::alias::{AliasOptions, TOP_LEVEL_BUILTINS, load_aliases, load_aliases_for_listing,@@ -318,8 +317,7 @@ fn unknown_alias_error(.replace("similar subcommands", "similar aliases").replace("similar subcommand", "similar alias");- let mut stream = anstream::AutoStream::auto(std::io::stderr());- let _ = write!(stream, "{rewritten}");+ eprint!("{rewritten}");WorktrunkError::AlreadyDisplayed { exit_code: 2 }.into()}diff --git a/src/commands/list/CLAUDE.md b/src/commands/list/CLAUDE.mdindex 19493dcc5..513a1eae2 100644--- a/src/commands/list/CLAUDE.md+++ b/src/commands/list/CLAUDE.md@@ -63,4 +63,8 @@ Measures pure skeleton latency. Target: <60ms.- `layout.rs` — column width calculation- `progressive_table.rs` — terminal rendering with in-place updates; reservesblank rows below the table so the shell prompt printed after exit renders- into pre-scrolled rows instead of jerking the settled table up+ into pre-scrolled rows instead of jerking the settled table up. It writes to+ a raw stdout rather than an anstream stream, since a strip would eat its+ cursor-control CSI, so it applies the color decision to content itself —+ every row, header, and footer through `prepare`; the module docstring covers+ the splitdiff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rsindex a58c45b3b..353aff5f6 100644--- a/src/commands/list/collect/mod.rs+++ b/src/commands/list/collect/mod.rs@@ -318,7 +318,8 @@ use once_cell::sync::OnceCell;use rayon::prelude::*;use worktrunk::git::{ErrorExt, LocalBranch, Repository, WorktreeInfo};use worktrunk::styling::{- INFO_SYMBOL, eprintln, format_with_gutter, hint_message, truncate_visible, warning_message,+ INFO_SYMBOL, eprintln, format_with_gutter, hint_message, terminal_width, truncate_visible,+ warning_message,};use crate::commands::is_worktree_at_expected_path;@@ -1350,9 +1351,7 @@ pub fn collect(// The picker passes an explicit width because the list only gets part of the// terminal — the rest belongs to the preview pane — and takes its rows// link-free because skim mangles OSC 8 (see `Destination`).- let width = list_width- .or_else(crate::display::terminal_width)- .unwrap_or(usize::MAX);+ let width = list_width.or_else(terminal_width).unwrap_or(usize::MAX);let destination = if progressive_handler.is_some() {super::layout::Destination::picker(width)} else {@@ -1373,7 +1372,7 @@ pub fn collect(// Single-line invariant: with no detectable width, an unlimited width// keeps rows untruncated rather than wrapping at a guessed width- let max_width = crate::display::terminal_width().unwrap_or(usize::MAX);+ let max_width = terminal_width().unwrap_or(usize::MAX);// Which gated fact families the plan requested — recorded on `ListData`// so JSON output can distinguish "not requested" from "undetermined".diff --git a/src/commands/list/layout.rs b/src/commands/list/layout.rsindex a38494d06..9401a98cf 100644--- a/src/commands/list/layout.rs+++ b/src/commands/list/layout.rs@@ -1275,8 +1275,8 @@ pub fn calculate_layout_with_width(#[cfg(test)]mod tests {use super::*;- use crate::display::terminal_width;use worktrunk::git::LineDiff;+ use worktrunk::styling::terminal_width;#[test]fn test_fit_header() {diff --git a/src/commands/list/progressive_table.rs b/src/commands/list/progressive_table.rsindex f3001ddd1..0742a018d 100644--- a/src/commands/list/progressive_table.rs+++ b/src/commands/list/progressive_table.rs@@ -9,6 +9,24 @@//! - Has predictable cursor behavior based on our rendering logic//! - Reserves blank rows below the table ([`PROMPT_RESERVE_LINES`]) so the//! shell prompt printed after exit doesn't scroll the settled table+//!+//! # Presentation vs. mechanics+//!+//! This is the one stdout writer that cannot route through an anstream stream:+//! anstream's strip adapter drops every escape sequence, including the crossterm+//! cursor-control CSI ([`MoveUp`], [`Clear`]) the in-place redraw is built on. So+//! the table splits the two itself. Content — the row, header, and footer strings,+//! which arrive with color and OSC-8 hyperlinks already baked in by the shared+//! render code — is stripped when color is off; the cursor-control sequences this+//! module emits are always written.+//!+//! "Color is off" is not re-derived from `NO_COLOR` and friends here. The decision+//! comes from [`anstream::AutoStream::choice`] — the single resolution the anstream+//! macros already use for every other stdout surface (process-global `ColorChoice`+//! first, then tty plus the environment) — read once in [`ProgressiveTable::new`].+//! Stripping uses [`anstream::adapter::strip_str`], the exact transform an anstream+//! stream in `Never` mode applies, so progressive output matches the buffered path+//! by construction rather than by approximation.use crossterm::{ExecutableCommand,@@ -17,7 +35,7 @@ use crossterm::{};use std::io::{IsTerminal, Write, stdout};-use crate::display::truncate_visible;+use worktrunk::styling::truncate_visible;/// Blank rows kept below the table so the shell prompt printed after exit/// renders into pre-scrolled rows instead of scrolling the settled table.@@ -60,8 +78,14 @@ fn write_prompt_reserve(stdout: &mut std::io::Stdout) -> std::io::Result<()> {////// Data mutation (`update_row`, `update_footer`) is separate from rendering (`flush`)./// Call `flush()` after updates to write changes to the terminal.+///+/// Every content string passes through [`ProgressiveTable::prepare`], which+/// truncates and — when color is off — strips the escapes the render code baked+/// in. The crossterm cursor-control sequences written alongside them are never+/// stripped; see the module docs for that split.pub struct ProgressiveTable {- /// Previously rendered content for each line (header + rows + spacer + footer)+ /// Previously rendered content for each line (header + rows + spacer + footer),+ /// each already passed through [`ProgressiveTable::prepare`]lines: Vec<String>,/// Maximum width for content (terminal width - safety margin)max_width: usize,@@ -75,6 +99,9 @@ pub struct ProgressiveTable {/// Whether the skeleton was printed. Tests skip `render_skeleton` to keep/// this false and suppress stdout output.rendered: bool,+ /// Whether content escapes are stripped, resolved once from+ /// `anstream::AutoStream::choice` at construction.+ strip_content: bool,}impl ProgressiveTable {@@ -100,7 +127,15 @@ impl ProgressiveTable {} else {None};- Self::new_with_height(header, skeletons, initial_footer, max_width, term_height)+ let strip_content = anstream::AutoStream::choice(&stdout()) == anstream::ColorChoice::Never;+ Self::new_with_height(+ header,+ skeletons,+ initial_footer,+ max_width,+ term_height,+ strip_content,+ )}fn new_with_height(@@ -109,6 +144,7 @@ impl ProgressiveTable {initial_footer: String,max_width: usize,terminal_height: Option<usize>,+ strip_content: bool,) -> Self {let total_row_count = skeletons.len();@@ -119,27 +155,50 @@ impl ProgressiveTable {.map(|h| total_row_count.min(h.saturating_sub(4 + PROMPT_RESERVE_LINES as usize))).unwrap_or(total_row_count);+ let mut table = Self {+ lines: Vec::with_capacity(visible_row_count + 3),+ max_width,+ row_count: visible_row_count,+ total_row_count,+ dirty: Vec::new(),+ rendered: false,+ strip_content,+ };+// Build initial lines: header + visible rows + spacer + footer- let mut lines = Vec::with_capacity(visible_row_count + 3);- lines.push(truncate_visible(&header, max_width));+ let header_line = table.prepare(&header);+ table.lines.push(header_line);for skeleton in skeletons.into_iter().take(visible_row_count) {- lines.push(truncate_visible(&skeleton, max_width));+ let row = table.prepare(&skeleton);+ table.lines.push(row);}// Spacer (blank line)- lines.push(String::new());+ table.lines.push(String::new());// Footer- lines.push(truncate_visible(&initial_footer, max_width));+ let footer_line = table.prepare(&initial_footer);+ table.lines.push(footer_line);- Self {- lines,- max_width,- row_count: visible_row_count,- total_row_count,- dirty: Vec::new(),- rendered: false,+ table+ }++ /// Fit a content string to the table's width and, when color is off, strip+ /// the escapes the render code baked into it.+ ///+ /// Truncation runs first because the width math is escape-aware, and a cut+ /// through styled content appends its own reset; stripping afterwards removes+ /// that reset along with the rest.+ /// Every content line — header, rows, footer, on both the in-place and+ /// overflow paths — goes through here, so no other content path calls+ /// [`truncate_visible`] directly.+ fn prepare(&self, content: &str) -> String {+ let truncated = truncate_visible(content, self.max_width);+ if self.strip_content {+ anstream::adapter::strip_str(&truncated).to_string()+ } else {+ truncated}}@@ -179,17 +238,17 @@ impl ProgressiveTable {return false;}- let truncated = truncate_visible(&content, self.max_width);+ let prepared = self.prepare(&content);// Line index: header (0) + row_idxlet line_idx = row_idx + 1;// Skip if content hasn't changed- if self.lines[line_idx] == truncated {+ if self.lines[line_idx] == prepared {return false;}- self.lines[line_idx] = truncated;+ self.lines[line_idx] = prepared;// Only mark dirty if we've rendered (otherwise nothing on screen to redraw)if self.rendered {self.dirty.push(line_idx);@@ -204,17 +263,17 @@ impl ProgressiveTable {/// # Returns/// `true` if the content changed, `false` if unchanged.pub fn update_footer(&mut self, content: String) -> bool {- let truncated = truncate_visible(&content, self.max_width);+ let prepared = self.prepare(&content);// Footer is the last linelet footer_idx = self.lines.len() - 1;// Skip if content hasn't changed- if self.lines[footer_idx] == truncated {+ if self.lines[footer_idx] == prepared {return false;}- self.lines[footer_idx] = truncated;+ self.lines[footer_idx] = prepared;// Only mark dirty if we've rendered (otherwise nothing on screen to redraw)if self.rendered {self.dirty.push(footer_idx);@@ -303,16 +362,12 @@ impl ProgressiveTable {stdout.execute(MoveUp(self.lines.len() as u16))?;stdout.execute(MoveToColumn(0))?;stdout.execute(Clear(ClearType::FromCursorDown))?;- writeln!(stdout, "{}", self.lines[0])?; // header (unchanged)+ writeln!(stdout, "{}", self.lines[0])?; // header (already prepared)for row in &final_rows {- writeln!(stdout, "{}", truncate_visible(row, self.max_width))?;+ writeln!(stdout, "{}", self.prepare(row))?;}writeln!(stdout)?;- writeln!(- stdout,- "{}",- truncate_visible(&final_footer, self.max_width)- )?;+ writeln!(stdout, "{}", self.prepare(&final_footer))?;write_prompt_reserve(&mut stdout)?;stdout.flush()} else {@@ -504,6 +559,7 @@ mod tests {"loading".into(),80,Some(10),+ false,);assert_eq!(table.row_count, 4);@@ -528,6 +584,7 @@ mod tests {"loading".into(),80,Some(20),+ false,);assert_eq!(table.row_count, 3);@@ -545,6 +602,7 @@ mod tests {"loading".into(),80,Some(11),+ false,);assert_eq!(table.row_count, 5);@@ -561,6 +619,7 @@ mod tests {"loading".into(),80,Some(10),+ false,);assert_eq!(table.row_count, 4);@@ -577,6 +636,7 @@ mod tests {"loading".into(),80,Some(10),+ false,);// Can update visible rows (0..4)@@ -598,6 +658,7 @@ mod tests {"loading".into(),80,Some(3),+ false,);assert_eq!(table.row_count, 0);@@ -617,10 +678,87 @@ mod tests {"loading".into(),80,None,+ false,);assert_eq!(table.row_count, 10);assert_eq!(table.total_row_count, 10);assert_eq!(table.row_count, table.total_row_count);}++ // Styled header, skeleton row, and footer, plus an OSC-8 hyperlink — one+ // per content path, so a path that skipped `prepare` shows up here.+ const STYLED_HEADER: &str = "\u{1b}[1mBRANCH\u{1b}[0m";+ const STYLED_ROW: &str = "\u{1b}[31mrow0\u{1b}[0m";+ const STYLED_FOOTER: &str = "\u{1b}[2mloading\u{1b}[0m";+ const LINKED_FOOTER: &str =+ "\u{1b}]8;;https://example.com\u{1b}\\4 worktrees\u{1b}]8;;\u{1b}\\";++ #[test]+ fn strip_content_removes_escapes_from_every_content_path() {+ let mut table = ProgressiveTable::new_with_height(+ STYLED_HEADER.into(),+ vec![STYLED_ROW.into()],+ STYLED_FOOTER.into(),+ 80,+ None,+ true,+ );++ assert!(table.update_row(0, "\u{1b}[32mrow0-done\u{1b}[0m".into()));+ assert!(table.update_footer(LINKED_FOOTER.into()));++ assert!(+ !table.lines.iter().any(|line| line.contains('\u{1b}')),+ "escape survived stripping: {:?}",+ table.lines+ );+ insta::assert_debug_snapshot!(table.lines, @r#"+ [+ "BRANCH",+ "row0-done",+ "",+ "4 worktrees",+ ]+ "#);+ }++ #[test]+ fn escapes_survive_when_strip_content_is_off() {+ let mut table = ProgressiveTable::new_with_height(+ STYLED_HEADER.into(),+ vec![STYLED_ROW.into()],+ STYLED_FOOTER.into(),+ 80,+ None,+ false,+ );++ assert_eq!(table.lines[0], STYLED_HEADER);+ assert_eq!(table.lines[1], STYLED_ROW);+ assert_eq!(table.lines[3], STYLED_FOOTER);++ assert!(table.update_row(0, "\u{1b}[32mrow0-done\u{1b}[0m".into()));+ assert!(table.update_footer(LINKED_FOOTER.into()));+ assert_eq!(table.lines[1], "\u{1b}[32mrow0-done\u{1b}[0m");+ assert_eq!(table.lines[3], LINKED_FOOTER);+ }++ #[test]+ fn stripping_removes_the_reset_a_styled_truncation_appends() {+ // Cutting styled content leaves a style open, so truncate_visible closes+ // it with ESC[0m; stripping takes that with the rest, leaving the+ // ellipsis as the only trace of the truncation.+ let styled_header = || "\u{1b}[31mtwelve chars here\u{1b}[0m".to_string();++ let kept =+ ProgressiveTable::new_with_height(styled_header(), vec![], "f".into(), 8, None, false);+ // The color ansi_cut closes at the cut sits between the kept text and+ // the ellipsis, so the whitespace trim can't reach past it.+ assert_eq!(kept.lines[0], "\u{1b}[31mtwelve \u{1b}[39m…\u{1b}[0m");++ let stripped =+ ProgressiveTable::new_with_height(styled_header(), vec![], "f".into(), 8, None, true);+ assert_eq!(stripped.lines[0], "twelve …");+ }}diff --git a/src/commands/list/render.rs b/src/commands/list/render.rsindex c79fac697..c55ad3a7d 100644--- a/src/commands/list/render.rs+++ b/src/commands/list/render.rs@@ -1,7 +1,7 @@-use crate::display::{format_relative_time_short, shorten_path, truncate_to_width};+use crate::display::{format_relative_time_short, shorten_path};use anstyle::{Effects, Style};use unicode_width::UnicodeWidthStr;-use worktrunk::styling::{DETACHED, StyledLine};+use worktrunk::styling::{DETACHED, StyledLine, truncate_visible};use super::columns::{ColumnKind, DiffVariant};use super::layout::{@@ -604,7 +604,7 @@ impl ColumnLayout {Some(None) => StyledLine::new(),Some(Some(summary)) => {let mut cell = StyledLine::new();- let msg = truncate_to_width(summary, max_summary_len);+ let msg = truncate_visible(summary, max_summary_len);cell.push_styled(msg, Style::new());cell}@@ -614,7 +614,7 @@ impl ColumnLayout {return self.placeholder_cell(placeholder);};let mut cell = StyledLine::new();- let msg = truncate_to_width(&commit.commit_message, max_message_len);+ let msg = truncate_visible(&commit.commit_message, max_message_len);cell.push_styled(msg, Style::new().dimmed());cell}diff --git a/src/commands/mod.rs b/src/commands/mod.rsindex e369e55e3..c75d8ba1c 100644--- a/src/commands/mod.rs+++ b/src/commands/mod.rs@@ -189,7 +189,7 @@ pub(crate) fn show_diffstat(repo: &worktrunk::git::Repository, range: &str) -> alet mut args = vec!["diff", "--color=always", "--stat"];// With no detectable width, omit the flag and let git use its default width.let stat_width_arg;- if let Some(term_width) = crate::display::terminal_width() {+ if let Some(term_width) = worktrunk::styling::terminal_width() {let stat_width = term_width.saturating_sub(worktrunk::styling::GUTTER_OVERHEAD);stat_width_arg = format!("--stat-width={stat_width}");args.push(&stat_width_arg);diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex ff1023077..3b0988542 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -1652,7 +1652,7 @@ pub fn handle_picker(worktrunk::trace::instant("Picker config resolved");// Read the terminal size once, from the canonical reader that- // `crate::display::terminal_width` also projects (stderr first, then stdout,+ // `worktrunk::styling::terminal_width` also projects (stderr first, then stdout,// then `COLUMNS`). The skim list-column width (`skim_list_width` below)// derives from the same snapshot, so the two can never observe different// widths — whether across a resize or because stdout and stderr point to@@ -1664,7 +1664,7 @@ pub fn handle_picker(// before. The picker requires a TTY, so that fallback only bites the// headless dry-run / preview-bench paths; `skim_list_width` still uses the// `COLUMNS` width there.- let term_dims = crate::display::terminal_dimensions();+ let term_dims = worktrunk::styling::terminal_dimensions();let (term_width, term_height) = match term_dims {Some((w, Some(h))) => (w, h),_ => (80, 24),diff --git a/src/commands/picker/prs.rs b/src/commands/picker/prs.rsindex bb06af377..6575ec04e 100644--- a/src/commands/picker/prs.rs+++ b/src/commands/picker/prs.rs@@ -48,7 +48,9 @@ use serde::Deserialize;use skim::prelude::*;use unicode_width::UnicodeWidthStr;use worktrunk::git::{ForgeKind, RefType, Repository};-use worktrunk::styling::{HINT_SYMBOL, INFO_SYMBOL, StyledLine, WARNING_SYMBOL, warning_message};+use worktrunk::styling::{+ HINT_SYMBOL, INFO_SYMBOL, StyledLine, WARNING_SYMBOL, truncate_visible, warning_message,+};use super::super::list::ci_status::{CiSource, CiStatus, GitHubComment, GitHubPrInfo, PrRef, PrStatus, ReviewState,@@ -1070,7 +1072,7 @@ fn render_commit_lines(commits: &[(String, String)], abbrev: usize, width: usizefor (oid, headline) in commits {let short: String = oid.chars().take(abbrev).collect();let budget = width.saturating_sub(short.width() + 2).max(8);- let headline = crate::display::truncate_to_width(headline, budget);+ let headline = truncate_visible(headline, budget);out.push_str(&cformat!("<dim>{short}</>{reset} {headline}\n"));}out@@ -1306,7 +1308,7 @@ fn render_freeform_row(entry: &PrEntry, list_width: usize) -> String {let pr_ref = entry.pr_ref();let prefix_plain = format!("{pr_ref} ");let branch_budget = list_width.saturating_sub(prefix_plain.width()).max(8);- let head_branch = crate::display::truncate_to_width(&entry.head_branch, branch_budget);+ let head_branch = truncate_visible(&entry.head_branch, branch_budget);cformat!("<bold>{pr_ref}</> <cyan>{head_branch}</>")}diff --git a/src/commands/statusline.rs b/src/commands/statusline.rsindex 1a5e48f01..dfcd4ecb3 100644--- a/src/commands/statusline.rs+++ b/src/commands/statusline.rs@@ -26,12 +26,13 @@ use ansi_str::AnsiStr;use anyhow::{Context, Result};use worktrunk::git::{Repository, WorkingTree};use worktrunk::styling::{- fix_dim_after_color_reset, terminal_width_for_statusline, truncate_visible,+ ColorChoice, fix_dim_after_color_reset, println, terminal_width_for_statusline,+ truncate_visible,};use super::list::{self, CollectOptions, StatuslineSegment, json_output};use crate::cli::StatuslineFormat;-use crate::output::{print_json, println_verbatim};+use crate::output::print_json;/// Claude Code context parsed from stdin JSONstruct ClaudeCodeContext {@@ -723,14 +724,22 @@ fn format_context_gauge(percentage: f64) -> String {/// Run the statusline command.///-/// 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.+/// Output goes through anstream like every other stdout surface, with the+/// process-global [`ColorChoice`] set to `Always` so the escapes survive:+/// 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.worktrunk::config::suppress_warnings();+ // A shell prompt or Claude Code captures this line and re-renders it, so+ // the escapes are part of the answer rather than presentation this process+ // chose. `Always` is the conventional `--color=always` semantic and+ // overrides `NO_COLOR` by design — an explicit request for color wins+ // (no-color.org).+ ColorChoice::Always.write_global();+// JSON format: output current worktree as JSONif matches!(format, StatuslineFormat::Json) {return run_json();@@ -846,7 +855,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_verbatim!("{}", output);+ println!("{}", output);Ok(())}diff --git a/src/display.rs b/src/display.rsindex 1192d7730..6491e30e5 100644--- a/src/display.rs+++ b/src/display.rs@@ -3,15 +3,11 @@//! This module provides utility functions for://! - Relative time formatting//! - Path manipulation and shortening-//! - Text truncation with word boundaries-//! - Terminal width detectionuse std::path::{Component, Path};use path_slash::PathExt as _;-use unicode_width::UnicodeWidthChar;use worktrunk::path::format_path_for_display;-use worktrunk::styling::visual_width;use worktrunk::utils::epoch_now;/// Format timestamp as abbreviated relative time (e.g., "2h")@@ -87,119 +83,11 @@ pub(crate) fn shorten_path(path: &Path, main_worktree_path: &Path) -> String {}}-/// Truncate text with ellipsis at exact width limit.-///-/// Truncates at character boundary (mid-word if needed) to fill the allocated-/// column width exactly. This ensures consistent table output width.-pub(crate) fn truncate_to_width(text: &str, max_width: usize) -> String {- if visual_width(text) <= max_width {- return text.to_string();- }-- // Build up string until we hit the width limit (accounting for "…" = 1 width)- let target_width = max_width.saturating_sub(1);- let mut current_width = 0;- let mut last_idx = 0;-- for (idx, ch) in text.char_indices() {- let char_width = ch.width().unwrap_or(0);- if current_width + char_width > target_width {- break;- }- current_width += char_width;- last_idx = idx + ch.len_utf8();- }-- // Truncate at exact character boundary (mid-word if needed)- let truncated = text[..last_idx].trim_end();- format!("{}…", truncated)-}--// Re-export from styling for convenience-pub(crate) use worktrunk::styling::{terminal_dimensions, terminal_width, truncate_visible};-#[cfg(test)]mod tests {use super::*;use std::path::PathBuf;- #[test]- fn test_truncate_normal_case() {- let text = "Fix bug with parsing and more text here";- let result = truncate_to_width(text, 25);- println!("Normal truncation: '{}'", result);- assert!(result.ends_with('…'));- }-- #[test]- fn test_truncate_with_existing_ascii_ellipsis() {- let text = "Fix bug with parsing... more text here";- let result = truncate_to_width(text, 25);- // Shows what happens when truncation lands on existing "..."- println!("ASCII ellipsis: '{}'", result);- assert!(result.ends_with('…'));- }-- #[test]- fn test_truncate_with_existing_unicode_ellipsis() {- let text = "Fix bug with parsing… more text here";- let result = truncate_to_width(text, 25);- // Shows what happens when truncation lands on existing "…"- println!("Unicode ellipsis: '{}'", result);- assert!(result.ends_with('…'));- }-- #[test]- fn test_truncate_already_has_three_dots() {- let text = "Short text...";- let result = truncate_to_width(text, 20);- // When text fits, should return as-is- assert_eq!(result, "Short text...");- }-- #[test]- fn test_truncate_exact_width() {- let text = "This is a very long message that needs truncation";- let result = truncate_to_width(text, 30);- assert!(result.ends_with('…'));- assert!(- !result.contains(" …"),- "Should not have space before ellipsis"- );- // Should truncate at exact width (mid-word if needed)- use unicode_width::UnicodeWidthStr;- assert_eq!(result.width(), 30);- }-- #[test]- fn test_truncate_unicode_width() {- let text = "Fix bug with café ☕ and more text";- let result = truncate_to_width(text, 25);- use unicode_width::UnicodeWidthStr;- assert!(- result.width() <= 25,- "Width {} should be <= 25",- result.width()- );- }-- #[test]- fn test_truncate_no_truncation_needed() {- let text = "Short message";- let result = truncate_to_width(text, 50);- assert_eq!(result, text);- }-- #[test]- fn test_truncate_very_long_word() {- let text = "Supercalifragilisticexpialidocious extra text";- let result = truncate_to_width(text, 20);- use unicode_width::UnicodeWidthStr;- // Should truncate mid-word if no space found- assert!(result.width() <= 20, "Width should be <= 20");- assert!(result.ends_with('…'));- }-#[test]fn test_format_relative_time_short() {let now: i64 = 1700000000; // Fixed timestamp for testing@@ -302,23 +190,4 @@ mod tests {// Should be after 2020 (1577836800)assert!(now > 1577836800, "epoch_now() should return current time");}-- #[test]- fn test_truncate_edge_cases() {- // Empty string- let result = truncate_to_width("", 10);- assert_eq!(result, "");-- // Single character- let result = truncate_to_width("X", 10);- assert_eq!(result, "X");-- // Exact width- let result = truncate_to_width("12345", 5);- assert_eq!(result, "12345");-- // Just over width- let result = truncate_to_width("123456", 5);- assert!(result.ends_with('…'));- }}diff --git a/src/help.rs b/src/help.rsindex b13e9a260..8bdb0705d 100644--- a/src/help.rs+++ b/src/help.rs@@ -49,16 +49,14 @@ use std::ffi::OsString;use std::process;use ansi_str::AnsiStr;-use clap::ColorChoice;use clap::error::ErrorKind;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, print};+use worktrunk::styling::{ColorChoice, eprintln, print, println};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@@ -70,8 +68,13 @@ enum PageMode {}impl PageMode {- /// ANSI color for the embedded `--help` reference block. Web keeps ANSI so- /// it can be converted to HTML downstream; plain strips it.+ /// The page's one color choice, declared globally for the stdout it+ /// prints to. The embedded `--help` reference block always renders with+ /// escapes and the stream decides what survives: web keeps them for the+ /// docs pipeline to turn into HTML spans, plain strips them for the+ /// portable markdown skill files read. Both generators read a pipe rather+ /// than a tty, so without the global web's escapes would be stripped+ /// every time.fn color(self) -> ColorChoice {match self {Self::Web => ColorChoice::Always,@@ -123,19 +126,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 => println_verbatim!(+ Self::Web => println!("{MARKER_OPEN_PREFIX}`wt {subcommand} --help-page` — edit src/cli/mod.rs to update -->"),- Self::Plain => println_verbatim!("# wt {subcommand}"),+ Self::Plain => println!("# wt {subcommand}"),}- println_verbatim!();+ println!();}/// Emit the closing END marker (web only).fn emit_footer(self) {if matches!(self, Self::Web) {- println_verbatim!();- println_verbatim!("{MARKER_CLOSE}");+ println!();+ println!("{MARKER_CLOSE}");}}}@@ -205,7 +208,6 @@ pub fn maybe_handle_help_with_pager(if args.iter().any(|a| a == "--help-md") {let mut cmd = cli::build_command();cmd = crate::completion::inject_hook_subcommands(cmd);- cmd = cmd.color(ColorChoice::Never); // No ANSI codes for raw markdown// Replace --help-md with --help for claplet filtered_args: Vec<String> = args@@ -225,7 +227,11 @@ pub fn maybe_handle_help_with_pager(ErrorKind::DisplayHelp | ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand){- let output = normalize_clap_help_fences(&err.render().to_string());+ // Escape-free markdown on stdout is this entry point's contract,+ // tty or not, so the choice is declared rather than left to the+ // stream's tty check.+ ColorChoice::Never.write_global();+ let output = normalize_clap_help_fences(&err.render().ansi().to_string());print!("{output}");process::exit(0);}@@ -234,13 +240,12 @@ pub fn maybe_handle_help_with_pager(let mut cmd = cli::build_command();cmd = crate::completion::inject_hook_subcommands(cmd);- cmd = cmd.color(clap::ColorChoice::Always); // Force clap to emit ANSI codesif let Err(err) = cmd.try_get_matches_from_mut(args_os) {match err.kind() {ErrorKind::DisplayHelp | ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand => {- // err.render() returns a StyledStr containing ANSI codes.- // Use .ansi() to preserve them; .to_string() strips ANSI codes.+ // .ansi() renders the StyledStr's styles as escapes; its+ // Display renders the text without them.let clap_output = err.render().ansi().to_string();// Splice configured aliases into `wt --help` and@@ -279,24 +284,15 @@ pub fn maybe_handle_help_with_pager(}}-/// Get the help reference block with configurable color output.-///-/// `ColorChoice::Always` produces ANSI codes for HTML conversion (web docs).-/// `ColorChoice::Never` produces plain text (skill reference files).-fn help_reference_with_color(- command_path: &[&str],- width: Option<usize>,- color: ColorChoice,-) -> String {- let output = help_reference_inner(command_path, width, color);- if matches!(color, ColorChoice::Always) {- // Strip OSC 8 hyperlinks. Clap generates these from markdown links like [text](url),- // but web docs convert ANSI to HTML via ansi_to_html which only handles SGR codes- // (colors), not OSC sequences - hyperlinks leak through as garbage.- worktrunk::styling::strip_osc8_hyperlinks(&output)- } else {- output- }+/// The help reference block, rendered with ANSI codes for the page's stdout+/// stream to keep or strip.+fn help_reference(command_path: &[&str], width: Option<usize>) -> String {+ let output = help_reference_inner(command_path, width);+ // Strip OSC 8 hyperlinks. Clap generates these from markdown links like [text](url),+ // but web docs convert ANSI to HTML via ansi_to_html which only handles SGR codes+ // (colors), not OSC sequences - hyperlinks leak through as garbage. The plain+ // stream drops them anyway, so the strip runs unconditionally.+ worktrunk::styling::strip_osc8_hyperlinks(&output)}/// Normalize fences in clap-rendered help output for downstream markdown@@ -311,7 +307,7 @@ fn normalize_clap_help_fences(text: &str) -> String {.replace("```console\n", "```bash\n")}-fn help_reference_inner(command_path: &[&str], width: Option<usize>, color: ColorChoice) -> String {+fn help_reference_inner(command_path: &[&str], width: Option<usize>) -> String {// Build args: ["wt", "config", "create", "--help"]let mut args: Vec<String> = vec!["wt".to_string()];args.extend(command_path.iter().map(|s| s.to_string()));@@ -319,7 +315,6 @@ fn help_reference_inner(command_path: &[&str], width: Option<usize>, color: Cololet mut cmd = cli::build_command();cmd = crate::completion::inject_hook_subcommands(cmd);- cmd = cmd.color(color);if let Some(w) = width {cmd = cmd.term_width(w);}@@ -329,15 +324,7 @@ fn help_reference_inner(command_path: &[&str], width: Option<usize>, color: Coloerr.kind(),ErrorKind::DisplayHelp | ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand) {- let rendered = err.render();- // .ansi() preserves ANSI codes; .to_string() strips them.- // Use .ansi() only when colors are enabled (for web HTML conversion).- let text = if matches!(color, ColorChoice::Always) {- rendered.ansi().to_string()- } else {- rendered.to_string()- };- normalize_clap_help_fences(&text)+ normalize_clap_help_fences(&err.render().ansi().to_string())} else {return String::new();};@@ -418,7 +405,6 @@ fn extract_about_and_subtitle(cmd: &clap::Command) -> (Option<String>, Option<Stfn handle_help_description(subcommand: Option<&str>) {let mut cmd = cli::build_command();cmd = crate::completion::inject_hook_subcommands(cmd);- cmd = cmd.color(ColorChoice::Never);let Some(subcommand) = subcommand else {eprintln!("Usage: wt <command> --help-description");@@ -491,9 +477,12 @@ Commands with schemas: list"////// This is used to generate docs/content/merge.md etc from the source.fn handle_help_page(subcommand: Option<&str>, mode: PageMode) {+ // This page's stdout is a pipe to a generator rather than a tty, so the+ // mode decides its color.+ mode.color().write_global();+let mut cmd = cli::build_command();cmd = crate::completion::inject_hook_subcommands(cmd);- cmd = cmd.color(ColorChoice::Never);let Some(subcommand) = subcommand else {eprintln!(@@ -520,21 +509,18 @@ 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());+ let reference_block = help_reference(&[subcommand], Some(100));- // 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);- println_verbatim!("{}", main_help.trim());- println_verbatim!();+ println!("{}", main_help.trim());+ println!();// Main command reference immediately after its content- println_verbatim!("## Command reference");- println_verbatim!();- println_verbatim!("```");- println_verbatim!("{}", reference_block.trim());- println_verbatim!("```");+ println!("## Command reference");+ println!();+ println!("```");+ println!("{}", reference_block.trim());+ println!("```");// Subdocs follow, each with their own command reference at the end.if let Some(subdocs) = subdoc_content {@@ -543,10 +529,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);- println_verbatim!();- println_verbatim!("# Subcommands");- println_verbatim!();- println_verbatim!("{}", subdocs_expanded.trim());+ println!();+ println!("# Subcommands");+ println!();+ println!("{}", subdocs_expanded.trim());}mode.emit_footer();@@ -810,7 +796,7 @@ fn format_subcommand_section(.chain(std::iter::once(subcommand_name)).collect();- let reference_block = help_reference_with_color(&command_path, Some(100), mode.color());+ let reference_block = help_reference(&command_path, Some(100));// Format the section: heading, badge (outside heading), main content, command referencelet mut section = format!("## {full_command}\n\n");diff --git a/src/logging.rs b/src/logging.rsindex 5b6d79343..402bdeb55 100644--- a/src/logging.rs+++ b/src/logging.rs@@ -619,7 +619,10 @@ where.from_env_lossy();let exclude_full = target_filter(|meta| meta.target() != SUBPROCESS_FULL_TARGET);let layer = tracing_subscriber::fmt::layer()- .with_writer(std::io::stderr)+ // `with_ansi(true)` keeps the formatter emitting styles; the+ // `AutoStream` writer strips or passes them per anstream's resolved+ // choice (global override, tty, NO_COLOR/CLICOLOR_FORCE).+ .with_writer(|| anstream::AutoStream::auto(std::io::stderr())).with_ansi(true).event_format(StderrFormat).with_filter(env_filter.and(exclude_full));diff --git a/src/main.rs b/src/main.rsindex 77f7cab5f..0a750665c 100644--- a/src/main.rs+++ b/src/main.rs@@ -1,6 +1,6 @@use clap::FromArgMatches;use clap::error::ErrorKind as ClapErrorKind;-use color_print::{ceprintln, cformat};+use color_print::cformat;use std::process;use worktrunk::config::{set_config_overrides, set_config_path};use worktrunk::git::{@@ -76,10 +76,15 @@ fn print_enhanced_clap_error(err: &clap::Error) {{let cmd = cli::build_command();if let Some(suggestion) = cli::suggest_nested_subcommand(&cmd, &unknown.to_string()) {- ceprintln!(- "{}+ // anstream's eprintln, so the stream's resolved color choice+ // governs cformat's escapes.+ eprintln!(+ "{}",+ cformat!(+ "{}<yellow>tip:</> perhaps <cyan,bold>{suggestion}</cyan,bold>?",- err.render().ansi()+ err.render().ansi()+ ));return;}diff --git a/src/output/global.rs b/src/output/global.rsindex d5e190dd4..b807f52c3 100644--- a/src/output/global.rs+++ b/src/output/global.rs@@ -64,7 +64,7 @@ use worktrunk::shell_exec::scrub_git_discovery_env_vars;use worktrunk::shell_exec::{DIRECTIVE_CD_FILE_ENV_VAR, DIRECTIVE_EXEC_FILE_ENV_VAR, RETIRED_DIRECTIVE_FILE_ENV_VAR,};-use worktrunk::styling::{hint_message, warning_message};+use worktrunk::styling::{hint_message, stderr, warning_message};/// Issue tracking whether to relax the EXEC scrub further for project aliases/// and hooks. (User aliases already pass EXEC through.) Emitted in the warning@@ -548,9 +548,9 @@ pub fn terminate_output() -> io::Result<()> {return Ok(());}- let mut stderr = io::stderr();-- // Reset ANSI state before returning to shell+ // Reset ANSI state before returning to shell. With color off anstream+ // strips the reset, which is correct — nothing emitted color.+ let mut stderr = stderr();write!(stderr, "{}", anstyle::Reset)?;stderr.flush()}diff --git a/src/output/mod.rs b/src/output/mod.rsindex 50db613f8..41617b974 100644--- a/src/output/mod.rs+++ b/src/output/mod.rs@@ -3,8 +3,7 @@//! # Architecture//!//! For regular output, use `eprintln!`/`println!` directly (from `worktrunk::styling`-//! for color support); [`print_json`] serializes a `--format=json` answer to stdout,-//! and [`println_verbatim`] writes a line whose color is already resolved.+//! for color support); [`print_json`] serializes a `--format=json` answer to stdout.//! This module handles shell integration directives (cd, exec) that need to be//! communicated to the parent shell.//!@@ -37,7 +36,6 @@ pub(crate) mod handlers;mod json;pub(crate) mod prompt;pub(crate) mod shell_integration;-mod verbatim;// Re-export the public APIpub(crate) use global::{@@ -61,5 +59,3 @@ pub(crate) use shell_integration::{pub(crate) use commit_generation::prompt_commit_generation;// Re-export the JSON answer printerpub(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.rsdeleted file mode 100644index 2ed6f37e6..000000000--- a/src/output/verbatim.rs+++ /dev/null@@ -1,40 +0,0 @@-//! 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/src/styling/line.rs b/src/styling/line.rsindex 9404f331a..ecda89560 100644--- a/src/styling/line.rs+++ b/src/styling/line.rs@@ -7,8 +7,23 @@ use anstyle::Style;use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};/// Truncate a styled string to a visible width budget, preserving escapes.-/// Escape sequences (ANSI/OSC) are zero-width; ellipsis ("…") is added when truncating.-/// Appends ESC[0m on truncation to avoid style bleed.+///+/// The budget counts what the terminal draws: escape sequences (ANSI/OSC) are+/// zero-width, and characters are measured by their unicode width, so a cut+/// never lands inside an escape and never overshoots on wide characters. Text+/// that already fits is returned untouched.+///+/// A cut ends the kept prefix with "…", after trimming the trailing whitespace+/// the cut exposed so no space hangs before the marker. Trimming is+/// best-effort: `ansi_cut` closes any style still open at the cut, and that+/// trailing escape blocks it.+///+/// A cut that keeps any escape also appends a reset, so a style opened before+/// the cut can't bleed past it. Text with no escapes has nothing to close and+/// stays plain.+///+/// A zero budget yields an empty string; a budget with room for nothing but the+/// ellipsis yields the bare ellipsis, with no prefix and so no reset.pub fn truncate_visible(rendered: &str, max_width: usize) -> String {truncate_visible_with_ellipsis(rendered, max_width, "…")}@@ -28,10 +43,7 @@ fn truncate_visible_with_ellipsis(rendered: &str, max_width: usize, ellipsis: &slet ellipsis_width = UnicodeWidthStr::width(ellipsis);let budget = max_width.saturating_sub(ellipsis_width);if budget == 0 {- let mut out = String::new();- out.push_str(ellipsis);- out.push_str("\u{1b}[0m");- return out;+ return ellipsis.to_owned();}let mut cut_at = 0;@@ -46,8 +58,12 @@ fn truncate_visible_with_ellipsis(rendered: &str, max_width: usize, ellipsis: &s}let mut out = rendered.ansi_cut(..cut_at).into_owned();+ out.truncate(out.trim_end().len());+ let carries_style = out.contains('\u{1b}');out.push_str(ellipsis);- out.push_str("\u{1b}[0m");+ if carries_style {+ out.push_str(&anstyle::Reset.to_string());+ }out}@@ -198,23 +214,25 @@ mod tests {assert_eq!(UnicodeWidthStr::width(s.ansi_strip().as_ref()), 1,);}- /// truncate_visible respects visual width, handles emoji, and appends reset codes.+ /// truncate_visible keeps the result within the visible budget, counting+ /// escapes as zero-width and wide characters as their display width.#[test]fn test_truncate_visible() {use ansi_str::AnsiStr;let visible_width = |s: &str| UnicodeWidthStr::width(s.ansi_strip().as_ref());- // Truncates colored text to budget, ends with reset- let colored = "\u{1b}[31mhello\u{1b}[0m";- let out = truncate_visible(colored, 3);+ // Escapes don't consume budget+ let out = truncate_visible("\u{1b}[31mhello\u{1b}[0m", 3);assert_eq!(visible_width(&out), 3);- assert!(out.ends_with("\u{1b}[0m"));// Wide emoji (width 2) truncated to budget 1let out = truncate_visible("🚀", 1);assert_eq!(visible_width(&out), 1);+ // A wide character straddling the cut is dropped, not split+ assert_eq!(truncate_visible("café ☕ and more", 7), "café…");+// Zero width → emptyassert!(truncate_visible("hello world", 0).is_empty());@@ -226,6 +244,30 @@ mod tests {assert!(visible_width(&out) <= 1);}+ /// The ellipsis replaces the whitespace a cut exposes; where the cut lands+ /// mid-word it fills the budget exactly.+ #[test]+ fn test_truncate_visible_trims_before_the_ellipsis() {+ assert_eq!(truncate_visible("hello world", 7), "hello…");++ let out = truncate_visible("This is a very long message that needs truncation", 30);+ assert_eq!(out, "This is a very long message t…");+ assert_eq!(UnicodeWidthStr::width(out.as_str()), 30);+ }++ /// A cut closes the styles it leaves open, and leaves plain text plain.+ #[test]+ fn test_truncate_visible_resets_only_styled_cuts() {+ assert!(!truncate_visible("hello world", 8).contains('\u{1b}'));++ let out = truncate_visible("\u{1b}[31mhello world\u{1b}[0m", 8);+ assert!(out.ends_with("…\u{1b}[0m"), "{out:?}");++ // Budget with room for nothing but the ellipsis keeps no prefix, so+ // there is no style to close.+ assert_eq!(truncate_visible("\u{1b}[31mhello\u{1b}[0m", 1), "…");+ }+/// StyledLine composition: push, extend, render, plain_text all produce correct output.#[test]fn test_styled_line_composition() {diff --git a/src/styling/mod.rs b/src/styling/mod.rsindex 88e10ad9c..d41b48665 100644--- a/src/styling/mod.rs+++ b/src/styling/mod.rs@@ -24,7 +24,7 @@ use ansi_str::AnsiStr;use unicode_width::UnicodeWidthStr;// Re-exports from anstream (auto-detecting output)-pub use anstream::{eprint, eprintln, print, println, stderr, stdout};+pub use anstream::{ColorChoice, eprint, eprintln, print, println, stderr, stdout};// Re-exports from anstyle (for composition)pub use anstyle::Style as AnstyleStyle;diff --git a/tests/integration_tests/list_progressive.rs b/tests/integration_tests/list_progressive.rsindex b269a58dd..5f5f351de 100644--- a/tests/integration_tests/list_progressive.rs+++ b/tests/integration_tests/list_progressive.rs@@ -5,7 +5,8 @@#![cfg(all(unix, feature = "shell-integration-tests"))]use crate::common::progressive_output::{ProgressiveCaptureOptions, capture_progressive_output};-use crate::common::{TestRepo, repo};+use crate::common::pty::{build_pty_command, exec_cmd_in_pty};+use crate::common::{TestRepo, repo, wt_bin};use rstest::rstest;/// Tests progressive rendering with multiple worktrees.@@ -179,3 +180,53 @@ fn test_list_progressive_fast_command(repo: TestRepo) {output.final_output());}++/// The progressive render applies the stream's resolved color choice to its+/// content: under `NO_COLOR` the raw PTY byte stream carries no SGR sequence+/// while the cursor-control CSI the in-place redraw is built on still flows —+/// distinguishing a stripped progressive render from a fall-through to the+/// buffered path, whose stream would carry no escapes at all. The forced run+/// proves the same command emits SGR when color is on, so the absence check+/// can't pass vacuously.+#[rstest]+fn test_list_progressive_honors_no_color(mut repo: TestRepo) {+ repo.add_worktree("feature-color");+ let sgr = regex::Regex::new(r"\x1b\[[0-9;]*m").unwrap();++ let capture = |no_color: bool| {+ let mut cmd = build_pty_command(+ wt_bin().to_str().unwrap(),+ &["list", "--full", "--branches"],+ repo.root_path(),+ &repo.test_env_vars(),+ None,+ );+ if no_color {+ // configure_pty_command sets the suite's CLICOLOR_FORCE=1, which+ // outranks NO_COLOR in anstream's resolution — remove it so the+ // choice resolves to Never.+ cmd.env_remove("CLICOLOR_FORCE");+ cmd.env("NO_COLOR", "1");+ }+ exec_cmd_in_pty(cmd, "")+ };++ let (plain, exit_code) = capture(true);+ assert_eq!(exit_code, 0);+ assert!(plain.contains("feature-color"), "output:\n{plain}");+ assert!(+ plain.contains("\x1b["),+ "cursor-control CSI should still flow under NO_COLOR:\n{plain:?}"+ );+ assert!(+ !sgr.is_match(&plain),+ "no SGR should reach the terminal under NO_COLOR:\n{plain:?}"+ );++ let (forced, exit_code) = capture(false);+ assert_eq!(exit_code, 0);+ assert!(+ sgr.is_match(&forced),+ "forced color should emit SGR:\n{forced:?}"+ );+}diff --git a/tests/integration_tests/output_system_guard.rs b/tests/integration_tests/output_system_guard.rsindex ef720de1a..2a7ff58e2 100644--- a/tests/integration_tests/output_system_guard.rs+++ b/tests/integration_tests/output_system_guard.rs@@ -1,4 +1,4 @@-//! Guard test to prevent stdout leaks in command code+//! Guard test to prevent stdout leaks anywhere in the crate//!//! stdout carries the command's answer — content the user may want to pipe,//! redirect, or capture: data (JSON, tables), rendered views (`wt config show`,@@ -7,19 +7,20 @@//! errors go to stderr. When shell integration is active (directive env vars//! set), directives are written to files, not stdout.//!-//! This test enforces: **No accidental stdout writes in command code**+//! This test enforces: **No accidental stdout writes anywhere under `src/`**//!//! Allowed://! - `eprintln!` / `eprint!` (stderr is safe)//! - `println!` / `print!` in files listed in `STDOUT_ALLOWED_PATHS`//!//! When adding stdout 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`)+//! - Use `worktrunk::styling::println`. Where the consumer renders the escapes+//! and is never a tty (the statusline, `--help-page`), declare that once at+//! the top of the command with `ColorChoice::Always.write_global()` — the+//! global anstream consults before tty detection — and print normally.//! - Add the file path to `STDOUT_ALLOWED_PATHS` with a comment explaining why//!-//! Neither printer panics when the consumer closes the pipe, which+//! anstream's macros don't panic when the consumer closes the pipe, which//! [`test_stdout_surfaces_survive_a_closed_consumer`] checks from the outside.use std::fs;@@ -31,76 +32,93 @@ use rstest::rstest;use crate::common::{TestRepo, repo};-/// Paths (relative to src/commands/) that are allowed to use println!/print! for stdout.+/// Paths (relative to src/) 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",+ "commands/init.rs",// Table and summary output for wt list- "list/collect/mod.rs",+ "commands/list/collect/mod.rs",// State data output (branch names, previous worktree, etc.)- "config/state.rs",+ "commands/config/state.rs",// Hint list output- "config/hints.rs",+ "commands/config/hints.rs",// Alias introspection output (show / dry-run), intended to be pipeable- "config/alias.rs",+ "commands/config/alias.rs",// Template evaluation output for scripting- "eval.rs",+ "commands/eval.rs",// LLM prompt output for wt step commit --show-prompt and squash --show-prompt- "step/commit.rs",- "step/squash.rs",+ "commands/step/commit.rs",+ "commands/step/squash.rs",// wt step copy-ignored dry-run plan (human preview + --format=json)- "step/copy_ignored.rs",+ "commands/step/copy_ignored.rs",// wt step prune dry-run plan (human preview + --format=json)- "step/prune.rs",+ "commands/step/prune.rs",// wt step relocate dry-run human preview (show_dry_run_preview)- "relocate.rs",+ "commands/relocate.rs",// wt config shell install/uninstall --dry-run preview (the interactive// `?` re-preview still goes to stderr)- "configure_shell.rs",+ "commands/configure_shell.rs",// JSON output for wt switch --format=json- "worktree/switch.rs",+ "commands/worktree/switch.rs",// Migrated TOML output for wt config update --print (pipeable)- "config/update.rs",+ "commands/config/update.rs",// Hook listing for wt hook show (paged), and the wt hook --dry-run preview- "hook_commands.rs",+ "commands/hook_commands.rs",+ // The statusline itself — a single line a shell prompt or Claude Code captures+ "commands/statusline.rs",+ // The --format=json answer for every command that has one+ "output/json.rs",+ // The doc entry points (--help-page, --help-md, --help-description) and+ // --version: help text is the command's answer, on stdout by POSIX+ // convention, and a generator or `version=$(wt --version)` reads it+ "help.rs",+ // wt --help / -h itself, whenever no pager takes the text (short help, no+ // pager configured, stdout not a tty, or the pager failed to spawn)+ "help_pager.rs",+ // The mock commands the suite puts on PATH under names like gh and glab:+ // this stdout is the mocked tool's output, read by the wt under test+ "testing/mock_stub.rs",];-/// Substrings that indicate the line is a special case (e.g., in a comment or test reference)+/// Substrings that mark a line where the token is text rather than a call+/// (inside a string literal, a comment, or a reference to a test file)const ALLOWED_LINE_PATTERNS: &[&str] = &[- "spacing_test.rs", // Test file reference+ // The `println!` inside llm.rs's SYNTHETIC_DIFF string literal is a line of+ // the fake diff a commit-message prompt is built from, not a call+ r#"println!("Hello, world!");"#,];+/// No file under `src/` writes to stdout unless it is listed as a surface that+/// deliberately does. The scan covers the whole crate rather than just+/// `src/commands/`: `src/help.rs` carries the answer for `--help-page` and+/// `--version`, and while it was outside the scanned tree its std `println!`s+/// panicked on a closed consumer unnoticed.#[test]-fn check_no_stdout_in_commands() {+fn check_no_unexpected_stdout_writes() {let project_root = env!("CARGO_MANIFEST_DIR");- let commands_dir = Path::new(project_root).join("src/commands");+ let src_dir = Path::new(project_root).join("src");// Forbidden tokens that write to stdoutlet stdout_tokens = ["print!", "println!"];let mut violations = Vec::new();- // Recursively scan all .rs files under src/commands/- scan_directory(- &commands_dir,- &stdout_tokens,- &mut violations,- &commands_dir,- );+ // Recursively scan all .rs files under src/+ scan_directory(&src_dir, &stdout_tokens, &mut violations, &src_dir);if !violations.is_empty() {panic!(- "Unexpected stdout writes in command code:\n\n{}\n\n\+ "Unexpected stdout writes:\n\n{}\n\n\stdout is reserved for data output (JSON, tables).\n\- Use worktrunk::styling::println for stdout, eprintln for stderr.\n\+ Use worktrunk::styling::println for stdout, and its eprintln — not color_print's ceprintln! — for stderr.\n\Add file path to STDOUT_ALLOWED_PATHS if stdout is intentional.",violations.join("\n"));}}-fn scan_directory(dir: &Path, tokens: &[&str], violations: &mut Vec<String>, commands_dir: &Path) {+fn scan_directory(dir: &Path, tokens: &[&str], violations: &mut Vec<String>, scan_root: &Path) {let entries = match fs::read_dir(dir) {Ok(e) => e,Err(_) => return,@@ -110,17 +128,17 @@ fn scan_directory(dir: &Path, tokens: &[&str], violations: &mut Vec<String>, comlet path = entry.path();if path.is_dir() {- scan_directory(&path, tokens, violations, commands_dir);+ scan_directory(&path, tokens, violations, scan_root);} else if path.extension().and_then(|s| s.to_str()) == Some("rs") {- check_file(&path, tokens, violations, commands_dir);+ check_file(&path, tokens, violations, scan_root);}}}-fn check_file(path: &Path, tokens: &[&str], violations: &mut Vec<String>, commands_dir: &Path) {- // Get path relative to src/commands/ for matching against STDOUT_ALLOWED_PATHS+fn check_file(path: &Path, tokens: &[&str], violations: &mut Vec<String>, scan_root: &Path) {+ // Get path relative to src/ for matching against STDOUT_ALLOWED_PATHSlet relative_path = path- .strip_prefix(commands_dir)+ .strip_prefix(scan_root).map(|p| p.to_slash_lossy()).unwrap_or_default();@@ -150,20 +168,19 @@ fn check_file(path: &Path, tokens: &[&str], violations: &mut Vec<String>, commanfor token in tokens {if let Some(pos) = line.find(token) {- // Skip eprint!/eprintln! - they go to stderr and are safe- // When we match print!/println!, check if preceded by 'e' (part of eprint/eprintln)- // Also verify the 'e' is at a word boundary (start of line, or after non-alphanumeric)- if pos > 0 {- let prev_char = line.as_bytes()[pos - 1];- if prev_char == b'e' {- // Check this 'e' is at a word boundary (not part of some_eprint)- if pos == 1- || !line.as_bytes()[pos - 2].is_ascii_alphanumeric()- && line.as_bytes()[pos - 2] != b'_'- {- continue;- }- }+ // The token also sits inside the stderr macros eprint!/eprintln!,+ // which are safe. Walk back over the identifier the token ends+ // and let that prefix through. color_print's ceprint!/ceprintln!+ // write through std's stderr directly, bypassing anstream's+ // resolved color choice, so they stay violations — as does a+ // longer identifier like some_eprintln!.+ let ident_start = line[..pos]+ .char_indices()+ .rev()+ .find(|(_, c)| !c.is_alphanumeric() && *c != '_')+ .map_or(0, |(i, c)| i + c.len_utf8());+ if &line[ident_start..pos] == "e" {+ continue;}// Skip if the token is in a comment@@ -190,12 +207,12 @@ fn check_file(path: &Path, tokens: &[&str], violations: &mut Vec<String>, comman/// 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.+/// on the surface a shell prompt runs on every redraw. anstream's macros drop+/// that error instead, and they now carry 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.+/// How a surface resolves color — the process-global `ColorChoice` or tty+/// detection — is a separate axis, 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@@ -240,3 +257,97 @@ fn test_stdout_surfaces_survive_a_closed_consumer(repo: TestRepo) {);}}++/// Whether stdout carries ANSI escapes is the consumer's call, except where a+/// command declares otherwise.+///+/// Color resolves in one place — anstream's `AutoStream::choice`: the+/// process-global `ColorChoice` a command may write first, then tty detection+/// and the `NO_COLOR` / `CLICOLOR_FORCE` conventions. The rest of the suite+/// runs with `CLICOLOR_FORCE=1` (`STATIC_TEST_ENV_VARS`), which settles that+/// question before anstream reaches the interesting part, so no other test can+/// see which way it decides — the statusline losing its escapes to a strip was+/// invisible to a green suite. These cases clear both variables and read a+/// piped stdout, the environment a real consumer provides, and are the one+/// place the unforced contract is pinned.+#[rstest]+fn test_color_follows_the_consumer(repo: TestRepo) {+ // (args, extra env, stdout carries ANSI escapes, what the case pins)+ for (args, env, expect_escapes, pins) in [+ (+ &["list", "statusline"][..],+ None,+ true,+ "the statusline declares Always because its consumer renders the escapes",+ ),+ (+ &["list", "statusline"][..],+ Some(("NO_COLOR", "1")),+ true,+ "a declared Always outranks NO_COLOR, as --color=always conventionally does",+ ),+ (+ &["merge", "--help-page"][..],+ None,+ true,+ "the web reference block's ANSI is data the docs pipeline turns into HTML spans",+ ),+ (+ &["merge", "--help-page", "--plain"][..],+ None,+ false,+ "plain pages are the portable markdown skill reference files read",+ ),+ (+ &["list"][..],+ None,+ false,+ "human output strips when it is piped rather than displayed",+ ),+ (+ &["list"][..],+ Some(("CLICOLOR_FORCE", "1")),+ true,+ "force-on reaches a piped consumer that wants the color anyway",+ ),+ ] {+ let mut command = repo.wt_command();+ command+ .args(args)+ // The fixture forces color on for every other test; removing both+ // conventions is what leaves the decision to anstream.+ .env_remove("CLICOLOR_FORCE")+ .env_remove("NO_COLOR");+ if let Some((key, value)) = env {+ command.env(key, value);+ }++ // `output()` pipes stdout, so the child's consumer is not a terminal.+ let output = command+ .output()+ .unwrap_or_else(|e| panic!("failed to run wt {args:?}: {e}"));++ let case = match env {+ Some((key, value)) => format!("wt {} with {key}={value}", args.join(" ")),+ None => format!("wt {}", args.join(" ")),+ };+ let stderr = String::from_utf8_lossy(&output.stderr);+ let stdout = String::from_utf8_lossy(&output.stdout);++ assert!(+ output.status.success(),+ "{case} exited {:?}; stderr: {stderr}",+ output.status.code()+ );+ // Without this an empty answer would satisfy every strip case.+ assert!(+ !stdout.is_empty(),+ "{case} wrote nothing to stdout; stderr: {stderr}"+ );+ assert_eq!(+ stdout.contains("\u{1b}["),+ expect_escapes,+ "{case}: expected stdout to carry ANSI escapes: {expect_escapes} — {pins}"+ );+ }+}diff --git a/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_worktree_path_prompt_auto_accept.snap b/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_worktree_path_prompt_auto_accept.snapindex 1ef4325ce..3bf0189d9 100644--- a/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_worktree_path_prompt_auto_accept.snap+++ b/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_worktree_path_prompt_auto_accept.snap@@ -48,4 +48,3 @@ exit_code: 0worktree-path = "{{ repo_path }}/../{{ branch | sanitize }}"✓ Created branch feature and worktree @ [TEMP]/project/.git.feature↳ To customize worktree locations, run wt config create-[0mdiff --git a/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_worktree_path_prompt_non_interactive_warning.snap b/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_worktree_path_prompt_non_interactive_warning.snapindex 1bf01daa9..0e60ad60c 100644--- a/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_worktree_path_prompt_non_interactive_warning.snap+++ b/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_worktree_path_prompt_non_interactive_warning.snap@@ -47,4 +47,3 @@ exit_code: 0worktree-path = "{{ repo_path }}/../{{ branch | sanitize }}"✓ Created branch feature and worktree @ [TEMP]/project/.git.feature↳ To customize worktree locations, run wt config create-[0mdiff --git a/tests/snapshots/integration__integration_tests__list_layout__width_30.snap b/tests/snapshots/integration__integration_tests__list_layout__width_30.snapindex 80908c13e..3b28b4966 100644--- a/tests/snapshots/integration__integration_tests__list_layout__width_30.snap+++ b/tests/snapshots/integration__integration_tests__list_layout__width_30.snap@@ -51,7 +51,7 @@ exit_code: 0+ feature-a+ feature-b+ feature-c-+ feature/implement-oauth2-so…[0m++ feature/implement-oauth2-so…----- stderr -----