Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Feat: Improve LLM command error messages
Maximilian Roos8b62fc0ab2e4
diff --git a/CLAUDE.md b/CLAUDE.mdindex 77c84e59a..77e17b6c3 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -370,6 +370,25 @@ output::gutter(format_with_gutter(&log, "", None))?;output::progress(format!("{CYAN}Merging...{CYAN:#}\n"))?;```+### External Command Error Formatting++When external commands (user-configured commands like LLM tools, hooks) fail, error messages must:+1. **Show the command that was run** - Include the full command with arguments so users can debug+2. **Put error output in a gutter** - Don't embed raw stderr inline in the message++Use the `format_error_block` helper in `src/git/error.rs` or follow its pattern:++```rust+// ✅ GOOD - command shown in header, error in gutter+❌ Commit generation command 'llm --model claude' failed+ ┃ Error: [Errno 8] nodename nor servname provided, or not known++// ❌ BAD - error embedded inline, command not shown+❌ Commit generation command 'llm' failed: LLM command failed: Error: [Errno 8]...+```++**Implementation:** See `format_error_block()` in `src/git/error.rs` for the pattern, and `llm_command_failed()` for an example.+### Table Column Alignment**Principle: Headers and values align consistently within each column type.**@@ -390,34 +409,7 @@ Column alignment follows standard tabular data conventions:### Snapshot Testing Requirement-Every command output must have a snapshot test (`tests/integration_tests/`). Use this pattern:--```rust-use crate::common::{TestRepo, make_snapshot_cmd, setup_snapshot_settings};-use insta_cmd::assert_cmd_snapshot;-use std::path::Path;--fn snapshot_remove(test_name: &str, repo: &TestRepo, args: &[&str], cwd: Option<&Path>) {- let settings = setup_snapshot_settings(repo);- settings.bind(|| {- let mut cmd = make_snapshot_cmd(repo, "remove", args, cwd);- assert_cmd_snapshot!(test_name, cmd);- });-}--fn setup_remove_repo() -> TestRepo {- let mut repo = TestRepo::new();- repo.commit("Initial commit");- repo.setup_remote("main");- repo-}--#[test]-fn test_remove_success() {- let repo = setup_remove_repo();- snapshot_remove("remove_success", &repo, &[], None);-}-```+Every command output must have a snapshot test (`tests/integration_tests/`). See `tests/integration_tests/remove.rs` for the standard pattern using `setup_snapshot_settings()`, `make_snapshot_cmd()`, and `assert_cmd_snapshot!()`.Cover success/error states, with/without data, and flag variations.diff --git a/src/commands/standalone.rs b/src/commands/standalone.rsindex dc2e504bd..375a746a1 100644--- a/src/commands/standalone.rs+++ b/src/commands/standalone.rs@@ -240,8 +240,7 @@ pub fn handle_squash(¤t_branch,repo_name,&env.config.commit_generation,- )- .context("Failed to generate commit message")?;+ )?;// Display the generated commit messagelet formatted_message = generator.format_message_for_display(&commit_message);diff --git a/src/git/error.rs b/src/git/error.rsindex de09626b1..51205fa34 100644--- a/src/git/error.rs+++ b/src/git/error.rs@@ -8,7 +8,7 @@ use std::path::Path;use super::HookType;use crate::path::format_path_for_display;use crate::styling::{- ERROR, ERROR_BOLD, ERROR_EMOJI, HINT, HINT_BOLD, HINT_EMOJI, format_with_gutter,+ ERROR, ERROR_BOLD, ERROR_EMOJI, HINT, HINT_BOLD, HINT_EMOJI, INFO_EMOJI, format_with_gutter,};/// Semantic errors that require special handling in main.rs@@ -253,3 +253,24 @@ pub fn branch_deletion_failed(branch: &str, error: &str) -> anyhow::Error {);anyhow::anyhow!("{}", format_error_block(header, error))}++/// LLM command failed error+///+/// `command` is the full command string (e.g., "llm --model claude")+/// `error` is the stderr output from the command+pub fn llm_command_failed(command: &str, error: &str) -> anyhow::Error {+ let error_header = format!("{ERROR_EMOJI} {ERROR}Commit generation command failed{ERROR:#}");+ let error_block = format_error_block(error_header, error);++ // Build message: error block + blank line separator + info block+ // Trim trailing newlines since output system adds one via println!+ let command_gutter = format_with_gutter(command, "", None);++ let mut msg = error_block.trim_end().to_string();+ msg.push_str("\n\n"); // "One blank after blocks"+ msg.push_str(INFO_EMOJI);+ msg.push_str(" Ran command:\n");+ msg.push_str(command_gutter.trim_end());++ anyhow::anyhow!("{}", msg)+}diff --git a/src/git/mod.rs b/src/git/mod.rsindex f4b6ed911..41212a3eb 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -32,10 +32,10 @@ static HEAVY_OPS_SEMAPHORE: LazyLock<semaphore::Semaphore> =pub use diff::{DiffStats, LineDiff};pub use error::{WorktrunkError, branch_already_exists, branch_deletion_failed, conflicting_changes,- detached_head, error_message, exit_code, is_command_not_approved, merge_commits_found,- no_worktree_found, not_interactive, parse_error, push_failed, rebase_conflict,- uncommitted_changes, worktree_creation_failed, worktree_missing, worktree_path_exists,- worktree_path_occupied, worktree_removal_failed,+ detached_head, error_message, exit_code, is_command_not_approved, llm_command_failed,+ merge_commits_found, no_worktree_found, not_interactive, parse_error, push_failed,+ rebase_conflict, uncommitted_changes, worktree_creation_failed, worktree_missing,+ worktree_path_exists, worktree_path_occupied, worktree_removal_failed,};pub use repository::{Repository, set_base_path};diff --git a/src/llm.rs b/src/llm.rsindex 04389d7b7..db02378a8 100644--- a/src/llm.rs+++ b/src/llm.rs@@ -2,7 +2,7 @@ use std::io::Write;use std::path::{Path, PathBuf};use std::process::{self, Stdio};use worktrunk::config::CommitGenerationConfig;-use worktrunk::git::Repository;+use worktrunk::git::{Repository, llm_command_failed};use worktrunk::path::format_path_for_display;use minijinja::Environment;@@ -13,6 +13,15 @@ struct PromptContext<'a> {repo_name: &'a str,}+/// Format a command and its arguments into a display string+fn format_command_display(command: &str, args: &[String]) -> String {+ if args.is_empty() {+ command.to_string()+ } else {+ format!("{} {}", command, args.join(" "))+ }+}+/// Default template for commit message prompts////// Synced to dev/config.example.toml by `cargo test readme_sync`@@ -103,7 +112,7 @@ fn execute_llm_command(command: &str, args: &[String], prompt: &str) -> anyhow::if !output.status.success() {let stderr = String::from_utf8_lossy(&output.stderr);- anyhow::bail!("LLM command failed: {}", stderr);+ anyhow::bail!("{}", stderr.trim());}let message = String::from_utf8_lossy(&output.stdout).trim().to_owned();@@ -216,17 +225,10 @@ pub fn generate_commit_message(// Check if commit generation is configured (non-empty command)if commit_generation_config.is_configured() {let command = commit_generation_config.command.as_ref().unwrap();+ let args = &commit_generation_config.args;// Commit generation is explicitly configured - fail if it doesn't work- return try_generate_commit_message(- command,- &commit_generation_config.args,- commit_generation_config,- )- .map_err(|e| {- anyhow::anyhow!(format!(- "Commit generation command '{}' failed: {}",- command, e- ))+ return try_generate_commit_message(command, args, commit_generation_config).map_err(|e| {+ llm_command_failed(&format_command_display(command, args), &e.to_string())});}@@ -311,6 +313,7 @@ pub fn generate_squash_message(// Check if commit generation is configured (non-empty command)if commit_generation_config.is_configured() {let command = commit_generation_config.command.as_ref().unwrap();+ let args = &commit_generation_config.args;// Commit generation is explicitly configured - fail if it doesn't worklet context = PromptContext {branch: current_branch,@@ -318,7 +321,9 @@ pub fn generate_squash_message(};let prompt =build_squash_prompt(commit_generation_config, target_branch, subjects, &context)?;- return execute_llm_command(command, &commit_generation_config.args, &prompt);+ return execute_llm_command(command, args, &prompt).map_err(|e| {+ llm_command_failed(&format_command_display(command, args), &e.to_string())+ });}// Fallback: deterministic commit message (only when not configured)diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rsindex caa82eb85..7504d75a2 100644--- a/tests/integration_tests/merge.rs+++ b/tests/integration_tests/merge.rs@@ -659,6 +659,72 @@ fn test_merge_squash_llm_fallback() {);}+#[test]+fn test_merge_squash_llm_error() {+ // Test that LLM command errors show proper gutter formatting with full command+ let mut repo = TestRepo::new();+ repo.commit("Initial commit");+ repo.setup_remote("main");++ // Create a worktree for main+ let main_wt = repo.root_path().parent().unwrap().join("test-repo.main-wt");+ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["worktree", "add", main_wt.to_str().unwrap(), "main"])+ .current_dir(repo.root_path())+ .output()+ .unwrap();++ // Create a feature worktree and make commits+ let feature_wt = repo.add_worktree("feature", "feature");++ std::fs::write(feature_wt.join("file1.txt"), "content 1").unwrap();+ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["add", "file1.txt"])+ .current_dir(&feature_wt)+ .output()+ .unwrap();+ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["commit", "-m", "feat: new feature"])+ .current_dir(&feature_wt)+ .output()+ .unwrap();++ std::fs::write(feature_wt.join("file2.txt"), "content 2").unwrap();+ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["add", "file2.txt"])+ .current_dir(&feature_wt)+ .output()+ .unwrap();+ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["commit", "-m", "fix: bug fix"])+ .current_dir(&feature_wt)+ .output()+ .unwrap();++ // Configure LLM command via config file with command that will fail+ // This tests that:+ // 1. The full command (with args) is shown in the error header+ // 2. The error output appears in a gutter+ let worktrunk_config = r#"+[commit-generation]+command = "sh"+args = ["-c", "echo 'Error: connection refused' >&2 && exit 1"]+"#;+ fs::write(repo.test_config_path(), worktrunk_config).unwrap();++ snapshot_merge(+ "merge_squash_llm_error",+ &repo,+ &["main"],+ Some(&feature_wt),+ );+}+#[test]fn test_merge_squash_single_commit() {let mut repo = TestRepo::new();diff --git a/tests/snapshots/integration__integration_tests__merge__merge_squash_llm_error.snap b/tests/snapshots/integration__integration_tests__merge__merge_squash_llm_error.snapnew file mode 100644index 000000000..d1fac1ec5--- /dev/null+++ b/tests/snapshots/integration__integration_tests__merge__merge_squash_llm_error.snap@@ -0,0 +1,33 @@+---+source: tests/integration_tests/merge.rs+info:+ program: wt+ args:+ - merge+ - main+ 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: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1761609600"+ WORKTRUNK_BIN: ""+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+---+success: false+exit_code: 1+----- stdout -----+🔄 [36mSquashing 2 commits into a single commit[0m (2 files, [32m+2[0m)...+🔄 [36mGenerating squash commit message...[0m+❌ [31mCommit generation command failed[0m+[107m [0m Error: connection refused++⚪ Ran command:+[107m [0m sh -c echo 'Error: connection refused' >&2 && exit 1++----- stderr -----