Skip to content

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

Add LLM setup prompt for first-time commit configuration (#867)

Maximilian Roose154b9ee5075
diff --git a/.claude-plugin/skills/worktrunk/reference/config.md b/.claude-plugin/skills/worktrunk/reference/config.md
index dace7aaa8..fb6496736 100644
--- a/.claude-plugin/skills/worktrunk/reference/config.md
+++ b/.claude-plugin/skills/worktrunk/reference/config.md
@@ -206,7 +206,8 @@ template = """
Write a commit message for the staged changes below.
<format>
-- Subject under 50 chars, blank line, then optional body
+- Subject line under 50 chars
+- For material changes, add a blank line then a body paragraph explaining the change
- Output only the commit message, no quotes or code blocks
</format>
@@ -251,7 +252,8 @@ squash-template = """
Combine these commits into a single commit message.
<format>
-- Subject under 50 chars, blank line, then optional body
+- Subject line under 50 chars
+- For material changes, add a blank line then a body paragraph explaining the change
- Output only the commit message, no quotes or code blocks
</format>
@@ -325,9 +327,9 @@ wt config shell init fish | source
Without shell integration, `wt switch` prints the target directory but cannot `cd` into it.
-### Skip first-run prompt
+### First-run prompts
-On first run without shell integration, Worktrunk offers to install it. Declining sets `skip-shell-integration-prompt = true` automatically.
+On first run without shell integration, Worktrunk offers to install it. Similarly, on first commit without LLM configuration, it offers to configure a detected tool (`claude`, `codex`). Declining sets `skip-shell-integration-prompt` or `skip-commit-generation-prompt` automatically.
# Other
diff --git a/.claude-plugin/skills/worktrunk/reference/llm-commits.md b/.claude-plugin/skills/worktrunk/reference/llm-commits.md
index 6edee2658..2d1b82df6 100644
--- a/.claude-plugin/skills/worktrunk/reference/llm-commits.md
+++ b/.claude-plugin/skills/worktrunk/reference/llm-commits.md
@@ -10,7 +10,7 @@ Any command that reads a prompt from stdin and outputs a commit message works. A
```toml
[commit.generation]
-command = "MAX_THINKING_TOKENS=0 claude -p --model haiku --tools '' --disable-slash-commands --setting-sources '' --system-prompt ''"
+command = "MAX_THINKING_TOKENS=0 claude -p --model=haiku --tools='' --disable-slash-commands --setting-sources='' --system-prompt=''"
```
The flags disable tools, skills, settings, and system prompt for fast text-only output. See [Claude Code docs](https://docs.anthropic.com/en/docs/build-with-claude/claude-code) for installation.
@@ -37,7 +37,7 @@ See [aichat docs](https://github.com/sigoden/aichat).
```toml
[commit.generation]
-command = "codex exec -m gpt-5.1-codex-mini -c model_reasoning_effort='low' --sandbox read-only --json - | jq -sr '[.[] | select(.item.type? == \"agent_message\")] | last.item.text'"
+command = "codex exec -m gpt-5.1-codex-mini -c model_reasoning_effort='low' --sandbox=read-only --json - | jq -sr '[.[] | select(.item.type? == \"agent_message\")] | last.item.text'"
```
Uses the fast mini model with low reasoning effort. Requires `jq` for JSON parsing. See [Codex CLI docs](https://developers.openai.com/codex/cli/).
diff --git a/Taskfile.yaml b/Taskfile.yaml
index 60e150489..733f7ec47 100644
--- a/Taskfile.yaml
+++ b/Taskfile.yaml
@@ -385,10 +385,10 @@ tasks:
# Documented commands from llm-commits.md
declare -A COMMANDS
- COMMANDS["claude"]='MAX_THINKING_TOKENS=0 claude -p --model haiku --tools '"'"''"'"' --disable-slash-commands --setting-sources '"'"''"'"' --system-prompt '"'"''"'"''
+ COMMANDS["claude"]='MAX_THINKING_TOKENS=0 claude -p --model=haiku --tools='"'"''"'"' --disable-slash-commands --setting-sources='"'"''"'"' --system-prompt='"'"''"'"''
COMMANDS["llm"]='llm -m claude-haiku-4.5'
COMMANDS["aichat"]='aichat -m claude:claude-haiku-4.5'
- COMMANDS["codex"]='codex exec -m gpt-5.1-codex-mini -c model_reasoning_effort='"'"'low'"'"' --sandbox read-only --json - | jq -sr '"'"'[.[] | select(.item.type? == "agent_message")] | last.item.text'"'"''
+ COMMANDS["codex"]='codex exec -m gpt-5.1-codex-mini -c model_reasoning_effort='"'"'low'"'"' --sandbox=read-only --json - | jq -sr '"'"'[.[] | select(.item.type? == "agent_message")] | last.item.text'"'"''
# Check which tools are available
echo "=== LLM Commit Message Benchmark ==="
diff --git a/dev/config.example.toml b/dev/config.example.toml
index 49abff16e..b6a7ce830 100644
--- a/dev/config.example.toml
+++ b/dev/config.example.toml
@@ -130,7 +130,8 @@
# Write a commit message for the staged changes below.
#
# <format>
-# - Subject under 50 chars, blank line, then optional body
+# - Subject line under 50 chars
+# - For material changes, add a blank line then a body paragraph explaining the change
# - Output only the commit message, no quotes or code blocks
# </format>
#
@@ -173,7 +174,8 @@
# Combine these commits into a single commit message.
#
# <format>
-# - Subject under 50 chars, blank line, then optional body
+# - Subject line under 50 chars
+# - For material changes, add a blank line then a body paragraph explaining the change
# - Output only the commit message, no quotes or code blocks
# </format>
#
diff --git a/docs/content/config.md b/docs/content/config.md
index 78a5a7276..0e71cbaf1 100644
--- a/docs/content/config.md
+++ b/docs/content/config.md
@@ -214,7 +214,8 @@ template = """
Write a commit message for the staged changes below.
<format>
-- Subject under 50 chars, blank line, then optional body
+- Subject line under 50 chars
+- For material changes, add a blank line then a body paragraph explaining the change
- Output only the commit message, no quotes or code blocks
</format>
@@ -259,7 +260,8 @@ squash-template = """
Combine these commits into a single commit message.
<format>
-- Subject under 50 chars, blank line, then optional body
+- Subject line under 50 chars
+- For material changes, add a blank line then a body paragraph explaining the change
- Output only the commit message, no quotes or code blocks
</format>
@@ -333,9 +335,9 @@ wt config shell init fish | source
Without shell integration, `wt switch` prints the target directory but cannot `cd` into it.
-### Skip first-run prompt
+### First-run prompts
-On first run without shell integration, Worktrunk offers to install it. Declining sets `skip-shell-integration-prompt = true` automatically.
+On first run without shell integration, Worktrunk offers to install it. Similarly, on first commit without LLM configuration, it offers to configure a detected tool (`claude`, `codex`). Declining sets `skip-shell-integration-prompt` or `skip-commit-generation-prompt` automatically.
# Other
diff --git a/docs/content/llm-commits.md b/docs/content/llm-commits.md
index f22cd2b64..6b2dd0cc3 100644
--- a/docs/content/llm-commits.md
+++ b/docs/content/llm-commits.md
@@ -23,7 +23,7 @@ Any command that reads a prompt from stdin and outputs a commit message works. A
```toml
[commit.generation]
-command = "MAX_THINKING_TOKENS=0 claude -p --model haiku --tools '' --disable-slash-commands --setting-sources '' --system-prompt ''"
+command = "MAX_THINKING_TOKENS=0 claude -p --model=haiku --tools='' --disable-slash-commands --setting-sources='' --system-prompt=''"
```
The flags disable tools, skills, settings, and system prompt for fast text-only output. See [Claude Code docs](https://docs.anthropic.com/en/docs/build-with-claude/claude-code) for installation.
@@ -50,7 +50,7 @@ See [aichat docs](https://github.com/sigoden/aichat).
```toml
[commit.generation]
-command = "codex exec -m gpt-5.1-codex-mini -c model_reasoning_effort='low' --sandbox read-only --json - | jq -sr '[.[] | select(.item.type? == \"agent_message\")] | last.item.text'"
+command = "codex exec -m gpt-5.1-codex-mini -c model_reasoning_effort='low' --sandbox=read-only --json - | jq -sr '[.[] | select(.item.type? == \"agent_message\")] | last.item.text'"
```
Uses the fast mini model with low reasoning effort. Requires `jq` for JSON parsing. See [Codex CLI docs](https://developers.openai.com/codex/cli/).
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index 0daafbebc..c34beace0 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -1653,7 +1653,8 @@ template = """
Write a commit message for the staged changes below.
<format>
-- Subject under 50 chars, blank line, then optional body
+- Subject line under 50 chars
+- For material changes, add a blank line then a body paragraph explaining the change
- Output only the commit message, no quotes or code blocks
</format>
@@ -1698,7 +1699,8 @@ squash-template = """
Combine these commits into a single commit message.
<format>
-- Subject under 50 chars, blank line, then optional body
+- Subject line under 50 chars
+- For material changes, add a blank line then a body paragraph explaining the change
- Output only the commit message, no quotes or code blocks
</format>
@@ -1772,9 +1774,9 @@ wt config shell init fish | source
Without shell integration, `wt switch` prints the target directory but cannot `cd` into it.
-### Skip first-run prompt
+### First-run prompts
-On first run without shell integration, Worktrunk offers to install it. Declining sets `skip-shell-integration-prompt = true` automatically.
+On first run without shell integration, Worktrunk offers to install it. Similarly, on first commit without LLM configuration, it offers to configure a detected tool (`claude`, `codex`). Declining sets `skip-shell-integration-prompt` or `skip-commit-generation-prompt` automatically.
# Other
diff --git a/src/commands/configure_shell.rs b/src/commands/configure_shell.rs
index f6e0fce68..c310fe650 100644
--- a/src/commands/configure_shell.rs
+++ b/src/commands/configure_shell.rs
@@ -11,6 +11,8 @@ use worktrunk::styling::{
prompt_message, warning_message,
};
+use crate::output::prompt::{PromptResponse, prompt_yes_no_preview};
+
pub struct ConfigureResult {
pub shell: Shell,
pub path: PathBuf,
@@ -724,36 +726,12 @@ pub fn prompt_for_install(
cmd: &str,
prompt_text: &str,
) -> Result<bool, String> {
- loop {
- eprint!(
- "{} ",
- prompt_message(color_print::cformat!("{prompt_text} <bold>[y/N/?]</>"))
- );
- io::stderr().flush().map_err(|e| e.to_string())?;
-
- let mut input = String::new();
- io::stdin()
- .read_line(&mut input)
- .map_err(|e| e.to_string())?;
-
- let response = input.trim().to_lowercase();
- match response.as_str() {
- "y" | "yes" => {
- eprintln!();
- return Ok(true);
- }
- "?" => {
- eprintln!();
- show_install_preview(results, completion_results, cmd);
- // Loop back to prompt again
- }
- _ => {
- // Empty, "n", "no", or anything else is decline
- eprintln!();
- return Ok(false);
- }
- }
- }
+ let response = prompt_yes_no_preview(prompt_text, || {
+ show_install_preview(results, completion_results, cmd);
+ })
+ .map_err(|e| e.to_string())?;
+
+ Ok(response == PromptResponse::Accepted)
}
/// Prompt user for yes/no confirmation (simple [y/N] prompt)
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index a5ce9c554..af16ebda6 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -1,7 +1,8 @@
use std::path::Path;
+use anyhow::Context;
use worktrunk::HookType;
-use worktrunk::config::ProjectConfig;
+use worktrunk::config::{ProjectConfig, UserConfig};
use worktrunk::git::Repository;
use worktrunk::styling::{eprintln, info_message};
@@ -89,6 +90,12 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
stage,
} = opts;
+ // One-time LLM setup prompt (errors logged internally; don't block merge)
+ if commit_opt.unwrap_or(true) {
+ let mut config = UserConfig::load().context("Failed to load config")?;
+ let _ = crate::output::prompt_commit_generation(&mut config);
+ }
+
let env = CommandEnv::for_action("merge")?;
let repo = &env.repo;
let config = &env.config;
diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rs
index bbad5b6f6..a6f9ca08a 100644
--- a/src/commands/step_commands.rs
+++ b/src/commands/step_commands.rs
@@ -48,6 +48,10 @@ pub fn step_commit(
return Ok(());
}
+ // One-time LLM setup prompt (errors logged internally; don't block commit)
+ let mut config = UserConfig::load().context("Failed to load config")?;
+ let _ = crate::output::prompt_commit_generation(&mut config);
+
let env = CommandEnv::for_action("commit")?;
let ctx = env.context(yes);
@@ -107,6 +111,10 @@ pub fn handle_squash(
skip_pre_commit: bool,
stage: Option<StageMode>,
) -> anyhow::Result<SquashResult> {
+ // One-time LLM setup prompt (errors logged internally; don't block commit)
+ let mut config = UserConfig::load().context("Failed to load config")?;
+ let _ = crate::output::prompt_commit_generation(&mut config);
+
let env = CommandEnv::for_action("squash")?;
let repo = &env.repo;
// Squash requires being on a branch (can't squash in detached HEAD)
diff --git a/src/config/user.rs b/src/config/user.rs
index 95a3ef1d5..8e8690783 100644
--- a/src/config/user.rs
+++ b/src/config/user.rs
@@ -169,6 +169,14 @@ pub struct UserConfig {
skip_serializing_if = "std::ops::Not::not"
)]
pub skip_shell_integration_prompt: bool,
+
+ /// Skip the first-run commit generation prompt
+ #[serde(
+ default,
+ rename = "skip-commit-generation-prompt",
+ skip_serializing_if = "std::ops::Not::not"
+ )]
+ pub skip_commit_generation_prompt: bool,
}
/// Configuration for commit message generation
@@ -181,7 +189,7 @@ pub struct CommitGenerationConfig {
///
/// Examples:
/// - `"llm -m claude-haiku-4.5"`
- /// - `"MAX_THINKING_TOKENS=0 claude -p --model haiku"`
+ /// - `"MAX_THINKING_TOKENS=0 claude -p --model=haiku"`
///
/// The command receives the prompt via stdin and should output the commit message.
#[serde(default)]
@@ -1008,6 +1016,49 @@ impl UserConfig {
})
}
+ /// Set `skip-commit-generation-prompt = true` and save.
+ ///
+ /// Acquires lock, reloads from disk, sets flag if not already set, and saves.
+ /// Pass `None` for default config path, or `Some(path)` for testing.
+ pub fn set_skip_commit_generation_prompt(
+ &mut self,
+ config_path: Option<&std::path::Path>,
+ ) -> Result<(), ConfigError> {
+ self.with_locked_mutation(config_path, |config| {
+ if config.skip_commit_generation_prompt {
+ return false;
+ }
+ config.skip_commit_generation_prompt = true;
+ true
+ })
+ }
+
+ /// Set commit generation command and save.
+ ///
+ /// Sets `[commit.generation] command = ...` in the user config.
+ /// Acquires lock, reloads from disk, sets the command, and saves.
+ /// Pass `None` for default config path, or `Some(path)` for testing.
+ pub fn set_commit_generation_command(
+ &mut self,
+ command: String,
+ config_path: Option<&std::path::Path>,
+ ) -> Result<(), ConfigError> {
+ self.with_locked_mutation(config_path, |config| {
+ // Ensure commit config exists
+ let commit_config = config
+ .configs
+ .commit
+ .get_or_insert_with(CommitConfig::default);
+ let gen_config = commit_config
+ .generation
+ .get_or_insert_with(CommitGenerationConfig::default);
+
+ // Set the command
+ gen_config.command = Some(command.clone());
+ true
+ })
+ }
+
/// Save the current configuration to the default config file location
pub fn save(&self) -> Result<(), ConfigError> {
self.save_impl(None)
@@ -1028,6 +1079,130 @@ impl UserConfig {
}
}
+ /// Update the [commit.generation] section in the document.
+ fn update_commit_generation_section(&self, doc: &mut toml_edit::DocumentMut) {
+ // Helper to update a string field only if changed, preserving comments
+ fn update_string_field(
+ table: &mut toml_edit::Table,
+ key: &str,
+ new_value: Option<&String>,
+ ) {
+ match new_value {
+ Some(v) => {
+ // Only update if value changed (preserves comments if unchanged)
+ let current = table.get(key).and_then(|i| i.as_str());
+ if current != Some(v.as_str()) {
+ table[key] = toml_edit::value(v.as_str());
+ }
+ }
+ None => {
+ table.remove(key);
+ }
+ }
+ }
+
+ if let Some(ref commit_cfg) = self.configs.commit
+ && let Some(ref gen_cfg) = commit_cfg.generation
+ {
+ // Ensure [commit] table exists
+ if !doc.contains_key("commit") {
+ doc["commit"] = toml_edit::Item::Table(toml_edit::Table::new());
+ }
+ if let Some(commit_table) = doc["commit"].as_table_mut() {
+ // Ensure [commit.generation] table exists
+ if !commit_table.contains_key("generation") {
+ commit_table["generation"] = toml_edit::Item::Table(toml_edit::Table::new());
+ }
+ if let Some(gen_table) = commit_table["generation"].as_table_mut() {
+ update_string_field(gen_table, "command", gen_cfg.command.as_ref());
+ update_string_field(gen_table, "template", gen_cfg.template.as_ref());
+ update_string_field(gen_table, "template-file", gen_cfg.template_file.as_ref());
+ update_string_field(
+ gen_table,
+ "squash-template",
+ gen_cfg.squash_template.as_ref(),
+ );
+ update_string_field(
+ gen_table,
+ "squash-template-file",
+ gen_cfg.squash_template_file.as_ref(),
+ );
+ }
+ }
+ }
+ }
+
+ /// Update the [projects] section in the document.
+ fn update_projects_section(&self, doc: &mut toml_edit::DocumentMut) {
+ // Ensure projects table exists
+ if !doc.contains_key("projects") {
+ doc["projects"] = toml_edit::Item::Table(toml_edit::Table::new());
+ }
+
+ if let Some(projects) = doc["projects"].as_table_mut() {
+ // Remove stale projects
+ let stale: Vec<_> = projects
+ .iter()
+ .filter(|(k, _)| !self.projects.contains_key(*k))
+ .map(|(k, _)| k.to_string())
+ .collect();
+ for key in stale {
+ projects.remove(&key);
+ }
+
+ // Add/update projects
+ for (project_id, project_config) in &self.projects {
+ if !projects.contains_key(project_id) {
+ projects[project_id] = toml_edit::Item::Table(toml_edit::Table::new());
+ }
+
+ // worktree-path (only if set)
+ if let Some(ref path) = project_config.overrides.worktree_path {
+ projects[project_id]["worktree-path"] = toml_edit::value(path);
+ } else if let Some(table) = projects[project_id].as_table_mut() {
+ table.remove("worktree-path");
+ }
+
+ // approved-commands
+ let commands =
+ Self::format_multiline_array(project_config.approved_commands.iter());
+ projects[project_id]["approved-commands"] = toml_edit::value(commands);
+
+ // Per-project nested config sections
+ Self::serialize_project_config_section(
+ projects,
+ project_id,
+ "commit-generation",
+ project_config.commit_generation.as_ref(),
+ );
+ Self::serialize_project_config_section(
+ projects,
+ project_id,
+ "list",
+ project_config.overrides.list.as_ref(),
+ );
+ Self::serialize_project_config_section(
+ projects,
+ project_id,
+ "commit",
+ project_config.overrides.commit.as_ref(),
+ );
+ Self::serialize_project_config_section(
+ projects,
+ project_id,
+ "merge",
+ project_config.overrides.merge.as_ref(),
+ );
+ Self::serialize_project_config_section(
+ projects,
+ project_id,
+ "select",
+ project_config.overrides.select.as_ref(),
+ );
+ }
+ }
+ }
+
/// Format a string array as multiline TOML for readability
///
/// TODO: toml_edit doesn't provide a built-in multiline array format option.
@@ -1091,6 +1266,11 @@ impl UserConfig {
///
/// Use this in tests to save to a temporary location instead of the user's config.
/// Preserves comments and formatting in the existing file when possible.
+ ///
+ /// TODO: This design is fragile. When file exists, we surgically update specific
+ /// sections to preserve comments. If a new programmatically-modifiable field is added
+ /// but not handled here, changes won't persist. Consider using a diff-based approach:
+ /// compare self vs existing config and only update what changed.
pub fn save_to(&self, config_path: &std::path::Path) -> Result<(), ConfigError> {
// Create parent directory if it doesn't exist
if let Some(parent) = config_path.parent() {
@@ -1099,8 +1279,8 @@ impl UserConfig {
})?;
}
- // If file exists, use toml_edit to preserve comments and formatting
let toml_string = if config_path.exists() {
+ // Surgically update sections to preserve comments
let existing_content = std::fs::read_to_string(config_path)
.map_err(|e| ConfigError::Message(format!("Failed to read config file: {}", e)))?;
@@ -1108,81 +1288,22 @@ impl UserConfig {
.parse()
.map_err(|e| ConfigError::Message(format!("Failed to parse config file: {}", e)))?;
- // Update skip-shell-integration-prompt flag
+ // Update all programmatically-modifiable sections
+ // NOTE: If you add a new setter that modifies config, add the update here too!
if self.skip_shell_integration_prompt {
doc["skip-shell-integration-prompt"] = toml_edit::value(true);
} else {
doc.remove("skip-shell-integration-prompt");
}
- // Update the projects section
- // Ensure projects table exists
- if !doc.contains_key("projects") {
- doc["projects"] = toml_edit::Item::Table(toml_edit::Table::new());
+ if self.skip_commit_generation_prompt {
+ doc["skip-commit-generation-prompt"] = toml_edit::value(true);
+ } else {
+ doc.remove("skip-commit-generation-prompt");
}
- if let Some(projects) = doc["projects"].as_table_mut() {
- // Remove stale projects
- let stale: Vec<_> = projects
- .iter()
- .filter(|(k, _)| !self.projects.contains_key(*k))
- .map(|(k, _)| k.to_string())
- .collect();
- for key in stale {
- projects.remove(&key);
- }
-
- // Add/update projects
- for (project_id, project_config) in &self.projects {
- if !projects.contains_key(project_id) {
- projects[project_id] = toml_edit::Item::Table(toml_edit::Table::new());
- }
-
- // worktree-path (only if set)
- if let Some(ref path) = project_config.overrides.worktree_path {
- projects[project_id]["worktree-path"] = toml_edit::value(path);
- } else if let Some(table) = projects[project_id].as_table_mut() {
- table.remove("worktree-path");
- }
-
- // approved-commands
- let commands =
- Self::format_multiline_array(project_config.approved_commands.iter());
- projects[project_id]["approved-commands"] = toml_edit::value(commands);
-
- // Per-project nested config sections
- Self::serialize_project_config_section(
- projects,
- project_id,
- "commit-generation",
- project_config.commit_generation.as_ref(),
- );
- Self::serialize_project_config_section(
- projects,
- project_id,
- "list",
- project_config.overrides.list.as_ref(),
- );
- Self::serialize_project_config_section(
- projects,
- project_id,
- "commit",
- project_config.overrides.commit.as_ref(),
- );
- Self::serialize_project_config_section(
- projects,
- project_id,
- "merge",
- project_config.overrides.merge.as_ref(),
- );
- Self::serialize_project_config_section(
- projects,
- project_id,
- "select",
- project_config.overrides.select.as_ref(),
- );
- }
- }
+ self.update_commit_generation_section(&mut doc);
+ self.update_projects_section(&mut doc);
doc.to_string()
} else {
@@ -1936,7 +2057,7 @@ worktree-path = "../{{ main_worktree }}.{{ branch }}"
squash_template_file: None,
};
let override_config = CommitGenerationConfig {
- command: Some("claude -p --model haiku".to_string()), // Override
+ command: Some("claude -p --model=haiku".to_string()), // Override
template: Some("custom".to_string()), // Override (was None)
template_file: None, // Fall back to base
squash_template: None,
@@ -1944,7 +2065,7 @@ worktree-path = "../{{ main_worktree }}.{{ branch }}"
};
let merged = base.merge_with(&override_config);
- assert_eq!(merged.command, Some("claude -p --model haiku".to_string()));
+ assert_eq!(merged.command, Some("claude -p --model=haiku".to_string()));
assert_eq!(merged.template, Some("custom".to_string()));
// When project sets template, template_file is cleared to maintain mutual exclusivity
assert_eq!(merged.template_file, None);
@@ -2877,7 +2998,7 @@ squash-template-file = "path/to/file"
for key in &valid_keys {
match key.as_str() {
"projects" => continue, // Skip - table type tested separately
- "skip-shell-integration-prompt" => {
+ "skip-shell-integration-prompt" | "skip-commit-generation-prompt" => {
scalar_lines.push(format!("{key} = true"));
}
"worktree-path" => {
diff --git a/src/llm.rs b/src/llm.rs
index 36da3112b..54c51da95 100644
--- a/src/llm.rs
+++ b/src/llm.rs
@@ -224,7 +224,8 @@ struct TemplateContext<'a> {
const DEFAULT_TEMPLATE: &str = r#"Write a commit message for the staged changes below.
<format>
-- Subject under 50 chars, blank line, then optional body
+- Subject line under 50 chars
+- For material changes, add a blank line then a body paragraph explaining the change
- Output only the commit message, no quotes or code blocks
</format>
@@ -256,7 +257,8 @@ Branch: {{ branch }}
const DEFAULT_SQUASH_TEMPLATE: &str = r#"Combine these commits into a single commit message.
<format>
-- Subject under 50 chars, blank line, then optional body
+- Subject line under 50 chars
+- For material changes, add a blank line then a body paragraph explaining the change
- Output only the commit message, no quotes or code blocks
</format>
diff --git a/src/output/commit_generation.rs b/src/output/commit_generation.rs
new file mode 100644
index 000000000..77d8bcb26
--- /dev/null
+++ b/src/output/commit_generation.rs
@@ -0,0 +1,261 @@
+//! Commit generation prompt for first-time LLM setup.
+//!
+//! Prompts users to configure LLM commit message generation when they first
+//! attempt a commit without configuration. Detects available tools (claude, codex)
+//! and offers to auto-configure the recommended settings.
+
+use std::io::{self, IsTerminal, Write};
+
+use color_print::cformat;
+use worktrunk::config::UserConfig;
+use worktrunk::styling::{
+ eprintln, format_with_gutter, hint_message, info_message, success_message,
+};
+
+use super::prompt::{PromptResponse, prompt_yes_no_preview};
+
+/// Detected LLM tool available on the system.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum LlmTool {
+ Claude,
+ Codex,
+}
+
+impl LlmTool {
+ /// Returns the command name for this tool.
+ pub fn command_name(&self) -> &'static str {
+ match self {
+ LlmTool::Claude => "claude",
+ LlmTool::Codex => "codex",
+ }
+ }
+
+ /// Returns the recommended configuration command for this tool.
+ ///
+ /// These must match the examples in docs/content/llm-commits.md.
+ pub fn recommended_config(&self) -> &'static str {
+ match self {
+ LlmTool::Claude => {
+ "MAX_THINKING_TOKENS=0 claude -p --model=haiku --tools='' --disable-slash-commands --setting-sources='' --system-prompt=''"
+ }
+ LlmTool::Codex => {
+ r#"codex exec -m gpt-5.1-codex-mini -c model_reasoning_effort='low' --sandbox=read-only --json - | jq -sr '[.[] | select(.item.type? == "agent_message")] | last.item.text'"#
+ }
+ }
+ }
+}
+
+impl std::fmt::Display for LlmTool {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}", self.command_name())
+ }
+}
+
+/// Check if a command is available in PATH.
+///
+/// Uses platform-appropriate method: `where` on Windows, `which` on Unix.
+fn command_exists(cmd: &str) -> bool {
+ #[cfg(windows)]
+ let check_cmd = "where";
+ #[cfg(not(windows))]
+ let check_cmd = "which";
+
+ std::process::Command::new(check_cmd)
+ .arg(cmd)
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .status()
+ .map(|s| s.success())
+ .unwrap_or(false)
+}
+
+/// Format a command string as TOML for display.
+///
+/// Uses the toml crate for proper escaping. The result may wrap in terminal
+/// but is always valid TOML.
+fn format_command_for_display(command: &str) -> String {
+ toml::Value::String(command.to_string()).to_string()
+}
+
+/// Detect available LLM tool on the system.
+///
+/// Checks for claude first (preferred), then codex.
+/// Returns None if neither is found.
+pub fn detect_llm_tool() -> Option<LlmTool> {
+ if command_exists("claude") {
+ Some(LlmTool::Claude)
+ } else if command_exists("codex") {
+ Some(LlmTool::Codex)
+ } else {
+ None
+ }
+}
+
+/// Prompt for commit generation configuration.
+///
+/// Shows a one-time prompt when the user attempts to commit without LLM configuration.
+/// Detects available tools and offers to auto-configure.
+///
+/// Note: This function does NOT emit hints about fallback messages. The existing
+/// `CommitGenerator::emit_hint_if_needed()` handles that. This function only handles
+/// the interactive prompt for first-time setup.
+///
+/// Returns `Ok(true)` if configuration was set up, `Ok(false)` otherwise.
+pub fn prompt_commit_generation(config: &mut UserConfig) -> anyhow::Result<bool> {
+ let is_tty = io::stdin().is_terminal() && io::stderr().is_terminal();
+
+ // Skip if already configured
+ if config
+ .commit_generation(None)
+ .command
+ .as_ref()
+ .is_some_and(|s| !s.trim().is_empty())
+ {
+ return Ok(false);
+ }
+
+ // Skip if prompt was previously declined or dismissed
+ if config.skip_commit_generation_prompt {
+ return Ok(false);
+ }
+
+ // Skip if not a TTY (non-interactive)
+ if !is_tty {
+ return Ok(false);
+ }
+
+ // Detect available tool
+ let Some(tool) = detect_llm_tool() else {
+ // No tool found - set skip flag so we don't check every time
+ let _ = config.set_skip_commit_generation_prompt(None);
+ return Ok(false);
+ };
+
+ // Build preview content (used by both ? and success cases)
+ let command = tool.recommended_config();
+ let formatted_command = format_command_for_display(command);
+ let config_preview = format!("[commit.generation]\ncommand = {formatted_command}");
+
+ // Show prompt with preview on ?
+ eprintln!();
+ io::stderr().flush()?;
+
+ let response = prompt_yes_no_preview(
+ &cformat!("Configure <bold>{tool}</> for commit messages?"),
+ || {
+ eprintln!(
+ "{}",
+ info_message(cformat!(
+ "Would add to <bold>~/.config/worktrunk/config.toml</>:"
+ ))
+ );
+ eprintln!("{}", format_with_gutter(&config_preview, None));
+ eprintln!();
+ },
+ )?;
+
+ match response {
+ PromptResponse::Accepted => {
+ // Set the configuration
+ let command = command.to_string();
+ if let Err(e) = config.set_commit_generation_command(command.clone(), None) {
+ log::error!("Failed to save config: {}", e);
+ eprintln!(
+ "{}",
+ hint_message(cformat!(
+ "Config save failed; add manually to <bright-black>~/.config/worktrunk/config.toml</>"
+ ))
+ );
+ return Ok(false);
+ }
+
+ // Show what was added
+ eprintln!("{}", success_message(cformat!("Added to user config:")));
+ eprintln!("{}", format_with_gutter(&config_preview, None));
+ eprintln!(
+ "{}",
+ hint_message(cformat!("View config: <bright-black>wt config show</>"))
+ );
+
+ Ok(true)
+ }
+ PromptResponse::Declined => {
+ // Set skip flag so we don't prompt again
+ let _ = config.set_skip_commit_generation_prompt(None);
+ Ok(false)
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_llm_tool_command_name() {
+ assert_eq!(LlmTool::Claude.command_name(), "claude");
+ assert_eq!(LlmTool::Codex.command_name(), "codex");
+ }
+
+ #[test]
+ fn test_llm_tool_recommended_config() {
+ let claude_config = LlmTool::Claude.recommended_config();
+ assert!(claude_config.contains("claude"));
+ assert!(claude_config.contains("haiku"));
+
+ let codex_config = LlmTool::Codex.recommended_config();
+ assert!(codex_config.contains("codex exec"));
+ assert!(codex_config.contains("gpt-5.1-codex-mini"));
+ }
+
+ #[test]
+ fn test_llm_tool_display() {
+ assert_eq!(format!("{}", LlmTool::Claude), "claude");
+ assert_eq!(format!("{}", LlmTool::Codex), "codex");
+ }
+
+ #[test]
+ fn test_format_command_produces_valid_toml() {
+ // Uses toml crate for proper escaping
+ let result = format_command_for_display("echo hello");
+ assert_eq!(result, "\"echo hello\"");
+
+ // Long commands stay as single-line TOML
+ let cmd = LlmTool::Claude.recommended_config();
+ let result = format_command_for_display(cmd);
+ assert!(result.starts_with('"') || result.starts_with('\''));
+ assert!(result.contains("claude"));
+ assert!(result.contains("haiku"));
+ }
+
+ #[test]
+ fn test_format_command_special_chars() {
+ let result = format_command_for_display(r#"echo "hello""#);
+ // toml crate may use literal strings ('...') or basic strings ("...")
+ assert!(
+ result.contains("echo") && result.contains("hello"),
+ "Command content should be preserved: {result}"
+ );
+ }
+
+ #[test]
+ fn test_command_exists_known_command() {
+ // 'which' (Unix) or 'where' (Windows) should always exist
+ #[cfg(not(windows))]
+ assert!(command_exists("which"));
+ #[cfg(windows)]
+ assert!(command_exists("where"));
+ }
+
+ #[test]
+ fn test_command_exists_nonexistent() {
+ // A command that definitely doesn't exist
+ assert!(!command_exists("__nonexistent_command_12345__"));
+ }
+
+ #[test]
+ fn test_detect_llm_tool() {
+ // Just exercise the function - result depends on what's installed
+ let _ = detect_llm_tool();
+ }
+}
diff --git a/src/output/mod.rs b/src/output/mod.rs
index c76818f47..145cc4daa 100644
--- a/src/output/mod.rs
+++ b/src/output/mod.rs
@@ -29,8 +29,10 @@
//!
//! See [`shell_integration`] module for the complete spec of warning messages.
+pub(crate) mod commit_generation;
mod global;
pub(crate) mod handlers;
+pub(crate) mod prompt;
pub(crate) mod shell_integration;
// Re-export the public API
@@ -46,3 +48,5 @@ pub(crate) use handlers::{
pub(crate) use shell_integration::{
print_shell_install_result, print_skipped_shells, prompt_shell_integration,
};
+// Re-export commit generation functions
+pub(crate) use commit_generation::prompt_commit_generation;
diff --git a/src/output/prompt.rs b/src/output/prompt.rs
new file mode 100644
index 000000000..4173b3ab3
--- /dev/null
+++ b/src/output/prompt.rs
@@ -0,0 +1,71 @@
+//! Reusable prompt utilities for interactive CLI prompts.
+
+use std::io::{self, Write};
+
+use color_print::cformat;
+use worktrunk::styling::PROMPT_SYMBOL;
+
+/// Response from a `[y/N/?]` prompt.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum PromptResponse {
+ /// User accepted (y/yes)
+ Accepted,
+ /// User declined (n/no/empty/other)
+ Declined,
+}
+
+/// Prompt with `[y/N/?]` options. Loops on `?` to show preview.
+///
+/// # Arguments
+/// * `prompt_text` - The question to ask (without the `[y/N/?]` suffix)
+/// * `show_preview` - Closure called when user enters `?`
+///
+/// # Returns
+/// * `Ok(Accepted)` if user enters `y` or `yes`
+/// * `Ok(Declined)` if user enters anything else (including empty)
+///
+/// # Example
+/// ```ignore
+/// match prompt_yes_no_preview(
+/// &cformat!("Configure <bold>{tool}</>?"),
+/// || {
+/// eprintln!("{}", info_message("Would add:"));
+/// eprintln!("{}", format_with_gutter(&preview, None));
+/// },
+/// )? {
+/// PromptResponse::Accepted => { /* do the thing */ }
+/// PromptResponse::Declined => { /* skip */ }
+/// }
+/// ```
+pub fn prompt_yes_no_preview(
+ prompt_text: &str,
+ show_preview: impl Fn(),
+) -> io::Result<PromptResponse> {
+ loop {
+ eprint!(
+ "{}",
+ cformat!("{PROMPT_SYMBOL} {prompt_text} <bold>[y/N/?]</> ")
+ );
+ io::stderr().flush()?;
+
+ let mut input = String::new();
+ io::stdin().read_line(&mut input)?;
+
+ let response = input.trim().to_lowercase();
+ match response.as_str() {
+ "y" | "yes" => {
+ worktrunk::styling::eprintln!();
+ return Ok(PromptResponse::Accepted);
+ }
+ "?" => {
+ worktrunk::styling::eprintln!();
+ show_preview();
+ // Loop back to prompt again
+ }
+ _ => {
+ worktrunk::styling::eprintln!();
+ return Ok(PromptResponse::Declined);
+ }
+ }
+ }
+}
diff --git a/tests/common/mod.rs b/tests/common/mod.rs
index 3dcc39474..a18ec95ba 100644
--- a/tests/common/mod.rs
+++ b/tests/common/mod.rs
@@ -1386,8 +1386,12 @@ impl TestRepo {
}
/// Overwrite the isolated WORKTRUNK_CONFIG_PATH used during tests.
+ ///
+ /// Automatically prepends `skip-commit-generation-prompt = true` to prevent
+ /// interactive prompts from appearing in test output.
pub fn write_test_config(&self, contents: &str) {
- std::fs::write(&self.test_config_path, contents).unwrap();
+ let full_contents = format!("skip-commit-generation-prompt = true\n{}", contents);
+ std::fs::write(&self.test_config_path, full_contents).unwrap();
}
/// Get the path to a named worktree
diff --git a/tests/integration_tests/approval_save.rs b/tests/integration_tests/approval_save.rs
index f59c9f32c..54b5c769a 100644
--- a/tests/integration_tests/approval_save.rs
+++ b/tests/integration_tests/approval_save.rs
@@ -669,6 +669,104 @@ fn test_skip_shell_integration_prompt_idempotent() {
assert_eq!(count, 1, "Flag should appear exactly once");
}
+#[test]
+fn test_skip_commit_generation_prompt_saves_to_disk() {
+ let temp_dir = TempDir::new().unwrap();
+ let config_path = temp_dir.path().join("worktrunk").join("config.toml");
+
+ let mut config = UserConfig::default();
+ config
+ .set_skip_commit_generation_prompt(Some(&config_path))
+ .unwrap();
+
+ // Verify file was created
+ assert!(
+ config_path.exists(),
+ "Config file was not created at {:?}",
+ config_path
+ );
+
+ // Verify TOML structure
+ let toml_content = fs::read_to_string(&config_path).unwrap();
+ assert_snapshot!(toml_content, @"skip-commit-generation-prompt = true");
+}
+
+#[test]
+fn test_skip_commit_generation_prompt_idempotent() {
+ let temp_dir = TempDir::new().unwrap();
+ let config_path = temp_dir.path().join("config.toml");
+
+ let mut config = UserConfig::default();
+
+ // Call twice - should not error
+ config
+ .set_skip_commit_generation_prompt(Some(&config_path))
+ .unwrap();
+ config
+ .set_skip_commit_generation_prompt(Some(&config_path))
+ .unwrap();
+
+ // Field should still be true
+ assert!(config.skip_commit_generation_prompt);
+
+ // File should have the flag exactly once
+ let toml_content = fs::read_to_string(&config_path).unwrap();
+ let count = toml_content
+ .matches("skip-commit-generation-prompt")
+ .count();
+ assert_eq!(count, 1, "Flag should appear exactly once");
+}
+
+#[test]
+fn test_set_commit_generation_command_saves_to_disk() {
+ let temp_dir = TempDir::new().unwrap();
+ let config_path = temp_dir.path().join("worktrunk").join("config.toml");
+
+ let mut config = UserConfig::default();
+ config
+ .set_commit_generation_command("llm -m haiku".to_string(), Some(&config_path))
+ .unwrap();
+
+ // Verify file was created
+ assert!(
+ config_path.exists(),
+ "Config file was not created at {:?}",
+ config_path
+ );
+
+ // Verify TOML structure - should have [commit.generation] section with command
+ let toml_content = fs::read_to_string(&config_path).unwrap();
+ assert_snapshot!(toml_content, @r#"
+ [commit]
+
+ [commit.generation]
+ command = "llm -m haiku"
+ "#);
+}
+
+#[test]
+fn test_set_commit_generation_command_with_special_chars() {
+ let temp_dir = TempDir::new().unwrap();
+ let config_path = temp_dir.path().join("config.toml");
+
+ let mut config = UserConfig::default();
+ // Command with quotes and environment variables (like claude config)
+ let command =
+ "MAX_THINKING_TOKENS=0 claude -p --model=haiku --tools='' --system-prompt=''".to_string();
+ config
+ .set_commit_generation_command(command, Some(&config_path))
+ .unwrap();
+
+ // Verify TOML can be parsed back
+ let toml_content = fs::read_to_string(&config_path).unwrap();
+ let parsed: UserConfig = toml::from_str(&toml_content).unwrap();
+ let gen_config = parsed.commit_generation(None);
+ assert_eq!(
+ gen_config.command.as_deref(),
+ Some("MAX_THINKING_TOKENS=0 claude -p --model=haiku --tools='' --system-prompt=''")
+ );
+}
+
///
/// When the config file is a symlink (e.g., user has config.toml -> dotfiles/worktrunk.toml),
/// saving should write to the target file without destroying the symlink.
@@ -748,3 +846,61 @@ command = "llm -m claude-haiku-4.5"
"Content should be identical whether read through symlink or target"
);
}
+
+/// Test that set_commit_generation_command persists to an existing config file
+/// while preserving other content.
+///
+/// This is a regression test for a bug where the "file exists" branch in save_to()
+/// didn't know about the commit.generation section, so setting the command would
+/// succeed in memory but not persist to disk.
+#[test]
+fn test_set_commit_generation_command_preserves_existing_content() {
+ let temp_dir = TempDir::new().unwrap();
+ let config_path = temp_dir.path().join("config.toml");
+
+ // Create existing config with other sections
+ let initial_content = r#"# My settings
+worktree-path = "../{{ repo }}.{{ branch }}"
+
+[projects."github.com/user/repo"]
+approved-commands = [
+ "npm install",
+]
+"#;
+ fs::write(&config_path, initial_content).unwrap();
+
+ // Load the config and set the commit generation command
+ let toml_str = fs::read_to_string(&config_path).unwrap();
+ let mut config: UserConfig = toml::from_str(&toml_str).unwrap();
+
+ config
+ .set_commit_generation_command("llm -m haiku".to_string(), Some(&config_path))
+ .unwrap();
+
+ // Read back what was saved
+ let saved = fs::read_to_string(&config_path).unwrap();
+
+ // Original content should be preserved
+ assert!(
+ saved.contains("worktree-path = \"../{{ repo }}.{{ branch }}\""),
+ "worktree-path should be preserved. Saved content:\n{saved}"
+ );
+ assert!(
+ saved.contains("npm install"),
+ "approved-commands should be preserved. Saved content:\n{saved}"
+ );
+ assert!(
+ saved.contains("# My settings"),
+ "Comments should be preserved. Saved content:\n{saved}"
+ );
+
+ // New section should be added
+ assert!(
+ saved.contains("[commit.generation]"),
+ "[commit.generation] section should be added. Saved content:\n{saved}"
+ );
+ assert!(
+ saved.contains("llm -m haiku"),
+ "command should be saved. Saved content:\n{saved}"
+ );
+}
diff --git a/tests/integration_tests/shell_integration_prompt.rs b/tests/integration_tests/shell_integration_prompt.rs
index c4cc75258..f3a5618fe 100644
--- a/tests/integration_tests/shell_integration_prompt.rs
+++ b/tests/integration_tests/shell_integration_prompt.rs
@@ -492,3 +492,176 @@ mod pty_tests {
);
}
}
+
+/// Tests for commit generation prompt (similar to shell integration prompt)
+#[cfg(all(unix, feature = "shell-integration-tests"))]
+mod commit_generation_prompt_tests {
+ use super::*;
+ use crate::common::pty::exec_in_pty_with_home;
+ use insta_cmd::get_cargo_bin;
+ use std::os::unix::fs::PermissionsExt;
+ use std::path::{Path, PathBuf};
+ use tempfile::TempDir;
+
+ fn setup_fake_claude(temp_home: &Path) -> PathBuf {
+ // Create a fake claude executable that does nothing
+ let bin_dir = temp_home.join("bin");
+ fs::create_dir_all(&bin_dir).unwrap();
+ let claude_path = bin_dir.join("claude");
+ fs::write(&claude_path, "#!/bin/sh\nexit 0\n").unwrap();
+ // Make executable
+ let mut perms = fs::metadata(&claude_path).unwrap().permissions();
+ perms.set_mode(0o755);
+ fs::set_permissions(&claude_path, perms).unwrap();
+ bin_dir
+ }
+
+ /// Test: No LLM tool available, prompt is skipped and skip flag is set
+ #[rstest]
+ fn test_no_llm_tool_sets_skip_flag(repo: TestRepo) {
+ let temp_home = TempDir::new().unwrap();
+
+ // Stage a change so commit has something to do
+ let test_file = repo.root_path().join("test.txt");
+ fs::write(&test_file, "test content\n").unwrap();
+ repo.run_git(&["add", "test.txt"]);
+
+ let mut env_vars = repo.test_env_vars();
+ // Use minimal PATH to ensure claude/codex aren't found
+ env_vars.push(("PATH".to_string(), "/usr/bin:/bin".to_string()));
+
+ let (output, exit_code) = exec_in_pty_with_home(
+ get_cargo_bin("wt").to_str().unwrap(),
+ &["step", "commit"],
+ repo.root_path(),
+ &env_vars,
+ "", // No input needed - prompt should be skipped
+ temp_home.path(),
+ );
+
+ // Should succeed (using fallback commit message)
+ assert_eq!(exit_code, 0, "Command should succeed: {output}");
+
+ // Config should have skip-commit-generation-prompt = true (no tool found)
+ let config_content = fs::read_to_string(repo.test_config_path()).unwrap_or_default();
+ assert!(
+ config_content.contains("skip-commit-generation-prompt = true"),
+ "Should set skip flag when no tool found: {config_content}"
+ );
+ }
+
+ /// Test: LLM tool available, user declines prompt
+ #[rstest]
+ fn test_user_declines_llm_prompt(repo: TestRepo) {
+ let temp_home = TempDir::new().unwrap();
+ let bin_dir = setup_fake_claude(temp_home.path());
+
+ // Stage a change
+ let test_file = repo.root_path().join("test.txt");
+ fs::write(&test_file, "test content\n").unwrap();
+ repo.run_git(&["add", "test.txt"]);
+
+ let mut env_vars = repo.test_env_vars();
+ // Add our fake claude to PATH
+ let path = format!("{}:/usr/bin:/bin", bin_dir.display());
+ env_vars.push(("PATH".to_string(), path));
+
+ let (output, exit_code) = exec_in_pty_with_home(
+ get_cargo_bin("wt").to_str().unwrap(),
+ &["step", "commit"],
+ repo.root_path(),
+ &env_vars,
+ "n\n", // Decline the prompt
+ temp_home.path(),
+ );
+
+ assert_eq!(exit_code, 0, "Command should succeed: {output}");
+
+ // Should show the prompt
+ assert!(
+ output.contains("Configure") && output.contains("claude"),
+ "Should show LLM config prompt: {output}"
+ );
+
+ // Config should have skip-commit-generation-prompt = true
+ let config_content = fs::read_to_string(repo.test_config_path()).unwrap_or_default();
+ assert!(
+ config_content.contains("skip-commit-generation-prompt = true"),
+ "Should set skip flag when declined: {config_content}"
+ );
+ }
+
+ /// Test: LLM tool available, user accepts prompt
+ #[rstest]
+ fn test_user_accepts_llm_prompt(repo: TestRepo) {
+ let temp_home = TempDir::new().unwrap();
+ let bin_dir = setup_fake_claude(temp_home.path());
+
+ // Stage a change
+ let test_file = repo.root_path().join("test.txt");
+ fs::write(&test_file, "test content\n").unwrap();
+ repo.run_git(&["add", "test.txt"]);
+
+ let mut env_vars = repo.test_env_vars();
+ let path = format!("{}:/usr/bin:/bin", bin_dir.display());
+ env_vars.push(("PATH".to_string(), path));
+
+ let (output, _exit_code) = exec_in_pty_with_home(
+ get_cargo_bin("wt").to_str().unwrap(),
+ &["step", "commit"],
+ repo.root_path(),
+ &env_vars,
+ "y\n", // Accept the prompt
+ temp_home.path(),
+ );
+
+ // Note: exit_code may be non-zero because our fake claude doesn't generate
+ // a real commit message. We're testing the prompt flow, not the LLM result.
+
+ // Should show success message for config save
+ assert!(
+ output.contains("Added to user config"),
+ "Should show config added message: {output}"
+ );
+
+ // Config should have the command configured
+ let config_content = fs::read_to_string(repo.test_config_path()).unwrap_or_default();
+ assert!(
+ config_content.contains("[commit.generation]") && config_content.contains("command"),
+ "Should add commit generation config: {config_content}"
+ );
+ }
+
+ /// Test: User requests preview (?)
+ #[rstest]
+ fn test_user_requests_preview(repo: TestRepo) {
+ let temp_home = TempDir::new().unwrap();
+ let bin_dir = setup_fake_claude(temp_home.path());
+
+ // Stage a change
+ let test_file = repo.root_path().join("test.txt");
+ fs::write(&test_file, "test content\n").unwrap();
+ repo.run_git(&["add", "test.txt"]);
+
+ let mut env_vars = repo.test_env_vars();
+ let path = format!("{}:/usr/bin:/bin", bin_dir.display());
+ env_vars.push(("PATH".to_string(), path));
+
+ let (output, exit_code) = exec_in_pty_with_home(
+ get_cargo_bin("wt").to_str().unwrap(),
+ &["step", "commit"],
+ repo.root_path(),
+ &env_vars,
+ "?\nn\n", // Request preview, then decline
+ temp_home.path(),
+ );
+
+ assert_eq!(exit_code, 0, "Command should succeed: {output}");
+
+ // Should show the preview
+ assert!(
+ output.contains("Would add to") && output.contains("[commit.generation]"),
+ "Should show preview: {output}"
+ );
+ }
+}
diff --git a/tests/integration_tests/shell_wrapper.rs b/tests/integration_tests/shell_wrapper.rs
index 3bfdbd07d..1301486c4 100644
--- a/tests/integration_tests/shell_wrapper.rs
+++ b/tests/integration_tests/shell_wrapper.rs
@@ -899,6 +899,9 @@ mod unix_tests {
#[case("zsh")]
#[case("fish")]
fn test_wrapper_merge(#[case] shell: &str, mut repo: TestRepo) {
+ // Disable LLM prompt (PTY tests are interactive, claude may be installed)
+ repo.write_test_config("");
+
// Create a feature branch
repo.add_worktree("feature");
@@ -1073,8 +1076,7 @@ test = "echo '✓ All 47 tests passed in 2.3s'"
let feature_wt = repo.add_feature();
// Pre-approve commands
- fs::write(
- repo.test_config_path(),
+ repo.write_test_config(
r#"[projects."../origin"]
approved-commands = [
"echo '✓ Code formatting check passed'",
@@ -1082,8 +1084,7 @@ approved-commands = [
"echo '✓ All 47 tests passed in 2.3s'",
]
"#,
- )
- .unwrap();
+ );
// Run merge from the feature worktree
let output =
@@ -1131,16 +1132,14 @@ test = "echo '✗ Test suite failed: 3 tests failing' && exit 1"
);
// Pre-approve the commands
- fs::write(
- repo.test_config_path(),
+ repo.write_test_config(
r#"[projects."../origin"]
approved-commands = [
"echo '✓ Code formatting check passed'",
"echo '✗ Test suite failed: 3 tests failing' && exit 1",
]
"#,
- )
- .unwrap();
+ );
// Run merge from the feature worktree
let output =
@@ -1198,10 +1197,8 @@ check2 = "{} check2 3"
let feature_wt = repo.add_feature();
// Pre-approve commands
- fs::write(
- repo.test_config_path(),
- format!(
- r#"worktree-path = "../{{{{ repo }}}}.{{{{ branch }}}}"
+ repo.write_test_config(&format!(
+ r#"worktree-path = "../{{{{ repo }}}}.{{{{ branch }}}}"
[projects."../origin"]
approved-commands = [
@@ -1209,11 +1206,9 @@ approved-commands = [
"{} check2 3",
]
"#,
- script_path.display(),
- script_path.display()
- ),
- )
- .unwrap();
+ script_path.display(),
+ script_path.display()
+ ));
// Run merge from the feature worktree
let output =
@@ -2450,7 +2445,7 @@ command = "{}"
"#,
llm_path.display()
);
- fs::write(repo.test_config_path(), worktrunk_config).unwrap();
+ repo.write_test_config(&worktrunk_config);
// Set PATH with mock binaries and run merge
let path_with_bin = format!(
diff --git a/tests/snapshots/integration__integration_tests__configure_shell__pty_tests__install_preview_declined.snap b/tests/snapshots/integration__integration_tests__configure_shell__pty_tests__install_preview_declined.snap
index 6851dabd3..097e8d61a 100644
--- a/tests/snapshots/integration__integration_tests__configure_shell__pty_tests__install_preview_declined.snap
+++ b/tests/snapshots/integration__integration_tests__configure_shell__pty_tests__install_preview_declined.snap
@@ -3,5 +3,5 @@ source: tests/integration_tests/configure_shell.rs
expression: "output.trim_start_matches('\\n')"
---
-❯ Install shell integration? [y/N/?]
+❯ Install shell integration? [y/N/?]
✗ Cancelled by user
diff --git a/tests/snapshots/integration__integration_tests__configure_shell__pty_tests__install_preview_with_gutter.snap b/tests/snapshots/integration__integration_tests__configure_shell__pty_tests__install_preview_with_gutter.snap
index 0d6312c47..ced466a2c 100644
--- a/tests/snapshots/integration__integration_tests__configure_shell__pty_tests__install_preview_with_gutter.snap
+++ b/tests/snapshots/integration__integration_tests__configure_shell__pty_tests__install_preview_with_gutter.snap
@@ -3,7 +3,7 @@ source: tests/integration_tests/configure_shell.rs
expression: "output.trim_start_matches('\\n')"
---
-❯ Install shell integration? [y/N/?]
+❯ Install shell integration? [y/N/?]
✓ Added shell extension & completions for zsh @ ~/.zshrc
↳ Skipped bash; ~/.bashrc not found
↳ Skipped fish; ~/.config/fish/functions not found
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_create.snap b/tests/snapshots/integration__integration_tests__help__help_config_create.snap
index 453bfc924..0abc3f326 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_create.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_create.snap
@@ -182,7 +182,8 @@ Creates ~/.config/worktrunk/config.toml with the following content:
# Write a commit message for the staged changes below.
#
# <format>
- # - Subject under 50 chars, blank line, then optional body
+ # - Subject line under 50 chars
+ # - For material changes, add a blank line then a body paragraph explaining the change
# - Output only the commit message, no quotes or code blocks
# </format>
#
@@ -225,7 +226,8 @@ Creates ~/.config/worktrunk/config.toml with the following content:
# Combine these commits into a single commit message.
#
# <format>
- # - Subject under 50 chars, blank line, then optional body
+ # - Subject line under 50 chars
+ # - For material changes, add a blank line then a body paragraph explaining the change
# - Output only the commit message, no quotes or code blocks
# </format>
#
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_long.snap b/tests/snapshots/integration__integration_tests__help__help_config_long.snap
index 3e03f855e..60e21dced 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_long.snap
@@ -225,7 +225,8 @@ Default template:
Write a commit message for the staged changes below.

<format>
- - Subject under 50 chars, blank line, then optional body
+ - Subject line under 50 chars
+ - For material changes, add a blank line then a body paragraph explaining the change
- Output only the commit message, no quotes or code blocks
</format>

@@ -266,7 +267,8 @@ Default template:
Combine these commits into a single commit message.

<format>
- - Subject under 50 chars, blank line, then optional body
+ - Subject line under 50 chars
+ - For material changes, add a blank line then a body paragraph explaining the change
- Output only the commit message, no quotes or code blocks
</format>

@@ -331,9 +333,9 @@ Or manually add to the shell config:
Without shell integration, wt switch prints the target directory but cannot cd into it.
-Skip first-run prompt
+First-run prompts
-On first run without shell integration, Worktrunk offers to install it. Declining sets skip-shell-integration-prompt = true automatically.
+On first run without shell integration, Worktrunk offers to install it. Similarly, on first commit without LLM configuration, it offers to configure a detected tool (claude, codex). Declining sets skip-shell-integration-prompt or skip-commit-generation-prompt automatically.
OTHER
diff --git a/tests/snapshots/integration__integration_tests__merge__step_commit_show_prompt.snap b/tests/snapshots/integration__integration_tests__merge__step_commit_show_prompt.snap
index f9af1f925..6e848b7fc 100644
--- a/tests/snapshots/integration__integration_tests__merge__step_commit_show_prompt.snap
+++ b/tests/snapshots/integration__integration_tests__merge__step_commit_show_prompt.snap
@@ -37,7 +37,8 @@ exit_code: 0
Write a commit message for the staged changes below.
<format>
-- Subject under 50 chars, blank line, then optional body
+- Subject line under 50 chars
+- For material changes, add a blank line then a body paragraph explaining the change
- Output only the commit message, no quotes or code blocks
</format>
diff --git a/tests/snapshots/integration__integration_tests__merge__step_commit_show_prompt_no_staged_changes.snap b/tests/snapshots/integration__integration_tests__merge__step_commit_show_prompt_no_staged_changes.snap
index f9af1f925..6e848b7fc 100644
--- a/tests/snapshots/integration__integration_tests__merge__step_commit_show_prompt_no_staged_changes.snap
+++ b/tests/snapshots/integration__integration_tests__merge__step_commit_show_prompt_no_staged_changes.snap
@@ -37,7 +37,8 @@ exit_code: 0
Write a commit message for the staged changes below.
<format>
-- Subject under 50 chars, blank line, then optional body
+- Subject line under 50 chars
+- For material changes, add a blank line then a body paragraph explaining the change
- Output only the commit message, no quotes or code blocks
</format>
diff --git a/tests/snapshots/integration__integration_tests__merge__step_squash_show_prompt.snap b/tests/snapshots/integration__integration_tests__merge__step_squash_show_prompt.snap
index 44991d9c8..3b1876fe9 100644
--- a/tests/snapshots/integration__integration_tests__merge__step_squash_show_prompt.snap
+++ b/tests/snapshots/integration__integration_tests__merge__step_squash_show_prompt.snap
@@ -37,7 +37,8 @@ exit_code: 0
Combine these commits into a single commit message.
<format>
-- Subject under 50 chars, blank line, then optional body
+- Subject line under 50 chars
+- For material changes, add a blank line then a body paragraph explaining the change
- Output only the commit message, no quotes or code blocks
</format>
diff --git a/tests/snapshots/integration__integration_tests__shell_integration_prompt__pty_tests__prompt_accept.snap b/tests/snapshots/integration__integration_tests__shell_integration_prompt__pty_tests__prompt_accept.snap
index c288dd2de..6d50125ef 100644
--- a/tests/snapshots/integration__integration_tests__shell_integration_prompt__pty_tests__prompt_accept.snap
+++ b/tests/snapshots/integration__integration_tests__shell_integration_prompt__pty_tests__prompt_accept.snap
@@ -8,7 +8,7 @@ y
↳ To customize worktree locations, run wt config create
▲ Cannot change directory — shell integration not installed
-❯ Install shell integration? [y/N/?]
+❯ Install shell integration? [y/N/?]
✓ Added shell extension & completions for bash @ ~/.bashrc
↳ Skipped zsh; ~/.zshrc not found
↳ Skipped fish; ~/.config/fish/functions not found
diff --git a/tests/snapshots/integration__integration_tests__shell_integration_prompt__pty_tests__prompt_decline.snap b/tests/snapshots/integration__integration_tests__shell_integration_prompt__pty_tests__prompt_decline.snap
index dd5efaf63..437bb1f52 100644
--- a/tests/snapshots/integration__integration_tests__shell_integration_prompt__pty_tests__prompt_decline.snap
+++ b/tests/snapshots/integration__integration_tests__shell_integration_prompt__pty_tests__prompt_decline.snap
@@ -8,5 +8,5 @@ n
↳ To customize worktree locations, run wt config create
▲ Cannot change directory — shell integration not installed
-❯ Install shell integration? [y/N/?]
+❯ Install shell integration? [y/N/?]
↳ To enable automatic cd, run wt config shell install
diff --git a/tests/snapshots/integration__integration_tests__shell_integration_prompt__pty_tests__prompt_preview_decline.snap b/tests/snapshots/integration__integration_tests__shell_integration_prompt__pty_tests__prompt_preview_decline.snap
index 8826fd7d6..3ce347e22 100644
--- a/tests/snapshots/integration__integration_tests__shell_integration_prompt__pty_tests__prompt_preview_decline.snap
+++ b/tests/snapshots/integration__integration_tests__shell_integration_prompt__pty_tests__prompt_preview_decline.snap
@@ -9,9 +9,9 @@ n
↳ To customize worktree locations, run wt config create
▲ Cannot change directory — shell integration not installed
-❯ Install shell integration? [y/N/?]
+❯ Install shell integration? [y/N/?]
○ Will add shell extension & completions for bash @ ~/.bashrc
  if command -v wt >/dev/null 2>&1; then eval "$(command wt config shell init bash)"; fi
-❯ Install shell integration? [y/N/?]
+❯ Install shell integration? [y/N/?]
↳ To enable automatic cd, run wt config shell install