Skip to content

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

fix(switch): name the directory the --execute program runs in in its header (#4043)

Worktrunk Botd41ba2b1e543
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b9a0abba9..8446a33fb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,8 @@
### Fixed
+- **`wt switch --execute` now names the directory the program actually starts in**: the `Executing (--execute) @ …` header rendered the worktree the background hooks run in, which the program need not enter — `--no-cd` starts it in the invoking directory, and a switch from a subdirectory keeps that position, so the header pointed one level out. It now names the program's own directory, and omits the path when that is where the user's shell already stands. ([#4042](https://github.com/max-sixty/worktrunk/issues/4042), thanks @yajo for reporting)
+
- **Codex on Windows: the activity hooks no longer fail on every event**: each hook led with a bare `bash`, which `cmd.exe` resolves to the WSL launcher rather than Git Bash; in a sandboxed session it refuses to start, so every event raised a `Hook failed` banner. Each hook now carries a Windows-only command that runs the same `wt.sh` through a `cmd.exe` shim, which finds Git Bash by path rather than by name. ([#4008](https://github.com/max-sixty/worktrunk/pull/4008), fixes [#4007](https://github.com/max-sixty/worktrunk/issues/4007), thanks @McNultyyy for reporting and diagnosing)
## 0.76.0
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rs
index f3812de18..e37aa0194 100644
--- a/src/commands/worktree/switch.rs
+++ b/src/commands/worktree/switch.rs
@@ -1849,7 +1849,7 @@ impl SwitchPipeline<'_> {
let fallback_path = repo.repo_path()?.to_path_buf();
let cwd = shell_cwd().unwrap_or(fallback_path.clone());
let source_root = repo.current_worktree().root().unwrap_or(fallback_path);
- let hooks_display_path =
+ let display_paths =
handle_switch_output(&result, &branch_info, change_dir, Some(&source_root), &cwd)?;
// Offer shell integration if not already installed/active (only shows
@@ -1892,7 +1892,7 @@ impl SwitchPipeline<'_> {
branch_info.branch.as_deref(),
yes,
&extra_vars,
- hooks_display_path.as_deref(),
+ display_paths.hooks.as_deref(),
&hook_plan,
)?;
}
@@ -1939,7 +1939,10 @@ impl SwitchPipeline<'_> {
})
.collect();
let argv: Vec<String> = std::iter::once(program).chain(args?).collect();
- execute_user_command(&argv, hooks_display_path.as_deref())?;
+ // The header names where the program starts, which is the
+ // directory the switch cd'd to and not the worktree the hooks
+ // announce (#4042).
+ execute_user_command(&argv, display_paths.execute.as_deref())?;
}
Ok(())
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 8ac919083..e6925029a 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -1018,6 +1018,23 @@ pub(crate) fn resolve_subdir_in_target(
target_root.to_path_buf()
}
+/// The "@ path" annotations a switch's follow-on output should carry.
+///
+/// Both are `Some` only when the user's shell won't be where the annotated work
+/// runs; the two paths differ because the work doesn't share one directory.
+/// Background hooks always run at the worktree root, while the `--execute`
+/// program runs wherever the switch cd'd — the root, or the subdirectory
+/// position [`resolve_subdir_in_target`] preserved — and nowhere at all under
+/// `--no-cd`, which leaves it in the invoking directory (#4042).
+pub struct SwitchDisplayPaths {
+ /// Where the background `post-switch` / `post-start` hooks run, when that
+ /// isn't where the user's shell is (or will be).
+ pub hooks: Option<PathBuf>,
+ /// Where the `--execute` program starts, when that isn't where the user's
+ /// shell is (or will be).
+ pub execute: Option<PathBuf>,
+}
+
/// Handle output for a switch operation
///
/// # Shell Integration Warnings
@@ -1045,27 +1062,25 @@ pub(crate) fn resolve_subdir_in_target(
///
/// # Return Value
///
-/// Returns `Some(path)` when post-switch hooks should show "@ path" in their
-/// announcements (because the user's shell won't be in that directory). This happens when:
-/// - Shell integration is not active (user's shell stays in original directory)
-/// - `change_dir` is false (user explicitly requested no directory change)
-///
-/// Returns `None` when the user will be in the worktree directory (shell integration
-/// active or already at the worktree), so no path annotation needed.
+/// See [`SwitchDisplayPaths`] — the two annotations differ, because the hooks
+/// and the `--execute` program don't always run in the same directory.
pub fn handle_switch_output(
result: &SwitchResult,
branch_info: &SwitchBranchInfo,
change_dir: bool,
source_worktree_root: Option<&Path>,
cwd: &Path,
-) -> anyhow::Result<Option<std::path::PathBuf>> {
+) -> anyhow::Result<SwitchDisplayPaths> {
// Set target directory for command execution, preserving subdirectory position.
// If the user is in apps/gateway/ in the source worktree and that directory exists
// in the target, cd to apps/gateway/ in the target instead of the root.
- if change_dir {
+ let cd_target = if change_dir {
let cd_target = resolve_subdir_in_target(result.path(), source_worktree_root, cwd);
super::change_directory(&cd_target)?;
- }
+ Some(cd_target)
+ } else {
+ None
+ };
// Translate to the user's logical (symlink-preserved) path for display messages.
// The cd directive (above) handles its own translation internally.
@@ -1087,15 +1102,30 @@ pub fn handle_switch_output(
),
};
+ // The `--execute` program runs in `cd_target`, which is the worktree root
+ // only when the user was at the source worktree's root: otherwise
+ // `resolve_subdir_in_target` kept their subdirectory position, and the
+ // hooks' path names a directory one level out from the program's. Annotate
+ // it only when the user's shell won't be there — `--no-cd` leaves the
+ // program where the shell already stands, and shell integration takes the
+ // shell to `cd_target` too (#4042).
+ let display_path_for_execute = cd_target.filter(|target| {
+ !super::is_shell_integration_active()
+ && super::global::compute_hooks_display_path(target, cwd).is_some()
+ });
+
stderr().flush()?;
- Ok(display_path_for_hooks)
+ Ok(SwitchDisplayPaths {
+ hooks: display_path_for_hooks,
+ execute: display_path_for_execute.map(|target| super::to_logical_path(&target)),
+ })
}
/// Execute the --execute command after hooks have run.
///
-/// `display_path` is shown when the user's shell won't be in the worktree
-/// directory (shell integration not active). This helps users understand where
-/// the command runs.
+/// `display_path` names the directory the program starts in
+/// ([`SwitchDisplayPaths::execute`]), and is `Some` only when the user's shell
+/// won't be there — otherwise the header has nothing to annotate.
///
pub fn execute_user_command(argv: &[String], display_path: Option<&Path>) -> anyhow::Result<()> {
super::global::print_outdated_execute_wrapper_warning();
diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rs
index 633905b9e..06376d648 100644
--- a/tests/integration_tests/switch.rs
+++ b/tests/integration_tests/switch.rs
@@ -939,6 +939,85 @@ fn test_switch_execute_does_not_inherit_git_discovery_vars(mut repo: TestRepo) {
);
}
+/// `--no-cd` starts the `--execute` program in the invoking directory, so the
+/// "Executing (--execute) @ …" header must not name the new worktree. The path
+/// it renders is the one the background hooks run in; the program never enters
+/// it, and naming it there sent a reporter looking for a broken template
+/// variable instead of the directory the flag moved (issue #4042).
+#[rstest]
+fn test_switch_no_cd_execute_header_omits_worktree_path(mut repo: TestRepo) {
+ repo.add_worktree("feature");
+
+ let output = repo
+ .wt_command()
+ .args(["switch", "feature", "--no-cd", "--execute", "pwd"])
+ .current_dir(repo.root_path())
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "switch --no-cd --execute failed:\nstdout: {}\nstderr: {}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ let header = stderr
+ .lines()
+ .find(|line| line.contains("Executing (--execute)"))
+ .unwrap_or_else(|| panic!("no --execute header in stderr:\n{stderr}"));
+ assert!(
+ !header.contains('@'),
+ "--no-cd runs the program in the invoking directory, but the header named a path: {header}"
+ );
+}
+
+/// A switch from a subdirectory keeps the user's position, so the `--execute`
+/// program starts in `<worktree>/<subdir>` — not at the worktree root the
+/// background hooks run in. The header names the program's own directory
+/// (issue #4042), which is the same claim `--no-cd` breaks one tree over.
+#[rstest]
+fn test_switch_execute_header_names_preserved_subdirectory(mut repo: TestRepo) {
+ // The subdirectory has to exist in both worktrees for the position to
+ // carry over, so commit it before branching.
+ let subdir = repo.root_path().join("apps").join("gateway");
+ fs::create_dir_all(&subdir).unwrap();
+ fs::write(subdir.join("main.rs"), "fn main() {}\n").unwrap();
+ repo.run_git(&["add", "."]);
+ repo.commit("Add apps/gateway");
+ let worktree = repo.add_worktree("feature");
+ assert!(worktree.join("apps").join("gateway").is_dir());
+
+ let output = repo
+ .wt_command()
+ .args(["switch", "feature", "--execute", "pwd"])
+ .current_dir(&subdir)
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "switch --execute from a subdirectory failed:\nstdout: {}\nstderr: {}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ let stdout = String::from_utf8_lossy(&output.stdout).replace('\\', "/");
+ assert!(
+ stdout.trim_end().ends_with("apps/gateway"),
+ "the program should have started in the target's subdirectory: {stdout}"
+ );
+
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ let header = stderr
+ .lines()
+ .find(|line| line.contains("Executing (--execute)"))
+ .unwrap_or_else(|| panic!("no --execute header in stderr:\n{stderr}"));
+ assert!(
+ header.contains("apps/gateway"),
+ "the header named the worktree root, not the directory the program ran in: {header}"
+ );
+}
+
/// `--execute` computes only the template variables its command names.
///
/// The context map built at that call site feeds `expand_template` and nothing
diff --git a/tests/snapshots/integration__integration_tests__directives__switch_no_cd_execute_does_not_emit_cd.snap b/tests/snapshots/integration__integration_tests__directives__switch_no_cd_execute_does_not_emit_cd.snap
index c2d3f4350..6364e11b5 100644
--- a/tests/snapshots/integration__integration_tests__directives__switch_no_cd_execute_does_not_emit_cd.snap
+++ b/tests/snapshots/integration__integration_tests__directives__switch_no_cd_execute_does_not_emit_cd.snap
@@ -67,6 +67,6 @@ _REPO_
----- stderr -----
✓ Created branch exec-test from main and worktree @ _REPO_.exec-test
↳ To customize worktree locations, run wt config create
-◎ Executing (--execute) @ _REPO_.exec-test:
+◎ Executing (--execute):
  pwd