Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
perf(statusline): size from COLUMNS, drop the parent-TTY walk (#3286)
Worktrunk Bot25069b4f76da
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex cadff5bfb..a40d87e9c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -78,6 +78,8 @@- **Statusline rate-limit pace color grades by severity**: The pace segment's color now deepens (dim → dim-yellow → yellow) with the projected throttling severity, so an early-window burst stays muted while a costly projected lockout stands out. The displayed pace number is unchanged. ([#3229](https://github.com/max-sixty/worktrunk/pull/3229))+- **Statusline width comes from `COLUMNS`, not a parent-process walk**: `wt list statusline` used to spawn up to 10 `ps` calls plus `stty` per render to recover a terminal width, because Claude Code piped the subprocess with no inherited TTY. Claude Code now sets `COLUMNS`/`LINES` to the terminal dimensions before running the script (since v2.1.153), so the width comes straight from there — less a fixed 5-column margin for Claude Code's own UI — and the `ps`/`stty` walk is gone. On an older Claude Code that doesn't set `COLUMNS`, the line renders untruncated rather than walking the process tree. ([#3286](https://github.com/max-sixty/worktrunk/pull/3286), closes [#2950](https://github.com/max-sixty/worktrunk/issues/2950))+### Fixed- **Picker `Alt-x` removal updates the row in place**: Removing a worktree no longer re-collects the whole list (a flicker that reset the cursor to the top): an unmerged worktree's row morphs into a branch-only row while the worktree is removed in the background, and a merged worktree's row drops with the cursor landing on the row that slid up. A removal that can't safely happen — the current or main worktree, or a dirty or locked one — is declined with the same diagnostic `wt remove` prints, rather than a dead keypress or a disruptive `cd` home. The post-removal cursor lands by row identity, so it stays correct even under an active filter. ([#3262](https://github.com/max-sixty/worktrunk/pull/3262), [#3199](https://github.com/max-sixty/worktrunk/pull/3199), [#3211](https://github.com/max-sixty/worktrunk/pull/3211), [#3225](https://github.com/max-sixty/worktrunk/pull/3225))diff --git a/src/commands/statusline.rs b/src/commands/statusline.rsindex 76bd6d15a..b827bc216 100644--- a/src/commands/statusline.rs+++ b/src/commands/statusline.rs@@ -817,7 +817,7 @@ pub fn run(format: StatuslineFormat) -> Result<()> {}// Fit segments to terminal width using priority-based dropping; with no- // detectable width (even via the parent-TTY walk), render everything+ // detectable width (no `COLUMNS` from Claude Code), render everythinglet max_width = terminal_width_for_statusline().unwrap_or(usize::MAX);// Reserve 1 char for leading space (ellipsis handled by truncate_visible fallback)let content_budget = max_width.saturating_sub(1);diff --git a/src/styling/mod.rs b/src/styling/mod.rsindex e4127abff..11eb13b08 100644--- a/src/styling/mod.rs+++ b/src/styling/mod.rs@@ -81,10 +81,12 @@ pub fn verbosity() -> u8 {/// height comes back `None`; callers that need a height supply their own/// fallback.///-/// Does **not** probe the parent process tree — that fallback is expensive-/// (spawns `ps` up to 10 times plus `stty`) and only useful for `wt statusline`-/// under Claude Code, where no TTY is inherited. Statusline calls-/// [`terminal_width_for_statusline`] instead.+/// Under Claude Code the statusline subprocess inherits no TTY, so direct+/// detection fails and the `COLUMNS` fallback supplies the width — Claude Code+/// sets `COLUMNS`/`LINES` to the terminal dimensions before running the script+/// (since v2.1.153). Statusline callers route through+/// [`terminal_width_for_statusline`], which reserves a margin for Claude Code's+/// own UI chrome.pub fn terminal_dimensions() -> Option<(usize, Option<usize>)> {// Prefer direct terminal detection (more accurate than COLUMNS which may be stale/wrong).// Check stderr first (status messages), then stdout (table output).@@ -108,84 +110,26 @@ pub fn terminal_width() -> Option<usize> {terminal_dimensions().map(|(width, _)| width)}-/// Terminal width for `wt statusline`, including a subprocess-compat fallback.+/// Columns reserved for Claude Code's own UI chrome (e.g. an "Approaching+/// context limit" message) when sizing the statusline, so the line doesn't+/// render flush to the terminal edge.+const STATUSLINE_UI_RESERVED_COLUMNS: usize = 5;++/// Terminal width for `wt statusline`, reserving a margin for Claude Code's UI.////// Claude Code invokes `wt statusline` as a subprocess with pipes for stdin,-/// stdout, and stderr — so [`terminal_width`] always returns `None`, and the-/// statusline output would overflow the bar.-/// As a last resort, this walks up to 10 parent processes looking for a TTY-/// and asks `stty size` for its dimensions, reserving 5 columns for Claude-/// Code's own UI messages.+/// stdout, and stderr, so direct detection ([`terminal_width`]) returns `None`.+/// Since v2.1.153 Claude Code sets `COLUMNS`/`LINES` to the terminal dimensions+/// before running the script, so [`terminal_width`]'s `COLUMNS` fallback+/// supplies the width. A few columns are reserved for Claude Code's own UI+/// messages. Returns `None` when no width is detectable (e.g. an older Claude+/// Code that doesn't set `COLUMNS`), in which case the statusline renders+/// everything untruncated.///-/// Every other caller should use [`terminal_width`] — the parent-TTY walk is-/// a statusline-specific workaround, not a general fallback.+/// Every other caller should use [`terminal_width`] — the reserved margin is a+/// statusline-specific concern.pub fn terminal_width_for_statusline() -> Option<usize> {- statusline_width_fallback(terminal_width())-}--/// Apply the parent-TTY fallback to a width returned by [`terminal_width`].-///-/// Split from [`terminal_width_for_statusline`] so tests can exercise the-/// fallback path without racing the process-wide `COLUMNS` env var.-fn statusline_width_fallback(base: Option<usize>) -> Option<usize> {- #[cfg(unix)]- if base.is_none() {- return detect_parent_tty_width();- }- base-}--/// Detect terminal width by walking up the process tree to find a TTY.-///-/// This is a fallback for subprocesses (like Claude Code hooks) that don't have-/// direct TTY access. Walks up to 10 parent processes looking for one with a TTY,-/// then queries that TTY's size via `stty` and [`statusline_width_from_stty_size`].-#[cfg(unix)]-fn detect_parent_tty_width() -> Option<usize> {- use crate::shell_exec::Cmd;-- let mut pid = std::process::id().to_string();-- for _ in 0..10 {- let output = Cmd::new("ps")- .args(["-o", "ppid=,tty=", "-p", &pid])- .run()- .ok()?;-- let info = String::from_utf8_lossy(&output.stdout);- let mut parts = info.split_whitespace();- let ppid = parts.next()?;- let tty = parts.next()?;-- // Valid TTY found (not "?" or "??")- if !tty.is_empty() && tty != "?" && tty != "??" {- // Query TTY size using stty- let size = Cmd::new("sh")- .args(["-c", &format!("stty size < /dev/{tty}")])- .run()- .ok()?;-- return statusline_width_from_stty_size(&String::from_utf8_lossy(&size.stdout));- }-- if ppid == "1" || ppid == "0" {- break;- }- pid = ppid.to_string();- }-- None-}--/// Convert `stty size` output (`"<rows> <cols>"`) into a statusline width.-///-/// Reserves 5 columns for Claude Code's UI messages (like "Approaching-/// context limit"). Returns `None` when the output has no parseable column-/// count.-#[cfg(unix)]-fn statusline_width_from_stty_size(stty_size: &str) -> Option<usize> {- let cols = stty_size.split_whitespace().nth(1)?.parse::<usize>().ok()?;- Some(cols.saturating_sub(5))+ terminal_width().map(|w| w.saturating_sub(STATUSLINE_UI_RESERVED_COLUMNS))}/// Calculate visual width of a string, ignoring ANSI escape codes@@ -218,29 +162,24 @@ mod tests {use anstyle::Style;use unicode_width::UnicodeWidthStr;- #[test]- fn statusline_width_fallback_returns_base_when_known() {- // Fast path: if `terminal_width()` found a real width, use it as-is.- assert_eq!(statusline_width_fallback(Some(80)), Some(80));- assert_eq!(statusline_width_fallback(Some(1)), Some(1));- }-- #[test]- fn statusline_width_fallback_probes_parent_tty_when_unknown() {- // Slow path: `None` signals "direct detection failed" — the helper- // then walks the process tree. Whether a TTY is found depends on the- // test environment, so only assert the return type.- let _ = statusline_width_fallback(None);- }-#[test]fn terminal_width_for_statusline_returns_a_width() {// End-to-end smoke test. Under cargo test, `COLUMNS=80` is set in- // `.cargo/config.toml`, so the fast path always finds a width.+ // `.cargo/config.toml`, so a width is always detectable.let width = terminal_width_for_statusline();assert!(width.expect("COLUMNS=80 is set in .cargo/config.toml") > 0);}+ #[test]+ fn terminal_width_for_statusline_reserves_ui_margin() {+ // The statusline width is the detected width less a fixed margin for+ // Claude Code's own UI chrome, saturating rather than underflowing.+ assert_eq!(+ terminal_width_for_statusline(),+ terminal_width().map(|w| w.saturating_sub(STATUSLINE_UI_RESERVED_COLUMNS)),+ );+ }+#[test]fn terminal_width_projects_terminal_dimensions() {// `terminal_width` is exactly the width component of@@ -260,21 +199,6 @@ mod tests {assert!(width > 0);}- #[cfg(unix)]- #[test]- fn statusline_width_from_stty_size_reserves_five_columns() {- // `stty size` prints "<rows> <cols>"; the column count loses 5 to- // Claude Code's UI chrome.- assert_eq!(statusline_width_from_stty_size("24 200"), Some(195));- assert_eq!(statusline_width_from_stty_size("24 80"), Some(75));- // Saturates rather than underflowing on a terminal narrower than 5.- assert_eq!(statusline_width_from_stty_size("24 3"), Some(0));- // No parseable column count.- assert_eq!(statusline_width_from_stty_size(""), None);- assert_eq!(statusline_width_from_stty_size("24"), None);- assert_eq!(statusline_width_from_stty_size("24 wide"), None);- }-#[test]fn test_toml_formatting() {let toml_content = r#"worktree-path = "../{{ repo }}.{{ branch }}"