Skip to content

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

Add post-switch hook for background execution after every switch (#284)

Maximilian Roos7f1ed8577bc6
diff --git a/docs/content/hook.md b/docs/content/hook.md
index 225d12cfa..a35ab35de 100644
--- a/docs/content/hook.md
+++ b/docs/content/hook.md
@@ -25,6 +25,7 @@ wt hook pre-merge --force # Skip approval prompts (for CI)
|------|------|----------|-----------|
| `post-create` | After worktree created | Yes | No |
| `post-start` | After worktree created | No (background) | No |
+| `post-switch` | After every switch | No (background) | No |
| `pre-commit` | Before commit during merge | Yes | Yes |
| `pre-merge` | Before merging to target | Yes | Yes |
| `post-merge` | After successful merge | Yes | No |
@@ -60,6 +61,18 @@ server = "npm run dev"
Output logged to `.git/wt-logs/{branch}-{source}-post-start-{name}.log` (source is `user` or `project`).
+### post-switch
+
+Runs after **every** switch operation, **in background**. Triggers on all switch results: creating new worktrees, switching to existing ones, or switching to the current worktree.
+
+**Use cases**: Renaming terminal tabs, updating tmux window names, IDE notifications.
+
+```toml
+post-switch = "echo 'Switched to {{ branch }}'"
+```
+
+Output logged to `.git/wt-logs/{branch}-{source}-post-switch-{name}.log` (source is `user` or `project`).
+
### pre-commit
Runs before committing during `wt merge`, **fail-fast**. All commands must exit 0 for the commit to proceed.
@@ -377,6 +390,7 @@ Usage: <b><span class=c>wt hook</span></b> <span class=c>[OPTIONS]</span> <span
<b><span class=c>show</span></b> Show configured hooks
<b><span class=c>post-create</span></b> Run post-create hooks
<b><span class=c>post-start</span></b> Run post-start hooks
+ <b><span class=c>post-switch</span></b> Run post-switch hooks
<b><span class=c>pre-commit</span></b> Run pre-commit hooks
<b><span class=c>pre-merge</span></b> Run pre-merge hooks
<b><span class=c>post-merge</span></b> Run post-merge hooks
diff --git a/src/cli.rs b/src/cli.rs
index 76198f90c..bed3da31e 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -1003,7 +1003,7 @@ pub enum HookCommand {
/// Lists user and project hooks. Project hooks show approval status (❓ = needs approval).
Show {
/// Hook type to show (default: all)
- #[arg(value_parser = ["post-create", "post-start", "pre-commit", "pre-merge", "post-merge", "pre-remove"])]
+ #[arg(value_parser = ["post-create", "post-start", "post-switch", "pre-commit", "pre-merge", "post-merge", "pre-remove"])]
hook_type: Option<String>,
/// Show expanded commands with current variables
@@ -1037,6 +1037,19 @@ pub enum HookCommand {
force: bool,
},
+ /// Run post-switch hooks
+ ///
+ /// Background — runs without blocking.
+ PostSwitch {
+ /// Run only this command from hook config
+ #[arg(add = crate::completion::hook_command_name_completer())]
+ name: Option<String>,
+
+ /// Skip approval prompts
+ #[arg(short, long)]
+ force: bool,
+ },
+
/// Run pre-commit hooks
PreCommit {
/// Run only this command from hook config
@@ -1445,6 +1458,7 @@ wt hook pre-merge --force # Skip approval prompts (for CI)
|------|------|----------|-----------|
| `post-create` | After worktree created | Yes | No |
| `post-start` | After worktree created | No (background) | No |
+| `post-switch` | After every switch | No (background) | No |
| `pre-commit` | Before commit during merge | Yes | Yes |
| `pre-merge` | Before merging to target | Yes | Yes |
| `post-merge` | After successful merge | Yes | No |
@@ -1480,6 +1494,18 @@ server = "npm run dev"
Output logged to `.git/wt-logs/{branch}-{source}-post-start-{name}.log` (source is `user` or `project`).
+### post-switch
+
+Runs after **every** switch operation, **in background**. Triggers on all switch results: creating new worktrees, switching to existing ones, or switching to the current worktree.
+
+**Use cases**: Renaming terminal tabs, updating tmux window names, IDE notifications.
+
+```toml
+post-switch = "echo 'Switched to {{ branch }}'"
+```
+
+Output logged to `.git/wt-logs/{branch}-{source}-post-switch-{name}.log` (source is `user` or `project`).
+
### pre-commit
Runs before committing during `wt merge`, **fail-fast**. All commands must exit 0 for the commit to proceed.
diff --git a/src/commands/project_config.rs b/src/commands/project_config.rs
index 3d16c5423..12411cd34 100644
--- a/src/commands/project_config.rs
+++ b/src/commands/project_config.rs
@@ -11,6 +11,7 @@ pub fn collect_commands_for_hooks(
let cfg = match hook {
HookType::PostCreate => &project_config.post_create,
HookType::PostStart => &project_config.post_start,
+ HookType::PostSwitch => &project_config.post_switch,
HookType::PreCommit => &project_config.pre_commit,
HookType::PreMerge => &project_config.pre_merge,
HookType::PostMerge => &project_config.post_merge,
diff --git a/src/commands/standalone.rs b/src/commands/standalone.rs
index 2c3f18fd8..b91153e2d 100644
--- a/src/commands/standalone.rs
+++ b/src/commands/standalone.rs
@@ -101,6 +101,20 @@ pub fn run_hook(hook_type: HookType, force: bool, name_filter: Option<&str>) ->
name_filter,
)
}
+ HookType::PostSwitch => {
+ let user_config = user_hook!(post_switch);
+ let project_config = project_config.as_ref().and_then(|c| c.post_switch.as_ref());
+ require_hooks(user_config, project_config, hook_type)?;
+ run_hook_with_filter(
+ &ctx,
+ user_config,
+ project_config,
+ hook_type,
+ &[],
+ HookFailureStrategy::FailFast,
+ name_filter,
+ )
+ }
HookType::PreCommit => {
let user_config = user_hook!(pre_commit);
let project_config = project_config.as_ref().and_then(|c| c.pre_commit.as_ref());
@@ -656,6 +670,7 @@ pub fn handle_hook_show(hook_type_filter: Option<&str>, expanded: bool) -> anyho
let filter: Option<HookType> = hook_type_filter.map(|s| match s {
"post-create" => HookType::PostCreate,
"post-start" => HookType::PostStart,
+ "post-switch" => HookType::PostSwitch,
"pre-commit" => HookType::PreCommit,
"pre-merge" => HookType::PreMerge,
"post-merge" => HookType::PostMerge,
@@ -725,6 +740,7 @@ fn render_user_hooks(
let hooks = [
(HookType::PostCreate, &config.post_create),
(HookType::PostStart, &config.post_start),
+ (HookType::PostSwitch, &config.post_switch),
(HookType::PreCommit, &config.pre_commit),
(HookType::PreMerge, &config.pre_merge),
(HookType::PostMerge, &config.post_merge),
@@ -784,6 +800,7 @@ fn render_project_hooks(
let hooks = [
(HookType::PostCreate, &config.post_create),
(HookType::PostStart, &config.post_start),
+ (HookType::PostSwitch, &config.post_switch),
(HookType::PreCommit, &config.pre_commit),
(HookType::PreMerge, &config.pre_merge),
(HookType::PostMerge, &config.post_merge),
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index 46920b238..155312740 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -848,6 +848,47 @@ impl<'a> CommandContext<'a> {
None,
)
}
+
+ /// Spawn post-switch commands in parallel as background processes (non-blocking)
+ ///
+ /// Spawns user hooks first, then project hooks. Skips all hooks if verify is false.
+ /// Runs on every switch, including to existing worktrees and newly created ones.
+ pub fn spawn_post_switch_commands(&self, verify: bool) -> anyhow::Result<()> {
+ if !verify {
+ return Ok(());
+ }
+
+ let pipeline = HookPipeline::new(*self);
+
+ // Spawn user hooks first (no approval required)
+ if let Some(user_config) = &self.config.post_switch {
+ pipeline.spawn_background(
+ user_config,
+ HookType::PostSwitch,
+ HookSource::User,
+ &[],
+ None,
+ )?;
+ }
+
+ // Then spawn project hooks (approval checked at gate, not here)
+ let project_config = match self.repo.load_project_config()? {
+ Some(cfg) => cfg,
+ None => return Ok(()),
+ };
+
+ let Some(post_switch_config) = &project_config.post_switch else {
+ return Ok(());
+ };
+
+ pipeline.spawn_background(
+ post_switch_config,
+ HookType::PostSwitch,
+ HookSource::Project,
+ &[],
+ None,
+ )
+ }
}
/// Push changes to target branch
diff --git a/src/config/project.rs b/src/config/project.rs
index e91688ab0..ace25f7e7 100644
--- a/src/config/project.rs
+++ b/src/config/project.rs
@@ -50,6 +50,14 @@ pub struct ProjectConfig {
#[serde(default, rename = "post-start")]
pub post_start: Option<CommandConfig>,
+ /// Commands to execute after switching to a worktree (non-blocking, background)
+ /// Runs on every switch, including to existing worktrees and newly created ones
+ /// Supports string (single command) or table (named, parallel)
+ ///
+ /// Available template variables: `{{ repo }}`, `{{ branch }}`, `{{ worktree }}`, `{{ worktree_name }}`, `{{ repo_root }}`, `{{ default_branch }}`, `{{ commit }}`, `{{ short_commit }}`, `{{ remote }}`, `{{ upstream }}`
+ #[serde(default, rename = "post-switch")]
+ pub post_switch: Option<CommandConfig>,
+
/// Commands to execute before committing changes during merge (blocking, fail-fast validation)
/// Supports string (single command) or table (named, sequential)
/// All commands must exit with code 0 for commit to proceed
@@ -134,6 +142,7 @@ mod tests {
let config = ProjectConfig::default();
assert!(config.post_create.is_none());
assert!(config.post_start.is_none());
+ assert!(config.post_switch.is_none());
assert!(config.pre_commit.is_none());
assert!(config.pre_merge.is_none());
assert!(config.post_merge.is_none());
@@ -203,6 +212,7 @@ test = "cargo test"
let contents = r#"
post-create = "npm install"
post-start = "npm run watch"
+post-switch = "rename-tab"
pre-commit = "cargo fmt --check"
pre-merge = "cargo test"
post-merge = "git push"
@@ -211,6 +221,7 @@ pre-remove = "echo bye"
let config: ProjectConfig = toml::from_str(contents).unwrap();
assert!(config.post_create.is_some());
assert!(config.post_start.is_some());
+ assert!(config.post_switch.is_some());
assert!(config.pre_commit.is_some());
assert!(config.pre_merge.is_some());
assert!(config.post_merge.is_some());
diff --git a/src/config/user.rs b/src/config/user.rs
index 074a437f9..44ca5c512 100644
--- a/src/config/user.rs
+++ b/src/config/user.rs
@@ -168,6 +168,14 @@ pub struct WorktrunkConfig {
)]
pub post_start: Option<CommandConfig>,
+ /// Commands to execute after switching to a worktree (background)
+ #[serde(
+ default,
+ rename = "post-switch",
+ skip_serializing_if = "Option::is_none"
+ )]
+ pub post_switch: Option<CommandConfig>,
+
/// Commands to execute before committing during merge (blocking, fail-fast)
#[serde(
default,
@@ -342,6 +350,7 @@ impl Default for WorktrunkConfig {
merge: None,
post_create: None,
post_start: None,
+ post_switch: None,
pre_commit: None,
pre_merge: None,
post_merge: None,
@@ -805,6 +814,9 @@ run = "npm install"
[post-start]
run = "npm run build"
+
+[post-switch]
+rename-tab = "echo 'switched'"
"#;
let keys = find_unknown_keys(content);
assert!(keys.is_empty());
diff --git a/src/git/mod.rs b/src/git/mod.rs
index 539396348..74398f4e7 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -286,6 +286,7 @@ pub(crate) use parse::DefaultBranchName;
pub enum HookType {
PostCreate,
PostStart,
+ PostSwitch,
PreCommit,
PreMerge,
PostMerge,
diff --git a/src/main.rs b/src/main.rs
index d961d34c2..89404ed16 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1144,6 +1144,9 @@ fn main() {
HookCommand::PostStart { name, force } => {
run_hook(HookType::PostStart, force, name.as_deref())
}
+ HookCommand::PostSwitch { name, force } => {
+ run_hook(HookType::PostSwitch, force, name.as_deref())
+ }
HookCommand::PreCommit { name, force } => {
run_hook(HookType::PreCommit, force, name.as_deref())
}
@@ -1230,10 +1233,10 @@ fn main() {
} => WorktrunkConfig::load()
.context("Failed to load config")
.and_then(|config| {
- // "Approve at the Gate": collect and approve hooks upfront when creating
+ // "Approve at the Gate": collect and approve hooks upfront
// This ensures approval happens once at the command entry point
- // If user declines, skip hooks but continue with worktree creation
- let approved = if create && verify {
+ // If user declines, skip hooks but continue with worktree operation
+ let approved = if verify {
let repo = Repository::current();
let repo_root = repo.worktree_base().context("Failed to switch worktree")?;
// Compute worktree path for template expansion in approval prompt
@@ -1246,19 +1249,34 @@ fn main() {
&repo_root,
force,
);
- approve_hooks(&ctx, &[HookType::PostCreate, HookType::PostStart])?
+ // Approve different hooks based on whether we're creating or switching
+ if create {
+ approve_hooks(
+ &ctx,
+ &[
+ HookType::PostCreate,
+ HookType::PostStart,
+ HookType::PostSwitch,
+ ],
+ )?
+ } else {
+ // When switching to existing, only post-switch needs approval
+ approve_hooks(&ctx, &[HookType::PostSwitch])?
+ }
} else {
- true // No hooks to approve = considered approved
+ true // --no-verify: skip all hooks
};
- // Skip hooks if --no-hooks or user declined approval
+ // Skip hooks if --no-verify or user declined approval
let skip_hooks = !verify || !approved;
// Show message if user declined approval
if !approved {
- crate::output::print(info_message(
- "Commands declined, continuing worktree creation",
- ))?;
+ crate::output::print(info_message(if create {
+ "Commands declined, continuing worktree creation"
+ } else {
+ "Commands declined"
+ }))?;
}
// Execute switch operation (creates worktree, runs post-create hooks if approved)
@@ -1272,24 +1290,31 @@ fn main() {
&config,
)?;
- // Show success message (temporal locality: immediately after worktree creation)
+ // Show success message (temporal locality: immediately after worktree operation)
handle_switch_output(&result, &branch_info, execute.is_some())?;
- // Now spawn post-start hooks (background processes, after success message)
- // Only run post-start commands when creating a NEW worktree, not when switching to existing
- // Hooks only run if --no-hooks wasn't passed and approval was granted (or --force used)
- if !skip_hooks && let SwitchResult::Created { path, .. } = &result {
+ // Spawn background hooks after success message
+ // - post-switch: runs on ALL switches (Created, Existing, AlreadyAt)
+ // - post-start: runs only when creating a NEW worktree
+ if !skip_hooks {
let repo = Repository::current();
let repo_root = repo.worktree_base().context("Failed to switch worktree")?;
let ctx = CommandContext::new(
&repo,
&config,
Some(branch_info.branch()),
- path,
+ result.path(),
&repo_root,
force,
);
- ctx.spawn_post_start_commands(true)?;
+
+ // Post-switch runs first (immediate "I'm here" signal)
+ ctx.spawn_post_switch_commands(true)?;
+
+ // Post-start runs only on creation (setup tasks)
+ if matches!(&result, SwitchResult::Created { .. }) {
+ ctx.spawn_post_start_commands(true)?;
+ }
}
// Execute user command after post-start hooks have been spawned
diff --git a/tests/integration_tests/completion.rs b/tests/integration_tests/completion.rs
index 5df8b77f4..7270a5ea3 100644
--- a/tests/integration_tests/completion.rs
+++ b/tests/integration_tests/completion.rs
@@ -707,6 +707,7 @@ fn test_complete_hook_subcommands(repo: TestRepo) {
assert!(subcommands.contains(&"show"), "Missing show");
assert!(subcommands.contains(&"post-create"), "Missing post-create");
assert!(subcommands.contains(&"post-start"), "Missing post-start");
+ assert!(subcommands.contains(&"post-switch"), "Missing post-switch");
assert!(subcommands.contains(&"pre-commit"), "Missing pre-commit");
assert!(subcommands.contains(&"pre-merge"), "Missing pre-merge");
assert!(subcommands.contains(&"post-merge"), "Missing post-merge");
@@ -714,8 +715,8 @@ fn test_complete_hook_subcommands(repo: TestRepo) {
assert!(subcommands.contains(&"approvals"), "Missing approvals");
assert_eq!(
subcommands.len(),
- 8,
- "Should have exactly 8 hook subcommands"
+ 9,
+ "Should have exactly 9 hook subcommands"
);
// Test 2: Partial input "po" - filters to post-* subcommands
@@ -725,6 +726,7 @@ fn test_complete_hook_subcommands(repo: TestRepo) {
let subcommands = value_suggestions(&stdout);
assert!(subcommands.contains(&"post-create"));
assert!(subcommands.contains(&"post-start"));
+ assert!(subcommands.contains(&"post-switch"));
assert!(subcommands.contains(&"post-merge"));
assert!(!subcommands.contains(&"pre-commit"));
assert!(!subcommands.contains(&"pre-merge"));