Skip to content

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

refactor(picker): read terminal size once from a canonical reader (#3219)

Maximilian Roos546ea8fe3a65
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rs
index c610e69ed..f6c4a3dd8 100644
--- a/src/commands/picker/mod.rs
+++ b/src/commands/picker/mod.rs
@@ -912,14 +912,24 @@ pub fn handle_picker(
let show_prs = cli_prs;
worktrunk::trace::instant("Picker config resolved");
- // Read the terminal size once. Layout detection, the visible-row cap, the
- // preview dimensions, and the half-page scroll all derive from this single
- // snapshot, so the estimate cap and the actual layout can never observe
- // different terminal sizes across a resize. (`crate::display::terminal_width`
- // below is a separate, stderr-first width probe for the skim list column.)
- let (term_width, term_height) = terminal_size::terminal_size()
- .map(|(terminal_size::Width(w), terminal_size::Height(h))| (w as usize, h as usize))
- .unwrap_or((80, 24));
+ // Read the terminal size once, from the canonical reader that
+ // `crate::display::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
+ // different terminals.
+ //
+ // The layout needs both dimensions, so it trusts the snapshot only when a
+ // real terminal was detected (width and height both present). A width-only
+ // `COLUMNS` reading — or no reading at all — falls back to 80x24, exactly as
+ // 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_width, term_height) = match term_dims {
+ Some((w, Some(h))) => (w, h),
+ _ => (80, 24),
+ };
// Reset the preview tab to working-tree and select the layout from the
// terminal size.
@@ -1005,11 +1015,13 @@ pub fn handle_picker(
// right-hand columns — no reload, no re-layout, so no column ever moves.
// (The Down layout already used full width, so this is a no-op there.)
//
- // The picker requires a TTY, so detection essentially always succeeds; the
- // unlimited-width fallback just keeps the math total. Skim prefixes every
- // line with a 2-column cursor gutter ("> "), so the full width loses 2.
- let terminal_width = crate::display::terminal_width().unwrap_or(usize::MAX);
- let skim_list_width = terminal_width.saturating_sub(2);
+ // The width comes from the same `term_dims` snapshot as the layout above;
+ // its fully-headless fallback is `usize::MAX` (vs. the layout's 80 width) to
+ // keep the math total when no width is known at all — the picker requires a
+ // TTY, so that only applies to the headless paths. Skim prefixes every line
+ // with a 2-column cursor gutter ("> "), so the full width loses 2.
+ let list_width_source = term_dims.map(|(w, _)| w).unwrap_or(usize::MAX);
+ let skim_list_width = list_width_source.saturating_sub(2);
// Estimate item count for the preview window spec (only the Down
// layout depends on it). The Down layout caps visible rows at
diff --git a/src/display.rs b/src/display.rs
index 7b0415601..1192d7730 100644
--- a/src/display.rs
+++ b/src/display.rs
@@ -116,7 +116,7 @@ pub(crate) fn truncate_to_width(text: &str, max_width: usize) -> String {
}
// Re-export from styling for convenience
-pub(crate) use worktrunk::styling::{terminal_width, truncate_visible};
+pub(crate) use worktrunk::styling::{terminal_dimensions, terminal_width, truncate_visible};
#[cfg(test)]
mod tests {
diff --git a/src/styling/mod.rs b/src/styling/mod.rs
index f93783296..e4127abff 100644
--- a/src/styling/mod.rs
+++ b/src/styling/mod.rs
@@ -66,28 +66,46 @@ pub fn verbosity() -> u8 {
VERBOSITY.load(Ordering::Relaxed)
}
-/// Get terminal width, or `None` if detection fails (piped context, no TTY).
+/// Get terminal width and height, or `None` if detection fails (piped context,
+/// no TTY, and no `COLUMNS`).
///
-/// Prefers direct terminal size detection over COLUMNS environment variable,
-/// because tools like cargo may set COLUMNS incorrectly.
+/// This is the canonical terminal-size reader; [`terminal_width`] is its width
+/// projection, so width-only and width+height callers share one probe chain and
+/// can never observe different widths:
///
-/// Checks stderr first (for status messages), then stdout (for table output).
+/// 1. Direct `terminal_size` detection — stderr first (status messages), then
+/// stdout (table output). More accurate than `COLUMNS`, which tools like
+/// cargo may set incorrectly.
+/// 2. The `COLUMNS` env var, for scripts and piped contexts where detection
+/// fails. `COLUMNS` carries a width but has no height counterpart, so the
+/// 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.
-pub fn terminal_width() -> Option<usize> {
- // Prefer direct terminal detection (more accurate than COLUMNS which may be stale/wrong)
- // Check stderr first (status messages), then stdout (table output)
- if let Some((terminal_size::Width(w), _)) =
+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).
+ if let Some((terminal_size::Width(w), terminal_size::Height(h))) =
terminal_size::terminal_size_of(std::io::stderr()).or_else(terminal_size::terminal_size)
{
- return Some(w as usize);
+ return Some((w as usize, Some(h as usize)));
}
- // Fall back to COLUMNS env var (for scripts, piped contexts, or when detection fails)
- std::env::var("COLUMNS").ok()?.parse::<usize>().ok()
+ // Fall back to COLUMNS (width only — there is no height equivalent) for
+ // scripts, piped contexts, or when detection fails.
+ let columns = std::env::var("COLUMNS").ok()?.parse::<usize>().ok()?;
+ Some((columns, None))
+}
+
+/// Get terminal width, or `None` if detection fails (piped context, no TTY).
+///
+/// The width projection of [`terminal_dimensions`] — see it for the probe chain
+/// (stderr, then stdout, then `COLUMNS`).
+pub fn terminal_width() -> Option<usize> {
+ terminal_dimensions().map(|(width, _)| width)
}
/// Terminal width for `wt statusline`, including a subprocess-compat fallback.
@@ -223,6 +241,25 @@ mod tests {
assert!(width.expect("COLUMNS=80 is set in .cargo/config.toml") > 0);
}
+ #[test]
+ fn terminal_width_projects_terminal_dimensions() {
+ // `terminal_width` is exactly the width component of
+ // `terminal_dimensions`, so the two can never report different widths
+ // regardless of TTY / `COLUMNS` state — this locks that delegation.
+ assert_eq!(terminal_width(), terminal_dimensions().map(|(w, _)| w));
+ }
+
+ #[test]
+ fn terminal_dimensions_returns_a_width() {
+ // Under cargo test, `COLUMNS=80` is set in `.cargo/config.toml`, so a
+ // width is always available even with no TTY. Height depends on the
+ // environment (a real TTY yields `Some`; the `COLUMNS` fallback yields
+ // `None`), so only the width is asserted.
+ let (width, _height) =
+ terminal_dimensions().expect("COLUMNS=80 is set in .cargo/config.toml");
+ assert!(width > 0);
+ }
+
#[cfg(unix)]
#[test]
fn statusline_width_from_stty_size_reserves_five_columns() {