Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Fix shell wrapper piping and simplify process detachment (#258)
Maximilian Roosb4e2f2e4edb2
diff --git a/docs/content/faq.md b/docs/content/faq.mdindex 77f2fc9cb..da33b706d 100644--- a/docs/content/faq.md+++ b/docs/content/faq.md@@ -138,6 +138,25 @@ $ cargo install worktrunk --no-default-featuresThis disables bash syntax highlighting in command output but keeps all core functionality. The syntax highlighting feature requires C99 compiler support and can fail on older systems or minimal Docker images.+## Why does JSON output go to stderr?++The `wt` shell function captures stdout so it can eval the output as shell script — this is how `wt switch` runs `cd` in the caller's shell. With stdout reserved for shell directives, data output (JSON, tables) goes to stderr during interactive use.++When stdout isn't a terminal (piped or redirected), the wrapper runs the binary directly instead:++```bash+wt list --format=json | jq . # Binary runs directly, JSON flows to jq+wt list --format=json > worktrees.json # Binary runs directly, JSON goes to file+```++This direct-binary mode applies to all commands, not just data-producing flags. Shell-side effects like directory changing require the wrapper, so `wt switch branch | cat` won't change directories. In practice this is fine — piped output is typically for data processing, not interactive use.++To force direct-binary mode interactively, bypass the wrapper:++```bash+command wt list --format=json # Outputs to stdout+```+## Running tests (for contributors)### Quick testsdiff --git a/src/commands/process.rs b/src/commands/process.rsindex bc2e5e20f..5d1ed58a7 100644--- a/src/commands/process.rs+++ b/src/commands/process.rs@@ -48,7 +48,7 @@ fn posix_command_separator(command: &str) -> &'static str {/// Spawn a detached background process with output redirected to a log file////// The process will be fully detached from the parent:-/// - On Unix: uses double-fork with setsid to create a daemon+/// - On Unix: uses process_group(0) to create a new process group (survives PTY closure)/// - On Windows: uses CREATE_NEW_PROCESS_GROUP to detach from console////// Logs are centralized in the main worktree's `.git/wt-logs/` directory.@@ -99,12 +99,12 @@ pub fn spawn_detached(#[cfg(unix)]{- spawn_detached_unix(worktree_path, command, log_file, context_json)?;+ spawn_detached_unix(worktree_path, command, log_file, context_json, name)?;}#[cfg(windows)]{- spawn_detached_windows(worktree_path, command, log_file, context_json)?;+ spawn_detached_windows(worktree_path, command, log_file, context_json, name)?;}Ok(log_path)@@ -116,14 +116,9 @@ fn spawn_detached_unix(command: &str,log_file: fs::File,context_json: Option<&str>,+ name: &str,) -> anyhow::Result<()> {- // Detachment using nohup and background execution (&):- // - nohup makes the process immune to SIGHUP (continues after parent exits)- // - sh -c allows complex shell commands with pipes, redirects, etc.- // - & backgrounds the process immediately- // - We wait for the outer shell to exit (happens immediately after backgrounding)- // - This prevents zombie process accumulation under high concurrency- // - Output redirected to log file for debugging+ use std::os::unix::process::CommandExt;// Build the command, optionally piping JSON context to stdinlet full_command = match context_json {@@ -141,12 +136,18 @@ fn spawn_detached_unix(None => command.to_string(),};+ let shell_cmd = format!("sh -c {} &", shell_escape::escape(full_command.into()));++ // Log only the operation identifier, not the full command (which may contain context_json+ // with user data that shouldn't appear in debug logs)+ log::debug!("spawn_detached: {} in {}", name, worktree_path.display());++ // Detachment via process_group(0): puts the spawned shell in its own process group.+ // When the controlling PTY closes, SIGHUP is sent to the foreground process group.+ // Since our process is in a different group, it doesn't receive the signal.let mut child = Command::new("sh").arg("-c")- .arg(format!(- "nohup sh -c {} &",- shell_escape::escape(full_command.into())- ))+ .arg(&shell_cmd).current_dir(worktree_path).stdin(Stdio::null()).stdout(Stdio::from(@@ -155,10 +156,11 @@ fn spawn_detached_unix(.context("Failed to clone log file handle")?,)).stderr(Stdio::from(log_file))+ .process_group(0) // New process group, not in PTY's foreground group.spawn().context("Failed to spawn detached process")?;- // Wait for the outer shell to exit (immediate, doesn't block on background command)+ // Wait for sh to exit (immediate, doesn't block on background command)child.wait().context("Failed to wait for detachment shell")?;@@ -172,10 +174,15 @@ fn spawn_detached_windows(command: &str,log_file: fs::File,context_json: Option<&str>,+ name: &str,) -> anyhow::Result<()> {use std::os::windows::process::CommandExt;use worktrunk::shell_exec::ShellConfig;+ // Log only the operation identifier, not the full command (which may contain context_json+ // with user data that shouldn't appear in debug logs)+ log::debug!("spawn_detached: {} in {}", name, worktree_path.display());+// CREATE_NEW_PROCESS_GROUP: Creates new process group (0x00000200)// DETACHED_PROCESS: Creates process without console (0x00000008)const CREATE_NEW_PROCESS_GROUP: u32 = 0x00000200;diff --git a/src/commands/statusline.rs b/src/commands/statusline.rsindex 1fa01cb04..d1c3a6be4 100644--- a/src/commands/statusline.rs+++ b/src/commands/statusline.rs@@ -123,7 +123,7 @@ fn format_directory_fish_style(path: &Path) -> String {/// Run the statusline command.///-/// Output uses `output::data_raw()` which routes based on mode:+/// Output uses `output::data()` which routes based on mode:/// - Interactive: stdout (for shell prompts)/// - Directive: stderr (stdout reserved for shell script)pub fn run(claude_code: bool) -> Result<()> {@@ -201,7 +201,7 @@ pub fn run(claude_code: bool) -> Result<()> {use worktrunk::styling::fix_dim_after_color_reset;let reset = anstyle::Reset;let output = fix_dim_after_color_reset(&output);- output::data_raw(format!("{reset} {output}"))?;+ output::data(format!("{reset} {output}"))?;}Ok(())diff --git a/src/output/global.rs b/src/output/global.rsindex 1dd48d0f1..dcd9421e3 100644--- a/src/output/global.rs+++ b/src/output/global.rs@@ -33,7 +33,7 @@ use std::process::Stdio;use std::sync::{Mutex, OnceLock};#[cfg(unix)]use worktrunk::shell_exec::ShellConfig;-use worktrunk::styling::{eprintln, hint_message, println, stderr};+use worktrunk::styling::{eprintln, hint_message, stderr};/// Output mode selection#[derive(Debug, Clone, Copy)]@@ -127,8 +127,10 @@ pub fn blank() -> io::Result<()> {/// Emit structured data output without emoji decoration///-/// Used for JSON and other pipeable data.-/// - **Interactive**: writes to stdout (for piping to `jq`, etc.)+/// Used for JSON, prompts, statuslines, and other pipeable data. Writes directly+/// to stdout/stderr without anstream processing, preserving any ANSI codes.+///+/// - **Interactive**: writes to stdout (for piping to `jq`, `llm`, etc.)/// - **Directive**: writes to stderr (stdout reserved for shell script)////// Example:@@ -136,30 +138,6 @@ pub fn blank() -> io::Result<()> {/// output::data(json_string)?;/// ```pub fn data(content: impl Into<String>) -> io::Result<()> {- let content = content.into();- match get_mode() {- OutputMode::Interactive => {- // Structured data goes to stdout for piping- println!("{content}");- io::stdout().flush()- }- OutputMode::Directive(_) => {- // stdout reserved for shell script, data goes to stderr- eprintln!("{content}");- stderr().flush()- }- }-}--/// Emit raw data output, bypassing anstream color detection-///-/// Like `data()` but writes directly to stdout/stderr without anstream processing.-/// Use when ANSI codes must be preserved regardless of TTY detection (e.g., statusline-/// output for Claude Code which always expects ANSI).-///-/// - **Interactive**: writes to stdout-/// - **Directive**: writes to stderr (stdout reserved for shell script)-pub fn data_raw(content: impl Into<String>) -> io::Result<()> {let content = content.into();match get_mode() {OutputMode::Interactive => {diff --git a/src/output/mod.rs b/src/output/mod.rsindex 9a3f3d860..83fea126b 100644--- a/src/output/mod.rs+++ b/src/output/mod.rs@@ -54,8 +54,8 @@ pub mod handlers;// Re-export the public APIpub use global::{- OutputMode, blank, change_directory, data, data_raw, execute, flush, flush_for_stderr_prompt,- gutter, initialize, print, shell_integration_hint, table, terminate_output,+ OutputMode, blank, change_directory, data, execute, flush, flush_for_stderr_prompt, gutter,+ initialize, print, shell_integration_hint, table, terminate_output,};// Re-export output handlerspub use handlers::{diff --git a/templates/bash.sh b/templates/bash.shindex 01718e68d..91540a2b3 100644--- a/templates/bash.sh+++ b/templates/bash.sh@@ -25,6 +25,10 @@ if command -v {{ cmd }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then# --source: use cargo run (builds from source)if [[ "$use_source" == true ]]; then+ if [[ ! -t 1 ]]; then+ cargo run --bin {{ cmd }} --quiet -- "${args[@]}"+ return+ filocal script exit_code=0script="$(cargo run --bin {{ cmd }} --quiet -- --internal "${args[@]}")" || exit_code=$?if [[ -n "$script" ]]; then@@ -36,6 +40,13 @@ if command -v {{ cmd }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; thenreturn "$exit_code"fi+ # If stdout is not a terminal (piped/redirected), run directly.+ # This allows `wt list --format=json | jq` to work.+ if [[ ! -t 1 ]]; then+ command "${WORKTRUNK_BIN:-{{ cmd }}}" "${args[@]}"+ return+ fi+wt_exec --internal "${args[@]}"}diff --git a/templates/fish.fish b/templates/fish.fishindex c35acdd86..047de251a 100644--- a/templates/fish.fish+++ b/templates/fish.fish@@ -38,6 +38,10 @@ if type -q {{ cmd }}; or test -n "$WORKTRUNK_BIN"# --source: use cargo run (builds from source)if test $use_source = true+ if not isatty stdout+ cargo run --bin {{ cmd }} --quiet -- $args+ return $status+ endcargo run --bin {{ cmd }} --quiet -- --internal $args | string collect --allow-empty | read --local -z scriptset -l exit_code $pipestatus[1]if test -n "$script"@@ -49,6 +53,14 @@ if type -q {{ cmd }}; or test -n "$WORKTRUNK_BIN"return $exit_codeend+ # If stdout is not a terminal (piped/redirected), run directly.+ # This allows `wt list --format=json | jq` to work.+ if not isatty stdout+ test -n "$WORKTRUNK_BIN"; or set -l WORKTRUNK_BIN (type -P {{ cmd }})+ command $WORKTRUNK_BIN $args+ return $status+ end+wt_exec --internal $argsenddiff --git a/templates/powershell.ps1 b/templates/powershell.ps1index 17044ac36..b385e6b6e 100644--- a/templates/powershell.ps1+++ b/templates/powershell.ps1@@ -17,6 +17,14 @@ if (Get-Command {{ cmd }} -ErrorAction SilentlyContinue) {$wtBin = (Get-Command {{ cmd }} -CommandType Application).Source+ # If output is redirected (piped), run directly without wrapper.+ # This allows `wt list --format=json | ConvertFrom-Json` to work - the output+ # flows through instead of being captured and Invoke-Expression'd.+ if ([Console]::IsOutputRedirected) {+ & $wtBin @Arguments+ return $LASTEXITCODE+ }+# Run wt with --internal=powershell# stdout is captured for Invoke-Expression (contains Set-Location directives)# stderr passes through to console in real-time (user messages, progress, errors)diff --git a/templates/zsh.zsh b/templates/zsh.zshindex 53f44e51f..bcaa7b139 100644--- a/templates/zsh.zsh+++ b/templates/zsh.zsh@@ -28,6 +28,10 @@ if command -v {{ cmd }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then# --source: use cargo run (builds from source)if [[ "$use_source" == true ]]; then+ if [[ ! -t 1 ]]; then+ cargo run --bin {{ cmd }} --quiet -- "${args[@]}"+ return+ filocal script exit_code=0script="$(cargo run --bin {{ cmd }} --quiet -- --internal "${args[@]}")" || exit_code=$?if [[ -n "$script" ]]; then@@ -39,6 +43,13 @@ if command -v {{ cmd }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; thenreturn "$exit_code"fi+ # If stdout is not a terminal (piped/redirected), run directly.+ # This allows `wt list --format=json | jq` to work.+ if [[ ! -t 1 ]]; then+ command "${WORKTRUNK_BIN:-{{ cmd }}}" "${args[@]}"+ return+ fi+wt_exec --internal "${args[@]}"}diff --git a/tests/common/mod.rs b/tests/common/mod.rsindex 114769110..a9b7f4e9e 100644--- a/tests/common/mod.rs+++ b/tests/common/mod.rs@@ -1933,6 +1933,17 @@ pub fn setup_snapshot_settings(repo: &TestRepo) -> insta::Settings {settings.add_filter(r"\x1b\[0m$", "");settings.add_filter(r"\x1b\[0m\n", "\n");+ // Normalize tree-sitter bash syntax highlighting differences between platforms.+ // On Linux, tree-sitter-bash may parse paths as "string" tokens (green: [32m),+ // while on macOS the same paths are just dimmed (no color). This causes snapshot+ // mismatches when the same code produces different ANSI sequences.+ // Strip green color from _REPO_ placeholders and normalize the surrounding sequences.+ // Pattern: [2m [0m[2m[32m_REPO_...[0m[2m [0m[2m -> [2m _REPO_... [0m[2m+ settings.add_filter(+ r"\x1b\[2m \x1b\[0m\x1b\[2m\x1b\[32m(_REPO_[^\x1b]*)\x1b\[0m\x1b\[2m \x1b\[0m\x1b\[2m",+ "\x1b[2m $1 \x1b[0m\x1b[2m",+ );+settings}diff --git a/tests/common/shell.rs b/tests/common/shell.rsindex 0985d3e2e..811005685 100644--- a/tests/common/shell.rs+++ b/tests/common/shell.rs@@ -2,8 +2,6 @@ use super::{TestRepo, wt_command};use insta_cmd::get_cargo_bin;use std::{collections::HashSet,- env,- path::PathBuf,process::{Command, Stdio},sync::LazyLock,};@@ -49,80 +47,6 @@ pub fn shell_available(shell: &str) -> bool {AVAILABLE_SHELLS.contains(shell)}-/// Path to dev-detach binary (workspace member built automatically by `cargo test`).-///-/// Uses custom binary detection (matching insta_cmd's logic) to provide a clearer-/// error message when the binary is missing. The standard `get_cargo_bin()` panics-/// with "Cannot determine path to executable 'dev-detach'" which doesn't explain-/// how to fix the issue.-///-/// Note: The binary is only built when running `cargo test` without package filters.-/// Commands like `cargo test -p worktrunk` or `cargo test --test integration` do NOT-/// build the dev-detach binary. Use `cargo test` or `cargo test --workspace` instead.-static DEV_DETACH_BIN: LazyLock<PathBuf> = LazyLock::new(|| {- // Check for CARGO_BIN_EXE_dev-detach first (set when dev-detach is a build dependency)- if let Some(path) = env::var_os("CARGO_BIN_EXE_dev-detach") {- return PathBuf::from(path);- }-- // Fall back to target directory detection- let target_dir = env::current_exe()- .ok()- .map(|mut path| {- path.pop();- if path.ends_with("deps") || path.ends_with("examples") {- path.pop();- }- path- })- .expect("Could not determine target directory from current exe");-- let binary_name = format!("dev-detach{}", env::consts::EXE_SUFFIX);- let path = target_dir.join(&binary_name);-- if !path.is_file() {- panic!(- "\n\- ══════════════════════════════════════════════════════════════════════════════\n\- dev-detach binary not found at: {}\n\- \n\- The dev-detach binary is only built when running `cargo test` without\n\- package filters. Commands like these do NOT build it:\n\- \n\- cargo test -p worktrunk\n\- cargo test --test integration\n\- cargo test --lib --bins\n\- \n\- To fix, run one of these first:\n\- \n\- cargo build -p dev-detach # just build the binary\n\- cargo test # or run full workspace tests\n\- \n\- Then re-run your specific test command.\n\- ══════════════════════════════════════════════════════════════════════════════\n",- path.display()- );- }-- path-});--/// Convert signal number to human-readable name-#[cfg(unix)]-fn signal_name(sig: i32) -> &'static str {- match sig {- 1 => "SIGHUP",- 2 => "SIGINT",- 3 => "SIGQUIT",- 6 => "SIGABRT",- 9 => "SIGKILL",- 11 => "SIGSEGV",- 13 => "SIGPIPE",- 15 => "SIGTERM",- _ => "UNKNOWN",- }-}-/// Map shell display names to actual binaries.pub fn get_shell_binary(shell: &str) -> &str {match shell {@@ -133,97 +57,102 @@ pub fn get_shell_binary(shell: &str) -> &str {}}-/// Build a command to execute a shell script via dev-detach.-fn build_shell_command(repo: &TestRepo, shell: &str, script: &str) -> Command {- let mut cmd = Command::new(&*DEV_DETACH_BIN);- repo.clean_cli_env(&mut cmd);+/// Execute a script in the given shell with the repo's isolated environment.+///+/// Uses a PTY so that stdout appears as a terminal to the shell. This is required+/// for shell wrapper tests since the wrapper uses `[[ ! -t 1 ]]` to detect piping.+#[cfg(unix)]+pub fn execute_shell_script(repo: &TestRepo, shell: &str, script: &str) -> String {+ use portable_pty::CommandBuilder;+ use std::io::Read;++ let pair = super::open_pty();- // Prevent user shell config from leaking into tests- cmd.env_remove("BASH_ENV");- cmd.env_remove("ENV");- cmd.env_remove("ZDOTDIR");- cmd.env_remove("XONSHRC");- cmd.env_remove("XDG_CONFIG_HOME");+ let mut cmd = CommandBuilder::new(get_shell_binary(shell));- // Build argument list: <dev-detach-binary> <shell> [shell-flags...] -c <script>- cmd.arg(get_shell_binary(shell));+ // Clear inherited environment for test isolation+ cmd.env_clear();++ // Set minimal required environment for shells to function+ cmd.env("HOME", repo.home_path().to_string_lossy().to_string());+ cmd.env(+ "PATH",+ std::env::var("PATH").unwrap_or_else(|_| "/usr/bin:/bin".to_string()),+ );+ cmd.env("USER", "testuser");+ cmd.env("SHELL", get_shell_binary(shell));++ // Add repo's test environment (git config, worktrunk config, etc.)+ for (key, value) in repo.test_env_vars() {+ cmd.env(key, value);+ }// Add shell-specific no-config flagsmatch shell {- "bash" => cmd.arg("--noprofile").arg("--norc"),- "zsh" => cmd.arg("--no-globalrcs").arg("-f"),- "fish" => cmd.arg("--no-config"),- "powershell" | "pwsh" => cmd.arg("-NoProfile"),- "xonsh" => cmd.arg("--no-rc"),- "nushell" | "nu" => cmd.arg("--no-config-file"),- _ => &mut cmd,+ "bash" => {+ cmd.arg("--noprofile");+ cmd.arg("--norc");+ }+ "zsh" => {+ cmd.arg("--no-globalrcs");+ cmd.arg("-f");+ }+ "fish" => {+ cmd.arg("--no-config");+ }+ "powershell" | "pwsh" => {+ cmd.arg("-NoProfile");+ }+ "xonsh" => {+ cmd.arg("--no-rc");+ }+ "nushell" | "nu" => {+ cmd.arg("--no-config-file");+ }+ _ => {}};- cmd.arg("-c").arg(script);- cmd.stdin(std::process::Stdio::null());- cmd.stdout(std::process::Stdio::piped());- cmd.stderr(std::process::Stdio::piped());- cmd-}+ // PTY combines stdout/stderr at the terminal device level, so we don't need+ // explicit redirection. Redirecting would break the shell wrapper protocol:+ // wt_exec() captures stdout for directives, and stderr must stay separate.+ cmd.arg("-c");+ cmd.arg(script);+ cmd.cwd(repo.root_path());-/// Execute a script in the given shell with the repo's isolated environment.-pub fn execute_shell_script(repo: &TestRepo, shell: &str, script: &str) -> String {- let mut cmd = build_shell_command(repo, shell, script);+ // Pass through LLVM coverage env vars for subprocess coverage collection+ super::pass_coverage_env_to_pty_cmd(&mut cmd);- let output = cmd- .current_dir(repo.root_path())- .output()- .unwrap_or_else(|e| panic!("Failed to execute {} script: {}", shell, e));+ let mut child = pair.slave.spawn_command(cmd).unwrap();+ drop(pair.slave); // Close slave in parent- let stderr = String::from_utf8_lossy(&output.stderr);+ // Read everything the "terminal" would display+ let mut reader = pair.master.try_clone_reader().unwrap();+ let mut buf = String::new();+ reader.read_to_string(&mut buf).unwrap(); // Blocks until child exits & PTY closes- // Check for dev-detach-specific errors (setsid failures, execvp failures, etc.)- if stderr.contains("dev-detach:") {- panic!(- "dev-detach binary error:\nstderr: {}\nstdout: {}",- stderr,- String::from_utf8_lossy(&output.stdout)- );- }+ let status = child.wait().unwrap();- if !output.status.success() {- let exit_info = match output.status.code() {- Some(code) => format!("exit code {}", code),- None => {- #[cfg(unix)]- {- use std::os::unix::process::ExitStatusExt;- match output.status.signal() {- Some(sig) => format!("killed by signal {} ({})", sig, signal_name(sig)),- None => "killed by signal (unknown)".to_string(),- }- }- #[cfg(not(unix))]- {- "killed by signal".to_string()- }- }+ if !status.success() {+ let exit_info = match status.exit_code() {+ 0 => "unknown error".to_string(),+ code => format!("exit code {}", code),};panic!(- "Shell script failed ({}):\nCommand: dev-detach {} [shell-flags...] -c <script>\nstdout: {}\nstderr: {}",- exit_info,- shell,- String::from_utf8_lossy(&output.stdout),- stderr+ "Shell script failed ({}):\nshell: {}\noutput: {}",+ exit_info, shell, buf);}- // Check for shell errors in stderr (command not found, syntax errors, etc.)+ // Check for shell errors in output (command not found, syntax errors, etc.)// These indicate problems with our shell integration code- if stderr.contains("command not found") || stderr.contains("not defined") {+ if buf.contains("command not found") || buf.contains("not defined") {panic!(- "Shell integration error detected:\nstderr: {}\nstdout: {}",- stderr,- String::from_utf8_lossy(&output.stdout)+ "Shell integration error detected:\nshell: {}\noutput: {}",+ shell, buf);}- String::from_utf8(output.stdout).unwrap()+ buf}/// Generate `wt config shell init <shell>` output for the repo.diff --git a/tests/snapshots/integration__integration_tests__init__init_bash.snap b/tests/snapshots/integration__integration_tests__init__init_bash.snapindex 41d7495e9..0c47a2ac9 100644--- a/tests/snapshots/integration__integration_tests__init__init_bash.snap+++ b/tests/snapshots/integration__integration_tests__init__init_bash.snap@@ -16,10 +16,12 @@ info:GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"GIT_CONFIG_SYSTEM: /dev/nullGIT_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"HOME: "[TEST_HOME]"LANG: CLC_ALL: CPATH: "[PATH]"+ RUST_LOG: warnSOURCE_DATE_EPOCH: "1735776000"USERPROFILE: "[TEST_HOME]"WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"@@ -69,6 +71,10 @@ wt_exec() {# --source: use cargo run (builds from source)if [[ "$use_source" == true ]]; then+ if [[ ! -t 1 ]]; then+ cargo run --bin wt --quiet -- "${args[@]}"+ return+ filocal script exit_code=0script="$(cargo run --bin wt --quiet -- --internal "${args[@]}")" || exit_code=$?if [[ -n "$script" ]]; then@@ -80,6 +86,13 @@ wt_exec() {return "$exit_code"fi+ # If stdout is not a terminal (piped/redirected), run directly.+ # This allows `wt list --format=json | jq` to work.+ if [[ ! -t 1 ]]; then+ command "${WORKTRUNK_BIN:-wt}" "${args[@]}"+ return+ fi+wt_exec --internal "${args[@]}"}diff --git a/tests/snapshots/integration__integration_tests__init__init_fish.snap b/tests/snapshots/integration__integration_tests__init__init_fish.snapindex 0791ebe65..ba185dde0 100644--- a/tests/snapshots/integration__integration_tests__init__init_fish.snap+++ b/tests/snapshots/integration__integration_tests__init__init_fish.snap@@ -16,10 +16,12 @@ info:GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"GIT_CONFIG_SYSTEM: /dev/nullGIT_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"HOME: "[TEST_HOME]"LANG: CLC_ALL: CPATH: "[PATH]"+ RUST_LOG: warnSOURCE_DATE_EPOCH: "1735776000"USERPROFILE: "[TEST_HOME]"WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"@@ -68,6 +70,10 @@ if type -q wt; or test -n "$WORKTRUNK_BIN"# --source: use cargo run (builds from source)if test $use_source = true+ if not isatty stdout+ cargo run --bin wt --quiet -- $args+ return $status+ endcargo run --bin wt --quiet -- --internal $args | string collect --allow-empty | read --local -z scriptset -l exit_code $pipestatus[1]if test -n "$script"@@ -79,6 +85,14 @@ if type -q wt; or test -n "$WORKTRUNK_BIN"return $exit_codeend+ # If stdout is not a terminal (piped/redirected), run directly.+ # This allows `wt list --format=json | jq` to work.+ if not isatty stdout+ test -n "$WORKTRUNK_BIN"; or set -l WORKTRUNK_BIN (type -P wt)+ command $WORKTRUNK_BIN $args+ return $status+ end+wt_exec --internal $argsenddiff --git a/tests/snapshots/integration__integration_tests__init__init_zsh.snap b/tests/snapshots/integration__integration_tests__init__init_zsh.snapindex 8f63fb851..292e72bbb 100644--- a/tests/snapshots/integration__integration_tests__init__init_zsh.snap+++ b/tests/snapshots/integration__integration_tests__init__init_zsh.snap@@ -16,10 +16,12 @@ info:GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"GIT_CONFIG_SYSTEM: /dev/nullGIT_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"HOME: "[TEST_HOME]"LANG: CLC_ALL: CPATH: "[PATH]"+ RUST_LOG: warnSOURCE_DATE_EPOCH: "1735776000"USERPROFILE: "[TEST_HOME]"WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"@@ -72,6 +74,10 @@ wt_exec() {# --source: use cargo run (builds from source)if [[ "$use_source" == true ]]; then+ if [[ ! -t 1 ]]; then+ cargo run --bin wt --quiet -- "${args[@]}"+ return+ filocal script exit_code=0script="$(cargo run --bin wt --quiet -- --internal "${args[@]}")" || exit_code=$?if [[ -n "$script" ]]; then@@ -83,6 +89,13 @@ wt_exec() {return "$exit_code"fi+ # If stdout is not a terminal (piped/redirected), run directly.+ # This allows `wt list --format=json | jq` to work.+ if [[ ! -t 1 ]]; then+ command "${WORKTRUNK_BIN:-wt}" "${args[@]}"+ return+ fi+wt_exec --internal "${args[@]}"}