Skip to content

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

fix: improve shell integration warning for explicit path invocations (#382)

Maximilian Roos3af0d9861949
diff --git a/src/main.rs b/src/main.rs
index 760b65dfd..0a56085fd 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -60,6 +60,79 @@ fn binary_name() -> String {
.unwrap_or_else(|| "wt".to_string())
}
+/// Get the raw `argv[0]` value (how we were invoked).
+///
+/// Used in error messages to show what command was actually run.
+/// Returns the full invocation path (e.g., `target/debug/wt`, `./wt`, `wt`).
+pub fn invocation_path() -> String {
+ std::env::args().next().unwrap_or_else(|| "wt".to_string())
+}
+
+/// Check if we were invoked via an explicit path rather than PATH lookup.
+///
+/// # Purpose
+///
+/// When shell integration is configured (e.g., `eval "$(wt config shell init)"`),
+/// the shell wrapper function intercepts calls to `wt` and handles directory
+/// changes. However, this only works when the shell finds `wt` via PATH lookup.
+///
+/// If the user runs a specific binary path (like `cargo run` or `./target/debug/wt`),
+/// the shell wrapper won't intercept it, and shell integration won't work.
+///
+/// # Heuristic
+///
+/// Returns `true` if argv\[0\] contains a path separator (`/` or `\`).
+///
+/// - PATH lookup: shell sets argv\[0\] to just the command name (`wt`)
+/// - Explicit path: argv\[0\] contains the path (`./wt`, `target/debug/wt`, `/usr/bin/wt`)
+///
+/// # Examples
+///
+/// | Invocation | argv\[0\] | Returns | Reason |
+/// |-----------------------------|----------------------|---------|---------------------------|
+/// | `wt switch foo` | `wt` | `false` | PATH lookup, wrapper works|
+/// | `cargo run -- switch foo` | `target/debug/wt` | `true` | Explicit path, no wrapper |
+/// | `./target/debug/wt switch` | `./target/debug/wt` | `true` | Explicit path, no wrapper |
+/// | `/usr/local/bin/wt switch` | `/usr/local/bin/wt` | `true` | Explicit path, no wrapper |
+///
+/// # Edge Cases
+///
+/// - **False positive**: User types full path to installed binary (`/usr/local/bin/wt`).
+/// Harmless — if they're typing the full path, shell wrapper wouldn't intercept anyway.
+///
+/// - **Aliases**: `alias wt='...'` — shell expands alias before setting argv\[0\], so:
+/// - `alias wt='wt'` → argv\[0\] = `wt` → `false` (correct)
+/// - `alias wt='./target/debug/wt'` → argv\[0\] = `./target/debug/wt` → `true` (correct)
+///
+/// - **Symlinks**: If `~/bin/wt` is a symlink to `target/debug/wt`, argv\[0\] = `~/bin/wt`
+/// (contains `/`) → `true`. This is correct — the shell wrapper wraps PATH's `wt`,
+/// not the symlink.
+///
+/// - **`git wt` subcommand**: When invoked as `git wt`, git dispatches to `git-wt` binary
+/// and sets argv\[0\] = `git-wt` (no path separator) → returns `false`. However, shell
+/// integration configured for `wt` won't intercept `git wt` — they're different commands.
+/// This is handled separately by `is_integration_configured()` which checks for the
+/// actual binary name (`git-wt`), not `wt`.
+///
+/// # Why Not Other Approaches?
+///
+/// - **`current_exe()` + check for `/target/debug/`**: Only catches cargo builds,
+/// misses other "ran specific path" scenarios.
+///
+/// - **Compare with `which wt`**: More accurate but requires subprocess overhead
+/// and `which` behavior varies across shells.
+///
+/// - **Check if `current_exe()` is in PATH**: Complex PATH parsing, platform differences.
+///
+/// The argv\[0\] heuristic is simple, fast, and catches all cases where shell
+/// integration won't work because the shell wrapper wasn't invoked.
+pub fn was_invoked_with_explicit_path() -> bool {
+ std::env::args()
+ .next()
+ .map(|arg0| arg0.contains('/') || arg0.contains('\\'))
+ .unwrap_or(false)
+}
+
/// Custom help handling for pager support and markdown rendering.
///
/// We intercept help requests to provide:
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index a99254065..ec776bb44 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -523,7 +523,12 @@ pub fn prompt_shell_integration(
.any(|r| matches!(r.action, ConfigAction::AlreadyExists));
if current_shell_installed {
- super::print(hint_message("Restart shell to activate shell integration"))?;
+ // Shell integration is configured but not active for this invocation
+ if !crate::was_invoked_with_explicit_path() {
+ // Invoked via PATH but wrapper isn't active - needs shell restart
+ super::print(hint_message("Restart shell to activate shell integration"))?;
+ }
+ // For explicit paths: no hint needed - handle_switch_output() warning already explains
return Ok(false);
}
@@ -619,16 +624,25 @@ pub fn handle_switch_output(
let is_shell_integration_active = super::is_shell_integration_active();
// Compute shell warning reason once (only if we'll need it)
- let shell_warning_reason = if is_shell_integration_active {
+ let shell_warning_reason: Option<String> = if is_shell_integration_active {
None
} else if Shell::is_integration_configured(&crate::binary_name())
.ok()
.flatten()
.is_some()
{
- Some("shell requires restart")
+ if crate::was_invoked_with_explicit_path() {
+ // Invoked with explicit path - shell wrapper won't intercept this binary
+ let invoked = crate::invocation_path();
+ let wraps = crate::binary_name();
+ Some(cformat!(
+ "ran <bold>{invoked}</>; shell integration wraps <bold>{wraps}</>"
+ ))
+ } else {
+ Some("shell requires restart".to_string())
+ }
} else {
- Some("shell integration not installed")
+ Some("shell integration not installed".to_string())
};
// Show path mismatch warning after the main message
@@ -652,7 +666,7 @@ pub fn handle_switch_output(
None
}
SwitchResult::Existing(_) => {
- if let Some(reason) = shell_warning_reason {
+ if let Some(reason) = &shell_warning_reason {
// Shell integration not active — warn that shell won't cd
if let Some(cmd) = execute_command {
// --execute: command will run in target dir, but shell stays put
diff --git a/tests/common/mod.rs b/tests/common/mod.rs
index 29d162d11..dbe729dac 100644
--- a/tests/common/mod.rs
+++ b/tests/common/mod.rs
@@ -1944,6 +1944,8 @@ pub fn setup_snapshot_settings(repo: &TestRepo) -> insta::Settings {
if let Some(root) = project_root {
settings.add_filter(&regex::escape(root.to_str().unwrap()), "[PROJECT_ROOT]");
}
+ // Normalize llvm-cov-target to target for coverage builds (cargo-llvm-cov)
+ settings.add_filter(r"/target/llvm-cov-target/", "/target/");
// Normalize backslashes FIRST so all subsequent path filters only need forward-slash versions.
// This must come before any path replacement filters.
diff --git a/tests/integration_tests/approval_pty.rs b/tests/integration_tests/approval_pty.rs
index 7885c089d..430bb2743 100644
--- a/tests/integration_tests/approval_pty.rs
+++ b/tests/integration_tests/approval_pty.rs
@@ -102,6 +102,13 @@ fn normalize_output(output: &str) -> String {
.unwrap()
.replace_all(&output, "[CONFIG]");
+ // Normalize binary path in shell integration hint (e.g., /path/to/target/debug/wt -> [BIN])
+ // Also handles llvm-cov-target used by cargo-llvm-cov in coverage builds
+ // The path may contain ANSI codes (bold), so match any non-whitespace before /target
+ let output = regex::Regex::new(r"[^\s]+/target/(llvm-cov-target/)?debug/wt")
+ .unwrap()
+ .replace_all(&output, "[BIN]");
+
// Normalize blank lines due to PTY timing variations
// Different environments (local, CI, Claude Code web) may have blank lines
// in different positions due to timing-dependent buffering.
diff --git a/tests/integration_tests/shell_integration_prompt.rs b/tests/integration_tests/shell_integration_prompt.rs
index 187536a8f..b75a32060 100644
--- a/tests/integration_tests/shell_integration_prompt.rs
+++ b/tests/integration_tests/shell_integration_prompt.rs
@@ -290,13 +290,17 @@ mod pty_tests {
output.replace("\r\n", "\n")
}
- /// Test: Already installed (config line exists) → skip prompt, show restart hint
+ /// Test: Already installed (config line exists) → skip prompt
///
/// This covers the "installed but shell not restarted" scenario where:
/// - Shell integration is not active (no WORKTRUNK_DIRECTIVE_FILE)
/// - But the config line is already in shell config files
- /// - We should detect this and show a restart hint (not prompt)
+ /// - We should detect this and skip the prompt (not show interactive prompt)
/// - We should NOT mark as prompted (no interactive prompt shown)
+ ///
+ /// Note: Since tests run via `cargo test`, argv[0] contains a path (`target/debug/wt`),
+ /// so the "restart shell" hint is suppressed. Shell integration won't intercept explicit
+ /// paths, so restarting wouldn't help. In production (PATH lookup), users see a restart hint.
#[rstest]
fn test_already_installed_skips_prompt(repo: TestRepo) {
// Create isolated HOME with shell config that already has integration
@@ -328,12 +332,6 @@ mod pty_tests {
"Should not prompt when already installed: {output}"
);
- // Should show restart hint
- assert!(
- output.contains("Restart") && output.contains("shell"),
- "Should show restart hint: {output}"
- );
-
// Should have created the worktree
assert!(
output.contains("Created new worktree for"),
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_accept.snap b/tests/integration_tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_accept.snap
index 58859b2cc..75245d9eb 100644
--- a/tests/integration_tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_accept.snap
+++ b/tests/integration_tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_accept.snap
@@ -13,5 +13,4 @@ y
  echo 'test command'
test command
✓ Created new worktree for test-approve from main @ _REPO_/repo.BRANCH
-▲ Cannot change directory — shell requires restart
-↳ Restart shell to activate shell integration
+▲ Cannot change directory — ran [BIN]; shell integration wraps wt
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_decline.snap b/tests/integration_tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_decline.snap
index 0bf72e267..09efbf9ef 100644
--- a/tests/integration_tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_decline.snap
+++ b/tests/integration_tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_decline.snap
@@ -11,5 +11,4 @@ n
❯ Allow and remember? [y/N]
○ Commands declined, continuing worktree creation
✓ Created new worktree for test-decline from main @ _REPO_/repo.BRANCH
-▲ Cannot change directory — shell requires restart
-↳ Restart shell to activate shell integration
+▲ Cannot change directory — ran [BIN]; shell integration wraps wt
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_mixed_approved_unapproved_accept.snap b/tests/integration_tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_mixed_approved_unapproved_accept.snap
index 4ed142980..93c016800 100644
--- a/tests/integration_tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_mixed_approved_unapproved_accept.snap
+++ b/tests/integration_tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_mixed_approved_unapproved_accept.snap
@@ -21,5 +21,4 @@ y
  echo 'Third command'
Third command
✓ Created new worktree for test-mixed-accept from main @ _REPO_/repo.BRANCH
-▲ Cannot change directory — shell requires restart
-↳ Restart shell to activate shell integration
+▲ Cannot change directory — ran [BIN]; shell integration wraps wt
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_mixed_approved_unapproved_decline.snap b/tests/integration_tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_mixed_approved_unapproved_decline.snap
index d381bc478..001875ca2 100644
--- a/tests/integration_tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_mixed_approved_unapproved_decline.snap
+++ b/tests/integration_tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_mixed_approved_unapproved_decline.snap
@@ -13,5 +13,4 @@ n
❯ Allow and remember? [y/N]
○ Commands declined, continuing worktree creation
✓ Created new worktree for test-mixed-decline from main @ _REPO_/repo.BRANCH
-▲ Cannot change directory — shell requires restart
-↳ Restart shell to activate shell integration
+▲ Cannot change directory — ran [BIN]; shell integration wraps wt
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_multiple_commands.snap b/tests/integration_tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_multiple_commands.snap
index 8a782fc98..1359ea040 100644
--- a/tests/integration_tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_multiple_commands.snap
+++ b/tests/integration_tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_multiple_commands.snap
@@ -23,5 +23,4 @@ y
  echo 'Third command'
Third command
✓ Created new worktree for test-multi from main @ _REPO_/repo.BRANCH
-▲ Cannot change directory — shell requires restart
-↳ Restart shell to activate shell integration
+▲ Cannot change directory — ran [BIN]; shell integration wraps wt
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_named_commands.snap b/tests/integration_tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_named_commands.snap
index 5d73162cd..681b91c55 100644
--- a/tests/integration_tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_named_commands.snap
+++ b/tests/integration_tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_named_commands.snap
@@ -23,5 +23,4 @@ y
  echo 'Running tests...'
Running tests...
✓ Created new worktree for test-named from main @ _REPO_/repo.BRANCH
-▲ Cannot change directory — shell requires restart
-↳ Restart shell to activate shell integration
+▲ Cannot change directory — ran [BIN]; shell integration wraps wt
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_permission_error.snap b/tests/integration_tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_permission_error.snap
index 3f5085c18..adc19d237 100644
--- a/tests/integration_tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_permission_error.snap
+++ b/tests/integration_tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_permission_error.snap
@@ -15,5 +15,4 @@ y
  echo 'test command'
test command
✓ Created new worktree for test-permission from main @ _REPO_/repo.BRANCH
-▲ Cannot change directory — shell requires restart
-↳ Restart shell to activate shell integration
+▲ Cannot change directory — ran [BIN]; shell integration wraps wt
diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rs
index c9778ab82..8a888f6e4 100644
--- a/tests/integration_tests/switch.rs
+++ b/tests/integration_tests/switch.rs
@@ -104,6 +104,10 @@ fn test_switch_existing_branch(mut repo: TestRepo) {
/// runs `wt` binary directly (not through the shell wrapper), show a warning that explains
/// the actual situation: shell IS configured, but cd can't happen because we're not
/// running through the shell function.
+///
+/// Since tests run via `cargo test`, argv[0] contains a path (`target/debug/wt`), which
+/// triggers the "explicit path" code path. The warning explains that shell integration
+/// won't intercept explicit paths.
#[rstest]
fn test_switch_existing_with_shell_integration_configured(mut repo: TestRepo) {
use std::fs;
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_existing_with_shell_configured.snap b/tests/snapshots/integration__integration_tests__switch__switch_existing_with_shell_configured.snap
index 6b562fda2..4eb609cb8 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_existing_with_shell_configured.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_existing_with_shell_configured.snap
@@ -32,5 +32,4 @@ exit_code: 0
----- stdout -----
----- stderr -----
-▲ Worktree for shell-configured @ _REPO_.shell-configured, but cannot change directory — shell requires restart
-↳ Restart shell to activate shell integration
+▲ Worktree for shell-configured @ _REPO_.shell-configured, but cannot change directory — ran [PROJECT_ROOT]/target/debug/wt; shell integration wraps wt