Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat: Enhance approval UI and refactor command handling
Maximilian Roosa48d873774e7
diff --git a/src/commands/command_approval.rs b/src/commands/command_approval.rsindex f4faf420c..1f5ae6c79 100644--- a/src/commands/command_approval.rs+++ b/src/commands/command_approval.rs@@ -2,26 +2,27 @@//!//! Shared helpers for approving commands declared in project configuration.-use worktrunk::config::WorktrunkConfig;+use worktrunk::config::{Command, WorktrunkConfig};use worktrunk::git::{GitError, GitResultExt};use worktrunk::styling::{- AnstyleStyle, HINT_EMOJI, WARNING, WARNING_EMOJI, eprint, eprintln, format_bash_with_gutter,+ AnstyleStyle, HINT_EMOJI, WARNING, WARNING_EMOJI, format_bash_with_gutter, print, println,};/// Batch approval helper used when multiple commands are queued for execution./// Returns `Ok(true)` when execution may continue, `Ok(false)` when the user/// declined, and `Err` if config reload/save fails.+///+/// Shows expanded commands to the user. Templates are saved to config for future approval checks.pub fn approve_command_batch(- commands: &[(Option<String>, String)],+ commands: &[Command],project_id: &str,config: &WorktrunkConfig,force: bool,context: &str,) -> Result<bool, GitError> {- let needs_approval: Vec<(&Option<String>, &String)> = commands+ let needs_approval: Vec<&Command> = commands.iter()- .filter(|(_, command)| !config.is_command_approved(project_id, command))- .map(|(name, command)| (name, command))+ .filter(|cmd| !config.is_command_approved(project_id, &cmd.template)).collect();if needs_approval.is_empty() {@@ -36,7 +37,7 @@ pub fn approve_command_batch(if !approved {let dim = AnstyleStyle::new().dimmed();- eprintln!("{dim}{context} declined{dim:#}");+ println!("{dim}{context} declined{dim:#}");return Ok(false);}@@ -44,23 +45,22 @@ pub fn approve_command_batch(if !force {let mut fresh_config = WorktrunkConfig::load().git_context("Failed to reload config")?;- // Get or create the project entry once, outside the looplet project_entry = fresh_config.projects.entry(project_id.to_string()).or_default();let mut updated = false;- for (_, command) in needs_approval {- if !project_entry.approved_commands.iter().any(|c| c == command) {- project_entry.approved_commands.push(command.to_string());+ for cmd in &needs_approval {+ if !project_entry.approved_commands.contains(&cmd.template) {+ project_entry.approved_commands.push(cmd.template.clone());updated = true;}}if updated && let Err(e) = fresh_config.save() {log_approval_warning("Failed to save command approval", e);- eprintln!("You will be prompted again next time.");+ println!("You will be prompted again next time.");}}@@ -68,13 +68,10 @@ pub fn approve_command_batch(}fn log_approval_warning(message: &str, error: impl std::fmt::Display) {- eprintln!("{WARNING_EMOJI} {WARNING}{message}: {error}{WARNING:#}");+ println!("{WARNING_EMOJI} {WARNING}{message}: {error}{WARNING:#}");}-fn prompt_for_batch_approval(- commands: &[(&Option<String>, &String)],- project_id: &str,-) -> std::io::Result<bool> {+fn prompt_for_batch_approval(commands: &[&Command], project_id: &str) -> std::io::Result<bool> {use std::io::{self, Write};let project_name = project_id.split('/').next_back().unwrap_or(project_id);@@ -84,33 +81,26 @@ fn prompt_for_batch_approval(let count = commands.len();let plural = if count == 1 { "" } else { "s" };- eprintln!();- eprintln!(+ println!();+ println!("{WARNING_EMOJI} {WARNING}Permission required to execute {warning_bold}{count}{warning_bold:#} command{plural}{WARNING:#}",);- eprintln!();- eprintln!("{bold}{project_name}{bold:#} ({dim}{project_id}{dim:#}) wants to execute:");- eprintln!();-- for (name, command) in commands {- let label = match name {- Some(n) => format!("{n}: {command}"),- None => (*command).clone(),- };- eprint!("{}", format_bash_with_gutter(&label, ""));+ println!();++ for cmd in commands {+ println!("{bold}{project_name}{bold:#} ({dim}{project_id}{dim:#}) wants to execute:");+ println!();+ print!("{}", format_bash_with_gutter(&cmd.expanded, ""));+ println!();}- eprintln!();- eprint!("{HINT_EMOJI} Allow and remember? {bold}[y/N]{bold:#} ");- io::stderr().flush()?;+ print!("{HINT_EMOJI} Allow and remember? {bold}[y/N]{bold:#} ");+ io::stdout().flush()?;let mut response = String::new();io::stdin().read_line(&mut response)?;- // Add newline after user input to prevent output interleaving.- // Without this, success messages (stdout) can appear on the same line as the prompt (stderr)- // when the user types 'y' + Enter, since the Enter only adds a newline to stderr.- eprintln!();+ println!();Ok(response.trim().eq_ignore_ascii_case("y"))}diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rsindex 9effa9c25..af708d4c8 100644--- a/src/commands/command_executor.rs+++ b/src/commands/command_executor.rs@@ -1,6 +1,6 @@use std::collections::HashMap;use std::path::Path;-use worktrunk::config::{CommandConfig, WorktrunkConfig, expand_template};+use worktrunk::config::{Command, CommandConfig, WorktrunkConfig, expand_template};use worktrunk::git::{GitError, Repository};use super::command_approval::approve_command_batch;@@ -43,12 +43,12 @@ impl<'a> CommandContext<'a> {/// Expand commands from a CommandConfig without approval////// This is the canonical command expansion implementation.-/// Returns expanded commands as (name, command) tuples.+/// Returns cloned commands with their expanded forms filled in.fn expand_commands(command_config: &CommandConfig,ctx: &CommandContext<'_>,extra_vars: &[(&str, &str)],-) -> Result<Vec<(Option<String>, String)>, GitError> {+) -> Result<Vec<Command>, GitError> {let commands = command_config.commands();if commands.is_empty() {return Ok(Vec::new());@@ -73,33 +73,41 @@ fn expand_commands(base_extras.insert(key.to_string(), value.to_string());}- let mut expanded = Vec::new();+ let mut expanded_commands = Vec::new();- for (name, command) in commands {+ for cmd in commands {let extras_owned = base_extras.clone();let extras_ref: HashMap<&str, &str> = extras_owned.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();- let expanded_cmd = expand_template(command, repo_name, ctx.branch, &extras_ref);- expanded.push((name.clone(), expanded_cmd));+ let expanded_str = expand_template(&cmd.template, repo_name, ctx.branch, &extras_ref);+ expanded_commands.push(Command::with_expansion(+ cmd.name.clone(),+ cmd.template.clone(),+ expanded_str,+ ));}- Ok(expanded)+ Ok(expanded_commands)}-pub fn prepare_project_commands<F>(+/// Prepare project commands for execution with approval+///+/// This function:+/// 1. Expands command templates with context variables+/// 2. Requests user approval for unapproved commands (unless auto_trust or force)+/// 3. Returns prepared commands ready for execution+///+/// Returns `Err(GitError::CommandNotApproved)` if the user declines approval.+pub fn prepare_project_commands(command_config: &CommandConfig,ctx: &CommandContext<'_>,auto_trust: bool,extra_vars: &[(&str, &str)],approval_context: &str,- mut on_skip: F,-) -> Result<Vec<PreparedCommand>, GitError>-where- F: FnMut(Option<&str>, &str),-{+) -> Result<Vec<PreparedCommand>, GitError> {let commands = command_config.commands();if commands.is_empty() {return Ok(Vec::new());@@ -107,27 +115,27 @@ wherelet project_id = ctx.repo.project_identifier()?;- // Approve using original command strings (before expansion)+ // Expand commands before approval for transparency+ let expanded_commands = expand_commands(command_config, ctx, extra_vars)?;++ // Approve using expanded commands (which have both template and expanded forms)if !auto_trust&& !approve_command_batch(- commands,+ &expanded_commands,&project_id,ctx.config,ctx.force,approval_context,)?{- for (name, command) in commands {- on_skip(name.as_deref(), command);- }return Err(GitError::CommandNotApproved);}- // Expand commands after approval- let expanded = expand_commands(command_config, ctx, extra_vars)?;-- Ok(expanded+ Ok(expanded_commands.into_iter()- .map(|(name, expanded)| PreparedCommand { name, expanded })+ .map(|cmd| PreparedCommand {+ name: cmd.name,+ expanded: cmd.expanded,+ }).collect())}diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex 23899aff1..221dd2952 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -1,5 +1,5 @@use worktrunk::HookType;-use worktrunk::config::{ProjectConfig, WorktrunkConfig};+use worktrunk::config::{Command, ProjectConfig, WorktrunkConfig};use worktrunk::git::{GitError, GitResultExt, Repository};use worktrunk::styling::{AnstyleStyle, CYAN, CYAN_BOLD, ERROR, ERROR_EMOJI, HINT, HINT_EMOJI, WARNING, WARNING_EMOJI,@@ -19,8 +19,10 @@ struct MergeCommandCollector<'a> {squash_enabled: bool,}-/// Collected commands with project identifier-type CollectedCommands = (Vec<(Option<String>, String)>, String);+/// Commands collected for batch approval with their project identifier+/// - `Vec<Command>`: Commands with both template and (initial) expanded forms+/// - `String`: Project identifier for config lookup+type CollectedCommands = (Vec<Command>, String);impl<'a> MergeCommandCollector<'a> {/// Collect all commands that will be executed during merge@@ -155,6 +157,7 @@ pub fn handle_merge(.collect()?;// Approve all commands in a single batch+ // Commands collected here are not yet expanded - expansion happens later in prepare_project_commandsapprove_command_batch(&all_commands,&project_id,@@ -502,11 +505,6 @@ pub fn run_pre_merge_commands(false,&[("target", target_branch)],"Pre-merge commands",- |_name, command| {- let dim = AnstyleStyle::new().dimmed();- crate::output::progress(format!("{dim}Skipping pre-merge command: {command}{dim:#}"))- .ok();- },)?;for prepared in commands {let label = crate::commands::format_command_label("pre-merge", prepared.name.as_deref());@@ -564,10 +562,6 @@ pub fn execute_post_merge_commands(false,&[("target", target_branch)],"Post-merge commands",- |_name, command| {- let dim = AnstyleStyle::new().dimmed();- crate::output::progress(format!("{dim}Skipping command: {command}{dim:#}")).ok();- },)?;if commands.is_empty() {@@ -636,10 +630,6 @@ pub fn run_pre_commit_commands(false,&extra_vars,"Pre-commit commands",- |_name, command| {- let dim = AnstyleStyle::new().dimmed();- crate::output::progress(format!("{dim}Skipping command: {command}{dim:#}")).ok();- },)?;if commands.is_empty() {diff --git a/src/commands/worktree.rs b/src/commands/worktree.rsindex 4c4a9a5ac..cb4397bcf 100644--- a/src/commands/worktree.rs+++ b/src/commands/worktree.rs@@ -104,8 +104,8 @@ use std::path::PathBuf;use worktrunk::config::{ProjectConfig, WorktrunkConfig};use worktrunk::git::{GitError, GitResultExt, Repository};use worktrunk::styling::{- ADDITION, AnstyleStyle, CYAN, CYAN_BOLD, DELETION, GREEN, GREEN_BOLD, SUCCESS_EMOJI, WARNING,- WARNING_EMOJI, format_bash_with_gutter,+ ADDITION, CYAN, CYAN_BOLD, DELETION, GREEN, GREEN_BOLD, SUCCESS_EMOJI, WARNING, WARNING_EMOJI,+ format_bash_with_gutter,};use super::command_executor::{CommandContext, prepare_project_commands};@@ -452,17 +452,8 @@ pub fn execute_post_create_commands(let repo_root = repo.main_worktree_root()?;let ctx = CommandContext::new(repo, config, branch, worktree_path, &repo_root, force);- let commands = prepare_project_commands(- post_create_config,- &ctx,- false,- &[],- "Post-create commands",- |_name, command| {- let dim = AnstyleStyle::new().dimmed();- crate::output::progress(format!("{dim}Skipping command: {command}{dim:#}")).ok();- },- )?;+ let commands =+ prepare_project_commands(post_create_config, &ctx, false, &[], "Post-create commands")?;if commands.is_empty() {return Ok(());@@ -511,17 +502,8 @@ pub fn spawn_post_start_commands(let repo_root = repo.main_worktree_root()?;let ctx = CommandContext::new(repo, config, branch, worktree_path, &repo_root, force);- let commands = prepare_project_commands(- post_start_config,- &ctx,- false,- &[],- "Post-start commands",- |_name, command| {- let dim = AnstyleStyle::new().dimmed();- crate::output::progress(format!("{dim}Skipping command: {command}{dim:#}")).ok();- },- )?;+ let commands =+ prepare_project_commands(post_start_config, &ctx, false, &[], "Post-start commands")?;if commands.is_empty() {return Ok(());@@ -577,17 +559,8 @@ pub fn execute_post_start_commands_sequential(let repo_root = repo.main_worktree_root()?;let ctx = CommandContext::new(repo, config, branch, worktree_path, &repo_root, force);- let commands = prepare_project_commands(- post_start_config,- &ctx,- false,- &[],- "Post-start commands",- |_name, command| {- let dim = AnstyleStyle::new().dimmed();- crate::output::progress(format!("{dim}Skipping command: {command}{dim:#}")).ok();- },- )?;+ let commands =+ prepare_project_commands(post_start_config, &ctx, false, &[], "Post-start commands")?;if commands.is_empty() {return Ok(());diff --git a/src/config/mod.rs b/src/config/mod.rsindex bd4b05e84..00d097eb6 100644--- a/src/config/mod.rs+++ b/src/config/mod.rs@@ -200,9 +200,40 @@ pub struct ProjectConfig {pub post_merge_command: Option<CommandConfig>,}+/// Represents a command with its template and optionally expanded form+#[derive(Debug, Clone, PartialEq)]+pub struct Command {+ /// Optional name for the command (e.g., "build", "test", or auto-numbered "1", "2")+ pub name: Option<String>,+ /// Template string that may contain variables like {branch}, {worktree}+ pub template: String,+ /// Expanded command with variables substituted (same as template if not expanded yet)+ pub expanded: String,+}++impl Command {+ /// Create a new command from a template (not yet expanded)+ pub fn new(name: Option<String>, template: String) -> Self {+ Self {+ name,+ expanded: template.clone(),+ template,+ }+ }++ /// Create a command with both template and expanded forms+ pub fn with_expansion(name: Option<String>, template: String, expanded: String) -> Self {+ Self {+ name,+ template,+ expanded,+ }+ }+}+/// Configuration for commands - canonical representation///-/// Internally stores commands as `Vec<(Option<name>, command)>` for uniform processing.+/// Internally stores commands as `Vec<Command>` for uniform processing./// Deserializes from three TOML formats:/// - Single string: `post-create-command = "npm install"`/// - Array: `post-create-command = ["npm install", "npm test"]`@@ -215,12 +246,12 @@ pub struct ProjectConfig {/// This canonical form eliminates branching at call sites - code just iterates over commands.#[derive(Debug, Clone, PartialEq)]pub struct CommandConfig {- commands: Vec<(Option<String>, String)>,+ commands: Vec<Command>,}impl CommandConfig {/// Returns the commands as a slice- pub fn commands(&self) -> &[(Option<String>, String)] {+ pub fn commands(&self) -> &[Command] {&self.commands}}@@ -241,15 +272,17 @@ impl<'de> Deserialize<'de> for CommandConfig {let toml = CommandConfigToml::deserialize(deserializer)?;let commands = match toml {- CommandConfigToml::Single(cmd) => vec![(None, cmd)],+ CommandConfigToml::Single(cmd) => vec![Command::new(None, cmd)],CommandConfigToml::Multiple(cmds) => cmds.into_iter().enumerate()- .map(|(i, cmd)| (Some((i + 1).to_string()), cmd))+ .map(|(i, template)| Command::new(Some((i + 1).to_string()), template)).collect(),CommandConfigToml::Named(map) => {// IndexMap preserves insertion order from TOML- map.into_iter().map(|(k, v)| (Some(k), v)).collect()+ map.into_iter()+ .map(|(name, template)| Command::new(Some(name), template))+ .collect()}};Ok(CommandConfig { commands })@@ -265,8 +298,8 @@ impl Serialize for CommandConfig {use serde::ser::SerializeMap;// If single unnamed command, serialize as string- if self.commands.len() == 1 && self.commands[0].0.is_none() {- return self.commands[0].1.serialize(serializer);+ if self.commands.len() == 1 && self.commands[0].name.is_none() {+ return self.commands[0].template.serialize(serializer);}// If all commands are unnamed or numbered 1,2,3..., serialize as array@@ -274,21 +307,22 @@ impl Serialize for CommandConfig {.commands.iter().enumerate()- .all(|(i, (name, _))| name.as_ref().is_none_or(|n| n == &(i + 1).to_string()));+ .all(|(i, cmd)| cmd.name.as_ref().is_none_or(|n| n == &(i + 1).to_string()));if all_numbered {- let cmds: Vec<_> = self.commands.iter().map(|(_, cmd)| cmd).collect();- return cmds.serialize(serializer);+ let templates: Vec<_> = self.commands.iter().map(|cmd| &cmd.template).collect();+ return templates.serialize(serializer);}// Otherwise serialize as named map// At this point, all commands must have names (from Named TOML format)let mut map = serializer.serialize_map(Some(self.commands.len()))?;- for (name, cmd) in &self.commands {- let key = name+ for cmd in &self.commands {+ let key = cmd+ .name.as_ref().expect("named format requires all commands to have names");- map.serialize_entry(key, cmd)?;+ map.serialize_entry(key, &cmd.template)?;}map.end()}@@ -835,7 +869,7 @@ mod tests {let cmd_config = config.post_create_command.unwrap();let commands = cmd_config.commands();assert_eq!(commands.len(), 1);- assert_eq!(commands[0], (None, "npm install".to_string()));+ assert_eq!(commands[0], Command::new(None, "npm install".to_string()));}#[test]@@ -847,9 +881,12 @@ mod tests {assert_eq!(commands.len(), 2);assert_eq!(commands[0],- (Some("1".to_string()), "npm install".to_string())+ Command::new(Some("1".to_string()), "npm install".to_string())+ );+ assert_eq!(+ commands[1],+ Command::new(Some("2".to_string()), "npm test".to_string()));- assert_eq!(commands[1], (Some("2".to_string()), "npm test".to_string()));}#[test]@@ -866,11 +903,11 @@ mod tests {// Preserves TOML insertion orderassert_eq!(commands[0],- (Some("server".to_string()), "npm run dev".to_string())+ Command::new(Some("server".to_string()), "npm run dev".to_string()));assert_eq!(commands[1],- (Some("watch".to_string()), "npm run watch".to_string())+ Command::new(Some("watch".to_string()), "npm run watch".to_string()));}@@ -890,7 +927,7 @@ mod tests {// Extract just the names for easier verificationlet names: Vec<_> = commands.iter()- .map(|(n, _)| n.as_deref().unwrap())+ .map(|cmd| cmd.name.as_deref().unwrap()).collect();// Verify TOML insertion order is preserved@@ -920,12 +957,12 @@ task2 = "echo 'Task 2 running' > task2.txt"assert_eq!(commands.len(), 2);// Should be in TOML order: task1, task2assert_eq!(- commands[0].0.as_deref(),+ commands[0].name.as_deref(),Some("task1"),"First command should be task1");assert_eq!(- commands[1].0.as_deref(),+ commands[1].name.as_deref(),Some("task2"),"Second command should be task2");@@ -951,7 +988,7 @@ task2 = "echo 'Task 2 running' > task2.txt"let cmd_config = config.pre_merge_command.unwrap();let commands = cmd_config.commands();assert_eq!(commands.len(), 1);- assert_eq!(commands[0], (None, "cargo test".to_string()));+ assert_eq!(commands[0], Command::new(None, "cargo test".to_string()));}#[test]@@ -963,11 +1000,11 @@ task2 = "echo 'Task 2 running' > task2.txt"assert_eq!(commands.len(), 2);assert_eq!(commands[0],- (Some("1".to_string()), "cargo fmt -- --check".to_string())+ Command::new(Some("1".to_string()), "cargo fmt -- --check".to_string()));assert_eq!(commands[1],- (Some("2".to_string()), "cargo test".to_string())+ Command::new(Some("2".to_string()), "cargo test".to_string()));}@@ -986,18 +1023,18 @@ task2 = "echo 'Task 2 running' > task2.txt"// Preserves TOML insertion orderassert_eq!(commands[0],- (+ Command::new(Some("format".to_string()),"cargo fmt -- --check".to_string()));assert_eq!(commands[1],- (Some("lint".to_string()), "cargo clippy".to_string())+ Command::new(Some("lint".to_string()), "cargo clippy".to_string()));assert_eq!(commands[2],- (Some("test".to_string()), "cargo test".to_string())+ Command::new(Some("test".to_string()), "cargo test".to_string()));}diff --git a/tests/integration_tests/approval_ui.rs b/tests/integration_tests/approval_ui.rsnew file mode 100644index 000000000..8430dc253--- /dev/null+++ b/tests/integration_tests/approval_ui.rs@@ -0,0 +1,255 @@+//! Tests for command approval UI++use crate::common::{TestRepo, make_snapshot_cmd, setup_snapshot_settings};+use insta_cmd::assert_cmd_snapshot;+use std::fs;+use std::io::Write;+use std::process::{Command, Stdio};++/// Helper to create snapshot with test environment+fn snapshot_approval(test_name: &str, repo: &TestRepo, args: &[&str], approve: bool) {+ let settings = setup_snapshot_settings(repo);+ settings.bind(|| {+ let mut cmd = make_snapshot_cmd(repo, "switch", args, None);+ cmd.stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());++ let mut child = cmd.spawn().expect("Failed to spawn command");++ // Write approval response+ {+ let stdin = child.stdin.as_mut().expect("Failed to get stdin");+ let response = if approve { b"y\n" } else { b"n\n" };+ stdin.write_all(response).expect("Failed to write to stdin");+ }++ let output = child+ .wait_with_output()+ .expect("Failed to wait for command");++ // Use insta snapshot for combined output+ let stdout = String::from_utf8_lossy(&output.stdout);+ let stderr = String::from_utf8_lossy(&output.stderr);+ let combined = format!(+ "exit_code: {}\n----- stdout -----\n{}\n----- stderr -----\n{}",+ output.status.code().unwrap_or(-1),+ stdout,+ stderr+ );++ insta::assert_snapshot!(test_name, combined);+ });+}++#[test]+fn test_approval_single_command() {+ let repo = TestRepo::new();+ repo.commit("Initial commit");++ let config_dir = repo.root_path().join(".config");+ fs::create_dir_all(&config_dir).expect("Failed to create .config dir");+ fs::write(+ config_dir.join("wt.toml"),+ r#"post-create-command = "echo 'Worktree path: {worktree}'""#,+ )+ .expect("Failed to write config");++ repo.commit("Add config");++ snapshot_approval(+ "approval_single_command",+ &repo,+ &["--create", "feature/test-approval"],+ false,+ );+}++#[test]+fn test_approval_multiple_commands() {+ let repo = TestRepo::new();+ repo.commit("Initial commit");++ let config_dir = repo.root_path().join(".config");+ fs::create_dir_all(&config_dir).expect("Failed to create .config dir");+ fs::write(+ config_dir.join("wt.toml"),+ r#"post-create-command = [+ "echo 'Branch: {branch}'",+ "echo 'Worktree: {worktree}'",+ "echo 'Repo: {main-worktree}'",+ "cd {worktree} && pwd"+]"#,+ )+ .expect("Failed to write config");++ repo.commit("Add config");++ snapshot_approval(+ "approval_multiple_commands",+ &repo,+ &["--create", "test/nested-branch"],+ false,+ );+}++#[test]+fn test_approval_mixed_approved_unapproved() {+ let repo = TestRepo::new();+ repo.commit("Initial commit");++ let config_dir = repo.root_path().join(".config");+ fs::create_dir_all(&config_dir).expect("Failed to create .config dir");+ fs::write(+ config_dir.join("wt.toml"),+ r#"post-create-command = [+ "echo 'First command'",+ "echo 'Second command'",+ "echo 'Third command'"+]"#,+ )+ .expect("Failed to write config");++ repo.commit("Add config");++ // Pre-approve the second command+ let project_id = repo.root_path().file_name().unwrap().to_str().unwrap();+ fs::write(+ repo.test_config_path(),+ format!(+ r#"[projects."{}"]+approved-commands = ["echo 'Second command'"]+"#,+ project_id+ ),+ )+ .expect("Failed to write test config");++ snapshot_approval(+ "approval_mixed_approved_unapproved",+ &repo,+ &["--create", "test-mixed"],+ false,+ );+}++#[test]+fn test_force_flag_does_not_save_approvals() {+ let repo = TestRepo::new();+ repo.commit("Initial commit");++ let config_dir = repo.root_path().join(".config");+ fs::create_dir_all(&config_dir).expect("Failed to create .config dir");+ fs::write(+ config_dir.join("wt.toml"),+ r#"post-create-command = "echo 'test command' > output.txt""#,+ )+ .expect("Failed to write config");++ repo.commit("Add config");++ // Run with --force+ let settings = setup_snapshot_settings(&repo);+ settings.bind(|| {+ let mut cmd = make_snapshot_cmd(+ &repo,+ "switch",+ &["--create", "test-force", "--force"],+ None,+ );+ assert_cmd_snapshot!("force_does_not_save_approvals_first_run", cmd);+ });++ // Clean up the worktree+ let mut cmd = Command::new(insta_cmd::get_cargo_bin("wt"));+ repo.clean_cli_env(&mut cmd);+ cmd.arg("remove")+ .arg("test-force")+ .arg("--force")+ .current_dir(repo.root_path());+ cmd.output().expect("Failed to remove worktree");++ // Run again WITHOUT --force - should prompt+ snapshot_approval(+ "force_does_not_save_approvals_second_run",+ &repo,+ &["--create", "test-force-2"],+ false,+ );+}++#[test]+fn test_already_approved_commands_skip_prompt() {+ let repo = TestRepo::new();+ repo.commit("Initial commit");++ let config_dir = repo.root_path().join(".config");+ fs::create_dir_all(&config_dir).expect("Failed to create .config dir");+ fs::write(+ config_dir.join("wt.toml"),+ r#"post-create-command = "echo 'approved' > output.txt""#,+ )+ .expect("Failed to write config");++ repo.commit("Add config");++ // Pre-approve the command+ let project_id = repo.root_path().file_name().unwrap().to_str().unwrap();+ fs::write(+ repo.test_config_path(),+ format!(+ r#"[projects."{}"]+approved-commands = ["echo 'approved' > output.txt"]+"#,+ project_id+ ),+ )+ .expect("Failed to write test config");++ // Should execute without prompting+ let settings = setup_snapshot_settings(&repo);+ settings.bind(|| {+ let mut cmd = make_snapshot_cmd(&repo, "switch", &["--create", "test-approved"], None);+ assert_cmd_snapshot!("already_approved_skip_prompt", cmd);+ });+}++#[test]+fn test_decline_approval_skips_only_unapproved() {+ let repo = TestRepo::new();+ repo.commit("Initial commit");++ let config_dir = repo.root_path().join(".config");+ fs::create_dir_all(&config_dir).expect("Failed to create .config dir");+ fs::write(+ config_dir.join("wt.toml"),+ r#"post-create-command = [+ "echo 'First command'",+ "echo 'Second command'",+ "echo 'Third command'"+]"#,+ )+ .expect("Failed to write config");++ repo.commit("Add config");++ // Pre-approve the second command+ let project_id = repo.root_path().file_name().unwrap().to_str().unwrap();+ fs::write(+ repo.test_config_path(),+ format!(+ r#"[projects."{}"]+approved-commands = ["echo 'Second command'"]+"#,+ project_id+ ),+ )+ .expect("Failed to write test config");++ snapshot_approval(+ "decline_approval_skips_only_unapproved",+ &repo,+ &["--create", "test-decline"],+ false,+ );+}diff --git a/tests/integration_tests/mod.rs b/tests/integration_tests/mod.rsindex 6c62f1114..938ab1675 100644--- a/tests/integration_tests/mod.rs+++ b/tests/integration_tests/mod.rs@@ -1,5 +1,6 @@// column_alignment merged into spacing_edge_casespub mod approval_save;+pub mod approval_ui;pub mod column_alignment_verification;pub mod completion;pub mod completion_validation;diff --git a/tests/snapshots/integration__integration_tests__approval_ui__already_approved.snap b/tests/snapshots/integration__integration_tests__approval_ui__already_approved.snapnew file mode 100644index 000000000..d1c012a8a--- /dev/null+++ b/tests/snapshots/integration__integration_tests__approval_ui__already_approved.snap@@ -0,0 +1,33 @@+---+source: tests/integration_tests/approval_ui.rs+info:+ program: wt+ args:+ - switch+ - "--create"+ - test-approved+ env:+ CLICOLOR_FORCE: "1"+ COLUMNS: "150"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: /dev/null+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1761609600"+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpi1XuqH/test-config.toml+---+success: true+exit_code: 0+----- stdout -----+π [36mRunning post-create:[0m+[40m [0m [1m[34mecho[0m [32m'approved'[0m [36m>[0m output.txt[0m++β [32mCreated new worktree for [1m[32mtest-approved[0m[32m at [1m[32m[REPO].test-approved[0m[0m++To enable automatic cd, run: wt config shell++----- stderr -----+[0mdiff --git a/tests/snapshots/integration__integration_tests__approval_ui__already_approved_skip_prompt.snap b/tests/snapshots/integration__integration_tests__approval_ui__already_approved_skip_prompt.snapnew file mode 100644index 000000000..7b80b6edc--- /dev/null+++ b/tests/snapshots/integration__integration_tests__approval_ui__already_approved_skip_prompt.snap@@ -0,0 +1,33 @@+---+source: tests/integration_tests/approval_ui.rs+info:+ program: wt+ args:+ - switch+ - "--create"+ - test-approved+ env:+ CLICOLOR_FORCE: "1"+ COLUMNS: "150"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: /dev/null+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1761609600"+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpBnYBfI/test-config.toml+---+success: true+exit_code: 0+----- stdout -----+π [36mRunning post-create:[0m+[40m [0m [1m[34mecho[0m [32m'approved'[0m [36m>[0m output.txt[0m++β [32mCreated new worktree for [1m[32mtest-approved[0m[32m from [1m[32mmain[0m[32m at [1m[32m[REPO].test-approved[0m[0m++To enable automatic cd, run: wt config shell++----- stderr -----+[0mdiff --git a/tests/snapshots/integration__integration_tests__approval_ui__approval_mixed_approved_unapproved.snap b/tests/snapshots/integration__integration_tests__approval_ui__approval_mixed_approved_unapproved.snapnew file mode 100644index 000000000..fa10e1243--- /dev/null+++ b/tests/snapshots/integration__integration_tests__approval_ui__approval_mixed_approved_unapproved.snap@@ -0,0 +1,24 @@+---+source: tests/integration_tests/approval_ui.rs+expression: combined+---+exit_code: 0+----- stdout -----++π‘ [33mPermission required to execute [1m[33m2[0m commands[0m++[1mtest-repo[0m ([2mtest-repo[0m) wants to execute:++[40m [0m [1m[34mecho[0m [32m'First command'[0m[0m++[1mtest-repo[0m ([2mtest-repo[0m) wants to execute:++[40m [0m [1m[34mecho[0m [32m'Third command'[0m[0m++π‘ Allow and remember? [1m[y/N][0m+[2mPost-create commands declined[0m+β [32mCreated new worktree for [1m[32mtest-mixed[0m[32m from [1m[32mmain[0m[32m at [1m[32m[REPO].test-mixed[0m[0m++To enable automatic cd, run: wt config shell++----- stderr -----diff --git a/tests/snapshots/integration__integration_tests__approval_ui__approval_multiple_commands.snap b/tests/snapshots/integration__integration_tests__approval_ui__approval_multiple_commands.snapnew file mode 100644index 000000000..7bf0a01d7--- /dev/null+++ b/tests/snapshots/integration__integration_tests__approval_ui__approval_multiple_commands.snap@@ -0,0 +1,32 @@+---+source: tests/integration_tests/approval_ui.rs+expression: combined+---+exit_code: 0+----- stdout -----++π‘ [33mPermission required to execute [1m[33m4[0m commands[0m++[1mtest-repo[0m ([2mtest-repo[0m) wants to execute:++[40m [0m [1m[34mecho[0m [32m'Branch: test-nested-branch'[0m[0m++[1mtest-repo[0m ([2mtest-repo[0m) wants to execute:++[40m [0m [1m[34mecho[0m [32m'Worktree: [REPO].test-nested-branch'[0m[0m++[1mtest-repo[0m ([2mtest-repo[0m) wants to execute:++[40m [0m [1m[34mecho[0m [32m'Repo: test-repo'[0m[0m++[1mtest-repo[0m ([2mtest-repo[0m) wants to execute:++[40m [0m [1m[34mcd[0m [REPO].test-nested-branch [36m&&[0m [1m[34mpwd[0m[0m++π‘ Allow and remember? [1m[y/N][0m+[2mPost-create commands declined[0m+β [32mCreated new worktree for [1m[32mtest/nested-branch[0m[32m from [1m[32mmain[0m[32m at [1m[32m[REPO].test-nested-branch[0m[0m++To enable automatic cd, run: wt config shell++----- stderr -----diff --git a/tests/snapshots/integration__integration_tests__approval_ui__approval_single_command.snap b/tests/snapshots/integration__integration_tests__approval_ui__approval_single_command.snapnew file mode 100644index 000000000..3964c1007--- /dev/null+++ b/tests/snapshots/integration__integration_tests__approval_ui__approval_single_command.snap@@ -0,0 +1,20 @@+---+source: tests/integration_tests/approval_ui.rs+expression: combined+---+exit_code: 0+----- stdout -----++π‘ [33mPermission required to execute [1m[33m1[0m command[0m++[1mtest-repo[0m ([2mtest-repo[0m) wants to execute:++[40m [0m [1m[34mecho[0m [32m'Worktree path: [REPO].feature-test-approval'[0m[0m++π‘ Allow and remember? [1m[y/N][0m+[2mPost-create commands declined[0m+β [32mCreated new worktree for [1m[32mfeature/test-approval[0m[32m from [1m[32mmain[0m[32m at [1m[32m[REPO].feature-test-approval[0m[0m++To enable automatic cd, run: wt config shell++----- stderr -----diff --git a/tests/snapshots/integration__integration_tests__approval_ui__decline_approval_skips_only_unapproved.snap b/tests/snapshots/integration__integration_tests__approval_ui__decline_approval_skips_only_unapproved.snapnew file mode 100644index 000000000..5010e040f--- /dev/null+++ b/tests/snapshots/integration__integration_tests__approval_ui__decline_approval_skips_only_unapproved.snap@@ -0,0 +1,24 @@+---+source: tests/integration_tests/approval_ui.rs+expression: combined+---+exit_code: 0+----- stdout -----++π‘ [33mPermission required to execute [1m[33m2[0m commands[0m++[1mtest-repo[0m ([2mtest-repo[0m) wants to execute:++[40m [0m [1m[34mecho[0m [32m'First command'[0m[0m++[1mtest-repo[0m ([2mtest-repo[0m) wants to execute:++[40m [0m [1m[34mecho[0m [32m'Third command'[0m[0m++π‘ Allow and remember? [1m[y/N][0m+[2mPost-create commands declined[0m+β [32mCreated new worktree for [1m[32mtest-decline[0m[32m from [1m[32mmain[0m[32m at [1m[32m[REPO].test-decline[0m[0m++To enable automatic cd, run: wt config shell++----- stderr -----diff --git a/tests/snapshots/integration__integration_tests__approval_ui__force_does_not_save_approvals_first_run.snap b/tests/snapshots/integration__integration_tests__approval_ui__force_does_not_save_approvals_first_run.snapnew file mode 100644index 000000000..03ef94b0d--- /dev/null+++ b/tests/snapshots/integration__integration_tests__approval_ui__force_does_not_save_approvals_first_run.snap@@ -0,0 +1,34 @@+---+source: tests/integration_tests/approval_ui.rs+info:+ program: wt+ args:+ - switch+ - "--create"+ - test-force+ - "--force"+ env:+ CLICOLOR_FORCE: "1"+ COLUMNS: "150"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: /dev/null+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1761609600"+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpoE9OYj/test-config.toml+---+success: true+exit_code: 0+----- stdout -----+π [36mRunning post-create:[0m+[40m [0m [1m[34mecho[0m [32m'test command'[0m [36m>[0m output.txt[0m++β [32mCreated new worktree for [1m[32mtest-force[0m[32m from [1m[32mmain[0m[32m at [1m[32m[REPO].test-force[0m[0m++To enable automatic cd, run: wt config shell++----- stderr -----+[0mdiff --git a/tests/snapshots/integration__integration_tests__approval_ui__force_does_not_save_approvals_second_run.snap b/tests/snapshots/integration__integration_tests__approval_ui__force_does_not_save_approvals_second_run.snapnew file mode 100644index 000000000..8348a0e49--- /dev/null+++ b/tests/snapshots/integration__integration_tests__approval_ui__force_does_not_save_approvals_second_run.snap@@ -0,0 +1,20 @@+---+source: tests/integration_tests/approval_ui.rs+expression: combined+---+exit_code: 0+----- stdout -----++π‘ [33mPermission required to execute [1m[33m1[0m command[0m++[1mtest-repo[0m ([2mtest-repo[0m) wants to execute:++[40m [0m [1m[34mecho[0m [32m'test command'[0m [36m>[0m output.txt[0m++π‘ Allow and remember? [1m[y/N][0m+[2mPost-create commands declined[0m+β [32mCreated new worktree for [1m[32mtest-force-2[0m[32m from [1m[32mmain[0m[32m at [1m[32m[REPO].test-force-2[0m[0m++To enable automatic cd, run: wt config shell++----- stderr -----diff --git a/tests/snapshots/integration__integration_tests__approval_ui__force_first_run.snap b/tests/snapshots/integration__integration_tests__approval_ui__force_first_run.snapnew file mode 100644index 000000000..963acdd87--- /dev/null+++ b/tests/snapshots/integration__integration_tests__approval_ui__force_first_run.snap@@ -0,0 +1,34 @@+---+source: tests/integration_tests/approval_ui.rs+info:+ program: wt+ args:+ - switch+ - "--create"+ - test-force+ - "--force"+ env:+ CLICOLOR_FORCE: "1"+ COLUMNS: "150"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: /dev/null+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1761609600"+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpIZ3rwP/test-config.toml+---+success: true+exit_code: 0+----- stdout -----+π [36mRunning post-create:[0m+[40m [0m [1m[34mecho[0m [32m'test command'[0m [36m>[0m output.txt[0m++β [32mCreated new worktree for [1m[32mtest-force[0m[32m at [1m[32m[REPO].test-force[0m[0m++To enable automatic cd, run: wt config shell++----- stderr -----+[0m