Skip to content

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

feat(switch): run --execute against the picked worktree (#3394)

Worktrunk Botbd504f09982f
diff --git a/docs/content/switch.md b/docs/content/switch.md
index 96d40089e..e1deedd5f 100644
--- a/docs/content/switch.md
+++ b/docs/content/switch.md
@@ -176,6 +176,10 @@ Usage: <b><span class=c>wt switch</span></b> <span class=c>[OPTIONS]</span> <spa
Replaces the wt process with the command after switching, giving it full terminal control.
Useful for launching editors, AI agents, or other interactive tools.
+ Without a branch argument, the interactive picker opens and the command runs against the
+ selected worktree — so <b>wt switch -x claude</b> picks a worktree, then launches Claude Code
+ there.
+
Supports <u>hook template variables</u> (<b>{{ branch }}</b>, <b>{{ worktree_path }}</b>, etc.) and filters. <b>{{</b>
<b> base }}</b> and <b>{{ base_worktree_path }}</b> require <b>--create</b>.
diff --git a/skills/worktrunk/reference/switch.md b/skills/worktrunk/reference/switch.md
index 52c84c80e..c9520a63b 100644
--- a/skills/worktrunk/reference/switch.md
+++ b/skills/worktrunk/reference/switch.md
@@ -172,6 +172,10 @@ Options:
Replaces the wt process with the command after switching, giving it full terminal control.
Useful for launching editors, AI agents, or other interactive tools.
+ Without a branch argument, the interactive picker opens and the command runs against the
+ selected worktree — so wt switch -x claude picks a worktree, then launches Claude Code
+ there.
+
Supports hook template variables ({{ branch }}, {{ worktree_path }}, etc.) and filters. {{
base }} and {{ base_worktree_path }} require --create.
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index 038c35fa6..36dce2a10 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -350,15 +350,15 @@ pub(crate) struct SwitchArgs {
pub(crate) branch: Option<String>,
/// Include branches without worktrees
- #[arg(long, help_heading = "Picker Options", conflicts_with_all = ["create", "base", "execute", "execute_args", "clobber"])]
+ #[arg(long, help_heading = "Picker Options", conflicts_with_all = ["create", "base", "clobber"])]
pub(crate) branches: bool,
/// Include remote branches
- #[arg(long, help_heading = "Picker Options", conflicts_with_all = ["create", "base", "execute", "execute_args", "clobber"])]
+ #[arg(long, help_heading = "Picker Options", conflicts_with_all = ["create", "base", "clobber"])]
pub(crate) remotes: bool,
/// Include open PRs/MRs
- #[arg(long, help_heading = "Picker Options", conflicts_with_all = ["create", "base", "execute", "execute_args", "clobber"])]
+ #[arg(long, help_heading = "Picker Options", conflicts_with_all = ["create", "base", "clobber"])]
pub(crate) prs: bool,
/// Create a new branch
@@ -378,6 +378,10 @@ pub(crate) struct SwitchArgs {
/// it full terminal control. Useful for launching editors, AI agents,
/// or other interactive tools.
///
+ /// Without a branch argument, the interactive picker opens and the
+ /// command runs against the selected worktree — so `wt switch -x claude`
+ /// picks a worktree, then launches Claude Code there.
+ ///
/// Supports [hook template variables](@/hook.md#template-variables)
/// (`{{ branch }}`, `{{ worktree_path }}`, etc.) and filters.
/// `{{ base }}` and `{{ base_worktree_path }}` require `--create`.
@@ -397,7 +401,7 @@ pub(crate) struct SwitchArgs {
/// Template example: `-x code -- '{{ worktree_path }}'` opens VS Code
/// at the worktree, `-x tmux -- new -s '{{ branch | sanitize }}'` starts
/// a tmux session named after the branch.
- #[arg(short = 'x', long, requires = "branch")]
+ #[arg(short = 'x', long)]
pub(crate) execute: Option<String>,
/// Additional arguments for --execute command (after --)
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rs
index 8e2c4ba34..92d6423f1 100644
--- a/src/commands/picker/mod.rs
+++ b/src/commands/picker/mod.rs
@@ -1593,6 +1593,8 @@ pub fn handle_picker(
cli_prs: bool,
change_dir_flag: Option<bool>,
format: SwitchFormat,
+ execute: Option<&str>,
+ execute_args: &[String],
) -> anyhow::Result<()> {
// Interactive picker requires a terminal for the TUI. The dry-run and
// preview-bench paths bypass skim entirely, so no TTY is required —
@@ -2162,10 +2164,12 @@ summary = true
// Run the switch — the same `SwitchPipeline` as `wt switch <branch>`,
// so hooks, approval, and output cannot drift from the argument path.
- // The picker has no `--execute`, offers no shell integration, and does
- // not capture pre-switch source identity (`capture_source: false` — an
- // existing switch's `{{ base }}` / `{{ base_worktree_path }}` stay
- // unset; result-derived `base` for creates and `target` still flow).
+ // The picker offers no shell integration, but (like the argument path)
+ // the pipeline captures the pre-switch source worktree, so an existing
+ // switch's `{{ base }}` / `{{ base_worktree_path }}` resolve to the
+ // worktree the user came from. An `--execute` command (`wt switch -x
+ // <cmd>`) runs against the picked worktree, and its `{{ base }}` matches
+ // what `wt switch <branch> -x <cmd>` would produce.
SwitchPipeline {
repo: &repo,
config: &mut config,
@@ -2179,9 +2183,8 @@ summary = true
format,
is_recovered,
suggestion_ctx: None,
- capture_source: false,
- execute: None,
- execute_args: &[],
+ execute,
+ execute_args,
shell_integration_binary: None,
}
.run()?;
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rs
index 46a15d602..6ad2ecff3 100644
--- a/src/commands/worktree/switch.rs
+++ b/src/commands/worktree/switch.rs
@@ -1525,9 +1525,13 @@ fn capture_switch_source(repo: &Repository, is_recovered: bool) -> (String, Stri
/// its own copy of that call.
///
/// The picker-vs-argument differences are field values, not separate code: the
-/// picker passes `verify: true`, `yes: false`, `capture_source: false`,
-/// `suggestion_ctx: None`, `execute: None`, and `shell_integration_binary:
-/// None`.
+/// picker passes `verify: true`, `yes: false`, `suggestion_ctx: None`, and
+/// `shell_integration_binary: None`. It threads `execute` / `execute_args`
+/// through from `wt switch -x <cmd>` (no branch), and — like the argument path
+/// — captures the pre-switch source worktree, so a picked worktree runs the
+/// command and resolves its `{{ base }}` exactly as the argument path does.
+/// Source capture is no longer a divergence axis: both entry points always
+/// capture, with `is_recovered` the only thing that suppresses it.
pub(crate) struct SwitchPipeline<'a> {
pub repo: &'a Repository,
/// Mutable because the bare-repo path-fix offer
@@ -1548,18 +1552,15 @@ pub(crate) struct SwitchPipeline<'a> {
pub format: SwitchFormat,
/// True when `current_or_recover` recovered from a deleted CWD. Suppresses
/// pre-switch hooks (no source worktree to run them against) and source
- /// capture.
+ /// capture (`{{ base }}` / `{{ base_worktree_path }}` stay unset — there is
+ /// no live source worktree to read).
pub is_recovered: bool,
/// Error-enrichment context for a failed `plan_switch`, so the hint
- /// suggests the full `wt switch … --execute=… -- …`. `None` for the
- /// picker, which has no `--execute`.
+ /// suggests the full `wt switch … --execute=… -- …`. `None` for the picker,
+ /// which has no branch argument to embed in that suggested command.
pub suggestion_ctx: Option<SwitchSuggestionCtx>,
- /// Whether to capture the source worktree's branch/root before the switch,
- /// for post-switch `{{ base }}` / `{{ base_worktree_path }}`. The argument
- /// path captures; the picker does not — it does not track where the user
- /// came from, so an existing switch's base vars stay unset.
- pub capture_source: bool,
- /// `--execute` command and its trailing args. `None` / empty for the picker.
+ /// `--execute` command and its trailing args. Flows from `wt switch -x
+ /// <cmd>` on both the argument path and the picker (no branch given).
pub execute: Option<&'a str>,
pub execute_args: &'a [String],
/// Binary name for the shell-integration offer. `Some` only on the argument
@@ -1584,7 +1585,6 @@ impl SwitchPipeline<'_> {
format,
is_recovered,
suggestion_ctx,
- capture_source,
execute,
execute_args,
shell_integration_binary,
@@ -1605,14 +1605,10 @@ impl SwitchPipeline<'_> {
// Capture source (base) worktree identity BEFORE the switch, for
// post-switch {{ base }} / {{ base_worktree_path }}. Done here — after
- // pre-switch hooks, before plan / approve / validate, none of which
- // move the current worktree. The picker passes `capture_source: false`;
- // it does not track where the user came from.
- let (source_branch, source_path) = if capture_source {
- capture_switch_source(repo, is_recovered)
- } else {
- (String::new(), String::new())
- };
+ // pre-switch hooks, before plan / approve / validate, none of which move
+ // the current worktree. Both entry points capture; `capture_switch_source`
+ // returns empty on the recovered path (no live source worktree).
+ let (source_branch, source_path) = capture_switch_source(repo, is_recovered);
// Validate and resolve the target branch.
let plan = plan_switch(repo, identifier, create, base, clobber, config).map_err(|err| {
@@ -1839,7 +1835,6 @@ fn run_switch(
format,
is_recovered,
suggestion_ctx,
- capture_source: true,
execute,
execute_args,
shell_integration_binary: Some(binary_name),
@@ -1865,13 +1860,16 @@ pub fn handle_switch_command(args: SwitchArgs, yes: bool) -> anyhow::Result<()>
let change_dir_flag = flag_pair(args.cd, args.no_cd);
let Some(branch) = args.branch else {
- // No branch argument: open the interactive picker.
+ // No branch argument: open the interactive picker. `--execute`
+ // (and its trailing args) run against the picked worktree.
return crate::commands::handle_picker(
args.branches,
args.remotes,
args.prs,
change_dir_flag,
args.format,
+ args.execute.as_deref(),
+ &args.execute_args,
);
};
diff --git a/src/main.rs b/src/main.rs
index 906cc7741..26f4a7397 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -686,7 +686,15 @@ fn handle_select_command(branches: bool, remotes: bool) -> anyhow::Result<()> {
// Deprecated: show warning and delegate to handle_picker
warn_select_deprecated();
worktrunk::config::suppress_warnings();
- handle_picker(branches, remotes, false, None, SwitchFormat::Text)
+ handle_picker(
+ branches,
+ remotes,
+ false,
+ None,
+ SwitchFormat::Text,
+ None,
+ &[],
+ )
}
/// Rayon thread count sized for mixed git+network I/O workloads.
diff --git a/tests/integration_tests/switch_picker.rs b/tests/integration_tests/switch_picker.rs
index 9c1272759..d7aa250a6 100644
--- a/tests/integration_tests/switch_picker.rs
+++ b/tests/integration_tests/switch_picker.rs
@@ -2523,6 +2523,109 @@ fn test_switch_picker_no_cd_switches_without_cd_directive(mut repo: TestRepo) {
);
}
+/// `wt switch -x <cmd>` with no branch argument opens the picker and runs the
+/// command against the selected worktree — the composition requested in #3370.
+/// Before the fix, `--execute`'s `requires = "branch"` rejected this at parse
+/// time. The EXEC directive file is the observable proof: `--execute` writes
+/// the expanded command there for the shell wrapper to source, so its presence
+/// confirms the picker threaded `execute` into the shared `SwitchPipeline`.
+#[rstest]
+fn test_switch_picker_runs_execute_command(mut repo: TestRepo) {
+ repo.remove_fixture_worktrees();
+ repo.run_git(&["remote", "remove", "origin"]);
+ repo.add_worktree("target-branch");
+
+ let (cd_path, exec_path, _guard) = directive_files_for_pty();
+
+ let mut env_vars = repo.test_env_vars();
+ env_vars.push((
+ "WORKTRUNK_DIRECTIVE_CD_FILE".to_string(),
+ cd_path.display().to_string(),
+ ));
+ env_vars.push((
+ "WORKTRUNK_DIRECTIVE_EXEC_FILE".to_string(),
+ exec_path.display().to_string(),
+ ));
+
+ // No branch argument — `-x` alone opens the picker. Select target-branch and
+ // press Enter; the switch pipeline then writes the execute command to the
+ // EXEC file instead of a cd directive.
+ let result = exec_in_pty_with_input_expectations(
+ wt_bin().to_str().unwrap(),
+ &["switch", "--execute", "echo picker-exec-ran"],
+ repo.root_path(),
+ &env_vars,
+ &[
+ // Preview-pane gate: see test_switch_picker_emits_cd_directive_by_default.
+ ("target", Some("target-branch has no uncommitted changes")),
+ ("\r", None), // Enter to switch
+ ],
+ );
+
+ assert_eq!(
+ result.exit_code, 0,
+ "Expected exit code 0 for picker switch with --execute"
+ );
+
+ let exec_contents = std::fs::read_to_string(&exec_path).unwrap_or_default();
+ assert!(
+ exec_contents.contains("picker-exec-ran"),
+ "EXEC file should contain the --execute command after a picker switch, got: {}",
+ exec_contents
+ );
+}
+
+/// `{{ base }}` in a picker `--execute` resolves to the source worktree, just
+/// as it does on the argument path (`wt switch <branch> -x …`). The picker now
+/// captures pre-switch source identity, so the two paths no longer diverge:
+/// before, the picker left `base` unset while pre-flight validation still
+/// accepted the template, so `-x 'echo {{ base }}'` passed validation and then
+/// errored on the undefined value *after* the switch had already landed.
+/// Selecting from the `main` worktree, `{{ base }}` expands to `main`.
+#[rstest]
+fn test_switch_picker_execute_base_resolves_to_source(mut repo: TestRepo) {
+ repo.remove_fixture_worktrees();
+ repo.run_git(&["remote", "remove", "origin"]);
+ repo.add_worktree("target-branch");
+
+ let (cd_path, exec_path, _guard) = directive_files_for_pty();
+
+ let mut env_vars = repo.test_env_vars();
+ env_vars.push((
+ "WORKTRUNK_DIRECTIVE_CD_FILE".to_string(),
+ cd_path.display().to_string(),
+ ));
+ env_vars.push((
+ "WORKTRUNK_DIRECTIVE_EXEC_FILE".to_string(),
+ exec_path.display().to_string(),
+ ));
+
+ // Run from the `main` worktree so the captured source branch is `main`.
+ let result = exec_in_pty_with_input_expectations(
+ wt_bin().to_str().unwrap(),
+ &["switch", "--execute", "echo {{ base }}"],
+ repo.root_path(),
+ &env_vars,
+ &[
+ ("target", Some("target-branch has no uncommitted changes")),
+ ("\r", None), // Enter to switch
+ ],
+ );
+
+ assert_eq!(
+ result.exit_code, 0,
+ "picker `-x '{{{{ base }}}}'` should succeed, not error on an undefined \
+ value after the switch"
+ );
+
+ let exec_contents = std::fs::read_to_string(&exec_path).unwrap_or_default();
+ assert!(
+ exec_contents.contains("echo main"),
+ "EXEC file should contain the expanded `{{{{ base }}}}` (the source \
+ branch `main`), got: {exec_contents}"
+ );
+}
+
/// A project `pre-switch` hook must pass through the approval gate when the
/// picker switches — the picker has no `--yes`, so an unapproved project
/// command is shown for approval, never auto-run.
diff --git a/tests/snapshots/integration__integration_tests__help__help_switch_long.snap b/tests/snapshots/integration__integration_tests__help__help_switch_long.snap
index 3898c8ecd..16fce5f4d 100644
--- a/tests/snapshots/integration__integration_tests__help__help_switch_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_switch_long.snap
@@ -61,6 +61,8 @@ Usage: wt switch [OPTIONS] [BRANCH] [--
Replaces the wt process with the command after switching, giving it full terminal control. Useful for launching editors, AI agents, or other interactive tools.
+ Without a branch argument, the interactive picker opens and the command runs against the selected worktree — so wt switch -x claude picks a worktree, then launches Claude Code there.
+
Supports ]8;;@/hook.md#template-variables\hook template variables]8;;\ ({{ branch }}, {{ worktree_path }}, etc.) and filters. {{ base }} and {{ base_worktree_path }} require --create.
Especially useful with shell aliases: