Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor(picker): read terminal size once for layout sizing (#3210)
Maximilian Roos93cfa78576ea
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex 4d9385e06..cc9dec3e2 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -21,7 +21,9 @@//! On the main thread, `handle_picker`://!//! 1. `current_or_recover` + config resolution.-//! 2. `PreviewState::new` — auto-detects Right vs Down layout.+//! 2. Reads the terminal size once; `PreviewState::new` records the+//! Right-vs-Down layout detected from it. Every later sizing step (the+//! estimate cap, preview dimensions, half-page scroll) reuses that snapshot.//! 3. Allocates the `PreviewOrchestrator` and kicks off a *speculative*//! `git diff HEAD` for the current worktree on `COLLECT_POOL`.//! That bg work overlaps with everything below.@@ -638,8 +640,20 @@ 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));+// Initialize preview mode state file (auto-cleanup on drop)- let state = PreviewState::new();+ let state = PreviewState::new(PreviewLayout::for_dimensions(+ term_width as f64,+ term_height as f64,+ ));worktrunk::trace::instant("Picker layout detected");// Prime the current worktree's root / git-dir / branch caches with one@@ -682,7 +696,9 @@ pub fn handle_picker(}));// num_items doesn't matter for Right (dims independent of it); for// Down it only affects height, which doesn't alter pager wrapping.- let dims = state.initial_layout.preview_dimensions(0);+ let dims = state+ .initial_layout+ .dimensions_for(term_width, term_height, 0);orchestrator.spawn_preview(Arc::new(item), PreviewMode::WorkingTree, dims);}@@ -727,12 +743,7 @@ pub fn handle_picker(// for the height computation, so we short-circuit once the estimate// reaches it.let num_items_estimate = {- let cap = {- let term_height = terminal_size::terminal_size()- .map(|(_, terminal_size::Height(h))| h as usize)- .unwrap_or(24);- preview::max_visible_items(preview::available_height(term_height))- };+ let cap = preview::max_visible_items(preview::available_height(term_height));let mut estimate = repo.list_worktrees().map(|w| w.len()).unwrap_or(cap);if estimate < cap && show_branches {// Local branches are a superset of worktree branches (each@@ -748,10 +759,13 @@ pub fn handle_picker(estimate};worktrunk::trace::instant("Picker estimate computed");- let preview_window_spec = state- .initial_layout- .to_preview_window_spec(num_items_estimate);- let preview_dims = state.initial_layout.preview_dimensions(num_items_estimate);+ // Compute the dimensions once; the skim preview-window spec is formatted+ // from them rather than recomputed.+ let preview_dims =+ state+ .initial_layout+ .dimensions_for(term_width, term_height, num_items_estimate);+ let preview_window_spec = state.initial_layout.spec_for(preview_dims);// Summary hint: when summaries are disabled, prime the Summary cache// with config guidance instead of showing a perpetual "Generating…"@@ -805,9 +819,7 @@ pub fn handle_picker(let state_path_str = shell_escape::unix::escape(state_path_display.into()).into_owned();// Half-page preview scroll: half of skim's usable height.- let half_page = terminal_size::terminal_size()- .map(|(_, terminal_size::Height(h))| (preview::available_height(h as usize) / 2).max(5))- .unwrap_or(10);+ let half_page = (preview::available_height(term_height) / 2).max(5);// Configure skim options with Rust-based preview and mode switching keybindingslet options = SkimOptionsBuilder::default()@@ -1334,7 +1346,7 @@ fn resolve_identifier(#[cfg(test)]pub mod tests {use super::items::WorktreeSkimItem;- use super::preview::{PreviewLayout, PreviewMode, PreviewStateData};+ use super::preview::{PreviewMode, PreviewStateData};use super::{PickerAction, PickerCollector, PickerRemovalTarget, drain_stashed_warnings,parse_reload_remove_token, picker_item_identifier, resolve_identifier,@@ -1393,17 +1405,6 @@ pub mod tests {let _ = fs::remove_file(&state_path);}- #[test]- fn test_preview_layout() {- // Right uses absolute width derived from terminal size- let spec = PreviewLayout::Right.to_preview_window_spec(10);- assert!(spec.starts_with("right:"));-- // Down calculates based on item count- let spec = PreviewLayout::Down.to_preview_window_spec(5);- assert!(spec.starts_with("down:"));- }-#[test]fn test_resolve_identifier() {// Switch returns the selected namediff --git a/src/commands/picker/preview.rs b/src/commands/picker/preview.rsindex 814436030..b594efacd 100644--- a/src/commands/picker/preview.rs+++ b/src/commands/picker/preview.rs@@ -1,6 +1,7 @@//! Preview mode and layout management.//!-//! Handles preview state persistence and layout auto-detection for the interactive selector.+//! Handles preview modes, layout selection, and preview-state persistence for+//! the interactive selector.use std::fs;use std::path::PathBuf;@@ -111,7 +112,7 @@ pub(super) fn max_visible_items(available: usize) -> usize {/// Preview layout orientation for the interactive selector///-/// Preview window position (auto-detected at startup based on terminal dimensions)+/// Preview window position, selected from the terminal dimensions read once at startup////// - Right: Preview on the right side (50% width) - better for wide terminals/// - Down: Preview below the list - better for tall/vertical monitors@@ -123,7 +124,7 @@ pub(super) enum PreviewLayout {}impl PreviewLayout {- /// Auto-detect layout based on terminal dimensions.+ /// Determine the layout for the given terminal dimensions (cols × rows).////// Terminal dimensions are in characters, not pixels. Since characters are/// typically twice as tall as wide (~0.5 aspect ratio), we correct for this@@ -136,16 +137,10 @@ impl PreviewLayout {/// Returns Down for portrait (effective ratio < 1.0), Right for landscape./// Also returns Down when the terminal is too narrow for side-by-side layout,/// even if the aspect ratio suggests landscape (e.g. 60×24 on a phone).- pub(super) fn auto_detect() -> Self {- let (cols, rows) = terminal_size::terminal_size()- .map(|(terminal_size::Width(w), terminal_size::Height(h))| (w as f64, h as f64))- .unwrap_or((80.0, 24.0));-- Self::for_dimensions(cols, rows)- }-- /// Determine layout for given terminal dimensions (cols × rows).- fn for_dimensions(cols: f64, rows: f64) -> Self {+ ///+ /// The terminal is read once in `handle_picker`; both layout detection here+ /// and the preview sizing below are threaded that single snapshot.+ pub(super) fn for_dimensions(cols: f64, rows: f64) -> Self {// Too narrow for side-by-side — branch names won't fit in half the widthif cols < MIN_COLS_FOR_RIGHT_LAYOUT {return Self::Down;@@ -161,36 +156,26 @@ impl PreviewLayout {}}- /// Calculate the preview window spec for skim.- /// Derives dimensions from `preview_dimensions` to ensure consistency.- pub(super) fn to_preview_window_spec(self, num_items: usize) -> String {- let (width, height) = self.preview_dimensions(num_items);+ /// Format the skim preview-window spec from already-computed dimensions.+ /// Right positions the preview by width, Down by height.+ pub(super) fn spec_for(self, (width, height): (usize, usize)) -> String {match self {- Self::Right => format!("right:{}", width),- Self::Down => format!("down:{}", height),+ Self::Right => format!("right:{width}"),+ Self::Down => format!("down:{height}"),}}- /// Calculate preview dimensions (width, height) in characters.- /// Single source of truth for preview sizing — used by both skim config- /// and background pre-computation. Reads the live terminal size, then- /// delegates the pure layout math to `dimensions_for`.- pub(super) fn preview_dimensions(self, num_items: usize) -> (usize, usize) {- 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));-- self.dimensions_for(term_width, term_height, num_items)- }-- /// Pure layout math behind `preview_dimensions`, with the terminal size- /// passed in so the split is testable without a live TTY.+ /// Compute preview dimensions (width, height) in characters for a terminal+ /// size. Single source of truth for preview sizing — the picker reads the+ /// terminal once and calls this for both the skim preview-window spec (via+ /// `spec_for`) and background pre-computation. Pure, so it's testable+ /// without a live TTY.////// Right keeps a fixed 50%/90% split independent of `num_items`. Down lets/// the list grow to `max_visible_items(available)` rows (half of skim's/// area) and hands the rest to the preview, floored at `MIN_PREVIEW_LINES`/// and clamped to never exceed `available`.- fn dimensions_for(+ pub(super) fn dimensions_for(self,term_width: usize,term_height: usize,@@ -214,7 +199,7 @@ impl PreviewLayout {}}-/// Preview state persistence (mode only, layout auto-detected)+/// Preview state persistence (mode only; layout is derived per session, not persisted)////// State file format: Single digit representing preview mode (1-6)pub(super) struct PreviewStateData;@@ -252,12 +237,12 @@ pub(super) struct PreviewState {}impl PreviewState {- pub(super) fn new() -> Self {+ pub(super) fn new(initial_layout: PreviewLayout) -> Self {let path = PreviewStateData::state_path();PreviewStateData::write_mode(PreviewMode::WorkingTree);Self {path,- initial_layout: PreviewLayout::auto_detect(),+ initial_layout,}}}@@ -291,14 +276,10 @@ mod tests {}#[test]- fn test_preview_layout_to_preview_window_spec() {- // Right uses absolute width derived from terminal size- let spec = PreviewLayout::Right.to_preview_window_spec(10);- assert!(spec.starts_with("right:"));-- // Down calculates based on item count- let spec = PreviewLayout::Down.to_preview_window_spec(5);- assert!(spec.starts_with("down:"));+ fn test_preview_layout_spec_for() {+ // Right positions by width, Down by height.+ assert_eq!(PreviewLayout::Right.spec_for((40, 21)), "right:40");+ assert_eq!(PreviewLayout::Down.spec_for((80, 15)), "down:15");}#[test]