Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(switch): interactive picker runs the full switch pipeline (#2845)
Maximilian Roosff4e481a4c44
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex cfd53c68c..c7c596fcc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,8 @@### Fixed+- **Interactive picker switches with `cd = false`**: With `[switch] cd = false` (or `wt switch --no-cd`), opening the picker (`wt switch` with no branch argument) and selecting a worktree printed the branch name and exited — no switch, no hooks, and `Alt-c` created nothing. The picker now runs the same switch pipeline as `wt switch <branch>`, suppressing only the cd directive: `pre-switch`/`post-switch` hooks fire and `Alt-c` creates the worktree. `--format=json` works in the picker too, and replaces the old print-only output for scripting — it both switches and prints a structured result (`action`, `branch`, `path`) to stdout. ([#2837](https://github.com/max-sixty/worktrunk/issues/2837))+- **`wt remove` reaps a wedged fsmonitor daemon**: When `core.fsmonitor=true`, git runs a per-worktree `git fsmonitor--daemon`. Removal already sent `git fsmonitor--daemon stop`, but `stop` is an IPC request to the daemon itself, so a daemon that had stopped answering its socket ignored it and then leaked forever once its worktree was gone (dozens could accumulate, and one wedged daemon hangs `wt list`). Removal now resolves the daemon's PID from its IPC socket and force-terminates it (SIGTERM, brief wait, SIGKILL) when `stop` doesn't take. The signal only ever targets the daemon whose socket resolves to the worktree being removed.- **Orphaned fsmonitor daemons are reaped**: `wt remove`'s background internal sweep now terminates (`SIGTERM`, then `SIGKILL` after a short bounded wait) any `git fsmonitor--daemon` whose IPC socket no longer resolves to a live worktree. This reclaims daemons orphaned by paths that bypass `wt remove`'s synchronous daemon stop (plain `git worktree remove`, manual `rm -rf`, or a crashed `wt`), which otherwise accumulate until reboot and can hang `wt list` when wedged. A daemon serving a live worktree is never reaped.diff --git a/docs/content/switch.md b/docs/content/switch.mdindex 6b5531c02..ca0a3ce08 100644--- a/docs/content/switch.md+++ b/docs/content/switch.md@@ -184,9 +184,6 @@ Usage: <b><span class=c>wt switch</span></b> <span class=c>[OPTIONS]</span> <spaHooks still run normally. Useful when hooks handle navigation (e.g., tmux workflows) orfor CI/automation. Use --cd to override.- In picker mode (no branch argument), prints the selected branch name and exits without- switching. Useful for scripting.-<b><span class=c>-h</span></b>, <b><span class=c>--help</span></b>Print help (see a summary with '-h')diff --git a/docs/content/tips-patterns.md b/docs/content/tips-patterns.mdindex b3d2a9099..0949d058c 100644--- a/docs/content/tips-patterns.md+++ b/docs/content/tips-patterns.md@@ -17,7 +17,7 @@ Create a worktree and launch Claude in one command:## `wt` aliases-Compose with template filters and [vars](@/tips-patterns.md#per-branch-variables) for branch-specific shortcuts:+Compose with template filters and [vars](@/tips-patterns.md#per-branch-variables):```toml# .config/wt.toml@@ -27,6 +27,9 @@ open = "open http://localhost:{{ branch | hash_port }}"# Test with branch-specific features from varstest = "cargo test --features {{ vars.features | default('default') }}"++# Switch via the interactive picker, print the chosen branch+pick = "wt switch --format=json | jq -r '.branch'"```See [Aliases](@/extending.md#aliases) for scoping, approval, and reference.@@ -327,15 +330,6 @@ Each worktree gets its own [cmux](https://cmux.com) workspace. Switching worktre[switch]cd = false-[aliases]-# Two-step the picker: with cd=false, `wt switch` (no args) prints the chosen-# branch and exits without firing hooks. Capture that and feed it back so the-# pre-switch hook runs.-pick = """-b=$(wt switch)-[ -n "$b" ] && wt switch "$b"-"""-[pre-create]cmux = "cmux new-workspace --name {{ repo | sanitize }}/{{ branch | sanitize }} --cwd {{ worktree_path }} --focus true"@@ -356,8 +350,6 @@ WS=$(cmux --json list-workspaces 2>/dev/null \\"""```-Use `wt pick` to open the interactive picker; `wt switch --create <branch>` and `wt switch <branch>` continue to work directly.-**Why `pre-*` instead of `post-*`?** cmux restricts socket access to processes spawned inside a cmux terminal. `post-*` hooks run as detached background processes, breaking the process ancestry chain. `pre-*` hooks run in the foreground and inherit the terminal's process lineage.## Xcode DerivedData cleanupdiff --git a/skills/worktrunk/reference/switch.md b/skills/worktrunk/reference/switch.mdindex 9e1194020..e89196b6b 100644--- a/skills/worktrunk/reference/switch.md+++ b/skills/worktrunk/reference/switch.md@@ -176,9 +176,6 @@ Options:Hooks still run normally. Useful when hooks handle navigation (e.g., tmux workflows) orfor CI/automation. Use --cd to override.- In picker mode (no branch argument), prints the selected branch name and exits without- switching. Useful for scripting.--h, --helpPrint help (see a summary with '-h')diff --git a/skills/worktrunk/reference/tips-patterns.md b/skills/worktrunk/reference/tips-patterns.mdindex 7ead9615e..4f942a962 100644--- a/skills/worktrunk/reference/tips-patterns.md+++ b/skills/worktrunk/reference/tips-patterns.md@@ -14,7 +14,7 @@ wsc feature -- 'Fix GH #322' # Runs `claude 'Fix GH #322'`## `wt` aliases-Compose with template filters and [vars](https://worktrunk.dev/tips-patterns/#per-branch-variables) for branch-specific shortcuts:+Compose with template filters and [vars](https://worktrunk.dev/tips-patterns/#per-branch-variables):```toml# .config/wt.toml@@ -24,6 +24,9 @@ open = "open http://localhost:{{ branch | hash_port }}"# Test with branch-specific features from varstest = "cargo test --features {{ vars.features | default('default') }}"++# Switch via the interactive picker, print the chosen branch+pick = "wt switch --format=json | jq -r '.branch'"```See [Aliases](https://worktrunk.dev/extending/#aliases) for scoping, approval, and reference.@@ -344,15 +347,6 @@ Each worktree gets its own [cmux](https://cmux.com) workspace. Switching worktre[switch]cd = false-[aliases]-# Two-step the picker: with cd=false, `wt switch` (no args) prints the chosen-# branch and exits without firing hooks. Capture that and feed it back so the-# pre-switch hook runs.-pick = """-b=$(wt switch)-[ -n "$b" ] && wt switch "$b"-"""-[pre-create]cmux = "cmux new-workspace --name {{ repo | sanitize }}/{{ branch | sanitize }} --cwd {{ worktree_path }} --focus true"@@ -373,8 +367,6 @@ WS=$(cmux --json list-workspaces 2>/dev/null \\"""```-Use `wt pick` to open the interactive picker; `wt switch --create <branch>` and `wt switch <branch>` continue to work directly.-**Why `pre-*` instead of `post-*`?** cmux restricts socket access to processes spawned inside a cmux terminal. `post-*` hooks run as detached background processes, breaking the process ancestry chain. `pre-*` hooks run in the foreground and inherit the terminal's process lineage.## Xcode DerivedData cleanupdiff --git a/src/cli/mod.rs b/src/cli/mod.rsindex 60c93cce6..20b4c82d5 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -337,9 +337,6 @@ pub(crate) struct SwitchArgs {////// Hooks still run normally. Useful when hooks handle navigation/// (e.g., tmux workflows) or for CI/automation. Use --cd to override.- ///- /// In picker mode (no branch argument), prints the selected branch- /// name and exits without switching. Useful for scripting.#[arg(long, overrides_with = "cd")]pub(crate) no_cd: bool,@@ -359,7 +356,7 @@ pub(crate) struct SwitchArgs {////// JSON prints structured result to stdout. Designed for tool/// integration (e.g., Claude Code WorktreeCreate hooks).- #[arg(long, default_value = "text", requires = "branch", conflicts_with_all = ["branches", "remotes"], help_heading = "Automation")]+ #[arg(long, default_value = "text", help_heading = "Automation")]pub(crate) format: SwitchFormat,}diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex 158aaed93..56ae45138 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -117,10 +117,12 @@ use super::list::progressive::RenderTarget;use super::repository_ext::{RemoveTarget, RepositoryCliExt};use super::template_vars::TemplateVars;use super::worktree::{- RemoveResult, SwitchBranchInfo, SwitchResult, approve_switch_hooks, execute_switch,- offer_bare_repo_worktree_path_fix, path_mismatch, plan_switch, run_pre_switch_hooks,- spawn_switch_background_hooks, switch_hook_project_config, validate_switch_templates,+ RemoveResult, SwitchBranchInfo, SwitchResult, approve_switch_hooks, emit_switch_json,+ execute_switch, offer_bare_repo_worktree_path_fix, path_mismatch, plan_switch,+ run_pre_switch_hooks, spawn_switch_background_hooks, switch_hook_project_config,+ validate_switch_templates,};+use crate::cli::SwitchFormat;use crate::output::{handle_remove_output, handle_switch_output};use worktrunk::git::{BranchDeletionMode, delete_branch_if_safe};@@ -415,6 +417,7 @@ pub fn handle_picker(cli_branches: bool,cli_remotes: bool,change_dir_flag: Option<bool>,+ format: SwitchFormat,) -> 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 —@@ -779,18 +782,6 @@ pub fn handle_picker(_ => PickerAction::Switch,};- // --no-cd: just output the selected branch name and exit (read-only, no side effects)- if !change_dir {- let selected_name = out- .selected_items- .first()- .map(|item| item.output().to_string());- let query = out.query.trim().to_string();- let identifier = resolve_identifier(&action, query, selected_name)?;- println!("{identifier}");- return Ok(());- }-let should_create = matches!(action, PickerAction::Create);// Get branch name: from query if creating new, from selected item if switching.@@ -862,6 +853,10 @@ pub fn handle_picker(let (result, branch_info) =execute_switch(&repo, plan, &config, false, hooks_approved, &hook_plan)?;+ // --format=json: structured result to stdout, identical to the+ // argument path. All switch behavior above proceeds normally.+ emit_switch_json(format, &result, &branch_info)?;+// Compute path mismatch lazily (deferred from plan_switch for existing worktrees).// Skip for detached HEAD worktrees (branch is None).let branch_info = match &result {@@ -909,8 +904,7 @@ pub fn handle_picker(/// Resolve the branch identifier from picker output.///-/// Extracted from the picker callback for testability. Used by both the-/// interactive path and the `--no-cd` print path.+/// Extracted from the picker's accept handler for testability.fn resolve_identifier(action: &PickerAction,query: String,diff --git a/src/commands/worktree/mod.rs b/src/commands/worktree/mod.rsindex 39458edd3..0f1c0cd1f 100644--- a/src/commands/worktree/mod.rs+++ b/src/commands/worktree/mod.rs@@ -100,7 +100,7 @@ pub use resolve::{pub use switch::{SwitchOptions, run_switch};#[cfg(unix)]pub(crate) use switch::{- approve_switch_hooks, run_pre_switch_hooks, spawn_switch_background_hooks,+ approve_switch_hooks, emit_switch_json, run_pre_switch_hooks, spawn_switch_background_hooks,switch_hook_project_config, validate_switch_templates,};#[cfg(unix)]diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsindex b677e1fea..49ae2b965 100644--- a/src/commands/worktree/switch.rs+++ b/src/commands/worktree/switch.rs@@ -1248,6 +1248,25 @@ impl SwitchJsonOutput {}}+/// Emit the structured `--format=json` result to stdout when requested.+///+/// Shared by the argument path and the interactive picker so `wt switch+/// --format=json` produces identical output regardless of how the branch+/// was chosen. A no-op for `SwitchFormat::Text`.+pub(crate) fn emit_switch_json(+ format: SwitchFormat,+ result: &SwitchResult,+ branch_info: &SwitchBranchInfo,+) -> anyhow::Result<()> {+ if format != SwitchFormat::Json {+ return Ok(());+ }+ let json = SwitchJsonOutput::from_result(result, branch_info);+ let json = serde_json::to_string(&json).context("Failed to serialize to JSON")?;+ println!("{json}");+ Ok(())+}+/// Options for the switch commandpub struct SwitchOptions<'a> {pub branch: &'a str,@@ -1660,11 +1679,7 @@ pub fn run_switch(// --format=json: write structured result to stdout. All behavior (hooks,// --execute, shell integration) proceeds normally — format only affects output.- if format == SwitchFormat::Json {- let json = SwitchJsonOutput::from_result(&result, &branch_info);- let json = serde_json::to_string(&json).context("Failed to serialize to JSON")?;- println!("{json}");- }+ emit_switch_json(format, &result, &branch_info)?;// Early exit for benchmarking time-to-first-outputif std::env::var_os("WORKTRUNK_FIRST_OUTPUT").is_some() {diff --git a/src/main.rs b/src/main.rsindex 65c1bf7d9..9425fd3f0 100644--- a/src/main.rs+++ b/src/main.rs@@ -653,7 +653,7 @@ fn handle_select_command(branches: bool, remotes: bool) -> anyhow::Result<()> {// Deprecated: show warning and delegate to handle_pickerwarn_select_deprecated();worktrunk::config::suppress_warnings();- handle_picker(branches, remotes, None)+ handle_picker(branches, remotes, None, SwitchFormat::Text)}#[cfg(not(unix))]@@ -683,7 +683,12 @@ fn handle_switch_command(args: SwitchArgs, yes: bool) -> anyhow::Result<()> {let Some(branch) = args.branch else {#[cfg(unix)]{- return handle_picker(args.branches, args.remotes, change_dir_flag);+ return handle_picker(+ args.branches,+ args.remotes,+ change_dir_flag,+ args.format,+ );}#[cfg(not(unix))]diff --git a/tests/integration_tests/output_system_guard.rs b/tests/integration_tests/output_system_guard.rsindex cc06ca96c..d52e3ee04 100644--- a/tests/integration_tests/output_system_guard.rs+++ b/tests/integration_tests/output_system_guard.rs@@ -51,7 +51,7 @@ const STDOUT_ALLOWED_PATHS: &[&str] = &["step/prune.rs",// JSON output for wt step relocate --format=json"step/relocate.rs",- // --no-cd flag: branch name output for scripting+ // Dry-run cache inventory dump (WORKTRUNK_PICKER_DRY_RUN)"picker/mod.rs",// JSON output for wt switch --format=json"worktree/switch.rs",diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rsindex 7bdf5ec52..86b0e60a2 100644--- a/tests/integration_tests/switch.rs+++ b/tests/integration_tests/switch.rs@@ -1700,6 +1700,19 @@ fn test_switch_no_args_requires_tty(repo: TestRepo) {snapshot_switch("switch_missing_argument_hints", &repo, &[]);}+#[cfg(unix)] // `wt select` is a deprecated alias for the Unix-only picker+#[rstest]+fn test_select_deprecated_alias_requires_tty(repo: TestRepo) {+ // `wt select` warns that it is deprecated, then delegates to the same+ // interactive picker as `wt switch`; in a non-TTY it bails on the+ // terminal requirement.+ let settings = setup_snapshot_settings(&repo);+ settings.bind(|| {+ let mut cmd = make_snapshot_cmd(&repo, "select", &[], None);+ assert_cmd_snapshot!("select_deprecated_requires_tty", cmd);+ });+}+////// This verifies the fix for non-Unix platforms where stdin was incorrectly/// set to Stdio::null() instead of Stdio::inherit(), breaking interactivediff --git a/tests/integration_tests/switch_picker.rs b/tests/integration_tests/switch_picker.rsindex 77a2c4317..567b22446 100644--- a/tests/integration_tests/switch_picker.rs+++ b/tests/integration_tests/switch_picker.rs@@ -1177,11 +1177,11 @@ fn test_switch_picker_emits_cd_directive_by_default(mut repo: TestRepo) {}#[rstest]-fn test_switch_picker_no_cd_prints_branch_without_switching(mut repo: TestRepo) {+fn test_switch_picker_no_cd_switches_without_cd_directive(mut repo: TestRepo) {repo.remove_fixture_worktrees();repo.run_git(&["remote", "remove", "origin"]);- // Create a worktree to select+ // Create a worktree to switch torepo.add_worktree("target-branch");let (cd_path, exec_path, _guard) = directive_files_for_pty();@@ -1196,35 +1196,38 @@ fn test_switch_picker_no_cd_prints_branch_without_switching(mut repo: TestRepo)exec_path.display().to_string(),));- // Run `wt switch --no-cd`, filter to "target", press Enter to select+ // `wt switch --no-cd` opens the picker and switches identically to+ // `wt switch <branch> --no-cd` — it only suppresses the cd directive.+ // `--format=json` is the observable proof the switch pipeline ran: the+ // structured result reaches stdout only after `execute_switch`.let result = exec_in_pty_with_input_expectations(wt_bin().to_str().unwrap(),- &["switch", "--no-cd"],+ &["switch", "--no-cd", "--format=json"],repo.root_path(),&env_vars,&[// Preview-pane gate: see test_switch_picker_emits_cd_directive_by_default// for the rationale (matcher-driven row redraw can lag the cursor).("target", Some("target-branch has no uncommitted changes")),- ("\r", None), // Enter to select+ ("\r", None), // Enter to switch],);assert_eq!(result.exit_code, 0,- "Expected exit code 0 for --no-cd selection"+ "Expected exit code 0 for --no-cd switch");+ // The structured result reaches stdout only after execute_switch — the+ // old print-only path emitted a bare branch name and never reached it.let screen = result.screen();-- // --no-cd should output the branch nameassert!(- screen.contains("target-branch"),- "Expected branch name in output with --no-cd.\nScreen:\n{}",+ screen.contains("\"action\""),+ "Expected --format=json switch result on screen.\nScreen:\n{}",screen);- // --no-cd should NOT emit a cd directive (read-only operation)+ // --no-cd suppresses only the cd directive; the switch still ran.let cd_content = std::fs::read_to_string(&cd_path).unwrap_or_default();assert!(cd_content.trim().is_empty(),diff --git a/tests/snapshots/integration__integration_tests__help__help_switch_long.snap b/tests/snapshots/integration__integration_tests__help__help_switch_long.snapindex 75ead7c5e..7eeb2bf4b 100644--- a/tests/snapshots/integration__integration_tests__help__help_switch_long.snap+++ b/tests/snapshots/integration__integration_tests__help__help_switch_long.snap@@ -84,8 +84,6 @@ Usage: [1m[36mwt switch[0m [36m[OPTIONS][0m [36m[BRANCH][0m [1m[36m[--Skip directory change after switching[0mHooks still run normally. Useful when hooks handle navigation (e.g., tmux workflows) or for CI/automation. Use --cd to override.[0m-- In picker mode (no branch argument), prints the selected branch name and exits without switching. Useful for scripting.[0m[1m[36m-h[0m, [1m[36m--help[0mPrint help (see a summary with '-h')diff --git a/tests/snapshots/integration__integration_tests__switch__select_deprecated_requires_tty.snap b/tests/snapshots/integration__integration_tests__switch__select_deprecated_requires_tty.snapnew file mode 100644index 000000000..0da6f6169--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__select_deprecated_requires_tty.snap@@ -0,0 +1,59 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - select+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMON_DIR: ""+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_DIR: ""+ GIT_EDITOR: ""+ GIT_INDEX_FILE: ""+ GIT_OBJECT_DIRECTORY: ""+ GIT_TERMINAL_PROMPT: "0"+ GIT_WORK_TREE: ""+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ NO_COLOR: ""+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"+ PATH: "[PATH]"+ PSModulePath: ""+ RUST_LOG: warn+ SHELL: ""+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_BASH_INSTALLED: "0"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_FISH_INSTALLED: "0"+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+[33m▲[39m [33mwt select is deprecated; use wt switch instead[39m+[31m✗[39m [31mInteractive picker requires an interactive terminal[39m