Skip to content

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

feat(switch): add AI summary preview tab (#1049)

Maximilian Roos74e3d6baf8b2
diff --git a/dev/config.example.toml b/dev/config.example.toml
index b83ec64b9..96de01395 100644
--- a/dev/config.example.toml
+++ b/dev/config.example.toml
@@ -51,6 +51,7 @@
# full = false # Show CI status and main…± diffstat columns (--full)
# branches = false # Include branches without worktrees (--branches)
# remotes = false # Include remote-only branches (--remotes)
+# summary = false # AI branch summaries in picker tab 5 (requires [commit.generation])
#
# ### Commit
#
diff --git a/docs/content/config.md b/docs/content/config.md
index 1d9dc1b16..dfe1ce39a 100644
--- a/docs/content/config.md
+++ b/docs/content/config.md
@@ -121,6 +121,7 @@ Persistent flag values for `wt list`. Override on command line as needed.
full = false # Show CI status and main…± diffstat columns (--full)
branches = false # Include branches without worktrees (--branches)
remotes = false # Include remote-only branches (--remotes)
+summary = false # AI branch summaries in picker tab 5 (requires [commit.generation])
```
### Commit
diff --git a/docs/content/faq.md b/docs/content/faq.md
index 364db3f9b..82a380a29 100644
--- a/docs/content/faq.md
+++ b/docs/content/faq.md
@@ -164,7 +164,7 @@ Worktrunk runs `git` commands internally and optionally runs `gh` (GitHub) or `g
1. **User hooks** (`~/.config/worktrunk/config.toml`) — Personal automation for all repositories
2. **Project hooks** (`.config/wt.toml`) — Repository-specific automation
-3. **LLM commands** (`~/.config/worktrunk/config.toml`) — Commit message generation
+3. **LLM commands** (`~/.config/worktrunk/config.toml`) — Commit message generation and [picker summaries](@/llm-commits.md#picker-summaries)
4. **--execute flag** — Explicitly provided commands
User hooks don't require approval (you defined them). Commands from project hooks require approval on first run. Approved commands are saved to user config. If a command changes, Worktrunk requires new approval.
diff --git a/docs/content/llm-commits.md b/docs/content/llm-commits.md
index fab2fc20e..963f2f716 100644
--- a/docs/content/llm-commits.md
+++ b/docs/content/llm-commits.md
@@ -93,6 +93,19 @@ $ wt step squash
See [`wt merge`](@/merge.md) and [`wt step`](@/step.md) for full documentation.
+## Picker summaries
+
+The `wt switch` [interactive picker](@/switch.md#interactive-picker) can show AI-generated branch summaries in preview tab 5. Summaries use the same `[commit.generation] command` and describe each branch's changes in a few sentences.
+
+Enable in user config:
+
+```toml
+[list]
+summary = true
+```
+
+Summaries are generated in parallel across all worktrees when the picker opens, cached in `.git/wt-cache/summaries/`, and invalidated when the branch's diff changes.
+
## Prompt templates
Worktrunk uses [minijinja](https://docs.rs/minijinja/) templates (Jinja2-like syntax) to build prompts. There are sensible defaults, but templates are fully customizable.
diff --git a/docs/content/switch.md b/docs/content/switch.md
index 94e1edf11..9ac6aeeba 100644
--- a/docs/content/switch.md
+++ b/docs/content/switch.md
@@ -93,7 +93,7 @@ When called without arguments, `wt switch` opens an interactive picker to browse
| `Enter` | Switch to selected worktree |
| `Alt-c` | Create new worktree from query |
| `Esc` | Cancel |
-| `1`/`2`/`3`/`4` | Switch preview tab |
+| `1`–`5` | Switch preview tab |
| `Alt-p` | Toggle preview panel |
| `Ctrl-u`/`Ctrl-d` | Scroll preview up/down |
@@ -103,6 +103,7 @@ When called without arguments, `wt switch` opens an interactive picker to browse
2. **log** — Recent commits; commits already on the default branch have dimmed hashes
3. **main…±** — Diff of changes since the merge-base with the default branch
4. **remote⇅** — Diff vs upstream tracking branch (ahead/behind)
+5. **summary** — AI-generated branch summary (requires `[list] summary = true` and `[commit.generation]`)
**Pager configuration:** The preview panel pipes diff output through git's pager. Override in user config:
diff --git a/skills/worktrunk/reference/config.md b/skills/worktrunk/reference/config.md
index 0419bbe1c..f3a2666a3 100644
--- a/skills/worktrunk/reference/config.md
+++ b/skills/worktrunk/reference/config.md
@@ -113,6 +113,7 @@ Persistent flag values for `wt list`. Override on command line as needed.
full = false # Show CI status and main…± diffstat columns (--full)
branches = false # Include branches without worktrees (--branches)
remotes = false # Include remote-only branches (--remotes)
+summary = false # AI branch summaries in picker tab 5 (requires [commit.generation])
```
### Commit
diff --git a/skills/worktrunk/reference/faq.md b/skills/worktrunk/reference/faq.md
index 9964bad9c..892b22407 100644
--- a/skills/worktrunk/reference/faq.md
+++ b/skills/worktrunk/reference/faq.md
@@ -158,7 +158,7 @@ Worktrunk runs `git` commands internally and optionally runs `gh` (GitHub) or `g
1. **User hooks** (`~/.config/worktrunk/config.toml`) — Personal automation for all repositories
2. **Project hooks** (`.config/wt.toml`) — Repository-specific automation
-3. **LLM commands** (`~/.config/worktrunk/config.toml`) — Commit message generation
+3. **LLM commands** (`~/.config/worktrunk/config.toml`) — Commit message generation and [picker summaries](https://worktrunk.dev/llm-commits/#picker-summaries)
4. **--execute flag** — Explicitly provided commands
User hooks don't require approval (you defined them). Commands from project hooks require approval on first run. Approved commands are saved to user config. If a command changes, Worktrunk requires new approval.
diff --git a/skills/worktrunk/reference/llm-commits.md b/skills/worktrunk/reference/llm-commits.md
index e5d1d6604..1ea27da52 100644
--- a/skills/worktrunk/reference/llm-commits.md
+++ b/skills/worktrunk/reference/llm-commits.md
@@ -80,6 +80,19 @@ $ wt step squash
See [`wt merge`](https://worktrunk.dev/merge/) and [`wt step`](https://worktrunk.dev/step/) for full documentation.
+## Picker summaries
+
+The `wt switch` [interactive picker](https://worktrunk.dev/switch/#interactive-picker) can show AI-generated branch summaries in preview tab 5. Summaries use the same `[commit.generation] command` and describe each branch's changes in a few sentences.
+
+Enable in user config:
+
+```toml
+[list]
+summary = true
+```
+
+Summaries are generated in parallel across all worktrees when the picker opens, cached in `.git/wt-cache/summaries/`, and invalidated when the branch's diff changes.
+
## Prompt templates
Worktrunk uses [minijinja](https://docs.rs/minijinja/) templates (Jinja2-like syntax) to build prompts. There are sensible defaults, but templates are fully customizable.
diff --git a/skills/worktrunk/reference/switch.md b/skills/worktrunk/reference/switch.md
index 7f1b45dd4..14e3ece37 100644
--- a/skills/worktrunk/reference/switch.md
+++ b/skills/worktrunk/reference/switch.md
@@ -71,7 +71,7 @@ When called without arguments, `wt switch` opens an interactive picker to browse
| `Enter` | Switch to selected worktree |
| `Alt-c` | Create new worktree from query |
| `Esc` | Cancel |
-| `1`/`2`/`3`/`4` | Switch preview tab |
+| `1`–`5` | Switch preview tab |
| `Alt-p` | Toggle preview panel |
| `Ctrl-u`/`Ctrl-d` | Scroll preview up/down |
@@ -81,6 +81,7 @@ When called without arguments, `wt switch` opens an interactive picker to browse
2. **log** — Recent commits; commits already on the default branch have dimmed hashes
3. **main…±** — Diff of changes since the merge-base with the default branch
4. **remote⇅** — Diff vs upstream tracking branch (ahead/behind)
+5. **summary** — AI-generated branch summary (requires `[list] summary = true` and `[commit.generation]`)
**Pager configuration:** The preview panel pipes diff output through git's pager. Override in user config:
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index 5ee5848f2..1e96019a7 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -322,7 +322,7 @@ When called without arguments, `wt switch` opens an interactive picker to browse
| `Enter` | Switch to selected worktree |
| `Alt-c` | Create new worktree from query |
| `Esc` | Cancel |
-| `1`/`2`/`3`/`4` | Switch preview tab |
+| `1`–`5` | Switch preview tab |
| `Alt-p` | Toggle preview panel |
| `Ctrl-u`/`Ctrl-d` | Scroll preview up/down |
@@ -332,6 +332,7 @@ When called without arguments, `wt switch` opens an interactive picker to browse
2. **log** — Recent commits; commits already on the default branch have dimmed hashes
3. **main…±** — Diff of changes since the merge-base with the default branch
4. **remote⇅** — Diff vs upstream tracking branch (ahead/behind)
+5. **summary** — AI-generated branch summary (requires `[list] summary = true` and `[commit.generation]`)
**Pager configuration:** The preview panel pipes diff output through git's pager. Override in user config:
@@ -1564,6 +1565,7 @@ Persistent flag values for `wt list`. Override on command line as needed.
full = false # Show CI status and main…± diffstat columns (--full)
branches = false # Include branches without worktrees (--branches)
remotes = false # Include remote-only branches (--remotes)
+summary = false # AI branch summaries in picker tab 5 (requires [commit.generation])
```
### Commit
diff --git a/src/commands/select/items.rs b/src/commands/select/items.rs
index c964ece6e..b38ef2d0b 100644
--- a/src/commands/select/items.rs
+++ b/src/commands/select/items.rs
@@ -21,7 +21,7 @@ use super::pager::{get_diff_pager, pipe_through_pager};
use super::preview::{PreviewMode, PreviewStateData};
/// Cache key for pre-computed previews: (branch_name, mode).
-type PreviewCacheKey = (String, PreviewMode);
+pub(super) type PreviewCacheKey = (String, PreviewMode);
/// Cache for pre-computed previews, keyed by (branch_name, mode).
/// Shared across all WorktreeSkimItems for background pre-computation.
@@ -141,6 +141,7 @@ impl WorktreeSkimItem {
let tab2 = format_tab("2: log", mode == PreviewMode::Log);
let tab3 = format_tab("3: main…±", mode == PreviewMode::BranchDiff);
let tab4 = format_tab("4: remote⇅", mode == PreviewMode::UpstreamDiff);
+ let tab5 = format_tab("5: summary", mode == PreviewMode::Summary);
// Controls use dim yellow to distinguish from dimmed (white) tabs
let controls = cformat!(
@@ -150,35 +151,35 @@ impl WorktreeSkimItem {
// End each tab and controls with full reset to prevent style bleeding
// into dividers and preview content
format!(
- "{tab1}{reset} | {tab2}{reset} | {tab3}{reset} | {tab4}{reset}\n{controls}{reset}\n\n"
+ "{tab1}{reset} | {tab2}{reset} | {tab3}{reset} | {tab4}{reset} | {tab5}{reset}\n{controls}{reset}\n\n"
)
}
/// Render preview for the given mode with specified dimensions.
/// Uses cache if available, otherwise computes and caches.
- /// Applies pager at display time for diff modes (not cached).
+ /// Post-processing (diff pager, markdown render) applied at display time.
fn preview_for_mode(&self, mode: PreviewMode, width: usize, height: usize) -> String {
let cache_key = (self.branch_name.clone(), mode);
- let result = self
+ let content = self
.preview_cache
.entry(cache_key)
.or_insert_with(|| Self::compute_preview(&self.item, mode, width, height))
.value()
.clone();
- // Apply pager at display time for diff modes (1, 3, 4)
- // Log mode (2) doesn't benefit from diff pagers
- let is_diff_mode = matches!(
- mode,
- PreviewMode::WorkingTree | PreviewMode::BranchDiff | PreviewMode::UpstreamDiff
- );
-
- if is_diff_mode && let Some(pager_cmd) = get_diff_pager() {
- return pipe_through_pager(&result, pager_cmd, width);
+ // Post-processing at display time (not cached)
+ match mode {
+ PreviewMode::Summary => super::summary::render_summary(&content, width),
+ PreviewMode::WorkingTree | PreviewMode::BranchDiff | PreviewMode::UpstreamDiff => {
+ if let Some(pager_cmd) = get_diff_pager() {
+ pipe_through_pager(&content, pager_cmd, width)
+ } else {
+ content
+ }
+ }
+ PreviewMode::Log => content,
}
-
- result
}
/// Compute preview for any mode. Called from cache miss and background pre-computation.
@@ -193,6 +194,7 @@ impl WorktreeSkimItem {
PreviewMode::Log => Self::compute_log_preview(item, width, height),
PreviewMode::BranchDiff => Self::compute_branch_diff_preview(item, width),
PreviewMode::UpstreamDiff => Self::compute_upstream_diff_preview(item, width),
+ PreviewMode::Summary => Self::compute_summary_preview(item),
}
}
@@ -397,6 +399,18 @@ impl WorktreeSkimItem {
output
}
+
+ /// Compute Tab 5: Summary preview (AI-generated branch summary)
+ ///
+ /// Returns a synchronous placeholder when the background summary generation
+ /// hasn't completed yet. The actual summary is generated by background threads
+ /// and inserted into the preview cache.
+ fn compute_summary_preview(_item: &ListItem) -> String {
+ format!(
+ "{INFO_SYMBOL} Generating summary...\n\n\
+ Press 5 again to refresh once generation completes.\n"
+ )
+ }
}
#[cfg(test)]
@@ -406,11 +420,12 @@ mod tests {
#[test]
fn test_render_preview_tabs_working_tree_mode() {
let output = WorktreeSkimItem::render_preview_tabs(PreviewMode::WorkingTree);
- // Tab 1 should be bold (active), tabs 2/3/4 dimmed
+ // Tab 1 should be bold (active), tabs 2/3/4/5 dimmed
assert!(output.contains("1: HEAD±"));
assert!(output.contains("2: log"));
assert!(output.contains("3: main…±"));
assert!(output.contains("4: remote⇅"));
+ assert!(output.contains("5: summary"));
assert!(output.contains("Enter: switch"));
// Verify structure: tabs on first line, controls on second
assert!(output.contains(" | "));
@@ -424,6 +439,7 @@ mod tests {
assert!(output.contains("2: log"));
assert!(output.contains("3: main…±"));
assert!(output.contains("4: remote⇅"));
+ assert!(output.contains("5: summary"));
}
#[test]
@@ -433,6 +449,7 @@ mod tests {
assert!(output.contains("2: log"));
assert!(output.contains("3: main…±"));
assert!(output.contains("4: remote⇅"));
+ assert!(output.contains("5: summary"));
}
#[test]
@@ -442,6 +459,95 @@ mod tests {
assert!(output.contains("2: log"));
assert!(output.contains("3: main…±"));
assert!(output.contains("4: remote⇅"));
+ assert!(output.contains("5: summary"));
+ }
+
+ #[test]
+ fn test_render_preview_tabs_summary_mode() {
+ let output = WorktreeSkimItem::render_preview_tabs(PreviewMode::Summary);
+ assert!(output.contains("1: HEAD±"));
+ assert!(output.contains("2: log"));
+ assert!(output.contains("3: main…±"));
+ assert!(output.contains("4: remote⇅"));
+ assert!(output.contains("5: summary"));
+ }
+
+ #[test]
+ fn test_compute_summary_preview_always_shows_generating() {
+ // All items show the same "Generating..." placeholder synchronously.
+ // The background thread produces the correct result (which may be
+ // "No changes to summarize" for the default branch).
+ use crate::commands::list::model::{ItemKind, WorktreeData};
+
+ let mut item = ListItem::new_branch("abc123".to_string(), "main".to_string());
+ item.kind = ItemKind::Worktree(Box::new(WorktreeData {
+ is_main: true,
+ ..Default::default()
+ }));
+
+ let output = WorktreeSkimItem::compute_summary_preview(&item);
+ assert!(output.contains("Generating summary..."));
+ }
+
+ #[test]
+ fn test_compute_summary_preview_feature_branch() {
+ let item = ListItem::new_branch("abc123".to_string(), "feature".to_string());
+
+ let output = WorktreeSkimItem::compute_summary_preview(&item);
+ assert!(output.contains("Generating summary..."));
+ assert!(output.contains("Press 5 again"));
+ }
+
+ #[test]
+ fn test_compute_preview_summary_mode() {
+ let item = ListItem::new_branch("abc123".to_string(), "feature".to_string());
+
+ let output = WorktreeSkimItem::compute_preview(&item, PreviewMode::Summary, 80, 40);
+ assert!(output.contains("Generating summary..."));
+ }
+
+ #[test]
+ fn test_preview_for_mode_summary_cache_hit() {
+ let item = Arc::new(ListItem::new_branch(
+ "abc123".to_string(),
+ "feature".to_string(),
+ ));
+ let preview_cache: PreviewCache = Arc::new(DashMap::new());
+ preview_cache.insert(
+ ("feature".to_string(), PreviewMode::Summary),
+ "Add auth module\n\nImplements JWT-based authentication.".to_string(),
+ );
+
+ let skim_item = WorktreeSkimItem {
+ display_text: String::new(),
+ display_text_with_ansi: String::new(),
+ branch_name: "feature".to_string(),
+ item,
+ preview_cache,
+ };
+
+ let output = skim_item.preview_for_mode(PreviewMode::Summary, 80, 40);
+ assert!(output.contains("Add auth module"));
+ }
+
+ #[test]
+ fn test_preview_for_mode_summary_cache_miss() {
+ let item = Arc::new(ListItem::new_branch(
+ "abc123".to_string(),
+ "feature".to_string(),
+ ));
+ let preview_cache: PreviewCache = Arc::new(DashMap::new());
+
+ let skim_item = WorktreeSkimItem {
+ display_text: String::new(),
+ display_text_with_ansi: String::new(),
+ branch_name: "feature".to_string(),
+ item,
+ preview_cache,
+ };
+
+ let output = skim_item.preview_for_mode(PreviewMode::Summary, 80, 40);
+ assert!(output.contains("Generating summary..."));
}
#[test]
@@ -456,13 +562,13 @@ mod tests {
// This prevents bold/dim from bleeding into the " | " dividers
let full_reset = "\x1b[0m";
- // Count resets - should have one after each of the 4 tabs
- assert_eq!(first_line.matches(full_reset).count(), 4);
+ // Count resets - should have one after each of the 5 tabs
+ assert_eq!(first_line.matches(full_reset).count(), 5);
// The sequence should be: style + text + [22m + [0m + divider
// Check that dividers come after full resets
let parts: Vec<&str> = first_line.split(" | ").collect();
- assert_eq!(parts.len(), 4);
+ assert_eq!(parts.len(), 5);
assert!(parts.iter().all(|part| part.ends_with(full_reset)));
// Controls line should end with full reset to ensure clean state for preview content
diff --git a/src/commands/select/mod.rs b/src/commands/select/mod.rs
index 6f43119f5..e5996feed 100644
--- a/src/commands/select/mod.rs
+++ b/src/commands/select/mod.rs
@@ -6,6 +6,7 @@ mod items;
mod log_formatter;
mod pager;
mod preview;
+mod summary;
use std::io::IsTerminal;
use std::sync::Arc;
@@ -181,7 +182,7 @@ pub fn handle_select(cli_branches: bool, cli_remotes: bool) -> anyhow::Result<()
.to_string(),
))
.bind(vec![
- // Mode switching (1/2/3/4 keys change preview content)
+ // Mode switching (1/2/3/4/5 keys change preview content)
format!(
"1:execute-silent(echo 1 > {0})+refresh-preview",
state_path_str
@@ -198,6 +199,10 @@ pub fn handle_select(cli_branches: bool, cli_remotes: bool) -> anyhow::Result<()
"4:execute-silent(echo 4 > {0})+refresh-preview",
state_path_str
),
+ format!(
+ "5:execute-silent(echo 5 > {0})+refresh-preview",
+ state_path_str
+ ),
// Create new worktree with query as branch name (alt-c for "create")
"alt-c:accept(create)".to_string(),
// Preview toggle (alt-p shows/hides preview)
@@ -224,16 +229,18 @@ pub fn handle_select(cli_branches: bool, cli_remotes: bool) -> anyhow::Result<()
// to overlap I/O-bound git commands. Tasks are fire-and-forget — ongoing
// git commands are harmless read-only operations even if skim exits early.
let (preview_width, preview_height) = state.initial_layout.preview_dimensions(num_items);
+
let modes = [
PreviewMode::WorkingTree,
PreviewMode::Log,
PreviewMode::BranchDiff,
PreviewMode::UpstreamDiff,
];
- for item in items_for_precompute {
+
+ for item in &items_for_precompute {
for mode in modes {
let cache = Arc::clone(&preview_cache);
- let item = Arc::clone(&item);
+ let item = Arc::clone(item);
rayon::spawn(move || {
let cache_key = (item.branch_name().to_string(), mode);
cache.entry(cache_key).or_insert_with(|| {
@@ -243,6 +250,39 @@ pub fn handle_select(cli_branches: bool, cli_remotes: bool) -> anyhow::Result<()
}
}
+ // Queue summary generation after tabs 1-4 so git previews get rayon priority.
+ if config.list.summary() && config.commit_generation.is_configured() {
+ let llm_command = config.commit_generation.command.clone().unwrap();
+ for item in &items_for_precompute {
+ let item = Arc::clone(item);
+ let cache = Arc::clone(&preview_cache);
+ let cmd = llm_command.clone();
+ let repo = repo.clone();
+ rayon::spawn(move || {
+ summary::generate_and_cache_summary(&item, &cmd, &cache, &repo);
+ });
+ }
+ } else {
+ // No LLM configured or summaries disabled — insert config hint so the
+ // tab shows a useful message instead of a perpetual "Generating..." placeholder.
+ let hint = if !config.commit_generation.is_configured() {
+ "Configure [commit.generation] command to enable AI summaries.\n\n\
+ Example in ~/.config/worktrunk/config.toml:\n\n\
+ [commit.generation]\n\
+ command = \"llm -m haiku\"\n\n\
+ [list]\n\
+ summary = true\n"
+ } else {
+ "Enable summaries in ~/.config/worktrunk/config.toml:\n\n\
+ [list]\n\
+ summary = true\n"
+ };
+ for item in &items_for_precompute {
+ let branch = item.branch_name().to_string();
+ preview_cache.insert((branch, PreviewMode::Summary), hint.to_string());
+ }
+ }
+
// Run skim
let output = Skim::run_with(&options, Some(rx));
@@ -338,6 +378,9 @@ pub mod tests {
let _ = fs::write(&state_path, "4");
assert_eq!(PreviewStateData::read_mode(), PreviewMode::UpstreamDiff);
+ let _ = fs::write(&state_path, "5");
+ assert_eq!(PreviewStateData::read_mode(), PreviewMode::Summary);
+
// Cleanup
let _ = fs::remove_file(&state_path);
}
diff --git a/src/commands/select/preview.rs b/src/commands/select/preview.rs
index f8a28ad12..9443c3f2d 100644
--- a/src/commands/select/preview.rs
+++ b/src/commands/select/preview.rs
@@ -12,6 +12,7 @@ use std::path::PathBuf;
/// 2. Log: Commit history since diverging from the default branch (git log with merge-base)
/// 3. BranchDiff: Line diffs since the merge-base with the default branch (git diff --stat DEFAULT…)
/// 4. UpstreamDiff: Diff vs upstream tracking branch (ahead/behind)
+/// 5. Summary: AI-generated branch summary (requires [commit.generation] config)
///
/// Loosely aligned with `wt list` columns, though not a perfect match:
/// - Tab 1 corresponds to "HEAD±" column
@@ -24,6 +25,7 @@ pub(super) enum PreviewMode {
Log = 2,
BranchDiff = 3,
UpstreamDiff = 4,
+ Summary = 5,
}
impl PreviewMode {
@@ -32,6 +34,7 @@ impl PreviewMode {
2 => Self::Log,
3 => Self::BranchDiff,
4 => Self::UpstreamDiff,
+ 5 => Self::Summary,
_ => Self::WorkingTree,
}
}
@@ -136,7 +139,7 @@ impl PreviewLayout {
/// Preview state persistence (mode only, layout auto-detected)
///
-/// State file format: Single digit representing preview mode (1-4)
+/// State file format: Single digit representing preview mode (1-5)
pub(super) struct PreviewStateData;
impl PreviewStateData {
@@ -194,6 +197,7 @@ mod tests {
assert_eq!(PreviewMode::from_u8(2), PreviewMode::Log);
assert_eq!(PreviewMode::from_u8(3), PreviewMode::BranchDiff);
assert_eq!(PreviewMode::from_u8(4), PreviewMode::UpstreamDiff);
+ assert_eq!(PreviewMode::from_u8(5), PreviewMode::Summary);
// Invalid values default to WorkingTree
assert_eq!(PreviewMode::from_u8(0), PreviewMode::WorkingTree);
assert_eq!(PreviewMode::from_u8(99), PreviewMode::WorkingTree);
@@ -263,6 +267,14 @@ mod tests {
.unwrap_or(PreviewMode::WorkingTree);
assert_eq!(mode, PreviewMode::UpstreamDiff);
+ let _ = fs::write(&state_path, "5");
+ let mode = fs::read_to_string(&state_path)
+ .ok()
+ .and_then(|s| s.trim().parse::<u8>().ok())
+ .map(PreviewMode::from_u8)
+ .unwrap_or(PreviewMode::WorkingTree);
+ assert_eq!(mode, PreviewMode::Summary);
+
// Cleanup
let _ = fs::remove_file(&state_path);
}
diff --git a/src/commands/select/summary.rs b/src/commands/select/summary.rs
new file mode 100644
index 000000000..167b77774
--- /dev/null
+++ b/src/commands/select/summary.rs
@@ -0,0 +1,666 @@
+//! AI summary generation for the interactive selector.
+//!
+//! Generates branch summaries using the configured LLM command, with caching
+//! in `.git/wt-cache/summaries/`. Summaries are invalidated when the combined
+//! diff (branch diff + working tree diff) changes.
+
+use std::collections::hash_map::DefaultHasher;
+use std::fs;
+use std::hash::{Hash, Hasher};
+use std::path::PathBuf;
+use std::sync::LazyLock;
+
+use color_print::cformat;
+use dashmap::DashMap;
+use minijinja::Environment;
+use serde::{Deserialize, Serialize};
+use worktrunk::git::Repository;
+use worktrunk::path::sanitize_for_filename;
+use worktrunk::sync::Semaphore;
+
+use super::super::list::model::ListItem;
+use super::items::PreviewCacheKey;
+use super::preview::PreviewMode;
+use crate::llm::{execute_llm_command, prepare_diff};
+
+/// Limits concurrent LLM calls to avoid overwhelming the network / LLM
+/// provider. 8 permits balances parallelism with resource usage — LLM calls
+/// are I/O-bound (1-5s network waits), so more permits than the CPU-bound
+/// `HEAVY_OPS_SEMAPHORE` (4) but still bounded.
+static LLM_SEMAPHORE: LazyLock<Semaphore> = LazyLock::new(|| Semaphore::new(8));
+
+/// Cached summary stored in `.git/wt-cache/summaries/<branch>.json`
+#[derive(Serialize, Deserialize)]
+struct CachedSummary {
+ summary: String,
+ diff_hash: u64,
+ /// Original branch name (useful for humans inspecting cache files)
+ branch: String,
+}
+
+/// Combined diff output for a branch (branch diff + working tree diff)
+struct CombinedDiff {
+ diff: String,
+ stat: String,
+}
+
+/// Template for summary generation.
+///
+/// Uses commit-message format (subject + body) which naturally produces
+/// imperative-mood summaries without "This branch..." preamble.
+const SUMMARY_TEMPLATE: &str = r#"Write a summary of this branch's changes as a commit message.
+
+<format>
+- Subject line under 50 chars, imperative mood ("Add feature" not "Adds feature")
+- Blank line, then a body paragraph or bullet list explaining the key changes
+- Output only the message — no quotes, code blocks, or labels
+</format>
+
+<diffstat>
+{{ git_diff_stat }}
+</diffstat>
+
+<diff>
+{{ git_diff }}
+</diff>
+"#;
+
+/// Render LLM summary for terminal display using the project's markdown theme.
+///
+/// Promotes the first line to an H4 header (renders bold) so the commit-message
+/// subject line stands out, then renders everything through the standard
+/// markdown renderer used by `--help` pages.
+///
+/// Pre-styled text (containing ANSI escapes) is passed through with word
+/// wrapping only — no H4 promotion.
+pub(super) fn render_summary(text: &str, width: usize) -> String {
+ // Already styled (e.g. dim "no changes" message) — just wrap
+ if text.contains('\x1b') {
+ return crate::md_help::render_markdown_in_help_with_width(text, Some(width));
+ }
+
+ // Promote subject line to H4 (bold) for visual hierarchy
+ let markdown = if let Some((subject, body)) = text.split_once('\n') {
+ format!("#### {subject}\n{body}")
+ } else {
+ format!("#### {text}")
+ };
+
+ crate::md_help::render_markdown_in_help_with_width(&markdown, Some(width))
+}
+
+/// Get the cache directory for summaries
+fn cache_dir(repo: &Repository) -> PathBuf {
+ repo.git_common_dir().join("wt-cache").join("summaries")
+}
+
+/// Get the cache file path for a branch
+fn cache_file(repo: &Repository, branch: &str) -> PathBuf {
+ let safe_branch = sanitize_for_filename(branch);
+ cache_dir(repo).join(format!("{safe_branch}.json"))
+}
+
+/// Read cached summary from file
+fn read_cache(repo: &Repository, branch: &str) -> Option<CachedSummary> {
+ let path = cache_file(repo, branch);
+ let json = fs::read_to_string(&path).ok()?;
+ serde_json::from_str(&json).ok()
+}
+
+/// Write summary to cache file (atomic write via temp file + rename)
+fn write_cache(repo: &Repository, branch: &str, cached: &CachedSummary) {
+ let path = cache_file(repo, branch);
+
+ if let Some(parent) = path.parent()
+ && let Err(e) = fs::create_dir_all(parent)
+ {
+ log::debug!("Failed to create summary cache dir for {}: {}", branch, e);
+ return;
+ }
+
+ let Ok(json) = serde_json::to_string(cached) else {
+ log::debug!("Failed to serialize summary cache for {}", branch);
+ return;
+ };
+
+ let temp_path = path.with_extension("json.tmp");
+ if let Err(e) = fs::write(&temp_path, &json) {
+ log::debug!(
+ "Failed to write summary cache temp file for {}: {}",
+ branch,
+ e
+ );
+ return;
+ }
+
+ #[cfg(windows)]
+ let _ = fs::remove_file(&path);
+
+ if let Err(e) = fs::rename(&temp_path, &path) {
+ log::debug!("Failed to rename summary cache file for {}: {}", branch, e);
+ let _ = fs::remove_file(&temp_path);
+ }
+}
+
+/// Hash a string to produce a cache invalidation key
+fn hash_diff(diff: &str) -> u64 {
+ let mut hasher = DefaultHasher::new();
+ diff.hash(&mut hasher);
+ hasher.finish()
+}
+
+/// Compute the combined diff for a branch (branch diff + working tree diff).
+///
+/// Returns None if there's nothing to summarize (default branch with no changes,
+/// or no default branch known and no working tree diff available).
+fn compute_combined_diff(item: &ListItem, repo: &Repository) -> Option<CombinedDiff> {
+ let branch = item.branch_name();
+ let default_branch = repo.default_branch();
+
+ let mut diff = String::new();
+ let mut stat = String::new();
+
+ // Branch diff: what's ahead of default branch (skipped if default branch unknown)
+ if let Some(ref default_branch) = default_branch {
+ let is_default_branch = branch == *default_branch;
+ if !is_default_branch {
+ let merge_base = format!("{}...{}", default_branch, item.head());
+ if let Ok(branch_stat) = repo.run_command(&["diff", &merge_base, "--stat"]) {
+ stat.push_str(&branch_stat);
+ }
+ if let Ok(branch_diff) = repo.run_command(&["diff", &merge_base]) {
+ diff.push_str(&branch_diff);
+ }
+ }
+ }
+
+ // Working tree diff: uncommitted changes
+ if let Some(wt_data) = item.worktree_data() {
+ let path = wt_data.path.display().to_string();
+ if let Ok(wt_stat) = repo.run_command(&["-C", &path, "diff", "HEAD", "--stat"])
+ && !wt_stat.trim().is_empty()
+ {
+ stat.push_str(&wt_stat);
+ }
+ if let Ok(wt_diff) = repo.run_command(&["-C", &path, "diff", "HEAD"])
+ && !wt_diff.trim().is_empty()
+ {
+ diff.push_str(&wt_diff);
+ }
+ }
+
+ if diff.trim().is_empty() {
+ return None;
+ }
+
+ Some(CombinedDiff { diff, stat })
+}
+
+/// Render the summary prompt template
+fn render_prompt(diff: &str, stat: &str) -> anyhow::Result<String> {
+ let env = Environment::new();
+ let tmpl = env.template_from_str(SUMMARY_TEMPLATE)?;
+ let rendered = tmpl.render(minijinja::context! {
+ git_diff => diff,
+ git_diff_stat => stat,
+ })?;
+ Ok(rendered)
+}
+
+/// Generate a summary for a single item, using cache when available.
+fn generate_summary(item: &ListItem, llm_command: &str, repo: &Repository) -> String {
+ let branch = item.branch_name();
+
+ // Compute combined diff
+ let Some(combined) = compute_combined_diff(item, repo) else {
+ return cformat!("<dim>No changes to summarize on {branch}.</>");
+ };
+
+ let diff_hash = hash_diff(&combined.diff);
+
+ // Check cache
+ if let Some(cached) = read_cache(repo, branch)
+ && cached.diff_hash == diff_hash
+ {
+ return cached.summary;
+ }
+
+ // Prepare diff (filter large diffs)
+ let prepared = prepare_diff(combined.diff, combined.stat);
+
+ // Render template
+ let prompt = match render_prompt(&prepared.diff, &prepared.stat) {
+ Ok(p) => p,
+ Err(e) => return format!("Template error: {e}"),
+ };
+
+ // Call LLM
+ let summary = match execute_llm_command(llm_command, &prompt) {
+ Ok(s) => s,
+ Err(e) => return format!("LLM error: {e}"),
+ };
+
+ // Write cache
+ write_cache(
+ repo,
+ branch,
+ &CachedSummary {
+ summary: summary.clone(),
+ diff_hash,
+ branch: branch.to_string(),
+ },
+ );
+
+ summary
+}
+
+/// Generate a summary for one item and insert it into the preview cache.
+/// Acquires the LLM semaphore to limit concurrent calls across rayon tasks.
+pub(super) fn generate_and_cache_summary(
+ item: &ListItem,
+ llm_command: &str,
+ preview_cache: &DashMap<PreviewCacheKey, String>,
+ repo: &Repository,
+) {
+ let _permit = LLM_SEMAPHORE.acquire();
+ let branch = item.branch_name().to_string();
+ let summary = generate_summary(item, llm_command, repo);
+ preview_cache.insert((branch, PreviewMode::Summary), summary);
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::commands::list::model::{ItemKind, WorktreeData};
+
+ fn git_command(dir: &std::path::Path) -> std::process::Command {
+ let mut cmd = std::process::Command::new("git");
+ cmd.current_dir(dir)
+ .env("GIT_AUTHOR_NAME", "Test")
+ .env("GIT_AUTHOR_EMAIL", "[email protected]")
+ .env("GIT_COMMITTER_NAME", "Test")
+ .env("GIT_COMMITTER_EMAIL", "[email protected]");
+ cmd
+ }
+
+ fn git(dir: &std::path::Path, args: &[&str]) {
+ let output = git_command(dir).args(args).output().unwrap();
+ assert!(
+ output.status.success(),
+ "git {:?} failed: {}",
+ args,
+ String::from_utf8_lossy(&output.stderr)
+ );
+ }
+
+ fn git_output(dir: &std::path::Path, args: &[&str]) -> String {
+ let output = git_command(dir).args(args).output().unwrap();
+ String::from_utf8(output.stdout).unwrap().trim().to_string()
+ }
+
+ /// Create a minimal temp git repo (for cache-only tests that don't need branches).
+ fn temp_repo() -> (tempfile::TempDir, Repository) {
+ let dir = tempfile::tempdir().unwrap();
+ git(dir.path(), &["init", "--initial-branch=main"]);
+ git(dir.path(), &["commit", "--allow-empty", "-m", "init"]);
+ let repo = Repository::at(dir.path()).unwrap();
+ (dir, repo)
+ }
+
+ /// Create a temp repo with main branch, default-branch config, and a real commit.
+ fn temp_repo_configured() -> (tempfile::TempDir, Repository, String) {
+ let dir = tempfile::tempdir().unwrap();
+ git(dir.path(), &["init", "--initial-branch=main"]);
+ git(dir.path(), &["config", "worktrunk.default-branch", "main"]);
+ fs::write(dir.path().join("README.md"), "# Project\n").unwrap();
+ git(dir.path(), &["add", "README.md"]);
+ git(dir.path(), &["commit", "-m", "initial commit"]);
+ let head = git_output(dir.path(), &["rev-parse", "HEAD"]);
+ let repo = Repository::at(dir.path()).unwrap();
+ (dir, repo, head)
+ }
+
+ /// Create a temp repo with main + feature branch that has real changes.
+ fn temp_repo_with_feature() -> (tempfile::TempDir, Repository, String) {
+ let (dir, _, _) = temp_repo_configured();
+
+ git(dir.path(), &["checkout", "-b", "feature"]);
+ fs::write(dir.path().join("new.txt"), "new content\n").unwrap();
+ git(dir.path(), &["add", "new.txt"]);
+ git(dir.path(), &["commit", "-m", "add new file"]);
+
+ let head = git_output(dir.path(), &["rev-parse", "HEAD"]);
+ let repo = Repository::at(dir.path()).unwrap();
+ (dir, repo, head)
+ }
+
+ fn feature_item(head: &str, path: &std::path::Path) -> ListItem {
+ let mut item = ListItem::new_branch(head.to_string(), "feature".to_string());
+ item.kind = ItemKind::Worktree(Box::new(WorktreeData {
+ path: path.to_path_buf(),
+ ..Default::default()
+ }));
+ item
+ }
+
+ #[test]
+ fn test_cache_roundtrip() {
+ let (_dir, repo) = temp_repo();
+ let branch = "feature/test-branch";
+ let cached = CachedSummary {
+ summary: "Add tests\n\nThis adds unit tests for cache.".to_string(),
+ diff_hash: 12345,
+ branch: branch.to_string(),
+ };
+
+ assert!(read_cache(&repo, branch).is_none());
+
+ write_cache(&repo, branch, &cached);
+ let loaded = read_cache(&repo, branch).unwrap();
+ assert_eq!(loaded.summary, cached.summary);
+ assert_eq!(loaded.diff_hash, cached.diff_hash);
+ assert_eq!(loaded.branch, cached.branch);
+ }
+
+ #[test]
+ fn test_write_cache_handles_unwritable_path() {
+ let (_dir, repo) = temp_repo();
+ // Block cache directory creation by placing a file where the directory should be
+ let cache_parent = repo.git_common_dir().join("wt-cache");
+ fs::write(&cache_parent, "blocker").unwrap();
+
+ let cached = CachedSummary {
+ summary: "test".to_string(),
+ diff_hash: 1,
+ branch: "main".to_string(),
+ };
+ // Should not panic — just logs and returns
+ write_cache(&repo, "main", &cached);
+ assert!(read_cache(&repo, "main").is_none());
+
+ // Cleanup: remove the blocker file so TempDir cleanup works
+ fs::remove_file(&cache_parent).unwrap();
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn test_write_cache_handles_write_failure() {
+ use std::os::unix::fs::PermissionsExt;
+
+ let (_dir, repo) = temp_repo();
+ let cache_path = cache_dir(&repo);
+ fs::create_dir_all(&cache_path).unwrap();
+ // Make directory read-only so file writes fail
+ fs::set_permissions(&cache_path, fs::Permissions::from_mode(0o444)).unwrap();
+
+ let cached = CachedSummary {
+ summary: "test".to_string(),
+ diff_hash: 1,
+ branch: "main".to_string(),
+ };
+ // Should not panic — just logs and returns
+ write_cache(&repo, "main", &cached);
+ assert!(read_cache(&repo, "main").is_none());
+
+ // Restore permissions so TempDir cleanup works
+ fs::set_permissions(&cache_path, fs::Permissions::from_mode(0o755)).unwrap();
+ }
+
+ #[test]
+ fn test_cache_invalidation_by_hash() {
+ let (_dir, repo) = temp_repo();
+ let branch = "main";
+ let cached = CachedSummary {
+ summary: "Old summary".to_string(),
+ diff_hash: 111,
+ branch: branch.to_string(),
+ };
+ write_cache(&repo, branch, &cached);
+
+ let loaded = read_cache(&repo, branch).unwrap();
+ assert_ne!(loaded.diff_hash, 222);
+ }
+
+ #[test]
+ fn test_cache_file_uses_sanitized_branch() {
+ let (_dir, repo) = temp_repo();
+ let path = cache_file(&repo, "feature/my-branch");
+ let filename = path.file_name().unwrap().to_str().unwrap();
+ assert!(filename.starts_with("feature-my-branch-"));
+ assert!(filename.ends_with(".json"));
+ }
+
+ #[test]
+ fn test_cache_dir_under_git() {
+ let (_dir, repo) = temp_repo();
+ let dir = cache_dir(&repo);
+ assert!(dir.to_str().unwrap().contains("wt-cache"));
+ assert!(dir.to_str().unwrap().contains("summaries"));
+ }
+
+ #[test]
+ fn test_hash_diff_deterministic() {
+ let hash1 = hash_diff("some diff content");
+ let hash2 = hash_diff("some diff content");
+ assert_eq!(hash1, hash2);
+ }
+
+ #[test]
+ fn test_hash_diff_different_inputs() {
+ let hash1 = hash_diff("diff A");
+ let hash2 = hash_diff("diff B");
+ assert_ne!(hash1, hash2);
+ }
+
+ #[test]
+ fn test_render_prompt() {
+ let result = render_prompt("diff content", "1 file changed");
+ assert!(result.is_ok());
+ let prompt = result.unwrap();
+ assert!(prompt.contains("diff content"));
+ assert!(prompt.contains("1 file changed"));
+ }
+
+ #[test]
+ fn test_render_prompt_commit_message_format() {
+ let result = render_prompt("", "").unwrap();
+ assert!(result.contains("commit message"));
+ assert!(result.contains("imperative mood"));
+ }
+
+ #[test]
+ fn test_render_summary_subject_bold() {
+ let text = "Add new feature\n\nSome body text here.";
+ let rendered = render_summary(text, 80);
+ assert!(rendered.contains("\x1b[1m"));
+ assert!(rendered.contains("Add new feature"));
+ }
+
+ #[test]
+ fn test_render_summary_single_line() {
+ let text = "Add new feature";
+ let rendered = render_summary(text, 80);
+ assert!(rendered.contains("\x1b[1m"));
+ assert!(rendered.contains("Add new feature"));
+ }
+
+ #[test]
+ fn test_render_summary_wraps_body() {
+ let text = format!("Subject\n\n{}", "word ".repeat(30));
+ let rendered = render_summary(&text, 40);
+ assert!(rendered.lines().count() > 3);
+ }
+
+ #[test]
+ fn test_render_summary_body_preserved() {
+ let text = "Subject\n\n- First bullet\n- Second bullet";
+ let rendered = render_summary(text, 80);
+ assert!(rendered.contains("First bullet"));
+ assert!(rendered.contains("Second bullet"));
+ }
+
+ #[test]
+ fn test_render_summary_prestyled_skips_h4() {
+ let text = "\x1b[2mNo changes to summarize.\x1b[0m";
+ let rendered = render_summary(text, 80);
+ assert!(!rendered.contains("####"));
+ assert!(rendered.contains("No changes to summarize."));
+ }
+
+ #[test]
+ fn test_compute_combined_diff_with_branch_changes() {
+ let (dir, repo, head) = temp_repo_with_feature();
+ let item = feature_item(&head, dir.path());
+
+ let result = compute_combined_diff(&item, &repo);
+ assert!(result.is_some());
+ let combined = result.unwrap();
+ assert!(combined.diff.contains("new.txt"));
+ assert!(combined.stat.contains("new.txt"));
+ }
+
+ #[test]
+ fn test_compute_combined_diff_default_branch_no_changes() {
+ let (dir, repo, head) = temp_repo_configured();
+
+ let mut item = ListItem::new_branch(head, "main".to_string());
+ item.kind = ItemKind::Worktree(Box::new(WorktreeData {
+ path: dir.path().to_path_buf(),
+ ..Default::default()
+ }));
+
+ let result = compute_combined_diff(&item, &repo);
+ assert!(result.is_none());
+ }
+
+ #[test]
+ fn test_compute_combined_diff_with_uncommitted_changes() {
+ let (dir, repo, head) = temp_repo_with_feature();
+ // Add uncommitted changes
+ fs::write(dir.path().join("uncommitted.txt"), "wip\n").unwrap();
+ git(dir.path(), &["add", "uncommitted.txt"]);
+
+ let item = feature_item(&head, dir.path());
+ let result = compute_combined_diff(&item, &repo);
+ assert!(result.is_some());
+ let combined = result.unwrap();
+ // Should contain both the branch diff and the working tree diff
+ assert!(combined.diff.contains("new.txt"));
+ assert!(combined.diff.contains("uncommitted.txt"));
+ }
+
+ #[test]
+ fn test_compute_combined_diff_branch_only_no_worktree() {
+ let (_dir, repo, head) = temp_repo_with_feature();
+ // Branch-only item (no worktree data) — only branch diff included
+ let item = ListItem::new_branch(head, "feature".to_string());
+
+ let result = compute_combined_diff(&item, &repo);
+ assert!(result.is_some());
+ let combined = result.unwrap();
+ assert!(combined.diff.contains("new.txt"));
+ }
+
+ #[test]
+ fn test_compute_combined_diff_no_default_branch_with_worktree_changes() {
+ // Repo without default-branch config and exotic branch names that
+ // infer_default_branch_locally() won't detect (it checks "main",
+ // "master", "develop", "trunk"). This ensures default_branch() returns
+ // None, exercising the code path where branch diff is skipped.
+ let dir = tempfile::tempdir().unwrap();
+ git(dir.path(), &["init", "--initial-branch=init-branch"]);
+ fs::write(dir.path().join("README.md"), "# Project\n").unwrap();
+ git(dir.path(), &["add", "README.md"]);
+ git(dir.path(), &["commit", "-m", "initial commit"]);
+ git(dir.path(), &["checkout", "-b", "feature"]);
+ git(
+ dir.path(),
+ &["commit", "--allow-empty", "-m", "feature commit"],
+ );
+
+ // Add uncommitted changes
+ fs::write(dir.path().join("wip.txt"), "work in progress\n").unwrap();
+ git(dir.path(), &["add", "wip.txt"]);
+
+ let head = git_output(dir.path(), &["rev-parse", "HEAD"]);
+ let repo = Repository::at(dir.path()).unwrap();
+
+ // Verify default_branch() actually returns None with these branch names
+ assert!(
+ repo.default_branch().is_none(),
+ "expected no default branch with exotic branch names"
+ );
+
+ let item = feature_item(&head, dir.path());
+ let result = compute_combined_diff(&item, &repo);
+ assert!(
+ result.is_some(),
+ "should include working tree diff even without default branch"
+ );
+ let combined = result.unwrap();
+ assert!(combined.diff.contains("wip.txt"));
+ }
+
+ #[test]
+ fn test_generate_summary_calls_llm() {
+ let (dir, repo, head) = temp_repo_with_feature();
+ let item = feature_item(&head, dir.path());
+
+ let summary = generate_summary(&item, "cat >/dev/null && echo 'Add new file'", &repo);
+ assert_eq!(summary, "Add new file");
+ }
+
+ #[test]
+ fn test_generate_summary_caches_result() {
+ let (dir, repo, head) = temp_repo_with_feature();
+ let item = feature_item(&head, dir.path());
+
+ let summary1 = generate_summary(&item, "cat >/dev/null && echo 'Add new file'", &repo);
+ assert_eq!(summary1, "Add new file");
+
+ // Second call with different command should return cached value
+ let summary2 = generate_summary(&item, "cat >/dev/null && echo 'Different output'", &repo);
+ assert_eq!(summary2, "Add new file");
+ }
+
+ #[test]
+ fn test_generate_summary_no_changes() {
+ let (dir, repo, head) = temp_repo_configured();
+
+ let mut item = ListItem::new_branch(head, "main".to_string());
+ item.kind = ItemKind::Worktree(Box::new(WorktreeData {
+ path: dir.path().to_path_buf(),
+ ..Default::default()
+ }));
+
+ let summary = generate_summary(&item, "echo 'should not run'", &repo);
+ assert!(summary.contains("No changes to summarize"));
+ }
+
+ #[test]
+ fn test_generate_summary_llm_error() {
+ let (dir, repo, head) = temp_repo_with_feature();
+ let item = feature_item(&head, dir.path());
+
+ let summary = generate_summary(&item, "cat >/dev/null && echo 'fail' >&2 && exit 1", &repo);
+ assert!(summary.starts_with("LLM error:"));
+ }
+
+ #[test]
+ fn test_generate_and_cache_summary_populates_cache() {
+ let (dir, repo, head) = temp_repo_with_feature();
+ let item = feature_item(&head, dir.path());
+ let cache: DashMap<PreviewCacheKey, String> = DashMap::new();
+
+ generate_and_cache_summary(
+ &item,
+ "cat >/dev/null && echo 'Add new file'",
+ &cache,
+ &repo,
+ );
+
+ let key = ("feature".to_string(), PreviewMode::Summary);
+ assert!(cache.contains_key(&key));
+ assert_eq!(cache.get(&key).unwrap().value(), "Add new file");
+ }
+}
diff --git a/src/config/user/sections.rs b/src/config/user/sections.rs
index c16d40b24..d51f1f8e7 100644
--- a/src/config/user/sections.rs
+++ b/src/config/user/sections.rs
@@ -128,6 +128,11 @@ pub struct ListConfig {
#[serde(skip_serializing_if = "Option::is_none")]
pub remotes: Option<bool>,
+ /// Show AI-generated branch summaries in the interactive picker (tab 5).
+ /// Requires `[commit.generation] command` to be configured.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub summary: Option<bool>,
+
/// (Experimental) Per-task timeout in milliseconds.
/// When set to a positive value, git operations that exceed this timeout are terminated.
/// Timed-out tasks show defaults in the table. Set to 0 to explicitly disable timeout
@@ -152,6 +157,11 @@ impl ListConfig {
self.remotes.unwrap_or(false)
}
+ /// Show AI-generated branch summaries in picker (default: false)
+ pub fn summary(&self) -> bool {
+ self.summary.unwrap_or(false)
+ }
+
/// Per-task timeout in milliseconds (default: None)
pub fn timeout_ms(&self) -> Option<u64> {
self.timeout_ms
@@ -164,6 +174,7 @@ impl Merge for ListConfig {
full: other.full.or(self.full),
branches: other.branches.or(self.branches),
remotes: other.remotes.or(self.remotes),
+ summary: other.summary.or(self.summary),
timeout_ms: other.timeout_ms.or(self.timeout_ms),
}
}
diff --git a/src/config/user/tests.rs b/src/config/user/tests.rs
index 788eb430e..8f25b616b 100644
--- a/src/config/user/tests.rs
+++ b/src/config/user/tests.rs
@@ -280,6 +280,7 @@ fn test_list_config_serde() {
full: Some(true),
branches: Some(false),
remotes: None,
+ summary: None,
timeout_ms: Some(500),
};
let json = serde_json::to_string(&config).unwrap();
@@ -287,6 +288,7 @@ fn test_list_config_serde() {
assert_eq!(parsed.full, Some(true));
assert_eq!(parsed.branches, Some(false));
assert_eq!(parsed.remotes, None);
+ assert_eq!(parsed.summary, None);
assert_eq!(parsed.timeout_ms, Some(500));
}
@@ -491,12 +493,14 @@ fn test_merge_list_config() {
full: Some(true),
branches: Some(false),
remotes: None,
+ summary: Some(true),
timeout_ms: Some(1000),
};
let override_config = ListConfig {
full: None, // Should fall back to base
branches: Some(true), // Should override
remotes: Some(true), // Should override (base was None)
+ summary: None, // Should fall back to base
timeout_ms: None, // Should fall back to base
};
@@ -504,6 +508,7 @@ fn test_merge_list_config() {
assert_eq!(merged.full, Some(true)); // From base
assert_eq!(merged.branches, Some(true)); // From override
assert_eq!(merged.remotes, Some(true)); // From override
+ assert_eq!(merged.summary, Some(true)); // From base
assert_eq!(merged.timeout_ms, Some(1000)); // From base
}
@@ -840,9 +845,7 @@ fn test_effective_list_project_only() {
overrides: OverridableConfig {
list: Some(ListConfig {
full: Some(true),
- branches: None,
- remotes: None,
- timeout_ms: None,
+ ..Default::default()
}),
..Default::default()
},
@@ -934,11 +937,13 @@ fn test_list_config_accessor_methods_with_values() {
full: Some(true),
branches: Some(true),
remotes: Some(false),
+ summary: Some(true),
timeout_ms: Some(5000),
};
assert!(config.full());
assert!(config.branches());
assert!(!config.remotes());
+ assert!(config.summary());
assert_eq!(config.timeout_ms(), Some(5000));
}
diff --git a/src/llm.rs b/src/llm.rs
index 76b099917..2f3f7b356 100644
--- a/src/llm.rs
+++ b/src/llm.rs
@@ -56,11 +56,11 @@ const MAX_FILES: usize = 50;
const LOCK_FILE_PATTERNS: &[&str] = &[".lock", "-lock.json", "-lock.yaml", ".lock.hcl"];
/// Prepared diff output with optional filtering applied
-struct PreparedDiff {
+pub(crate) struct PreparedDiff {
/// The diff content (possibly filtered/truncated)
- diff: String,
+ pub(crate) diff: String,
/// The diffstat output
- stat: String,
+ pub(crate) stat: String,
}
/// Check if a filename matches lock file patterns
@@ -133,7 +133,7 @@ fn truncate_diff_section(section: &str, max_lines: usize) -> String {
}
/// Prepare diff for LLM consumption, applying filtering if needed
-fn prepare_diff(diff: String, stat: String) -> PreparedDiff {
+pub(crate) fn prepare_diff(diff: String, stat: String) -> PreparedDiff {
// If under threshold, pass through unchanged
if diff.len() < DIFF_SIZE_THRESHOLD {
return PreparedDiff { diff, stat };
@@ -289,7 +289,7 @@ const DEFAULT_SQUASH_TEMPLATE: &str = r#"Combine these commits into a single com
///
/// This is the canonical way to execute LLM commands in this codebase.
/// All LLM execution should go through this function to maintain consistency.
-fn execute_llm_command(command: &str, prompt: &str) -> anyhow::Result<String> {
+pub(crate) fn execute_llm_command(command: &str, prompt: &str) -> anyhow::Result<String> {
// Log prompt for debugging (Cmd logs the command itself)
log::debug!(" Prompt (stdin):");
for line in prompt.lines() {
diff --git a/tests/integration_tests/switch_picker.rs b/tests/integration_tests/switch_picker.rs
index f1fef2cb1..18a0b5b83 100644
--- a/tests/integration_tests/switch_picker.rs
+++ b/tests/integration_tests/switch_picker.rs
@@ -453,8 +453,14 @@ fn switch_picker_settings(repo: &TestRepo) -> insta::Settings {
// \A anchors to absolute start of string, matching only the first line.
settings.add_filter(r"\A> [^\n]*", "> [QUERY]");
- // Skim count indicators (matched/total) at end of lines
- settings.add_filter(r"(?m)\d+/\d+\s*$", "[N/M]");
+ // Skim count indicators (matched/total) at end of lines.
+ // Normalize leading whitespace too — skim right-aligns the count with padding
+ // that varies based on unicode character width calculations across platforms.
+ // The tab header line may have the count jammed against "summary" (no space)
+ // or even truncate "summary" when skim's width_cjk() treats ambiguous-width
+ // unicode symbols (±, …, ⇅) as double-width, consuming extra columns.
+ settings.add_filter(r"(?m)summary?\w*\s*\d+/\d+\s*$", "summary [N/M]");
+ settings.add_filter(r"(?m)\s+\d+/\d+\s*$", " [N/M]");
// Commit hashes (7-8 hex chars)
settings.add_filter(r"\b[0-9a-f]{7,8}\b", "[HASH]");
@@ -770,6 +776,59 @@ fn test_new_feature() {
});
}
+#[rstest]
+fn test_switch_picker_preview_panel_summary(mut repo: TestRepo) {
+ repo.remove_fixture_worktrees();
+ // Remove origin so snapshots don't show origin/main
+ repo.run_git(&["remote", "remove", "origin"]);
+
+ let feature_path = repo.add_worktree("feature");
+
+ // Make a commit so there's content to potentially summarize
+ std::fs::write(feature_path.join("new.txt"), "content\n").unwrap();
+ let output = repo
+ .git_command()
+ .args(["-C", feature_path.to_str().unwrap(), "add", "."])
+ .output()
+ .unwrap();
+ assert!(output.status.success(), "Failed to add file");
+ let output = repo
+ .git_command()
+ .args([
+ "-C",
+ feature_path.to_str().unwrap(),
+ "commit",
+ "-m",
+ "Add new file",
+ ])
+ .output()
+ .unwrap();
+ assert!(output.status.success(), "Failed to commit");
+
+ let env_vars = repo.test_env_vars();
+ // Type "feature" to filter, press 5 for summary panel
+ // Wait for "commit.generation" hint since no LLM is configured
+ let result = exec_in_pty_capture_before_abort(
+ wt_bin().to_str().unwrap(),
+ &["switch"],
+ repo.root_path(),
+ &env_vars,
+ &[
+ ("feature", None),
+ ("5", Some("│Configure")), // Wait for config hint (│ = border drawn)
+ ],
+ );
+
+ assert_valid_abort_exit_code(result.exit_code);
+
+ let (list, preview) = result.panels();
+ let settings = switch_picker_settings(&repo);
+ settings.bind(|| {
+ assert_snapshot!("switch_picker_preview_summary_list", list);
+ assert_snapshot!("switch_picker_preview_summary_preview", preview);
+ });
+}
+
#[rstest]
fn test_switch_picker_respects_list_config(mut repo: TestRepo) {
repo.add_worktree("active-worktree");
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 5e8c9a472..87c3b3145 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_create.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_create.snap
@@ -108,6 +108,7 @@ Creates ~/.config/worktrunk/config.toml with the following content:
# full = false # Show CI status and main…± diffstat columns (--full)
# branches = false # Include branches without worktrees (--branches)
# remotes = false # Include remote-only branches (--remotes)
+ # summary = false # AI branch summaries in picker tab 5 (requires [commit.generation])
#
# ### Commit
#
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 5f26111ef..4a5e256db 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_long.snap
@@ -150,6 +150,7 @@ Persistent flag values for wt list. Override on command line as needed.
full = false # Show CI status and main…± diffstat columns (--full)
branches = false # Include branches without worktrees (--branches)
remotes = false # Include remote-only branches (--remotes)
+ summary = false # AI branch summaries in picker tab 5 (requires [commit.generation])
Commit
diff --git a/tests/snapshots/integration__integration_tests__help__help_switch_long.snap b/tests/snapshots/integration__integration_tests__help__help_switch_long.snap
index 4f3f37821..48037a8b0 100644
--- a/tests/snapshots/integration__integration_tests__help__help_switch_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_switch_long.snap
@@ -19,6 +19,7 @@ info:
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
WORKTRUNK_TEST_POWERSHELL_ENV: "0"
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
---
@@ -165,7 +166,7 @@ When called without arguments, wt switch opens an interactive picker to
Enter Switch to selected worktree
Alt-c Create new worktree from query
Esc Cancel
- 1/2/3/4 Switch preview tab
+ 1–5 Switch preview tab
Alt-p Toggle preview panel
Ctrl-u/Ctrl-d Scroll preview up/down
@@ -175,6 +176,7 @@ When called without arguments, wt switch opens an interactive picker to
2. log — Recent commits; commits already on the default branch have dimmed hashes
3. main…± — Diff of changes since the merge-base with the default branch
4. remote⇅ — Diff vs upstream tracking branch (ahead/behind)
+5. summary — AI-generated branch summary (requires [list] summary = true and [commit.generation])
Pager configuration: The preview panel pipes diff output through git's pager. Override in user config:
diff --git a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_abort_escape_preview.snap b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_abort_escape_preview.snap
index bcb2f20ac..70b578f57 100644
--- a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_abort_escape_preview.snap
+++ b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_abort_escape_preview.snap
@@ -2,7 +2,7 @@
source: tests/integration_tests/switch_picker.rs
expression: preview
---
-1: HEAD± | 2: log | 3: main…± | 4: remote⇅ [N/M]
+1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary [N/M]
Enter: switch | alt-c: create | Esc: cancel | ctrl-u/d: scr
○ main has no uncommitted changes
diff --git a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_multiple_worktrees_preview.snap b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_multiple_worktrees_preview.snap
index bcb2f20ac..70b578f57 100644
--- a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_multiple_worktrees_preview.snap
+++ b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_multiple_worktrees_preview.snap
@@ -2,7 +2,7 @@
source: tests/integration_tests/switch_picker.rs
expression: preview
---
-1: HEAD± | 2: log | 3: main…± | 4: remote⇅ [N/M]
+1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary [N/M]
Enter: switch | alt-c: create | Esc: cancel | ctrl-u/d: scr
○ main has no uncommitted changes
diff --git a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_log_preview.snap b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_log_preview.snap
index 1e64cdf8d..a11a5eaca 100644
--- a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_log_preview.snap
+++ b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_log_preview.snap
@@ -2,7 +2,7 @@
source: tests/integration_tests/switch_picker.rs
expression: preview
---
-1: HEAD± | 2: log | 3: main…± | 4: remote⇅ [N/M]
+1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary [N/M]
Enter: switch | alt-c: create | Esc: cancel | ctrl-u/d: scr
* [HASH] +1 [TIME] (feature) Add file 5 with content
diff --git a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_main_diff_preview.snap b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_main_diff_preview.snap
index 83c539c7d..494330b69 100644
--- a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_main_diff_preview.snap
+++ b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_main_diff_preview.snap
@@ -2,7 +2,7 @@
source: tests/integration_tests/switch_picker.rs
expression: preview
---
-1: HEAD± | 2: log | 3: main…± | 4: remote⇅ [N/M]
+1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary [N/M]
Enter: switch | alt-c: create | Esc: cancel | ctrl-u/d: scr
feature_code.rs | 6 ++++++
diff --git a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_summary_list.snap b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_summary_list.snap
new file mode 100644
index 000000000..26a255260
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_summary_list.snap
@@ -0,0 +1,7 @@
+---
+source: tests/integration_tests/switch_picker.rs
+expression: list
+---
+> [QUERY]
+ Branch Status HEAD± main↕ Remote⇅ Commit
+> + feature ↑ ↑1 [HASH]..
diff --git a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_summary_preview.snap b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_summary_preview.snap
new file mode 100644
index 000000000..2d67b0e32
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_summary_preview.snap
@@ -0,0 +1,16 @@
+---
+source: tests/integration_tests/switch_picker.rs
+expression: preview
+---
+1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary [N/M]
+Enter: switch | alt-c: create | Esc: cancel | ctrl-u/d: scr
+
+Configure [commit.generation] command to enable AI summarie
+
+Example in ~/.config/worktrunk/config.toml:
+
+[commit.generation]
+command = "llm -m haiku"
+
+[list]
+summary = true
diff --git a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_uncommitted_preview.snap b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_uncommitted_preview.snap
index 6dfd86164..6807cadde 100644
--- a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_uncommitted_preview.snap
+++ b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_uncommitted_preview.snap
@@ -2,7 +2,7 @@
source: tests/integration_tests/switch_picker.rs
expression: preview
---
-1: HEAD± | 2: log | 3: main…± | 4: remote⇅ [N/M]
+1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary [N/M]
Enter: switch | alt-c: create | Esc: cancel | ctrl-u/d: scr
tracked.txt | 4 +++-
diff --git a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_with_branches_preview.snap b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_with_branches_preview.snap
index bcb2f20ac..70b578f57 100644
--- a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_with_branches_preview.snap
+++ b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_with_branches_preview.snap
@@ -2,7 +2,7 @@
source: tests/integration_tests/switch_picker.rs
expression: preview
---
-1: HEAD± | 2: log | 3: main…± | 4: remote⇅ [N/M]
+1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary [N/M]
Enter: switch | alt-c: create | Esc: cancel | ctrl-u/d: scr
○ main has no uncommitted changes