Skip to content

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

perf(select): pre-compute preview tabs in background (#935)

Maximilian Roos50de5ff89603
diff --git a/Cargo.lock b/Cargo.lock
index 42aec8fa0..980849199 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2708,6 +2708,15 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "wait-timeout"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "walkdir"
version = "2.5.0"
@@ -3205,6 +3214,7 @@ dependencies = [
"urlencoding",
"vergen-gitcl",
"vt100",
+ "wait-timeout",
"which 8.0.0",
"wrap-ansi",
"wt-perf",
diff --git a/Cargo.toml b/Cargo.toml
index b54952016..141455ab9 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -123,6 +123,8 @@ fs2 = "0.4.3"
sanitize-filename = "0.6.0"
schemars = { version = "1.2.1", features = ["derive"] }
+wait-timeout = "0.2"
+
[target.'cfg(unix)'.dependencies]
skim = "0.20"
nix = { version = "0.31", default-features = false, features = ["process", "signal"] }
diff --git a/src/commands/select/items.rs b/src/commands/select/items.rs
index b67bdedc3..083c112a3 100644
--- a/src/commands/select/items.rs
+++ b/src/commands/select/items.rs
@@ -8,6 +8,7 @@ use std::sync::Arc;
use anstyle::Reset;
use color_print::cformat;
+use dashmap::DashMap;
use skim::prelude::*;
use worktrunk::git::Repository;
use worktrunk::styling::INFO_SYMBOL;
@@ -16,9 +17,16 @@ use super::super::list::model::ListItem;
use super::log_formatter::{
FIELD_DELIM, batch_fetch_stats, format_log_output, process_log_with_dimming, strip_hash_markers,
};
-use super::pager::{get_diff_pager, run_git_diff_with_pager};
+use super::pager::{get_diff_pager, pipe_through_pager};
use super::preview::{PreviewMode, PreviewStateData};
+/// Cache key for pre-computed previews: (branch_name, mode).
+type PreviewCacheKey = (String, PreviewMode);
+
+/// Cache for pre-computed previews, keyed by (branch_name, mode).
+/// Shared across all WorktreeSkimItems for background pre-computation.
+pub(super) type PreviewCache = Arc<DashMap<PreviewCacheKey, String>>;
+
/// Header item for column names (non-selectable)
pub(super) struct HeaderSkimItem {
pub display_text: String,
@@ -39,12 +47,48 @@ impl SkimItem for HeaderSkimItem {
}
}
+/// Common diff rendering: check stat, show stat + full diff if non-empty.
+fn compute_diff_preview(args: &[&str], no_changes_msg: &str, width: usize) -> String {
+ let mut output = String::new();
+ let Ok(repo) = Repository::current() else {
+ return format!("{no_changes_msg}\n");
+ };
+
+ // Check stat output first
+ let mut stat_args = args.to_vec();
+ stat_args.push("--stat");
+ stat_args.push("--color=always");
+ let stat_width_arg = format!("--stat-width={}", width);
+ stat_args.push(&stat_width_arg);
+
+ if let Ok(stat) = repo.run_command(&stat_args)
+ && !stat.trim().is_empty()
+ {
+ output.push_str(&stat);
+
+ // Build diff args with color
+ let mut diff_args = args.to_vec();
+ diff_args.push("--color=always");
+
+ if let Ok(diff) = repo.run_command(&diff_args) {
+ output.push_str(&diff);
+ }
+ } else {
+ output.push_str(no_changes_msg);
+ output.push('\n');
+ }
+
+ output
+}
+
/// Wrapper to implement SkimItem for ListItem
pub(super) struct WorktreeSkimItem {
pub display_text: String,
pub display_text_with_ansi: String,
pub branch_name: String,
pub item: Arc<ListItem>,
+ /// Shared cache for pre-computed previews (all modes)
+ pub preview_cache: PreviewCache,
}
impl SkimItem for WorktreeSkimItem {
@@ -110,94 +154,86 @@ impl WorktreeSkimItem {
)
}
- /// Render preview for the given mode with specified dimensions
+ /// Render preview for the given mode with specified dimensions.
+ /// Uses cache if available, otherwise computes and caches.
+ /// Applies pager at display time for diff modes (not cached).
fn preview_for_mode(&self, mode: PreviewMode, width: usize, height: usize) -> String {
- match mode {
- PreviewMode::WorkingTree => self.render_working_tree_preview(width),
- PreviewMode::Log => self.render_log_preview(width, height),
- PreviewMode::BranchDiff => self.render_branch_diff_preview(width),
- PreviewMode::UpstreamDiff => self.render_upstream_diff_preview(width),
- }
- }
+ let cache_key = (self.branch_name.clone(), mode);
- /// Common diff rendering pattern: check stat, show stat + full diff if non-empty
- fn render_diff_preview(&self, args: &[&str], no_changes_msg: &str, width: usize) -> String {
- let mut output = String::new();
- let Ok(repo) = Repository::current() else {
- return no_changes_msg.to_string();
+ // Get from cache or compute
+ let result = if let Some(cached) = self.preview_cache.get(&cache_key) {
+ cached.clone()
+ } else {
+ let computed = Self::compute_preview(&self.item, mode, width, height);
+ self.preview_cache.insert(cache_key, computed.clone());
+ computed
};
- // Check stat output first
- let mut stat_args = args.to_vec();
- stat_args.push("--stat");
- stat_args.push("--color=always");
- let stat_width_arg = format!("--stat-width={}", width);
- stat_args.push(&stat_width_arg);
-
- if let Ok(stat) = repo.run_command(&stat_args)
- && !stat.trim().is_empty()
- {
- output.push_str(&stat);
-
- // Build diff args with color
- let mut diff_args = args.to_vec();
- diff_args.push("--color=always");
-
- // Try streaming through pager first (git diff | pager), fall back to plain diff
- let diff = get_diff_pager()
- .and_then(|pager| run_git_diff_with_pager(&diff_args, pager, width))
- .or_else(|| repo.run_command(&diff_args).ok());
-
- if let Some(diff) = diff {
- output.push_str(&diff);
- }
- } else {
- output.push_str(no_changes_msg);
- output.push('\n');
+ // Apply pager at display time for diff modes (1, 3, 4)
+ // Log mode (2) doesn't benefit from diff pagers
+ let is_diff_mode = matches!(
+ mode,
+ PreviewMode::WorkingTree | PreviewMode::BranchDiff | PreviewMode::UpstreamDiff
+ );
+
+ if is_diff_mode && let Some(pager_cmd) = get_diff_pager() {
+ return pipe_through_pager(&result, pager_cmd, width);
}
- output
+ result
+ }
+
+ /// Compute preview for any mode. Called from cache miss and background pre-computation.
+ pub(super) fn compute_preview(
+ item: &ListItem,
+ mode: PreviewMode,
+ width: usize,
+ height: usize,
+ ) -> String {
+ match mode {
+ PreviewMode::WorkingTree => Self::compute_working_tree_preview(item, width),
+ PreviewMode::Log => Self::compute_log_preview(item, width, height),
+ PreviewMode::BranchDiff => Self::compute_branch_diff_preview(item, width),
+ PreviewMode::UpstreamDiff => Self::compute_upstream_diff_preview(item, width),
+ }
}
- /// Render Tab 1: Working tree preview (uncommitted changes vs HEAD)
- /// Matches `wt list` "HEAD±" column
- fn render_working_tree_preview(&self, width: usize) -> String {
- let Some(wt_info) = self.item.worktree_data() else {
- // Branch without worktree - selecting will create one
- let branch = self.item.branch_name();
+ /// Compute Tab 1: Working tree preview (uncommitted changes vs HEAD)
+ fn compute_working_tree_preview(item: &ListItem, width: usize) -> String {
+ let Some(wt_info) = item.worktree_data() else {
+ let branch = item.branch_name();
return format!(
"{INFO_SYMBOL} {branch} is branch only — press Enter to create worktree\n"
);
};
- let branch = self.item.branch_name();
+ let branch = item.branch_name();
let path = wt_info.path.display().to_string();
- self.render_diff_preview(
+ compute_diff_preview(
&["-C", &path, "diff", "HEAD"],
&cformat!("{INFO_SYMBOL} <bold>{branch}</> has no uncommitted changes"),
width,
)
}
- /// Render Tab 3: Branch diff preview (line diffs in commits ahead of default branch)
- /// Matches `wt list` "main…± (--full)" column
- fn render_branch_diff_preview(&self, width: usize) -> String {
- let branch = self.item.branch_name();
+ /// Compute Tab 3: Branch diff preview (line diffs in commits ahead of default branch)
+ fn compute_branch_diff_preview(item: &ListItem, width: usize) -> String {
+ let branch = item.branch_name();
let Ok(repo) = Repository::current() else {
return cformat!("{INFO_SYMBOL} <bold>{branch}</> has no commits ahead of main\n");
};
let Some(default_branch) = repo.default_branch() else {
return cformat!("{INFO_SYMBOL} <bold>{branch}</> has no commits ahead of main\n");
};
- if self.item.counts.is_some_and(|c| c.ahead == 0) {
+ if item.counts.is_some_and(|c| c.ahead == 0) {
return cformat!(
"{INFO_SYMBOL} <bold>{branch}</> has no commits ahead of <bold>{default_branch}</>\n"
);
}
- let merge_base = format!("{}...{}", default_branch, self.item.head());
- self.render_diff_preview(
+ let merge_base = format!("{}...{}", default_branch, item.head());
+ compute_diff_preview(
&["diff", &merge_base],
&cformat!(
"{INFO_SYMBOL} <bold>{branch}</> has no file changes vs <bold>{default_branch}</>"
@@ -206,32 +242,23 @@ impl WorktreeSkimItem {
)
}
- /// Render Tab 4: Upstream diff preview (ahead/behind vs tracking branch)
- /// Matches `wt list` "Remote⇅" column
- fn render_upstream_diff_preview(&self, width: usize) -> String {
- let branch = self.item.branch_name();
+ /// Compute Tab 4: Upstream diff preview (ahead/behind vs tracking branch)
+ fn compute_upstream_diff_preview(item: &ListItem, width: usize) -> String {
+ let branch = item.branch_name();
- // Check if this branch has an upstream tracking branch
- // Use as_ref() to avoid cloning UpstreamStatus on every preview render
- let Some(active) = self.item.upstream.as_ref().and_then(|u| u.active()) else {
+ let Some(active) = item.upstream.as_ref().and_then(|u| u.active()) else {
return cformat!("{INFO_SYMBOL} <bold>{branch}</> has no upstream tracking branch\n");
};
- // Use @{u} syntax for performance (avoids extra git command to resolve upstream ref)
- // Format: branch@{u} resolves to the upstream tracking branch
let upstream_ref = format!("{}@{{u}}", branch);
if active.ahead == 0 && active.behind == 0 {
return cformat!("{INFO_SYMBOL} <bold>{branch}</> is up to date with upstream\n");
}
- // Handle different states: ahead only, behind only, or diverged
- // Use ⇡/⇣ symbols to match wt list's Remote⇅ column
if active.ahead > 0 && active.behind > 0 {
- // Diverged: show local changes (what would be pushed)
- // Use three-dot diff to show changes unique to local branch
- let range = format!("{}...{}", upstream_ref, self.item.head());
- self.render_diff_preview(
+ let range = format!("{}...{}", upstream_ref, item.head());
+ compute_diff_preview(
&["diff", &range],
&cformat!(
"{INFO_SYMBOL} <bold>{branch}</> has diverged (⇡{} ⇣{}) but no unique file changes",
@@ -241,17 +268,15 @@ impl WorktreeSkimItem {
width,
)
} else if active.ahead > 0 {
- // Ahead only: show unpushed commits
- let range = format!("{}...{}", upstream_ref, self.item.head());
- self.render_diff_preview(
+ let range = format!("{}...{}", upstream_ref, item.head());
+ compute_diff_preview(
&["diff", &range],
&cformat!("{INFO_SYMBOL} <bold>{branch}</> has no unpushed file changes"),
width,
)
} else {
- // Behind only: show what upstream has that we don't
- let range = format!("{}...{}", self.item.head(), upstream_ref);
- self.render_diff_preview(
+ let range = format!("{}...{}", item.head(), upstream_ref);
+ compute_diff_preview(
&["diff", &range],
&cformat!(
"{INFO_SYMBOL} <bold>{branch}</> is behind upstream (⇣{}) but no file changes",
@@ -262,8 +287,9 @@ impl WorktreeSkimItem {
}
}
- /// Render Tab 2: Log preview
- fn render_log_preview(&self, width: usize, height: usize) -> String {
+ /// Compute log preview for a worktree item.
+ /// This can be called from background threads for pre-computation.
+ pub(super) fn compute_log_preview(item: &ListItem, width: usize, height: usize) -> String {
// Minimum preview width to show timestamps (adds ~7 chars: space + 4-char time + space)
// Note: preview is typically 50% of terminal width, so 50 = 100-col terminal
const TIMESTAMP_WIDTH_THRESHOLD: usize = 50;
@@ -274,8 +300,8 @@ impl WorktreeSkimItem {
let show_timestamps = width >= TIMESTAMP_WIDTH_THRESHOLD;
// Calculate how many log lines fit in preview (height minus header)
let log_limit = height.saturating_sub(HEADER_LINES).max(1);
- let head = self.item.head();
- let branch = self.item.branch_name();
+ let head = item.head();
+ let branch = item.branch_name();
let Ok(repo) = Repository::current() else {
output.push_str(&cformat!(
"{INFO_SYMBOL} <bold>{branch}</> has no commits\n"
diff --git a/src/commands/select/mod.rs b/src/commands/select/mod.rs
index 76a570235..a7afc668f 100644
--- a/src/commands/select/mod.rs
+++ b/src/commands/select/mod.rs
@@ -12,6 +12,7 @@ use std::sync::Arc;
use anyhow::Context;
use crossterm::{execute, terminal};
+use dashmap::DashMap;
use skim::prelude::*;
use worktrunk::config::UserConfig;
use worktrunk::git::Repository;
@@ -20,8 +21,8 @@ use super::list::collect;
use super::worktree::{execute_switch, plan_switch};
use crate::output::handle_switch_output;
-use items::{HeaderSkimItem, WorktreeSkimItem};
-use preview::{PreviewLayout, PreviewState};
+use items::{HeaderSkimItem, PreviewCache, WorktreeSkimItem};
+use preview::{PreviewLayout, PreviewMode, PreviewState};
pub fn handle_select(
show_branches: bool,
@@ -91,7 +92,12 @@ pub fn handle_select(
let header_display_text = header_line.render();
let header_plain_text = header_line.plain_text();
+ // Create shared cache for all preview modes (pre-computed in background)
+ let preview_cache: PreviewCache = Arc::new(DashMap::new());
+
// Convert to skim items using the layout system for rendering
+ // Keep Arc<ListItem> refs for background pre-computation
+ let mut items_for_precompute: Vec<Arc<super::list::model::ListItem>> = Vec::new();
let mut items: Vec<Arc<dyn SkimItem>> = list_data
.items
.into_iter()
@@ -103,11 +109,15 @@ pub fn handle_select(
let display_text_with_ansi = rendered_line.render();
let display_text = rendered_line.plain_text();
+ let item = Arc::new(item);
+ items_for_precompute.push(Arc::clone(&item));
+
Arc::new(WorktreeSkimItem {
display_text,
display_text_with_ansi,
branch_name,
- item: Arc::new(item),
+ item,
+ preview_cache: Arc::clone(&preview_cache),
}) as Arc<dyn SkimItem>
})
.collect();
@@ -203,6 +213,34 @@ pub fn handle_select(
}
drop(tx);
+ // Spawn background thread to pre-compute all preview modes for all worktrees.
+ // Use same dimension calculation as skim's preview window.
+ // Thread runs until complete or process exits — no join needed since ongoing
+ // git commands are harmless read-only operations even if skim exits early.
+ let (preview_width, preview_height) = state.initial_layout.preview_dimensions(num_items);
+ let precompute_cache = Arc::clone(&preview_cache);
+ std::thread::spawn(move || {
+ let modes = [
+ PreviewMode::WorkingTree,
+ PreviewMode::Log,
+ PreviewMode::BranchDiff,
+ PreviewMode::UpstreamDiff,
+ ];
+ for item in items_for_precompute {
+ let branch_name = item.branch_name().to_string();
+ for mode in modes {
+ let cache_key = (branch_name.clone(), mode);
+ // Skip if already cached (e.g., user viewed it before we got here)
+ if precompute_cache.contains_key(&cache_key) {
+ continue;
+ }
+ let preview =
+ WorktreeSkimItem::compute_preview(&item, mode, preview_width, preview_height);
+ precompute_cache.insert(cache_key, preview);
+ }
+ }
+ });
+
// Run skim
let output = Skim::run_with(&options, Some(rx));
@@ -279,8 +317,9 @@ pub mod tests {
#[test]
fn test_preview_layout() {
- // Right is always 50%
- assert_eq!(PreviewLayout::Right.to_preview_window_spec(10), "right:50%");
+ // 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);
diff --git a/src/commands/select/pager.rs b/src/commands/select/pager.rs
index dcb41ece2..ced5d56f8 100644
--- a/src/commands/select/pager.rs
+++ b/src/commands/select/pager.rs
@@ -5,18 +5,17 @@
use std::io::Read;
use std::process::{Command, Stdio};
use std::sync::OnceLock;
-use std::time::{Duration, Instant};
+use std::time::Duration;
+
+use wait_timeout::ChildExt;
use worktrunk::config::UserConfig;
use worktrunk::shell::extract_filename_from_path;
use crate::pager::{git_config_pager, parse_pager_value};
-/// Cached pager command, detected once at startup.
-///
-/// None means no pager should be used (empty config or "cat").
-/// We cache this to avoid running `git config` on every preview render.
-pub(super) static CACHED_PAGER: OnceLock<Option<String>> = OnceLock::new();
+/// Cached pager command, ready to use. None means no pager.
+static CACHED_PAGER: OnceLock<Option<String>> = OnceLock::new();
/// Maximum time to wait for pager to complete.
///
@@ -24,17 +23,31 @@ pub(super) static CACHED_PAGER: OnceLock<Option<String>> = OnceLock::new();
/// If the pager takes longer than this, kill it and fall back to raw diff.
pub(super) const PAGER_TIMEOUT: Duration = Duration::from_millis(2000);
-/// Get the cached pager command, initializing if needed.
+/// Check if a pager spawns its own internal pager (e.g., less).
+/// Delta and bat spawn `less` by default, which hangs in non-TTY contexts.
+fn needs_paging_disabled(pager_cmd: &str) -> bool {
+ pager_cmd
+ .split_whitespace()
+ .next()
+ .and_then(extract_filename_from_path)
+ .is_some_and(|basename| {
+ basename.eq_ignore_ascii_case("delta")
+ || basename.eq_ignore_ascii_case("bat")
+ || basename.eq_ignore_ascii_case("batcat")
+ })
+}
+
+/// Get the cached pager command, ready to use.
///
-/// Precedence (highest to lowest):
-/// 1. `[select] pager` in user config (explicit override, used as-is)
-/// 2. `GIT_PAGER` environment variable (with auto-detection applied)
-/// 3. `core.pager` git config (with auto-detection applied)
+/// Returns the pager command with any necessary flags (like `--paging=never`)
+/// already appended. Precedence:
+/// 1. `[select] pager` in user config (used as-is)
+/// 2. `GIT_PAGER` environment variable (auto-detection applied)
+/// 3. `core.pager` git config (auto-detection applied)
pub(super) fn get_diff_pager() -> Option<&'static String> {
CACHED_PAGER
.get_or_init(|| {
- // Check user config first for explicit pager override
- // When set, use exactly as specified (no auto-detection)
+ // Check user config first - use exactly as specified (no auto-detection)
if let Ok(config) = UserConfig::load()
&& let Some(select_config) = config.configs.select
&& let Some(pager) = select_config.pager
@@ -43,143 +56,99 @@ pub(super) fn get_diff_pager() -> Option<&'static String> {
return Some(pager);
}
- // GIT_PAGER takes precedence over core.pager
- if let Ok(pager) = std::env::var("GIT_PAGER") {
- return parse_pager_value(&pager);
- }
+ // GIT_PAGER or core.pager - apply auto-detection for delta/bat
+ let pager = if let Ok(p) = std::env::var("GIT_PAGER") {
+ parse_pager_value(&p)
+ } else {
+ git_config_pager()
+ };
- // Fall back to core.pager config
- git_config_pager()
+ pager.map(|p| {
+ if needs_paging_disabled(&p) {
+ format!("{} --paging=never", p)
+ } else {
+ p
+ }
+ })
})
.as_ref()
}
-/// Check if the pager spawns its own internal pager (e.g., less).
+/// Pipe text through the configured pager for display.
///
-/// Some pagers like delta and bat spawn `less` by default, which hangs in
-/// non-TTY contexts like skim's preview panel. These need `--paging=never`.
-///
-/// Used only when user hasn't set `[select] pager` config explicitly.
-/// When config is set, that value is used as-is without modification.
-pub(super) fn pager_needs_paging_disabled(pager_cmd: &str) -> bool {
- // Split on whitespace to get the command name, then extract basename
- // Uses extract_filename_from_path for consistent handling of Windows paths and .exe
- pager_cmd
- .split_whitespace()
- .next()
- .and_then(extract_filename_from_path)
- // bat is called "batcat" on Debian/Ubuntu
- // Case-insensitive for Windows where commands might be Delta.exe, BAT.EXE, etc.
- .is_some_and(|basename| {
- basename.eq_ignore_ascii_case("delta")
- || basename.eq_ignore_ascii_case("bat")
- || basename.eq_ignore_ascii_case("batcat")
- })
-}
-
-/// Check if user has explicitly configured a select-specific pager.
-pub(super) fn has_explicit_pager_config() -> bool {
- UserConfig::load()
- .ok()
- .and_then(|config| config.configs.select)
- .and_then(|select| select.pager)
- .is_some_and(|p| !p.trim().is_empty())
-}
+/// Returns the paged output, or the original text if the pager fails or times out.
+/// Sets `COLUMNS` environment variable for pagers like delta with side-by-side mode.
+pub(super) fn pipe_through_pager(text: &str, pager_cmd: &str, width: usize) -> String {
+ log::debug!("Piping through pager: {}", pager_cmd);
-/// Run git diff piped directly through the pager as a streaming pipeline.
-///
-/// Runs `git <args> | pager` as a single shell command, avoiding intermediate
-/// buffering. Returns None if pipeline fails or times out (caller should fall back to raw diff).
-///
-/// Sets `COLUMNS` environment variable to the preview width, allowing pagers to detect
-/// the correct width. For pagers like delta with side-by-side mode, users can reference
-/// this in their config: `[select] pager = "delta --width=$COLUMNS"`.
-///
-/// When `[select] pager` is not configured, automatically appends `--paging=never` for
-/// delta/bat/batcat pagers to prevent hangs.
-pub(super) fn run_git_diff_with_pager(
- git_args: &[&str],
- pager_cmd: &str,
- width: usize,
-) -> Option<String> {
- // Note: pager_cmd is expected to be valid shell code (like git's core.pager).
- // Users with paths containing special chars must quote them in their config.
-
- // Apply auto-detection only when user hasn't set explicit config
- // If config is set, use the value as-is (user has full control)
- let pager_with_args = if !has_explicit_pager_config() && pager_needs_paging_disabled(pager_cmd)
- {
- format!("{} --paging=never", pager_cmd)
- } else {
- pager_cmd.to_string()
- };
-
- // Build shell pipeline: git <args> | pager
- // Shell-escape args to handle paths with spaces
- let escaped_args: Vec<String> = git_args
- .iter()
- .map(|arg| shlex::try_quote(arg).unwrap_or((*arg).into()).into_owned())
- .collect();
- let pipeline = format!("git {} | {}", escaped_args.join(" "), pager_with_args);
-
- log::debug!("Running pager pipeline: {}", pipeline);
-
- // Spawn pipeline with COLUMNS set to preview width
- // Pagers can use this directly (e.g., `delta --width=$COLUMNS`)
+ // Spawn pager with stdin piped
let mut child = match Command::new("sh")
.arg("-c")
- .arg(&pipeline)
+ .arg(pager_cmd)
+ .stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.env("COLUMNS", width.to_string())
- // Prevent subprocesses from writing to the directive file
.env_remove(worktrunk::shell_exec::DIRECTIVE_FILE_ENV_VAR)
.spawn()
{
Ok(child) => child,
Err(e) => {
- log::debug!("Failed to spawn pager pipeline: {}", e);
- return None;
+ log::debug!("Failed to spawn pager: {}", e);
+ return text.to_string();
}
};
- // Read output in a thread to avoid blocking
- let stdout = child.stdout.take()?;
+ // Write input to stdin in a thread to avoid deadlock.
+ // Thread will unblock when: (a) write completes, or (b) pipe breaks (pager exits/killed).
+ let stdin = child.stdin.take();
+ let input = text.to_string();
+ let writer_thread = std::thread::spawn(move || {
+ if let Some(mut stdin) = stdin {
+ use std::io::Write;
+ let _ = stdin.write_all(input.as_bytes());
+ }
+ });
+
+ // Read output in a thread to avoid deadlock (can't read stdout after stdin fills)
+ let stdout = child.stdout.take();
let reader_thread = std::thread::spawn(move || {
- let mut stdout = stdout;
- let mut output = Vec::new();
- let _ = stdout.read_to_end(&mut output);
- output
+ stdout.map(|mut stdout| {
+ let mut output = Vec::new();
+ let _ = stdout.read_to_end(&mut output);
+ output
+ })
});
- // Wait for pipeline with timeout
- let start = Instant::now();
- loop {
- match child.try_wait() {
- Ok(Some(status)) => {
- let output = reader_thread.join().ok()?;
- if status.success() {
- return String::from_utf8(output).ok();
- } else {
- log::debug!("Pager pipeline exited with status: {}", status);
- return None;
- }
- }
- Ok(None) => {
- if start.elapsed() > PAGER_TIMEOUT {
- log::debug!("Pager pipeline timed out after {:?}", PAGER_TIMEOUT);
- let _ = child.kill();
- return None;
- }
- std::thread::sleep(Duration::from_millis(10));
- }
- Err(e) => {
- log::debug!("Failed to wait for pager pipeline: {}", e);
- let _ = child.kill();
- return None;
+ // Wait for pager with timeout
+ match child.wait_timeout(PAGER_TIMEOUT) {
+ Ok(Some(status)) => {
+ // Pager exited within timeout
+ let _ = writer_thread.join();
+ if let Ok(Some(output)) = reader_thread.join()
+ && status.success()
+ && let Ok(s) = String::from_utf8(output)
+ {
+ return s;
}
+ log::debug!("Pager exited with status: {}", status);
+ }
+ Ok(None) => {
+ // Timed out - kill pager and clean up
+ log::debug!("Pager timed out after {:?}", PAGER_TIMEOUT);
+ let _ = child.kill();
+ let _ = child.wait();
+ let _ = reader_thread.join();
+ }
+ Err(e) => {
+ log::debug!("Failed to wait for pager: {}", e);
+ let _ = child.kill();
+ let _ = child.wait();
+ let _ = reader_thread.join();
}
}
+
+ text.to_string()
}
#[cfg(test)]
@@ -187,44 +156,76 @@ mod tests {
use super::*;
#[test]
- fn test_pager_needs_paging_disabled() {
+ fn test_needs_paging_disabled() {
// delta - plain command name
- assert!(pager_needs_paging_disabled("delta"));
+ assert!(needs_paging_disabled("delta"));
// delta - with arguments
- assert!(pager_needs_paging_disabled("delta --side-by-side"));
- assert!(pager_needs_paging_disabled("delta --paging=always"));
+ assert!(needs_paging_disabled("delta --side-by-side"));
+ assert!(needs_paging_disabled("delta --paging=always"));
// delta - full path
- assert!(pager_needs_paging_disabled("/usr/bin/delta"));
- assert!(pager_needs_paging_disabled(
+ assert!(needs_paging_disabled("/usr/bin/delta"));
+ assert!(needs_paging_disabled(
"/opt/homebrew/bin/delta --line-numbers"
));
// bat - also spawns less by default
- assert!(pager_needs_paging_disabled("bat"));
- assert!(pager_needs_paging_disabled("/usr/bin/bat"));
- assert!(pager_needs_paging_disabled("bat --style=plain"));
+ assert!(needs_paging_disabled("bat"));
+ assert!(needs_paging_disabled("/usr/bin/bat"));
+ assert!(needs_paging_disabled("bat --style=plain"));
// Pagers that don't spawn sub-pagers
- assert!(!pager_needs_paging_disabled("less"));
- assert!(!pager_needs_paging_disabled("diff-so-fancy"));
- assert!(!pager_needs_paging_disabled("colordiff"));
+ assert!(!needs_paging_disabled("less"));
+ assert!(!needs_paging_disabled("diff-so-fancy"));
+ assert!(!needs_paging_disabled("colordiff"));
// Edge cases - similar names but not delta/bat
- assert!(!pager_needs_paging_disabled("delta-preview"));
- assert!(!pager_needs_paging_disabled("/path/to/delta-preview"));
- assert!(pager_needs_paging_disabled("batcat")); // Debian's bat package name
+ assert!(!needs_paging_disabled("delta-preview"));
+ assert!(!needs_paging_disabled("/path/to/delta-preview"));
+ assert!(needs_paging_disabled("batcat")); // Debian's bat package name
// Case-insensitive matching (Windows command names)
- assert!(pager_needs_paging_disabled("Delta"));
- assert!(pager_needs_paging_disabled("DELTA"));
- assert!(pager_needs_paging_disabled("BAT"));
- assert!(pager_needs_paging_disabled("Bat"));
- assert!(pager_needs_paging_disabled("BatCat"));
- assert!(pager_needs_paging_disabled("delta.exe"));
- assert!(pager_needs_paging_disabled("Delta.EXE"));
+ assert!(needs_paging_disabled("Delta"));
+ assert!(needs_paging_disabled("DELTA"));
+ assert!(needs_paging_disabled("BAT"));
+ assert!(needs_paging_disabled("Bat"));
+ assert!(needs_paging_disabled("BatCat"));
+ assert!(needs_paging_disabled("delta.exe"));
+ assert!(needs_paging_disabled("Delta.EXE"));
+ }
+
+ #[test]
+ fn test_get_diff_pager_initializes() {
+ // Exercise the config initialization path
+ // Returns None or Some depending on user's pager config
+ let _ = get_diff_pager();
+ }
+
+ #[test]
+ fn test_pipe_through_pager_passthrough() {
+ // Use cat as a simple pager that passes through input unchanged
+ let input = "line 1\nline 2\nline 3";
+ let result = pipe_through_pager(input, "cat", 80);
+ assert_eq!(result, input);
+ }
+
+ #[test]
+ fn test_pipe_through_pager_with_transform() {
+ // Use tr to transform input (proves pager is actually being invoked)
+ let input = "hello world";
+ let result = pipe_through_pager(input, "tr 'a-z' 'A-Z'", 80);
+ assert_eq!(result, "HELLO WORLD");
+ }
+
+ #[test]
+ fn test_pipe_through_pager_invalid_command() {
+ // Invalid pager command should return original text
+ let input = "original text";
+ let result = pipe_through_pager(input, "nonexistent-command-xyz", 80);
+ assert_eq!(result, input);
}
#[test]
- fn test_has_explicit_pager_config() {
- // This function loads real config, so we just test that it doesn't panic
- // The behavior is covered by integration tests that set actual config
- let _ = has_explicit_pager_config();
+ fn test_pipe_through_pager_failing_command() {
+ // Pager that exits with error should return original text
+ let input = "original text";
+ let result = pipe_through_pager(input, "false", 80);
+ assert_eq!(result, input);
}
}
diff --git a/src/commands/select/preview.rs b/src/commands/select/preview.rs
index 561a2b17d..f8a28ad12 100644
--- a/src/commands/select/preview.rs
+++ b/src/commands/select/preview.rs
@@ -18,7 +18,7 @@ use std::path::PathBuf;
/// - Tab 2 shows commits (related to "main↕" counts)
/// - Tab 3 corresponds to "main…± (--full)" column
/// - Tab 4 corresponds to "Remote⇅" column
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(super) enum PreviewMode {
WorkingTree = 1,
Log = 2,
@@ -55,6 +55,9 @@ pub(super) const LIST_CHROME_LINES: usize = 4;
/// Minimum preview lines to keep usable even with many items.
pub(super) const MIN_PREVIEW_LINES: usize = 5;
+/// Preview width as percentage of terminal width (for Right layout).
+const PREVIEW_WIDTH_PERCENT: usize = 50;
+
/// Preview layout orientation for the interactive selector
///
/// Preview window position (auto-detected at startup based on terminal dimensions)
@@ -95,26 +98,37 @@ impl PreviewLayout {
}
}
- /// Calculate the preview window spec for skim
- ///
- /// For Right layout: always 50%
- /// For Down layout: dynamically sized based on item count - list gets
- /// up to MAX_VISIBLE_ITEMS lines, preview gets the rest (min 5 lines)
+ /// 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);
match self {
- Self::Right => "right:50%".to_string(),
- Self::Down => {
- let height = terminal_size::terminal_size()
- .map(|(_, terminal_size::Height(h))| h as usize)
- .unwrap_or(24);
+ Self::Right => format!("right:{}", width),
+ Self::Down => format!("down:{}", height),
+ }
+ }
- let available = height * SKIM_HEIGHT_PERCENT / 100;
+ /// Calculate preview dimensions (width, height) in characters.
+ /// Single source of truth for preview sizing — used by both skim config
+ /// and background pre-computation.
+ 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));
+
+ match self {
+ Self::Right => {
+ let width = term_width * PREVIEW_WIDTH_PERCENT / 100;
+ let height = term_height * SKIM_HEIGHT_PERCENT / 100;
+ (width, height)
+ }
+ Self::Down => {
+ let width = term_width;
+ let available = term_height * SKIM_HEIGHT_PERCENT / 100;
let list_lines = LIST_CHROME_LINES + num_items.min(MAX_VISIBLE_ITEMS);
- // Ensure preview doesn't exceed available space while trying to maintain minimum
let remaining = available.saturating_sub(list_lines);
- let preview_lines = remaining.max(MIN_PREVIEW_LINES).min(available);
-
- format!("down:{}", preview_lines)
+ let height = remaining.max(MIN_PREVIEW_LINES).min(available);
+ (width, height)
}
}
}
@@ -187,8 +201,9 @@ mod tests {
#[test]
fn test_preview_layout_to_preview_window_spec() {
- // Right is always 50%
- assert_eq!(PreviewLayout::Right.to_preview_window_spec(10), "right:50%");
+ // 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);
diff --git a/src/shell/utils.rs b/src/shell/utils.rs
index 270de9458..c98ffeab1 100644
--- a/src/shell/utils.rs
+++ b/src/shell/utils.rs
@@ -4,7 +4,9 @@
//! shell names from paths, and probing shell configuration state.
use std::process::{Command, Stdio};
-use std::time::{Duration, Instant};
+use std::time::Duration;
+
+use wait_timeout::ChildExt;
use super::Shell;
@@ -131,29 +133,27 @@ pub fn detect_zsh_compinit() -> Option<bool> {
.spawn()
.ok()?;
- let start = Instant::now();
+ // Take stdout handle before wait_timeout (which reaps the process)
+ let mut stdout_handle = child.stdout.take()?;
+
let timeout = Duration::from_secs(2);
- loop {
- match child.try_wait() {
- Ok(Some(_status)) => {
- // Process finished (exit status is always 0 due to || fallback in probe)
- // wait_with_output() collects remaining stdout even after try_wait() succeeds
- let output = child.wait_with_output().ok()?;
- let stdout = String::from_utf8_lossy(&output.stdout);
- return Some(stdout.contains("__WT_COMPINIT_YES__"));
- }
- Ok(None) => {
- // Still running - check timeout
- if start.elapsed() > timeout {
- let _ = child.kill();
- let _ = child.wait(); // Reap zombie process
- return None;
- }
- std::thread::sleep(Duration::from_millis(20));
- }
- Err(_) => return None,
+ match child.wait_timeout(timeout) {
+ Ok(Some(_status)) => {
+ // Process finished - read stdout (use lossy decode for robustness)
+ use std::io::Read;
+ let mut buf = Vec::new();
+ let _ = stdout_handle.read_to_end(&mut buf);
+ let stdout = String::from_utf8_lossy(&buf);
+ Some(stdout.contains("__WT_COMPINIT_YES__"))
+ }
+ Ok(None) => {
+ // Timed out - kill and clean up
+ let _ = child.kill();
+ let _ = child.wait();
+ None
}
+ Err(_) => None,
}
}
diff --git a/src/shell_exec.rs b/src/shell_exec.rs
index 6900c48a3..1a73cb9b6 100644
--- a/src/shell_exec.rs
+++ b/src/shell_exec.rs
@@ -14,6 +14,8 @@ use std::process::{Command, Stdio};
use std::sync::OnceLock;
use std::time::Instant;
+use wait_timeout::ChildExt;
+
use crate::git::{GitError, WorktrunkError};
use crate::sync::Semaphore;
@@ -295,29 +297,21 @@ fn run_with_timeout_impl(
});
// Wait for process with timeout
- let deadline = Instant::now() + timeout;
- let status = loop {
- match child.try_wait()? {
- Some(status) => break status,
- None => {
- if Instant::now() >= deadline {
- // Timeout exceeded - kill the process (SIGKILL on Unix)
- let _ = child.kill();
- let _ = child.wait(); // Reap the process
-
- // Wait for reader threads to complete (they'll see EOF after kill)
- // This prevents thread leaks
- let _ = stdout_thread.join();
- let _ = stderr_thread.join();
-
- return Err(std::io::Error::new(
- ErrorKind::TimedOut,
- "command timed out",
- ));
- }
- // Sleep briefly before checking again
- std::thread::sleep(std::time::Duration::from_millis(10));
- }
+ let status = match child.wait_timeout(timeout)? {
+ Some(status) => status,
+ None => {
+ // Timeout exceeded - kill the process
+ let _ = child.kill();
+ let _ = child.wait();
+
+ // Wait for reader threads to complete (they'll see EOF after kill)
+ let _ = stdout_thread.join();
+ let _ = stderr_thread.join();
+
+ return Err(std::io::Error::new(
+ ErrorKind::TimedOut,
+ "command timed out",
+ ));
}
};