Skip to content

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

fix(tui): Prevent pager from hanging

Maximilian Roosc6122a1d1e9b
diff --git a/Cargo.toml b/Cargo.toml
index a55f5f133..6da82bff9 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -38,6 +38,12 @@ path = "src/main.rs"
name = "dev-detach"
path = "tests/bin/dev-detach.rs"
+# Helper binary to setup test environment for debugging `wt beta select`.
+# Creates a temporary repo with known state for manual testing.
+[[bin]]
+name = "setup-select-test"
+path = "tests/bin/setup-select-test.rs"
+
[dependencies]
anstream = "0.6"
anstyle = "1.0"
@@ -98,10 +104,11 @@ name = "list"
harness = false
[lints.rust]
-# No unsafe code in the main codebase or tests.
-# TTY isolation for shell integration tests is handled by the dev-detach helper binary,
-# which uses the nix crate's safe wrappers for Unix syscalls (setsid, execvp).
-unsafe_code = "forbid"
+# Unsafe code is denied by default but can be explicitly allowed where necessary.
+# Currently used for:
+# - TTY detachment in pager invocation (pre_exec + setsid) to prevent hangs in TUI contexts
+# - dev-detach helper binary (uses nix crate's wrappers for Unix syscalls)
+unsafe_code = "deny"
# The profile that 'dist' will build with
[profile.dist]
diff --git a/src/commands/CLAUDE.md b/src/commands/CLAUDE.md
new file mode 100644
index 000000000..dfdcf967c
--- /dev/null
+++ b/src/commands/CLAUDE.md
@@ -0,0 +1,68 @@
+# Debugging Interactive Terminal Commands
+
+When debugging TUI commands like `wt beta select`, use MCP's `node-terminal` tools to test interactively.
+
+## Debugging Workflow
+
+### 1. Create Test Environment
+
+```bash
+cargo run --bin setup-select-test
+```
+
+This creates a reproducible test repo at `/tmp/wt-select-test/test-repo`.
+
+### 2. Test in MCP Terminal
+
+```typescript
+// Create terminal and navigate to test repo
+mcp__node-terminal__terminal_create({ sessionId: "test" })
+mcp__node-terminal__terminal_write({ sessionId: "test", input: "cd /tmp/wt-select-test/test-repo" })
+mcp__node-terminal__terminal_send_key({ sessionId: "test", key: "enter" })
+
+// Run with debug logging
+mcp__node-terminal__terminal_write({
+ sessionId: "test",
+ input: "RUST_LOG=worktrunk=debug cargo run --quiet -- beta select 2> test.log"
+})
+mcp__node-terminal__terminal_send_key({ sessionId: "test", key: "enter" })
+
+// Test the interaction
+mcp__node-terminal__terminal_write({ sessionId: "test", input: "3" })
+mcp__node-terminal__terminal_read({ sessionId: "test" })
+```
+
+### 3. If Synthetic Test Works But User Reports Issues
+
+**Test on the actual repository!** Environment-specific issues (git config, shell config) won't appear in isolated test environments.
+
+```typescript
+// Use -C to test in user's actual repo
+mcp__node-terminal__terminal_write({
+ sessionId: "test",
+ input: "RUST_LOG=worktrunk=debug cargo run --quiet -- -C /path/to/actual/repo beta select 2> debug.log"
+})
+```
+
+### 4. Analyze Logs
+
+```bash
+tail -100 debug.log | grep -E "error|hang|stuck"
+```
+
+## Important Flags
+
+- **`-C <path>`**: Set working directory (alternative to `cd`)
+- **`--source`**: Use local source (only needed with installed `wt`, not with `cargo run`)
+
+```bash
+# Testing with cargo run (already uses local source):
+cargo run --quiet -- -C /path/to/repo beta select
+
+# Testing with installed wt:
+wt --source -C /path/to/repo beta select
+```
+
+## MCP Limitations
+
+MCP terminals use pseudo-TTY, not real terminals. If tests pass in MCP but users report issues, the bug is likely environment-specific. Always test on the actual problematic repository.
diff --git a/src/commands/select.rs b/src/commands/select.rs
index c90ae4ca6..13495d0f9 100644
--- a/src/commands/select.rs
+++ b/src/commands/select.rs
@@ -95,7 +95,8 @@ impl SkimItem for WorktreeSkimItem {
fn preview(&self, _context: PreviewContext<'_>) -> ItemPreview {
let mode = PreviewMode::read_from_state();
- ItemPreview::AnsiText(self.preview_for_mode(mode).clone())
+ let result = self.preview_for_mode(mode);
+ ItemPreview::AnsiText(result.clone())
}
}
@@ -130,7 +131,7 @@ impl WorktreeSkimItem {
output.push_str(&stat);
output.push_str("\n\n");
- // Show full diff with renderer
+ // Show full diff with pager (spawned via setsid to prevent TTY access)
if let Ok(diff) = repo.run_diff_with_pager(args) {
output.push_str(&diff);
}
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index 43b231f64..679e5421a 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -1012,6 +1012,9 @@ impl Repository {
}
/// Run git diff through a renderer (pager) if configured, otherwise return colored diff output.
+ ///
+ /// The pager is spawned in a detached session (via setsid on Unix) to prevent it from
+ /// accessing /dev/tty, which would cause hangs when called from within TUI contexts like skim.
pub fn run_diff_with_pager(&self, args: &[&str]) -> Result<String, GitError> {
let mut git_args = args.to_vec();
git_args.push("--color=always");
@@ -1058,7 +1061,11 @@ fn detect_pager() -> Option<String> {
.or_else(|| std::env::var("PAGER").ok().and_then(|s| validate(&s)))
}
+#[cfg(unix)]
+#[allow(unsafe_code)] // Required for pre_exec + setsid to detach from controlling terminal
fn invoke_renderer(pager_cmd: &str, git_output: &str) -> Option<String> {
+ use std::os::unix::process::CommandExt;
+
log::debug!("Invoking renderer: {}", pager_cmd);
let mut cmd = Command::new("sh");
@@ -1069,10 +1076,56 @@ fn invoke_renderer(pager_cmd: &str, git_output: &str) -> Option<String> {
.stderr(Stdio::null())
.env("PAGER", "cat")
.env("DELTA_PAGER", "cat")
- .env("BAT_PAGER", "");
+ .env("BAT_PAGER", "")
+ .env("DELTA_NAVIGATE", "0"); // Disable interactive navigate mode (requires TTY)
+
+ // Detach from controlling terminal to prevent pager from accessing /dev/tty
+ // This is critical for TUI contexts (like skim preview) where TTY access would hang
+ //
+ // SAFETY: pre_exec is safe here because:
+ // - setsid() is async-signal-safe (can be called between fork and exec)
+ // - We don't access any memory from the parent process
+ // - We don't perform any allocations or other unsafe operations
+ // - setsid() cannot fail in this context (fresh fork, not a process group leader)
+ unsafe {
+ cmd.pre_exec(|| {
+ // setsid() cannot fail after fork() - we're not a process group leader yet
+ let _ = nix::unistd::setsid();
+ Ok(())
+ });
+ }
+
+ let child = cmd.spawn().ok()?;
+ handle_pager_io(child, git_output)
+}
+
+#[cfg(windows)]
+fn invoke_renderer(pager_cmd: &str, git_output: &str) -> Option<String> {
+ use std::os::windows::process::CommandExt;
+
+ log::debug!("Invoking renderer: {}", pager_cmd);
+
+ const CREATE_NEW_PROCESS_GROUP: u32 = 0x00000200;
+ const DETACHED_PROCESS: u32 = 0x00000008;
+
+ let mut cmd = Command::new("cmd");
+ cmd.arg("/C")
+ .arg(pager_cmd)
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null())
+ .env("PAGER", "cat")
+ .env("DELTA_PAGER", "cat")
+ .env("BAT_PAGER", "")
+ .env("DELTA_NAVIGATE", "0") // Disable interactive navigate mode (requires TTY)
+ .creation_flags(CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS);
- let mut child = cmd.spawn().ok()?;
+ let child = cmd.spawn().ok()?;
+ handle_pager_io(child, git_output)
+}
+/// Common I/O handling for pager child processes
+fn handle_pager_io(mut child: std::process::Child, git_output: &str) -> Option<String> {
if let Some(mut stdin) = child.stdin.take() {
let _ = stdin.write_all(git_output.as_bytes());
drop(stdin);
diff --git a/tests/bin/setup-select-test.rs b/tests/bin/setup-select-test.rs
new file mode 100644
index 000000000..4a0298e56
--- /dev/null
+++ b/tests/bin/setup-select-test.rs
@@ -0,0 +1,188 @@
+//! Helper binary to setup a test environment for debugging `wt beta select`
+//!
+//! This creates a temporary git repository with a known state:
+//! - main branch with 3 commits
+//! - feature branch with 15 commits ahead of main (100 lines per file)
+//! - Multiple worktrees with varying amounts of work
+//! - Some uncommitted changes in the feature worktree
+//!
+//! Run with: cargo run --bin setup-select-test
+//! Then cd into the printed path and run: wt beta select
+
+use std::fs;
+use std::io::{self, Write};
+use std::path::PathBuf;
+use std::process::Command;
+
+fn main() {
+ println!("Setting up test environment for `wt beta select`...\n");
+
+ // Create temp directory in /tmp
+ let temp_base = std::env::temp_dir().join("wt-select-test");
+ if temp_base.exists() {
+ fs::remove_dir_all(&temp_base).expect("Failed to clean old test directory");
+ }
+ fs::create_dir(&temp_base).expect("Failed to create temp directory");
+
+ let root = temp_base.join("test-repo");
+ fs::create_dir(&root).expect("Failed to create repo directory");
+ let root = root.canonicalize().expect("Failed to canonicalize path");
+
+ // Initialize git repo
+ git(&root, &["init", "-b", "main"]);
+ git(&root, &["config", "user.name", "Test User"]);
+ git(&root, &["config", "user.email", "[email protected]"]);
+
+ // Create commits on main
+ for i in 1..=3 {
+ fs::write(
+ root.join(format!("file{}.txt", i)),
+ format!("content {}", i),
+ )
+ .expect("Failed to write file");
+ git(&root, &["add", "."]);
+ git(&root, &["commit", "-m", &format!("Main commit {}", i)]);
+ }
+
+ // Create feature branch with commits ahead - MORE COMMITS AND BIGGER FILES
+ git(&root, &["switch", "-c", "feature"]);
+ for i in 1..=15 {
+ // Create larger files with more content
+ let mut content = String::new();
+ for line in 1..=100 {
+ content.push_str(&format!("Line {} of feature file {}\n", line, i));
+ }
+ fs::write(root.join(format!("feature{}.txt", i)), content).expect("Failed to write file");
+ git(&root, &["add", "."]);
+ git(
+ &root,
+ &[
+ "commit",
+ "-m",
+ &format!("Feature commit {}: Add feature{}.txt with 100 lines", i, i),
+ ],
+ );
+ }
+
+ // Switch back to main in primary worktree BEFORE creating worktrees
+ git(&root, &["switch", "main"]);
+
+ // Create multiple worktrees to simulate realistic scenario
+
+ // Feature worktree (15 commits ahead)
+ let feature_wt = temp_base.join("feature-wt");
+ git(
+ &root,
+ &["worktree", "add", feature_wt.to_str().unwrap(), "feature"],
+ );
+
+ // Create more branches with different amounts of work
+ for (i, num_commits) in [(2, 5), (3, 3), (4, 8), (5, 2)].iter() {
+ let branch_name = format!("branch{}", i);
+ git(&root, &["branch", &branch_name, "main"]);
+
+ let wt_path = temp_base.join(format!("branch{}-wt", i));
+ git(
+ &root,
+ &["worktree", "add", wt_path.to_str().unwrap(), &branch_name],
+ );
+
+ // Add commits to this branch via its worktree
+ for j in 1..=*num_commits {
+ let file_content = format!("Content for {} commit {}\n", branch_name, j);
+ fs::write(wt_path.join(format!("file{}.txt", j)), file_content)
+ .expect("Failed to write file");
+ let mut cmd = Command::new("git");
+ git_env(&mut cmd);
+ cmd.args(["add", "."])
+ .current_dir(&wt_path)
+ .output()
+ .expect("Failed to git add");
+
+ let mut cmd = Command::new("git");
+ git_env(&mut cmd);
+ cmd.args(["commit", "-m", &format!("{} commit {}", branch_name, j)])
+ .current_dir(&wt_path)
+ .output()
+ .expect("Failed to git commit");
+ }
+ }
+
+ // Add uncommitted changes to feature worktree
+ let feature_wt = feature_wt.canonicalize().expect("Failed to canonicalize");
+ fs::write(feature_wt.join("uncommitted.txt"), "uncommitted changes")
+ .expect("Failed to write uncommitted file");
+
+ // Create some branches without worktrees
+ git(&root, &["branch", "no-worktree-1", "main"]);
+ git(&root, &["branch", "no-worktree-2", "main"]);
+
+ println!("✅ Test environment ready!\n");
+ println!("Repository path: {}", root.display());
+ println!();
+ println!("Worktrees created:");
+ println!(" - main (primary): {}", root.display());
+ println!(" - feature: 15 commits ahead, 1 uncommitted file");
+ println!(" - branch2: 5 commits ahead");
+ println!(" - branch3: 3 commits ahead");
+ println!(" - branch4: 8 commits ahead");
+ println!(" - branch5: 2 commits ahead");
+ println!();
+ println!("Branches without worktrees:");
+ println!(" - no-worktree-1, no-worktree-2");
+ println!();
+ println!("Total: 6 worktrees + 2 branches = 8 items in list");
+ println!();
+ println!("To test:");
+ println!();
+ println!("Method 1 - Using cd:");
+ println!(" cd {}", root.display());
+ println!(" cargo run --quiet -- beta select");
+ println!();
+ println!("Method 2 - Using -C flag:");
+ println!(" cargo run --quiet -- -C {} beta select", root.display());
+ println!();
+ println!("Expected behavior:");
+ println!(" - Navigate with arrow keys through 8 items");
+ println!(" - Press 3 on 'feature': Shows LARGE diff (15 files, 1500 lines)");
+ println!(" - Press 3 on other branches: Shows smaller diffs");
+ println!();
+ println!("Press Enter to clean up and exit (or Ctrl+C to leave the test repo)...");
+
+ io::stdout().flush().unwrap();
+ let mut input = String::new();
+ io::stdin().read_line(&mut input).unwrap();
+
+ println!("Cleaning up...");
+ if let Err(e) = fs::remove_dir_all(&temp_base) {
+ eprintln!("Warning: Failed to clean up test directory: {}", e);
+ eprintln!("You may need to manually remove: {}", temp_base.display());
+ } else {
+ println!("Test environment cleaned up.");
+ }
+}
+
+fn git_env(cmd: &mut Command) {
+ // Set git config for test environment
+ cmd.env("GIT_CONFIG_GLOBAL", "/dev/null");
+ cmd.env("GIT_CONFIG_SYSTEM", "/dev/null");
+ cmd.env("GIT_AUTHOR_DATE", "2025-01-01T00:00:00Z");
+ cmd.env("GIT_COMMITTER_DATE", "2025-01-01T00:00:00Z");
+}
+
+fn git(repo: &PathBuf, args: &[&str]) {
+ let mut cmd = Command::new("git");
+ git_env(&mut cmd);
+ let output = cmd
+ .args(args)
+ .current_dir(repo)
+ .output()
+ .expect("Failed to execute git command");
+
+ if !output.status.success() {
+ eprintln!("Git command failed: git {}", args.join(" "));
+ eprintln!("stdout: {}", String::from_utf8_lossy(&output.stdout));
+ eprintln!("stderr: {}", String::from_utf8_lossy(&output.stderr));
+ std::process::exit(1);
+ }
+}